@inkeep/open-knowledge 0.21.0-beta.3 → 0.21.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/assets/skills/write-skill/SKILL.md +1 -1
  4. package/dist/cli.mjs +6 -6
  5. package/dist/constants-D_fn2gJ5.mjs +2 -0
  6. package/dist/{dist-BFJW9DuR.mjs → dist-BoIBsVKQ.mjs} +7 -7
  7. package/dist/{dist-BfGtTRv6.mjs → dist-CyrjbW_1.mjs} +1 -1
  8. package/dist/index.mjs +1 -1
  9. package/dist/init-C2FFPegh.mjs +1 -0
  10. package/dist/{init-Dhv1aPmb.mjs → init-aFKryDql.mjs} +4 -4
  11. package/dist/loader-BRXvCpfb.mjs +1 -0
  12. package/dist/{loader-D-6349k6.mjs → loader-cHaFsfjb.mjs} +2 -2
  13. package/dist/preview-COxjHZAN.mjs +1 -0
  14. package/dist/{preview-xN_Wn3OU.mjs → preview-D-tqQRoR.mjs} +2 -2
  15. package/dist/public/assets/{ActivityModeContent-D247jYIx.js → ActivityModeContent-JcuqYTcN.js} +1 -1
  16. package/dist/public/assets/{DocumentContext-Dp34RL1b.js → DocumentContext-CS9CRE3q.js} +1 -1
  17. package/dist/public/assets/{ManagedArtifactProperties-3GfeTlU_.js → ManagedArtifactProperties-Cjg3FRVy.js} +1 -1
  18. package/dist/public/assets/{PropertyPanel-BPt3vBiZ.js → PropertyPanel-CraqaB9N.js} +1 -1
  19. package/dist/public/assets/{SettingsDialogBody-XSleH_pq.js → SettingsDialogBody-DkJ4RyFM.js} +1 -1
  20. package/dist/public/assets/{SourceEditor-67Xo2sLX.js → SourceEditor-28ru_CJh.js} +1 -1
  21. package/dist/public/assets/{config-validation-events-DC_j_did.js → config-validation-events-DP4yGHlz.js} +1 -1
  22. package/dist/public/assets/{index-B8UWwvZN.js → index-Cq9y9rMZ.js} +5 -5
  23. package/dist/public/assets/{selection-context-Dnus99C9.js → selection-context-Di_xmsrN.js} +1 -1
  24. package/dist/public/assets/{telemetry-impl-DZfG0f1d.js → telemetry-impl-BJxTjOze.js} +1 -1
  25. package/dist/public/assets/{typing-burst-detector-B9U9Xf1T.js → typing-burst-detector-Ctlm0p3c.js} +1 -1
  26. package/dist/public/index.html +6 -6
  27. package/dist/{repair-launch-json-C_HhrBCD.mjs → repair-launch-json-uFBfGKLP.mjs} +2 -2
  28. package/dist/{repair-mcp-configs-DL6KPJV-.mjs → repair-mcp-configs-6LApQ0mX.mjs} +2 -2
  29. package/dist/repair-skills-BTQFXB6F.mjs +1 -0
  30. package/dist/{repair-skills-CDWroVyX.mjs → repair-skills-YawjMuJ1.mjs} +2 -2
  31. package/dist/{src-wE89WH5Y.mjs → src-5CVv-qoH.mjs} +2 -2
  32. package/dist/{start-CzFNa_MZ.mjs → start-CdzWaARn.mjs} +2 -2
  33. package/dist/start-DwYEgK3b.mjs +1 -0
  34. package/dist/{write-project-skill-DoA_hW3W.mjs → write-project-skill--BR_4GZD.mjs} +2 -2
  35. package/package.json +1 -1
  36. package/dist/constants-DAG7bApL.mjs +0 -2
  37. package/dist/init-jgSviz-c.mjs +0 -1
  38. package/dist/loader-DiFWs1y_.mjs +0 -1
  39. package/dist/preview-Be_jN91d.mjs +0 -1
  40. package/dist/repair-skills-BgtUq92b.mjs +0 -1
  41. package/dist/start-CNdOSXUn.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$a as _enum,$i as reattachLeadingDocBoundary,$n as SkillInstallStateSuccessSchema,$r as assertNeverProblemType,$t as MANAGED_ARTIFACT_PREFIX_TEMPLATE,A as ApiConfigSuccessSchema,Aa as EXECUTABLE_BLOCKLIST_EXTENSIONS,Ai as isBranchNotFoundGitError,An as SaveVersionRequestSchema,Ao as clone,Ar as TEMPLATE_NAME_REGEX,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Ba as detectRemovedKeys,Bi as parseFrontmatterYaml,Bn as ShareConstructUrlRequestSchema,Br as TestFlushGitSuccessSchema,Bt as InstalledSkillsSchema,C as AgentPatchSuccessSchema,Ca as ConfigSchema$1,Ci as formatFileSize,Cn as SKILL_STATE_REL,Co as $ZodObject,Cr as SyncConflictsSuccessSchema,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Da as DEFAULT_LOGS_MAX_BYTES,Di as getWikiLinkText,Do as safeParse$1,Dr as SyncTriggerRequestSchema,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ea as DEFAULT_EMBEDDINGS_MODEL,Ei as getParseHealth,En as SKILL_TARGETS_REL,Eo as parseAsync,Er as SyncStatusSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as isOrphanMode,Fn as SeedApplySuccessSchema,Fo as require_dist$1,Fr as TemplateMoveRequestSchema,Ft as HubsSuccessSchema,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ga as mediaKindForSidebarAssetExtension,Gi as parseSkillTargets,Gn as SharePublishResponseSchema,Gr as TrashCleanupSuccessSchema,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1ServerInfoPayloadSchema,Ha as isKnownConfigError,Hi as parseInstalledSkills,Hn as SharePublishNameCheckResponseSchema,Hr as TestRescanFilesSuccessSchema,Ht as LinkGraphSuccessSchema,I as BrokenLinkSchema,Ia as SANDBOXED_HTML_CSP,Ii as isValidBranchName,In as SeedListPacksSuccessSchema,Ir as TemplateMoveSuccessSchema,It as INSTALLED_SKILLS_REL,J as CC1_CONTRACT_VERSION,Ja as validatePatchScopes,Ji as previewEmbedFence,Jn as SkillFileGetSuccessSchema,Jr as UploadRequestSchema,Jt as LocalOpEmbeddingsMutationSuccessSchema,K as CC1_CHANNEL_DISK_ACK,Ka as normalizeAttachmentFolderPath,Ki as parseTemplateFile,Kn as SkillDeleteSuccessSchema,Kr as UA_PATTERNS,Kt as LocalOpAuthStatusSuccessSchema,L as CC1BranchSwitchedPayloadSchema,La as SANDBOXED_HTML_EXTENSIONS,Li as managedArtifactDocNameFromContentTarget,Ln as SeedPlanSuccessSchema,Lr as TemplatePutRequestSchema,Lt as InstallSkillRequestSchema,M as BacklinksSuccessSchema,Ma as LINKABLE_ASSET_EXTENSIONS,Mi as isHiddenDocName,Mn as SearchRequestSchema,Mo as normalizeParams,Mr as TagsListSuccessSchema,N as BranchInfoResponseSchema,Na as LOCAL_DIR,Nn as SearchSuccessSchema,No as $constructor,Nr as TemplateDeleteSuccessSchema,Nt as HistorySuccessSchema,O as AgentWriteRequestSchema,Oa as DEFAULT_SPANS_MAX_BYTES,Oi as iconFromClientName,On as SUPPORTED_DOC_EXTENSIONS,Oo as safeParseAsync$1,Or as SyncTriggerSuccessSchema,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pa as OK_PROJECT_MARKER,Pi as isManagedArtifactDocName,Pn as SeedApplyRequestSchema,Pr as TemplateGetSuccessSchema,Pt as HistoryVersionSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qa as ZodOptional$1,Qi as readFmMap,Qn as SkillInstallRequestSchema,Qr as applyPatchToFm,Qt as MANAGED_ARTIFACT_PREFIX_SKILL,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ra as addConfigSpanEvent,Ri as mergeThreeWay,Rn as SemanticIndexStatusSchema,Rr as TemplatePutSuccessSchema,Rt as InstallSkillSuccessSchema,S as AgentPatchRequestSchema,Sa as CONFIG_SCHEMA_MAJOR_PATH,Si as fnv1aDigest,Sn as SKILL_NAME_REGEX,So as meta$1,Sr as SyncConflictContentSuccessSchema,St as EDITOR_PROJECT_SKILL_ROOT,T as AgentUndoSuccessSchema,Ta as DEFAULT_EMBEDDINGS_BASE_URL,Ti as getHeadingSlug,Tn as SKILL_STATE_VERSION_RE,To as parse$1,Tr as SyncResolveConflictSuccessSchema,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ua as isValidAttachmentFolderPath,Ui as parseManagedArtifactName,Un as SharePublishOwnersResponseSchema,Ur as TestResetSuccessSchema,Ut as LocalOpAuthEmptySuccessSchema,V as CC1DiskAckPayloadSchema,Va as humanFormat,Vi as parseGlobalSkillBundleDoc,Vn as ShareConstructUrlResponseSchema,Vr as TestRescanBacklinksSuccessSchema,Vt as LINEAGE_EPOCH_KEY,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wa as locateIssue,Wi as parseProjectSkillBundleDoc,Wn as SharePublishRequestSchema,Wr as TrashCleanupRequestSchema,Wt as LocalOpAuthHostRequestSchema,X as CONFIG_DOC_NAMES,Xa as withConfigSpanSync,Xi as projectMergeBoundarySpace,Xn as SkillFilePutSuccessSchema,Xr as applyFastDiff,Xt as LocalOpOkInitRequestSchema,Y as CLIENT_VERSION_HEADER,Ya as withConfigSpan,Yi as projectFull,Yn as SkillFilePutRequestSchema,Yr as WorkspaceSuccessSchema,Yt as LocalOpEmbeddingsSetKeyRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Zi as projectSkillContentDocName,Zn as SkillGetSuccessSchema,Zr as applyIncrementalDiff,Zt as LocalOpOkInitResponseSchema,_ as AGENT_ICON_COLORS,_a as withFences,_i as emptyInstalledSkills,_n as RenamePathSuccessSchema,_r as SkillUpdateSuccessSchema,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as serializeFrontmatterMap,ai as composeTemplateFile,an as MetricsReconciliationSuccessSchema,ao as discriminatedUnion,ar as SkillRestoreRequestSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,ba as Fragment,bi as expandTagToHierarchy,bn as RollbackSuccessSchema,br as StreamingProblemEventSchema,c as isValidLockPid,ci as createCodeFenceTracker,cn as PREVIEW_EMBED_STARTERS,co as looseObject,cr as SkillStateSchema,ct as CreatePageSuccessSchema,da as stripFrontmatter,di as createWorkspaceSearchDocument,dn as PROTOCOL_VERSION,do as optional,dr as SkillTargetsPutRequestSchema,ea as renderInventoryFooter,ei as classifyGitAuthError,en as MANAGED_ARTIFACT_SCOPES,eo as _null,er as SkillInstallSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fa as tagsMatchingPrefix,fi as defaultScheduler,fn as PageHeadingsSuccessSchema,fo as preprocess,fr as SkillTargetsPutSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as validateDocName,gi as emitToleranceFire,gn as RenamePathRequestSchema,go as unknown,gr as SkillUpdateRequestSchema,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as unwrapFrontmatterFences,hi as displayNameFromClientName,hn as ProblemDetailsSchema,ho as union,hr as SkillUninstallSuccessSchema,ht as DeletePathSuccessSchema,ia as searchWorkspaceCorpus,ii as colorFromSeed,in as MetricsParseHealthSuccessSchema,io as custom,ir as SkillPutSuccessSchema,it as ClientLogsSuccessSchema,j as BacklinkCountsSuccessSchema,ja as INLINE_RENDERABLE_EXTENSIONS,ji as isFrontmatterValueEmpty,jn as SaveVersionSuccessSchema,jo as defineLazy,jr as TagsForNameSuccessSchema,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ka as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,ki as instantiateDoc,kn as SYSTEM_DOC_NAME,ko as prettifyError,kr as TEMPLATE_IDENTITY_KEY,kt as FrontmatterPatchRequestSchema,la as skillLiveDocName,li as createTagInTextRegex,ln as PREVIEW_THEME_TOKENS,lo as number,lr as SkillTargetEditorSchema,m as releaseServerLock,ma as toWikiLinkSlug,mi as detectFmRegion,mn as PrincipalSuccessSchema,mo as string,mr as SkillUninstallRequestSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as resolveInternalHref,ni as classifyWikiLinkTarget,nn as MarkdownManager,no as array,nr as SkillMoveSuccessSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as setToleranceTelemetryHook,oi as containsXmlTag,on as ORPHAN_MODES,oo as intersection,or as SkillRestoreSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as toBridgeInvariantLog,pi as detectAppliedToleranceClasses,pn as PagesSuccessSchema,po as record,pr as SkillTargetsSchema,pt as DeadLinksSuccessSchema,q as CC1_CHANNEL_SERVER_INFO,qa as toConfigIssue,qi as prependFrontmatter,qn as SkillFileDeleteSuccessSchema,qr as UploadAssetSuccessSchema,qt as LocalOpCloneRequestSchema,ra as resolveSkillBundleWikiTarget,rn as MetricsAgentPresenceSuccessSchema,ro as boolean,rr as SkillPutRequestSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as sharedExtensions,si as createBasenameIndex,sn as OrphansSuccessSchema,so as literal,sr as SkillScopeSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as resolveAssetProjectPath,ti as classifyMarkdownHref,tn as MCP_SERVER_NAME,tr as SkillMoveRequestSchema,tt as CheckoutRequestSchema,u as readProcessLock,ua as splitLeadingDocBoundary,ui as createWorkspaceSearchCorpus,un as PROJECT_SKILL_EDITOR_IDS,uo as object$1,ur as SkillTargetsGetSuccessSchema,va as getSchema,vi as emptySkillState,vn as RescueListSuccessSchema,vo as datetime,vr as SkillsListSuccessSchema,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wa as DEFAULT_DEDUP_MODE,wi as getAgentCanonicalDescriptors,wn as SKILL_STATE_TARGETS,wo as $ZodType,wr as SyncResolveConflictRequestSchema,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as ASSET_EXTENSIONS,xi as extractFrontmatterTags,xn as SKILL_CONTENT_ROOT,xo as describe$1,xr as SuggestLinksSuccessSchema,xt as EDITOR_PROJECT_CONFIG_PATH,y as AdvisoryWarningSchema,ya as PluginKey,yi as encodeShareUrl,yn as RollbackRequestSchema,yo as toJSONSchema,yr as SpawnCursorSuccessSchema,yt as DuplicatePathSuccessSchema,z as CC1ConfigValidationRejectedPayloadSchema,za as applyPatchToDocument,zi as normalizeBridge,zn as ServerInfoSuccessSchema,zr as TemplatesListSuccessSchema,zt as InstalledAgentsSuccessSchema}from"./server-lock-CN2YHwpP-Ca8AKq_V.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BS2W3Uzl.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-DY9lXoT3-Cmzgvwd8.mjs";import{t as createPatch}from"./libesm-Ob3yvbRV.mjs";import{n as mimes,t as build_default}from"./build-CN003PPg.mjs";import{t as require_yazl}from"./yazl-Docqgl6q.mjs";import{t as b1}from"./chunk-YNYSPYQ5-gU4-j5DO.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DbAN9IDm.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-NzTooVTc.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-D3pxE_Og.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-BVeTwIsz.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BkE4vqrf.mjs";import"./chunk-DXB73IDG-F_tmy-Lz.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BwpNU33k.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DApqA6Ow.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-CmrD0Dg2.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-DaS5XS55.mjs";import{n as n$1}from"./chunk-3THT3N7L-B1WzJUh4.mjs";import{t as n$2}from"./chunk-44UOCSGV-BZ6LfyW2.mjs";import{t as import_websocket_server$1}from"./wrapper-BZO_sIci.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import Crypto from"crypto";import crypto$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
1
+ import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$a as _enum,$i as reattachLeadingDocBoundary,$n as SkillInstallStateSuccessSchema,$r as assertNeverProblemType,$t as MANAGED_ARTIFACT_PREFIX_TEMPLATE,A as ApiConfigSuccessSchema,Aa as EXECUTABLE_BLOCKLIST_EXTENSIONS,Ai as isBranchNotFoundGitError,An as SaveVersionRequestSchema,Ao as clone,Ar as TEMPLATE_NAME_REGEX,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Ba as detectRemovedKeys,Bi as parseFrontmatterYaml,Bn as ShareConstructUrlRequestSchema,Br as TestFlushGitSuccessSchema,Bt as InstalledSkillsSchema,C as AgentPatchSuccessSchema,Ca as ConfigSchema$1,Ci as formatFileSize,Cn as SKILL_STATE_REL,Co as $ZodObject,Cr as SyncConflictsSuccessSchema,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Da as DEFAULT_LOGS_MAX_BYTES,Di as getWikiLinkText,Do as safeParse$1,Dr as SyncTriggerRequestSchema,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ea as DEFAULT_EMBEDDINGS_MODEL,Ei as getParseHealth,En as SKILL_TARGETS_REL,Eo as parseAsync,Er as SyncStatusSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as isOrphanMode,Fn as SeedApplySuccessSchema,Fo as require_dist$1,Fr as TemplateMoveRequestSchema,Ft as HubsSuccessSchema,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ga as mediaKindForSidebarAssetExtension,Gi as parseSkillTargets,Gn as SharePublishResponseSchema,Gr as TrashCleanupSuccessSchema,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1ServerInfoPayloadSchema,Ha as isKnownConfigError,Hi as parseInstalledSkills,Hn as SharePublishNameCheckResponseSchema,Hr as TestRescanFilesSuccessSchema,Ht as LinkGraphSuccessSchema,I as BrokenLinkSchema,Ia as SANDBOXED_HTML_CSP,Ii as isValidBranchName,In as SeedListPacksSuccessSchema,Ir as TemplateMoveSuccessSchema,It as INSTALLED_SKILLS_REL,J as CC1_CONTRACT_VERSION,Ja as validatePatchScopes,Ji as previewEmbedFence,Jn as SkillFileGetSuccessSchema,Jr as UploadRequestSchema,Jt as LocalOpEmbeddingsMutationSuccessSchema,K as CC1_CHANNEL_DISK_ACK,Ka as normalizeAttachmentFolderPath,Ki as parseTemplateFile,Kn as SkillDeleteSuccessSchema,Kr as UA_PATTERNS,Kt as LocalOpAuthStatusSuccessSchema,L as CC1BranchSwitchedPayloadSchema,La as SANDBOXED_HTML_EXTENSIONS,Li as managedArtifactDocNameFromContentTarget,Ln as SeedPlanSuccessSchema,Lr as TemplatePutRequestSchema,Lt as InstallSkillRequestSchema,M as BacklinksSuccessSchema,Ma as LINKABLE_ASSET_EXTENSIONS,Mi as isHiddenDocName,Mn as SearchRequestSchema,Mo as normalizeParams,Mr as TagsListSuccessSchema,N as BranchInfoResponseSchema,Na as LOCAL_DIR,Nn as SearchSuccessSchema,No as $constructor,Nr as TemplateDeleteSuccessSchema,Nt as HistorySuccessSchema,O as AgentWriteRequestSchema,Oa as DEFAULT_SPANS_MAX_BYTES,Oi as iconFromClientName,On as SUPPORTED_DOC_EXTENSIONS,Oo as safeParseAsync$1,Or as SyncTriggerSuccessSchema,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pa as OK_PROJECT_MARKER,Pi as isManagedArtifactDocName,Pn as SeedApplyRequestSchema,Pr as TemplateGetSuccessSchema,Pt as HistoryVersionSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qa as ZodOptional$1,Qi as readFmMap,Qn as SkillInstallRequestSchema,Qr as applyPatchToFm,Qt as MANAGED_ARTIFACT_PREFIX_SKILL,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ra as addConfigSpanEvent,Ri as mergeThreeWay,Rn as SemanticIndexStatusSchema,Rr as TemplatePutSuccessSchema,Rt as InstallSkillSuccessSchema,S as AgentPatchRequestSchema,Sa as CONFIG_SCHEMA_MAJOR_PATH,Si as fnv1aDigest,Sn as SKILL_NAME_REGEX,So as meta$1,Sr as SyncConflictContentSuccessSchema,St as EDITOR_PROJECT_SKILL_ROOT,T as AgentUndoSuccessSchema,Ta as DEFAULT_EMBEDDINGS_BASE_URL,Ti as getHeadingSlug,Tn as SKILL_STATE_VERSION_RE,To as parse$1,Tr as SyncResolveConflictSuccessSchema,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ua as isValidAttachmentFolderPath,Ui as parseManagedArtifactName,Un as SharePublishOwnersResponseSchema,Ur as TestResetSuccessSchema,Ut as LocalOpAuthEmptySuccessSchema,V as CC1DiskAckPayloadSchema,Va as humanFormat,Vi as parseGlobalSkillBundleDoc,Vn as ShareConstructUrlResponseSchema,Vr as TestRescanBacklinksSuccessSchema,Vt as LINEAGE_EPOCH_KEY,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wa as locateIssue,Wi as parseProjectSkillBundleDoc,Wn as SharePublishRequestSchema,Wr as TrashCleanupRequestSchema,Wt as LocalOpAuthHostRequestSchema,X as CONFIG_DOC_NAMES,Xa as withConfigSpanSync,Xi as projectMergeBoundarySpace,Xn as SkillFilePutSuccessSchema,Xr as applyFastDiff,Xt as LocalOpOkInitRequestSchema,Y as CLIENT_VERSION_HEADER,Ya as withConfigSpan,Yi as projectFull,Yn as SkillFilePutRequestSchema,Yr as WorkspaceSuccessSchema,Yt as LocalOpEmbeddingsSetKeyRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Zi as projectSkillContentDocName,Zn as SkillGetSuccessSchema,Zr as applyIncrementalDiff,Zt as LocalOpOkInitResponseSchema,_ as AGENT_ICON_COLORS,_a as withFences,_i as emptyInstalledSkills,_n as RenamePathSuccessSchema,_r as SkillUpdateSuccessSchema,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as serializeFrontmatterMap,ai as composeTemplateFile,an as MetricsReconciliationSuccessSchema,ao as discriminatedUnion,ar as SkillRestoreRequestSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,ba as Fragment,bi as expandTagToHierarchy,bn as RollbackSuccessSchema,br as StreamingProblemEventSchema,c as isValidLockPid,ci as createCodeFenceTracker,cn as PREVIEW_EMBED_STARTERS,co as looseObject,cr as SkillStateSchema,ct as CreatePageSuccessSchema,da as stripFrontmatter,di as createWorkspaceSearchDocument,dn as PROTOCOL_VERSION,do as optional,dr as SkillTargetsPutRequestSchema,ea as renderInventoryFooter,ei as classifyGitAuthError,en as MANAGED_ARTIFACT_SCOPES,eo as _null,er as SkillInstallSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fa as tagsMatchingPrefix,fi as defaultScheduler,fn as PageHeadingsSuccessSchema,fo as preprocess,fr as SkillTargetsPutSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as validateDocName,gi as emitToleranceFire,gn as RenamePathRequestSchema,go as unknown,gr as SkillUpdateRequestSchema,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as unwrapFrontmatterFences,hi as displayNameFromClientName,hn as ProblemDetailsSchema,ho as union,hr as SkillUninstallSuccessSchema,ht as DeletePathSuccessSchema,ia as searchWorkspaceCorpus,ii as colorFromSeed,in as MetricsParseHealthSuccessSchema,io as custom,ir as SkillPutSuccessSchema,it as ClientLogsSuccessSchema,j as BacklinkCountsSuccessSchema,ja as INLINE_RENDERABLE_EXTENSIONS,ji as isFrontmatterValueEmpty,jn as SaveVersionSuccessSchema,jo as defineLazy,jr as TagsForNameSuccessSchema,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ka as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,ki as instantiateDoc,kn as SYSTEM_DOC_NAME,ko as prettifyError,kr as TEMPLATE_IDENTITY_KEY,kt as FrontmatterPatchRequestSchema,la as skillLiveDocName,li as createTagInTextRegex,ln as PREVIEW_THEME_TOKENS,lo as number,lr as SkillTargetEditorSchema,m as releaseServerLock,ma as toWikiLinkSlug,mi as detectFmRegion,mn as PrincipalSuccessSchema,mo as string,mr as SkillUninstallRequestSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as resolveInternalHref,ni as classifyWikiLinkTarget,nn as MarkdownManager,no as array,nr as SkillMoveSuccessSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as setToleranceTelemetryHook,oi as containsXmlTag,on as ORPHAN_MODES,oo as intersection,or as SkillRestoreSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as toBridgeInvariantLog,pi as detectAppliedToleranceClasses,pn as PagesSuccessSchema,po as record,pr as SkillTargetsSchema,pt as DeadLinksSuccessSchema,q as CC1_CHANNEL_SERVER_INFO,qa as toConfigIssue,qi as prependFrontmatter,qn as SkillFileDeleteSuccessSchema,qr as UploadAssetSuccessSchema,qt as LocalOpCloneRequestSchema,ra as resolveSkillBundleWikiTarget,rn as MetricsAgentPresenceSuccessSchema,ro as boolean,rr as SkillPutRequestSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as sharedExtensions,si as createBasenameIndex,sn as OrphansSuccessSchema,so as literal,sr as SkillScopeSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as resolveAssetProjectPath,ti as classifyMarkdownHref,tn as MCP_SERVER_NAME,tr as SkillMoveRequestSchema,tt as CheckoutRequestSchema,u as readProcessLock,ua as splitLeadingDocBoundary,ui as createWorkspaceSearchCorpus,un as PROJECT_SKILL_EDITOR_IDS,uo as object$1,ur as SkillTargetsGetSuccessSchema,va as getSchema,vi as emptySkillState,vn as RescueListSuccessSchema,vo as datetime,vr as SkillsListSuccessSchema,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wa as DEFAULT_DEDUP_MODE,wi as getAgentCanonicalDescriptors,wn as SKILL_STATE_TARGETS,wo as $ZodType,wr as SyncResolveConflictRequestSchema,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as ASSET_EXTENSIONS,xi as extractFrontmatterTags,xn as SKILL_CONTENT_ROOT,xo as describe$1,xr as SuggestLinksSuccessSchema,xt as EDITOR_PROJECT_CONFIG_PATH,y as AdvisoryWarningSchema,ya as PluginKey,yi as encodeShareUrl,yn as RollbackRequestSchema,yo as toJSONSchema,yr as SpawnCursorSuccessSchema,yt as DuplicatePathSuccessSchema,z as CC1ConfigValidationRejectedPayloadSchema,za as applyPatchToDocument,zi as normalizeBridge,zn as ServerInfoSuccessSchema,zr as TemplatesListSuccessSchema,zt as InstalledAgentsSuccessSchema}from"./server-lock-CN2YHwpP-Ca8AKq_V.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BS2W3Uzl.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-DY9lXoT3-Cmzgvwd8.mjs";import{t as createPatch}from"./libesm-Ob3yvbRV.mjs";import{n as mimes,t as build_default}from"./build-CN003PPg.mjs";import{t as require_yazl}from"./yazl-Docqgl6q.mjs";import{t as b1}from"./chunk-YNYSPYQ5-gU4-j5DO.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DbAN9IDm.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-NzTooVTc.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-D3pxE_Og.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-BVeTwIsz.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BkE4vqrf.mjs";import"./chunk-DXB73IDG-F_tmy-Lz.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BwpNU33k.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DApqA6Ow.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-CmrD0Dg2.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-DaS5XS55.mjs";import{n as n$1}from"./chunk-3THT3N7L-B1WzJUh4.mjs";import{t as n$2}from"./chunk-44UOCSGV-BZ6LfyW2.mjs";import{t as import_websocket_server$1}from"./wrapper-BZO_sIci.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
2
2
  `)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}if(S===`auto-consolidation`){let e=w;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:E,size:D,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActor(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let s;try{s=JSON.parse(e.slice(10))}catch{return null}return typeof s!=`object`||!s?null:parseOkActorObject(s)}return null}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
@@ -35,10 +35,10 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
35
35
  `,`Details:
36
36
  `,(0,g.getIncompatibilityDetails)(S,e),`To resolve the conflict:
37
37
  `,(0,g.getConflictResolutionRecipe)(S,e))}return w}}})),require_MultiWritableMetricStorage=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,s,g){this._backingStorages.forEach(S=>{S.record(e,t,s,g)})}}})),require_ObservableResult=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_HashMap(),g=require_Instruments();e.ObservableResultImpl=class{_buffer=new s.AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,s={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(s,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,S,w={}){if(!(0,g.isObservableInstrument)(e))return;let E=this._buffer.get(e);if(E??(E=new s.AttributeHashMap,this._buffer.set(e,E)),typeof S!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${S}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(S)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),S=Math.trunc(S),!Number.isInteger(S))||E.set(w,S)}}})),require_ObservableRegistry=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Instruments(),g=require_ObservableResult(),S=require_utils$3();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let s=this._findCallback(e,t);s<0||this._callbacks.splice(s,1)}addBatchCallback(e,g){let S=new Set(g.filter(s.isObservableInstrument));if(S.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,g);return}this._findBatchCallback(e,S)>=0||this._batchCallbacks.push({callback:e,instruments:S})}removeBatchCallback(e,t){let g=new Set(t.filter(s.isObservableInstrument)),S=this._findBatchCallback(e,g);S<0||this._batchCallbacks.splice(S,1)}async observe(e,t){let s=this._observeCallbacks(e,t),g=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...s,...g])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:s,instrument:w})=>{let E=new g.ObservableResultImpl(w._descriptor.name,w._descriptor.valueType),D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w._metricStorages.forEach(t=>{t.record(E._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:s,instruments:w})=>{let E=new g.BatchObservableResultImpl,D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w.forEach(t=>{let s=E._buffer.get(t);s!=null&&t._metricStorages.forEach(t=>{t.record(s,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(s=>s.callback===e&&s.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(s=>s.callback===e&&(0,S.setEquals)(s.instruments,t))}}})),require_SyncMetricStorage=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage(),s=require_DeltaMetricProcessor(),g=require_TemporalMetricProcessor();e.SyncMetricStorage=class extends t.MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,S,w,E){super(e),this._aggregationCardinalityLimit=E,this._deltaMetricStorage=new s.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new g.TemporalMetricProcessor(t,w),this._attributesProcessor=S}record(e,t,s,g){t=this._attributesProcessor.process(t,s),this._deltaMetricStorage.record(e,t,s,g)}collect(e,t){let s=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,s,t)}}})),require_AttributesProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},s=class{_processors;constructor(e){this._processors=e}process(e,t){let s=e;for(let e of this._processors)s=e.process(s,t);return s}},g=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let s={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(s[t]=e[t])}),s}},S=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let s={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(s[t]=e[t])}),s}};function w(){return k}e.createNoopAttributesProcessor=w;function E(e){return new s(e)}e.createMultiAttributesProcessor=E;function D(e){return new g(e)}e.createAllowListAttributesProcessor=D;function O(e){return new S(e)}e.createDenyListAttributesProcessor=O;let k=new t})),require_MeterSharedState=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor(),s=require_Meter(),g=require_AsyncMetricStorage(),S=require_MetricStorageRegistry(),w=require_MultiWritableMetricStorage(),E=require_ObservableRegistry(),D=require_SyncMetricStorage(),O=require_AttributesProcessor();e.MeterSharedState=class{metricStorageRegistry=new S.MetricStorageRegistry;observableRegistry=new E.ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new s.Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,D.SyncMetricStorage);return t.length===1?t[0]:new w.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,g.AsyncMetricStorage)}async collect(e,t,s){let g=await this.observableRegistry.observe(t,s?.timeoutMillis),S=this.metricStorageRegistry.getStorages(e);if(S.length===0)return null;let w=[];return S.forEach(s=>{let g=s.collect(e,t);g!=null&&w.push(g)}),w.length===0?{errors:g}:{scopeMetrics:{scope:this._instrumentationScope,metrics:w},errors:g}}_registerMetricStorage(e,s){let g=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(g=>{let S=(0,t.createInstrumentDescriptorWithView)(g,e),w=this.metricStorageRegistry.findOrUpdateCompatibleStorage(S);if(w!=null)return w;let E=new s(S,g.aggregation.createAggregator(S),g.attributesProcessor,this._meterProviderSharedState.metricCollectors,g.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(g.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,g])=>{let S=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(S!=null)return S;let w=g.createAggregator(e),E=t.selectCardinalityLimit(e.type),D=new s(e,w,(0,O.createNoopAttributesProcessor)(),[t],E);return this.metricStorageRegistry.registerForCollector(t,D),D});g=g.concat(t)}return g}}})),require_MeterProviderSharedState=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$3(),s=require_ViewRegistry(),g=require_MeterSharedState(),S=require_AggregationOption();e.MeterProviderSharedState=class{viewRegistry=new s.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let s=(0,t.instrumentationScopeId)(e),S=this.meterSharedStates.get(s);return S??(S=new g.MeterSharedState(this,e),this.meterSharedStates.set(s,S)),S}selectAggregations(e){let t=[];for(let s of this.metricCollectors)t.push([s,(0,S.toAggregation)(s.selectAggregation(e))]);return t}}})),require_MetricCollector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$14();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let s=(0,t.millisToHrTime)(Date.now()),g=[],S=[],w=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let w=await t.collect(this,s,e);w?.scopeMetrics!=null&&g.push(w.scopeMetrics),w?.errors!=null&&S.push(...w.errors)});return await Promise.all(w),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:g},errors:S}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate(),s=require_AttributesProcessor(),g=require_InstrumentSelector(),S=require_MeterSelector(),w=require_AggregationOption();function E(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function D(e){if(E(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){D(e),e.attributesProcessors==null?this.attributesProcessor=(0,s.createNoopAttributesProcessor)():this.attributesProcessor=(0,s.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,w.toAggregation)(e.aggregation??{type:w.AggregationType.DEFAULT}),this.instrumentSelector=new g.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new S.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$2(),g=require_MeterProviderSharedState(),S=require_MetricCollector(),w=require_View();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new g.MeterProviderSharedState(e?.resource??(0,s.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new w.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new S.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,s=``,g={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:s,schemaUrl:g.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var s=require_MetricData();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return s.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return s.InstrumentType}});var g=require_MetricReader();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return g.MetricReader}});var S=require_PeriodicExportingMetricReader();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return S.PeriodicExportingMetricReader}});var w=require_InMemoryMetricExporter();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return w.InMemoryMetricExporter}});var E=require_ConsoleMetricExporter();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return E.ConsoleMetricExporter}});var D=require_MeterProvider();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return D.MeterProvider}});var O=require_AggregationOption();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return O.AggregationType}});var k=require_AttributesProcessor();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return k.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return k.createDenyListAttributesProcessor}});var j=require_utils$3();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return j.TimeoutError}})})),require_enums=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExceptionEventName=void 0,e.ExceptionEventName=`exception`})),require_Span=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SpanImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=(init_esm$1(),__toCommonJS(esm_exports$1)),S=require_enums();e.SpanImpl=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:t.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=s.otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+s.otperformance.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,g){if(g==null||this._isSpanEnded())return this;if(e.length===0)return t.diag.warn(`Invalid attribute key: ${e}`),this;if(!(0,s.isAttributeValue)(g))return t.diag.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:S}=this._spanLimits,w=!Object.prototype.hasOwnProperty.call(this.attributes,e);return S!==void 0&&this._attributesCount>=S&&w?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(g),w&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,g,S){if(this._isSpanEnded())return this;let{eventCountLimit:w}=this._spanLimits;if(w===0)return t.diag.warn(`No events allowed.`),this._droppedEventsCount++,this;w!==void 0&&this.events.length>=w&&(this._droppedEventsCount===0&&t.diag.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),(0,s.isTimeInput)(g)&&((0,s.isTimeInput)(S)||(S=g),g=void 0);let E=(0,s.sanitizeAttributes)(g),{attributePerEventCountLimit:D}=this._spanLimits,O={},k=0,j=0;for(let e in E){if(!Object.prototype.hasOwnProperty.call(E,e))continue;let t=E[e];if(D!==void 0&&j>=D){k++;continue}O[e]=this._truncateToSize(t),j++}return this.events.push({name:e,attributes:O,time:this._getTime(S),droppedAttributesCount:k}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:g}=this._spanLimits;if(g===0)return this._droppedLinksCount++,this;g!==void 0&&this.links.length>=g&&(this._droppedLinksCount===0&&t.diag.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:S}=this._spanLimits,w=(0,s.sanitizeAttributes)(e.attributes),E={},D=0,O=0;for(let e in w){if(!Object.prototype.hasOwnProperty.call(w,e))continue;let t=w[e];if(S!==void 0&&O>=S){D++;continue}E[e]=this._truncateToSize(t),O++}let k={context:e.context};return O>0&&(k.attributes=E),D>0&&(k.droppedAttributesCount=D),this.links.push(k),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===t.SpanStatusCode.UNSET||this.status.code===t.SpanStatusCode.OK)return this;let s={code:e.code};return e.code===t.SpanStatusCode.ERROR&&(typeof e.message==`string`?s.message=e.message:e.message!=null&&t.diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=s,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){if(this._isSpanEnded()){t.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=(0,s.hrTimeDuration)(this.startTime,this.endTime),this._duration[0]<0&&(t.diag.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&t.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&t.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e==`number`&&e<=s.otperformance.now())return(0,s.hrTime)(e+this._performanceOffset);if(typeof e==`number`)return(0,s.millisToHrTime)(e);if(e instanceof Date)return(0,s.millisToHrTime)(e.getTime());if((0,s.isTimeInputHrTime)(e))return e;if(this._startTimeProvided)return(0,s.millisToHrTime)(Date.now());let t=s.otperformance.now()-this._performanceStartTime;return(0,s.addHrTimes)(this.startTime,(0,s.millisToHrTime)(t))}isRecording(){return this._ended===!1}recordException(e,s){let w={};typeof e==`string`?w[g.ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?w[g.ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(w[g.ATTR_EXCEPTION_TYPE]=e.name),e.message&&(w[g.ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(w[g.ATTR_EXCEPTION_STACKTRACE]=e.stack)),w[g.ATTR_EXCEPTION_TYPE]||w[g.ATTR_EXCEPTION_MESSAGE]?this.addEvent(S.ExceptionEventName,w,s):t.diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);t.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let s=this._attributeValueLengthLimit;return s<=0?(t.diag.warn(`Attribute value limit must be positive, got ${s}`),e):typeof e==`string`?this._truncateToLimitUtil(e,s):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,s):e):e}}})),require_Sampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=void 0,(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(e.SamplingDecision||={})})),require_AlwaysOffSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOffSampler=void 0;let t=require_Sampler();e.AlwaysOffSampler=class{shouldSample(){return{decision:t.SamplingDecision.NOT_RECORD}}toString(){return`AlwaysOffSampler`}}})),require_AlwaysOnSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOnSampler=void 0;let t=require_Sampler();e.AlwaysOnSampler=class{shouldSample(){return{decision:t.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}}})),require_ParentBasedSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ParentBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_AlwaysOffSampler(),S=require_AlwaysOnSampler();e.ParentBasedSampler=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||=((0,s.globalErrorHandler)(Error(`ParentBasedSampler must have a root sampler configured`)),new S.AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new S.AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new g.AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new S.AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new g.AlwaysOffSampler}shouldSample(e,s,g,S,w,E){let D=t.trace.getSpanContext(e);return!D||!(0,t.isSpanContextValid)(D)?this._root.shouldSample(e,s,g,S,w,E):D.isRemote?D.traceFlags&t.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,s,g,S,w,E):this._remoteParentNotSampled.shouldSample(e,s,g,S,w,E):D.traceFlags&t.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,s,g,S,w,E):this._localParentNotSampled.shouldSample(e,s,g,S,w,E)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}})),require_TraceIdRatioBasedSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceIdRatioBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Sampler();e.TraceIdRatioBasedSampler=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,g){return{decision:(0,t.isValidTraceId)(g)&&this._accumulate(g)<this._upperBound?s.SamplingDecision.RECORD_AND_SAMPLED:s.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let s=0;s<e.length/8;s++){let g=s*8,S=parseInt(e.slice(g,g+8),16);t=(t^S)>>>0}return t}}})),require_config=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildSamplerFromEnv=e.loadDefaultConfig=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_AlwaysOffSampler(),S=require_AlwaysOnSampler(),w=require_ParentBasedSampler(),E=require_TraceIdRatioBasedSampler();var D;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(D||={});let O=1;function k(){return{sampler:j(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}e.loadDefaultConfig=k;function j(){let e=(0,s.getStringFromEnv)(`OTEL_TRACES_SAMPLER`)??D.ParentBasedAlwaysOn;switch(e){case D.AlwaysOn:return new S.AlwaysOnSampler;case D.AlwaysOff:return new g.AlwaysOffSampler;case D.ParentBasedAlwaysOn:return new w.ParentBasedSampler({root:new S.AlwaysOnSampler});case D.ParentBasedAlwaysOff:return new w.ParentBasedSampler({root:new g.AlwaysOffSampler});case D.TraceIdRatio:return new E.TraceIdRatioBasedSampler(F());case D.ParentBasedTraceIdRatio:return new w.ParentBasedSampler({root:new E.TraceIdRatioBasedSampler(F())});default:return t.diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${D.ParentBasedAlwaysOn}".`),new w.ParentBasedSampler({root:new S.AlwaysOnSampler})}}e.buildSamplerFromEnv=j;function F(){let e=(0,s.getNumberFromEnv)(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1.`),1):e<0||e>1?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to 1.`),1):e}})),require_utility=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.mergeConfig=e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=void 0;let t=require_config(),s=require_src$14();e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function g(e){let s={sampler:(0,t.buildSamplerFromEnv)()},g=(0,t.loadDefaultConfig)(),S=Object.assign({},g,s,e);return S.generalLimits=Object.assign({},g.generalLimits,e.generalLimits||{}),S.spanLimits=Object.assign({},g.spanLimits,e.spanLimits||{}),S}e.mergeConfig=g;function S(t){let g=Object.assign({},t.spanLimits);return g.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??e.DEFAULT_ATTRIBUTE_COUNT_LIMIT,g.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},t,{spanLimits:g})}e.reconfigureLimits=S})),require_BatchSpanProcessorBase=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessorBase=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14();e.BatchSpanProcessorBase=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,g){this._exporter=e,this._maxExportBatchSize=typeof g?.maxExportBatchSize==`number`?g.maxExportBatchSize:(0,s.getNumberFromEnv)(`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=typeof g?.maxQueueSize==`number`?g.maxQueueSize:(0,s.getNumberFromEnv)(`OTEL_BSP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=typeof g?.scheduledDelayMillis==`number`?g.scheduledDelayMillis:(0,s.getNumberFromEnv)(`OTEL_BSP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=typeof g?.exportTimeoutMillis==`number`?g.exportTimeoutMillis:(0,s.getNumberFromEnv)(`OTEL_BSP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new s.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&t.diag.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(t.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{let s=[],g=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=g;e<t;e++)s.push(this._flushOneBatch());Promise.all(s).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,g)=>{let S=setTimeout(()=>{g(Error(`Timeout`))},this._exportTimeoutMillis);t.context.with((0,s.suppressTracing)(t.context.active()),()=>{let t;this._finishedSpans.length<=this._maxExportBatchSize?(t=this._finishedSpans,this._finishedSpans=[]):t=this._finishedSpans.splice(0,this._maxExportBatchSize);let w=()=>this._exporter.export(t,t=>{clearTimeout(S),t.code===s.ExportResultCode.SUCCESS?e():g(t.error??Error(`BatchSpanProcessor: span export failed`))}),E=null;for(let e=0,s=t.length;e<s;e++){let s=t[e];s.resource.asyncAttributesPending&&s.resource.waitForAsyncAttributes&&(E??=[],E.push(s.resource.waitForAsyncAttributes()))}E===null?w():Promise.all(E).then(w,e=>{(0,s.globalErrorHandler)(e),g(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,(0,s.globalErrorHandler)(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}})),require_BatchSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessor=void 0;let t=require_BatchSpanProcessorBase();e.BatchSpanProcessor=class extends t.BatchSpanProcessorBase{onShutdown(){}}})),require_RandomIdGenerator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=void 0;let t=8,s=16;e.RandomIdGenerator=class{generateTraceId=S(16);generateSpanId=S(8)};let g=Buffer.allocUnsafe(16);function S(e){return function(){for(let t=0;t<e/4;t++)g.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(g[t]>0);t++)t===e-1&&(g[e-1]=1);return g.toString(`hex`,0,e)}}})),require_node=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_BatchSpanProcessor();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}});var s=require_RandomIdGenerator();Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return s.RandomIdGenerator}})})),require_platform=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_node();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return t.RandomIdGenerator}})})),require_semconv=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.METRIC_OTEL_SDK_SPAN_STARTED=e.METRIC_OTEL_SDK_SPAN_LIVE=e.ATTR_OTEL_SPAN_SAMPLING_RESULT=e.ATTR_OTEL_SPAN_PARENT_ORIGIN=void 0,e.ATTR_OTEL_SPAN_PARENT_ORIGIN=`otel.span.parent.origin`,e.ATTR_OTEL_SPAN_SAMPLING_RESULT=`otel.span.sampling_result`,e.METRIC_OTEL_SDK_SPAN_LIVE=`otel.sdk.span.live`,e.METRIC_OTEL_SDK_SPAN_STARTED=`otel.sdk.span.started`})),require_TracerMetrics=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TracerMetrics=void 0;let t=require_Sampler(),s=require_semconv();e.TracerMetrics=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(s.METRIC_OTEL_SDK_SPAN_STARTED,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(s.METRIC_OTEL_SDK_SPAN_LIVE,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,w){let E=S(w);if(this.startedSpans.add(1,{[s.ATTR_OTEL_SPAN_PARENT_ORIGIN]:g(e),[s.ATTR_OTEL_SPAN_SAMPLING_RESULT]:E}),w===t.SamplingDecision.NOT_RECORD)return()=>{};let D={[s.ATTR_OTEL_SPAN_SAMPLING_RESULT]:E};return this.liveSpans.add(1,D),()=>{this.liveSpans.add(-1,D)}}};function g(e){return e?e.isRemote?`remote`:`local`:`none`}function S(e){switch(e){case t.SamplingDecision.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case t.SamplingDecision.RECORD:return`RECORD_ONLY`;case t.SamplingDecision.NOT_RECORD:return`DROP`}}})),require_version=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`})),require_Tracer=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Tracer=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_Span(),S=require_utility(),w=require_platform(),E=require_TracerMetrics(),D=require_version();e.Tracer=class{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,s,g,O){let k=(0,S.mergeConfig)(s);this._sampler=k.sampler,this._generalLimits=k.generalLimits,this._spanLimits=k.spanLimits,this._idGenerator=s.idGenerator||new w.RandomIdGenerator,this._resource=g,this._spanProcessor=O,this.instrumentationScope=e;let j=k.meterProvider?k.meterProvider.getMeter(`@opentelemetry/sdk-trace`,D.VERSION):t.createNoopMeter();this._tracerMetrics=new E.TracerMetrics(j)}startSpan(e,S={},w=t.context.active()){S.root&&(w=t.trace.deleteSpan(w));let E=t.trace.getSpan(w);if((0,s.isTracingSuppressed)(w))return t.diag.debug(`Instrumentation suppressed, returning Noop Span`),t.trace.wrapSpanContext(t.INVALID_SPAN_CONTEXT);let D=E?.spanContext(),O=this._idGenerator.generateSpanId(),k,j,F;!D||!t.trace.isSpanContextValid(D)?j=this._idGenerator.generateTraceId():(j=D.traceId,F=D.traceState,k=D);let L=S.kind??t.SpanKind.INTERNAL,B=(S.links??[]).map(e=>({context:e.context,attributes:(0,s.sanitizeAttributes)(e.attributes)})),H=(0,s.sanitizeAttributes)(S.attributes),q=this._sampler.shouldSample(w,j,e,L,H,B),ee=this._tracerMetrics.startSpan(D,q.decision);F=q.traceState??F;let J=q.decision===t.SamplingDecision.RECORD_AND_SAMPLED?t.TraceFlags.SAMPLED:t.TraceFlags.NONE,Y={traceId:j,spanId:O,traceFlags:J,traceState:F};if(q.decision===t.SamplingDecision.NOT_RECORD)return t.diag.debug(`Recording is off, propagating context in a non-recording span`),t.trace.wrapSpanContext(Y);let te=(0,s.sanitizeAttributes)(Object.assign(H,q.attributes));return new g.SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:w,spanContext:Y,name:e,kind:L,links:B,parentSpanContext:k,attributes:te,startTime:S.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:ee})}startActiveSpan(e,s,g,S){let w,E,D;if(arguments.length<2)return;arguments.length===2?D=s:arguments.length===3?(w=s,D=g):(w=s,E=g,D=S);let O=E??t.context.active(),k=this.startSpan(e,w,O),j=t.trace.setSpan(O,k);return t.context.with(j,D,void 0,k)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}})),require_MultiSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiSpanProcessor=void 0;let t=require_src$14();e.MultiSpanProcessor=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(s=>{Promise.all(e).then(()=>{s()}).catch(e=>{(0,t.globalErrorHandler)(e||Error(`MultiSpanProcessor: forceFlush failed`)),s()})})}onStart(e,t){for(let s of this._spanProcessors)s.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,s)=>{Promise.all(e).then(()=>{t()},s)})}}})),require_BasicTracerProvider=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BasicTracerProvider=e.ForceFlushState=void 0;let t=require_src$14(),s=require_src$2(),g=require_Tracer(),S=require_config(),w=require_MultiSpanProcessor(),E=require_utility();var D;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(D=e.ForceFlushState||={}),e.BasicTracerProvider=class{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){let g=(0,t.merge)({},(0,S.loadDefaultConfig)(),(0,E.reconfigureLimits)(e));this._resource=g.resource??(0,s.defaultResource)(),this._config=Object.assign({},g,{resource:this._resource});let D=[];e.spanProcessors?.length&&D.push(...e.spanProcessors),this._activeSpanProcessor=new w.MultiSpanProcessor(D)}getTracer(e,t,s){let S=`${e}@${t||``}:${s?.schemaUrl||``}`;return this._tracers.has(S)||this._tracers.set(S,new g.Tracer({name:e,version:t,schemaUrl:s?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(S)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(s=>{let g,S=setTimeout(()=>{s(Error(`Span processor did not completed within timeout period of ${e} ms`)),g=D.timeout},e);t.forceFlush().then(()=>{clearTimeout(S),g!==D.timeout&&(g=D.resolved,s(g))}).catch(e=>{clearTimeout(S),g=D.error,s(e)})}));return new Promise((e,s)=>{Promise.all(t).then(t=>{let g=t.filter(e=>e!==D.resolved);g.length>0?s(g):e()}).catch(e=>s([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}})),require_ConsoleSpanExporter=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleSpanExporter=void 0;let t=require_src$14();e.ConsoleSpanExporter=class{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:(0,t.hrTimeToMicroseconds)(e.startTime),duration:(0,t.hrTimeToMicroseconds)(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,s){for(let t of e)console.dir(this._exportInfo(t),{depth:3});if(s)return s({code:t.ExportResultCode.SUCCESS})}}})),require_InMemorySpanExporter=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemorySpanExporter=void 0;let t=require_src$14();e.InMemorySpanExporter=class{_finishedSpans=[];_stopped=!1;export(e,s){if(this._stopped)return s({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedSpans.push(...e),setTimeout(()=>s({code:t.ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}})),require_SimpleSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleSpanProcessor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14();e.SimpleSpanProcessor=class{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new s.BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)===0)return;let g=this._doExport(e).catch(e=>(0,s.globalErrorHandler)(e));this._pendingExports.add(g),g.finally(()=>this._pendingExports.delete(g))}async _doExport(e){e.resource.asyncAttributesPending&&await e.resource.waitForAsyncAttributes?.();let t=await s.internal._export(this._exporter,[e]);if(t.code!==s.ExportResultCode.SUCCESS)throw t.error??Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),require_NoopSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopSpanProcessor=void 0,e.NoopSpanProcessor=class{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}})),require_src=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=e.TraceIdRatioBasedSampler=e.ParentBasedSampler=e.AlwaysOnSampler=e.AlwaysOffSampler=e.NoopSpanProcessor=e.SimpleSpanProcessor=e.InMemorySpanExporter=e.ConsoleSpanExporter=e.RandomIdGenerator=e.BatchSpanProcessor=e.BasicTracerProvider=void 0;var t=require_BasicTracerProvider();Object.defineProperty(e,`BasicTracerProvider`,{enumerable:!0,get:function(){return t.BasicTracerProvider}});var s=require_platform();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return s.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return s.RandomIdGenerator}});var g=require_ConsoleSpanExporter();Object.defineProperty(e,`ConsoleSpanExporter`,{enumerable:!0,get:function(){return g.ConsoleSpanExporter}});var S=require_InMemorySpanExporter();Object.defineProperty(e,`InMemorySpanExporter`,{enumerable:!0,get:function(){return S.InMemorySpanExporter}});var w=require_SimpleSpanProcessor();Object.defineProperty(e,`SimpleSpanProcessor`,{enumerable:!0,get:function(){return w.SimpleSpanProcessor}});var E=require_NoopSpanProcessor();Object.defineProperty(e,`NoopSpanProcessor`,{enumerable:!0,get:function(){return E.NoopSpanProcessor}});var D=require_AlwaysOffSampler();Object.defineProperty(e,`AlwaysOffSampler`,{enumerable:!0,get:function(){return D.AlwaysOffSampler}});var O=require_AlwaysOnSampler();Object.defineProperty(e,`AlwaysOnSampler`,{enumerable:!0,get:function(){return O.AlwaysOnSampler}});var k=require_ParentBasedSampler();Object.defineProperty(e,`ParentBasedSampler`,{enumerable:!0,get:function(){return k.ParentBasedSampler}});var j=require_TraceIdRatioBasedSampler();Object.defineProperty(e,`TraceIdRatioBasedSampler`,{enumerable:!0,get:function(){return j.TraceIdRatioBasedSampler}});var F=require_Sampler();Object.defineProperty(e,`SamplingDecision`,{enumerable:!0,get:function(){return F.SamplingDecision}})})),require_utils$2=__commonJSMin$2(((e,t)=>{function s(e){if(e.length===0)return;let t=Object.create(null),s=0;for(;s<e.length;++s){let t=e.charCodeAt(s);if(j[t]!==1){if(t!==47||s===0)return;break}}if(s===e.length)return;let S=e.slice(0,s).toLowerCase(),w=++s;for(;s<e.length;++s)if(j[e.charCodeAt(s)]!==1){if(s===w||g(e,s,t)===void 0)return;break}if(s!==w)return{type:S,subtype:e.slice(w,s).toLowerCase(),params:t}}function g(e,t,s){for(;t<e.length;){for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)return;let g,S=t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(j[s]!==1){if(s!==61)return;break}}if(t===e.length||(g=e.slice(S,t),++t,t===e.length))return;let w=``,E;if(e.charCodeAt(t)===34){E=++t;let s=!1;for(;t<e.length;++t){let g=e.charCodeAt(t);if(g===92){s?(E=t,s=!1):(w+=e.slice(E,t),s=!0);continue}if(g===34){if(s){E=t,s=!1;continue}w+=e.slice(E,t);break}if(s&&=(E=t-1,!1),F[g]!==1)return}if(t===e.length)return;++t}else{for(E=t;t<e.length;++t)if(j[e.charCodeAt(t)]!==1){if(t===E)return;break}w=e.slice(E,t)}g=g.toLowerCase(),s[g]===void 0&&(s[g]=w)}return s}function S(e,t){if(e.length===0)return;let s=Object.create(null),g=0;for(;g<e.length;++g)if(j[e.charCodeAt(g)]!==1){if(w(e,g,s,t)===void 0)return;break}return{type:e.slice(0,g).toLowerCase(),params:s}}function w(e,t,s,g){for(;t<e.length;){for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)return;let S,w=t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(j[s]!==1){if(s===61)break;return}}if(t===e.length)return;let E=``,D,k;if(S=e.slice(w,t),S.charCodeAt(S.length-1)===42){let s=++t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(L[s]!==1){if(s!==39)return;break}}if(t===e.length)return;for(k=e.slice(s,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;D=t;let g=0;for(;t<e.length;++t){let s=e.charCodeAt(t);if(B[s]!==1){if(s===37){let s,S;if(t+2<e.length&&(s=H[e.charCodeAt(t+1)])!==-1&&(S=H[e.charCodeAt(t+2)])!==-1){let w=(s<<4)+S;E+=e.slice(D,t),E+=String.fromCharCode(w),t+=2,D=t+1,w>=128?g=2:g===0&&(g=1);continue}return}break}}if(E+=e.slice(D,t),E=O(E,k,g),E===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){D=++t;let s=!1;for(;t<e.length;++t){let g=e.charCodeAt(t);if(g===92){s?(D=t,s=!1):(E+=e.slice(D,t),s=!0);continue}if(g===34){if(s){D=t,s=!1;continue}E+=e.slice(D,t);break}if(s&&=(D=t-1,!1),F[g]!==1)return}if(t===e.length)return;++t}else{for(D=t;t<e.length;++t)if(j[e.charCodeAt(t)]!==1){if(t===D)return;break}E=e.slice(D,t)}if(E=g(E,2),E===void 0)return}S=S.toLowerCase(),s[S]===void 0&&(s[S]=E)}return s}function E(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return D.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return D.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return D.utf16le;case`base64`:return D.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return D.other.bind(e)}}let D={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,s)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function O(e,t,s){let g=E(t);if(g)return g(e,s)}function k(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let j=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],F=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],L=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],B=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],H=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:k,convertToUTF8:O,getDecoder:E,parseContentType:s,parseDisposition:S}})),require_sbmh=__commonJSMin$2(((e,t)=>{function s(e,t,s,g,S){for(let w=0;w<S;++w)if(e[t+w]!==s[g+w])return!1;return!0}var g=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let s=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(s),this._occ=[s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s],s>1)for(let t=0;t<s-1;++t)this._occ[e[t]]=s-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let s;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let g=e.length;for(this._bufPos=t||0;s!==g&&this.matches<this.maxMatches;)s=S(this,e);return s}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function S(e,t){let g=t.length,S=e._needle,E=S.length,D=-e._lookbehindSize,O=E-1,k=S[O],j=g-E,F=e._occ,L=e._lookbehind;if(D<0){for(;D<0&&D<=j;){let s=D+O,g=s<0?L[e._lookbehindSize+s]:t[s];if(g===k&&w(e,t,D,O))return e._lookbehindSize=0,++e.matches,D>-e._lookbehindSize?e._cb(!0,L,0,e._lookbehindSize+D,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=D+E;D+=F[g]}for(;D<0&&!w(e,t,D,g-D);)++D;if(D<0){let s=e._lookbehindSize+D;return s>0&&e._cb(!1,L,0,s,!1),e._lookbehindSize-=s,L.copy(L,0,s,e._lookbehindSize),L.set(t,e._lookbehindSize),e._lookbehindSize+=g,e._bufPos=g,g}e._cb(!1,L,0,e._lookbehindSize,!1),e._lookbehindSize=0}D+=e._bufPos;let B=S[0];for(;D<=j;){let g=t[D+O];if(g===k&&t[D]===B&&s(S,0,t,D,O))return++e.matches,D>0?e._cb(!0,t,e._bufPos,D,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=D+E;D+=F[g]}for(;D<g;){if(t[D]!==B||!s(t,D,S,0,g-D)){++D;continue}t.copy(L,0,D,g),e._lookbehindSize=g-D;break}return D>0&&e._cb(!1,t,e._bufPos,D<g?D:g,!0),e._bufPos=g,g}function w(e,t,s,g){let S=e._lookbehind,w=e._lookbehindSize,E=e._needle;for(let e=0;e<g;++e,++s)if((s<0?S[w+s]:t[s])!==E[e])return!1;return!0}t.exports=g})),require_multipart=__commonJSMin$2(((e,t)=>{let{Readable:s,Writable:g}=__require$2(`stream`),S=require_sbmh(),{basename:w,convertToUTF8:E,getDecoder:D,parseContentType:O,parseDisposition:k}=require_utils$2(),j=Buffer.from(`\r
38
- `),F=Buffer.from(`\r`),L=Buffer.from(`-`);function B(){}let H=2e3,q=16*1024,ee=0,J=1,Y=2;var te=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,s){let g=t;for(;t<s;)switch(this.state){case 0:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(fe[s]!==1){if(s!==58||(this.name+=e.latin1Slice(g,t),this.name.length===0))return-1;++t,S=!0,this.state=1;break}}if(!S){this.name+=e.latin1Slice(g,t);break}}case 1:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(s!==32&&s!==9){g=t,S=!0,this.state=2;break}}if(!S)break}case 2:switch(this.crlf){case 0:for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(me[s]!==1){if(s!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(g,t++);break;case 1:if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];s===32||s===9?(g=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),s===13?(++this.crlf,++t):(g=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;let s=this.header;return this.reset(),this.cb(s),t}}break}return t}},ne=class extends s{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let ae={push:(e,t)=>{},destroy:()=>{}};function oe(e,t){let s=e._writecb;e._writecb=null,t?e.destroy(t):s&&s()}function se(e,t){return e}var ce=class extends g{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let s=e.conType.params.boundary,g=typeof e.defParamCharset==`string`&&e.defParamCharset?D(e.defParamCharset):se,H=e.defCharset||`utf8`,q=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},J=e.limits,Y=J&&typeof J.fieldSize==`number`?J.fieldSize:1*1024*1024,oe=J&&typeof J.fileSize==`number`?J.fileSize:1/0,ce=J&&typeof J.files==`number`?J.files:1/0,ue=J&&typeof J.fields==`number`?J.fields:1/0,de=J&&typeof J.parts==`number`?J.parts:1/0,fe=-1,me=0,ge=0,_e=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let ve=0,ye,Ce=0,we,Te,De,je,Me=!1,Pe=!1,Ie=!1;this._hparser=null;let Re=new te(e=>{this._hparser=null,_e=!1,De=`text/plain`,we=H,Te=`7bit`,je=void 0,Me=!1;let t;if(!e[`content-disposition`]){_e=!0;return}let s=k(e[`content-disposition`][0],g);if(!s||s.type!==`form-data`){_e=!0;return}if(s.params&&(s.params.name&&(je=s.params.name),s.params[`filename*`]?t=s.params[`filename*`]:s.params.filename&&(t=s.params.filename),t!==void 0&&!q&&(t=w(t))),e[`content-type`]){let t=O(e[`content-type`][0]);t&&(De=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(we=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(Te=e[`content-transfer-encoding`][0].toLowerCase()),De===`application/octet-stream`||t!==void 0){if(ge===ce){Pe||(Pe=!0,this.emit(`filesLimit`)),_e=!0;return}if(++ge,this.listenerCount(`file`)===0){_e=!0;return}ve=0,this._fileStream=new ne(ee,this),++this._fileEndsLeft,this.emit(`file`,je,this._fileStream,{filename:t,encoding:Te,mimeType:De})}else{if(me===ue){Ie||(Ie=!0,this.emit(`fieldsLimit`)),_e=!0;return}if(++me,this.listenerCount(`field`)===0){_e=!0;return}ye=[],Ce=0}}),ze=0,Be=(e,t,s,g,S)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,s,g);if(e===-1){this._hparser=null,Re.reset(),this.emit(`error`,Error(`Malformed part header`));break}s=e}if(s===g)break;if(ze!==0){if(ze===1){switch(t[s]){case 45:ze=2,++s;break;case 13:ze=3,++s;break;default:ze=0}if(s===g)return}if(ze===2){if(ze=0,t[s]===45){this._complete=!0,this._bparser=ae;return}let e=this._writecb;this._writecb=B,Be(!1,L,0,1,!1),this._writecb=e}else if(ze===3)if(ze=0,t[s]===10){if(++s,fe>=de||(this._hparser=Re,s===g))break;continue retrydata}else{let e=this._writecb;this._writecb=B,Be(!1,F,0,1,!1),this._writecb=e}}if(!_e){if(this._fileStream){let e,w=Math.min(g-s,oe-ve);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),ve+=e.length,ve===oe?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,_e=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(ye!==void 0){let e,w=Math.min(g-s,Y-Ce);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),Ce+=w,ye.push(e),Ce===Y&&(_e=!0,Me=!0)}}break}if(e){if(ze=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(ye!==void 0){let e;switch(ye.length){case 0:e=``;break;case 1:e=E(ye[0],we,0);break;default:e=E(Buffer.concat(ye,Ce),we,0)}ye=void 0,Ce=0,this.emit(`field`,je,e,{nameTruncated:!1,valueTruncated:Me,encoding:Te,mimeType:De})}++fe===de&&this.emit(`partsLimit`)}};this._bparser=new S(`\r\n--${s}`,Be),this._writecb=null,this._finalcb=null,this.write(j)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,s){this._writecb=s,this._bparser.push(e,0),this._writecb&&oe(this)}_destroy(e,t){this._hparser=null,this._bparser=ae,e||=de(this);let s=this._fileStream;s&&(this._fileStream=null,s.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=ue.bind(null,this,e):ue(this,e)}};function ue(e,t,s){if(s)return t(s);s=de(e),t(s)}function de(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let fe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],me=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];t.exports=ce})),require_urlencoded=__commonJSMin$2(((e,t)=>{let{Writable:s}=__require$2(`stream`),{getDecoder:g}=require_utils$2();var S=class extends s{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let s=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(s=e.conType.params.charset),this.charset=s;let S=e.limits;this.fieldSizeLimit=S&&typeof S.fieldSize==`number`?S.fieldSize:1*1024*1024,this.fieldsLimit=S&&typeof S.fields==`number`?S.fields:1/0,this.fieldNameSizeLimit=S&&typeof S.fieldNameSize==`number`?S.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=g(s)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,s){if(this._fields>=this.fieldsLimit)return s();let g=0,S=e.length;if(this._lastPos=0,this._byte!==-2){if(g=w(this,e,g,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;g<S;)if(this._inKey){for(g=E(this,e,g,S);g<S;){switch(e[g]){case 61:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue;case 43:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._key+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesKey,g=E(this,e,g,S);continue}++g,++this._bytesKey,g=E(this,e,g,S)}this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g))}else{for(g=D(this,e,g,S);g<S;){switch(e[g]){case 38:if(this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue main;case 43:this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._val+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesVal,g=D(this,e,g,S);continue}++g,++this._bytesVal,g=D(this,e,g,S)}this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g))}s()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function w(e,t,s,g){if(s>=g)return g;if(e._byte===-1){let S=O[t[s++]];if(S===-1)return-1;if(S>=8&&(e._encode=2),s<g){let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((S<<4)+g):e._val+=String.fromCharCode((S<<4)+g),e._byte=-2,e._lastPos=s}else e._byte=S}else{let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+g):e._val+=String.fromCharCode((e._byte<<4)+g),e._byte=-2,e._lastPos=s}return s}function E(e,t,s,g){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<s&&(e._key+=t.latin1Slice(e._lastPos,s-1)),e._keyTrunc=!0;s<g;++s){let g=t[s];if(g===61||g===38)break;++e._bytesKey}e._lastPos=s}return s}function D(e,t,s,g){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<s&&(e._val+=t.latin1Slice(e._lastPos,s-1)),e._valTrunc=!0;s<g&&t[s]!==38;++s)++e._bytesVal;e._lastPos=s}return s}let O=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports=S})),require_lib=__commonJSMin$2(((e,t)=>{let{parseContentType:s}=require_utils$2();function g(e){let t=e.headers,g=s(t[`content-type`]);if(!g)throw Error(`Malformed content type`);for(let s of S){if(!s.detect(g))continue;let S={limits:e.limits,headers:t,conType:g,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(S.highWaterMark=e.highWaterMark),e.fileHwm&&(S.fileHwm=e.fileHwm),S.defCharset=e.defCharset,S.defParamCharset=e.defParamCharset,S.preservePath=e.preservePath,new s(S)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let S=[require_multipart(),require_urlencoded()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return g(e)}}));const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,s){t.push(s),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,s){if(s<=65535){pushCodeUnit(e,t,s);return}s-=65536,pushCodeUnit(e,t,55296+(s>>10)),pushCodeUnit(e,t,56320+(s&1023))}function decodeUTF8(e){let t=[],s=[],g=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(g=3);g<e.length;){let S=e[g];if(S<=127){pushCodeUnit(t,s,S),g++;continue}if(S<194||S>244){pushCodeUnit(t,s,REPLACEMENT),g++;continue}if(S<=223){if(g+1>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1];if((w&192)!=128){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&31)<<6|w&63),g+=2;continue}if(S<=239){if(g+2>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2];if(!((w&192)==128&&(E&192)==128&&!(S===224&&w<160)&&!(S===237&&w>=160))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&15)<<12|(w&63)<<6|E&63),g+=3;continue}if(g+3>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2],D=e[g+3];if(!((w&192)==128&&(E&192)==128&&(D&192)==128&&!(S===240&&w<144)&&!(S===244&&w>143))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodePoint(t,s,(S&7)<<18|(w&63)<<12|(E&63)<<6|D&63),g+=4}return flushChunk(t,s),t.join(``)}function decodeUTF16LE(e){let t=[],s=[],g=e.length,S=0;for(;S+1<g;){let w=e[S]|e[S+1]<<8;if(S+=2,w>=55296&&w<=56319){if(S+1<g){let g=e[S]|e[S+1]<<8;g>=56320&&g<=57343?(pushCodeUnit(t,s,w),pushCodeUnit(t,s,g),S+=2):pushCodeUnit(t,s,REPLACEMENT)}else pushCodeUnit(t,s,REPLACEMENT);continue}if(w>=56320&&w<=57343){pushCodeUnit(t,s,REPLACEMENT);continue}pushCodeUnit(t,s,w)}return S<g&&pushCodeUnit(t,s,REPLACEMENT),flushChunk(t,s),t.join(``)}function decodeASCII(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t]&127;t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeLatin1(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t];t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeWindows1252(e){let t=[],s=``;for(let g=0;g<e.length;g++){let S=e[g],w=S>=128&&S<=159?WINDOWS_1252_EXTRA[S]:void 0;s+=w??String.fromCharCode(S),s.length>=CHUNK&&(t.push(s),s=``)}return s&&t.push(s),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,s){return dv(e).setUint8(t,s),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,s){return dv(e).setUint16(t,s,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,s){return dv(e).setUint16(t,s),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,s){return dv(e).setUint32(t,s,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,s){return dv(e).setUint32(t,s),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,s){return dv(e).setInt32(t,s),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,s){return dv(e).setBigUint64(t,s,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let s=await this.read(e,t);return this.peekQueue.push(e.subarray(0,s)),s}async read(e,t=!1){if(e.length===0)return 0;let s=this.readFromPeekBuffer(e);if(this.endOfStream||(s+=await this.readRemainderFromStream(e.subarray(s),t)),s===0&&!t)throw new EndOfStreamError;return s}readFromPeekBuffer(e){let t=e.length,s=0;for(;this.peekQueue.length>0&&t>0;){let g=this.peekQueue.pop();if(!g)throw Error(`peekData should be defined`);let S=Math.min(g.length,t);e.set(g.subarray(0,S),s),s+=S,t-=S,S<g.length&&this.peekQueue.push(g.subarray(S))}return s}async readRemainderFromStream(e,t){let s=0;for(;s<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let g=await this.readFromStream(e.subarray(s),t);if(g===0)break;s+=g}if(!t&&s<e.length)throw new EndOfStreamError;return s}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let s=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return s.done&&(this.endOfStream=s.done),s.value?(e.set(s.value),s.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let s=Math.min(t.length,e.length);return e.set(t.subarray(0,s)),s<t.length?this.buffer=t.subarray(s):this.buffer=null,s}async readFromStream(e,t){if(e.length===0)return 0;let s=0;for(this.buffer&&(s+=this.writeChunk(e,this.buffer));s<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(s+=this.writeChunk(e.subarray(s),t.value))}if(!t&&s===0&&this.endOfStream)throw new EndOfStreamError;return s}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.readBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async peekToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.peekBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let s=this.normalizeOptions(e,t),g=s.position-this.position;if(g>0)return await this.ignore(g),this.readBuffer(e,t);if(g<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(s.length===0)return 0;let S=await this.streamReader.read(e.subarray(0,s.length),s.mayBeLess);if(this.position+=S,(!t||!t.mayBeLess)&&S<s.length)throw new EndOfStreamError;return S}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=0;if(s.position){let t=s.position-this.position;if(t>0){let S=new Uint8Array(s.length+t);return g=await this.peekBuffer(S,{mayBeLess:s.mayBeLess}),e.set(S.subarray(t)),g-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(s.length>0){try{g=await this.streamReader.peek(e.subarray(0,s.length),s.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError}return g}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),s=new Uint8Array(t),g=0;for(;g<e;){let S=e-g,w=await this.readBuffer(s,{length:Math.min(t,S)});if(w<0)return w;g+=w}return g}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.uint8Array.length-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(s.position,s.position+g)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.blob.size-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;let S=await this.blob.slice(s.position,s.position+g).arrayBuffer();return e.set(new Uint8Array(S)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let s=makeWebStreamReader(e),g=t??{},S=g.onClose;return g.onClose=async()=>{if(await s.close(),S)return S()},new ReadStreamTokenizer(s,g)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$8=__toESM$2(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$8.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),s=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(s,{position:e.fileInfo.size-t});for(let g=s.length-4;g>=0;g--)if(s[g]===eocdSignatureBytes[0]&&s[g+1]===eocdSignatureBytes[1]&&s[g+2]===eocdSignatureBytes[2]&&s[g+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+g;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let s=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),g=[];this.tokenizer.setPosition(s.offsetOfStartOfCd);for(let e=0;e<s.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),g.push(t),debug(`Add central-directory file-entry: n=${e+1}/${g.length}: filename=${g[e].filename}`)}return this.tokenizer.setPosition(e),g}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let s=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let g=e(t);s=!!g.stop;let S;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],s=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let S=-1;for(;S<0&&s===syncBufferSize;){s=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),S=indexOf(this.syncBuffer.subarray(0,s),ddSignatureArray);let t=S>=0?S:s;if(g.handler){let s=new Uint8Array(t);await this.tokenizer.readBuffer(s),e.push(s)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),g.handler&&await this.inflate(t,mergeArrays(e),g.handler)}else g.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),S=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(S),await this.inflate(t,S,g.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!s)}async iterateOverCentralDirectory(e,t){for(let s of e){let e=t(s);if(e.handler){this.tokenizer.setPosition(s.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let g=new Uint8Array(s.compressedSize);await this.tokenizer.readBuffer(g),await this.inflate(t,g,e.handler)}}if(e.stop)break}}async inflate(t,s,g){if(t.compressedMethod===0)return g(s);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${s.length}`),g(await e.decompressDeflateRaw(s))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),s=new DecompressionStream(`deflate-raw`),g=t.pipeThrough(s);try{let e=await new Response(g).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let s=e.length,g=t.length;if(g>s)return-1;for(let S=0;S<=s-g;S++){let s=!0;for(let w=0;w<g;w++)if(e[S+w]!==t[w]){s=!1;break}if(s)return S}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let s=new Uint8Array(1024),g=await e.readBuffer(s,{mayBeLess:!0});if(g===0){t.close();return}t.enqueue(s.subarray(0,g))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,s){return e?e.constructor===t?!0:objectToString.call(e)===s:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let s=new Uint8Array(t),g=0;for(let t of e)assertUint8Array(t),s.set(t,g),g+=t.length;return s}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g&255,g>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g>>8&255,g&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let s=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(s))return!1;let g=256;for(let s=t;s<t+148;s++)g+=e[s];for(let s=t+156;s<t+512;s++)g+=e[s];return s===g}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,s){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${s} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:s=maximumUntrustedSkipSizeInBytes,reason:g=`skip`}={}){let S=getSafeBound(t,s,g);await e.ignore(S)}async function safeReadBuffer(e,t,s,{maximumLength:g=t.length,reason:S=`read`}={}){let w=getSafeBound(s?.length??t.length,g,S);return e.readBuffer(t,{...s,length:w})}function checkBytes(e,t,s){s={offset:0,...s};for(let[g,S]of t.entries())if(s.mask){if(S!==(s.mask[g]&e[g+s.offset]))return!1}else if(S!==e[g+s.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,s){return hasUnknownFileSize(e)&&e.position-t>s}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),g=[],S=0;try{for(;;){let{done:e,value:w}=await s.read();if(e)break;if(S+=w.length,S>t)throw await s.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);g.push(w)}}finally{s.releaseLock()}let w=new Uint8Array(S),E=0;for(let e of g)w.set(e,E),E+=e.length;return w}function mergeByteChunks(e,t){let s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,s=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(s,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let s=[e.compressedSize,e.uncompressedSize];for(let e of s)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let s=e.slice(0,t),g=s.lastIndexOf(`"`);return s.slice(g+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let s=e.length-zipDataDescriptorLengthInBytes;for(let g=0;g<=s;g++)if(UINT32_LE.get(e,g)===zipDataDescriptorSignature&&UINT32_LE.get(e,g+8)===t+g)return g;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:s=maximumZipEntrySizeInBytes}={}){let{syncBuffer:g}=e,{length:S}=g,w=[],E=0;for(;;){let D=await e.tokenizer.peekBuffer(g,{mayBeLess:!0}),O=findZipDataDescriptorOffset(g.subarray(0,D),E),k=O>=0?0:D===S?Math.min(zipDataDescriptorOverlapLengthInBytes,D-1):0,j=O>=0?O:D-k;if(j===0)break;if(E+=j,E>s)throw Error(`ZIP entry compressed data exceeds ${s} bytes`);if(t){let t=new Uint8Array(j);await e.tokenizer.readBuffer(t),w.push(t)}else await e.tokenizer.ignore(j);if(O>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=E),t)return mergeByteChunks(w,E)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:s,maximumDescriptorLength:g=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:s,maximumLength:g});if(!s){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let S=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);let w=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(w),w}ZipHandler.prototype.inflate=async function(e,t,s){if(e.compressedMethod===0)return s(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return s(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,s=0,g=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let S=await this.readLocalFileHeader();if(!S)break;if(s++,s>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let w=e(S);t=!!w.stop,await this.tokenizer.ignore(S.extraFieldLength);let E=await readZipEntryData(this,S,{shouldBuffer:!!w.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,g))});if(w.handler&&await this.inflate(S,E,w.handler),S.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,s=createOpenXmlZipDetectionState(),g=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(s,e.filename),updateIWorkZipDetectionStateFromFilename(g,e.filename),g.hasDocumentEntry&&(g.hasMasterSlideEntry||g.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(g),{stop:!0};let S=e.filename===`[Content_Types].xml`,w=getOpenXmlFileTypeFromZipEntries(s);if(!S&&w)return t=w,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return s.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(s.isParsingContentTypes=!0,{async handler(e){let g=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));g&&(t=getFileTypeFromMimeType(g)),s.hasParsedContentTypesEntry=!0,s.isParsingContentTypes=!1},stop:!0}):(s.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;s.isParsingContentTypes&&(s.isParsingContentTypes=!1,s.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!s.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(s))}let S=hasUnknownFileSize(e)&&g.hasDocumentEntry&&!g.hasMasterSlideEntry&&!g.hasTablesEntry&&!g.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(g);return t??getOpenXmlFileTypeFromZipEntries(s)??S??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),s=128,g=0;for(;(t&s)===0&&s!==0;)++g,s>>=1;let S=new Uint8Array(g+1);return await safeReadBuffer(e,S,void 0,{maximumLength:S.length,reason:`EBML field`}),S}async function s(){let e=await t(),s=await t();s[0]^=128>>s.length-1;let g=Math.min(6,s.length),S=new DataView(e.buffer),w=new DataView(s.buffer,s.length-g,g);return{id:getUintBE(S),len:getUintBE(w)}}async function g(t){let g=0;for(;t>0;){if(g++,g>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,w,16777216))return;let S=e.position,E=await s();if(E.id===17026){if(E.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(E.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(E.len)||E.len<0||E.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,E.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=S))return}}let S=await s(),w=e.position;switch(await g(S.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},s={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function g(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let S=hasUnknownFileSize(e),w=e.position,E=0,D=!1;do{if(E++,E>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,w,maximumPngStreamScanBudgetInBytes))break;let O=e.position,k=await g();if(k.length<0)return;if(k.type===`IHDR`){if(k.length!==13)return;D=!0}switch(k.type){case`IDAT`:return t;case`acTL`:return s;default:if(!D&&k.type!==`CgBI`)return;if(S&&k.length>maximumPngChunkSizeInBytes)return D&&isPngAncillaryChunk(k.type)?t:void 0;try{await safeIgnore(e,k.length+4,{maximumLength:S?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!S&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=O)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function s(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let g=hasUnknownFileSize(e),S=e.position,w=0;for(;e.position+24<e.fileInfo.size&&(w++,!(w>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,S,16777216)));){let S=e.position,w=await s(),E=w.size-24;if(!Number.isFinite(E)||E<0){t=!0;break}if(checkBytes(w.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(E-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(g&&E>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,E,{maximumLength:g?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=S){t=!0;break}}}catch(s){if(s instanceof EndOfStreamError||s instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw s}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((s,g)=>{t.addEventListener(`abort`,()=>{g(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let s=e.getReader(),g=0,S=!1,w=!1,E=async e=>{S||w||(w=!0,await s.cancel(e))};return new ReadableStream({async pull(e){if(g>=t){e.close(),await E();return}let{done:w,value:D}=await s.read();if(w||!D){S=!0,e.close();return}let O=t-g;if(D.length>O){e.enqueue(D.subarray(0,O)),g+=O,e.close(),await E();return}e.enqueue(D),g+=D.length},async cancel(e){await E(e)}})}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let s=e.position;for(let t of this.detectors){let g;try{g=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(g)return g;if(s!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:s}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),g=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),S=await g.stat();if(!S.isFile()){await g.close();return}let w=new s(g,{...this.getTokenizerOptions(),fileInfo:{path:e,size:S.size}});return this.fromTokenizer(w)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let s=normalizeSampleSize(t?.sampleSize??4100),g,S=!1,w=e.getReader(),E=[],D=0;try{for(;D<s;){let{value:e,done:t}=await readWithSignal(w,this.options.signal);if(t||!e){S=!0;break}E.push(e),D+=e.length}if(!S&&D===s){let{value:e,done:t}=await readWithSignal(w,this.options.signal);t||!e?S=!0:(E.push(e),D+=e.length)}}finally{w.releaseLock()}if(D>0){let e=E.length===1?E[0]:concatUint8Arrays(E);try{g=await this.fromBuffer(e.subarray(0,s))}catch(e){if(!(e instanceof EndOfStreamError))throw e;g=void 0}!S&&g?.ext===`pages`&&(g={ext:`zip`,mime:`application/zip`})}let O=new TransformStream({start(e){for(let t of E)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),k=e.pipeThrough(O);return k.fileType=g,k}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let s=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),g=hasUnknownFileSize(t),S,w,E,D;if(g){let t=new AbortController;S=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),w=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),E=new e({...this.options,signal:w}),E.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{D=await(E??this).fromStream(s)}catch(e){if(e?.name===`AbortError`&&w?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(S),g||this.gzipProbeDepth--}return D?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),s=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||s&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return s?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:s?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
38
+ `),F=Buffer.from(`\r`),L=Buffer.from(`-`);function B(){}let H=2e3,q=16*1024,ee=0,J=1,Y=2;var te=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,s){let g=t;for(;t<s;)switch(this.state){case 0:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(fe[s]!==1){if(s!==58||(this.name+=e.latin1Slice(g,t),this.name.length===0))return-1;++t,S=!0,this.state=1;break}}if(!S){this.name+=e.latin1Slice(g,t);break}}case 1:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(s!==32&&s!==9){g=t,S=!0,this.state=2;break}}if(!S)break}case 2:switch(this.crlf){case 0:for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(me[s]!==1){if(s!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(g,t++);break;case 1:if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];s===32||s===9?(g=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),s===13?(++this.crlf,++t):(g=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;let s=this.header;return this.reset(),this.cb(s),t}}break}return t}},ne=class extends s{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let ae={push:(e,t)=>{},destroy:()=>{}};function oe(e,t){let s=e._writecb;e._writecb=null,t?e.destroy(t):s&&s()}function se(e,t){return e}var ce=class extends g{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let s=e.conType.params.boundary,g=typeof e.defParamCharset==`string`&&e.defParamCharset?D(e.defParamCharset):se,H=e.defCharset||`utf8`,q=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},J=e.limits,Y=J&&typeof J.fieldSize==`number`?J.fieldSize:1*1024*1024,oe=J&&typeof J.fileSize==`number`?J.fileSize:1/0,ce=J&&typeof J.files==`number`?J.files:1/0,ue=J&&typeof J.fields==`number`?J.fields:1/0,de=J&&typeof J.parts==`number`?J.parts:1/0,fe=-1,me=0,ge=0,_e=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let ve=0,ye,Ce=0,we,Te,De,je,Me=!1,Pe=!1,Ie=!1;this._hparser=null;let Re=new te(e=>{this._hparser=null,_e=!1,De=`text/plain`,we=H,Te=`7bit`,je=void 0,Me=!1;let t;if(!e[`content-disposition`]){_e=!0;return}let s=k(e[`content-disposition`][0],g);if(!s||s.type!==`form-data`){_e=!0;return}if(s.params&&(s.params.name&&(je=s.params.name),s.params[`filename*`]?t=s.params[`filename*`]:s.params.filename&&(t=s.params.filename),t!==void 0&&!q&&(t=w(t))),e[`content-type`]){let t=O(e[`content-type`][0]);t&&(De=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(we=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(Te=e[`content-transfer-encoding`][0].toLowerCase()),De===`application/octet-stream`||t!==void 0){if(ge===ce){Pe||(Pe=!0,this.emit(`filesLimit`)),_e=!0;return}if(++ge,this.listenerCount(`file`)===0){_e=!0;return}ve=0,this._fileStream=new ne(ee,this),++this._fileEndsLeft,this.emit(`file`,je,this._fileStream,{filename:t,encoding:Te,mimeType:De})}else{if(me===ue){Ie||(Ie=!0,this.emit(`fieldsLimit`)),_e=!0;return}if(++me,this.listenerCount(`field`)===0){_e=!0;return}ye=[],Ce=0}}),ze=0,Be=(e,t,s,g,S)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,s,g);if(e===-1){this._hparser=null,Re.reset(),this.emit(`error`,Error(`Malformed part header`));break}s=e}if(s===g)break;if(ze!==0){if(ze===1){switch(t[s]){case 45:ze=2,++s;break;case 13:ze=3,++s;break;default:ze=0}if(s===g)return}if(ze===2){if(ze=0,t[s]===45){this._complete=!0,this._bparser=ae;return}let e=this._writecb;this._writecb=B,Be(!1,L,0,1,!1),this._writecb=e}else if(ze===3)if(ze=0,t[s]===10){if(++s,fe>=de||(this._hparser=Re,s===g))break;continue retrydata}else{let e=this._writecb;this._writecb=B,Be(!1,F,0,1,!1),this._writecb=e}}if(!_e){if(this._fileStream){let e,w=Math.min(g-s,oe-ve);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),ve+=e.length,ve===oe?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,_e=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(ye!==void 0){let e,w=Math.min(g-s,Y-Ce);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),Ce+=w,ye.push(e),Ce===Y&&(_e=!0,Me=!0)}}break}if(e){if(ze=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(ye!==void 0){let e;switch(ye.length){case 0:e=``;break;case 1:e=E(ye[0],we,0);break;default:e=E(Buffer.concat(ye,Ce),we,0)}ye=void 0,Ce=0,this.emit(`field`,je,e,{nameTruncated:!1,valueTruncated:Me,encoding:Te,mimeType:De})}++fe===de&&this.emit(`partsLimit`)}};this._bparser=new S(`\r\n--${s}`,Be),this._writecb=null,this._finalcb=null,this.write(j)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,s){this._writecb=s,this._bparser.push(e,0),this._writecb&&oe(this)}_destroy(e,t){this._hparser=null,this._bparser=ae,e||=de(this);let s=this._fileStream;s&&(this._fileStream=null,s.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=ue.bind(null,this,e):ue(this,e)}};function ue(e,t,s){if(s)return t(s);s=de(e),t(s)}function de(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let fe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],me=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];t.exports=ce})),require_urlencoded=__commonJSMin$2(((e,t)=>{let{Writable:s}=__require$2(`stream`),{getDecoder:g}=require_utils$2();var S=class extends s{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let s=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(s=e.conType.params.charset),this.charset=s;let S=e.limits;this.fieldSizeLimit=S&&typeof S.fieldSize==`number`?S.fieldSize:1*1024*1024,this.fieldsLimit=S&&typeof S.fields==`number`?S.fields:1/0,this.fieldNameSizeLimit=S&&typeof S.fieldNameSize==`number`?S.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=g(s)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,s){if(this._fields>=this.fieldsLimit)return s();let g=0,S=e.length;if(this._lastPos=0,this._byte!==-2){if(g=w(this,e,g,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;g<S;)if(this._inKey){for(g=E(this,e,g,S);g<S;){switch(e[g]){case 61:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue;case 43:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._key+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesKey,g=E(this,e,g,S);continue}++g,++this._bytesKey,g=E(this,e,g,S)}this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g))}else{for(g=D(this,e,g,S);g<S;){switch(e[g]){case 38:if(this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue main;case 43:this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._val+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesVal,g=D(this,e,g,S);continue}++g,++this._bytesVal,g=D(this,e,g,S)}this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g))}s()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function w(e,t,s,g){if(s>=g)return g;if(e._byte===-1){let S=O[t[s++]];if(S===-1)return-1;if(S>=8&&(e._encode=2),s<g){let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((S<<4)+g):e._val+=String.fromCharCode((S<<4)+g),e._byte=-2,e._lastPos=s}else e._byte=S}else{let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+g):e._val+=String.fromCharCode((e._byte<<4)+g),e._byte=-2,e._lastPos=s}return s}function E(e,t,s,g){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<s&&(e._key+=t.latin1Slice(e._lastPos,s-1)),e._keyTrunc=!0;s<g;++s){let g=t[s];if(g===61||g===38)break;++e._bytesKey}e._lastPos=s}return s}function D(e,t,s,g){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<s&&(e._val+=t.latin1Slice(e._lastPos,s-1)),e._valTrunc=!0;s<g&&t[s]!==38;++s)++e._bytesVal;e._lastPos=s}return s}let O=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports=S})),require_lib=__commonJSMin$2(((e,t)=>{let{parseContentType:s}=require_utils$2();function g(e){let t=e.headers,g=s(t[`content-type`]);if(!g)throw Error(`Malformed content type`);for(let s of S){if(!s.detect(g))continue;let S={limits:e.limits,headers:t,conType:g,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(S.highWaterMark=e.highWaterMark),e.fileHwm&&(S.fileHwm=e.fileHwm),S.defCharset=e.defCharset,S.defParamCharset=e.defParamCharset,S.preservePath=e.preservePath,new s(S)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let S=[require_multipart(),require_urlencoded()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return g(e)}}));const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,s){t.push(s),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,s){if(s<=65535){pushCodeUnit(e,t,s);return}s-=65536,pushCodeUnit(e,t,55296+(s>>10)),pushCodeUnit(e,t,56320+(s&1023))}function decodeUTF8(e){let t=[],s=[],g=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(g=3);g<e.length;){let S=e[g];if(S<=127){pushCodeUnit(t,s,S),g++;continue}if(S<194||S>244){pushCodeUnit(t,s,REPLACEMENT),g++;continue}if(S<=223){if(g+1>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1];if((w&192)!=128){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&31)<<6|w&63),g+=2;continue}if(S<=239){if(g+2>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2];if(!((w&192)==128&&(E&192)==128&&!(S===224&&w<160)&&!(S===237&&w>=160))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&15)<<12|(w&63)<<6|E&63),g+=3;continue}if(g+3>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2],D=e[g+3];if(!((w&192)==128&&(E&192)==128&&(D&192)==128&&!(S===240&&w<144)&&!(S===244&&w>143))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodePoint(t,s,(S&7)<<18|(w&63)<<12|(E&63)<<6|D&63),g+=4}return flushChunk(t,s),t.join(``)}function decodeUTF16LE(e){let t=[],s=[],g=e.length,S=0;for(;S+1<g;){let w=e[S]|e[S+1]<<8;if(S+=2,w>=55296&&w<=56319){if(S+1<g){let g=e[S]|e[S+1]<<8;g>=56320&&g<=57343?(pushCodeUnit(t,s,w),pushCodeUnit(t,s,g),S+=2):pushCodeUnit(t,s,REPLACEMENT)}else pushCodeUnit(t,s,REPLACEMENT);continue}if(w>=56320&&w<=57343){pushCodeUnit(t,s,REPLACEMENT);continue}pushCodeUnit(t,s,w)}return S<g&&pushCodeUnit(t,s,REPLACEMENT),flushChunk(t,s),t.join(``)}function decodeASCII(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t]&127;t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeLatin1(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t];t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeWindows1252(e){let t=[],s=``;for(let g=0;g<e.length;g++){let S=e[g],w=S>=128&&S<=159?WINDOWS_1252_EXTRA[S]:void 0;s+=w??String.fromCharCode(S),s.length>=CHUNK&&(t.push(s),s=``)}return s&&t.push(s),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,s){return dv(e).setUint8(t,s),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,s){return dv(e).setUint16(t,s,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,s){return dv(e).setUint16(t,s),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,s){return dv(e).setUint32(t,s,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,s){return dv(e).setUint32(t,s),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,s){return dv(e).setInt32(t,s),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,s){return dv(e).setBigUint64(t,s,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let s=await this.read(e,t);return this.peekQueue.push(e.subarray(0,s)),s}async read(e,t=!1){if(e.length===0)return 0;let s=this.readFromPeekBuffer(e);if(this.endOfStream||(s+=await this.readRemainderFromStream(e.subarray(s),t)),s===0&&!t)throw new EndOfStreamError;return s}readFromPeekBuffer(e){let t=e.length,s=0;for(;this.peekQueue.length>0&&t>0;){let g=this.peekQueue.pop();if(!g)throw Error(`peekData should be defined`);let S=Math.min(g.length,t);e.set(g.subarray(0,S),s),s+=S,t-=S,S<g.length&&this.peekQueue.push(g.subarray(S))}return s}async readRemainderFromStream(e,t){let s=0;for(;s<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let g=await this.readFromStream(e.subarray(s),t);if(g===0)break;s+=g}if(!t&&s<e.length)throw new EndOfStreamError;return s}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let s=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return s.done&&(this.endOfStream=s.done),s.value?(e.set(s.value),s.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let s=Math.min(t.length,e.length);return e.set(t.subarray(0,s)),s<t.length?this.buffer=t.subarray(s):this.buffer=null,s}async readFromStream(e,t){if(e.length===0)return 0;let s=0;for(this.buffer&&(s+=this.writeChunk(e,this.buffer));s<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(s+=this.writeChunk(e.subarray(s),t.value))}if(!t&&s===0&&this.endOfStream)throw new EndOfStreamError;return s}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.readBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async peekToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.peekBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let s=this.normalizeOptions(e,t),g=s.position-this.position;if(g>0)return await this.ignore(g),this.readBuffer(e,t);if(g<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(s.length===0)return 0;let S=await this.streamReader.read(e.subarray(0,s.length),s.mayBeLess);if(this.position+=S,(!t||!t.mayBeLess)&&S<s.length)throw new EndOfStreamError;return S}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=0;if(s.position){let t=s.position-this.position;if(t>0){let S=new Uint8Array(s.length+t);return g=await this.peekBuffer(S,{mayBeLess:s.mayBeLess}),e.set(S.subarray(t)),g-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(s.length>0){try{g=await this.streamReader.peek(e.subarray(0,s.length),s.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError}return g}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),s=new Uint8Array(t),g=0;for(;g<e;){let S=e-g,w=await this.readBuffer(s,{length:Math.min(t,S)});if(w<0)return w;g+=w}return g}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.uint8Array.length-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(s.position,s.position+g)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.blob.size-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;let S=await this.blob.slice(s.position,s.position+g).arrayBuffer();return e.set(new Uint8Array(S)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let s=makeWebStreamReader(e),g=t??{},S=g.onClose;return g.onClose=async()=>{if(await s.close(),S)return S()},new ReadStreamTokenizer(s,g)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$8=__toESM$2(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$8.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),s=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(s,{position:e.fileInfo.size-t});for(let g=s.length-4;g>=0;g--)if(s[g]===eocdSignatureBytes[0]&&s[g+1]===eocdSignatureBytes[1]&&s[g+2]===eocdSignatureBytes[2]&&s[g+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+g;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let s=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),g=[];this.tokenizer.setPosition(s.offsetOfStartOfCd);for(let e=0;e<s.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),g.push(t),debug(`Add central-directory file-entry: n=${e+1}/${g.length}: filename=${g[e].filename}`)}return this.tokenizer.setPosition(e),g}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let s=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let g=e(t);s=!!g.stop;let S;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],s=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let S=-1;for(;S<0&&s===syncBufferSize;){s=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),S=indexOf(this.syncBuffer.subarray(0,s),ddSignatureArray);let t=S>=0?S:s;if(g.handler){let s=new Uint8Array(t);await this.tokenizer.readBuffer(s),e.push(s)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),g.handler&&await this.inflate(t,mergeArrays(e),g.handler)}else g.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),S=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(S),await this.inflate(t,S,g.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!s)}async iterateOverCentralDirectory(e,t){for(let s of e){let e=t(s);if(e.handler){this.tokenizer.setPosition(s.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let g=new Uint8Array(s.compressedSize);await this.tokenizer.readBuffer(g),await this.inflate(t,g,e.handler)}}if(e.stop)break}}async inflate(t,s,g){if(t.compressedMethod===0)return g(s);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${s.length}`),g(await e.decompressDeflateRaw(s))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),s=new DecompressionStream(`deflate-raw`),g=t.pipeThrough(s);try{let e=await new Response(g).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let s=e.length,g=t.length;if(g>s)return-1;for(let S=0;S<=s-g;S++){let s=!0;for(let w=0;w<g;w++)if(e[S+w]!==t[w]){s=!1;break}if(s)return S}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let s=new Uint8Array(1024),g=await e.readBuffer(s,{mayBeLess:!0});if(g===0){t.close();return}t.enqueue(s.subarray(0,g))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,s){return e?e.constructor===t?!0:objectToString.call(e)===s:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let s=new Uint8Array(t),g=0;for(let t of e)assertUint8Array(t),s.set(t,g),g+=t.length;return s}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g&255,g>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g>>8&255,g&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let s=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(s))return!1;let g=256;for(let s=t;s<t+148;s++)g+=e[s];for(let s=t+156;s<t+512;s++)g+=e[s];return s===g}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,s){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${s} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:s=maximumUntrustedSkipSizeInBytes,reason:g=`skip`}={}){let S=getSafeBound(t,s,g);await e.ignore(S)}async function safeReadBuffer(e,t,s,{maximumLength:g=t.length,reason:S=`read`}={}){let w=getSafeBound(s?.length??t.length,g,S);return e.readBuffer(t,{...s,length:w})}function checkBytes(e,t,s){s={offset:0,...s};for(let[g,S]of t.entries())if(s.mask){if(S!==(s.mask[g]&e[g+s.offset]))return!1}else if(S!==e[g+s.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,s){return hasUnknownFileSize(e)&&e.position-t>s}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),g=[],S=0;try{for(;;){let{done:e,value:w}=await s.read();if(e)break;if(S+=w.length,S>t)throw await s.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);g.push(w)}}finally{s.releaseLock()}let w=new Uint8Array(S),E=0;for(let e of g)w.set(e,E),E+=e.length;return w}function mergeByteChunks(e,t){let s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,s=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(s,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let s=[e.compressedSize,e.uncompressedSize];for(let e of s)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let s=e.slice(0,t),g=s.lastIndexOf(`"`);return s.slice(g+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let s=e.length-zipDataDescriptorLengthInBytes;for(let g=0;g<=s;g++)if(UINT32_LE.get(e,g)===zipDataDescriptorSignature&&UINT32_LE.get(e,g+8)===t+g)return g;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:s=maximumZipEntrySizeInBytes}={}){let{syncBuffer:g}=e,{length:S}=g,w=[],E=0;for(;;){let D=await e.tokenizer.peekBuffer(g,{mayBeLess:!0}),O=findZipDataDescriptorOffset(g.subarray(0,D),E),k=O>=0?0:D===S?Math.min(zipDataDescriptorOverlapLengthInBytes,D-1):0,j=O>=0?O:D-k;if(j===0)break;if(E+=j,E>s)throw Error(`ZIP entry compressed data exceeds ${s} bytes`);if(t){let t=new Uint8Array(j);await e.tokenizer.readBuffer(t),w.push(t)}else await e.tokenizer.ignore(j);if(O>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=E),t)return mergeByteChunks(w,E)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:s,maximumDescriptorLength:g=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:s,maximumLength:g});if(!s){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let S=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);let w=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(w),w}ZipHandler.prototype.inflate=async function(e,t,s){if(e.compressedMethod===0)return s(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return s(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,s=0,g=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let S=await this.readLocalFileHeader();if(!S)break;if(s++,s>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let w=e(S);t=!!w.stop,await this.tokenizer.ignore(S.extraFieldLength);let E=await readZipEntryData(this,S,{shouldBuffer:!!w.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,g))});if(w.handler&&await this.inflate(S,E,w.handler),S.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,s=createOpenXmlZipDetectionState(),g=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(s,e.filename),updateIWorkZipDetectionStateFromFilename(g,e.filename),g.hasDocumentEntry&&(g.hasMasterSlideEntry||g.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(g),{stop:!0};let S=e.filename===`[Content_Types].xml`,w=getOpenXmlFileTypeFromZipEntries(s);if(!S&&w)return t=w,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return s.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(s.isParsingContentTypes=!0,{async handler(e){let g=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));g&&(t=getFileTypeFromMimeType(g)),s.hasParsedContentTypesEntry=!0,s.isParsingContentTypes=!1},stop:!0}):(s.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;s.isParsingContentTypes&&(s.isParsingContentTypes=!1,s.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!s.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(s))}let S=hasUnknownFileSize(e)&&g.hasDocumentEntry&&!g.hasMasterSlideEntry&&!g.hasTablesEntry&&!g.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(g);return t??getOpenXmlFileTypeFromZipEntries(s)??S??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),s=128,g=0;for(;(t&s)===0&&s!==0;)++g,s>>=1;let S=new Uint8Array(g+1);return await safeReadBuffer(e,S,void 0,{maximumLength:S.length,reason:`EBML field`}),S}async function s(){let e=await t(),s=await t();s[0]^=128>>s.length-1;let g=Math.min(6,s.length),S=new DataView(e.buffer),w=new DataView(s.buffer,s.length-g,g);return{id:getUintBE(S),len:getUintBE(w)}}async function g(t){let g=0;for(;t>0;){if(g++,g>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,w,16777216))return;let S=e.position,E=await s();if(E.id===17026){if(E.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(E.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(E.len)||E.len<0||E.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,E.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=S))return}}let S=await s(),w=e.position;switch(await g(S.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},s={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function g(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let S=hasUnknownFileSize(e),w=e.position,E=0,D=!1;do{if(E++,E>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,w,maximumPngStreamScanBudgetInBytes))break;let O=e.position,k=await g();if(k.length<0)return;if(k.type===`IHDR`){if(k.length!==13)return;D=!0}switch(k.type){case`IDAT`:return t;case`acTL`:return s;default:if(!D&&k.type!==`CgBI`)return;if(S&&k.length>maximumPngChunkSizeInBytes)return D&&isPngAncillaryChunk(k.type)?t:void 0;try{await safeIgnore(e,k.length+4,{maximumLength:S?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!S&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=O)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function s(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let g=hasUnknownFileSize(e),S=e.position,w=0;for(;e.position+24<e.fileInfo.size&&(w++,!(w>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,S,16777216)));){let S=e.position,w=await s(),E=w.size-24;if(!Number.isFinite(E)||E<0){t=!0;break}if(checkBytes(w.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(E-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(g&&E>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,E,{maximumLength:g?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=S){t=!0;break}}}catch(s){if(s instanceof EndOfStreamError||s instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw s}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((s,g)=>{t.addEventListener(`abort`,()=>{g(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let s=e.getReader(),g=0,S=!1,w=!1,E=async e=>{S||w||(w=!0,await s.cancel(e))};return new ReadableStream({async pull(e){if(g>=t){e.close(),await E();return}let{done:w,value:D}=await s.read();if(w||!D){S=!0,e.close();return}let O=t-g;if(D.length>O){e.enqueue(D.subarray(0,O)),g+=O,e.close(),await E();return}e.enqueue(D),g+=D.length},async cancel(e){await E(e)}})}async function fileTypeFromBuffer(e,t){return new FileTypeParser(t).fromBuffer(e)}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let s=e.position;for(let t of this.detectors){let g;try{g=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(g)return g;if(s!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:s}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),g=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),S=await g.stat();if(!S.isFile()){await g.close();return}let w=new s(g,{...this.getTokenizerOptions(),fileInfo:{path:e,size:S.size}});return this.fromTokenizer(w)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let s=normalizeSampleSize(t?.sampleSize??4100),g,S=!1,w=e.getReader(),E=[],D=0;try{for(;D<s;){let{value:e,done:t}=await readWithSignal(w,this.options.signal);if(t||!e){S=!0;break}E.push(e),D+=e.length}if(!S&&D===s){let{value:e,done:t}=await readWithSignal(w,this.options.signal);t||!e?S=!0:(E.push(e),D+=e.length)}}finally{w.releaseLock()}if(D>0){let e=E.length===1?E[0]:concatUint8Arrays(E);try{g=await this.fromBuffer(e.subarray(0,s))}catch(e){if(!(e instanceof EndOfStreamError))throw e;g=void 0}!S&&g?.ext===`pages`&&(g={ext:`zip`,mime:`application/zip`})}let O=new TransformStream({start(e){for(let t of E)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),k=e.pipeThrough(O);return k.fileType=g,k}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let s=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),g=hasUnknownFileSize(t),S,w,E,D;if(g){let t=new AbortController;S=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),w=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),E=new e({...this.options,signal:w}),E.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{D=await(E??this).fromStream(s)}catch(e){if(e?.name===`AbortError`&&w?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(S),g||this.gzipProbeDepth--}return D?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),s=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||s&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return s?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:s?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
39
39
  `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return detectPng(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new StringType(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
40
40
  `))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return detectAsf(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new StringType(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&tarHeaderChecksumMatches(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
41
- `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);async function fileTypeFromFile(e,t){return new FileTypeParser(t).fromFile(e)}var util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\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])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
41
+ `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);var util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\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])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
42
42
  ]))`;continue}else if(g[e]===`$`){S+=`($|(?=[\r
43
43
  ]))`;continue}}if(s.s&&g[e]===`.`){S+=E?`${g[e]}\r\n`:`[${g[e]}\r\n]`;continue}S+=g[e],g[e]===`\\`?w=!0:E&&g[e]===`]`?E=!1:!E&&g[e]===`[`&&(E=!0)}try{new RegExp(S)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return S}function parseRecordDef(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((s,g)=>({...s,[g]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,g]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let s={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return s;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:g,...S}=parseStringDef(e.keyType._def,t);return{...s,propertyNames:S}}else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...s,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:g,...S}=parseBrandedDef(e.keyType._def,t);return{...s,propertyNames:S}}return s}function parseMapDef(e,t){return t.mapStrategy===`record`?parseRecordDef(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||parseAnyDef(t),parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||parseAnyDef(t)],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){let t=e.values,s=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),g=Array.from(new Set(s.map(e=>typeof e)));return{type:g.length===1?g[0]===`string`?`string`:`number`:[`string`,`number`],enum:s}}function parseNeverDef(e){return e.target===`openAi`?void 0:{not:parseAnyDef({...e,currentPath:[...e.currentPath,`not`]})}}function parseNullDef(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const primitiveMappings={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let s=primitiveMappings[t._def.typeName];return s&&!e.includes(s)?[...e,s]:e},[]);return{type:e.length>1?e:e[0]}}else if(s.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=s.reduce((e,t)=>{let s=typeof t._def.value;switch(s){case`string`:case`number`:case`boolean`:return[...e,s];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,s)=>s.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let s=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${s}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return s.length?{anyOf:s}:void 0};function parseNullableDef(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return s&&`$ref`in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return s&&{anyOf:[s,{type:`null`}]}}function parseNumberDef(e,t){let s={type:`number`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`int`:s.type=`integer`,addErrorMessage(s,`type`,g.message,t);break;case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseObjectDef(e,t){let s=t.target===`openAi`,g={type:`object`,properties:{}},S=[],w=e.shape();for(let e in w){let E=w[e];if(E===void 0||E._def===void 0)continue;let D=safeIsOptional(E);D&&s&&(E._def.typeName===`ZodOptional`&&(E=E._def.innerType),E.isNullable()||(E=E.nullable()),D=!1);let O=parseDef(E._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});O!==void 0&&(g.properties[e]=O,D||S.push(e))}S.length&&(g.required=S);let E=decideAdditionalProperties(e,t);return E!==void 0&&(g.additionalProperties=E),g}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!==`ZodNever`)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return s?{anyOf:[{not:parseAnyDef(t)},s]}:parseAnyDef(t)},parsePipelineDef=(e,t)=>{if(t.pipeStrategy===`input`)return parseDef(e.in._def,t);if(t.pipeStrategy===`output`)return parseDef(e.out._def,t);let s=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[s,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,s?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let s={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(s,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(s,`maxItems`,e.maxSize.value,e.maxSize.message,t),s}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function parseUndefinedDef(e){return{not:parseAnyDef(e)}}function parseUnknownDef(e){return parseAnyDef(e)}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,s)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,s);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,s);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,s);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,s);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,s);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(s);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(s);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,s);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,s);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,s);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,s);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,s);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,s);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,s);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,s);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,s);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,s);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,s);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(s);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,s);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(s);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(s);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,s);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,s);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,s);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,s);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,s);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,s=!1){let g=t.seen.get(e);if(t.override){let S=t.override?.(e,t,g,s);if(S!==ignoreOverride)return S}if(g&&!s){let e=get$ref(g,t);if(e!==void 0)return e}let S={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,S);let w=selectParser(e,e.typeName,t),E=typeof w==`function`?parseDef(w(),t):w;if(E&&addMeta(e,t,E),t.postProcess){let s=t.postProcess(E,e,t);return S.jsonSchema=E,s}return S.jsonSchema=E,E}const get$ref=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:getRelativePath(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,s)=>t.currentPath[s]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),parseAnyDef(t)):t.$refStrategy===`seen`?parseAnyDef(t):void 0}},addMeta=(e,t,s)=>(e.description&&(s.description=e.description,t.markdownDescription&&(s.markdownDescription=e.description)),s),zodToJsonSchema=(e,t)=>{let s=getRefs(t),g=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,g])=>({...e,[t]:parseDef(g._def,{...s,currentPath:[...s.basePath,s.definitionPath,t]},!0)??parseAnyDef(s)}),{}):void 0,S=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,w=parseDef(e._def,S===void 0?s:{...s,currentPath:[...s.basePath,s.definitionPath,S]},!1)??parseAnyDef(s),E=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;E!==void 0&&(w.title=E),s.flags.hasReferencedOpenAiAnyType&&(g||={},g[s.openAiAnyTypeName]||(g[s.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:s.$refStrategy===`relative`?`1`:[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join(`/`)}}));let D=S===void 0?g?{...w,[s.definitionPath]:g}:w:{$ref:[...s.$refStrategy===`relative`?[]:s.basePath,s.definitionPath,S].join(`/`),[s.definitionPath]:{...g,[S]:w}};return s.target===`jsonSchema7`?D.$schema=`http://json-schema.org/draft-07/schema#`:(s.target===`jsonSchema2019-09`||s.target===`openAi`)&&(D.$schema=`https://json-schema.org/draft/2019-09/schema#`),s.target===`openAi`&&(`anyOf`in D||`oneOf`in D||`allOf`in D||`type`in D&&Array.isArray(D.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),D};function mapMiniTarget(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function toJsonSchemaCompat(e,t){return isZ4Schema(e)?toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??`input`}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function getMethodLiteral(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s!=`string`)throw Error(`Schema method literal must be a string`);return s}function parseWithCompat(e,t){let s=safeParse(e,t);if(!s.success)throw s.error;return s.data}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,e=>{this._oncancel(e)}),this.setNotificationHandler(ProgressNotificationSchema,e=>{this._onprogress(e)}),this.setRequestHandler(PingRequestSchema,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(e,t)=>{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return{...s}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(e,t)=>{let s=async()=>{let g=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(g,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,s=t.id,g=this._requestResolvers.get(s);if(g)if(this._requestResolvers.delete(s),e.type===`response`)g(t);else{let e=t;g(new McpError(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${s}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let S=await this._taskStore.getTask(g,t.sessionId);if(!S)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${g}`);if(!isTerminal(S.status))return await this._waitForTaskUpdate(g,t.signal),await s();if(isTerminal(S.status)){let e=await this._taskStore.getTaskResult(g,t.sessionId);return this._clearTaskQueue(g),{...e,_meta:{...e._meta,[RELATED_TASK_META_KEY]:{taskId:g}}}}return await s()};return await s()}),this.setRequestHandler(ListTasksRequestSchema,async(e,t)=>{try{let{tasks:s,nextCursor:g}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:s,nextCursor:g,_meta:{}}}catch(e){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(e,t)=>{try{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(s.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let g=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!g)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...g}}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,s,g,S=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(g,t),startTime:Date.now(),timeout:t,maxTotalTimeout:s,resetTimeoutOnProgress:S,onTimeout:g})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let s=Date.now()-t.startTime;if(t.maxTotalTimeout&&s>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),McpError.fromError(ErrorCode.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:s});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let s=this.transport?.onerror;this._transport.onerror=e=>{s?.(e),this._onerror(e)};let g=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{g?.(e,t),isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=McpError.fromError(ErrorCode.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let s of e.values())s(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,g=this._transport,S=e.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(s===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:ErrorCode.MethodNotFound,message:`Method not found`}};S&&this._taskMessageQueue?this._enqueueTaskMessage(S,{type:`error`,message:t,timestamp:Date.now()},g?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):g?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let w=new AbortController;this._requestHandlerAbortControllers.set(e.id,w);let E=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,D=this._taskStore?this.requestTaskStore(e,g?.sessionId):void 0,O={signal:w.signal,sessionId:g?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(w.signal.aborted)return;let s={relatedRequestId:e.id};S&&(s.relatedTask={taskId:S}),await this.notification(t,s)},sendRequest:async(t,s,g)=>{if(w.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,`Request was cancelled`);let E={...g,relatedRequestId:e.id};S&&!E.relatedTask&&(E.relatedTask={taskId:S});let O=E.relatedTask?.taskId??S;return O&&D&&await D.updateTaskStatus(O,`input_required`),await this.request(t,s,E)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:S,taskStore:D,taskRequestedTtl:E?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{E&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,O)).then(async t=>{if(w.signal.aborted)return;let s={result:t,jsonrpc:`2.0`,id:e.id};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`response`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)},async t=>{if(w.signal.aborted)return;let s={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`error`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===w&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...s}=e.params,g=Number(t),S=this._progressHandlers.get(g);if(!S){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let w=this._responseHandlers.get(g),E=this._timeoutInfo.get(g);if(E&&w&&E.resetTimeoutOnProgress)try{this._resetTimeout(g)}catch(e){this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),w(e);return}S(s)}_onresponse(e){let t=Number(e.id),s=this._requestResolvers.get(t);if(s){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?s(e):s(new McpError(e.error.code,e.error.message,e.error.data));return}let g=this._responseHandlers.get(t);if(g===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let S=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let s=e.result;if(s.task&&typeof s.task==`object`){let e=s.task;typeof e.taskId==`string`&&(S=!0,this._taskProgressTokens.set(e.taskId,t))}}S||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?g(e):g(McpError.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,s){let{task:g}=s??{};if(!g){try{yield{type:`result`,result:await this.request(e,t,s)}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}return}let S;try{let g=await this.request(e,CreateTaskResultSchema,s);if(g.task)S=g.task.taskId,yield{type:`taskCreated`,task:g.task};else throw new McpError(ErrorCode.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:S},s);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)}:e.status===`failed`?yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)};return}let g=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,g)),s?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}}request(e,t,s){let{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w,task:E,relatedTask:D}=s??{};return new Promise((O,k)=>{let j=e=>{k(e)};if(!this._transport){j(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),E&&this.assertTaskCapability(e.method)}catch(e){j(e);return}s?.signal?.throwIfAborted();let F=this._requestMessageId++,L={...e,jsonrpc:`2.0`,id:F};s?.onprogress&&(this._progressHandlers.set(F,s.onprogress),L.params={...e.params,_meta:{...e.params?._meta||{},progressToken:F}}),E&&(L.params={...L.params,task:E}),D&&(L.params={...L.params,_meta:{...L.params?._meta||{},[RELATED_TASK_META_KEY]:D}});let B=e=>{this._responseHandlers.delete(F),this._progressHandlers.delete(F),this._cleanupTimeout(F),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:F,reason:String(e)}},{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),k(e instanceof McpError?e:new McpError(ErrorCode.RequestTimeout,String(e)))};this._responseHandlers.set(F,e=>{if(!s?.signal?.aborted){if(e instanceof Error)return k(e);try{let s=safeParse(t,e.result);s.success?O(s.data):k(s.error)}catch(e){k(e)}}}),s?.signal?.addEventListener(`abort`,()=>{B(s?.signal?.reason)});let H=s?.timeout??6e4;this._setupTimeout(F,H,s?.maxTotalTimeout,()=>B(McpError.fromError(ErrorCode.RequestTimeout,`Request timed out`,{timeout:H})),s?.resetTimeoutOnProgress??!1);let q=D?.taskId;q?(this._requestResolvers.set(F,e=>{let t=this._responseHandlers.get(F);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${F}`))}),this._enqueueTaskMessage(q,{type:`request`,message:L,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(F),k(e)})):this._transport.send(L,{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>{this._cleanupTimeout(F),k(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},GetTaskResultSchema,t)}async getTaskResult(e,t,s){return this.request({method:`tasks/result`,params:e},t,s)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ListTasksResultSchema,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},CancelTaskResultSchema,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let s=t?.relatedTask?.taskId;if(s){let g={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}};await this._enqueueTaskMessage(s,{type:`notification`,message:g,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:`2.0`};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),this._transport?.send(s,t).catch(e=>this._onerror(e))});return}let g={...e,jsonrpc:`2.0`};t?.relatedTask&&(g={...g,params:{...g.params,_meta:{...g.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),await this._transport.send(g,t)}setRequestHandler(e,t){let s=getMethodLiteral(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(s,g)=>{let S=parseWithCompat(e,s);return Promise.resolve(t(S,g))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let s=getMethodLiteral(e);this._notificationHandlers.set(s,s=>{let g=parseWithCompat(e,s);return Promise.resolve(t(g))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,s){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let g=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,s,g)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let s=await this._taskMessageQueue.dequeueAll(e,t);for(let t of s)if(t.type===`request`&&isJSONRPCRequest(t.message)){let s=t.message.id,g=this._requestResolvers.get(s);g?(g(new McpError(ErrorCode.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(s)):this._onerror(Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let s=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(s=t.pollInterval)}catch{}return new Promise((e,g)=>{if(t.aborted){g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`));return}let S=setTimeout(e,s);t.addEventListener(`abort`,()=>{clearTimeout(S),g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let s=this._taskStore;if(!s)throw Error(`No task store configured`);return{createTask:async g=>{if(!e)throw Error(`No request provided`);return await s.createTask(g,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let g=await s.getTask(e,t);if(!g)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return g},storeTaskResult:async(e,g,S)=>{await s.storeTaskResult(e,g,S,t);let w=await s.getTask(e,t);if(w){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:w});await this.notification(t),isTerminal(w.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>s.getTaskResult(e,t),updateTaskStatus:async(e,g,S)=>{let w=await s.getTask(e,t);if(!w)throw new McpError(ErrorCode.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(w.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${e}" from terminal status "${w.status}" to "${g}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(e,g,S,t);let E=await s.getTask(e,t);if(E){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:E});await this.notification(t),isTerminal(E.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>s.listTasks(e,t)}}};function isPlainObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let s={...e};for(let e in t){let g=e,S=t[g];if(S===void 0)continue;let w=s[g];isPlainObject$1(w)&&isPlainObject$1(S)?s[g]={...w,...S}:s[g]=S}return s}var require_code$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var s=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=s;var g=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){var e;return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){var e;return this._names??=this._items.reduce((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=g,e.nil=new g(``);function S(e,...t){let s=[e[0]],S=0;for(;S<t.length;)D(s,t[S]),s.push(e[++S]);return new g(s)}e._=S;let w=new g(`+`);function E(e,...t){let s=[B(e[0])],S=0;for(;S<t.length;)s.push(w),D(s,t[S]),s.push(w,B(e[++S]));return O(s),new g(s)}e.str=E;function D(e,t){t instanceof g?e.push(...t._items):t instanceof s?e.push(t):e.push(F(t))}e.addCodeArg=D;function O(e){let t=1;for(;t<e.length-1;){if(e[t]===w){let s=k(e[t-1],e[t+1]);if(s!==void 0){e.splice(t-1,3,s);continue}e[t++]=`+`}t++}}function k(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof s||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof s))return`"${e}${t.slice(1)}`}function j(e,t){return t.emptyStr()?e:e.emptyStr()?t:E`${e}${t}`}e.strConcat=j;function F(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:B(Array.isArray(e)?e.join(`,`):e)}function L(e){return new g(B(e))}e.stringify=L;function B(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=B;function H(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new g(`.${t}`):S`[${t}]`}e.getProperty=H;function q(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new g(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=q;function ee(e){return new g(e.toString())}e.regexpCode=ee})),require_scope=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=require_code$1();var s=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},g;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(g||(e.UsedValueState=g={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var S=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,s;if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=S;var w=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:s,itemIndex:g}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(s)}[${g}]`}};e.ValueScopeName=w;let E=(0,t._)`\n`;e.ValueScope=class extends S{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?E:t.nil}}get(){return this._scope}name(e){return new w(e,this._newName(e))}value(e,t){var s;if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let g=this.toName(e),{prefix:S}=g,w=t.key??t.ref,E=this._values[S];if(E){let e=E.get(w);if(e)return e}else E=this._values[S]=new Map;E.set(w,g);let D=this._scope[S]||(this._scope[S]=[]),O=D.length;return D[O]=t.ref,g.setValue(t,{property:S,itemIndex:O}),g}getValue(e,t){let s=this._values[e];if(s)return s.get(t)}scopeRefs(e,s=this._values){return this._reduceValues(s,s=>{if(s.scopePath===void 0)throw Error(`CodeGen: name "${s}" has no value`);return(0,t._)`${e}${s.scopePath}`})}scopeCode(e=this._values,t,s){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,s)}_reduceValues(S,w,E={},D){let O=t.nil;for(let k in S){let j=S[k];if(!j)continue;let F=E[k]=E[k]||new Map;j.forEach(S=>{if(F.has(S))return;F.set(S,g.Started);let E=w(S);if(E){let s=this.opts.es5?e.varKinds.var:e.varKinds.const;O=(0,t._)`${O}${s} ${S} = ${E};${this.opts._n}`}else if(E=D?.(S))O=(0,t._)`${O}${E}${this.opts._n}`;else throw new s(S);F.set(S,g.Completed)})}return O}}})),require_codegen=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=require_code$1(),s=require_scope();var g=require_code$1();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return g._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return g.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return g.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return g.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return g.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return g.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return g.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return g.Name}});var S=require_scope();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return S.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return S.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return S.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return S.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var w=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},E=class extends w{constructor(e,t,s){super(),this.varKind=e,this.name=t,this.rhs=s}render({es5:e,_n:t}){let g=e?s.varKinds.var:this.varKind,S=this.rhs===void 0?``:` = ${this.rhs}`;return`${g} ${this.name}${S};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ge(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},D=class extends w{constructor(e,t,s){super(),this.lhs=e,this.rhs=t,this.sideEffects=s}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,s){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ge(this.rhs,e,s),this}get names(){return me(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},O=class extends D{constructor(e,t,s,g){super(e,s,g),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},k=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},j=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},F=class extends w{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},L=class extends w{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ge(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},B=class extends w{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,s)=>t+s.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let s=e[t].optimizeNodes();Array.isArray(s)?e.splice(t,1,...s):s?e[t]=s:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:s}=this,g=s.length;for(;g--;){let S=s[g];S.optimizeNames(e,t)||(_e(e,S.names),s.splice(g,1))}return s.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>fe(e,t.names),{})}},H=class extends B{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},q=class extends B{},ee=class extends H{};ee.kind=`else`;var J=class e extends H{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let s=this.else;if(s){let e=s.optimizeNodes();s=this.else=Array.isArray(e)?new ee(e):e}if(s)return t===!1?s instanceof e?s:s.nodes:this.nodes.length?this:new e(ve(t),s instanceof e?[s]:s.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){var s;if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ge(this.condition,e,t),this}get names(){let e=super.names;return me(e,this.condition),this.else&&fe(e,this.else.names),e}};J.kind=`if`;var Y=class extends H{};Y.kind=`for`;var te=class extends Y{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ge(this.iteration,e,t),this}get names(){return fe(super.names,this.iteration.names)}},ne=class extends Y{constructor(e,t,s,g){super(),this.varKind=e,this.name=t,this.from=s,this.to=g}render(e){let t=e.es5?s.varKinds.var:this.varKind,{name:g,from:S,to:w}=this;return`for(${t} ${g}=${S}; ${g}<${w}; ${g}++)`+super.render(e)}get names(){return me(me(super.names,this.from),this.to)}},ae=class extends Y{constructor(e,t,s,g){super(),this.loop=e,this.varKind=t,this.name=s,this.iterable=g}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ge(this.iterable,e,t),this}get names(){return fe(super.names,this.iterable.names)}},oe=class extends H{constructor(e,t,s){super(),this.name=e,this.args=t,this.async=s}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};oe.kind=`func`;var se=class extends B{render(e){return`return `+super.render(e)}};se.kind=`return`;var ce=class extends H{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var s,g;return super.optimizeNames(e,t),(s=this.catch)==null||s.optimizeNames(e,t),(g=this.finally)==null||g.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&fe(e,this.catch.names),this.finally&&fe(e,this.finally.names),e}},ue=class extends H{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ue.kind=`catch`;var de=class extends H{render(e){return`finally`+super.render(e)}};de.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
44
44
  `:``},this._extScope=e,this._scope=new s.Scope({parent:e}),this._nodes=[new q]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let s=this._extScope.value(e,t);return(this._values[s.prefix]||(this._values[s.prefix]=new Set)).add(s),s}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,s,g){let S=this._scope.toName(t);return s!==void 0&&g&&(this._constants[S.str]=s),this._leafNode(new E(e,S,s)),S}const(e,t,g){return this._def(s.varKinds.const,e,t,g)}let(e,t,g){return this._def(s.varKinds.let,e,t,g)}var(e,t,g){return this._def(s.varKinds.var,e,t,g)}assign(e,t,s){return this._leafNode(new D(e,t,s))}add(t,s){return this._leafNode(new O(t,e.operators.ADD,s))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new L(e)),this}object(...e){let s=[`{`];for(let[g,S]of e)s.length>1&&s.push(`,`),s.push(g),(g!==S||this.opts.es5)&&(s.push(`:`),(0,t.addCodeArg)(s,S));return s.push(`}`),new t._Code(s)}if(e,t,s){if(this._blockNode(new J(e)),t&&s)this.code(t).else().code(s).endIf();else if(t)this.code(t).endIf();else if(s)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new J(e))}else(){return this._elseNode(new ee)}endIf(){return this._endBlockNode(J,ee)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new te(e),t)}forRange(e,t,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.let){let E=this._scope.toName(e);return this._for(new ne(w,E,t,g),()=>S(E))}forOf(e,g,S,w=s.varKinds.const){let E=this._scope.toName(e);if(this.opts.es5){let e=g instanceof t.Name?g:this.var(`_arr`,g);return this.forRange(`_i`,0,(0,t._)`${e}.length`,s=>{this.var(E,(0,t._)`${e}[${s}]`),S(E)})}return this._for(new ae(`of`,w,E,g),()=>S(E))}forIn(e,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${g})`,S);let E=this._scope.toName(e);return this._for(new ae(`in`,w,E,g),()=>S(E))}endFor(){return this._endBlockNode(Y)}label(e){return this._leafNode(new k(e))}break(e){return this._leafNode(new j(e))}return(e){let t=new se;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(se)}try(e,t,s){if(!t&&!s)throw Error(`CodeGen: "try" without "catch" and "finally"`);let g=new ce;if(this._blockNode(g),this.code(e),t){let e=this.name(`e`);this._currNode=g.catch=new ue(e),t(e)}return s&&(this._currNode=g.finally=new de,this.code(s)),this._endBlockNode(ue,de)}throw(e){return this._leafNode(new F(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let s=this._nodes.length-t;if(s<0||e!==void 0&&s!==e)throw Error(`CodeGen: wrong number of nodes: ${s} vs ${e} expected`);return this._nodes.length=t,this}func(e,s=t.nil,g,S){return this._blockNode(new oe(e,s,g)),S&&this.code(S).endFunc(),this}endFunc(){return this._endBlockNode(oe)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let s=this._currNode;if(s instanceof e||t&&s instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof J))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function fe(e,t){for(let s in t)e[s]=(e[s]||0)+(t[s]||0);return e}function me(e,s){return s instanceof t._CodeOrName?fe(e,s.names):e}function ge(e,s,g){if(e instanceof t.Name)return S(e);if(!w(e))return e;return new t._Code(e._items.reduce((e,s)=>(s instanceof t.Name&&(s=S(s)),s instanceof t._Code?e.push(...s._items):e.push(s),e),[]));function S(e){let t=g[e.str];return t===void 0||s[e.str]!==1?e:(delete s[e.str],t)}function w(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&s[e.str]===1&&g[e.str]!==void 0)}}function _e(e,t){for(let s in t)e[s]=(e[s]||0)-(t[s]||0)}function ve(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${je(e)}`}e.not=ve;let ye=De(e.operators.AND);function Ce(...e){return e.reduce(ye)}e.and=Ce;let we=De(e.operators.OR);function Te(...e){return e.reduce(we)}e.or=Te;function De(e){return(s,g)=>s===t.nil?g:g===t.nil?s:(0,t._)`${je(s)} ${e} ${je(g)}`}function je(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),require_util=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=require_codegen(),s=require_code$1();function g(e){let t={};for(let s of e)t[s]=!0;return t}e.toHash=g;function S(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(w(e,t),!E(t,e.self.RULES.all))}e.alwaysValidSchema=S;function w(e,t=e.schema){let{opts:s,self:g}=e;if(!s.strictSchema||typeof t==`boolean`)return;let S=g.RULES.keywords;for(let s in t)S[s]||ae(e,`unknown keyword: "${s}"`)}e.checkUnknownRules=w;function E(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(t[s])return!0;return!1}e.schemaHasRules=E;function D(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(s!==`$ref`&&t.all[s])return!0;return!1}e.schemaHasRulesButRef=D;function O({topSchemaRef:e,schemaPath:s},g,S,w){if(!w){if(typeof g==`number`||typeof g==`boolean`)return g;if(typeof g==`string`)return(0,t._)`${g}`}return(0,t._)`${e}${s}${(0,t.getProperty)(S)}`}e.schemaRefOrVal=O;function k(e){return L(decodeURIComponent(e))}e.unescapeFragment=k;function j(e){return encodeURIComponent(F(e))}e.escapeFragment=j;function F(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=F;function L(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=L;function B(e,t){if(Array.isArray(e))for(let s of e)t(s);else t(e)}e.eachItem=B;function H({mergeNames:e,mergeToName:s,mergeValues:g,resultToName:S}){return(w,E,D,O)=>{let k=D===void 0?E:D instanceof t.Name?(E instanceof t.Name?e(w,E,D):s(w,E,D),D):E instanceof t.Name?(s(w,D,E),E):g(E,D);return O===t.Name&&!(k instanceof t.Name)?S(w,k):k}}e.mergeEvaluated={props:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>{e.if((0,t._)`${s} === true`,()=>e.assign(g,!0),()=>e.assign(g,(0,t._)`${g} || {}`).code((0,t._)`Object.assign(${g}, ${s})`))}),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>{s===!0?e.assign(g,!0):(e.assign(g,(0,t._)`${g} || {}`),ee(e,g,s))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:q}),items:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>e.assign(g,(0,t._)`${s} === true ? true : ${g} > ${s} ? ${g} : ${s}`)),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>e.assign(g,s===!0?!0:(0,t._)`${g} > ${s} ? ${g} : ${s}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function q(e,s){if(s===!0)return e.var(`props`,!0);let g=e.var(`props`,(0,t._)`{}`);return s!==void 0&&ee(e,g,s),g}e.evaluatedPropsToName=q;function ee(e,s,g){Object.keys(g).forEach(g=>e.assign((0,t._)`${s}${(0,t.getProperty)(g)}`,!0))}e.setEvaluated=ee;let J={};function Y(e,t){return e.scopeValue(`func`,{ref:t,code:J[t.code]||(J[t.code]=new s._Code(t.code))})}e.useFunc=Y;var te;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(te||(e.Type=te={}));function ne(e,s,g){if(e instanceof t.Name){let S=s===te.Num;return g?S?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:S?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return g?(0,t.getProperty)(e).toString():`/`+F(e)}e.getErrorPath=ne;function ae(e,t,s=e.opts.strictSchema){if(s){if(t=`strict mode: ${t}`,s===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=ae})),require_names=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),require_errors=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=require_codegen(),s=require_util(),g=require_names();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:s})=>s?(0,t.str)`"${e}" keyword must be ${s} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function S(s,g=e.keywordError,S,w){let{it:E}=s,{gen:D,compositeRule:j,allErrors:L}=E,B=F(s,g,S);w??(j||L)?O(D,B):k(E,(0,t._)`[${B}]`)}e.reportError=S;function w(t,s=e.keywordError,S){let{it:w}=t,{gen:E,compositeRule:D,allErrors:j}=w;O(E,F(t,s,S)),D||j||k(w,g.default.vErrors)}e.reportExtraError=w;function E(e,s){e.assign(g.default.errors,s),e.if((0,t._)`${g.default.vErrors} !== null`,()=>e.if(s,()=>e.assign((0,t._)`${g.default.vErrors}.length`,s),()=>e.assign(g.default.vErrors,null)))}e.resetErrorsCount=E;function D({gen:e,keyword:s,schemaValue:S,data:w,errsCount:E,it:D}){if(E===void 0)throw Error(`ajv implementation error`);let O=e.name(`err`);e.forRange(`i`,E,g.default.errors,E=>{e.const(O,(0,t._)`${g.default.vErrors}[${E}]`),e.if((0,t._)`${O}.instancePath === undefined`,()=>e.assign((0,t._)`${O}.instancePath`,(0,t.strConcat)(g.default.instancePath,D.errorPath))),e.assign((0,t._)`${O}.schemaPath`,(0,t.str)`${D.errSchemaPath}/${s}`),D.opts.verbose&&(e.assign((0,t._)`${O}.schema`,S),e.assign((0,t._)`${O}.data`,w))})}e.extendErrors=D;function O(e,s){let S=e.const(`err`,s);e.if((0,t._)`${g.default.vErrors} === null`,()=>e.assign(g.default.vErrors,(0,t._)`[${S}]`),(0,t._)`${g.default.vErrors}.push(${S})`),e.code((0,t._)`${g.default.errors}++`)}function k(e,s){let{gen:g,validateName:S,schemaEnv:w}=e;w.$async?g.throw((0,t._)`new ${e.ValidationError}(${s})`):(g.assign((0,t._)`${S}.errors`,s),g.return(!1))}let j={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function F(e,s,g){let{createErrors:S}=e.it;return S===!1?(0,t._)`{}`:L(e,s,g)}function L(e,t,s={}){let{gen:g,it:S}=e,w=[B(S,s),H(e,s)];return q(e,t,w),g.object(...w)}function B({errorPath:e},{instancePath:S}){let w=S?(0,t.str)`${e}${(0,s.getErrorPath)(S,s.Type.Str)}`:e;return[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,w)]}function H({keyword:e,it:{errSchemaPath:g}},{schemaPath:S,parentSchema:w}){let E=w?g:(0,t.str)`${g}/${e}`;return S&&(E=(0,t.str)`${E}${(0,s.getErrorPath)(S,s.Type.Str)}`),[j.schemaPath,E]}function q(e,{params:s,message:S},w){let{keyword:E,data:D,schemaValue:O,it:k}=e,{opts:F,propertyName:L,topSchemaRef:B,schemaPath:H}=k;w.push([j.keyword,E],[j.params,typeof s==`function`?s(e):s||(0,t._)`{}`]),F.messages&&w.push([j.message,typeof S==`function`?S(e):S]),F.verbose&&w.push([j.schema,O],[j.parentSchema,(0,t._)`${B}${H}`],[g.default.data,D]),L&&w.push([j.propertyName,L])}})),require_boolSchema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=require_errors(),s=require_codegen(),g=require_names(),S={message:`boolean schema is false`};function w(e){let{gen:t,schema:S,validateName:w}=e;S===!1?D(e,!1):typeof S==`object`&&S.$async===!0?t.return(g.default.data):(t.assign((0,s._)`${w}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=w;function E(e,t){let{gen:s,schema:g}=e;g===!1?(s.var(t,!1),D(e)):s.var(t,!0)}e.boolOrEmptySchema=E;function D(e,s){let{gen:g,data:w}=e,E={gen:g,keyword:`false schema`,data:w,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(E,S,void 0,s)}})),require_rules=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function s(e){return typeof e==`string`&&t.has(e)}e.isJSONType=s;function g(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=g})),require_applicability=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},g){let S=t.RULES.types[g];return S&&S!==!0&&s(e,S)}e.schemaHasRulesForType=t;function s(e,t){return t.rules.some(t=>g(e,t))}e.shouldUseGroup=s;function g(e,t){var s;return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=g})),require_dataType=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=require_rules(),s=require_applicability(),g=require_errors(),S=require_codegen(),w=require_util();var E;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(E||(e.DataType=E={}));function D(e){let t=O(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=D;function O(e){let s=Array.isArray(e)?e:e?[e]:[];if(s.every(t.isJSONType))return s;throw Error(`type must be JSONType or JSONType[]: `+s.join(`,`))}e.getJSONTypes=O;function k(e,t){let{gen:g,data:S,opts:w}=e,D=F(t,w.coerceTypes),O=t.length>0&&!(D.length===0&&t.length===1&&(0,s.schemaHasRulesForType)(e,t[0]));if(O){let s=q(t,S,w.strictNumbers,E.Wrong);g.if(s,()=>{D.length?L(e,t,D):J(e)})}return O}e.coerceAndCheckDataType=k;let j=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function F(e,t){return t?e.filter(e=>j.has(e)||t===`array`&&e===`array`):[]}function L(e,t,s){let{gen:g,data:w,opts:E}=e,D=g.let(`dataType`,(0,S._)`typeof ${w}`),O=g.let(`coerced`,(0,S._)`undefined`);E.coerceTypes===`array`&&g.if((0,S._)`${D} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>g.assign(w,(0,S._)`${w}[0]`).assign(D,(0,S._)`typeof ${w}`).if(q(t,w,E.strictNumbers),()=>g.assign(O,w))),g.if((0,S._)`${O} !== undefined`);for(let e of s)(j.has(e)||e===`array`&&E.coerceTypes===`array`)&&k(e);g.else(),J(e),g.endIf(),g.if((0,S._)`${O} !== undefined`,()=>{g.assign(w,O),B(e,O)});function k(e){switch(e){case`string`:g.elseIf((0,S._)`${D} == "number" || ${D} == "boolean"`).assign(O,(0,S._)`"" + ${w}`).elseIf((0,S._)`${w} === null`).assign(O,(0,S._)`""`);return;case`number`:g.elseIf((0,S._)`${D} == "boolean" || ${w} === null
@@ -47,7 +47,7 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
47
47
  || ${D} === "boolean" || ${w} === null`).assign(O,(0,S._)`[${w}]`)}}}function B({gen:e,parentData:t,parentDataProperty:s},g){e.if((0,S._)`${t} !== undefined`,()=>e.assign((0,S._)`${t}[${s}]`,g))}function H(e,t,s,g=E.Correct){let w=g===E.Correct?S.operators.EQ:S.operators.NEQ,D;switch(e){case`null`:return(0,S._)`${t} ${w} null`;case`array`:D=(0,S._)`Array.isArray(${t})`;break;case`object`:D=(0,S._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:D=O((0,S._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:D=O();break;default:return(0,S._)`typeof ${t} ${w} ${e}`}return g===E.Correct?D:(0,S.not)(D);function O(e=S.nil){return(0,S.and)((0,S._)`typeof ${t} == "number"`,e,s?(0,S._)`isFinite(${t})`:S.nil)}}e.checkDataType=H;function q(e,t,s,g){if(e.length===1)return H(e[0],t,s,g);let E,D=(0,w.toHash)(e);if(D.array&&D.object){let e=(0,S._)`typeof ${t} != "object"`;E=D.null?e:(0,S._)`!${t} || ${e}`,delete D.null,delete D.array,delete D.object}else E=S.nil;D.number&&delete D.integer;for(let e in D)E=(0,S.and)(E,H(e,t,s,g));return E}e.checkDataTypes=q;let ee={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,S._)`{type: ${e}}`:(0,S._)`{type: ${t}}`};function J(e){let t=Y(e);(0,g.reportError)(t,ee)}e.reportTypeError=J;function Y(e){let{gen:t,data:s,schema:g}=e,S=(0,w.schemaRefOrVal)(e,g,`type`);return{gen:t,keyword:`type`,data:s,schema:g.type,schemaCode:S,schemaValue:S,parentSchema:g,params:{},it:e}}})),require_defaults=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=require_codegen(),s=require_util();function g(e,t){let{properties:s,items:g}=e.schema;if(t===`object`&&s)for(let t in s)S(e,t,s[t].default);else t===`array`&&Array.isArray(g)&&g.forEach((t,s)=>S(e,s,t.default))}e.assignDefaults=g;function S(e,g,S){let{gen:w,compositeRule:E,data:D,opts:O}=e;if(S===void 0)return;let k=(0,t._)`${D}${(0,t.getProperty)(g)}`;if(E){(0,s.checkStrictMode)(e,`default is ignored for: ${k}`);return}let j=(0,t._)`${k} === undefined`;O.useDefaults===`empty`&&(j=(0,t._)`${j} || ${k} === null || ${k} === ""`),w.if(j,(0,t._)`${k} = ${(0,t.stringify)(S)}`)}})),require_code=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=require_codegen(),s=require_util(),g=require_names(),S=require_util();function w(e,s){let{gen:g,data:S,it:w}=e;g.if(F(g,S,s,w.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${s}`},!0),e.error()})}e.checkReportMissingProp=w;function E({gen:e,data:s,it:{opts:g}},S,w){return(0,t.or)(...S.map(S=>(0,t.and)(F(e,s,S,g.ownProperties),(0,t._)`${w} = ${S}`)))}e.checkMissingProp=E;function D(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=D;function O(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=O;function k(e,s,g){return(0,t._)`${O(e)}.call(${s}, ${g})`}e.isOwnProperty=k;function j(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} !== undefined`;return S?(0,t._)`${w} && ${k(e,s,g)}`:w}e.propertyInData=j;function F(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} === undefined`;return S?(0,t.or)(w,(0,t.not)(k(e,s,g))):w}e.noPropertyInData=F;function L(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=L;function B(e,t){return L(t).filter(g=>!(0,s.alwaysValidSchema)(e,t[g]))}e.schemaProperties=B;function H({schemaCode:e,data:s,it:{gen:S,topSchemaRef:w,schemaPath:E,errorPath:D},it:O},k,j,F){let L=F?(0,t._)`${e}, ${s}, ${w}${E}`:s,B=[[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,D)],[g.default.parentData,O.parentData],[g.default.parentDataProperty,O.parentDataProperty],[g.default.rootData,g.default.rootData]];O.opts.dynamicRef&&B.push([g.default.dynamicAnchors,g.default.dynamicAnchors]);let H=(0,t._)`${L}, ${S.object(...B)}`;return j===t.nil?(0,t._)`${k}(${H})`:(0,t._)`${k}.call(${j}, ${H})`}e.callValidateCode=H;let q=(0,t._)`new RegExp`;function ee({gen:e,it:{opts:s}},g){let w=s.unicodeRegExp?`u`:``,{regExp:E}=s.code,D=E(g,w);return e.scopeValue(`pattern`,{key:D.toString(),ref:D,code:(0,t._)`${E.code===`new RegExp`?q:(0,S.useFunc)(e,E)}(${g}, ${w})`})}e.usePattern=ee;function J(e){let{gen:g,data:S,keyword:w,it:E}=e,D=g.name(`valid`);if(E.allErrors){let e=g.let(`valid`,!0);return O(()=>g.assign(e,!1)),e}return g.var(D,!0),O(()=>g.break()),D;function O(E){let O=g.const(`len`,(0,t._)`${S}.length`);g.forRange(`i`,0,O,S=>{e.subschema({keyword:w,dataProp:S,dataPropType:s.Type.Num},D),g.if((0,t.not)(D),E)})}}e.validateArray=J;function Y(e){let{gen:g,schema:S,keyword:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(S.some(e=>(0,s.alwaysValidSchema)(E,e))&&!E.opts.unevaluated)return;let D=g.let(`valid`,!1),O=g.name(`_valid`);g.block(()=>S.forEach((s,S)=>{let E=e.subschema({keyword:w,schemaProp:S,compositeRule:!0},O);g.assign(D,(0,t._)`${D} || ${O}`),e.mergeValidEvaluated(E,O)||g.if((0,t.not)(D))})),e.result(D,()=>e.reset(),()=>e.error(!0))}e.validateUnion=Y})),require_keyword=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=require_codegen(),s=require_names(),g=require_code(),S=require_errors();function w(e,s){let{gen:g,keyword:S,schema:w,parentSchema:E,it:D}=e,O=s.macro.call(D.self,w,E,D),k=j(g,S,O);D.opts.validateSchema!==!1&&D.self.validateSchema(O,!0);let F=g.name(`valid`);e.subschema({schema:O,schemaPath:t.nil,errSchemaPath:`${D.errSchemaPath}/${S}`,topSchemaRef:k,compositeRule:!0},F),e.pass(F,()=>e.error(!0))}e.macroKeywordCode=w;function E(e,S){var w;let{gen:E,keyword:F,schema:L,parentSchema:B,$data:H,it:q}=e;k(q,S);let ee=j(E,F,!H&&S.compile?S.compile.call(q.self,L,B,q):S.validate),J=E.let(`valid`);e.block$data(J,Y),e.ok(S.valid??J);function Y(){if(S.errors===!1)ae(),S.modifying&&D(e),oe(()=>e.error());else{let t=S.async?te():ne();S.modifying&&D(e),oe(()=>O(e,t))}}function te(){let e=E.let(`ruleErrs`,null);return E.try(()=>ae((0,t._)`await `),s=>E.assign(J,!1).if((0,t._)`${s} instanceof ${q.ValidationError}`,()=>E.assign(e,(0,t._)`${s}.errors`),()=>E.throw(s))),e}function ne(){let e=(0,t._)`${ee}.errors`;return E.assign(e,null),ae(t.nil),e}function ae(w=S.async?(0,t._)`await `:t.nil){let D=q.opts.passContext?s.default.this:s.default.self,O=!(`compile`in S&&!H||S.schema===!1);E.assign(J,(0,t._)`${w}${(0,g.callValidateCode)(e,ee,D,O)}`,S.modifying)}function oe(e){var s;E.if((0,t.not)(S.valid??J),e)}}e.funcKeywordCode=E;function D(e){let{gen:s,data:g,it:S}=e;s.if(S.parentData,()=>s.assign(g,(0,t._)`${S.parentData}[${S.parentDataProperty}]`))}function O(e,g){let{gen:w}=e;w.if((0,t._)`Array.isArray(${g})`,()=>{w.assign(s.default.vErrors,(0,t._)`${s.default.vErrors} === null ? ${g} : ${s.default.vErrors}.concat(${g})`).assign(s.default.errors,(0,t._)`${s.default.vErrors}.length`),(0,S.extendErrors)(e)},()=>e.error())}function k({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function j(e,s,g){if(g===void 0)throw Error(`keyword "${s}" failed to compile`);return e.scopeValue(`keyword`,typeof g==`function`?{ref:g}:{ref:g,code:(0,t.stringify)(g)})}function F(e,t,s=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||s&&e===void 0)}e.validSchemaType=F;function L({schema:e,opts:t,self:s,errSchemaPath:g},S,w){if(Array.isArray(S.keyword)?!S.keyword.includes(w):S.keyword!==w)throw Error(`ajv implementation error`);let E=S.dependencies;if(E?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${w}: ${E.join(`,`)}`);if(S.validateSchema&&!S.validateSchema(e[w])){let e=`keyword "${w}" value is invalid at path "${g}": `+s.errorsText(S.validateSchema.errors);if(t.validateSchema===`log`)s.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=L})),require_subschema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=require_codegen(),s=require_util();function g(e,{keyword:g,schemaProp:S,schema:w,schemaPath:E,errSchemaPath:D,topSchemaRef:O}){if(g!==void 0&&w!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(g!==void 0){let w=e.schema[g];return S===void 0?{schema:w,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}`,errSchemaPath:`${e.errSchemaPath}/${g}`}:{schema:w[S],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}${(0,t.getProperty)(S)}`,errSchemaPath:`${e.errSchemaPath}/${g}/${(0,s.escapeFragment)(S)}`}}if(w!==void 0){if(E===void 0||D===void 0||O===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:w,schemaPath:E,topSchemaRef:O,errSchemaPath:D}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=g;function S(e,g,{dataProp:S,dataPropType:w,data:E,dataTypes:D,propertyName:O}){if(E!==void 0&&S!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:k}=g;if(S!==void 0){let{errorPath:E,dataPathArr:D,opts:O}=g;j(k.let(`data`,(0,t._)`${g.data}${(0,t.getProperty)(S)}`,!0)),e.errorPath=(0,t.str)`${E}${(0,s.getErrorPath)(S,w,O.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${S}`,e.dataPathArr=[...D,e.parentDataProperty]}E!==void 0&&(j(E instanceof t.Name?E:k.let(`data`,E,!0)),O!==void 0&&(e.propertyName=O)),D&&(e.dataTypes=D);function j(t){e.data=t,e.dataLevel=g.dataLevel+1,e.dataTypes=[],g.definedProperties=new Set,e.parentData=g.data,e.dataNames=[...g.dataNames,t]}}e.extendSubschemaData=S;function w(e,{jtdDiscriminator:t,jtdMetadata:s,compositeRule:g,createErrors:S,allErrors:w}){g!==void 0&&(e.compositeRule=g),S!==void 0&&(e.createErrors=S),w!==void 0&&(e.allErrors=w),e.jtdDiscriminator=t,e.jtdMetadata=s}e.extendSubschemaMode=w})),require_fast_deep_equal=__commonJSMin$2(((e,t)=>{t.exports=function e(t,s){if(t===s)return!0;if(t&&s&&typeof t==`object`&&typeof s==`object`){if(t.constructor!==s.constructor)return!1;var g,S,w;if(Array.isArray(t)){if(g=t.length,g!=s.length)return!1;for(S=g;S--!==0;)if(!e(t[S],s[S]))return!1;return!0}if(t.constructor===RegExp)return t.source===s.source&&t.flags===s.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===s.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===s.toString();if(w=Object.keys(t),g=w.length,g!==Object.keys(s).length)return!1;for(S=g;S--!==0;)if(!Object.prototype.hasOwnProperty.call(s,w[S]))return!1;for(S=g;S--!==0;){var E=w[S];if(!e(t[E],s[E]))return!1}return!0}return t!==t&&s!==s}})),require_json_schema_traverse=__commonJSMin$2(((e,t)=>{var s=t.exports=function(e,t,s){typeof t==`function`&&(s=t,t={}),s=t.cb||s;var S=typeof s==`function`?s:s.pre||function(){},w=s.post||function(){};g(t,S,w,e,``,e)};s.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},s.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},s.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},s.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function g(e,t,w,E,D,O,k,j,F,L){if(E&&typeof E==`object`&&!Array.isArray(E)){for(var B in t(E,D,O,k,j,F,L),E){var H=E[B];if(Array.isArray(H)){if(B in s.arrayKeywords)for(var q=0;q<H.length;q++)g(e,t,w,H[q],D+`/`+B+`/`+q,O,D,B,E,q)}else if(B in s.propsKeywords){if(H&&typeof H==`object`)for(var ee in H)g(e,t,w,H[ee],D+`/`+B+`/`+S(ee),O,D,B,E,ee)}else (B in s.keywords||e.allKeys&&!(B in s.skipKeywords))&&g(e,t,w,H,D+`/`+B,O,D,B,E)}w(E,D,O,k,j,F,L)}}function S(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),require_resolve=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=require_util(),s=require_fast_deep_equal(),g=require_json_schema_traverse(),S=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function w(e,t=!0){return typeof e==`boolean`?!0:t===!0?!D(e):t?O(e)<=t:!1}e.inlineRef=w;let E=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function D(e){for(let t in e){if(E.has(t))return!0;let s=e[t];if(Array.isArray(s)&&s.some(D)||typeof s==`object`&&D(s))return!0}return!1}function O(e){let s=0;for(let g in e)if(g===`$ref`||(s++,!S.has(g)&&(typeof e[g]==`object`&&(0,t.eachItem)(e[g],e=>s+=O(e)),s===1/0)))return 1/0;return s}function k(e,t=``,s){return s!==!1&&(t=L(t)),j(e,e.parse(t))}e.getFullPath=k;function j(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=j;let F=/#\/?$/;function L(e){return e?e.replace(F,``):``}e.normalizeId=L;function B(e,t,s){return s=L(s),e.resolve(t,s)}e.resolveUrl=B;let H=/^[a-z_][-a-z0-9._]*$/i;function q(e,t){if(typeof e==`boolean`)return{};let{schemaId:S,uriResolver:w}=this.opts,E=L(e[S]||t),D={"":E},O=k(w,E,!1),j={},F=new Set;return g(e,{allKeys:!0},(e,t,s,g)=>{if(g===void 0)return;let w=O+t,E=D[g];typeof e[S]==`string`&&(E=k.call(this,e[S])),ee.call(this,e.$anchor),ee.call(this,e.$dynamicAnchor),D[t]=E;function k(t){let s=this.opts.uriResolver.resolve;if(t=L(E?s(E,t):t),F.has(t))throw q(t);F.add(t);let g=this.refs[t];return typeof g==`string`&&(g=this.refs[g]),typeof g==`object`?B(e,g.schema,t):t!==L(w)&&(t[0]===`#`?(B(e,j[t],t),j[t]=e):this.refs[t]=w),t}function ee(e){if(typeof e==`string`){if(!H.test(e))throw Error(`invalid anchor "${e}"`);k.call(this,`#${e}`)}}}),j;function B(e,t,g){if(t!==void 0&&!s(e,t))throw q(g)}function q(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=q})),require_validate=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=require_boolSchema(),s=require_dataType(),g=require_applicability(),S=require_dataType(),w=require_defaults(),E=require_keyword(),D=require_subschema(),O=require_codegen(),k=require_names(),j=require_resolve(),F=require_util(),L=require_errors();function B(e){if(oe(e)&&(ce(e),ae(e))){J(e);return}H(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=B;function H({gen:e,validateName:t,schema:s,schemaEnv:g,opts:S},w){S.code.es5?e.func(t,(0,O._)`${k.default.data}, ${k.default.valCxt}`,g.$async,()=>{e.code((0,O._)`"use strict"; ${te(s,S)}`),ee(e,S),e.code(w)}):e.func(t,(0,O._)`${k.default.data}, ${q(S)}`,g.$async,()=>e.code(te(s,S)).code(w))}function q(e){return(0,O._)`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${e.dynamicRef?(0,O._)`, ${k.default.dynamicAnchors}={}`:O.nil}}={}`}function ee(e,t){e.if(k.default.valCxt,()=>{e.var(k.default.instancePath,(0,O._)`${k.default.valCxt}.${k.default.instancePath}`),e.var(k.default.parentData,(0,O._)`${k.default.valCxt}.${k.default.parentData}`),e.var(k.default.parentDataProperty,(0,O._)`${k.default.valCxt}.${k.default.parentDataProperty}`),e.var(k.default.rootData,(0,O._)`${k.default.valCxt}.${k.default.rootData}`),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{e.var(k.default.instancePath,(0,O._)`""`),e.var(k.default.parentData,(0,O._)`undefined`),e.var(k.default.parentDataProperty,(0,O._)`undefined`),e.var(k.default.rootData,k.default.data),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`{}`)})}function J(e){let{schema:t,opts:s,gen:g}=e;H(e,()=>{s.$comment&&t.$comment&&_e(e),fe(e),g.let(k.default.vErrors,null),g.let(k.default.errors,0),s.unevaluated&&Y(e),ue(e),ve(e)})}function Y(e){let{gen:t,validateName:s}=e;e.evaluated=t.const(`evaluated`,(0,O._)`${s}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}function te(e,t){let s=typeof e==`object`&&e[t.schemaId];return s&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${s} */`:O.nil}function ne(e,s){if(oe(e)&&(ce(e),ae(e))){se(e,s);return}(0,t.boolOrEmptySchema)(e,s)}function ae({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let s in e)if(t.RULES.all[s])return!0;return!1}function oe(e){return typeof e.schema!=`boolean`}function se(e,t){let{schema:s,gen:g,opts:S}=e;S.$comment&&s.$comment&&_e(e),me(e),ge(e);let w=g.const(`_errs`,k.default.errors);ue(e,w),g.var(t,(0,O._)`${w} === ${k.default.errors}`)}function ce(e){(0,F.checkUnknownRules)(e),de(e)}function ue(e,t){if(e.opts.jtd)return Ce(e,[],!1,t);let g=(0,s.getSchemaTypes)(e.schema);Ce(e,g,!(0,s.coerceAndCheckDataType)(e,g),t)}function de(e){let{schema:t,errSchemaPath:s,opts:g,self:S}=e;t.$ref&&g.ignoreKeywordsWithRef&&(0,F.schemaHasRulesButRef)(t,S.RULES)&&S.logger.warn(`$ref: keywords ignored in schema at path "${s}"`)}function fe(e){let{schema:t,opts:s}=e;t.default!==void 0&&s.useDefaults&&s.strictSchema&&(0,F.checkStrictMode)(e,`default is ignored in the schema root`)}function me(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,j.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ge(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function _e({gen:e,schemaEnv:t,schema:s,errSchemaPath:g,opts:S}){let w=s.$comment;if(S.$comment===!0)e.code((0,O._)`${k.default.self}.logger.log(${w})`);else if(typeof S.$comment==`function`){let s=(0,O.str)`${g}/$comment`,S=e.scopeValue(`root`,{ref:t.root});e.code((0,O._)`${k.default.self}.opts.$comment(${w}, ${s}, ${S}.schema)`)}}function ve(e){let{gen:t,schemaEnv:s,validateName:g,ValidationError:S,opts:w}=e;s.$async?t.if((0,O._)`${k.default.errors} === 0`,()=>t.return(k.default.data),()=>t.throw((0,O._)`new ${S}(${k.default.vErrors})`)):(t.assign((0,O._)`${g}.errors`,k.default.vErrors),w.unevaluated&&ye(e),t.return((0,O._)`${k.default.errors} === 0`))}function ye({gen:e,evaluated:t,props:s,items:g}){s instanceof O.Name&&e.assign((0,O._)`${t}.props`,s),g instanceof O.Name&&e.assign((0,O._)`${t}.items`,g)}function Ce(e,t,s,w){let{gen:E,schema:D,data:j,allErrors:L,opts:B,self:H}=e,{RULES:q}=H;if(D.$ref&&(B.ignoreKeywordsWithRef||!(0,F.schemaHasRulesButRef)(D,q))){E.block(()=>Ve(e,`$ref`,q.all.$ref.definition));return}B.jtd||Te(e,t),E.block(()=>{for(let e of q.rules)ee(e);ee(q.post)});function ee(F){(0,g.shouldUseGroup)(D,F)&&(F.type?(E.if((0,S.checkDataType)(F.type,j,B.strictNumbers)),we(e,F),t.length===1&&t[0]===F.type&&s&&(E.else(),(0,S.reportTypeError)(e)),E.endIf()):we(e,F),L||E.if((0,O._)`${k.default.errors} === ${w||0}`))}}function we(e,t){let{gen:s,schema:S,opts:{useDefaults:E}}=e;E&&(0,w.assignDefaults)(e,t.type),s.block(()=>{for(let s of t.rules)(0,g.shouldUseRule)(S,s)&&Ve(e,s.keyword,s.definition,t.type)})}function Te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(De(e,t),e.opts.allowUnionTypes||je(e,t),Me(e,e.dataTypes))}function De(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{Ie(e.dataTypes,t)||ze(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),Re(e,t)}}function je(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ze(e,`use allowUnionTypes to allow union type keyword`)}function Me(e,t){let s=e.self.RULES.all;for(let S in s){let w=s[S];if(typeof w==`object`&&(0,g.shouldUseRule)(e.schema,w)){let{type:s}=w.definition;s.length&&!s.some(e=>Pe(t,e))&&ze(e,`missing type "${s.join(`,`)}" for keyword "${S}"`)}}}function Pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function Ie(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function Re(e,t){let s=[];for(let g of e.dataTypes)Ie(t,g)?s.push(g):t.includes(`integer`)&&g===`number`&&s.push(`integer`);e.dataTypes=s}function ze(e,t){let s=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${s}" (strictTypes)`,(0,F.checkStrictMode)(e,t,e.opts.strictTypes)}var Be=class{constructor(e,t,s){if((0,E.validateKeywordUsage)(e,t,s),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=s,this.data=e.data,this.schema=e.schema[s],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,F.schemaRefOrVal)(e,this.schema,s,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Ge(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,E.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${s} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,k.default.errors))}result(e,t,s){this.failResult((0,O.not)(e),t,s)}failResult(e,t,s){this.gen.if(e),s?s():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,O.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,O._)`${t} !== undefined && (${(0,O.or)(this.invalid$data(),e)})`)}error(e,t,s){if(t){this.setParams(t),this._error(e,s),this.setParams({});return}this._error(e,s)}_error(e,t){(e?L.reportExtraError:L.reportError)(this,this.def.error,t)}$dataError(){(0,L.reportError)(this,this.def.$dataError||L.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,L.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,s=O.nil){this.gen.block(()=>{this.check$data(e,s),t()})}check$data(e=O.nil,t=O.nil){if(!this.$data)return;let{gen:s,schemaCode:g,schemaType:S,def:w}=this;s.if((0,O.or)((0,O._)`${g} === undefined`,t)),e!==O.nil&&s.assign(e,!0),(S.length||w.validateSchema)&&(s.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&s.assign(e,!1)),s.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:s,def:g,it:w}=this;return(0,O.or)(E(),D());function E(){if(s.length){if(!(t instanceof O.Name))throw Error(`ajv implementation error`);let e=Array.isArray(s)?s:[s];return(0,O._)`${(0,S.checkDataTypes)(e,t,w.opts.strictNumbers,S.DataType.Wrong)}`}return O.nil}function D(){if(g.validateSchema){let s=e.scopeValue(`validate$data`,{ref:g.validateSchema});return(0,O._)`!${s}(${t})`}return O.nil}}subschema(e,t){let s=(0,D.getSubschema)(this.it,e);(0,D.extendSubschemaData)(s,this.it,e),(0,D.extendSubschemaMode)(s,e);let g={...this.it,...s,items:void 0,props:void 0};return ne(g,t),g}mergeEvaluated(e,t){let{it:s,gen:g}=this;s.opts.unevaluated&&(s.props!==!0&&e.props!==void 0&&(s.props=F.mergeEvaluated.props(g,e.props,s.props,t)),s.items!==!0&&e.items!==void 0&&(s.items=F.mergeEvaluated.items(g,e.items,s.items,t)))}mergeValidEvaluated(e,t){let{it:s,gen:g}=this;if(s.opts.unevaluated&&(s.props!==!0||s.items!==!0))return g.if(t,()=>this.mergeEvaluated(e,O.Name)),!0}};e.KeywordCxt=Be;function Ve(e,t,s,g){let S=new Be(e,s,t);`code`in s?s.code(S,g):S.$data&&s.validate?(0,E.funcKeywordCode)(S,s):`macro`in s?(0,E.macroKeywordCode)(S,s):(s.compile||s.validate)&&(0,E.funcKeywordCode)(S,s)}let Ue=/^\/(?:[^~]|~0|~1)*$/,We=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ge(e,{dataLevel:t,dataNames:s,dataPathArr:g}){let S,w;if(e===``)return k.default.rootData;if(e[0]===`/`){if(!Ue.test(e))throw Error(`Invalid JSON-pointer: ${e}`);S=e,w=k.default.rootData}else{let E=We.exec(e);if(!E)throw Error(`Invalid JSON-pointer: ${e}`);let D=+E[1];if(S=E[2],S===`#`){if(D>=t)throw Error(j(`property/index`,D));return g[t-D]}if(D>t)throw Error(j(`data`,D));if(w=s[t-D],!S)return w}let E=w,D=S.split(`/`);for(let e of D)e&&(w=(0,O._)`${w}${(0,O.getProperty)((0,F.unescapeJsonPointer)(e))}`,E=(0,O._)`${E} && ${w}`);return E;function j(e,s){return`Cannot access ${e} ${s} levels up, current level is ${t}`}}e.getData=Ge})),require_validation_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),require_ref_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_resolve();e.default=class extends Error{constructor(e,s,g,S){super(S||`can't resolve reference ${g} from id ${s}`),this.missingRef=(0,t.resolveUrl)(e,s,g),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),require_compile=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=require_codegen(),s=require_validation_error(),g=require_names(),S=require_resolve(),w=require_util(),E=require_validate();var D=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let s;typeof e.schema==`object`&&(s=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,S.normalizeId)(s?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=s?.$async,this.refs={}}};e.SchemaEnv=D;function O(e){let w=F.call(this,e);if(w)return w;let D=(0,S.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:O,lines:k}=this.opts.code,{ownProperties:j}=this.opts,L=new t.CodeGen(this.scope,{es5:O,lines:k,ownProperties:j}),B;e.$async&&(B=L.scopeValue(`Error`,{ref:s.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let H=L.scopeName(`validate`);e.validateName=H;let q={gen:L,allErrors:this.opts.allErrors,data:g.default.data,parentData:g.default.parentData,parentDataProperty:g.default.parentDataProperty,dataNames:[g.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:L.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:H,ValidationError:B,schema:e.schema,schemaEnv:e,rootId:D,baseId:e.baseId||D,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},ee;try{this._compilations.add(e),(0,E.validateFunctionCode)(q),L.optimize(this.opts.code.optimize);let s=L.toString();ee=`${L.scopeRefs(g.default.scope)}return ${s}`,this.opts.code.process&&(ee=this.opts.code.process(ee,e));let S=Function(`${g.default.self}`,`${g.default.scope}`,ee)(this,this.scope.get());if(this.scope.value(H,{ref:S}),S.errors=null,S.schema=e.schema,S.schemaEnv=e,e.$async&&(S.$async=!0),this.opts.code.source===!0&&(S.source={validateName:H,validateCode:s,scopeValues:L._values}),this.opts.unevaluated){let{props:e,items:s}=q;S.evaluated={props:e instanceof t.Name?void 0:e,items:s instanceof t.Name?void 0:s,dynamicProps:e instanceof t.Name,dynamicItems:s instanceof t.Name},S.source&&(S.source.evaluated=(0,t.stringify)(S.evaluated))}return e.validate=S,e}catch(t){throw delete e.validate,delete e.validateName,ee&&this.logger.error(`Error compiling schema, function code:`,ee),t}finally{this._compilations.delete(e)}}e.compileSchema=O;function k(e,t,s){var g;s=(0,S.resolveUrl)(this.opts.uriResolver,t,s);let w=e.refs[s];if(w)return w;let E=B.call(this,e,s);if(E===void 0){let g=e.localRefs?.[s],{schemaId:S}=this.opts;g&&(E=new D({schema:g,schemaId:S,root:e,baseId:t}))}if(E!==void 0)return e.refs[s]=j.call(this,E)}e.resolveRef=k;function j(e){return(0,S.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:O.call(this,e)}function F(e){for(let t of this._compilations)if(L(t,e))return t}e.getCompilingSchema=F;function L(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function B(e,t){let s;for(;typeof(s=this.refs[t])==`string`;)t=s;return s||this.schemas[t]||H.call(this,e,t)}function H(e,t){let s=this.opts.uriResolver.parse(t),g=(0,S._getFullPath)(this.opts.uriResolver,s),w=(0,S.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&g===w)return ee.call(this,s,e);let E=(0,S.normalizeId)(g),k=this.refs[E]||this.schemas[E];if(typeof k==`string`){let t=H.call(this,e,k);return typeof t?.schema==`object`?ee.call(this,s,t):void 0}if(typeof k?.schema==`object`){if(k.validate||O.call(this,k),E===(0,S.normalizeId)(t)){let{schema:t}=k,{schemaId:s}=this.opts,g=t[s];return g&&(w=(0,S.resolveUrl)(this.opts.uriResolver,w,g)),new D({schema:t,schemaId:s,root:e,baseId:w})}return ee.call(this,s,k)}}e.resolveSchema=H;let q=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function ee(e,{baseId:t,schema:s,root:g}){var E;if(e.fragment?.[0]!==`/`)return;for(let g of e.fragment.slice(1).split(`/`)){if(typeof s==`boolean`)return;let e=s[(0,w.unescapeFragment)(g)];if(e===void 0)return;s=e;let E=typeof s==`object`&&s[this.opts.schemaId];!q.has(g)&&E&&(t=(0,S.resolveUrl)(this.opts.uriResolver,t,E))}let O;if(typeof s!=`boolean`&&s.$ref&&!(0,w.schemaHasRulesButRef)(s,this.RULES)){let e=(0,S.resolveUrl)(this.opts.uriResolver,t,s.$ref);O=H.call(this,g,e)}let{schemaId:k}=this.opts;if(O||=new D({schema:s,schemaId:k,root:g,baseId:t}),O.schema!==O.root.schema)return O}})),require_data=__commonJSMin$2(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),require_utils$1=__commonJSMin$2(((e,t)=>{let s=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),g=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function S(e){let t=``,s=0,g=0;for(g=0;g<e.length;g++)if(s=e[g].charCodeAt(0),s!==48){if(!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g];break}for(g+=1;g<e.length;g++){if(s=e[g].charCodeAt(0),!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g]}return t}let w=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function E(e){return e.length=0,!0}function D(e,t,s){if(e.length){let g=S(e);if(g!==``)t.push(g);else return s.error=!0,!1;e.length=0}return!0}function O(e){let t=0,s={error:!1,address:``,zone:``},g=[],w=[],O=!1,k=!1,j=D;for(let S=0;S<e.length;S++){let D=e[S];if(!(D===`[`||D===`]`))if(D===`:`){if(O===!0&&(k=!0),!j(w,g,s))break;if(++t>7){s.error=!0;break}S>0&&e[S-1]===`:`&&(O=!0),g.push(`:`);continue}else if(D===`%`){if(!j(w,g,s))break;j=E}else{w.push(D);continue}}return w.length&&(j===E?s.zone=w.join(``):k?g.push(w.join(``)):g.push(S(w))),s.address=g.join(``),s}function k(e){if(j(e,`:`)<2)return{host:e,isIPV6:!1};let t=O(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,s=t.address;return t.zone&&(e+=`%`+t.zone,s+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:s}}}function j(e,t){let s=0;for(let g=0;g<e.length;g++)e[g]===t&&s++;return s}function F(e){let t=e,s=[],g=-1,S=0;for(;S=t.length;){if(S===1){if(t===`.`)break;if(t===`/`){s.push(`/`);break}else{s.push(t);break}}else if(S===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){s.push(`/`);break}}else if(S===3&&t===`/..`){s.length!==0&&s.pop(),s.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),s.length!==0&&s.pop();continue}}if((g=t.indexOf(`/`,1))===-1){s.push(t);break}else s.push(t.slice(0,g)),t=t.slice(g)}return s.join(``)}function L(e,t){let s=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=s(e.scheme)),e.userinfo!==void 0&&(e.userinfo=s(e.userinfo)),e.host!==void 0&&(e.host=s(e.host)),e.path!==void 0&&(e.path=s(e.path)),e.query!==void 0&&(e.query=s(e.query)),e.fragment!==void 0&&(e.fragment=s(e.fragment)),e}function B(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let s=unescape(e.host);if(!g(s)){let t=k(s);s=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(s)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:w,recomposeAuthority:B,normalizeComponentEncoding:L,removeDotSegments:F,isIPv4:g,isUUID:s,normalizeIPv6:k,stringArrayToHexStripped:S}})),require_schemes=__commonJSMin$2(((e,t)=>{let{isUUID:s}=require_utils$1(),g=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function w(e){return S.indexOf(e)!==-1}function E(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function D(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function O(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function k(e){return e.secure=E(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function j(e){if((e.port===(E(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,s]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=s,e.resourceName=void 0}return e.fragment=void 0,e}function F(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let s=e.path.match(g);if(s){let g=t.scheme||e.scheme||`urn`;e.nid=s[1].toLowerCase(),e.nss=s[2];let S=oe(`${g}:${t.nid||e.nid}`);e.path=void 0,S&&(e=S.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function L(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let s=t.scheme||e.scheme||`urn`,g=e.nid.toLowerCase(),S=oe(`${s}:${t.nid||g}`);S&&(e=S.serialize(e,t));let w=e,E=e.nss;return w.path=`${g||t.nid}:${E}`,t.skipEscape=!0,w}function B(e,t){let g=e;return g.uuid=g.nss,g.nss=void 0,!t.tolerant&&(!g.uuid||!s(g.uuid))&&(g.error=g.error||`UUID is not valid.`),g}function H(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let q={scheme:`http`,domainHost:!0,parse:D,serialize:O},ee={scheme:`https`,domainHost:q.domainHost,parse:D,serialize:O},J={scheme:`ws`,domainHost:!0,parse:k,serialize:j},Y={scheme:`wss`,domainHost:J.domainHost,parse:J.parse,serialize:J.serialize},te={scheme:`urn`,parse:F,serialize:L,skipNormalize:!0},ne={scheme:`urn:uuid`,parse:B,serialize:H,skipNormalize:!0},ae={http:q,https:ee,ws:J,wss:Y,urn:te,"urn:uuid":ne};Object.setPrototypeOf(ae,null);function oe(e){return e&&(ae[e]||ae[e.toLowerCase()])||void 0}t.exports={wsIsSecure:E,SCHEMES:ae,isValidSchemeName:w,getSchemeHandler:oe}})),require_fast_uri=__commonJSMin$2(((e,t)=>{let{normalizeIPv6:s,removeDotSegments:g,recomposeAuthority:S,normalizeComponentEncoding:w,isIPv4:E,nonSimpleDomain:D}=require_utils$1(),{SCHEMES:O,getSchemeHandler:k}=require_schemes();function j(e,t){return typeof e==`string`?e=H(ee(e,t),t):typeof e==`object`&&(e=ee(H(e,t),t)),e}function F(e,t,s){let g=s?Object.assign({scheme:`null`},s):{scheme:`null`},S=L(ee(e,g),ee(t,g),g,!0);return g.skipEscape=!0,H(S,g)}function L(e,t,s,S){let w={};return S||(e=ee(H(e,s),s),t=ee(H(t,s),s)),s||={},!s.tolerant&&t.scheme?(w.scheme=t.scheme,w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.path?(t.path[0]===`/`?w.path=g(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?w.path=`/`+t.path:e.path?w.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:w.path=t.path,w.path=g(w.path)),w.query=t.query):(w.path=e.path,t.query===void 0?w.query=e.query:w.query=t.query),w.userinfo=e.userinfo,w.host=e.host,w.port=e.port),w.scheme=e.scheme),w.fragment=t.fragment,w}function B(e,t,s){return typeof e==`string`?(e=unescape(e),e=H(w(ee(e,s),!0),{...s,skipEscape:!0})):typeof e==`object`&&(e=H(w(e,!0),{...s,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=H(w(ee(t,s),!0),{...s,skipEscape:!0})):typeof t==`object`&&(t=H(w(t,!0),{...s,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function H(e,t){let s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},w=Object.assign({},t),E=[],D=k(w.scheme||s.scheme);D&&D.serialize&&D.serialize(s,w),s.path!==void 0&&(w.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),s.scheme!==void 0&&(s.path=s.path.split(`%3A`).join(`:`)))),w.reference!==`suffix`&&s.scheme&&E.push(s.scheme,`:`);let O=S(s);if(O!==void 0&&(w.reference!==`suffix`&&E.push(`//`),E.push(O),s.path&&s.path[0]!==`/`&&E.push(`/`)),s.path!==void 0){let e=s.path;!w.absolutePath&&(!D||!D.absolutePath)&&(e=g(e)),O===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),E.push(e)}return s.query!==void 0&&E.push(`?`,s.query),s.fragment!==void 0&&E.push(`#`,s.fragment),E.join(``)}let q=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ee(e,t){let g=Object.assign({},t),S={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},w=!1;g.reference===`suffix`&&(e=g.scheme?g.scheme+`:`+e:`//`+e);let O=e.match(q);if(O){if(S.scheme=O[1],S.userinfo=O[3],S.host=O[4],S.port=parseInt(O[5],10),S.path=O[6]||``,S.query=O[7],S.fragment=O[8],isNaN(S.port)&&(S.port=O[5]),S.host)if(E(S.host)===!1){let e=s(S.host);S.host=e.host.toLowerCase(),w=e.isIPV6}else w=!0;S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&S.query===void 0&&!S.path?S.reference=`same-document`:S.scheme===void 0?S.reference=`relative`:S.fragment===void 0?S.reference=`absolute`:S.reference=`uri`,g.reference&&g.reference!==`suffix`&&g.reference!==S.reference&&(S.error=S.error||`URI is not a `+g.reference+` reference.`);let t=k(g.scheme||S.scheme);if(!g.unicodeSupport&&(!t||!t.unicodeSupport)&&S.host&&(g.domainHost||t&&t.domainHost)&&w===!1&&D(S.host))try{S.host=URL.domainToASCII(S.host.toLowerCase())}catch(e){S.error=S.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(S.scheme!==void 0&&(S.scheme=unescape(S.scheme)),S.host!==void 0&&(S.host=unescape(S.host))),S.path&&=escape(unescape(S.path)),S.fragment&&=encodeURI(decodeURIComponent(S.fragment))),t&&t.parse&&t.parse(S,g)}else S.error=S.error||`URI can not be parsed.`;return S}let J={SCHEMES:O,normalize:j,resolve:F,resolveComponent:L,equal:B,serialize:H,parse:ee};t.exports=J,t.exports.default=J,t.exports.fastUri=J})),require_uri=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_uri();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),require_core$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var s=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return s._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return s.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return s.CodeGen}});let g=require_validation_error(),S=require_ref_error(),w=require_rules(),E=require_compile(),D=require_codegen(),O=require_resolve(),k=require_dataType(),j=require_util(),F=require_data(),L=require_uri(),B=(e,t)=>new RegExp(e,t);B.code=`new RegExp`;let H=[`removeAdditional`,`useDefaults`,`coerceTypes`],q=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),ee={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},J={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},Y=200;function te(e){var t,s,g,S,w,E,D,O,k,j,F,H,q,ee,J,Y,te,ne,ae,oe,se,ce,ue,de,fe;let me=e.strict,ge=e.code?.optimize,_e=ge===!0||ge===void 0?1:ge||0,ve=e.code?.regExp??B,ye=e.uriResolver??L.default;return{strictSchema:e.strictSchema??me??!0,strictNumbers:e.strictNumbers??me??!0,strictTypes:e.strictTypes??me??`log`,strictTuples:e.strictTuples??me??`log`,strictRequired:e.strictRequired??me??!1,code:e.code?{...e.code,optimize:_e,regExp:ve}:{optimize:_e,regExp:ve},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:ye}}var ne=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...te(e)};let{es5:t,lines:s}=this.opts.code;this.scope=new D.ValueScope({scope:{},prefixes:q,es5:t,lines:s}),this.logger=me(e.logger);let g=e.validateFormats;e.validateFormats=!1,this.RULES=(0,w.getRules)(),ae.call(this,ee,e,`NOT SUPPORTED`),ae.call(this,J,e,`DEPRECATED`,`warn`),this._metaOpts=de.call(this),e.formats&&ce.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ue.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),se.call(this),e.validateFormats=g}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:s}=this.opts,g=F;s===`id`&&(g={...F},g.id=g.$id,delete g.$id),t&&e&&this.addMetaSchema(g,g[s],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let s;if(typeof e==`string`){if(s=this.getSchema(e),!s)throw Error(`no schema with key or ref "${e}"`)}else s=this.compile(e);let g=s(t);return`$async`in s||(this.errors=s.errors),g}compile(e,t){let s=this._addSchema(e,t);return s.validate||this._compileSchemaEnv(s)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:s}=this.opts;return g.call(this,e,t);async function g(e,t){await w.call(this,e.$schema);let s=this._addSchema(e,t);return s.validate||E.call(this,s)}async function w(e){e&&!this.getSchema(e)&&await g.call(this,{$ref:e},!0)}async function E(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof S.default))throw t;return D.call(this,t),await O.call(this,t.missingSchema),E.call(this,e)}}function D({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function O(e){let s=await k.call(this,e);this.refs[e]||await w.call(this,s.$schema),this.refs[e]||this.addSchema(s,e,t)}async function k(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=s(e))}finally{delete this._loading[e]}}}addSchema(e,t,s,g=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,s,g);return this}let S;if(typeof e==`object`){let{schemaId:t}=this.opts;if(S=e[t],S!==void 0&&typeof S!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,O.normalizeId)(t||S),this._checkUnique(t),this.schemas[t]=this._addSchema(e,s,t,g,!0),this}addMetaSchema(e,t,s=this.opts.validateSchema){return this.addSchema(e,t,!0,s),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let s;if(s=e.$schema,s!==void 0&&typeof s!=`string`)throw Error(`$schema must be a string`);if(s=s||this.opts.defaultMeta||this.defaultMeta(),!s)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let g=this.validate(s,e);if(!g&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return g}getSchema(e){let t;for(;typeof(t=oe.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:s}=this.opts,g=new E.SchemaEnv({schema:{},schemaId:s});if(t=E.resolveSchema.call(this,g,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=oe.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let s=e[this.opts.schemaId];return s&&(s=(0,O.normalizeId)(s),delete this.schemas[s],delete this.refs[s]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let s;if(typeof e==`string`)s=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=s);else if(typeof e==`object`&&t===void 0){if(t=e,s=t.keyword,Array.isArray(s)&&!s.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(_e.call(this,s,t),!t)return(0,j.eachItem)(s,e=>ve.call(this,e)),this;Ce.call(this,t);let g={...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)};return(0,j.eachItem)(s,g.type.length===0?e=>ve.call(this,e,g):e=>g.type.forEach(t=>ve.call(this,e,g,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let s of t.rules){let t=s.rules.findIndex(t=>t.keyword===e);t>=0&&s.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:s=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${s}${e.instancePath} ${e.message}`).reduce((e,s)=>e+t+s)}$dataMetaSchema(e,t){let s=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let g of t){let t=g.split(`/`).slice(1),S=e;for(let e of t)S=S[e];for(let e in s){let t=s[e];if(typeof t!=`object`)continue;let{$data:g}=t.definition,w=S[e];g&&w&&(S[e]=Te(w))}}return e}_removeAllSchemas(e,t){for(let s in e){let g=e[s];(!t||t.test(s))&&(typeof g==`string`?delete e[s]:g&&!g.meta&&(this._cache.delete(g.schema),delete e[s]))}}_addSchema(e,t,s,g=this.opts.validateSchema,S=this.opts.addUsedSchema){let w,{schemaId:D}=this.opts;if(typeof e==`object`)w=e[D];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let k=this._cache.get(e);if(k!==void 0)return k;s=(0,O.normalizeId)(w||s);let j=O.getSchemaRefs.call(this,e,s);return k=new E.SchemaEnv({schema:e,schemaId:D,meta:t,baseId:s,localRefs:j}),this._cache.set(k.schema,k),S&&!s.startsWith(`#`)&&(s&&this._checkUnique(s),this.refs[s]=k),g&&this.validateSchema(e,!0),k}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):E.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{E.compileSchema.call(this,e)}finally{this.opts=t}}};ne.ValidationError=g.default,ne.MissingRefError=S.default,e.default=ne;function ae(e,t,s,g=`error`){for(let S in e){let w=S;w in t&&this.logger[g](`${s}: option ${S}. ${e[w]}`)}}function oe(e){return e=(0,O.normalizeId)(e),this.schemas[e]||this.refs[e]}function se(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ce(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ue(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let s=e[t];s.keyword||=t,this.addKeyword(s)}}function de(){let e={...this.opts};for(let t of H)delete e[t];return e}let fe={log(){},warn(){},error(){}};function me(e){if(e===!1)return fe;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ge=/^[a-z_$][a-z0-9_$:-]*$/i;function _e(e,t){let{RULES:s}=this;if((0,j.eachItem)(e,e=>{if(s.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ge.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ve(e,t,s){var g;let S=t?.post;if(s&&S)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:w}=this,E=S?w.post:w.rules.find(({type:e})=>e===s);if(E||(E={type:s,rules:[]},w.rules.push(E)),w.keywords[e]=!0,!t)return;let D={keyword:e,definition:{...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)}};t.before?ye.call(this,E,D,t.before):E.rules.push(D),w.all[e]=D,(g=t.implements)==null||g.forEach(e=>this.addKeyword(e))}function ye(e,t,s){let g=e.rules.findIndex(e=>e.keyword===s);g>=0?e.rules.splice(g,0,t):(e.rules.push(t),this.logger.warn(`rule ${s} is not defined`))}function Ce(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Te(t)),e.validateSchema=this.compile(t,!0))}let we={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function Te(e){return{anyOf:[e,we]}}})),require_id=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),require_ref=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=require_ref_error(),s=require_code(),g=require_codegen(),S=require_names(),w=require_compile(),E=require_util(),D={keyword:`$ref`,schemaType:`string`,code(e){let{gen:s,schema:S,it:E}=e,{baseId:D,schemaEnv:j,validateName:F,opts:L,self:B}=E,{root:H}=j;if((S===`#`||S===`#/`)&&D===H.baseId)return ee();let q=w.resolveRef.call(B,H,D,S);if(q===void 0)throw new t.default(E.opts.uriResolver,D,S);if(q instanceof w.SchemaEnv)return J(q);return Y(q);function ee(){if(j===H)return k(e,F,j,j.$async);let t=s.scopeValue(`root`,{ref:H});return k(e,(0,g._)`${t}.validate`,H,H.$async)}function J(t){k(e,O(e,t),t,t.$async)}function Y(t){let w=s.scopeValue(`schema`,L.code.source===!0?{ref:t,code:(0,g.stringify)(t)}:{ref:t}),E=s.name(`valid`),D=e.subschema({schema:t,dataTypes:[],schemaPath:g.nil,topSchemaRef:w,errSchemaPath:S},E);e.mergeEvaluated(D),e.ok(E)}}};function O(e,t){let{gen:s}=e;return t.validate?s.scopeValue(`validate`,{ref:t.validate}):(0,g._)`${s.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=O;function k(e,t,w,D){let{gen:O,it:k}=e,{allErrors:j,schemaEnv:F,opts:L}=k,B=L.passContext?S.default.this:g.nil;D?H():q();function H(){if(!F.$async)throw Error(`async schema referenced by sync schema`);let S=O.let(`valid`);O.try(()=>{O.code((0,g._)`await ${(0,s.callValidateCode)(e,t,B)}`),J(t),j||O.assign(S,!0)},e=>{O.if((0,g._)`!(${e} instanceof ${k.ValidationError})`,()=>O.throw(e)),ee(e),j||O.assign(S,!1)}),e.ok(S)}function q(){e.result((0,s.callValidateCode)(e,t,B),()=>J(t),()=>ee(t))}function ee(e){let t=(0,g._)`${e}.errors`;O.assign(S.default.vErrors,(0,g._)`${S.default.vErrors} === null ? ${t} : ${S.default.vErrors}.concat(${t})`),O.assign(S.default.errors,(0,g._)`${S.default.vErrors}.length`)}function J(e){var t;if(!k.opts.unevaluated)return;let s=w?.validate?.evaluated;if(k.props!==!0)if(s&&!s.dynamicProps)s.props!==void 0&&(k.props=E.mergeEvaluated.props(O,s.props,k.props));else{let t=O.var(`props`,(0,g._)`${e}.evaluated.props`);k.props=E.mergeEvaluated.props(O,t,k.props,g.Name)}if(k.items!==!0)if(s&&!s.dynamicItems)s.items!==void 0&&(k.items=E.mergeEvaluated.items(O,s.items,k.items));else{let t=O.var(`items`,(0,g._)`${e}.evaluated.items`);k.items=E.mergeEvaluated.items(O,t,k.items,g.Name)}}}e.callRef=k,e.default=D})),require_core=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_id(),s=require_ref();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,s.default]})),require_limitNumber=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=t.operators,g={maximum:{okStr:`<=`,ok:s.LTE,fail:s.GT},minimum:{okStr:`>=`,ok:s.GTE,fail:s.LT},exclusiveMaximum:{okStr:`<`,ok:s.LT,fail:s.GTE},exclusiveMinimum:{okStr:`>`,ok:s.GT,fail:s.LTE}};e.default={keyword:Object.keys(g),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:s})=>(0,t.str)`must be ${g[e].okStr} ${s}`,params:({keyword:e,schemaCode:s})=>(0,t._)`{comparison: ${g[e].okStr}, limit: ${s}}`},code(e){let{keyword:s,data:S,schemaCode:w}=e;e.fail$data((0,t._)`${S} ${g[s].fail} ${w} || isNaN(${S})`)}}})),require_multipleOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:s,data:g,schemaCode:S,it:w}=e,E=w.opts.multipleOfPrecision,D=s.let(`res`),O=E?(0,t._)`Math.abs(Math.round(${D}) - ${D}) > 1e-${E}`:(0,t._)`${D} !== parseInt(${D})`;e.fail$data((0,t._)`(${S} === 0 || (${D} = ${g}/${S}, ${O}))`)}}})),require_ucs2length=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,s=0,g=0,S;for(;g<t;)s++,S=e.charCodeAt(g++),S>=55296&&S<=56319&&g<t&&(S=e.charCodeAt(g),(S&64512)==56320&&g++);return s}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),require_limitLength=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_ucs2length();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:S,data:w,schemaCode:E,it:D}=e,O=S===`maxLength`?t.operators.GT:t.operators.LT,k=D.opts.unicode===!1?(0,t._)`${w}.length`:(0,t._)`${(0,s.useFunc)(e.gen,g.default)}(${w})`;e.fail$data((0,t._)`${k} ${O} ${E}`)}}})),require_pattern=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_util(),g=require_codegen();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,g.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,g._)`{pattern: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e,j=k.opts.unicodeRegExp?`u`:``;if(E){let{regExp:t}=k.opts.code,E=t.code===`new RegExp`?(0,g._)`new RegExp`:(0,s.useFunc)(S,t),D=S.let(`valid`);S.try(()=>S.assign(D,(0,g._)`${E}(${O}, ${j}).test(${w})`),()=>S.assign(D,!1)),e.fail$data((0,g._)`!${D}`)}else{let s=(0,t.usePattern)(e,D);e.fail$data((0,g._)`!${s}.test(${w})`)}}}})),require_limitProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${g}).length ${w} ${S}`)}}})),require_required=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,s.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,s._)`{missingProperty: ${e}}`},code(e){let{gen:S,schema:w,schemaCode:E,data:D,$data:O,it:k}=e,{opts:j}=k;if(!O&&w.length===0)return;let F=w.length>=j.loopRequired;if(k.allErrors?L():B(),j.strictRequired){let t=e.parentSchema.properties,{definedProperties:s}=e.it;for(let e of w)if(t?.[e]===void 0&&!s.has(e)){let t=`required property "${e}" is not defined at "${k.schemaEnv.baseId+k.errSchemaPath}" (strictRequired)`;(0,g.checkStrictMode)(k,t,k.opts.strictRequired)}}function L(){if(F||O)e.block$data(s.nil,H);else for(let s of w)(0,t.checkReportMissingProp)(e,s)}function B(){let s=S.let(`missing`);if(F||O){let t=S.let(`valid`,!0);e.block$data(t,()=>q(s,t)),e.ok(t)}else S.if((0,t.checkMissingProp)(e,w,s)),(0,t.reportMissingProp)(e,s),S.else()}function H(){S.forOf(`prop`,E,s=>{e.setParams({missingProperty:s}),S.if((0,t.noPropertyInData)(S,D,s,j.ownProperties),()=>e.error())})}function q(g,w){e.setParams({missingProperty:g}),S.forOf(g,E,()=>{S.assign(w,(0,t.propertyInData)(S,D,g,j.ownProperties)),S.if((0,s.not)(w),()=>{e.error(),S.break()})},s.nil)}}}})),require_limitItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${g}.length ${w} ${S}`)}}})),require_equal=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_deep_equal();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),require_uniqueItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_dataType(),s=require_codegen(),g=require_util(),S=require_equal();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,s.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,s._)`{i: ${e}, j: ${t}}`},code(e){let{gen:w,data:E,$data:D,schema:O,parentSchema:k,schemaCode:j,it:F}=e;if(!D&&!O)return;let L=w.let(`valid`),B=k.items?(0,t.getSchemaTypes)(k.items):[];e.block$data(L,H,(0,s._)`${j} === false`),e.ok(L);function H(){let t=w.let(`i`,(0,s._)`${E}.length`),g=w.let(`j`);e.setParams({i:t,j:g}),w.assign(L,!0),w.if((0,s._)`${t} > 1`,()=>(q()?ee:J)(t,g))}function q(){return B.length>0&&!B.some(e=>e===`object`||e===`array`)}function ee(g,S){let D=w.name(`item`),O=(0,t.checkDataTypes)(B,D,F.opts.strictNumbers,t.DataType.Wrong),k=w.const(`indices`,(0,s._)`{}`);w.for((0,s._)`;${g}--;`,()=>{w.let(D,(0,s._)`${E}[${g}]`),w.if(O,(0,s._)`continue`),B.length>1&&w.if((0,s._)`typeof ${D} == "string"`,(0,s._)`${D} += "_"`),w.if((0,s._)`typeof ${k}[${D}] == "number"`,()=>{w.assign(S,(0,s._)`${k}[${D}]`),e.error(),w.assign(L,!1).break()}).code((0,s._)`${k}[${D}] = ${g}`)})}function J(t,D){let O=(0,g.useFunc)(w,S.default),k=w.name(`outer`);w.label(k).for((0,s._)`;${t}--;`,()=>w.for((0,s._)`${D} = ${t}; ${D}--;`,()=>w.if((0,s._)`${O}(${E}[${t}], ${E}[${D}])`,()=>{e.error(),w.assign(L,!1).break(k)})))}}}})),require_const=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:S,data:w,$data:E,schemaCode:D,schema:O}=e;E||O&&typeof O==`object`?e.fail$data((0,t._)`!${(0,s.useFunc)(S,g.default)}(${w}, ${D})`):e.fail((0,t._)`${O} !== ${w}`)}}})),require_enum=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e;if(!E&&D.length===0)throw Error(`enum must have non-empty array`);let j=D.length>=k.opts.loopEnum,F,L=()=>F??=(0,s.useFunc)(S,g.default),B;if(j||E)B=S.let(`valid`),e.block$data(B,H);else{if(!Array.isArray(D))throw Error(`ajv implementation error`);let e=S.const(`vSchema`,O);B=(0,t.or)(...D.map((t,s)=>q(e,s)))}e.pass(B);function H(){S.assign(B,!1),S.forOf(`v`,O,e=>S.if((0,t._)`${L()}(${w}, ${e})`,()=>S.assign(B,!0).break()))}function q(e,s){let g=D[s];return typeof g==`object`&&g?(0,t._)`${L()}(${w}, ${e}[${s}])`:(0,t._)`${w} === ${g}`}}}})),require_validation$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_limitNumber(),s=require_multipleOf(),g=require_limitLength(),S=require_pattern(),w=require_limitProperties(),E=require_required(),D=require_limitItems(),O=require_uniqueItems(),k=require_const(),j=require_enum();e.default=[t.default,s.default,g.default,S.default,w.default,E.default,D.default,O.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},k.default,j.default]})),require_additionalItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=require_codegen(),s=require_util(),g={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:g}=e,{items:w}=t;if(!Array.isArray(w)){(0,s.checkStrictMode)(g,`"additionalItems" is ignored when "items" is not an array of schemas`);return}S(e,w)}};function S(e,g){let{gen:S,schema:w,data:E,keyword:D,it:O}=e;O.items=!0;let k=S.const(`len`,(0,t._)`${E}.length`);if(w===!1)e.setParams({len:g.length}),e.pass((0,t._)`${k} <= ${g.length}`);else if(typeof w==`object`&&!(0,s.alwaysValidSchema)(O,w)){let s=S.var(`valid`,(0,t._)`${k} <= ${g.length}`);S.if((0,t.not)(s),()=>j(s)),e.ok(s)}function j(w){S.forRange(`i`,g.length,k,g=>{e.subschema({keyword:D,dataProp:g,dataPropType:s.Type.Num},w),O.allErrors||S.if((0,t.not)(w),()=>S.break())})}}e.validateAdditionalItems=S,e.default=g})),require_items=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=require_codegen(),s=require_util(),g=require_code(),S={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:S}=e;if(Array.isArray(t))return w(e,`additionalItems`,t);S.items=!0,!(0,s.alwaysValidSchema)(S,t)&&e.ok((0,g.validateArray)(e))}};function w(e,g,S=e.schema){let{gen:w,parentSchema:E,data:D,keyword:O,it:k}=e;L(E),k.opts.unevaluated&&S.length&&k.items!==!0&&(k.items=s.mergeEvaluated.items(w,S.length,k.items));let j=w.name(`valid`),F=w.const(`len`,(0,t._)`${D}.length`);S.forEach((g,S)=>{(0,s.alwaysValidSchema)(k,g)||(w.if((0,t._)`${F} > ${S}`,()=>e.subschema({keyword:O,schemaProp:S,dataProp:S},j)),e.ok(j))});function L(e){let{opts:t,errSchemaPath:w}=k,E=S.length,D=E===e.minItems&&(E===e.maxItems||e[g]===!1);if(t.strictTuples&&!D){let e=`"${O}" is ${E}-tuple, but minItems or maxItems/${g} are not specified or different at path "${w}"`;(0,s.checkStrictMode)(k,e,t.strictTuples)}}}e.validateTuple=w,e.default=S})),require_prefixItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_items();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),require_items2020=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_code(),S=require_additionalItems();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:w,it:E}=e,{prefixItems:D}=w;E.items=!0,!(0,s.alwaysValidSchema)(E,t)&&(D?(0,S.validateAdditionalItems)(e,D):e.ok((0,g.validateArray)(e)))}}})),require_contains=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:s}})=>s===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${s} valid item(s)`,params:({params:{min:e,max:s}})=>s===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${s}}`},code(e){let{gen:g,schema:S,parentSchema:w,data:E,it:D}=e,O,k,{minContains:j,maxContains:F}=w;D.opts.next?(O=j===void 0?1:j,k=F):O=1;let L=g.const(`len`,(0,t._)`${E}.length`);if(e.setParams({min:O,max:k}),k===void 0&&O===0){(0,s.checkStrictMode)(D,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(k!==void 0&&O>k){(0,s.checkStrictMode)(D,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,s.alwaysValidSchema)(D,S)){let s=(0,t._)`${L} >= ${O}`;k!==void 0&&(s=(0,t._)`${s} && ${L} <= ${k}`),e.pass(s);return}D.items=!0;let B=g.name(`valid`);k===void 0&&O===1?q(B,()=>g.if(B,()=>g.break())):O===0?(g.let(B,!0),k!==void 0&&g.if((0,t._)`${E}.length > 0`,H)):(g.let(B,!1),H()),e.result(B,()=>e.reset());function H(){let e=g.name(`_valid`),t=g.let(`count`,0);q(e,()=>g.if(e,()=>ee(t)))}function q(t,S){g.forRange(`i`,0,L,g=>{e.subschema({keyword:`contains`,dataProp:g,dataPropType:s.Type.Num,compositeRule:!0},t),S()})}function ee(e){g.code((0,t._)`${e}++`),k===void 0?g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0).break()):(g.if((0,t._)`${e} > ${k}`,()=>g.assign(B,!1).break()),O===1?g.assign(B,!0):g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0)))}}}})),require_dependencies=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=require_codegen(),s=require_util(),g=require_code();e.error={message:({params:{property:e,depsCount:s,deps:g}})=>{let S=s===1?`property`:`properties`;return(0,t.str)`must have ${S} ${g} when property ${e} is present`},params:({params:{property:e,depsCount:s,deps:g,missingProperty:S}})=>(0,t._)`{property: ${e},
48
48
  missingProperty: ${S},
49
49
  depsCount: ${s},
50
- deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Crypto);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
50
+ deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=crypto$1);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
51
51
  `;return g&&(S+=`id: ${g}\n`),S+=`data: ${JSON.stringify(s)}\n\n`,e.enqueue(t.encode(S)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let s=e.headers.get(`accept`);if(!s?.includes(`application/json`)||!s.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let g=e.headers.get(`content-type`);if(!g||!g.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let S={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},w;if(t?.parsedBody!==void 0)w=t.parsedBody;else try{w=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let E;try{E=Array.isArray(w)?w.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(w)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let D=E.some(isInitializeRequest);if(D){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(E.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!D){let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s}if(!E.some(isJSONRPCRequest)){for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S});return new Response(null,{status:202})}let O=crypto.randomUUID(),k=E.find(e=>isInitializeRequest(e)),j=k?k.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(O,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(O)}});for(let e of E)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,O);for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S})});let F=new TextEncoder,L,B=new ReadableStream({start:e=>{L=e},cancel:()=>{this._streamMapping.delete(O)}}),H={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(H[`mcp-session-id`]=this.sessionId);for(let e of E)isJSONRPCRequest(e)&&(this._streamMapping.set(O,{controller:L,encoder:F,cleanup:()=>{this._streamMapping.delete(O);try{L.close()}catch{}}}),this._requestToStreamMapping.set(e.id,O));await this.writePrimingEvent(L,F,O,j);for(let e of E){let s,g;isJSONRPCRequest(e)&&this._eventStore&&j>=`2025-11-25`&&(s=()=>{this.closeSSEStream(e.id)},g=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S,closeSSEStream:s,closeStandaloneSSEStream:g})}return new Response(B,{status:200,headers:H})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let s=this._streamMapping.get(t);s&&s.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let s=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(s=e.id),s===void 0){if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,e,t);return}let g=this._requestToStreamMapping.get(s);if(!g)throw Error(`No connection established for request ID: ${String(s)}`);let S=this._streamMapping.get(g);if(!this._enableJsonResponse&&S?.controller&&S?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(g,e)),this.writeSSEEvent(S.controller,S.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(s,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===g).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!S)throw Error(`No connection established for request ID: ${String(s)}`);if(this._enableJsonResponse&&S.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let s=t.map(e=>this._requestResponseMap.get(e));s.length===1?S.resolveJson(new Response(JSON.stringify(s[0]),{status:200,headers:e})):S.resolveJson(new Response(JSON.stringify(s),{status:200,headers:e}))}else S.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},StreamableHTTPServerTransport=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new WebStandardStreamableHTTPServerTransport(e),this._requestListener=getRequestListener(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,s){let g=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:g,parsedBody:s}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}},Ye=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-RBT2dq5Y.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BJJIS9lB.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-GrZNCK4M.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-Beyjypib.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BeLs_C7x.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-Bx-u3U5l.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-DmEja_Fu.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-D4Xj3X_m.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-Bs6Rpbb2.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-BDAoI0Wd.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-CMm4PFgi.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-C1Ie7s0s.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-DDRhZsId.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-mNeJ3km7.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-CjBr6WQ1.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-BOBd42y5.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-JPk1lni-.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-CYFqsI8W.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-CzG01gPs.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-CzG01gPs.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-CzG01gPs.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-BWOdKDEd.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-DmL_7Y-J.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-C7696e-z.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BfL8J8kf.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-MRCnRrGo.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-DT3SY7zS.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-Bm1HBn07.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-Bz3kd4hU.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-DWcyuCoi.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-KAKdorsx.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-SP99R3HJ.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-DZ2L21IZ.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-CtzV8vlq.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-Uj1QzdPV.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-BLW4mXRs.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Q5NIWguo.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-DTBoovzp.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-C_A2RnwJ.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-Bg8MXC_K.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-CJd25AiD.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-Dcz4Ls85.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-D-u8wJ0b.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CFaeUWGI.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-CO_jR0w6.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-DSwwgRF5.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-DSwwgRF5.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DmHh8yog.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DmHh8yog.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-1CYG7cs0.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-BvcSF5Y7.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-CJH22fVg.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-CJH22fVg.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CHSnzs8i.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DgruzS3i.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DgruzS3i.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-hdWY1RUY.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-BIHNwDj2.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-Di-oK2tx.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-Dv3os04S.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-D3IG7CwN.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-CVG2Q30a.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CxVP9vXG.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-DeaNEJEM.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-BOXtVHu2.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-C2RH1Ljb.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-DYUNX0rt.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-BwDMGEnF.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-Bt-1Wusv.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-5Fopg2Q5.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-C4HsVKec.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-Cl63MOrV.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BGR2Dq7O.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-BLS00ZWn.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-CB3itqHE.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BR0Ho1t5.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-B_BV2fa3.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-B_BV2fa3.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-B_BV2fa3.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-DCUS8bvA.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-_D_zdU3z.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-ZPqGVO90.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-DA8bw7DG.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-DmPp1QHj.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-DmPp1QHj.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-Cu6NIWHE.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-Cu6NIWHE.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-xgS5bDTx.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,s){let g=tn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-QT4N2Z44-hqAAghSo.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function rn(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Gt)}function nn(){return sn.map(Gt)}function on(){return Zt.map(Gt)}function an(){return qt.map(Gt)}function ln(e){return`load`in e&&typeof e.load==`function`}function cn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,g){return t||=await e.load(),t.execute(s,g)}}}var ot=new TextEncoder;function Qi(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Le=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,s]of Object.entries(e))typeof s==`function`?this.writeFileLazy(t,s):Qi(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=m$1(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,s,g){h$1(e,`write`);let S=c$1(e);this.ensureParentDirs(S);let w=o(t,l$1(s));this.data.set(S,{type:`file`,content:w,mode:g?.mode??420,mtime:g?.mtime??new Date})}writeFileLazy(e,t,s){h$1(e,`write`);let g=c$1(e);this.ensureParentDirs(g),this.data.set(g,{type:`file`,lazy:t,mode:s?.mode??420,mtime:s?.mtime??new Date})}async materializeLazy(e,t){let s=await t.lazy(),g={type:`file`,content:typeof s==`string`?ot.encode(s):s,mode:t.mode,mtime:t.mtime};return this.data.set(e,g),g}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in s){let e=await this.materializeLazy(t,s);return e.content instanceof Uint8Array?e.content:ot.encode(e.content)}return s.content instanceof Uint8Array?s.content:ot.encode(s.content)}async writeFile(e,t,s){this.writeFileSync(e,t,s)}async appendFile(e,t,s){h$1(e,`append`);let g=c$1(e),S=this.data.get(g);if(S&&S.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let w=o(t,l$1(s));if(S?.type===`file`){let e=S;`lazy`in e&&(e=await this.materializeLazy(g,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),s=new Uint8Array(t.length+w.length);s.set(t),s.set(w,t.length),this.data.set(g,{type:`file`,content:s,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,s)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, stat '${e}'`);s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}async lstat(e){h$1(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(s.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:s.mode,size:s.target.length,mtime:s.mtime||new Date};s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`);if(s.length<=1)return t;let g=``,S=new Set;for(let t=0;t<s.length-1;t++){let w=s[t];g=`${g}/${w}`;let E=this.data.get(g),D=0,O=40;for(;E&&E.type===`symlink`&&D<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);S.add(g),g=v$1(g,E.target),E=this.data.get(g),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${g}/${s[s.length-1]}`}resolvePathWithSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`),g=``,S=new Set;for(let t of s){g=`${g}/${t}`;let s=this.data.get(g),w=0,E=40;for(;s&&s.type===`symlink`&&w<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);S.add(g),g=v$1(g,s.target),s=this.data.get(g),w++}if(w>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return g}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$1(e,`mkdir`);let s=c$1(e);if(this.data.has(s)){if(this.data.get(s)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let g=m$1(s);if(g!==`/`&&!this.data.has(g))if(t?.recursive)this.mkdirSync(g,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(s,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let g=new Set;for(;s&&s.type===`symlink`;){if(g.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);g.add(t),t=v$1(t,s.target),s=this.data.get(t)}if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let S=t===`/`?`/`:`${t}/`,w=new Map;for(let[e,s]of this.data.entries())if(e!==t&&e.startsWith(S)){let t=e.slice(S.length),g=t.split(`/`)[0];g&&!t.includes(`/`,g.length)&&!w.has(g)&&w.set(g,{name:g,isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:s.type===`symlink`})}return Array.from(w.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$1(e,`rm`);let s=c$1(e),g=this.data.get(s);if(!g){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(g.type===`directory`){let g=await this.readdir(s);if(g.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of g){let g=p$1(s,e);await this.rm(g,t)}}}this.data.delete(s)}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=c$1(e),S=c$1(t),w=this.data.get(g);if(!w)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(w.type===`file`)if(this.ensureParentDirs(S),`content`in w){let e=w.content instanceof Uint8Array?new Uint8Array(w.content):w.content;this.data.set(S,{...w,content:e})}else this.data.set(S,{...w});else if(w.type===`symlink`)this.ensureParentDirs(S),this.data.set(S,{...w});else if(w.type===`directory`){if(!s?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(S,{recursive:!0});let t=await this.readdir(g);for(let e of t){let t=p$1(g,e),w=p$1(S,e);await this.cp(t,w,s)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return y(e,t)}async chmod(e,t){h$1(e,`chmod`);let s=c$1(e),g=this.data.get(s);if(!g)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);g.mode=t}async symlink(e,t){h$1(t,`symlink`);let s=c$1(t);if(this.data.has(s))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(s),this.data.set(s,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=c$1(e),g=c$1(t),S=this.data.get(s);if(!S)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(S.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(g))throw Error(`EEXIST: file already exists, link '${t}'`);let w=S;`lazy`in w&&(w=await this.materializeLazy(s,w)),this.ensureParentDirs(g),this.data.set(g,{type:`file`,content:w.content,mode:w.mode,mtime:w.mtime})}async readlink(e){h$1(e,`readlink`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return s.target}async realpath(e){h$1(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,s){h$1(e,`utimes`);let g=c$1(e),S=this.resolvePathWithSymlinks(g),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);w.mtime=s}};function Ji(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function eo(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function to(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function so(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
52
52
  `),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
53
53
  `),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>_i$1(t)):e.writeFileSync(`/proc/self/status`,_i$1(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function un(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){Ji(e)&&(eo(e,t),to(e),so(e,s))}var ro=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],no=[`braceexpand`,`hashall`,`interactive-comments`];function Ls(e){let t=[],s=[...no.map(e=>({name:e,enabled:!0})),...ro.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s)e.enabled&&t.push(e.name);return t.join(`:`)}function lt(e){e.state.env.set(`SHELLOPTS`,Ls(e.state.options))}var io=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function Fs(e){let t=[];for(let s of io)e[s]&&t.push(s);return t.join(`:`)}function Ms(e){e.state.env.set(`BASHOPTS`,Fs(e.state.shoptOptions))}var oo=`BASH_ALIAS_`;function fn(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function dn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function hn(e,t){return e.env.get(`${oo}${t}`)}function Ws(e,t,s){if(!t.name||!fn(t.name))return t;let g=dn(t.name);if(!g)return t;let S=hn(e,g);if(!S||s.has(g))return t;try{s.add(g);let w=new V,E=S,D=S.endsWith(` `);if(!D)for(let e of t.args){let t=mn(e);E+=` ${t}`}let O;try{O=w.parse(E)}catch(e){if(e instanceof G$1)throw e;return t}if(O.statements.length!==1||O.statements[0].pipelines.length!==1||O.statements[0].pipelines[0].commands.length!==1)return pn(t,S);let k=O.statements[0].pipelines[0].commands[0];if(k.type!==`SimpleCommand`)return pn(t,S);let j={...k,assignments:[...t.assignments,...k.assignments],redirections:[...k.redirections,...t.redirections],line:t.line};if(D&&t.args.length>0&&(j={...j,args:[...j.args,...t.args]},j.args.length>0)){let t=j.args[0];if(fn(t)){let g=dn(t);if(g&&hn(e,g)){let g={type:`SimpleCommand`,name:t,args:j.args.slice(1),assignments:[],redirections:[]},S=Ws(e,g,s);S!==g&&(j={...j,name:S.name,args:[...S.args]})}}}return j}catch(e){throw s.delete(g),e}}function pn(e,t){let s=t;for(let t of e.args){let e=mn(t);s+=` ${e}`}let g=new V;return{type:`SimpleCommand`,name:g.parseWordFromString(`eval`,!1,!1),args:[g.parseWordFromString(`'${s.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function mn(e){let t=``;for(let s of e.parts)switch(s.type){case`Literal`:t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${s.value}'`;break;case`DoubleQuoted`:t+=`"${s.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${s.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${s.expression}))`;break;case`Glob`:t+=s.pattern;break;default:break}return t}async function yn(e,t){let s=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),g=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!g||!s.endsWith(`)`))return null;let S=g[1],w=[],E=!1,D=``,O=!1;for(let s of t.parts)if(s.type===`Literal`){let e=s.value;if(!E){let t=e.indexOf(`=(`);t!==-1&&(E=!0,e=e.slice(t+2))}if(E){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(D||O)&&(w.push(D),D=``,O=!1):e&&(D+=e)}}else if(E)if(s.type===`BraceExpansion`)if(/^\[.+\]=/.test(D))D+=En$1({type:`Word`,parts:[s]});else{(D||O)&&(w.push(D),D=``,O=!1);let t=await wl(e,{type:`Word`,parts:[s]});w.push(...t.values)}else{(s.type===`SingleQuoted`||s.type===`DoubleQuoted`||s.type===`Escaped`)&&(O=!0);let t=await Pt$1(e,{type:`Word`,parts:[s]});D+=t}return(D||O)&&w.push(D),`${S}=(${w.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function gn(e,t){let s=-1,g=-1,S=!1;for(let e=0;e<t.parts.length;e++){let w=t.parts[e];if(w.type===`Literal`){let t=w.value.indexOf(`+=`);if(t!==-1){let E=w.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){s=e,g=t,S=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=e,g=t,S=!0;break}}let E=w.value.indexOf(`=`);if(E!==-1&&(E===0||w.value[E-1]!==`+`)){let t=w.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){s=e,g=E;break}}}}if(s===-1)return null;let w=t.parts.slice(0,s),E=t.parts[s];if(E.type!==`Literal`)return null;let D=S?2:1,O=E.value.slice(0,g),k=E.value.slice(g+D),j=t.parts.slice(s+1),F=``;for(let t of w)F+=await Pt$1(e,{type:`Word`,parts:[t]});F+=O;let L={type:`Word`,parts:k===``?j:[{type:`Literal`,value:k},...j]},B=L.parts.length>0?await Pt$1(e,L):``;return`${F}${S?`+=`:`=`}${B}`}var ao=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function wn(e){return ao.includes(e)}var W=Object.freeze({stdout:``,stderr:``,exitCode:0});function z(e=``){return{stdout:e,stderr:``,exitCode:0}}function A(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function Ne(e,t,s=``,g=``){throw new b(e,t,s,g)}function le(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new b(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function zs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new f;return W}if(t.length>1)throw new d(1,``,`bash: break: too many arguments
@@ -754,7 +754,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
754
754
  `,exitCode:2,env:n(this.state.env,t?.env)});if(e instanceof RangeError)return this.logResult({stdout:``,stderr:`bash: ${n$1(e.message)}
755
755
  `,exitCode:1,env:n(this.state.env,t?.env)});throw e}finally{k?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return r(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=di$1(Vi(e),{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let e of this.transformPlugins){let g=e.transform({ast:t,metadata:s});t=g.ast,g.metadata&&(s=c$2(s,g.metadata))}return{script:Ot(t),ast:t,metadata:s}}};function Vi(e){let t=e.split(`
756
756
  `),s=[],g=[];for(let e=0;e<t.length;e++){let S=t[e];if(g.length>0){let e=g[g.length-1];if((e.stripTabs?S.replace(/^\t+/,``):S)===e.delimiter){s.push(S.trimStart()),g.pop();continue}s.push(S);continue}let w=S.trimStart();s.push(w);for(let e of w.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,s=e[3];g.push({delimiter:s,stripTabs:t})}}return s.join(`
757
- `)}var rl=new TextDecoder(`utf-8`,{fatal:!0});function Bi(e){if(!e)return e;let t=!1;for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);if(g>255)return e;g>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);try{return rl.decode(s)}catch{return e}}var ol=[`EACCES`,`escaping sandbox`,`EFBIG`],Ss=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=U.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$$2(this.root,`ReadWriteFs`),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(e,t){let s=this.allowSymlinks?f$1(e,this.canonicalRoot):P$1(e,this.root,this.canonicalRoot);if(s===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return s}validateParent(e,t){let s=U.dirname(e),g=this.resolveAndValidate(s,t);return U.join(g,U.basename(e))}toRealPath(e){let t=c$1(e),s=U.join(this.root,t);return U.resolve(s)}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(s,t);try{if(this.maxFileReadSize>0){let t=await g.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await g.readFile();return new Uint8Array(t)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,s){h$1(e,`write`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,s){h$1(e,`append`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let s=this.resolveAndValidate(t,e);return await I.promises.access(s),!0}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=await I.promises.lstat(s);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){h$1(e,`lstat`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let e=await I.promises.lstat(s);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){h$1(e,`mkdir`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.mkdir(g,{recursive:t?.recursive})}catch(t){let s=t;if(s.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await I.promises.lstat(s)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await I.promises.readdir(s,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){h$1(e,`rm`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.rm(g,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(s){let g=s;if(g.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(g.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(s,e,`rm`)}}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=this.toRealPath(e),S=this.toRealPath(t),w=this.resolveAndValidate(g,e),E=this.resolveAndValidate(S,t);try{await I.promises.cp(w,E,{recursive:s?.recursive??!1,filter:async e=>{try{if(I.lstatSync(e).isSymbolicLink()){let t=await I.promises.realpath(e).catch(()=>null);return t===null?!1:d$1(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){h$1(e,`mv`),h$1(t,`mv`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.validateParent(s,e),w=this.validateParent(g,t);try{if((await I.promises.lstat(S)).isSymbolicLink()){let s=await I.promises.readlink(S),g=U.resolve(U.dirname(w),s);if(!d$1(await I.promises.realpath(g).catch(()=>g),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(s.message?.includes(`EACCES`)||s.message?.includes(`escaping sandbox`))throw t}let E=U.dirname(w);try{await I.promises.mkdir(E,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await I.promises.rename(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(g.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(s,e,`mv`)}try{if(I.lstatSync(w).isDirectory()&&this.findEscapingSymlinks(w).length>0)throw await I.promises.rename(w,S),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return y(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,s){N(e,t,s,ol)}findEscapingSymlinks(e){let t=[];try{let s=I.readdirSync(e);for(let g of s){let s=U.join(e,g);try{let g=I.lstatSync(s);if(g.isSymbolicLink()){let g=I.readlinkSync(s),S=U.resolve(e,g),w;try{w=I.realpathSync(S)}catch{w=S}d$1(w,this.canonicalRoot)||t.push(s)}else g.isDirectory()&&t.push(...this.findEscapingSymlinks(s))}catch{}}}catch{}return t}scanDir(e,t){let s=this.toRealPath(e),g;try{g=this.resolveAndValidate(s,e)}catch{return}try{let s=I.readdirSync(g);for(let S of s){let s=e===`/`?`/${S}`:`${e}/${S}`;t.push(s);let w=U.join(g,S);I.lstatSync(w).isDirectory()&&this.scanDir(s,t)}}catch{}}async chmod(e,t){h$1(e,`chmod`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,s=await I.promises.open(g,e);try{await s.chmod(t)}finally{await s.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);h$1(t,`symlink`);let s=this.toRealPath(t),g=this.validateParent(s,t),S=c$1(t),w=c$1(U.dirname(S)),E=e.startsWith(`/`)?c$1(e):c$1(w===`/`?`/${e}`:`${w}/${e}`),D=U.join(this.canonicalRoot,E),O=U.dirname(g),k=e.startsWith(`/`)?D:U.relative(O,D)||`.`;try{await I.promises.symlink(k,g)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.resolveAndValidate(s,e),w=this.resolveAndValidate(g,t);try{await I.promises.link(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(g.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(g.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(s,e,`link`)}}async readlink(e){h$1(e,`readlink`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let t=await I.promises.readlink(s),g=c$1(e),S=U.dirname(g),w=U.isAbsolute(t)?t:U.resolve(U.dirname(s),t),E=await I.promises.realpath(w).catch(()=>w);if(d$1(E,this.canonicalRoot)){let e=E.slice(this.canonicalRoot.length)||`/`;return S===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:U.relative(S,e)}return U.basename(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){h$1(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let s;try{s=await I.promises.realpath(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(s.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(d$1(s,this.canonicalRoot))return s.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,s){h$1(e,`utimes`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(S,e);try{await g.utimes(t,s)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}},require_quote=__commonJSMin$2(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),require_parse=__commonJSMin$2(((e,t)=>{for(var s=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,g=RegExp(`^`+s+`$`),S=`|&;()<> \\t`,w=`"((\\\\"|[^"])*?)"`,E=`'((\\\\'|[^'])*?)'`,D=/^#$/,O=`'`,k=`"`,j=`$`,F=``,L=4294967296,B=0;B<4;B++)F+=(L*Math.random()).toString(16);var H=RegExp(`^`+F);function q(e,t){for(var s=t.lastIndex,g=[],S;S=t.exec(e);)g.push(S),t.lastIndex===S.index&&(t.lastIndex+=1);return t.lastIndex=s,g}function ee(e,t,s){var g=typeof e==`function`?e(s):e[s];return g===void 0&&s!=``?g=``:g===void 0&&(g=`$`),typeof g==`object`?t+F+JSON.stringify(g)+F:t+g}function J(e,t,F){F||={};var L=F.escape||`\\`,B=`(\\`+L+`['"`+S+`]|[^\\s'"`+S+`])+`,H=q(e,new RegExp([`(`+s+`)`,`(`+B+`|`+w+`|`+E+`)+`].join(`|`),`g`));if(H.length===0)return[];t||={};var J=!1;return H.map(function(s){var S=s[0];if(!S||J)return;if(g.test(S))return{op:S};var w=!1,E=!1,F=``,B=!1,H;function q(){H+=1;var e,s,g=S.charAt(H);if(g===`{`){if(H+=1,S.charAt(H)===`}`)throw Error(`Bad substitution: `+S.slice(H-2,H+1));if(e=S.indexOf(`}`,H),e<0)throw Error(`Bad substitution: `+S.slice(H));s=S.slice(H,e),H=e}else if(/[*@#?$!_-]/.test(g))s=g,H+=1;else{var w=S.slice(H);e=w.match(/[^\w\d_]/),e?(s=w.slice(0,e.index),H+=e.index-1):(s=w,H=S.length)}return ee(t,``,s)}for(H=0;H<S.length;H++){var Y=S.charAt(H);if(B||=!w&&(Y===`*`||Y===`?`),E)F+=Y,E=!1;else if(w)Y===w?w=!1:w==O?F+=Y:Y===L?(H+=1,Y=S.charAt(H),Y===k||Y===L||Y===j?F+=Y:F+=L+Y):Y===j?F+=q():F+=Y;else if(Y===k||Y===O)w=Y;else if(g.test(Y))return{op:S};else if(D.test(Y)){J=!0;var te={comment:e.slice(s.index+H+1)};return F.length?[F,te]:[te]}else Y===L?E=!0:Y===j?F+=q():F+=Y}return B?{op:`glob`,pattern:F}:F}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,s){var g=J(e,t,s);return typeof t==`function`?g.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var s=t.split(RegExp(`(`+F+`.*?`+F+`)`,`g`));return s.length===1?e.concat(s[0]):e.concat(s.filter(Boolean).map(function(e){return H.test(e)?JSON.parse(e.split(F)[1]):e}))},[]):g}})),require_shell_quote=__commonJSMin$2((e=>{e.quote=require_quote(),e.parse=require_parse()}));const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let s=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,s);for(let t=0;t<s;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$1(e,g);for(let t=0;t<g;t++)write$1(e,s.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$1(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((s,g)=>{let S={resolve:s,reject:g,weight:e,priority:t},w=findIndexFromEnd(this._queue,e=>t<=e.priority);w===-1&&e<=this._value?this._dispatchItem(S):this._queue.splice(w+1,0,S)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,s=0){let[g,S]=yield this.acquire(t,s);try{return yield e(g)}finally{S()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let s=this._weightedWaiters[t-1];if(!s)continue;let g=s.findIndex(t=>t.priority<=e);(g===-1?s:s.splice(0,g)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let s=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(s+1,0,t)}function findIndexFromEnd(e,t){for(let s=e.length-1;s>=0;s--)if(t(e[s]))return s;return-1}var __awaiter$1=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let s=0,g,S=``,w=``;for(;s<e.length;s++)g=e[s],S+=g.open,w+=g.close,~t.indexOf(g.close)&&(t=t.replace(g.rgx,g.close+g.open));return S+t+w}function chain(e,t){let s={has:e,keys:t};return s.reset=$.reset.bind(s),s.bold=$.bold.bind(s),s.dim=$.dim.bind(s),s.italic=$.italic.bind(s),s.underline=$.underline.bind(s),s.inverse=$.inverse.bind(s),s.hidden=$.hidden.bind(s),s.strikethrough=$.strikethrough.bind(s),s.black=$.black.bind(s),s.red=$.red.bind(s),s.green=$.green.bind(s),s.yellow=$.yellow.bind(s),s.blue=$.blue.bind(s),s.magenta=$.magenta.bind(s),s.cyan=$.cyan.bind(s),s.white=$.white.bind(s),s.gray=$.gray.bind(s),s.grey=$.grey.bind(s),s.bgBlack=$.bgBlack.bind(s),s.bgRed=$.bgRed.bind(s),s.bgGreen=$.bgGreen.bind(s),s.bgYellow=$.bgYellow.bind(s),s.bgBlue=$.bgBlue.bind(s),s.bgMagenta=$.bgMagenta.bind(s),s.bgCyan=$.bgCyan.bind(s),s.bgWhite=$.bgWhite.bind(s),s}function init(e,t){let s={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(s)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[s]):$.enabled?run([s],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},write=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let s=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,s);for(let t=0;t<s;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint(e,g);for(let t=0;t<g;t++)write(e,s.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&BITS7)*s,s*=128,g<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;break;case Set:if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;break;case Map:if(e.size!==t.size)return!1;for(let s of e.keys())if(!t.has(s)||!equalityDeep(e.get(s),t.get(s)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let s in e)if(!hasProperty(e,s)||!equalityDeep(e[s],t[s]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!equalityDeep(e[s],t[s]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((s,g)=>{g!==this.clientID&&outdatedTimeout<=e-s.lastUpdated&&this.states.has(g)&&t.push(g)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,s=this.meta.get(t),g=s===void 0?0:s.clock+1,S=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:g,lastUpdated:getUnixTime()});let w=[],E=[],D=[],O=[];e===null?O.push(t):S==null?e!=null&&w.push(t):(E.push(t),equalityDeep(S,e)||D.push(t)),(w.length>0||D.length>0||O.length>0)&&this.emit(`change`,[{added:w,updated:D,removed:O},`local`]),this.emit(`update`,[{added:w,updated:E,removed:O},`local`])}setLocalStateField(e,t){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,s)=>{let g=[];for(let s=0;s<t.length;s++){let S=t[s];if(e.states.has(S)){if(e.states.delete(S),S===e.clientID){let t=e.meta.get(S);e.meta.set(S,{clock:t.clock+1,lastUpdated:getUnixTime()})}g.push(S)}}g.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:g},s]),e.emit(`update`,[{added:[],updated:[],removed:g},s]))},encodeAwarenessUpdate=(e,t,s=e.states)=>{let g=t.length,S=createEncoder();writeVarUint(S,g);for(let w=0;w<g;w++){let g=t[w],E=s.get(g)||null,D=e.meta.get(g).clock;writeVarUint(S,g),writeVarUint(S,D),writeVarString(S,JSON.stringify(E))}return toUint8Array(S)},applyAwarenessUpdate=(e,t,s)=>{let g=createDecoder(t),S=getUnixTime(),w=[],E=[],D=[],O=[],k=readVarUint(g);for(let t=0;t<k;t++){let t=readVarUint(g),s=readVarUint(g),k=JSON.parse(readVarString(g)),j=e.meta.get(t),F=e.states.get(t),L=j===void 0?0:j.clock;(L<s||L===s&&k===null&&e.states.has(t))&&(k===null?t===e.clientID&&e.getLocalState()!=null?s++:e.states.delete(t):e.states.set(t,k),e.meta.set(t,{clock:s,lastUpdated:S}),j===void 0&&k!==null?w.push(t):j!==void 0&&k===null?O.push(t):k!==null&&(equalityDeep(k,F)||D.push(t),E.push(t)))}(w.length>0||D.length>0||O.length>0)&&e.emit(`change`,[{added:w,updated:D,removed:O},s]),(w.length>0||E.length>0||O.length>0)&&e.emit(`update`,[{added:w,updated:E,removed:O},s])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,s)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,s))},readSyncStep1=(e,t,s)=>writeSyncStep2(t,s,readVarUint8Array(e)),readSyncStep2=(e,t,s,g)=>{try{applyUpdate(t,readVarUint8Array(e),s)}catch(e){g?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let s=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,s),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,s){let{message:g}=this,S=g.readVarUint(),w=g.length;switch(S){case MessageType.Sync:case MessageType.SyncReply:g.writeVarUint(MessageType.Sync),await this.readSyncMessage(g,e,t,s,S!==MessageType.SyncReply),g.length>w+1&&(s?s(g.toUint8Array()):t&&t.send(g.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,g.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,s);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(g.decoder)});break;case MessageType.BroadcastStateless:{let t=g.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(g.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:g.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${S}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,s,g,S=!0){let w=e.readVarUint(),E=s?.messageAddress??t.name;switch(s&&await s.callbacks.beforeSync(s,{type:w,payload:e.peekVarUint8Array()}),w){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),g&&S)g(new OutgoingMessage(E).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(s){let e=new OutgoingMessage(E).createSyncMessage().writeFirstSyncStepFor(t);s.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(s?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(E).writeSyncStatus(!0);s.send(e.toUint8Array())}else{let e=new OutgoingMessage(E).writeSyncStatus(!1);s.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(s?.readOnly){s.send(new OutgoingMessage(E).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${w}`)}return w}applyQueryAwarenessMessage(e,t,s){let g=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);s&&s(g.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,s,g,S,w=!1,E,D){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=S,this.document=s,this.request=t,this.socketId=g,this.readOnly=w,this.sessionId=E??null,this.providerVersion=D??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),s=t.readVarString(),g=s.indexOf(`\0`),S=g===-1?s:s.substring(0,g);if(S!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${S}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,s)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:s},g){let S=e.concat(t,s);if(g!==null){let t=this.connections.get(g);t&&(e.forEach(e=>t.clients.add(e)),s.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,S);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let s=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(s.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,s,g,S,w={}){this.websocket=e,this.request=t,this.documentProvider=s,this.hooks=g,this.opts=S,this.defaultContext=w,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,s)=>{let g=this.hookPayloads[e],S=await this.documentProvider.createDocument(t,g.request,g.socketId,g.connectionConfig,g.context),w=this.createConnection(this.websocket,S,g,s,g.providerVersion);if(w.onClose((t,s)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),w.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...g,...e,document:S,connection:w,documentName:t},e=>{g.context={...g.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};w.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=w,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{w.handleMessage(e)}),await this.hooks(`connected`,{...g,documentName:t,context:g.context,connection:w})},this.handleQueueingMessage=async(e,t,s)=>{try{let g=new IncomingMessage(e);if(readVarString(g.decoder),!(readVarUint(g.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(g.decoder);let S=readVarString(g.decoder),w=null;hasContent(g.decoder)&&(w=readVarString(g.decoder));let E=t.indexOf(`\0`),D=E===-1?null:t.substring(E+1),O=t;try{let e=this.hookPayloads[t];e.providerVersion=w,await this.hooks(`onConnect`,{...e,documentName:s},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:S,...e,documentName:s},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let g=new OutgoingMessage(O).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(g.toUint8Array()),await this.setUpNewConnection(t,s,D)}catch(e){let s=e||Forbidden,g=new OutgoingMessage(O).writePermissionDenied(s.reason??`permission-denied`);this.websocket.send(g.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),s=t.indexOf(`\0`),g=s===-1?t:t.substring(0,s),S=this.documentConnections[t]??this.documentConnections[g];if(S){S.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,g)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=S.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,s,g,S){let w=new Connection(e,s.request,t,s.socketId,s.context,s.connectionConfig.readOnly,g,S);return w.onClose(async(e,t)=>{await w.waitForPendingMessages();let g={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:s.context,document:e,socketId:s.socketId,documentName:e.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request)};await this.hooks(`onDisconnect`,g),this.callbacks.onClose.forEach(t=>t(e,g))}),w.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),w.beforeHandleMessage((e,g)=>{let S={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:s.context,document:t,socketId:s.socketId,connection:e,documentName:t.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request),update:g};return this.hooks(`beforeHandleMessage`,S)}),w.beforeSync((e,g)=>{let S={clientsCount:t.getConnectionsCount(),context:s.context,document:t,documentName:t.name,connection:e,type:g.type,payload:g.payload};return this.hooks(`beforeSync`,S)}),w}},DirectConnection=class{constructor(e,t,s){this.document=null,this.document=e,this.instance=t,this.context=s??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(s,g,S,w)=>{let E=e.get(s),D=E?.start||Date.now(),O=async()=>{t.has(s)&&await t.get(s),e.delete(s);let S=g();t.set(s,S);let w=await S;return t.delete(s),w};if(E?.timeout&&clearTimeout(E.timeout),S===0||Date.now()-D>=w)return O();e.set(s,{start:D,timeout:setTimeout(O,S),func:O})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let s=e.get(t);if(s)return clearTimeout(s.timeout),s.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let s=e.priority===void 0?100:e.priority,g=t.priority===void 0?100:t.priority;return s>g?-1:s<g?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,s)=>(s.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+s.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,s={}){let g=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},s);return g.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),g}handleDocumentUpdate(e,t,s){let g=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,S=g?.request,w=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},E={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:S?.headers??new Headers,requestParameters:getParameters(S),socketId:g?.socketId??``,update:s,transactionOrigin:t,connection:g,context:w};if(this.hooks(`onChange`,E),shouldSkipStoreHooks(t))return;let D={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:w,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,D)}async createDocument(e,t,s,g,S){if(!e.trim())throw Error(`Document name must not be empty`);let w=this.loadingDocuments.get(e);if(w)return w;let E=this.documents.get(e);if(E)return Promise.resolve(E);let D=this.loadDocument(e,t,s,g,S);this.loadingDocuments.set(e,D);try{let t=await D;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,s,g,S){let w=t.headers,E=getParameters(t),D=S??{},O=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:w,requestParameters:E,connectionConfig:g,context:D,socketId:s,instance:this}),k=new Document(e,{...this.configuration.yDocOptions,...O}),j={instance:this,context:D,connectionConfig:g,document:k,documentName:e,socketId:s,requestHeaders:w,requestParameters:E};try{await this.hooks(`onLoadDocument`,j,e=>{e instanceof Doc?applyUpdate(k,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(k,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(k),t}return k.isLoading=!1,k.onUpdate((e,t,s)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,s)}),await this.hooks(`afterLoadDocument`,j),k.beforeBroadcastStateless((e,t)=>{let s={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,s)}),k.awareness.on(`update`,(t,s)=>{this.hooks(`onAwarenessUpdate`,{document:k,documentName:e,instance:this,...t,transactionOrigin:s,connection:isTransactionOrigin(s)&&s.source===`connection`?s.connection:void 0,awareness:k.awareness,states:awarenessStatesToArray(k.awareness.getStates())})}),k}storeDocumentHooks(e,t,s){let g=`onStoreDocument-${e.name}`;return this.debouncer.debounce(g,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},s?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,s=null){let{extensions:g}=this.configuration,S=Promise.resolve();return g.filter(t=>typeof t[e]==`function`).forEach(g=>{S=S.then(()=>g[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),s&&(S=S.then((...e)=>s(...e)))}),S}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let s=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(s)),await s,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create$1=Object.create,__defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__getOwnPropNames$1=Object.getOwnPropertyNames,__getProtoOf$1=Object.getPrototypeOf,__hasOwnProp$1=Object.prototype.hasOwnProperty,__commonJSMin$1=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps$1=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames$1(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp$1.call(e,D)&&D!==s&&__defProp$1(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc$1(t,D))||g.enumerable});return e},__toESM$1=(e,t,s)=>(s=e==null?{}:__create$1(__getProtoOf$1(e)),__copyProps$1(t||!e||!e.__esModule?__defProp$1(s,`default`,{value:e,enumerable:!0}):s,e)),__require$1=createRequire(import.meta.url),require_constants$2=__commonJSMin$1(((e,t)=>{let s=[`nodebuffer`,`arraybuffer`,`fragments`],g=typeof Blob<`u`;g&&s.push(`blob`),t.exports={BINARY_TYPES:s,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:g,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin$1(((e,t)=>{let{EMPTY_BUFFER:s}=require_constants$2(),g=Buffer[Symbol.species];function S(e,t){if(e.length===0)return s;if(e.length===1)return e[0];let S=Buffer.allocUnsafe(t),w=0;for(let t=0;t<e.length;t++){let s=e[t];S.set(s,w),w+=s.length}return w<t?new g(S.buffer,S.byteOffset,w):S}function w(e,t,s,g,S){for(let w=0;w<S;w++)s[g+w]=e[w]^t[w&3]}function E(e,t){for(let s=0;s<e.length;s++)e[s]^=t[s&3]}function D(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function O(e){if(O.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new g(e):ArrayBuffer.isView(e)?t=new g(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),O.readOnly=!1),t}if(t.exports={concat:S,mask:w,toArrayBuffer:D,toBuffer:O,unmask:E},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require$1(`bufferutil`);t.exports.mask=function(t,s,g,S,E){E<48?w(t,s,g,S,E):e.mask(t,s,g,S,E)},t.exports.unmask=function(t,s){t.length<32?E(t,s):e.unmask(t,s)}}catch{}})),require_limiter=__commonJSMin$1(((e,t)=>{let s=Symbol(`kDone`),g=Symbol(`kRun`);t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[g]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[g]()}[g](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}})),require_permessage_deflate=__commonJSMin$1(((e,t)=>{let s=__require$1(`zlib`),g=require_buffer_util(),S=require_limiter(),{kStatusCode:w}=require_constants$2(),E=Buffer[Symbol.species],D=Buffer.from([0,0,255,255]),O=Symbol(`permessage-deflate`),k=Symbol(`total-length`),j=Symbol(`callback`),F=Symbol(`buffers`),L=Symbol(`error`),B;t.exports=class{constructor(e,t,s){this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,B||=new S(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[j];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,s=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!s)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],t===`client_max_window_bits`){if(s!==!0){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if(t===`server_max_window_bits`){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(s!==!0)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){B.add(g=>{this._decompress(e,t,(e,t)=>{g(),s(e,t)})})}compress(e,t,s){B.add(g=>{this._compress(e,t,(e,t)=>{g(),s(e,t)})})}_decompress(e,t,S){let w=this._isServer?`client`:`server`;if(!this._inflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._inflate=s.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[O]=this,this._inflate[k]=0,this._inflate[F]=[],this._inflate.on(`error`,ee),this._inflate.on(`data`,q)}this._inflate[j]=S,this._inflate.write(e),t&&this._inflate.write(D),this._inflate.flush(()=>{let e=this._inflate[L];if(e){this._inflate.close(),this._inflate=null,S(e);return}let s=g.concat(this._inflate[F],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._inflate.reset()),S(null,s)})}_compress(e,t,S){let w=this._isServer?`server`:`client`;if(!this._deflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._deflate=s.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[k]=0,this._deflate[F]=[],this._deflate.on(`data`,H)}this._deflate[j]=S,this._deflate.write(e),this._deflate.flush(s.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=g.concat(this._deflate[F],this._deflate[k]);t&&(e=new E(e.buffer,e.byteOffset,e.length-4)),this._deflate[j]=null,this._deflate[k]=0,this._deflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._deflate.reset(),S(null,e)})}};function H(e){this[F].push(e),this[k]+=e.length}function q(e){if(this[k]+=e.length,this[O]._maxPayload<1||this[k]<=this[O]._maxPayload){this[F].push(e);return}this[L]=RangeError(`Max payload size exceeded`),this[L].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[L][w]=1009,this.removeListener(`data`,q),this.reset()}function ee(e){if(this[O]._inflate=null,this[L]){this[j](this[L]);return}e[w]=1007,this[j](e)}})),require_validation=__commonJSMin$1(((e,t)=>{let{isUtf8:s}=__require$1(`buffer`),{hasBlob:g}=require_constants$2(),S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function w(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function E(e){let t=e.length,s=0;for(;s<t;)if(!(e[s]&128))s++;else if((e[s]&224)==192){if(s+1===t||(e[s+1]&192)!=128||(e[s]&254)==192)return!1;s+=2}else if((e[s]&240)==224){if(s+2>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||e[s]===224&&(e[s+1]&224)==128||e[s]===237&&(e[s+1]&224)==160)return!1;s+=3}else if((e[s]&248)==240){if(s+3>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||(e[s+3]&192)!=128||e[s]===240&&(e[s+1]&240)==128||e[s]===244&&e[s+1]>143||e[s]>244)return!1;s+=4}else return!1;return!0}function D(e){return g&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:D,isValidStatusCode:w,isValidUTF8:E,tokenChars:S},s)t.exports.isValidUTF8=function(e){return e.length<24?E(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require$1(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?E(t):e(t)}}catch{}})),require_receiver=__commonJSMin$1(((e,t)=>{let{Writable:s}=__require$1(`stream`),g=require_permessage_deflate(),{BINARY_TYPES:S,EMPTY_BUFFER:w,kStatusCode:E,kWebSocket:D}=require_constants$2(),{concat:O,toArrayBuffer:k,unmask:j}=require_buffer_util(),{isValidStatusCode:F,isValidUTF8:L}=require_validation(),B=Buffer[Symbol.species],H=0,q=1,ee=2,J=3,Y=4,te=5,ne=6;t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||S[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[D]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(this._opcode===8&&this._state==0)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new B(t.buffer,t.byteOffset+e,t.length-e),new B(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],g=t.length-e;e>=s.length?t.set(this._buffers.shift(),g):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),g),this._buffers[0]=new B(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let s=(t[0]&64)==64;if(s&&!this._extensions[g.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);if(s>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=s*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&j(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[g.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(s)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let g;g=this._binaryType===`nodebuffer`?O(s,t):this._binaryType===`arraybuffer`?k(O(s,t)):this._binaryType===`blob`?new Blob(s):s,this._allowSynchronousEvents?(this.emit(`message`,g,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!0),this._state=0,this.startLoop(e)}))}else{let g=O(s,t);if(!this._skipUTF8Validation&&!L(g)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,g,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,w),this.end();else{let s=e.readUInt16BE(0);if(!F(s)){t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let g=new B(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!L(g)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,s,g),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,s,g,S){this._loop=!1,this._errored=!0;let w=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(w,this.createError),w.code=S,w[E]=g,w}}})),require_sender=__commonJSMin$1(((e,t)=>{let{Duplex:s}=__require$1(`stream`),{randomFillSync:g}=__require$1(`crypto`),S=require_permessage_deflate(),{EMPTY_BUFFER:w,kWebSocket:E,NOOP:D}=require_constants$2(),{isBlob:O,isValidStatusCode:k}=require_validation(),{mask:j,toBuffer:F}=require_buffer_util(),L=Symbol(`kByteLength`),B=Buffer.alloc(4),H=8*1024,q,ee=H,J=0,Y=1,te=2;t.exports=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=D,this[E]=void 0}static frame(e,t){let s,S=!1,w=2,E=!1;t.mask&&(s=t.maskBuffer||B,t.generateMask?t.generateMask(s):(ee===H&&(q===void 0&&(q=Buffer.alloc(H)),g(q,0,H),ee=0),s[0]=q[ee++],s[1]=q[ee++],s[2]=q[ee++],s[3]=q[ee++]),E=(s[0]|s[1]|s[2]|s[3])===0,w=6);let D;typeof e==`string`?(!t.mask||E)&&t[L]!==void 0?D=t[L]:(e=Buffer.from(e),D=e.length):(D=e.length,S=t.mask&&t.readOnly&&!E);let O=D;D>=65536?(w+=8,O=127):D>125&&(w+=2,O=126);let k=Buffer.allocUnsafe(S?D+w:w);return k[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(k[0]|=64),k[1]=O,O===126?k.writeUInt16BE(D,2):O===127&&(k[2]=k[3]=0,k.writeUIntBE(D,4,6)),!t.mask||(k[1]|=128,k[w-4]=s[0],k[w-3]=s[1],k[w-2]=s[2],k[w-1]=s[3],E)?[k,e]:S?(j(e,s,k,w,D),[k]):(j(e,s,e,0,D),[k,e])}close(t,s,g,S){let E;if(t===void 0)E=w;else if(typeof t!=`number`||!k(t))throw TypeError(`First argument must be a valid error code number`);else if(s===void 0||!s.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(t,0);else{let e=Buffer.byteLength(s);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);E=Buffer.allocUnsafe(2+e),E.writeUInt16BE(t,0),typeof s==`string`?E.write(s,2):E.set(s,2)}let D={[L]:E.length,fin:!0,generateMask:this._generateMask,mask:g,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(E,D),S):this.enqueue([this.dispatch,E,!1,D,S])}ping(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}pong(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}send(e,t,s){let g=this._extensions[S.extensionName],w=t.binary?2:1,E=t.compress,D,k;typeof e==`string`?(D=Buffer.byteLength(e),k=!1):O(e)?(D=e.size,k=!1):(e=F(e),D=e.length,k=F.readOnly),this._firstFragment?(this._firstFragment=!1,E&&g&&g.params[g._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(E=D>=g._threshold),this._compress=E):(E=!1,w=0),t.fin&&(this._firstFragment=!0);let j={[L]:D,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:w,readOnly:k,rsv1:E};O(e)?this._state===0?this.getBlobData(e,this._compress,j,s):this.enqueue([this.getBlobData,e,this._compress,j,s]):this._state===0?this.dispatch(e,this._compress,j,s):this.enqueue([this.dispatch,e,this._compress,j,s])}getBlobData(t,s,g,S){this._bufferedBytes+=g[L],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(ne,this,e,S);return}this._bufferedBytes-=g[L];let w=F(t);s?this.dispatch(w,s,g,S):(this._state=0,this.sendFrame(e.frame(w,g),S),this.dequeue())}).catch(e=>{process.nextTick(ae,this,e,S)})}dispatch(t,s,g,w){if(!s){this.sendFrame(e.frame(t,g),w);return}let E=this._extensions[S.extensionName];this._bufferedBytes+=g[L],this._state=1,E.compress(t,g.fin,(t,s)=>{if(this._socket.destroyed){ne(this,Error(`The socket was closed while data was being compressed`),w);return}this._bufferedBytes-=g[L],this._state=0,g.readOnly=!1,this.sendFrame(e.frame(s,g),w),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][L],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][L],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function ne(e,t,s){typeof s==`function`&&s(t);for(let s=0;s<e._queue.length;s++){let g=e._queue[s],S=g[g.length-1];typeof S==`function`&&S(t)}}function ae(e,t,s){ne(e,t,s),e.onerror(t)}})),require_event_target=__commonJSMin$1(((e,t)=>{let{kForOnEventAttribute:s,kListener:g}=require_constants$2(),S=Symbol(`kCode`),w=Symbol(`kData`),E=Symbol(`kError`),D=Symbol(`kMessage`),O=Symbol(`kReason`),k=Symbol(`kTarget`),j=Symbol(`kType`),F=Symbol(`kWasClean`);var L=class{constructor(e){this[k]=null,this[j]=e}get target(){return this[k]}get type(){return this[j]}};Object.defineProperty(L.prototype,`target`,{enumerable:!0}),Object.defineProperty(L.prototype,`type`,{enumerable:!0});var B=class extends L{constructor(e,t={}){super(e),this[S]=t.code===void 0?0:t.code,this[O]=t.reason===void 0?``:t.reason,this[F]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[S]}get reason(){return this[O]}get wasClean(){return this[F]}};Object.defineProperty(B.prototype,`code`,{enumerable:!0}),Object.defineProperty(B.prototype,`reason`,{enumerable:!0}),Object.defineProperty(B.prototype,`wasClean`,{enumerable:!0});var H=class extends L{constructor(e,t={}){super(e),this[E]=t.error===void 0?null:t.error,this[D]=t.message===void 0?``:t.message}get error(){return this[E]}get message(){return this[D]}};Object.defineProperty(H.prototype,`error`,{enumerable:!0}),Object.defineProperty(H.prototype,`message`,{enumerable:!0});var q=class extends L{constructor(e,t={}){super(e),this[w]=t.data===void 0?null:t.data}get data(){return this[w]}};Object.defineProperty(q.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:B,ErrorEvent:H,Event:L,EventTarget:{addEventListener(e,t,S={}){for(let w of this.listeners(e))if(!S[s]&&w[g]===t&&!w[s])return;let w;if(e===`message`)w=function(e,s){let g=new q(`message`,{data:s?e:e.toString()});g[k]=this,ee(t,this,g)};else if(e===`close`)w=function(e,s){let g=new B(`close`,{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});g[k]=this,ee(t,this,g)};else if(e===`error`)w=function(e){let s=new H(`error`,{error:e,message:e.message});s[k]=this,ee(t,this,s)};else if(e===`open`)w=function(){let e=new L(`open`);e[k]=this,ee(t,this,e)};else return;w[s]=!!S[s],w[g]=t,S.once?this.once(e,w):this.on(e,w)},removeEventListener(e,t){for(let S of this.listeners(e))if(S[g]===t&&!S[s]){this.removeListener(e,S);break}}},MessageEvent:q};function ee(e,t,s){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}})),require_extension=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e,t,s){e[t]===void 0?e[t]=[s]:e[t].push(s)}function S(e){let t=Object.create(null),S=Object.create(null),w=!1,E=!1,D=!1,O,k,j=-1,F=-1,L=-1,B=0;for(;B<e.length;B++)if(F=e.charCodeAt(B),O===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(B!==0&&(F===32||F===9))L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);F===44?(g(t,s,S),S=Object.create(null)):O=s,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);else if(k===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(F===32||F===9)L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B),g(S,e.slice(j,L),!0),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),j=L=-1}else if(F===61&&j!==-1&&L===-1)k=e.slice(j,B),j=L=-1;else throw SyntaxError(`Unexpected character at index ${B}`);else if(E){if(s[F]!==1)throw SyntaxError(`Unexpected character at index ${B}`);j===-1?j=B:w||=!0,E=!1}else if(D)if(s[F]===1)j===-1&&(j=B);else if(F===34&&j!==-1)D=!1,L=B;else if(F===92)E=!0;else throw SyntaxError(`Unexpected character at index ${B}`);else if(F===34&&e.charCodeAt(B-1)===61)D=!0;else if(L===-1&&s[F]===1)j===-1&&(j=B);else if(j!==-1&&(F===32||F===9))L===-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);w&&=(s=s.replace(/\\/g,``),!1),g(S,k,s),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),k=void 0,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);if(j===-1||D||F===32||F===9)throw SyntaxError(`Unexpected end of input`);L===-1&&(L=B);let H=e.slice(j,L);return O===void 0?g(t,H,S):(k===void 0?g(S,H,!0):w?g(S,k,H.replace(/\\/g,``)):g(S,k,H),g(t,O,S)),t}function w(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:w,parse:S}})),require_websocket=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`https`),S=__require$1(`http`),w=__require$1(`net`),E=__require$1(`tls`),{randomBytes:D,createHash:O}=__require$1(`crypto`),{Duplex:k,Readable:j}=__require$1(`stream`),{URL:F}=__require$1(`url`),L=require_permessage_deflate(),B=require_receiver(),H=require_sender(),{isBlob:q}=require_validation(),{BINARY_TYPES:ee,CLOSE_TIMEOUT:J,EMPTY_BUFFER:Y,GUID:te,kForOnEventAttribute:ne,kListener:ae,kStatusCode:oe,kWebSocket:se,NOOP:ce}=require_constants$2(),{EventTarget:{addEventListener:ue,removeEventListener:de}}=require_event_target(),{format:fe,parse:me}=require_extension(),{toBuffer:ge}=require_buffer_util(),_e=Symbol(`kAborted`),ve=[8,13],ye=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],Ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var we=class e extends s{constructor(t,s,g){super(),this._binaryType=ee[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=g.autoPong,this._closeTimeout=g.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s==`object`&&s?(g=s,s=[]):s=[s]),Te(this,t,s,g))}get binaryType(){return this._binaryType}set binaryType(e){ee.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,s,g){let S=new B({allowSynchronousEvents:g.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:g.maxPayload,skipUTF8Validation:g.skipUTF8Validation}),w=new H(t,this._extensions,g.generateMask);this._receiver=S,this._sender=w,this._socket=t,S[se]=this,w[se]=this,t[se]=this,S.on(`conclude`,Re),S.on(`drain`,ze),S.on(`error`,Be),S.on(`message`,Ue),S.on(`ping`,We),S.on(`pong`,Ge),w.onerror=Xe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),s.length>0&&t.unshift(s),t.on(`close`,nt),t.on(`data`,rt),t.on(`end`,it),t.on(`error`,at),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[L.extensionName]&&this._extensions[L.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,s){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,s,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.ping(t||Y,s,g)}pong(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.pong(t||Y,s,g)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof s==`function`&&(g=s,s={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}let S={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[L.extensionName]||(S.compress=!1),this._sender.send(t||Y,S,g)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we.prototype,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we.prototype,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we.prototype,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),Object.defineProperty(we.prototype,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(we.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(we.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ne])return t[ae];return null},set(t){for(let t of this.listeners(e))if(t[ne]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[ne]:!0})}})}),we.prototype.addEventListener=ue,we.prototype.removeEventListener=de,t.exports=we;function Te(e,t,s,w){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:J,protocolVersion:ve[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...w,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=E.autoPong,e._closeTimeout=E.closeTimeout,!ve.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${ve.join(`, `)})`);let k;if(t instanceof F)k=t;else try{k=new F(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}k.protocol===`http:`?k.protocol=`ws:`:k.protocol===`https:`&&(k.protocol=`wss:`),e._url=k.href;let j=k.protocol===`wss:`,B=k.protocol===`ws+unix:`,H;if(k.protocol!==`ws:`&&!j&&!B?H=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:B&&!k.pathname?H=`The URL's pathname is empty`:k.hash&&(H=`The URL contains a fragment identifier`),H){let t=SyntaxError(H);if(e._redirects===0)throw t;De(e,t);return}let q=j?443:80,ee=D(16).toString(`base64`),Y=j?g.request:S.request,ne=new Set,ae;if(E.createConnection=E.createConnection||(j?Me:je),E.defaultPort=E.defaultPort||q,E.port=k.port||q,E.host=k.hostname.startsWith(`[`)?k.hostname.slice(1,-1):k.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":ee,Connection:`Upgrade`,Upgrade:`websocket`},E.path=k.pathname+k.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate&&(ae=new L(E.perMessageDeflate===!0?{}:E.perMessageDeflate,!1,E.maxPayload),E.headers[`Sec-WebSocket-Extensions`]=fe({[L.extensionName]:ae.offer()})),s.length){for(let e of s){if(typeof e!=`string`||!Ce.test(e)||ne.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);ne.add(e)}E.headers[`Sec-WebSocket-Protocol`]=s.join(`,`)}if(E.origin&&(E.protocolVersion<13?E.headers[`Sec-WebSocket-Origin`]=E.origin:E.headers.Origin=E.origin),(k.username||k.password)&&(E.auth=`${k.username}:${k.password}`),B){let e=E.path.split(`:`);E.socketPath=e[0],E.path=e[1]}let oe;if(E.followRedirects){if(e._redirects===0){e._originalIpc=B,e._originalSecure=j,e._originalHostOrSocketPath=B?E.socketPath:k.host;let t=w&&w.headers;if(w={...w,headers:{}},t)for(let[e,s]of Object.entries(t))w.headers[e.toLowerCase()]=s}else if(e.listenerCount(`redirect`)===0){let t=B?e._originalIpc?E.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:k.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!j)&&(delete E.headers.authorization,delete E.headers.cookie,t||delete E.headers.host,E.auth=void 0)}E.auth&&!w.headers.authorization&&(w.headers.authorization=`Basic `+Buffer.from(E.auth).toString(`base64`)),oe=e._req=Y(E),e._redirects&&e.emit(`redirect`,e.url,oe)}else oe=e._req=Y(E);E.timeout&&oe.on(`timeout`,()=>{Pe(e,oe,`Opening handshake has timed out`)}),oe.on(`error`,t=>{oe===null||oe[_e]||(oe=e._req=null,De(e,t))}),oe.on(`response`,g=>{let S=g.headers.location,D=g.statusCode;if(S&&E.followRedirects&&D>=300&&D<400){if(++e._redirects>E.maxRedirects){Pe(e,oe,`Maximum redirects exceeded`);return}oe.abort();let g;try{g=new F(S,t)}catch{De(e,SyntaxError(`Invalid URL: ${S}`));return}Te(e,g,s,w)}else e.emit(`unexpected-response`,oe,g)||Pe(e,oe,`Unexpected server response: ${g.statusCode}`)}),oe.on(`upgrade`,(t,s,g)=>{if(e.emit(`upgrade`,t),e.readyState!==we.CONNECTING)return;oe=e._req=null;let S=t.headers.upgrade;if(S===void 0||S.toLowerCase()!==`websocket`){Pe(e,s,`Invalid Upgrade header`);return}let w=O(`sha1`).update(ee+te).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==w){Pe(e,s,`Invalid Sec-WebSocket-Accept header`);return}let D=t.headers[`sec-websocket-protocol`],k;if(D===void 0?ne.size&&(k=`Server sent no subprotocol`):ne.size?ne.has(D)||(k=`Server sent an invalid subprotocol`):k=`Server sent a subprotocol but none was requested`,k){Pe(e,s,k);return}D&&(e._protocol=D);let j=t.headers[`sec-websocket-extensions`];if(j!==void 0){if(!ae){Pe(e,s,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=me(j)}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}let g=Object.keys(t);if(g.length!==1||g[0]!==L.extensionName){Pe(e,s,`Server indicated an extension that was not requested`);return}try{ae.accept(t[L.extensionName])}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[L.extensionName]=ae}e.setSocket(s,g,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest?E.finishRequest(oe,e):oe.end()}function De(e,t){e._readyState=we.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function je(e){return e.path=e.socketPath,w.connect(e)}function Me(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=w.isIP(e.host)?``:e.host),E.connect(e)}function Pe(e,t,s){e._readyState=we.CLOSING;let g=Error(s);Error.captureStackTrace(g,Pe),t.setHeader?(t[_e]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(De,e,g)):(t.destroy(g),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function Ie(e,t,s){if(t){let s=q(t)?t.size:ge(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ye[e.readyState]})`);process.nextTick(s,t)}}function Re(e,t){let s=this[se];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,s._socket[se]!==void 0&&(s._socket.removeListener(`data`,rt),process.nextTick(Ke,s._socket),e===1005?s.close():s.close(e,t))}function ze(){let e=this[se];e.isPaused||e._socket.resume()}function Be(e){let t=this[se];t._socket[se]!==void 0&&(t._socket.removeListener(`data`,rt),process.nextTick(Ke,t._socket),t.close(e[oe])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function Ve(){this[se].emitClose()}function Ue(e,t){this[se].emit(`message`,e,t)}function We(e){let t=this[se];t._autoPong&&t.pong(e,!this._isServer,ce),t.emit(`ping`,e)}function Ge(e){this[se].emit(`pong`,e)}function Ke(e){e.resume()}function Xe(e){let t=this[se];t.readyState!==we.CLOSED&&(t.readyState===we.OPEN&&(t._readyState=we.CLOSING,$e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function $e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function nt(){let e=this[se];if(this.removeListener(`close`,nt),this.removeListener(`data`,rt),this.removeListener(`end`,it),e._readyState=we.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[se]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,Ve),e._receiver.on(`finish`,Ve))}function rt(e){this[se]._receiver.write(e)||this.pause()}function it(){let e=this[se];e._readyState=we.CLOSING,e._receiver.end(),this.end()}function at(){let e=this[se];this.removeListener(`error`,at),this.on(`error`,ce),e&&(e._readyState=we.CLOSING,this.destroy())}})),require_stream=__commonJSMin$1(((e,t)=>{require_websocket();let{Duplex:s}=__require$1(`stream`);function g(e){e.emit(`close`)}function S(){!this.destroyed&&this._writableState.finished&&this.destroy()}function w(e){this.removeListener(`error`,w),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function E(e,t){let E=!0,D=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,s){let g=!s&&D._readableState.objectMode?t.toString():t;D.push(g)||e.pause()}),e.once(`error`,function(e){D.destroyed||(E=!1,D.destroy(e))}),e.once(`close`,function(){D.destroyed||D.push(null)}),D._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(g,D);return}let S=!1;e.once(`error`,function(e){S=!0,s(e)}),e.once(`close`,function(){S||s(t),process.nextTick(g,D)}),E&&e.terminate()},D._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),D._readableState.endEmitted&&D.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},D._read=function(){e.isPaused&&e.resume()},D._write=function(t,s,g){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._write(t,s,g)});return}e.send(t,g)},D.on(`end`,S),D.on(`error`,w),D}t.exports=E})),require_subprotocol=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e){let t=new Set,g=-1,S=-1,w=0;for(;w<e.length;w++){let E=e.charCodeAt(w);if(S===-1&&s[E]===1)g===-1&&(g=w);else if(w!==0&&(E===32||E===9))S===-1&&g!==-1&&(S=w);else if(E===44){if(g===-1)throw SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);let s=e.slice(g,S);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),g=S=-1}else throw SyntaxError(`Unexpected character at index ${w}`)}if(g===-1||S!==-1)throw SyntaxError(`Unexpected end of input`);let E=e.slice(g,w);if(t.has(E))throw SyntaxError(`The "${E}" subprotocol is duplicated`);return t.add(E),t}t.exports={parse:g}})),require_websocket_server=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`http`),{Duplex:S}=__require$1(`stream`),{createHash:w}=__require$1(`crypto`),E=require_extension(),D=require_permessage_deflate(),O=require_subprotocol(),k=require_websocket(),{CLOSE_TIMEOUT:j,GUID:F,kWebSocket:L}=require_constants$2(),B=/^[+/0-9A-Za-z]{22}==$/,H=0,q=1,ee=2;t.exports=class extends s{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=g.createServer((e,t)=>{let s=g.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":`text/plain`}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=J(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,s,g)=>{this.handleUpgrade(t,s,g,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(Y,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Y,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{Y(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,g){t.on(`error`,te);let S=e.headers[`sec-websocket-key`],w=e.headers.upgrade,k=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){ae(this,e,t,405,`Invalid HTTP method`);return}if(w===void 0||w.toLowerCase()!==`websocket`){ae(this,e,t,400,`Invalid Upgrade header`);return}if(S===void 0||!B.test(S)){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(k!==13&&k!==8){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){ne(t,400);return}let j=e.headers[`sec-websocket-protocol`],F=new Set;if(j!==void 0)try{F=O.parse(j)}catch{ae(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let L=e.headers[`sec-websocket-extensions`],H={};if(this.options.perMessageDeflate&&L!==void 0){let s=new D(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=E.parse(L);e[D.extensionName]&&(s.accept(e[D.extensionName]),H[D.extensionName]=s)}catch{ae(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let w={origin:e.headers[`${k===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(w,(w,E,D,O)=>{if(!w)return ne(t,E||401,D,O);this.completeUpgrade(H,S,F,e,t,s,g)});return}if(!this.options.verifyClient(w))return ne(t,401)}this.completeUpgrade(H,S,F,e,t,s,g)}completeUpgrade(e,t,s,g,S,O,k){if(!S.readable||!S.writable)return S.destroy();if(S[L])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return ne(S,503);let j=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${w(`sha1`).update(t+F).digest(`base64`)}`],B=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,g):s.values().next().value;e&&(j.push(`Sec-WebSocket-Protocol: ${e}`),B._protocol=e)}if(e[D.extensionName]){let t=e[D.extensionName].params,s=E.format({[D.extensionName]:[t]});j.push(`Sec-WebSocket-Extensions: ${s}`),B._extensions=e}this.emit(`headers`,j,g),S.write(j.concat(`\r
757
+ `)}var rl=new TextDecoder(`utf-8`,{fatal:!0});function Bi(e){if(!e)return e;let t=!1;for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);if(g>255)return e;g>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);try{return rl.decode(s)}catch{return e}}var ol=[`EACCES`,`escaping sandbox`,`EFBIG`],Ss=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=U.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$$2(this.root,`ReadWriteFs`),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(e,t){let s=this.allowSymlinks?f$1(e,this.canonicalRoot):P$1(e,this.root,this.canonicalRoot);if(s===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return s}validateParent(e,t){let s=U.dirname(e),g=this.resolveAndValidate(s,t);return U.join(g,U.basename(e))}toRealPath(e){let t=c$1(e),s=U.join(this.root,t);return U.resolve(s)}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(s,t);try{if(this.maxFileReadSize>0){let t=await g.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await g.readFile();return new Uint8Array(t)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,s){h$1(e,`write`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,s){h$1(e,`append`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let s=this.resolveAndValidate(t,e);return await I.promises.access(s),!0}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=await I.promises.lstat(s);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){h$1(e,`lstat`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let e=await I.promises.lstat(s);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){h$1(e,`mkdir`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.mkdir(g,{recursive:t?.recursive})}catch(t){let s=t;if(s.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await I.promises.lstat(s)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await I.promises.readdir(s,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){h$1(e,`rm`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.rm(g,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(s){let g=s;if(g.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(g.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(s,e,`rm`)}}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=this.toRealPath(e),S=this.toRealPath(t),w=this.resolveAndValidate(g,e),E=this.resolveAndValidate(S,t);try{await I.promises.cp(w,E,{recursive:s?.recursive??!1,filter:async e=>{try{if(I.lstatSync(e).isSymbolicLink()){let t=await I.promises.realpath(e).catch(()=>null);return t===null?!1:d$1(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){h$1(e,`mv`),h$1(t,`mv`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.validateParent(s,e),w=this.validateParent(g,t);try{if((await I.promises.lstat(S)).isSymbolicLink()){let s=await I.promises.readlink(S),g=U.resolve(U.dirname(w),s);if(!d$1(await I.promises.realpath(g).catch(()=>g),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(s.message?.includes(`EACCES`)||s.message?.includes(`escaping sandbox`))throw t}let E=U.dirname(w);try{await I.promises.mkdir(E,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await I.promises.rename(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(g.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(s,e,`mv`)}try{if(I.lstatSync(w).isDirectory()&&this.findEscapingSymlinks(w).length>0)throw await I.promises.rename(w,S),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return y(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,s){N(e,t,s,ol)}findEscapingSymlinks(e){let t=[];try{let s=I.readdirSync(e);for(let g of s){let s=U.join(e,g);try{let g=I.lstatSync(s);if(g.isSymbolicLink()){let g=I.readlinkSync(s),S=U.resolve(e,g),w;try{w=I.realpathSync(S)}catch{w=S}d$1(w,this.canonicalRoot)||t.push(s)}else g.isDirectory()&&t.push(...this.findEscapingSymlinks(s))}catch{}}}catch{}return t}scanDir(e,t){let s=this.toRealPath(e),g;try{g=this.resolveAndValidate(s,e)}catch{return}try{let s=I.readdirSync(g);for(let S of s){let s=e===`/`?`/${S}`:`${e}/${S}`;t.push(s);let w=U.join(g,S);I.lstatSync(w).isDirectory()&&this.scanDir(s,t)}}catch{}}async chmod(e,t){h$1(e,`chmod`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,s=await I.promises.open(g,e);try{await s.chmod(t)}finally{await s.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);h$1(t,`symlink`);let s=this.toRealPath(t),g=this.validateParent(s,t),S=c$1(t),w=c$1(U.dirname(S)),E=e.startsWith(`/`)?c$1(e):c$1(w===`/`?`/${e}`:`${w}/${e}`),D=U.join(this.canonicalRoot,E),O=U.dirname(g),k=e.startsWith(`/`)?D:U.relative(O,D)||`.`;try{await I.promises.symlink(k,g)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.resolveAndValidate(s,e),w=this.resolveAndValidate(g,t);try{await I.promises.link(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(g.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(g.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(s,e,`link`)}}async readlink(e){h$1(e,`readlink`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let t=await I.promises.readlink(s),g=c$1(e),S=U.dirname(g),w=U.isAbsolute(t)?t:U.resolve(U.dirname(s),t),E=await I.promises.realpath(w).catch(()=>w);if(d$1(E,this.canonicalRoot)){let e=E.slice(this.canonicalRoot.length)||`/`;return S===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:U.relative(S,e)}return U.basename(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){h$1(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let s;try{s=await I.promises.realpath(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(s.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(d$1(s,this.canonicalRoot))return s.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,s){h$1(e,`utimes`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(S,e);try{await g.utimes(t,s)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}},require_quote=__commonJSMin$2(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),require_parse=__commonJSMin$2(((e,t)=>{for(var s=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,g=RegExp(`^`+s+`$`),S=`|&;()<> \\t`,w=`"((\\\\"|[^"])*?)"`,E=`'((\\\\'|[^'])*?)'`,D=/^#$/,O=`'`,k=`"`,j=`$`,F=``,L=4294967296,B=0;B<4;B++)F+=(L*Math.random()).toString(16);var H=RegExp(`^`+F);function q(e,t){for(var s=t.lastIndex,g=[],S;S=t.exec(e);)g.push(S),t.lastIndex===S.index&&(t.lastIndex+=1);return t.lastIndex=s,g}function ee(e,t,s){var g=typeof e==`function`?e(s):e[s];return g===void 0&&s!=``?g=``:g===void 0&&(g=`$`),typeof g==`object`?t+F+JSON.stringify(g)+F:t+g}function J(e,t,F){F||={};var L=F.escape||`\\`,B=`(\\`+L+`['"`+S+`]|[^\\s'"`+S+`])+`,H=q(e,new RegExp([`(`+s+`)`,`(`+B+`|`+w+`|`+E+`)+`].join(`|`),`g`));if(H.length===0)return[];t||={};var J=!1;return H.map(function(s){var S=s[0];if(!S||J)return;if(g.test(S))return{op:S};var w=!1,E=!1,F=``,B=!1,H;function q(){H+=1;var e,s,g=S.charAt(H);if(g===`{`){if(H+=1,S.charAt(H)===`}`)throw Error(`Bad substitution: `+S.slice(H-2,H+1));if(e=S.indexOf(`}`,H),e<0)throw Error(`Bad substitution: `+S.slice(H));s=S.slice(H,e),H=e}else if(/[*@#?$!_-]/.test(g))s=g,H+=1;else{var w=S.slice(H);e=w.match(/[^\w\d_]/),e?(s=w.slice(0,e.index),H+=e.index-1):(s=w,H=S.length)}return ee(t,``,s)}for(H=0;H<S.length;H++){var Y=S.charAt(H);if(B||=!w&&(Y===`*`||Y===`?`),E)F+=Y,E=!1;else if(w)Y===w?w=!1:w==O?F+=Y:Y===L?(H+=1,Y=S.charAt(H),Y===k||Y===L||Y===j?F+=Y:F+=L+Y):Y===j?F+=q():F+=Y;else if(Y===k||Y===O)w=Y;else if(g.test(Y))return{op:S};else if(D.test(Y)){J=!0;var te={comment:e.slice(s.index+H+1)};return F.length?[F,te]:[te]}else Y===L?E=!0:Y===j?F+=q():F+=Y}return B?{op:`glob`,pattern:F}:F}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,s){var g=J(e,t,s);return typeof t==`function`?g.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var s=t.split(RegExp(`(`+F+`.*?`+F+`)`,`g`));return s.length===1?e.concat(s[0]):e.concat(s.filter(Boolean).map(function(e){return H.test(e)?JSON.parse(e.split(F)[1]):e}))},[]):g}})),require_shell_quote=__commonJSMin$2((e=>{e.quote=require_quote(),e.parse=require_parse()}));const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let s=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,s);for(let t=0;t<s;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$1(e,g);for(let t=0;t<g;t++)write$1(e,s.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$1(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((s,g)=>{let S={resolve:s,reject:g,weight:e,priority:t},w=findIndexFromEnd(this._queue,e=>t<=e.priority);w===-1&&e<=this._value?this._dispatchItem(S):this._queue.splice(w+1,0,S)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,s=0){let[g,S]=yield this.acquire(t,s);try{return yield e(g)}finally{S()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let s=this._weightedWaiters[t-1];if(!s)continue;let g=s.findIndex(t=>t.priority<=e);(g===-1?s:s.splice(0,g)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let s=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(s+1,0,t)}function findIndexFromEnd(e,t){for(let s=e.length-1;s>=0;s--)if(t(e[s]))return s;return-1}var __awaiter$1=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let s=0,g,S=``,w=``;for(;s<e.length;s++)g=e[s],S+=g.open,w+=g.close,~t.indexOf(g.close)&&(t=t.replace(g.rgx,g.close+g.open));return S+t+w}function chain(e,t){let s={has:e,keys:t};return s.reset=$.reset.bind(s),s.bold=$.bold.bind(s),s.dim=$.dim.bind(s),s.italic=$.italic.bind(s),s.underline=$.underline.bind(s),s.inverse=$.inverse.bind(s),s.hidden=$.hidden.bind(s),s.strikethrough=$.strikethrough.bind(s),s.black=$.black.bind(s),s.red=$.red.bind(s),s.green=$.green.bind(s),s.yellow=$.yellow.bind(s),s.blue=$.blue.bind(s),s.magenta=$.magenta.bind(s),s.cyan=$.cyan.bind(s),s.white=$.white.bind(s),s.gray=$.gray.bind(s),s.grey=$.grey.bind(s),s.bgBlack=$.bgBlack.bind(s),s.bgRed=$.bgRed.bind(s),s.bgGreen=$.bgGreen.bind(s),s.bgYellow=$.bgYellow.bind(s),s.bgBlue=$.bgBlue.bind(s),s.bgMagenta=$.bgMagenta.bind(s),s.bgCyan=$.bgCyan.bind(s),s.bgWhite=$.bgWhite.bind(s),s}function init(e,t){let s={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(s)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[s]):$.enabled?run([s],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},write=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let s=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,s);for(let t=0;t<s;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint(e,g);for(let t=0;t<g;t++)write(e,s.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&BITS7)*s,s*=128,g<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;break;case Set:if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;break;case Map:if(e.size!==t.size)return!1;for(let s of e.keys())if(!t.has(s)||!equalityDeep(e.get(s),t.get(s)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let s in e)if(!hasProperty(e,s)||!equalityDeep(e[s],t[s]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!equalityDeep(e[s],t[s]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((s,g)=>{g!==this.clientID&&outdatedTimeout<=e-s.lastUpdated&&this.states.has(g)&&t.push(g)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,s=this.meta.get(t),g=s===void 0?0:s.clock+1,S=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:g,lastUpdated:getUnixTime()});let w=[],E=[],D=[],O=[];e===null?O.push(t):S==null?e!=null&&w.push(t):(E.push(t),equalityDeep(S,e)||D.push(t)),(w.length>0||D.length>0||O.length>0)&&this.emit(`change`,[{added:w,updated:D,removed:O},`local`]),this.emit(`update`,[{added:w,updated:E,removed:O},`local`])}setLocalStateField(e,t){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,s)=>{let g=[];for(let s=0;s<t.length;s++){let S=t[s];if(e.states.has(S)){if(e.states.delete(S),S===e.clientID){let t=e.meta.get(S);e.meta.set(S,{clock:t.clock+1,lastUpdated:getUnixTime()})}g.push(S)}}g.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:g},s]),e.emit(`update`,[{added:[],updated:[],removed:g},s]))},encodeAwarenessUpdate=(e,t,s=e.states)=>{let g=t.length,S=createEncoder();writeVarUint(S,g);for(let w=0;w<g;w++){let g=t[w],E=s.get(g)||null,D=e.meta.get(g).clock;writeVarUint(S,g),writeVarUint(S,D),writeVarString(S,JSON.stringify(E))}return toUint8Array(S)},applyAwarenessUpdate=(e,t,s)=>{let g=createDecoder(t),S=getUnixTime(),w=[],E=[],D=[],O=[],k=readVarUint(g);for(let t=0;t<k;t++){let t=readVarUint(g),s=readVarUint(g),k=JSON.parse(readVarString(g)),j=e.meta.get(t),F=e.states.get(t),L=j===void 0?0:j.clock;(L<s||L===s&&k===null&&e.states.has(t))&&(k===null?t===e.clientID&&e.getLocalState()!=null?s++:e.states.delete(t):e.states.set(t,k),e.meta.set(t,{clock:s,lastUpdated:S}),j===void 0&&k!==null?w.push(t):j!==void 0&&k===null?O.push(t):k!==null&&(equalityDeep(k,F)||D.push(t),E.push(t)))}(w.length>0||D.length>0||O.length>0)&&e.emit(`change`,[{added:w,updated:D,removed:O},s]),(w.length>0||E.length>0||O.length>0)&&e.emit(`update`,[{added:w,updated:E,removed:O},s])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,s)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,s))},readSyncStep1=(e,t,s)=>writeSyncStep2(t,s,readVarUint8Array(e)),readSyncStep2=(e,t,s,g)=>{try{applyUpdate(t,readVarUint8Array(e),s)}catch(e){g?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let s=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,s),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,s){let{message:g}=this,S=g.readVarUint(),w=g.length;switch(S){case MessageType.Sync:case MessageType.SyncReply:g.writeVarUint(MessageType.Sync),await this.readSyncMessage(g,e,t,s,S!==MessageType.SyncReply),g.length>w+1&&(s?s(g.toUint8Array()):t&&t.send(g.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,g.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,s);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(g.decoder)});break;case MessageType.BroadcastStateless:{let t=g.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(g.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:g.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${S}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,s,g,S=!0){let w=e.readVarUint(),E=s?.messageAddress??t.name;switch(s&&await s.callbacks.beforeSync(s,{type:w,payload:e.peekVarUint8Array()}),w){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),g&&S)g(new OutgoingMessage(E).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(s){let e=new OutgoingMessage(E).createSyncMessage().writeFirstSyncStepFor(t);s.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(s?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(E).writeSyncStatus(!0);s.send(e.toUint8Array())}else{let e=new OutgoingMessage(E).writeSyncStatus(!1);s.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(s?.readOnly){s.send(new OutgoingMessage(E).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${w}`)}return w}applyQueryAwarenessMessage(e,t,s){let g=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);s&&s(g.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,s,g,S,w=!1,E,D){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=S,this.document=s,this.request=t,this.socketId=g,this.readOnly=w,this.sessionId=E??null,this.providerVersion=D??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),s=t.readVarString(),g=s.indexOf(`\0`),S=g===-1?s:s.substring(0,g);if(S!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${S}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,s)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:s},g){let S=e.concat(t,s);if(g!==null){let t=this.connections.get(g);t&&(e.forEach(e=>t.clients.add(e)),s.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,S);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let s=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(s.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,s,g,S,w={}){this.websocket=e,this.request=t,this.documentProvider=s,this.hooks=g,this.opts=S,this.defaultContext=w,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,s)=>{let g=this.hookPayloads[e],S=await this.documentProvider.createDocument(t,g.request,g.socketId,g.connectionConfig,g.context),w=this.createConnection(this.websocket,S,g,s,g.providerVersion);if(w.onClose((t,s)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),w.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...g,...e,document:S,connection:w,documentName:t},e=>{g.context={...g.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};w.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=w,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{w.handleMessage(e)}),await this.hooks(`connected`,{...g,documentName:t,context:g.context,connection:w})},this.handleQueueingMessage=async(e,t,s)=>{try{let g=new IncomingMessage(e);if(readVarString(g.decoder),!(readVarUint(g.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(g.decoder);let S=readVarString(g.decoder),w=null;hasContent(g.decoder)&&(w=readVarString(g.decoder));let E=t.indexOf(`\0`),D=E===-1?null:t.substring(E+1),O=t;try{let e=this.hookPayloads[t];e.providerVersion=w,await this.hooks(`onConnect`,{...e,documentName:s},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:S,...e,documentName:s},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let g=new OutgoingMessage(O).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(g.toUint8Array()),await this.setUpNewConnection(t,s,D)}catch(e){let s=e||Forbidden,g=new OutgoingMessage(O).writePermissionDenied(s.reason??`permission-denied`);this.websocket.send(g.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),s=t.indexOf(`\0`),g=s===-1?t:t.substring(0,s),S=this.documentConnections[t]??this.documentConnections[g];if(S){S.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,g)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=S.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,s,g,S){let w=new Connection(e,s.request,t,s.socketId,s.context,s.connectionConfig.readOnly,g,S);return w.onClose(async(e,t)=>{await w.waitForPendingMessages();let g={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:s.context,document:e,socketId:s.socketId,documentName:e.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request)};await this.hooks(`onDisconnect`,g),this.callbacks.onClose.forEach(t=>t(e,g))}),w.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),w.beforeHandleMessage((e,g)=>{let S={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:s.context,document:t,socketId:s.socketId,connection:e,documentName:t.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request),update:g};return this.hooks(`beforeHandleMessage`,S)}),w.beforeSync((e,g)=>{let S={clientsCount:t.getConnectionsCount(),context:s.context,document:t,documentName:t.name,connection:e,type:g.type,payload:g.payload};return this.hooks(`beforeSync`,S)}),w}},DirectConnection=class{constructor(e,t,s){this.document=null,this.document=e,this.instance=t,this.context=s??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(s,g,S,w)=>{let E=e.get(s),D=E?.start||Date.now(),O=async()=>{t.has(s)&&await t.get(s),e.delete(s);let S=g();t.set(s,S);let w=await S;return t.delete(s),w};if(E?.timeout&&clearTimeout(E.timeout),S===0||Date.now()-D>=w)return O();e.set(s,{start:D,timeout:setTimeout(O,S),func:O})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let s=e.get(t);if(s)return clearTimeout(s.timeout),s.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let s=e.priority===void 0?100:e.priority,g=t.priority===void 0?100:t.priority;return s>g?-1:s<g?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,s)=>(s.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+s.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,s={}){let g=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},s);return g.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),g}handleDocumentUpdate(e,t,s){let g=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,S=g?.request,w=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},E={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:S?.headers??new Headers,requestParameters:getParameters(S),socketId:g?.socketId??``,update:s,transactionOrigin:t,connection:g,context:w};if(this.hooks(`onChange`,E),shouldSkipStoreHooks(t))return;let D={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:w,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,D)}async createDocument(e,t,s,g,S){if(!e.trim())throw Error(`Document name must not be empty`);let w=this.loadingDocuments.get(e);if(w)return w;let E=this.documents.get(e);if(E)return Promise.resolve(E);let D=this.loadDocument(e,t,s,g,S);this.loadingDocuments.set(e,D);try{let t=await D;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,s,g,S){let w=t.headers,E=getParameters(t),D=S??{},O=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:w,requestParameters:E,connectionConfig:g,context:D,socketId:s,instance:this}),k=new Document(e,{...this.configuration.yDocOptions,...O}),j={instance:this,context:D,connectionConfig:g,document:k,documentName:e,socketId:s,requestHeaders:w,requestParameters:E};try{await this.hooks(`onLoadDocument`,j,e=>{e instanceof Doc?applyUpdate(k,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(k,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(k),t}return k.isLoading=!1,k.onUpdate((e,t,s)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,s)}),await this.hooks(`afterLoadDocument`,j),k.beforeBroadcastStateless((e,t)=>{let s={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,s)}),k.awareness.on(`update`,(t,s)=>{this.hooks(`onAwarenessUpdate`,{document:k,documentName:e,instance:this,...t,transactionOrigin:s,connection:isTransactionOrigin(s)&&s.source===`connection`?s.connection:void 0,awareness:k.awareness,states:awarenessStatesToArray(k.awareness.getStates())})}),k}storeDocumentHooks(e,t,s){let g=`onStoreDocument-${e.name}`;return this.debouncer.debounce(g,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},s?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,s=null){let{extensions:g}=this.configuration,S=Promise.resolve();return g.filter(t=>typeof t[e]==`function`).forEach(g=>{S=S.then(()=>g[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),s&&(S=S.then((...e)=>s(...e)))}),S}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let s=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(s)),await s,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create$1=Object.create,__defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__getOwnPropNames$1=Object.getOwnPropertyNames,__getProtoOf$1=Object.getPrototypeOf,__hasOwnProp$1=Object.prototype.hasOwnProperty,__commonJSMin$1=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps$1=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames$1(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp$1.call(e,D)&&D!==s&&__defProp$1(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc$1(t,D))||g.enumerable});return e},__toESM$1=(e,t,s)=>(s=e==null?{}:__create$1(__getProtoOf$1(e)),__copyProps$1(t||!e||!e.__esModule?__defProp$1(s,`default`,{value:e,enumerable:!0}):s,e)),__require$1=createRequire(import.meta.url),require_constants$2=__commonJSMin$1(((e,t)=>{let s=[`nodebuffer`,`arraybuffer`,`fragments`],g=typeof Blob<`u`;g&&s.push(`blob`),t.exports={BINARY_TYPES:s,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:g,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin$1(((e,t)=>{let{EMPTY_BUFFER:s}=require_constants$2(),g=Buffer[Symbol.species];function S(e,t){if(e.length===0)return s;if(e.length===1)return e[0];let S=Buffer.allocUnsafe(t),w=0;for(let t=0;t<e.length;t++){let s=e[t];S.set(s,w),w+=s.length}return w<t?new g(S.buffer,S.byteOffset,w):S}function w(e,t,s,g,S){for(let w=0;w<S;w++)s[g+w]=e[w]^t[w&3]}function E(e,t){for(let s=0;s<e.length;s++)e[s]^=t[s&3]}function D(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function O(e){if(O.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new g(e):ArrayBuffer.isView(e)?t=new g(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),O.readOnly=!1),t}if(t.exports={concat:S,mask:w,toArrayBuffer:D,toBuffer:O,unmask:E},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require$1(`bufferutil`);t.exports.mask=function(t,s,g,S,E){E<48?w(t,s,g,S,E):e.mask(t,s,g,S,E)},t.exports.unmask=function(t,s){t.length<32?E(t,s):e.unmask(t,s)}}catch{}})),require_limiter=__commonJSMin$1(((e,t)=>{let s=Symbol(`kDone`),g=Symbol(`kRun`);t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[g]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[g]()}[g](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}})),require_permessage_deflate=__commonJSMin$1(((e,t)=>{let s=__require$1(`zlib`),g=require_buffer_util(),S=require_limiter(),{kStatusCode:w}=require_constants$2(),E=Buffer[Symbol.species],D=Buffer.from([0,0,255,255]),O=Symbol(`permessage-deflate`),k=Symbol(`total-length`),j=Symbol(`callback`),F=Symbol(`buffers`),L=Symbol(`error`),B;t.exports=class{constructor(e,t,s){this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,B||=new S(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[j];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,s=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!s)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],t===`client_max_window_bits`){if(s!==!0){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if(t===`server_max_window_bits`){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(s!==!0)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){B.add(g=>{this._decompress(e,t,(e,t)=>{g(),s(e,t)})})}compress(e,t,s){B.add(g=>{this._compress(e,t,(e,t)=>{g(),s(e,t)})})}_decompress(e,t,S){let w=this._isServer?`client`:`server`;if(!this._inflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._inflate=s.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[O]=this,this._inflate[k]=0,this._inflate[F]=[],this._inflate.on(`error`,ee),this._inflate.on(`data`,q)}this._inflate[j]=S,this._inflate.write(e),t&&this._inflate.write(D),this._inflate.flush(()=>{let e=this._inflate[L];if(e){this._inflate.close(),this._inflate=null,S(e);return}let s=g.concat(this._inflate[F],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._inflate.reset()),S(null,s)})}_compress(e,t,S){let w=this._isServer?`server`:`client`;if(!this._deflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._deflate=s.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[k]=0,this._deflate[F]=[],this._deflate.on(`data`,H)}this._deflate[j]=S,this._deflate.write(e),this._deflate.flush(s.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=g.concat(this._deflate[F],this._deflate[k]);t&&(e=new E(e.buffer,e.byteOffset,e.length-4)),this._deflate[j]=null,this._deflate[k]=0,this._deflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._deflate.reset(),S(null,e)})}};function H(e){this[F].push(e),this[k]+=e.length}function q(e){if(this[k]+=e.length,this[O]._maxPayload<1||this[k]<=this[O]._maxPayload){this[F].push(e);return}this[L]=RangeError(`Max payload size exceeded`),this[L].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[L][w]=1009,this.removeListener(`data`,q),this.reset()}function ee(e){if(this[O]._inflate=null,this[L]){this[j](this[L]);return}e[w]=1007,this[j](e)}})),require_validation=__commonJSMin$1(((e,t)=>{let{isUtf8:s}=__require$1(`buffer`),{hasBlob:g}=require_constants$2(),S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function w(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function E(e){let t=e.length,s=0;for(;s<t;)if(!(e[s]&128))s++;else if((e[s]&224)==192){if(s+1===t||(e[s+1]&192)!=128||(e[s]&254)==192)return!1;s+=2}else if((e[s]&240)==224){if(s+2>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||e[s]===224&&(e[s+1]&224)==128||e[s]===237&&(e[s+1]&224)==160)return!1;s+=3}else if((e[s]&248)==240){if(s+3>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||(e[s+3]&192)!=128||e[s]===240&&(e[s+1]&240)==128||e[s]===244&&e[s+1]>143||e[s]>244)return!1;s+=4}else return!1;return!0}function D(e){return g&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:D,isValidStatusCode:w,isValidUTF8:E,tokenChars:S},s)t.exports.isValidUTF8=function(e){return e.length<24?E(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require$1(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?E(t):e(t)}}catch{}})),require_receiver=__commonJSMin$1(((e,t)=>{let{Writable:s}=__require$1(`stream`),g=require_permessage_deflate(),{BINARY_TYPES:S,EMPTY_BUFFER:w,kStatusCode:E,kWebSocket:D}=require_constants$2(),{concat:O,toArrayBuffer:k,unmask:j}=require_buffer_util(),{isValidStatusCode:F,isValidUTF8:L}=require_validation(),B=Buffer[Symbol.species],H=0,q=1,ee=2,J=3,Y=4,te=5,ne=6;t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||S[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[D]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(this._opcode===8&&this._state==0)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new B(t.buffer,t.byteOffset+e,t.length-e),new B(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],g=t.length-e;e>=s.length?t.set(this._buffers.shift(),g):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),g),this._buffers[0]=new B(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let s=(t[0]&64)==64;if(s&&!this._extensions[g.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);if(s>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=s*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&j(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[g.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(s)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let g;g=this._binaryType===`nodebuffer`?O(s,t):this._binaryType===`arraybuffer`?k(O(s,t)):this._binaryType===`blob`?new Blob(s):s,this._allowSynchronousEvents?(this.emit(`message`,g,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!0),this._state=0,this.startLoop(e)}))}else{let g=O(s,t);if(!this._skipUTF8Validation&&!L(g)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,g,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,w),this.end();else{let s=e.readUInt16BE(0);if(!F(s)){t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let g=new B(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!L(g)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,s,g),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,s,g,S){this._loop=!1,this._errored=!0;let w=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(w,this.createError),w.code=S,w[E]=g,w}}})),require_sender=__commonJSMin$1(((e,t)=>{let{Duplex:s}=__require$1(`stream`),{randomFillSync:g}=__require$1(`crypto`),S=require_permessage_deflate(),{EMPTY_BUFFER:w,kWebSocket:E,NOOP:D}=require_constants$2(),{isBlob:O,isValidStatusCode:k}=require_validation(),{mask:j,toBuffer:F}=require_buffer_util(),L=Symbol(`kByteLength`),B=Buffer.alloc(4),H=8*1024,q,ee=H,J=0,Y=1,te=2;t.exports=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=D,this[E]=void 0}static frame(e,t){let s,S=!1,w=2,E=!1;t.mask&&(s=t.maskBuffer||B,t.generateMask?t.generateMask(s):(ee===H&&(q===void 0&&(q=Buffer.alloc(H)),g(q,0,H),ee=0),s[0]=q[ee++],s[1]=q[ee++],s[2]=q[ee++],s[3]=q[ee++]),E=(s[0]|s[1]|s[2]|s[3])===0,w=6);let D;typeof e==`string`?(!t.mask||E)&&t[L]!==void 0?D=t[L]:(e=Buffer.from(e),D=e.length):(D=e.length,S=t.mask&&t.readOnly&&!E);let O=D;D>=65536?(w+=8,O=127):D>125&&(w+=2,O=126);let k=Buffer.allocUnsafe(S?D+w:w);return k[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(k[0]|=64),k[1]=O,O===126?k.writeUInt16BE(D,2):O===127&&(k[2]=k[3]=0,k.writeUIntBE(D,4,6)),!t.mask||(k[1]|=128,k[w-4]=s[0],k[w-3]=s[1],k[w-2]=s[2],k[w-1]=s[3],E)?[k,e]:S?(j(e,s,k,w,D),[k]):(j(e,s,e,0,D),[k,e])}close(t,s,g,S){let E;if(t===void 0)E=w;else if(typeof t!=`number`||!k(t))throw TypeError(`First argument must be a valid error code number`);else if(s===void 0||!s.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(t,0);else{let e=Buffer.byteLength(s);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);E=Buffer.allocUnsafe(2+e),E.writeUInt16BE(t,0),typeof s==`string`?E.write(s,2):E.set(s,2)}let D={[L]:E.length,fin:!0,generateMask:this._generateMask,mask:g,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(E,D),S):this.enqueue([this.dispatch,E,!1,D,S])}ping(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}pong(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}send(e,t,s){let g=this._extensions[S.extensionName],w=t.binary?2:1,E=t.compress,D,k;typeof e==`string`?(D=Buffer.byteLength(e),k=!1):O(e)?(D=e.size,k=!1):(e=F(e),D=e.length,k=F.readOnly),this._firstFragment?(this._firstFragment=!1,E&&g&&g.params[g._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(E=D>=g._threshold),this._compress=E):(E=!1,w=0),t.fin&&(this._firstFragment=!0);let j={[L]:D,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:w,readOnly:k,rsv1:E};O(e)?this._state===0?this.getBlobData(e,this._compress,j,s):this.enqueue([this.getBlobData,e,this._compress,j,s]):this._state===0?this.dispatch(e,this._compress,j,s):this.enqueue([this.dispatch,e,this._compress,j,s])}getBlobData(t,s,g,S){this._bufferedBytes+=g[L],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(ne,this,e,S);return}this._bufferedBytes-=g[L];let w=F(t);s?this.dispatch(w,s,g,S):(this._state=0,this.sendFrame(e.frame(w,g),S),this.dequeue())}).catch(e=>{process.nextTick(ae,this,e,S)})}dispatch(t,s,g,w){if(!s){this.sendFrame(e.frame(t,g),w);return}let E=this._extensions[S.extensionName];this._bufferedBytes+=g[L],this._state=1,E.compress(t,g.fin,(t,s)=>{if(this._socket.destroyed){ne(this,Error(`The socket was closed while data was being compressed`),w);return}this._bufferedBytes-=g[L],this._state=0,g.readOnly=!1,this.sendFrame(e.frame(s,g),w),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][L],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][L],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function ne(e,t,s){typeof s==`function`&&s(t);for(let s=0;s<e._queue.length;s++){let g=e._queue[s],S=g[g.length-1];typeof S==`function`&&S(t)}}function ae(e,t,s){ne(e,t,s),e.onerror(t)}})),require_event_target=__commonJSMin$1(((e,t)=>{let{kForOnEventAttribute:s,kListener:g}=require_constants$2(),S=Symbol(`kCode`),w=Symbol(`kData`),E=Symbol(`kError`),D=Symbol(`kMessage`),O=Symbol(`kReason`),k=Symbol(`kTarget`),j=Symbol(`kType`),F=Symbol(`kWasClean`);var L=class{constructor(e){this[k]=null,this[j]=e}get target(){return this[k]}get type(){return this[j]}};Object.defineProperty(L.prototype,`target`,{enumerable:!0}),Object.defineProperty(L.prototype,`type`,{enumerable:!0});var B=class extends L{constructor(e,t={}){super(e),this[S]=t.code===void 0?0:t.code,this[O]=t.reason===void 0?``:t.reason,this[F]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[S]}get reason(){return this[O]}get wasClean(){return this[F]}};Object.defineProperty(B.prototype,`code`,{enumerable:!0}),Object.defineProperty(B.prototype,`reason`,{enumerable:!0}),Object.defineProperty(B.prototype,`wasClean`,{enumerable:!0});var H=class extends L{constructor(e,t={}){super(e),this[E]=t.error===void 0?null:t.error,this[D]=t.message===void 0?``:t.message}get error(){return this[E]}get message(){return this[D]}};Object.defineProperty(H.prototype,`error`,{enumerable:!0}),Object.defineProperty(H.prototype,`message`,{enumerable:!0});var q=class extends L{constructor(e,t={}){super(e),this[w]=t.data===void 0?null:t.data}get data(){return this[w]}};Object.defineProperty(q.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:B,ErrorEvent:H,Event:L,EventTarget:{addEventListener(e,t,S={}){for(let w of this.listeners(e))if(!S[s]&&w[g]===t&&!w[s])return;let w;if(e===`message`)w=function(e,s){let g=new q(`message`,{data:s?e:e.toString()});g[k]=this,ee(t,this,g)};else if(e===`close`)w=function(e,s){let g=new B(`close`,{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});g[k]=this,ee(t,this,g)};else if(e===`error`)w=function(e){let s=new H(`error`,{error:e,message:e.message});s[k]=this,ee(t,this,s)};else if(e===`open`)w=function(){let e=new L(`open`);e[k]=this,ee(t,this,e)};else return;w[s]=!!S[s],w[g]=t,S.once?this.once(e,w):this.on(e,w)},removeEventListener(e,t){for(let S of this.listeners(e))if(S[g]===t&&!S[s]){this.removeListener(e,S);break}}},MessageEvent:q};function ee(e,t,s){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}})),require_extension=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e,t,s){e[t]===void 0?e[t]=[s]:e[t].push(s)}function S(e){let t=Object.create(null),S=Object.create(null),w=!1,E=!1,D=!1,O,k,j=-1,F=-1,L=-1,B=0;for(;B<e.length;B++)if(F=e.charCodeAt(B),O===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(B!==0&&(F===32||F===9))L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);F===44?(g(t,s,S),S=Object.create(null)):O=s,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);else if(k===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(F===32||F===9)L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B),g(S,e.slice(j,L),!0),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),j=L=-1}else if(F===61&&j!==-1&&L===-1)k=e.slice(j,B),j=L=-1;else throw SyntaxError(`Unexpected character at index ${B}`);else if(E){if(s[F]!==1)throw SyntaxError(`Unexpected character at index ${B}`);j===-1?j=B:w||=!0,E=!1}else if(D)if(s[F]===1)j===-1&&(j=B);else if(F===34&&j!==-1)D=!1,L=B;else if(F===92)E=!0;else throw SyntaxError(`Unexpected character at index ${B}`);else if(F===34&&e.charCodeAt(B-1)===61)D=!0;else if(L===-1&&s[F]===1)j===-1&&(j=B);else if(j!==-1&&(F===32||F===9))L===-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);w&&=(s=s.replace(/\\/g,``),!1),g(S,k,s),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),k=void 0,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);if(j===-1||D||F===32||F===9)throw SyntaxError(`Unexpected end of input`);L===-1&&(L=B);let H=e.slice(j,L);return O===void 0?g(t,H,S):(k===void 0?g(S,H,!0):w?g(S,k,H.replace(/\\/g,``)):g(S,k,H),g(t,O,S)),t}function w(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:w,parse:S}})),require_websocket=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`https`),S=__require$1(`http`),w=__require$1(`net`),E=__require$1(`tls`),{randomBytes:D,createHash:O}=__require$1(`crypto`),{Duplex:k,Readable:j}=__require$1(`stream`),{URL:F}=__require$1(`url`),L=require_permessage_deflate(),B=require_receiver(),H=require_sender(),{isBlob:q}=require_validation(),{BINARY_TYPES:ee,CLOSE_TIMEOUT:J,EMPTY_BUFFER:Y,GUID:te,kForOnEventAttribute:ne,kListener:ae,kStatusCode:oe,kWebSocket:se,NOOP:ce}=require_constants$2(),{EventTarget:{addEventListener:ue,removeEventListener:de}}=require_event_target(),{format:fe,parse:me}=require_extension(),{toBuffer:ge}=require_buffer_util(),_e=Symbol(`kAborted`),ve=[8,13],ye=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],Ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var we=class e extends s{constructor(t,s,g){super(),this._binaryType=ee[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=g.autoPong,this._closeTimeout=g.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s==`object`&&s?(g=s,s=[]):s=[s]),Te(this,t,s,g))}get binaryType(){return this._binaryType}set binaryType(e){ee.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,s,g){let S=new B({allowSynchronousEvents:g.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:g.maxPayload,skipUTF8Validation:g.skipUTF8Validation}),w=new H(t,this._extensions,g.generateMask);this._receiver=S,this._sender=w,this._socket=t,S[se]=this,w[se]=this,t[se]=this,S.on(`conclude`,Re),S.on(`drain`,ze),S.on(`error`,Be),S.on(`message`,Ue),S.on(`ping`,We),S.on(`pong`,Ge),w.onerror=Xe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),s.length>0&&t.unshift(s),t.on(`close`,nt),t.on(`data`,rt),t.on(`end`,it),t.on(`error`,at),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[L.extensionName]&&this._extensions[L.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,s){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,s,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.ping(t||Y,s,g)}pong(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.pong(t||Y,s,g)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof s==`function`&&(g=s,s={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}let S={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[L.extensionName]||(S.compress=!1),this._sender.send(t||Y,S,g)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we.prototype,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we.prototype,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we.prototype,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),Object.defineProperty(we.prototype,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(we.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(we.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ne])return t[ae];return null},set(t){for(let t of this.listeners(e))if(t[ne]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[ne]:!0})}})}),we.prototype.addEventListener=ue,we.prototype.removeEventListener=de,t.exports=we;function Te(e,t,s,w){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:J,protocolVersion:ve[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...w,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=E.autoPong,e._closeTimeout=E.closeTimeout,!ve.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${ve.join(`, `)})`);let k;if(t instanceof F)k=t;else try{k=new F(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}k.protocol===`http:`?k.protocol=`ws:`:k.protocol===`https:`&&(k.protocol=`wss:`),e._url=k.href;let j=k.protocol===`wss:`,B=k.protocol===`ws+unix:`,H;if(k.protocol!==`ws:`&&!j&&!B?H=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:B&&!k.pathname?H=`The URL's pathname is empty`:k.hash&&(H=`The URL contains a fragment identifier`),H){let t=SyntaxError(H);if(e._redirects===0)throw t;De(e,t);return}let q=j?443:80,ee=D(16).toString(`base64`),Y=j?g.request:S.request,ne=new Set,ae;if(E.createConnection=E.createConnection||(j?Me:je),E.defaultPort=E.defaultPort||q,E.port=k.port||q,E.host=k.hostname.startsWith(`[`)?k.hostname.slice(1,-1):k.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":ee,Connection:`Upgrade`,Upgrade:`websocket`},E.path=k.pathname+k.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate&&(ae=new L(E.perMessageDeflate===!0?{}:E.perMessageDeflate,!1,E.maxPayload),E.headers[`Sec-WebSocket-Extensions`]=fe({[L.extensionName]:ae.offer()})),s.length){for(let e of s){if(typeof e!=`string`||!Ce.test(e)||ne.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);ne.add(e)}E.headers[`Sec-WebSocket-Protocol`]=s.join(`,`)}if(E.origin&&(E.protocolVersion<13?E.headers[`Sec-WebSocket-Origin`]=E.origin:E.headers.Origin=E.origin),(k.username||k.password)&&(E.auth=`${k.username}:${k.password}`),B){let e=E.path.split(`:`);E.socketPath=e[0],E.path=e[1]}let oe;if(E.followRedirects){if(e._redirects===0){e._originalIpc=B,e._originalSecure=j,e._originalHostOrSocketPath=B?E.socketPath:k.host;let t=w&&w.headers;if(w={...w,headers:{}},t)for(let[e,s]of Object.entries(t))w.headers[e.toLowerCase()]=s}else if(e.listenerCount(`redirect`)===0){let t=B?e._originalIpc?E.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:k.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!j)&&(delete E.headers.authorization,delete E.headers.cookie,t||delete E.headers.host,E.auth=void 0)}E.auth&&!w.headers.authorization&&(w.headers.authorization=`Basic `+Buffer.from(E.auth).toString(`base64`)),oe=e._req=Y(E),e._redirects&&e.emit(`redirect`,e.url,oe)}else oe=e._req=Y(E);E.timeout&&oe.on(`timeout`,()=>{Pe(e,oe,`Opening handshake has timed out`)}),oe.on(`error`,t=>{oe===null||oe[_e]||(oe=e._req=null,De(e,t))}),oe.on(`response`,g=>{let S=g.headers.location,D=g.statusCode;if(S&&E.followRedirects&&D>=300&&D<400){if(++e._redirects>E.maxRedirects){Pe(e,oe,`Maximum redirects exceeded`);return}oe.abort();let g;try{g=new F(S,t)}catch{De(e,SyntaxError(`Invalid URL: ${S}`));return}Te(e,g,s,w)}else e.emit(`unexpected-response`,oe,g)||Pe(e,oe,`Unexpected server response: ${g.statusCode}`)}),oe.on(`upgrade`,(t,s,g)=>{if(e.emit(`upgrade`,t),e.readyState!==we.CONNECTING)return;oe=e._req=null;let S=t.headers.upgrade;if(S===void 0||S.toLowerCase()!==`websocket`){Pe(e,s,`Invalid Upgrade header`);return}let w=O(`sha1`).update(ee+te).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==w){Pe(e,s,`Invalid Sec-WebSocket-Accept header`);return}let D=t.headers[`sec-websocket-protocol`],k;if(D===void 0?ne.size&&(k=`Server sent no subprotocol`):ne.size?ne.has(D)||(k=`Server sent an invalid subprotocol`):k=`Server sent a subprotocol but none was requested`,k){Pe(e,s,k);return}D&&(e._protocol=D);let j=t.headers[`sec-websocket-extensions`];if(j!==void 0){if(!ae){Pe(e,s,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=me(j)}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}let g=Object.keys(t);if(g.length!==1||g[0]!==L.extensionName){Pe(e,s,`Server indicated an extension that was not requested`);return}try{ae.accept(t[L.extensionName])}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[L.extensionName]=ae}e.setSocket(s,g,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest?E.finishRequest(oe,e):oe.end()}function De(e,t){e._readyState=we.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function je(e){return e.path=e.socketPath,w.connect(e)}function Me(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=w.isIP(e.host)?``:e.host),E.connect(e)}function Pe(e,t,s){e._readyState=we.CLOSING;let g=Error(s);Error.captureStackTrace(g,Pe),t.setHeader?(t[_e]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(De,e,g)):(t.destroy(g),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function Ie(e,t,s){if(t){let s=q(t)?t.size:ge(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ye[e.readyState]})`);process.nextTick(s,t)}}function Re(e,t){let s=this[se];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,s._socket[se]!==void 0&&(s._socket.removeListener(`data`,rt),process.nextTick(Ke,s._socket),e===1005?s.close():s.close(e,t))}function ze(){let e=this[se];e.isPaused||e._socket.resume()}function Be(e){let t=this[se];t._socket[se]!==void 0&&(t._socket.removeListener(`data`,rt),process.nextTick(Ke,t._socket),t.close(e[oe])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function Ve(){this[se].emitClose()}function Ue(e,t){this[se].emit(`message`,e,t)}function We(e){let t=this[se];t._autoPong&&t.pong(e,!this._isServer,ce),t.emit(`ping`,e)}function Ge(e){this[se].emit(`pong`,e)}function Ke(e){e.resume()}function Xe(e){let t=this[se];t.readyState!==we.CLOSED&&(t.readyState===we.OPEN&&(t._readyState=we.CLOSING,$e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function $e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function nt(){let e=this[se];if(this.removeListener(`close`,nt),this.removeListener(`data`,rt),this.removeListener(`end`,it),e._readyState=we.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[se]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,Ve),e._receiver.on(`finish`,Ve))}function rt(e){this[se]._receiver.write(e)||this.pause()}function it(){let e=this[se];e._readyState=we.CLOSING,e._receiver.end(),this.end()}function at(){let e=this[se];this.removeListener(`error`,at),this.on(`error`,ce),e&&(e._readyState=we.CLOSING,this.destroy())}})),require_stream=__commonJSMin$1(((e,t)=>{require_websocket();let{Duplex:s}=__require$1(`stream`);function g(e){e.emit(`close`)}function S(){!this.destroyed&&this._writableState.finished&&this.destroy()}function w(e){this.removeListener(`error`,w),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function E(e,t){let E=!0,D=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,s){let g=!s&&D._readableState.objectMode?t.toString():t;D.push(g)||e.pause()}),e.once(`error`,function(e){D.destroyed||(E=!1,D.destroy(e))}),e.once(`close`,function(){D.destroyed||D.push(null)}),D._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(g,D);return}let S=!1;e.once(`error`,function(e){S=!0,s(e)}),e.once(`close`,function(){S||s(t),process.nextTick(g,D)}),E&&e.terminate()},D._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),D._readableState.endEmitted&&D.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},D._read=function(){e.isPaused&&e.resume()},D._write=function(t,s,g){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._write(t,s,g)});return}e.send(t,g)},D.on(`end`,S),D.on(`error`,w),D}t.exports=E})),require_subprotocol=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e){let t=new Set,g=-1,S=-1,w=0;for(;w<e.length;w++){let E=e.charCodeAt(w);if(S===-1&&s[E]===1)g===-1&&(g=w);else if(w!==0&&(E===32||E===9))S===-1&&g!==-1&&(S=w);else if(E===44){if(g===-1)throw SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);let s=e.slice(g,S);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),g=S=-1}else throw SyntaxError(`Unexpected character at index ${w}`)}if(g===-1||S!==-1)throw SyntaxError(`Unexpected end of input`);let E=e.slice(g,w);if(t.has(E))throw SyntaxError(`The "${E}" subprotocol is duplicated`);return t.add(E),t}t.exports={parse:g}})),require_websocket_server=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`http`),{Duplex:S}=__require$1(`stream`),{createHash:w}=__require$1(`crypto`),E=require_extension(),D=require_permessage_deflate(),O=require_subprotocol(),k=require_websocket(),{CLOSE_TIMEOUT:j,GUID:F,kWebSocket:L}=require_constants$2(),B=/^[+/0-9A-Za-z]{22}==$/,H=0,q=1,ee=2;t.exports=class extends s{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=g.createServer((e,t)=>{let s=g.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":`text/plain`}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=J(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,s,g)=>{this.handleUpgrade(t,s,g,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(Y,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Y,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{Y(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,g){t.on(`error`,te);let S=e.headers[`sec-websocket-key`],w=e.headers.upgrade,k=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){ae(this,e,t,405,`Invalid HTTP method`);return}if(w===void 0||w.toLowerCase()!==`websocket`){ae(this,e,t,400,`Invalid Upgrade header`);return}if(S===void 0||!B.test(S)){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(k!==13&&k!==8){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){ne(t,400);return}let j=e.headers[`sec-websocket-protocol`],F=new Set;if(j!==void 0)try{F=O.parse(j)}catch{ae(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let L=e.headers[`sec-websocket-extensions`],H={};if(this.options.perMessageDeflate&&L!==void 0){let s=new D(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=E.parse(L);e[D.extensionName]&&(s.accept(e[D.extensionName]),H[D.extensionName]=s)}catch{ae(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let w={origin:e.headers[`${k===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(w,(w,E,D,O)=>{if(!w)return ne(t,E||401,D,O);this.completeUpgrade(H,S,F,e,t,s,g)});return}if(!this.options.verifyClient(w))return ne(t,401)}this.completeUpgrade(H,S,F,e,t,s,g)}completeUpgrade(e,t,s,g,S,O,k){if(!S.readable||!S.writable)return S.destroy();if(S[L])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return ne(S,503);let j=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${w(`sha1`).update(t+F).digest(`base64`)}`],B=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,g):s.values().next().value;e&&(j.push(`Sec-WebSocket-Protocol: ${e}`),B._protocol=e)}if(e[D.extensionName]){let t=e[D.extensionName].params,s=E.format({[D.extensionName]:[t]});j.push(`Sec-WebSocket-Extensions: ${s}`),B._extensions=e}this.emit(`headers`,j,g),S.write(j.concat(`\r
758
758
  `).join(`\r
759
759
  `)),S.removeListener(`error`,te),B.setSocket(S,O,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(B),B.on(`close`,()=>{this.clients.delete(B),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Y,this)})),k(B,g)}};function J(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}function Y(e){e._state=2,e.emit(`close`)}function te(){this.destroy()}function ne(e,t,s,S){s||=g.STATUS_CODES[t],S={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(s),...S},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${g.STATUS_CODES[t]}\r\n`+Object.keys(S).map(e=>`${e}: ${S[e]}`).join(`\r
760
760
  `)+`\r
@@ -1937,7 +1937,7 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
1937
1937
  `)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1}=e,Ge=createConcurrencyGuard(),Ke=new Map,Xe=createSingleFlight(),$e=null;function nt(){let e=j?.();return e instanceof Map?e:null}function rt(e){let t=nt();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function it(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)rt(resolve(g,t.slice(0,e).join(`/`)))}function at(e){let t=nt();t&&removeFolderIndexEntries(t,e)}function st(e,t){let s=nt();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&rt(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function vt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1938
1938
  `)}function Tt(){$e=null}F?.(Tt);let Et=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Dt(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return isWithinDir(s,t)?s:null}function jt(e){let t=Dt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Dt(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$6.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$6.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function Kt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function $t(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function en(e){if(!De)return!1;let t=isSupportedDocFile(e)?e:`${e}${getDocExtension(e)}`;return De.isExcluded(t)}function jr(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?nu:g,`.ok`,`skills`);for(let g of lu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(iu(t.source_folder,t.name))}catch(e){log$6.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||en(t)||e.add(t);return e}let Mr=e=>existsSync(resolve(g,e));function Fr(e,t){en(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function Ir(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let Lr=Ir(),zr=e=>e.endsWith(`.`)?e:`${e}.`;function Br(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:zr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:zr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:zr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:zr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:zr(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Vr(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.set(s,e.getText(`source`).toString())}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return g}function Hr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&&registerWrite(e,contentHash(E))}}function Ur(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Wr(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Gr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Kr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=Jr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function qr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function Jr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=qr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Yr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=qr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Xr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Wr(g);if(typeof s!=`string`)continue;let S=qr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Zr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Qr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Yr(S.docName,s):S;e.rewrites!==0&&(Gr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function ji(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Hi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ui(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Gi(e,t){return Lr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Xr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Zr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Qr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Ki(e,s){return Lr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Xr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Zr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Vr([w])).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Qr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Yi(e,s,S,E){return Lr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ui(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Hi(k)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Xr(L);Zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Qr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Wr(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Wr(t);typeof e==`string`&&Jr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Zr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ur([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Kr(e,H,L):Jr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Gr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Vr([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>e!==t);t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID$1(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=Jr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Hr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Xi(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Zi(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function ka(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function _s(e){return{value:e.value}}function xs(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Cs(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=ka(S),E=g||!w.response?w.response:_s(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),xs(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=ka(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}xs(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function Ts(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Ds(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=ka(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Os(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ks=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=ka(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),xs(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Kt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=$t(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),As=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Xi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&&registerDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=ka(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Zi({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),xs(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Kt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();Fr(O,ce);let ue=await validateMermaidFences(ce,O),de=jr();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,Mr),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=$t(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Ns=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=ka(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
1939
1939
  `),S=s.nextFenced+(g?`
1940
- `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Kt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=$t(ne);Fr(D,te.dc.document.getText(`source`).toString());let ye=jr();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,Mr);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ps(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Is=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ps(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ps(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$6.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=jr();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=jr();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=jr();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(jr(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),oc=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Xi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=ka(J);recordContributor(j,F,L,B,void 0,Zi({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Kt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=ka(J),ye=Y.dc.document.getText(`source`).toString();Fr(j,ye);let Ce=await validateMermaidFences(ye,j),we=jr();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,Mr),De=$t(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Xi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Zi({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Kt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$6.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$6.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$6.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$6.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$6.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(nu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Xi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$6.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Il(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function gc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=ka(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=ka(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$6.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Kt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$6.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$6.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$6.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function wc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$6.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ec=1048576,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$6.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$6.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=w===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(E)||isConfigDoc(E))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!k)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,B);try{tracedCpSync(D,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of H)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&H.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:B,duplicatedDocNames:H},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Dt(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Ki(E,D):await Gi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Tt();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$6.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let k=O===`file`?[stripDocExtension(E)]:Hi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):De.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Yi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Tt();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$6.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Xi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?ji(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[stripDocExtension(D)]:Hi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),Tt();for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ic=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Tt(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(Tt(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Rc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function zc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Xi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$6.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$6.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=await fileTypeFromFile(w),ae=ne?.mime,oe=ne?.ext;if(!ae){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(ae=`image/svg+xml`,oe=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:ae??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let se;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=oe??t??``;se=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else se=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,se),S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:ae??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$6.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:se,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc=`local-op-clone`,Gc=withValidation(LocalOpCloneRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Wc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Wc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Wc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$6.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await qc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$6.error({err:e,handler:Wc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function qc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$6.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$6.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Jc=`local-op-ok-init`,Yc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Jc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Jc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc});return}if(!Ge.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Jc})}finally{Ge.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`/api/local-op/auth/login`,Zc=`/api/local-op/auth/status`,Qc=`/api/local-op/auth/repos`,$c=`/api/local-op/auth/signout`,nl=null,il=`local-op-auth-login`,al=withValidation(LocalOpAuthHostRequestSchema,cl,{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})});async function cl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){let e=nl;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:il,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),nl=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,il),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});nl=w;let E=()=>{w.cancel(),nl===w&&(nl=null,Ge.release(Xc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}nl===w&&(nl=null,Ge.release(Xc))})}let ll=`local-op-auth-status`,ul=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:ll,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1940
+ `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Kt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=$t(ne);Fr(D,te.dc.document.getText(`source`).toString());let ye=jr();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,Mr);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ps(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Is=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ps(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ps(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$6.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=jr();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=jr();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=jr();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(jr(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),oc=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Xi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=ka(J);recordContributor(j,F,L,B,void 0,Zi({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Kt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=ka(J),ye=Y.dc.document.getText(`source`).toString();Fr(j,ye);let Ce=await validateMermaidFences(ye,j),we=jr();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,Mr),De=$t(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Xi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Zi({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Kt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$6.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$6.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$6.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$6.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$6.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(nu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Xi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$6.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Il(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function gc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=ka(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=ka(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$6.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Kt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$6.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$6.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$6.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function wc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$6.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ec=1048576,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$6.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$6.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=w===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(E)||isConfigDoc(E))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!k)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,B);try{tracedCpSync(D,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of H)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&H.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:B,duplicatedDocNames:H},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Dt(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Ki(E,D):await Gi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Tt();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$6.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let k=O===`file`?[stripDocExtension(E)]:Hi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):De.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Yi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Tt();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$6.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Xi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?ji(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[stripDocExtension(D)]:Hi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),Tt();for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ic=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Tt(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(Tt(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Rc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function zc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Xi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$6.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$6.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$6.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc=`local-op-clone`,Gc=withValidation(LocalOpCloneRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Wc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Wc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Wc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$6.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await qc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$6.error({err:e,handler:Wc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function qc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$6.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$6.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Jc=`local-op-ok-init`,Yc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Jc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Jc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc});return}if(!Ge.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Jc})}finally{Ge.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`/api/local-op/auth/login`,Zc=`/api/local-op/auth/status`,Qc=`/api/local-op/auth/repos`,$c=`/api/local-op/auth/signout`,nl=null,il=`local-op-auth-login`,al=withValidation(LocalOpAuthHostRequestSchema,cl,{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})});async function cl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){let e=nl;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:il,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),nl=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,il),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});nl=w;let E=()=>{w.cancel(),nl===w&&(nl=null,Ge.release(Xc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}nl===w&&(nl=null,Ge.release(Xc))})}let ll=`local-op-auth-status`,ul=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:ll,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1941
1941
  `).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:ll}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:ll})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:ll,cause:e})}finally{Ge.release(Zc)}},{handler:ll,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ll})}),dl=`local-op-auth-repos`,fl=withValidation(LocalOpAuthHostRequestSchema,pl,{handler:dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dl})});async function pl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:dl,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,dl),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Hc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1942
1942
  `);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$6.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Qc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Dl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ol=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let jl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Et.probeAll)}catch(e){t.headersSent||(log$6.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Fl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Il(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Bl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Il(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Wl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)]);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)]);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)]);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)]);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)]);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ru(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$6.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),sd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$6.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$6.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(Ce);if(e===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readOriginGitHubRepo(Ce);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(Ce,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),fd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function pd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let md=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await pd([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),hd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await pd([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),gd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await pd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),_d=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),vd=Ce?getLocalDir(Ce):null;async function yd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}vd&&clearArmedPaneTarget(vd),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:vd?readServerLock(vd)?.port??0:0,paneTarget:vd?readArmedPaneTarget(vd):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let bd=`local-op-embeddings-set-key`,xd=`local-op-embeddings-clear-key`,Sd=`/api/local-op/embeddings`,Cd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:bd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bd,cause:e})}finally{Ge.release(Sd)}},{handler:bd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bd})}),wd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xd,cause:e})}finally{Ge.release(Sd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Ed={"/api/config":yd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Td,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/git/branch-info":dd,"/api/git/checkout":fd,"/api/share/publish/owners":md,"/api/share/publish/name-check":hd,"/api/share/publish":gd,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":Cd,"/api/local-op/embeddings/clear-key":wd,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":_d};q&&(Ed[`/api/test-reset`]=dc,Ed[`/api/test-flush-git`]=uc,Ed[`/api/test-rescan-backlinks`]=fc,Ed[`/api/test-rescan-files`]=pc);let Dd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Od=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Dd.has(s)||Od.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Ed[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Ed[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$5=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$5.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$5.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$5.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-DdgvPBh6-Dv4DjLoy.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
1943
1943
  `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$5.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$5.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
@@ -3251,4 +3251,4 @@ Incremental by default — don't re-read the whole repo.
3251
3251
  `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await Ce.flushDeferredStores(`discard-stale`),De?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ve.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ve.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Ir.push(`head-watcher`)}function D(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=we.documents.get(S);if(!w)continue;let E=Mt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{en=new SyncEngine({projectDir:s,contentDir:t,contentFilter:me,contentRoot:L,syncEnabled:ne(),credentialArgs:O,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await en.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),en=null}Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}return Lr().then(We,Ge),{hocuspocus:we,sessionManager:Te,cc1Broadcaster:De,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ye,contentFilter:me,basenameIndex:ue,serverInstanceId:se,destroy:Fr,ready:Ke,degraded:Ir,lockDir:ce,get syncEngine(){return en}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-8Lv6A-Xa-DqbpfxSh.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:j,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
3252
3252
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
3253
3253
  `,`utf-8`),t}export{STARTER_PACKS as $,withSpan as $i,isAllowedWorkspaceHostHeader as $n,resolveBundledSkillDir as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spawnDetached as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedMkdirSync as Bi,handleCollabSocketError as Bn,readSkillManagement as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,serializeError as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,skillManagementPath as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,shutdownTelemetry as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,teardownToleranceTelemetryWriter as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedUnlinkSync as Gi,initContent as Gn,reconcile as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRenameSync as Hi,hasGcLogLatch as Hn,readTargetRecordedAt as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,toBroadcasterKey as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,updateLastKnownHash as Ji,initToleranceTelemetryWriter as Jn,registerAllTools as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedWriteFile as Ki,initShadowRepo as Kn,recordContributor as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,tracedAppendFileSync as Li,getMeter as Ln,readProjectLocalSemanticConfig as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,startWatcher as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,streamingProblemEvent as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,spansCurrentPath as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,swapContributors as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateSkillZip as Qi,isAllowedApiOrigin as Qn,resetMetrics as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,tracedLinkSync as Ri,getMetrics as Rn,readServerPackageVersion as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,seedBasenameIndex as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,shadowGit as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRmSync as Ui,incrementCollabSocketFilteredError as Un,readTargetVersion as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedRename as Vi,handleSpawnCursor as Vn,readStateManifest as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRmdirSync as Wi,incrementServerObserverFire as Wn,readUiLock as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,validateAgentId as Xi,installTestLoggers as Xn,releaseUiLock as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,updateUiLockPort as Yi,installPrettyZodErrors as Yn,registerWrite as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,validateCloneInputs as Zi,installUserSkill as Zn,removeLastKnownHash as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,GitDirAccessError as _a,safeSubdir as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeTracker as aa,resolvePackageVersion as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,resolveGitDirDetailed as ba,saveInMemoryCheckpoint as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,LATEST_PROTOCOL_VERSION as ca,restoreLifecycleFromConflictsJson as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,isJSONRPCResultResponse as da,runAuthReposSubprocess as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,withSpanSync as ea,resolveContentDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,atomicWriteFileSync as fa,runAuthStatusSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,writeConfigPatch as ga,safeContentPath as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,withFileLockSync as ha,runWithMcpLogger as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeTargetVersion as ia,resolvePack as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,splitMarkdownBlocks as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spansPreviousPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,isInitializedNotification as la,rewriteMarkdownLinksForDocumentRename as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,resolveConfigPath as ma,runDeviceFlowSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,writeSkillManagement as na,resolveCursorSpawnInvocation as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,McpServer as oa,resolveUiInfo as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,readConfigSafely as pa,runCloneSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedWriteFileSync as qi,initTelemetry as qn,recordSkillInstallEvent as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeStateManifest as ra,resolveLockDir as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,JSONRPCMessageSchema as sa,restoreContributors as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,writeRootGitignoreForNewRepo as ta,resolveCursorBinaryDefault as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,isJSONRPCRequest as ua,rewriteWikiLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,MalformedGitPointerError as va,safetyCheckpoint as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,setActiveSpanAttributes as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,resolveShadowDir as xa,saveVersion as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,parseCheckpoint as ya,sanitizeClientName as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedMkdir as zi,getTracer as zn,readSkillInstallStateSnapshot as zr,commitWipFromTree as zt};
3254
- //# sourceMappingURL=dist-BFJW9DuR.mjs.map
3254
+ //# sourceMappingURL=dist-BoIBsVKQ.mjs.map