@inkeep/open-knowledge 0.8.0-beta.13 → 0.8.0-beta.15
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.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/{chunk-HWBSOZZR-CFFhOzgy.mjs → chunk-HWBSOZZR-B0-Qfe0T.mjs} +3 -3
- package/dist/cli.d.mts +7 -1
- package/dist/cli.mjs +45 -42
- package/dist/constants-Bdd0BBBE.mjs +2 -0
- package/dist/{dist-lSCD8oz8.mjs → dist-D4zoOvWC.mjs} +16 -20
- package/dist/dist-LiBfDl2k.mjs +1 -0
- package/dist/{flag-coverage-QT4N2Z44-CQ2g5NLf.mjs → flag-coverage-QT4N2Z44-g6MqLsWy.mjs} +2 -2
- package/dist/{gh-detect-CmRIH7je.mjs → gh-detect-jLwJ9bOe.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-BNQrk71c.mjs → init-CL8mchva.mjs} +13 -13
- package/dist/init-Cn4QQisC.mjs +1 -0
- package/dist/{js-exec-M6UR76J5-BssUQ3SC.mjs → js-exec-M6UR76J5-D6BVeQcA.mjs} +4 -4
- package/dist/loader-Bd8DLr1D.mjs +1 -0
- package/dist/{loader-cKgl9-hM.mjs → loader-CD9Cf-je.mjs} +3 -3
- package/dist/preview-DnjgfpXJ.mjs +1 -0
- package/dist/{preview-CAhVgGQo.mjs → preview-DvYf3kcu.mjs} +2 -2
- package/dist/{python3-AUFTPCU6-BSuL_Nsg.mjs → python3-AUFTPCU6-CcfVkAVy.mjs} +3 -3
- package/dist/{repair-launch-json-BoiF16xN.mjs → repair-launch-json-Dhq_x0b3.mjs} +2 -2
- package/dist/{repair-mcp-configs-CXh6WSYS.mjs → repair-mcp-configs-DOuR37tP.mjs} +2 -2
- package/dist/repair-skills-7pBVTbub.mjs +1 -0
- package/dist/{repair-skills-B4l2j5St.mjs → repair-skills-B9jE33Ah.mjs} +2 -2
- package/dist/{sqlite3-56UMWEY3-B0OUvEvJ.mjs → sqlite3-56UMWEY3-DN8JOqf2.mjs} +1 -1
- package/dist/{src-BjRMhwz_.mjs → src-Cbymbi2A.mjs} +2 -2
- package/dist/start-C1b3Km0h.mjs +1 -0
- package/dist/{start-CQ9ydIkL.mjs → start-yi64RGnp.mjs} +2 -2
- package/dist/{write-project-skill-BH_iLvg3.mjs → write-project-skill-DCqIN5fH.mjs} +2 -2
- package/package.json +4 -1
- package/dist/constants-3pLYz7Cm.mjs +0 -2
- package/dist/dist-B1bXj22d.mjs +0 -1
- package/dist/init-B2oJJQ6d.mjs +0 -1
- package/dist/loader-DMjq2UMI.mjs +0 -1
- package/dist/preview-Bsp1hXwy.mjs +0 -1
- package/dist/repair-skills-K6DWb3wZ.mjs +0 -1
- package/dist/start-C0s4RRL3.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,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-s2X3YAg-.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-BniQ3qki-C_0QTo_r.mjs";import{a as simpleGit,i as esm_default,o as require_src$15,r as withParentLock,t as createGitInstance}from"./git-handle-CjyGVy33-B_7lAMm9.mjs";import{r as diffLines,t as createPatch}from"./libesm-YL3Bqolr.mjs";import{n as mimes,t as build_default}from"./build-fAc55Z_L.mjs";import{t as b1}from"./chunk-YNYSPYQ5-Dq-BWW-f.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-CkMj9l7f.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-Vm1q1kLH.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-Cd7Fiqsb.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import"./chunk-DXB73IDG-DfmyzFzL.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-SLhNX8t9.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DQP-O5US.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-_PX4ITYZ.mjs";import{n as n$1}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as n$2}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import
|
|
1
|
+
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,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-s2X3YAg-.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-BniQ3qki-C_0QTo_r.mjs";import{a as simpleGit,i as esm_default,o as require_src$15,r as withParentLock,t as createGitInstance}from"./git-handle-CjyGVy33-B_7lAMm9.mjs";import{r as diffLines,t as createPatch}from"./libesm-YL3Bqolr.mjs";import{n as mimes,t as build_default}from"./build-fAc55Z_L.mjs";import{t as b1}from"./chunk-YNYSPYQ5-Dq-BWW-f.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-CkMj9l7f.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-Vm1q1kLH.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-Cd7Fiqsb.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import"./chunk-DXB73IDG-DfmyzFzL.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-SLhNX8t9.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DQP-O5US.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-_PX4ITYZ.mjs";import{n as n$1}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as n$2}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import pino from"pino";import{Transform}from"node:stream";import crypto$2 from"crypto";import*as zlib$1 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import yazl from"yazl";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";var require_identity=__commonJSMin$1((e=>{let t=Symbol.for(`yaml.alias`),S=Symbol.for(`yaml.document`),w=Symbol.for(`yaml.map`),E=Symbol.for(`yaml.pair`),D=Symbol.for(`yaml.scalar`),O=Symbol.for(`yaml.seq`),k=Symbol.for(`yaml.node.type`),j=e=>!!e&&typeof e==`object`&&e[k]===t,F=e=>!!e&&typeof e==`object`&&e[k]===S,L=e=>!!e&&typeof e==`object`&&e[k]===w,B=e=>!!e&&typeof e==`object`&&e[k]===E,H=e=>!!e&&typeof e==`object`&&e[k]===D,q=e=>!!e&&typeof e==`object`&&e[k]===O;function J(e){if(e&&typeof e==`object`)switch(e[k]){case w:case O:return!0}return!1}function Y(e){if(e&&typeof e==`object`)switch(e[k]){case t:case w:case D:case O:return!0}return!1}e.ALIAS=t,e.DOC=S,e.MAP=w,e.NODE_TYPE=k,e.PAIR=E,e.SCALAR=D,e.SEQ=O,e.hasAnchor=e=>(H(e)||J(e))&&!!e.anchor,e.isAlias=j,e.isCollection=J,e.isDocument=F,e.isMap=L,e.isNode=Y,e.isPair=B,e.isScalar=H,e.isSeq=q})),require_visit=__commonJSMin$1((e=>{var t=require_identity();let S=Symbol(`break visit`),w=Symbol(`skip children`),E=Symbol(`remove node`);function D(e,S){let w=F(S);t.isDocument(e)?O(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):O(null,e,w,Object.freeze([]))}D.BREAK=S,D.SKIP=w,D.REMOVE=E;function O(e,w,D,k){let j=L(e,w,D,k);if(t.isNode(j)||t.isPair(j))return B(e,k,j),O(e,j,D,k);if(typeof j!=`symbol`){if(t.isCollection(w)){k=Object.freeze(k.concat(w));for(let e=0;e<w.items.length;++e){let t=O(e,w.items[e],D,k);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){k=Object.freeze(k.concat(w));let e=O(`key`,w.key,D,k);if(e===S)return S;e===E&&(w.key=null);let t=O(`value`,w.value,D,k);if(t===S)return S;t===E&&(w.value=null)}}return j}async function k(e,S){let w=F(S);t.isDocument(e)?await j(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):await j(null,e,w,Object.freeze([]))}k.BREAK=S,k.SKIP=w,k.REMOVE=E;async function j(e,w,D,O){let k=await L(e,w,D,O);if(t.isNode(k)||t.isPair(k))return B(e,O,k),j(e,k,D,O);if(typeof k!=`symbol`){if(t.isCollection(w)){O=Object.freeze(O.concat(w));for(let e=0;e<w.items.length;++e){let t=await j(e,w.items[e],D,O);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){O=Object.freeze(O.concat(w));let e=await j(`key`,w.key,D,O);if(e===S)return S;e===E&&(w.key=null);let t=await j(`value`,w.value,D,O);if(t===S)return S;t===E&&(w.value=null)}}return k}function F(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function L(e,S,w,E){if(typeof w==`function`)return w(e,S,E);if(t.isMap(S))return w.Map?.(e,S,E);if(t.isSeq(S))return w.Seq?.(e,S,E);if(t.isPair(S))return w.Pair?.(e,S,E);if(t.isScalar(S))return w.Scalar?.(e,S,E);if(t.isAlias(S))return w.Alias?.(e,S,E)}function B(e,S,w){let E=S[S.length-1];if(t.isCollection(E))E.items[e]=w;else if(t.isPair(E))e===`key`?E.key=w:E.value=w;else if(t.isDocument(E))E.contents=w;else{let e=t.isAlias(E)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=D,e.visitAsync=k})),require_directives=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();let w={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},E=e=>e.replace(/[!,[\]{}]/g,e=>w[e]);var D=class e{constructor(t,S){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,S)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,S){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let w=t.trim().split(/[ \t]+/),E=w.shift();switch(E){case`%TAG`:{if(w.length!==2&&(S(0,`%TAG directive should contain exactly two parts`),w.length<2))return!1;let[e,t]=w;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,w.length!==1)return S(0,`%YAML directive should contain exactly one part`),!1;let[e]=w;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return S(6,`Unsupported YAML version ${e}`,t),!1}}default:return S(0,`Unknown directive ${E}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let S=e.slice(2,-1);return S===`!`||S===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),S)}let[,S,w]=e.match(/^(.*!)([^!]*)$/s);w||t(`The ${e} tag has no suffix`);let E=this.tags[S];if(E)try{return E+decodeURIComponent(w)}catch(e){return t(String(e)),null}return S===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,S]of Object.entries(this.tags))if(e.startsWith(S))return t+E(e.substring(S.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],E=Object.entries(this.tags),D;if(e&&E.length>0&&t.isNode(e.contents)){let w={};S.visit(e.contents,(e,S)=>{t.isNode(S)&&S.tag&&(w[S.tag]=!0)}),D=Object.keys(w)}else D=[];for(let[t,S]of E)t===`!!`&&S===`tag:yaml.org,2002:`||(!e||D.some(e=>e.startsWith(S)))&&w.push(`%TAG ${t} ${S}`);return w.join(`
|
|
2
2
|
`)}};D.defaultYaml={explicit:!1,version:`1.2`},D.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=D})),require_anchors=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();function w(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function E(e){let t=new Set;return S.visit(e,{Value(e,S){S.anchor&&t.add(S.anchor)}}),t}function D(e,t){for(let S=1;;++S){let w=`${e}${S}`;if(!t.has(w))return w}}function O(e,S){let w=[],O=new Map,k=null;return{onAnchor:t=>{w.push(t),k??=E(e);let O=D(S,k);return k.add(O),O},setAnchors:()=>{for(let e of w){let S=O.get(e);if(typeof S==`object`&&S.anchor&&(t.isScalar(S.node)||t.isCollection(S.node)))S.node.anchor=S.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:O}}e.anchorIsValid=w,e.anchorNames=E,e.createNodeAnchors=O,e.findNewAnchor=D})),require_applyReviver=__commonJSMin$1((e=>{function t(e,S,w,E){if(E&&typeof E==`object`)if(Array.isArray(E))for(let S=0,w=E.length;S<w;++S){let w=E[S],D=t(e,E,String(S),w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}else if(E instanceof Map)for(let S of Array.from(E.keys())){let w=E.get(S),D=t(e,E,S,w);D===void 0?E.delete(S):D!==w&&E.set(S,D)}else if(E instanceof Set)for(let S of Array.from(E)){let w=t(e,E,S,S);w===void 0?E.delete(S):w!==S&&(E.delete(S),E.add(w))}else for(let[S,w]of Object.entries(E)){let D=t(e,E,S,w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}return e.call(S,w,E)}e.applyReviver=t})),require_toJS=__commonJSMin$1((e=>{var t=require_identity();function S(e,w,E){if(Array.isArray(e))return e.map((e,t)=>S(e,String(t),E));if(e&&typeof e.toJSON==`function`){if(!E||!t.hasAnchor(e))return e.toJSON(w,E);let S={aliasCount:0,count:1,res:void 0};E.anchors.set(e,S),E.onCreate=e=>{S.res=e,delete E.onCreate};let D=e.toJSON(w,E);return E.onCreate&&E.onCreate(D),D}return typeof e==`bigint`&&!E?.keep?Number(e):e}e.toJS=S})),require_Node=__commonJSMin$1((e=>{var t=require_applyReviver(),S=require_identity(),w=require_toJS();e.NodeBase=class{constructor(e){Object.defineProperty(this,S.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:E,maxAliasCount:D,onAnchor:O,reviver:k}={}){if(!S.isDocument(e))throw TypeError(`A document argument is required`);let j={anchors:new Map,doc:e,keep:!0,mapAsMap:E===!0,mapKeyWarned:!1,maxAliasCount:typeof D==`number`?D:100},F=w.toJS(this,``,j);if(typeof O==`function`)for(let{count:e,res:t}of j.anchors.values())O(t,e);return typeof k==`function`?t.applyReviver(k,{"":F},``,F):F}}})),require_Alias=__commonJSMin$1((e=>{var t=require_anchors(),S=require_visit(),w=require_identity(),E=require_Node(),D=require_toJS(),O=class extends E.NodeBase{constructor(e){super(w.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let E;t?.aliasResolveCache?E=t.aliasResolveCache:(E=[],S.visit(e,{Node:(e,t)=>{(w.isAlias(t)||w.hasAnchor(t))&&E.push(t)}}),t&&(t.aliasResolveCache=E));let D;for(let e of E){if(e===this)break;e.anchor===this.source&&(D=e)}return D}toJSON(e,t){if(!t)return{source:this.source};let{anchors:S,doc:w,maxAliasCount:E}=t,O=this.resolve(w,t);if(!O){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let j=S.get(O);if(j||=(D.toJS(O,null,t),S.get(O)),j?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(E>=0&&(j.count+=1,j.aliasCount===0&&(j.aliasCount=k(w,O,S)),j.count*j.aliasCount>E))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return j.res}toString(e,S,w){let E=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${E} `}return E}};function k(e,t,S){if(w.isAlias(t)){let w=t.resolve(e),E=S&&w&&S.get(w);return E?E.count*E.aliasCount:0}else if(w.isCollection(t)){let w=0;for(let E of t.items){let t=k(e,E,S);t>w&&(w=t)}return w}else if(w.isPair(t)){let w=k(e,t.key,S),E=k(e,t.value,S);return Math.max(w,E)}return 1}e.Alias=O})),require_Scalar=__commonJSMin$1((e=>{var t=require_identity(),S=require_Node(),w=require_toJS();let E=e=>!e||typeof e!=`function`&&typeof e!=`object`;var D=class extends S.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:w.toJS(this.value,e,t)}toString(){return String(this.value)}};D.BLOCK_FOLDED=`BLOCK_FOLDED`,D.BLOCK_LITERAL=`BLOCK_LITERAL`,D.PLAIN=`PLAIN`,D.QUOTE_DOUBLE=`QUOTE_DOUBLE`,D.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=D,e.isScalarValue=E})),require_createNode=__commonJSMin$1((e=>{var t=require_Alias(),S=require_identity(),w=require_Scalar();let E=`tag:yaml.org,2002:`;function D(e,t,S){if(t){let e=S.filter(e=>e.tag===t),w=e.find(e=>!e.format)??e[0];if(!w)throw Error(`Tag ${t} not found`);return w}return S.find(t=>t.identify?.(e)&&!t.format)}function O(e,E,O){if(S.isDocument(e)&&(e=e.contents),S.isNode(e))return e;if(S.isPair(e)){let t=O.schema[S.MAP].createNode?.(O.schema,null,O);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:k,onAnchor:j,onTagObj:F,schema:L,sourceObjects:B}=O,H;if(k&&e&&typeof e==`object`){if(H=B.get(e),H)return H.anchor??=j(e),new t.Alias(H.anchor);H={anchor:null,node:null},B.set(e,H)}E?.startsWith(`!!`)&&(E=`tag:yaml.org,2002:`+E.slice(2));let q=D(e,E,L.tags);if(!q){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new w.Scalar(e);return H&&(H.node=t),t}q=e instanceof Map?L[S.MAP]:Symbol.iterator in Object(e)?L[S.SEQ]:L[S.MAP]}F&&(F(q),delete O.onTagObj);let J=q?.createNode?q.createNode(O.schema,e,O):typeof q?.nodeClass?.from==`function`?q.nodeClass.from(O.schema,e,O):new w.Scalar(e);return E?J.tag=E:q.default||(J.tag=q.tag),H&&(H.node=J),J}e.createNode=O})),require_Collection=__commonJSMin$1((e=>{var t=require_createNode(),S=require_identity(),w=require_Node();function E(e,S,w){let E=w;for(let e=S.length-1;e>=0;--e){let t=S[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=E,E=e}else E=new Map([[t,E]])}return t.createNode(E,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let D=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends w.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>S.isNode(t)||S.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(D(e))this.add(t);else{let[w,...D]=e,O=this.get(w,!0);if(S.isCollection(O))O.addIn(D,t);else if(O===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}deleteIn(e){let[t,...w]=e;if(w.length===0)return this.delete(t);let E=this.get(t,!0);if(S.isCollection(E))return E.deleteIn(w);throw Error(`Expected YAML collection at ${t}. Remaining path: ${w}`)}getIn(e,t){let[w,...E]=e,D=this.get(w,!0);return E.length===0?!t&&S.isScalar(D)?D.value:D:S.isCollection(D)?D.getIn(E,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!S.isPair(t))return!1;let w=t.value;return w==null||e&&S.isScalar(w)&&w.value==null&&!w.commentBefore&&!w.comment&&!w.tag})}hasIn(e){let[t,...w]=e;if(w.length===0)return this.has(t);let E=this.get(t,!0);return S.isCollection(E)?E.hasIn(w):!1}setIn(e,t){let[w,...D]=e;if(D.length===0)this.set(w,t);else{let e=this.get(w,!0);if(S.isCollection(e))e.setIn(D,t);else if(e===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}},e.collectionFromPath=E,e.isEmptyPath=D})),require_stringifyComment=__commonJSMin$1((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function S(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=S,e.lineComment=(e,t,w)=>e.endsWith(`
|
|
3
3
|
`)?S(w,t):w.includes(`
|
|
4
4
|
`)?`
|
|
@@ -112,7 +112,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
112
112
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
113
113
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let S=`end`in t.value?t.value.end:void 0;(Array.isArray(S)?S[S.length-1]:void 0)?.type===`comment`?S?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let S=e.items[e.items.length-2]?.value?.end;if(Array.isArray(S)){F(S,t.start),S.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let S=!this.onKeyLine&&this.indent===e.indent,w=S&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,D=[];if(w&&t.sep&&!t.value){let S=[];for(let w=0;w<t.sep.length;++w){let E=t.sep[w];switch(E.type){case`newline`:S.push(w);break;case`space`:break;case`comment`:E.indent>e.indent&&(S.length=0);break;default:S.length=0}}S.length>=2&&(D=t.sep.splice(S[1]))}switch(this.type){case`anchor`:case`tag`:w||t.value?(D.push(this.sourceToken),e.items.push({start:D}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):w||t.value?(D.push(this.sourceToken),e.items.push({start:D,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey)if(!t.sep)if(E(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=j(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(E(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:D,key:null,sep:[this.sourceToken]}]});else if(O(t.key)&&!E(t.sep,`newline`)){let e=j(t.start),S=t.key,w=t.sep;w.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:S,sep:w}]})}else D.length>0?t.sep=t.sep.concat(D,this.sourceToken):t.sep.push(this.sourceToken);else t.sep?t.value||w?e.items.push({start:D,key:null,sep:[this.sourceToken]}):E(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let S=this.flowScalar(this.type);w||t.value?(e.items.push({start:D,key:S,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(S):(Object.assign(t,{key:S,sep:[]}),this.onKeyLine=!0);return}default:{let w=this.startBlockValue(e);if(w){if(w.type===`block-seq`){if(!t.explicitKey&&t.sep&&!E(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else S&&e.items.push({start:D});this.stack.push(w);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let S=`end`in t.value?t.value.end:void 0;(Array.isArray(S)?S[S.length-1]:void 0)?.type===`comment`?S?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let S=e.items[e.items.length-2]?.value?.end;if(Array.isArray(S)){F(S,t.start),S.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||E(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let S=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:S,sep:[]}):t.sep?this.stack.push(S):Object.assign(t,{key:S,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let S=this.startBlockValue(e);S?this.stack.push(S):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let S=j(k(t));L(e);let w=e.end.splice(1,e.end.length);w.push(this.sourceToken);let E={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:S,key:e,sep:w}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=E}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
114
114
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
115
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=j(k(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=j(k(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),require_public_api=__commonJSMin$1((e=>{var t=require_composer(),S=require_Document(),w=require_errors$1(),E=require_log(),D=require_identity(),O=require_line_counter(),k=require_parser();function j(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new O.LineCounter||null,prettyErrors:t}}function F(e,S={}){let{lineCounter:E,prettyErrors:D}=j(S),O=new k.Parser(E?.addNewLine),F=new t.Composer(S),L=Array.from(F.compose(O.parse(e)));if(D&&E)for(let t of L)t.errors.forEach(w.prettifyError(e,E)),t.warnings.forEach(w.prettifyError(e,E));return L.length>0?L:Object.assign([],{empty:!0},F.streamInfo())}function L(e,S={}){let{lineCounter:E,prettyErrors:D}=j(S),O=new k.Parser(E?.addNewLine),F=new t.Composer(S),L=null;for(let t of F.compose(O.parse(e),!0,e.length))if(!L)L=t;else if(L.options.logLevel!==`silent`){L.errors.push(new w.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return D&&E&&(L.errors.forEach(w.prettifyError(e,E)),L.warnings.forEach(w.prettifyError(e,E))),L}function B(e,t,S){let w;typeof t==`function`?w=t:S===void 0&&t&&typeof t==`object`&&(S=t);let D=L(e,S);if(!D)return null;if(D.warnings.forEach(e=>E.warn(D.options.logLevel,e)),D.errors.length>0){if(D.options.logLevel!==`silent`)throw D.errors[0];D.errors=[]}return D.toJS(Object.assign({reviver:w},S))}function H(e,t,w){let E=null;if(typeof t==`function`||Array.isArray(t)?E=t:w===void 0&&t&&(w=t),typeof w==`string`&&(w=w.length),typeof w==`number`){let e=Math.round(w);w=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=w??t??{};if(!e)return}return D.isDocument(e)&&!E?e.toString(w):new S.Document(e,E,w).toString(w)}e.parse=B,e.parseAllDocuments=F,e.parseDocument=L,e.stringify=H})),require_dist$2=__commonJSMin$1((e=>{var t=require_composer(),S=require_Document(),w=require_Schema(),E=require_errors$1(),D=require_Alias(),O=require_identity(),k=require_Pair(),j=require_Scalar(),F=require_YAMLMap(),L=require_YAMLSeq(),B=require_cst(),H=require_lexer(),q=require_line_counter(),J=require_parser(),Y=require_public_api(),ee=require_visit();e.Composer=t.Composer,e.Document=S.Document,e.Schema=w.Schema,e.YAMLError=E.YAMLError,e.YAMLParseError=E.YAMLParseError,e.YAMLWarning=E.YAMLWarning,e.Alias=D.Alias,e.isAlias=O.isAlias,e.isCollection=O.isCollection,e.isDocument=O.isDocument,e.isMap=O.isMap,e.isNode=O.isNode,e.isPair=O.isPair,e.isScalar=O.isScalar,e.isSeq=O.isSeq,e.Pair=k.Pair,e.Scalar=j.Scalar,e.YAMLMap=F.YAMLMap,e.YAMLSeq=L.YAMLSeq,e.Lexer=H.Lexer,e.LineCounter=q.LineCounter,e.Parser=J.Parser,e.parse=Y.parse,e.parseAllDocuments=Y.parseAllDocuments,e.parseDocument=Y.parseDocument,e.stringify=Y.stringify,e.visit=ee.visit,e.visitAsync=ee.visitAsync}));const NEVER=Object.freeze({status:`aborted`});function $constructor(e,t,S){function w(S,w){if(S._zod||Object.defineProperty(S,`_zod`,{value:{def:w,constr:O,traits:new Set},enumerable:!1}),S._zod.traits.has(e))return;S._zod.traits.add(e),t(S,w);let E=O.prototype,D=Object.keys(E);for(let e=0;e<D.length;e++){let t=D[e];t in S||(S[t]=E[t].bind(S))}}let E=S?.Parent??Object;class D extends E{}Object.defineProperty(D,`name`,{value:e});function O(e){var t;let E=S?.Parent?new D:this;w(E,e),(t=E._zod).deferred??(t.deferred=[]);for(let e of E._zod.deferred)e();return E}return Object.defineProperty(O,`init`,{value:w}),Object.defineProperty(O,Symbol.hasInstance,{value:t=>S?.Parent&&t instanceof S.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(O,`name`,{value:e}),O}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const globalConfig={};function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,S])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}function cached(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function nullish(e){return e==null}function cleanRegex(e){let t=e.startsWith(`^`)?1:0,S=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,S)}function floatSafeRemainder$1(e,t){let S=(e.toString().split(`.`)[1]||``).length,w=t.toString(),E=(w.split(`.`)[1]||``).length;if(E===0&&/\d?e-\d?/.test(w)){let e=w.match(/\d?e-(\d?)/);e?.[1]&&(E=Number.parseInt(e[1]))}let D=S>E?S:E;return Number.parseInt(e.toFixed(D).replace(`.`,``))%Number.parseInt(t.toFixed(D).replace(`.`,``))/10**D}const EVALUATING=Symbol(`evaluating`);function defineLazy(e,t,S){let w;Object.defineProperty(e,t,{get(){if(w!==EVALUATING)return w===void 0&&(w=EVALUATING,w=S()),w},set(S){Object.defineProperty(e,t,{value:S})},configurable:!0})}function assignProp(e,t,S){Object.defineProperty(e,t,{value:S,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){let t={};for(let S of e)Object.assign(t,Object.getOwnPropertyDescriptors(S));return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const allowsEval=cached(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject$4(e){if(isObject$1(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let S=t.prototype;return!(isObject$1(S)===!1||Object.prototype.hasOwnProperty.call(S,`isPrototypeOf`)===!1)}function shallowClone(e){return isPlainObject$4(e)?{...e}:Array.isArray(e)?[...e]:e}const propertyKeyTypes=new Set([`string`,`number`,`symbol`]);function escapeRegex$1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,S){let w=new e._zod.constr(t??e._zod.def);return(!t||S?.parent)&&(w._zod.parent=e),w}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const NUMBER_FORMAT_RANGES={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick$2(e,t){let S=e._zod.def,w=S.checks;if(w&&w.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let e={};for(let w in t){if(!(w in S.shape))throw Error(`Unrecognized key: "${w}"`);t[w]&&(e[w]=S.shape[w])}return assignProp(this,`shape`,e),e},checks:[]}))}function omit(e,t){let S=e._zod.def,w=S.checks;if(w&&w.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let w={...e._zod.def.shape};for(let e in t){if(!(e in S.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete w[e]}return assignProp(this,`shape`,w),w},checks:[]}))}function extend$1(e,t){if(!isPlainObject$4(t))throw Error(`Invalid input to extend: expected a plain object`);let S=e._zod.def.checks;if(S&&S.length>0){let S=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(S,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t};return assignProp(this,`shape`,S),S}}))}function safeExtend(e,t){if(!isPlainObject$4(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t};return assignProp(this,`shape`,S),S}}))}function merge$1(e,t){return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,`shape`,S),S},get catchall(){return t._zod.def.catchall},checks:[]}))}function partial(e,t,S){let w=t._zod.def.checks;if(w&&w.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return clone(t,mergeDefs(t._zod.def,{get shape(){let w=t._zod.def.shape,E={...w};if(S)for(let t in S){if(!(t in w))throw Error(`Unrecognized key: "${t}"`);S[t]&&(E[t]=e?new e({type:`optional`,innerType:w[t]}):w[t])}else for(let t in w)E[t]=e?new e({type:`optional`,innerType:w[t]}):w[t];return assignProp(this,`shape`,E),E},checks:[]}))}function required(e,t,S){return clone(t,mergeDefs(t._zod.def,{get shape(){let w=t._zod.def.shape,E={...w};if(S)for(let t in S){if(!(t in E))throw Error(`Unrecognized key: "${t}"`);S[t]&&(E[t]=new e({type:`nonoptional`,innerType:w[t]}))}else for(let t in w)E[t]=new e({type:`nonoptional`,innerType:w[t]});return assignProp(this,`shape`,E),E}}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let S=t;S<e.issues.length;S++)if(e.issues[S]?.continue!==!0)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var S;return(S=t).path??(S.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function finalizeIssue(e,t,S){let w={...e,path:e.path??[]};return e.message||(w.message=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(S.customError?.(e))??unwrapMessage(S.localeError?.(e))??`Invalid input`),delete w.inst,delete w.continue,t?.reportInput||delete w.input,w}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function issue(...e){let[t,S,w]=e;return typeof t==`string`?{message:t,code:`custom`,input:S,inst:w}:{...t}}const initializer$1=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){let S={},w=[];for(let E of e.issues)E.path.length>0?(S[E.path[0]]=S[E.path[0]]||[],S[E.path[0]].push(t(E))):w.push(t(E));return{formErrors:w,fieldErrors:S}}function formatError(e,t=e=>e.message){let S={_errors:[]},w=e=>{for(let E of e.issues)if(E.code===`invalid_union`&&E.errors.length)E.errors.map(e=>w({issues:e}));else if(E.code===`invalid_key`)w({issues:E.issues});else if(E.code===`invalid_element`)w({issues:E.issues});else if(E.path.length===0)S._errors.push(t(E));else{let e=S,w=0;for(;w<E.path.length;){let S=E.path[w];w===E.path.length-1?(e[S]=e[S]||{_errors:[]},e[S]._errors.push(t(E))):e[S]=e[S]||{_errors:[]},e=e[S],w++}}};return w(e),S}function toDotPath(e){let t=[],S=e.map(e=>typeof e==`object`?e.key:e);for(let e of S)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function prettifyError(e){let t=[],S=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of S)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join(`
|
|
115
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=j(k(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=j(k(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),require_public_api=__commonJSMin$1((e=>{var t=require_composer(),S=require_Document(),w=require_errors$1(),E=require_log(),D=require_identity(),O=require_line_counter(),k=require_parser();function j(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new O.LineCounter||null,prettyErrors:t}}function F(e,S={}){let{lineCounter:E,prettyErrors:D}=j(S),O=new k.Parser(E?.addNewLine),F=new t.Composer(S),L=Array.from(F.compose(O.parse(e)));if(D&&E)for(let t of L)t.errors.forEach(w.prettifyError(e,E)),t.warnings.forEach(w.prettifyError(e,E));return L.length>0?L:Object.assign([],{empty:!0},F.streamInfo())}function L(e,S={}){let{lineCounter:E,prettyErrors:D}=j(S),O=new k.Parser(E?.addNewLine),F=new t.Composer(S),L=null;for(let t of F.compose(O.parse(e),!0,e.length))if(!L)L=t;else if(L.options.logLevel!==`silent`){L.errors.push(new w.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return D&&E&&(L.errors.forEach(w.prettifyError(e,E)),L.warnings.forEach(w.prettifyError(e,E))),L}function B(e,t,S){let w;typeof t==`function`?w=t:S===void 0&&t&&typeof t==`object`&&(S=t);let D=L(e,S);if(!D)return null;if(D.warnings.forEach(e=>E.warn(D.options.logLevel,e)),D.errors.length>0){if(D.options.logLevel!==`silent`)throw D.errors[0];D.errors=[]}return D.toJS(Object.assign({reviver:w},S))}function H(e,t,w){let E=null;if(typeof t==`function`||Array.isArray(t)?E=t:w===void 0&&t&&(w=t),typeof w==`string`&&(w=w.length),typeof w==`number`){let e=Math.round(w);w=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=w??t??{};if(!e)return}return D.isDocument(e)&&!E?e.toString(w):new S.Document(e,E,w).toString(w)}e.parse=B,e.parseAllDocuments=F,e.parseDocument=L,e.stringify=H})),require_dist$1=__commonJSMin$1((e=>{var t=require_composer(),S=require_Document(),w=require_Schema(),E=require_errors$1(),D=require_Alias(),O=require_identity(),k=require_Pair(),j=require_Scalar(),F=require_YAMLMap(),L=require_YAMLSeq(),B=require_cst(),H=require_lexer(),q=require_line_counter(),J=require_parser(),Y=require_public_api(),ee=require_visit();e.Composer=t.Composer,e.Document=S.Document,e.Schema=w.Schema,e.YAMLError=E.YAMLError,e.YAMLParseError=E.YAMLParseError,e.YAMLWarning=E.YAMLWarning,e.Alias=D.Alias,e.isAlias=O.isAlias,e.isCollection=O.isCollection,e.isDocument=O.isDocument,e.isMap=O.isMap,e.isNode=O.isNode,e.isPair=O.isPair,e.isScalar=O.isScalar,e.isSeq=O.isSeq,e.Pair=k.Pair,e.Scalar=j.Scalar,e.YAMLMap=F.YAMLMap,e.YAMLSeq=L.YAMLSeq,e.Lexer=H.Lexer,e.LineCounter=q.LineCounter,e.Parser=J.Parser,e.parse=Y.parse,e.parseAllDocuments=Y.parseAllDocuments,e.parseDocument=Y.parseDocument,e.stringify=Y.stringify,e.visit=ee.visit,e.visitAsync=ee.visitAsync}));const NEVER=Object.freeze({status:`aborted`});function $constructor(e,t,S){function w(S,w){if(S._zod||Object.defineProperty(S,`_zod`,{value:{def:w,constr:O,traits:new Set},enumerable:!1}),S._zod.traits.has(e))return;S._zod.traits.add(e),t(S,w);let E=O.prototype,D=Object.keys(E);for(let e=0;e<D.length;e++){let t=D[e];t in S||(S[t]=E[t].bind(S))}}let E=S?.Parent??Object;class D extends E{}Object.defineProperty(D,`name`,{value:e});function O(e){var t;let E=S?.Parent?new D:this;w(E,e),(t=E._zod).deferred??(t.deferred=[]);for(let e of E._zod.deferred)e();return E}return Object.defineProperty(O,`init`,{value:w}),Object.defineProperty(O,Symbol.hasInstance,{value:t=>S?.Parent&&t instanceof S.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(O,`name`,{value:e}),O}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const globalConfig={};function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,S])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}function cached(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function nullish(e){return e==null}function cleanRegex(e){let t=e.startsWith(`^`)?1:0,S=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,S)}function floatSafeRemainder$1(e,t){let S=(e.toString().split(`.`)[1]||``).length,w=t.toString(),E=(w.split(`.`)[1]||``).length;if(E===0&&/\d?e-\d?/.test(w)){let e=w.match(/\d?e-(\d?)/);e?.[1]&&(E=Number.parseInt(e[1]))}let D=S>E?S:E;return Number.parseInt(e.toFixed(D).replace(`.`,``))%Number.parseInt(t.toFixed(D).replace(`.`,``))/10**D}const EVALUATING=Symbol(`evaluating`);function defineLazy(e,t,S){let w;Object.defineProperty(e,t,{get(){if(w!==EVALUATING)return w===void 0&&(w=EVALUATING,w=S()),w},set(S){Object.defineProperty(e,t,{value:S})},configurable:!0})}function assignProp(e,t,S){Object.defineProperty(e,t,{value:S,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){let t={};for(let S of e)Object.assign(t,Object.getOwnPropertyDescriptors(S));return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const allowsEval=cached(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject$4(e){if(isObject$1(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let S=t.prototype;return!(isObject$1(S)===!1||Object.prototype.hasOwnProperty.call(S,`isPrototypeOf`)===!1)}function shallowClone(e){return isPlainObject$4(e)?{...e}:Array.isArray(e)?[...e]:e}const propertyKeyTypes=new Set([`string`,`number`,`symbol`]);function escapeRegex$1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,S){let w=new e._zod.constr(t??e._zod.def);return(!t||S?.parent)&&(w._zod.parent=e),w}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const NUMBER_FORMAT_RANGES={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick$2(e,t){let S=e._zod.def,w=S.checks;if(w&&w.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let e={};for(let w in t){if(!(w in S.shape))throw Error(`Unrecognized key: "${w}"`);t[w]&&(e[w]=S.shape[w])}return assignProp(this,`shape`,e),e},checks:[]}))}function omit(e,t){let S=e._zod.def,w=S.checks;if(w&&w.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let w={...e._zod.def.shape};for(let e in t){if(!(e in S.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete w[e]}return assignProp(this,`shape`,w),w},checks:[]}))}function extend$1(e,t){if(!isPlainObject$4(t))throw Error(`Invalid input to extend: expected a plain object`);let S=e._zod.def.checks;if(S&&S.length>0){let S=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(S,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t};return assignProp(this,`shape`,S),S}}))}function safeExtend(e,t){if(!isPlainObject$4(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t};return assignProp(this,`shape`,S),S}}))}function merge$1(e,t){return clone(e,mergeDefs(e._zod.def,{get shape(){let S={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,`shape`,S),S},get catchall(){return t._zod.def.catchall},checks:[]}))}function partial(e,t,S){let w=t._zod.def.checks;if(w&&w.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return clone(t,mergeDefs(t._zod.def,{get shape(){let w=t._zod.def.shape,E={...w};if(S)for(let t in S){if(!(t in w))throw Error(`Unrecognized key: "${t}"`);S[t]&&(E[t]=e?new e({type:`optional`,innerType:w[t]}):w[t])}else for(let t in w)E[t]=e?new e({type:`optional`,innerType:w[t]}):w[t];return assignProp(this,`shape`,E),E},checks:[]}))}function required(e,t,S){return clone(t,mergeDefs(t._zod.def,{get shape(){let w=t._zod.def.shape,E={...w};if(S)for(let t in S){if(!(t in E))throw Error(`Unrecognized key: "${t}"`);S[t]&&(E[t]=new e({type:`nonoptional`,innerType:w[t]}))}else for(let t in w)E[t]=new e({type:`nonoptional`,innerType:w[t]});return assignProp(this,`shape`,E),E}}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let S=t;S<e.issues.length;S++)if(e.issues[S]?.continue!==!0)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var S;return(S=t).path??(S.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function finalizeIssue(e,t,S){let w={...e,path:e.path??[]};return e.message||(w.message=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(S.customError?.(e))??unwrapMessage(S.localeError?.(e))??`Invalid input`),delete w.inst,delete w.continue,t?.reportInput||delete w.input,w}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function issue(...e){let[t,S,w]=e;return typeof t==`string`?{message:t,code:`custom`,input:S,inst:w}:{...t}}const initializer$1=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){let S={},w=[];for(let E of e.issues)E.path.length>0?(S[E.path[0]]=S[E.path[0]]||[],S[E.path[0]].push(t(E))):w.push(t(E));return{formErrors:w,fieldErrors:S}}function formatError(e,t=e=>e.message){let S={_errors:[]},w=e=>{for(let E of e.issues)if(E.code===`invalid_union`&&E.errors.length)E.errors.map(e=>w({issues:e}));else if(E.code===`invalid_key`)w({issues:E.issues});else if(E.code===`invalid_element`)w({issues:E.issues});else if(E.path.length===0)S._errors.push(t(E));else{let e=S,w=0;for(;w<E.path.length;){let S=E.path[w];w===E.path.length-1?(e[S]=e[S]||{_errors:[]},e[S]._errors.push(t(E))):e[S]=e[S]||{_errors:[]},e=e[S],w++}}};return w(e),S}function toDotPath(e){let t=[],S=e.map(e=>typeof e==`object`?e.key:e);for(let e of S)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function prettifyError(e){let t=[],S=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of S)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join(`
|
|
116
116
|
`)}const _parse=e=>(t,S,w,E)=>{let D=w?Object.assign(w,{async:!1}):{async:!1},O=t._zod.run({value:S,issues:[]},D);if(O instanceof Promise)throw new $ZodAsyncError;if(O.issues.length){let t=new(E?.Err??e)(O.issues.map(e=>finalizeIssue(e,D,config())));throw captureStackTrace(t,E?.callee),t}return O.value},parse$6=_parse($ZodRealError),_parseAsync=e=>async(t,S,w,E)=>{let D=w?Object.assign(w,{async:!0}):{async:!0},O=t._zod.run({value:S,issues:[]},D);if(O instanceof Promise&&(O=await O),O.issues.length){let t=new(E?.Err??e)(O.issues.map(e=>finalizeIssue(e,D,config())));throw captureStackTrace(t,E?.callee),t}return O.value},parseAsync$1=_parseAsync($ZodRealError),_safeParse=e=>(t,S,w)=>{let E=w?{...w,async:!1}:{async:!1},D=t._zod.run({value:S,issues:[]},E);if(D instanceof Promise)throw new $ZodAsyncError;return D.issues.length?{success:!1,error:new(e??$ZodError)(D.issues.map(e=>finalizeIssue(e,E,config())))}:{success:!0,data:D.value}},safeParse$2=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,S,w)=>{let E=w?Object.assign(w,{async:!0}):{async:!0},D=t._zod.run({value:S,issues:[]},E);return D instanceof Promise&&(D=await D),D.issues.length?{success:!1,error:new e(D.issues.map(e=>finalizeIssue(e,E,config())))}:{success:!0,data:D.value}},safeParseAsync$2=_safeParseAsync($ZodRealError),_encode=e=>(t,S,w)=>{let E=w?Object.assign(w,{direction:`backward`}):{direction:`backward`};return _parse(e)(t,S,E)},encode$2=_encode($ZodRealError),_decode=e=>(t,S,w)=>_parse(e)(t,S,w),decode$2=_decode($ZodRealError),_encodeAsync=e=>async(t,S,w)=>{let E=w?Object.assign(w,{direction:`backward`}):{direction:`backward`};return _parseAsync(e)(t,S,E)},encodeAsync$1=_encodeAsync($ZodRealError),_decodeAsync=e=>async(t,S,w)=>_parseAsync(e)(t,S,w),decodeAsync$1=_decodeAsync($ZodRealError),_safeEncode=e=>(t,S,w)=>{let E=w?Object.assign(w,{direction:`backward`}):{direction:`backward`};return _safeParse(e)(t,S,E)},safeEncode$1=_safeEncode($ZodRealError),_safeDecode=e=>(t,S,w)=>_safeParse(e)(t,S,w),safeDecode$1=_safeDecode($ZodRealError),_safeEncodeAsync=e=>async(t,S,w)=>{let E=w?Object.assign(w,{direction:`backward`}):{direction:`backward`};return _safeParseAsync(e)(t,S,E)},safeEncodeAsync$1=_safeEncodeAsync($ZodRealError),_safeDecodeAsync=e=>async(t,S,w)=>_safeParseAsync(e)(t,S,w),safeDecodeAsync$1=_safeDecodeAsync($ZodRealError),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function emoji(){return new RegExp(_emoji$1,`u`)}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(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=/^[A-Za-z0-9_-]*$/,e164=/^\+[1-9]\d{6,14}$/,dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,date$1=RegExp(`^${dateSource}$`);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(e){return RegExp(`^${timeSource(e)}$`)}function datetime$1(e){let t=timeSource({precision:e.precision}),S=[`Z`];e.local&&S.push(``),e.offset&&S.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let w=`${t}(?:${S.join(`|`)})`;return RegExp(`^${dateSource}T(?:${w})$`)}const string$3=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},integer=/^-?\d+$/,number$2=/^-?\d+(?:\.\d+)?$/,boolean$2=/^(?:true|false)$/i,_null$2=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor(`$ZodCheck`,(e,t)=>{var S;e._zod??={},e._zod.def=t,(S=e._zod).onattach??(S.onattach=[])}),numericOriginMap={number:`number`,bigint:`bigint`,object:`date`},$ZodCheckLessThan=$constructor(`$ZodCheckLessThan`,(e,t)=>{$ZodCheck.init(e,t);let S=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let S=e._zod.bag,w=(t.inclusive?S.maximum:S.exclusiveMaximum)??1/0;t.value<w&&(t.inclusive?S.maximum=t.value:S.exclusiveMaximum=t.value)}),e._zod.check=w=>{(t.inclusive?w.value<=t.value:w.value<t.value)||w.issues.push({origin:S,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:w.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckGreaterThan=$constructor(`$ZodCheckGreaterThan`,(e,t)=>{$ZodCheck.init(e,t);let S=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let S=e._zod.bag,w=(t.inclusive?S.minimum:S.exclusiveMinimum)??-1/0;t.value>w&&(t.inclusive?S.minimum=t.value:S.exclusiveMinimum=t.value)}),e._zod.check=w=>{(t.inclusive?w.value>=t.value:w.value>t.value)||w.issues.push({origin:S,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:w.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor(`$ZodCheckMultipleOf`,(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(e=>{var S;(S=e._zod.bag).multipleOf??(S.multipleOf=t.value)}),e._zod.check=S=>{if(typeof S.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof S.value==`bigint`?S.value%t.value===BigInt(0):floatSafeRemainder$1(S.value,t.value)===0)||S.issues.push({origin:typeof S.value,code:`not_multiple_of`,divisor:t.value,input:S.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor(`$ZodCheckNumberFormat`,(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||`float64`;let S=t.format?.includes(`int`),w=S?`int`:`number`,[E,D]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{let w=e._zod.bag;w.format=t.format,w.minimum=E,w.maximum=D,S&&(w.pattern=integer)}),e._zod.check=O=>{let k=O.value;if(S){if(!Number.isInteger(k)){O.issues.push({expected:w,format:t.format,code:`invalid_type`,continue:!1,input:k,inst:e});return}if(!Number.isSafeInteger(k)){k>0?O.issues.push({input:k,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:w,inclusive:!0,continue:!t.abort}):O.issues.push({input:k,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:w,inclusive:!0,continue:!t.abort});return}}k<E&&O.issues.push({origin:`number`,input:k,code:`too_small`,minimum:E,inclusive:!0,inst:e,continue:!t.abort}),k>D&&O.issues.push({origin:`number`,input:k,code:`too_big`,maximum:D,inclusive:!0,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor(`$ZodCheckMaxLength`,(e,t)=>{var S;$ZodCheck.init(e,t),(S=e._zod.def).when??(S.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let S=e._zod.bag.maximum??1/0;t.maximum<S&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=S=>{let w=S.value;if(w.length<=t.maximum)return;let E=getLengthableOrigin(w);S.issues.push({origin:E,code:`too_big`,maximum:t.maximum,inclusive:!0,input:w,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor(`$ZodCheckMinLength`,(e,t)=>{var S;$ZodCheck.init(e,t),(S=e._zod.def).when??(S.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let S=e._zod.bag.minimum??-1/0;t.minimum>S&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=S=>{let w=S.value;if(w.length>=t.minimum)return;let E=getLengthableOrigin(w);S.issues.push({origin:E,code:`too_small`,minimum:t.minimum,inclusive:!0,input:w,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor(`$ZodCheckLengthEquals`,(e,t)=>{var S;$ZodCheck.init(e,t),(S=e._zod.def).when??(S.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let S=e._zod.bag;S.minimum=t.length,S.maximum=t.length,S.length=t.length}),e._zod.check=S=>{let w=S.value,E=w.length;if(E===t.length)return;let D=getLengthableOrigin(w),O=E>t.length;S.issues.push({origin:D,...O?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:S.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor(`$ZodCheckStringFormat`,(e,t)=>{var S,w;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{let S=e._zod.bag;S.format=t.format,t.pattern&&(S.patterns??=new Set,S.patterns.add(t.pattern))}),t.pattern?(S=e._zod).check??(S.check=S=>{t.pattern.lastIndex=0,!t.pattern.test(S.value)&&S.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:S.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(w=e._zod).check??(w.check=()=>{})}),$ZodCheckRegex=$constructor(`$ZodCheckRegex`,(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=S=>{t.pattern.lastIndex=0,!t.pattern.test(S.value)&&S.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:S.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=lowercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=uppercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor(`$ZodCheckIncludes`,(e,t)=>{$ZodCheck.init(e,t);let S=escapeRegex$1(t.includes),w=new RegExp(typeof t.position==`number`?`^.{${t.position}}${S}`:S);t.pattern=w,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(w)}),e._zod.check=S=>{S.value.includes(t.includes,t.position)||S.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:S.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor(`$ZodCheckStartsWith`,(e,t)=>{$ZodCheck.init(e,t);let S=RegExp(`^${escapeRegex$1(t.prefix)}.*`);t.pattern??=S,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(S)}),e._zod.check=S=>{S.value.startsWith(t.prefix)||S.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:S.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor(`$ZodCheckEndsWith`,(e,t)=>{$ZodCheck.init(e,t);let S=RegExp(`.*${escapeRegex$1(t.suffix)}$`);t.pattern??=S,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(S)}),e._zod.check=S=>{S.value.endsWith(t.suffix)||S.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:S.value,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor(`$ZodCheckOverwrite`,(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Doc$1=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
117
117
|
`).filter(e=>e),S=Math.min(...t.map(e=>e.length-e.trimStart().length)),w=t.map(e=>e.slice(S)).map(e=>` `.repeat(this.indent*2)+e);for(let e of w)this.content.push(e)}compile(){let e=Function,t=this?.args,S=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,S.join(`
|
|
118
118
|
`))}};const version$1={major:4,minor:3,patch:6},$ZodType=$constructor(`$ZodType`,(e,t)=>{var S;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version$1;let w=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&w.unshift(e);for(let t of w)for(let S of t._zod.onattach)S(e);if(w.length===0)(S=e._zod).deferred??(S.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,S)=>{let w=aborted(e),E;for(let D of t){if(D._zod.def.when){if(!D._zod.def.when(e))continue}else if(w)continue;let t=e.issues.length,O=D._zod.check(e);if(O instanceof Promise&&S?.async===!1)throw new $ZodAsyncError;if(E||O instanceof Promise)E=(E??Promise.resolve()).then(async()=>{await O,e.issues.length!==t&&(w||=aborted(e,t))});else{if(e.issues.length===t)continue;w||=aborted(e,t)}}return E?E.then(()=>e):e},S=(S,E,D)=>{if(aborted(S))return S.aborted=!0,S;let O=t(E,w,D);if(O instanceof Promise){if(D.async===!1)throw new $ZodAsyncError;return O.then(t=>e._zod.parse(t,D))}return e._zod.parse(O,D)};e._zod.run=(E,D)=>{if(D.skipChecks)return e._zod.parse(E,D);if(D.direction===`backward`){let t=e._zod.parse({value:E.value,issues:[]},{...D,skipChecks:!0});return t instanceof Promise?t.then(e=>S(e,E,D)):S(t,E,D)}let O=e._zod.parse(E,D);if(O instanceof Promise){if(D.async===!1)throw new $ZodAsyncError;return O.then(e=>t(e,w,D))}return t(O,w,D)}}defineLazy(e,`~standard`,()=>({validate:t=>{try{let S=safeParse$2(e,t);return S.success?{value:S.data}:{issues:S.error?.issues}}catch{return safeParseAsync$2(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),$ZodString=$constructor(`$ZodString`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$3(e._zod.bag),e._zod.parse=(S,w)=>{if(t.coerce)try{S.value=String(S.value)}catch{}return typeof S.value==`string`||S.issues.push({expected:`string`,code:`invalid_type`,input:S.value,inst:e}),S}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor(`$ZodGUID`,(e,t)=>{t.pattern??=guid,$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor(`$ZodEmail`,(e,t)=>{t.pattern??=email,$ZodStringFormat.init(e,t)}),$ZodURL=$constructor(`$ZodURL`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=S=>{try{let w=S.value.trim(),E=new URL(w);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(E.hostname)||S.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:S.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(E.protocol.endsWith(`:`)?E.protocol.slice(0,-1):E.protocol)||S.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:S.value,inst:e,continue:!t.abort})),t.normalize?S.value=E.href:S.value=w;return}catch{S.issues.push({code:`invalid_format`,format:`url`,input:S.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor(`$ZodNanoID`,(e,t)=>{t.pattern??=nanoid,$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor(`$ZodCUID`,(e,t)=>{t.pattern??=cuid,$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=cuid2,$ZodStringFormat.init(e,t)}),$ZodULID=$constructor(`$ZodULID`,(e,t)=>{t.pattern??=ulid,$ZodStringFormat.init(e,t)}),$ZodXID=$constructor(`$ZodXID`,(e,t)=>{t.pattern??=xid,$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=ksuid,$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime$1(t),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor(`$ZodISODate`,(e,t)=>{t.pattern??=date$1,$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time$1(t),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=duration$1,$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=ipv4,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv4`}),$ZodIPv6=$constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=ipv6,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=S=>{try{new URL(`http://[${S.value}]`)}catch{S.issues.push({code:`invalid_format`,format:`ipv6`,input:S.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=cidrv4,$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=cidrv6,$ZodStringFormat.init(e,t),e._zod.check=S=>{let w=S.value.split(`/`);try{if(w.length!==2)throw Error();let[e,t]=w;if(!t)throw Error();let S=Number(t);if(`${S}`!==t||S<0||S>128)throw Error();new URL(`http://[${e}]`)}catch{S.issues.push({code:`invalid_format`,format:`cidrv6`,input:S.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $ZodBase64=$constructor(`$ZodBase64`,(e,t)=>{t.pattern??=base64,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=S=>{isValidBase64(S.value)||S.issues.push({code:`invalid_format`,format:`base64`,input:S.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const $ZodBase64URL=$constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=base64url,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=S=>{isValidBase64URL(S.value)||S.issues.push({code:`invalid_format`,format:`base64url`,input:S.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor(`$ZodE164`,(e,t)=>{t.pattern??=e164,$ZodStringFormat.init(e,t)});function isValidJWT$1(e,t=null){try{let S=e.split(`.`);if(S.length!==3)return!1;let[w]=S;if(!w)return!1;let E=JSON.parse(atob(w));return!(`typ`in E&&E?.typ!==`JWT`||!E.alg||t&&(!(`alg`in E)||E.alg!==t))}catch{return!1}}const $ZodJWT=$constructor(`$ZodJWT`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=S=>{isValidJWT$1(S.value,t.alg)||S.issues.push({code:`invalid_format`,format:`jwt`,input:S.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor(`$ZodNumber`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$2,e._zod.parse=(S,w)=>{if(t.coerce)try{S.value=Number(S.value)}catch{}let E=S.value;if(typeof E==`number`&&!Number.isNaN(E)&&Number.isFinite(E))return S;let D=typeof E==`number`?Number.isNaN(E)?`NaN`:Number.isFinite(E)?void 0:`Infinity`:void 0;return S.issues.push({expected:`number`,code:`invalid_type`,input:E,inst:e,...D?{received:D}:{}}),S}}),$ZodNumberFormat=$constructor(`$ZodNumberFormat`,(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor(`$ZodBoolean`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$2,e._zod.parse=(S,w)=>{if(t.coerce)try{S.value=!!S.value}catch{}let E=S.value;return typeof E==`boolean`||S.issues.push({expected:`boolean`,code:`invalid_type`,input:E,inst:e}),S}}),$ZodNull=$constructor(`$ZodNull`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,e._zod.values=new Set([null]),e._zod.parse=(t,S)=>{let w=t.value;return w===null||t.issues.push({expected:`null`,code:`invalid_type`,input:w,inst:e}),t}}),$ZodAny=$constructor(`$ZodAny`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodUnknown=$constructor(`$ZodUnknown`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor(`$ZodNever`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,S)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function handleArrayResult(e,t,S){e.issues.length&&t.issues.push(...prefixIssues(S,e.issues)),t.value[S]=e.value}const $ZodArray=$constructor(`$ZodArray`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(S,w)=>{let E=S.value;if(!Array.isArray(E))return S.issues.push({expected:`array`,code:`invalid_type`,input:E,inst:e}),S;S.value=Array(E.length);let D=[];for(let e=0;e<E.length;e++){let O=E[e],k=t.element._zod.run({value:O,issues:[]},w);k instanceof Promise?D.push(k.then(t=>handleArrayResult(t,S,e))):handleArrayResult(k,S,e)}return D.length?Promise.all(D).then(()=>S):S}});function handlePropertyResult(e,t,S,w,E){if(e.issues.length){if(E&&!(S in w))return;t.issues.push(...prefixIssues(S,e.issues))}e.value===void 0?S in w&&(t.value[S]=void 0):t.value[S]=e.value}function normalizeDef(e){let t=Object.keys(e.shape);for(let S of t)if(!e.shape?.[S]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${S}": expected a Zod schema`);let S=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(S)}}function handleCatchall(e,t,S,w,E,D){let O=[],k=E.keySet,j=E.catchall._zod,F=j.def.type,L=j.optout===`optional`;for(let E in t){if(k.has(E))continue;if(F===`never`){O.push(E);continue}let D=j.run({value:t[E],issues:[]},w);D instanceof Promise?e.push(D.then(e=>handlePropertyResult(e,S,E,t,L))):handlePropertyResult(D,S,E,t,L)}return O.length&&S.issues.push({code:`unrecognized_keys`,keys:O,input:t,inst:D}),e.length?Promise.all(e).then(()=>S):S}const $ZodObject=$constructor(`$ZodObject`,(e,t)=>{if($ZodType.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let S={...e};return Object.defineProperty(t,`shape`,{value:S}),S}})}let S=cached(()=>normalizeDef(t));defineLazy(e._zod,`propValues`,()=>{let e=t.shape,S={};for(let t in e){let w=e[t]._zod;if(w.values){S[t]??(S[t]=new Set);for(let e of w.values)S[t].add(e)}}return S});let w=isObject$1,E=t.catchall,D;e._zod.parse=(t,O)=>{D??=S.value;let k=t.value;if(!w(k))return t.issues.push({expected:`object`,code:`invalid_type`,input:k,inst:e}),t;t.value={};let j=[],F=D.shape;for(let e of D.keys){let S=F[e],w=S._zod.optout===`optional`,E=S._zod.run({value:k[e],issues:[]},O);E instanceof Promise?j.push(E.then(S=>handlePropertyResult(S,t,e,k,w))):handlePropertyResult(E,t,e,k,w)}return E?handleCatchall(j,k,t,O,S.value,e):j.length?Promise.all(j).then(()=>t):t}}),$ZodObjectJIT=$constructor(`$ZodObjectJIT`,(e,t)=>{$ZodObject.init(e,t);let S=e._zod.parse,w=cached(()=>normalizeDef(t)),E=e=>{let t=new Doc$1([`shape`,`payload`,`ctx`]),S=w.value,E=e=>{let t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let D=Object.create(null),O=0;for(let e of S.keys)D[e]=`key_${O++}`;t.write(`const newResult = {};`);for(let w of S.keys){let S=D[w],O=esc(w),k=e[w]?._zod?.optout===`optional`;t.write(`const ${S} = ${E(w)};`),k?t.write(`
|
|
@@ -151,7 +151,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
151
151
|
|
|
152
152
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let k=t.compile();return(t,S)=>k(e,t,S)},D,O=isObject$1,k=!globalConfig.jitless,j=k&&allowsEval.value,F=t.catchall,L;e._zod.parse=(B,H)=>{L??=w.value;let q=B.value;return O(q)?k&&j&&H?.async===!1&&H.jitless!==!0?(D||=E(t.shape),B=D(B,H),F?handleCatchall([],q,B,H,L,e):B):S(B,H):(B.issues.push({expected:`object`,code:`invalid_type`,input:q,inst:e}),B)}});function handleUnionResults(e,t,S,w){for(let S of e)if(S.issues.length===0)return t.value=S.value,t;let E=e.filter(e=>!aborted(e));return E.length===1?(t.value=E[0].value,E[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:S,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,w,config())))}),t)}const $ZodUnion=$constructor(`$ZodUnion`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),defineLazy(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazy(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let S=t.options.length===1,w=t.options[0]._zod.run;e._zod.parse=(E,D)=>{if(S)return w(E,D);let O=!1,k=[];for(let e of t.options){let t=e._zod.run({value:E.value,issues:[]},D);if(t instanceof Promise)k.push(t),O=!0;else{if(t.issues.length===0)return t;k.push(t)}}return O?Promise.all(k).then(t=>handleUnionResults(t,E,e,D)):handleUnionResults(k,E,e,D)}}),$ZodDiscriminatedUnion=$constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,$ZodUnion.init(e,t);let S=e._zod.parse;defineLazy(e._zod,`propValues`,()=>{let e={};for(let S of t.options){let w=S._zod.propValues;if(!w||Object.keys(w).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(S)}"`);for(let[t,S]of Object.entries(w)){e[t]||(e[t]=new Set);for(let w of S)e[t].add(w)}}return e});let w=cached(()=>{let e=t.options,S=new Map;for(let w of e){let e=w._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(w)}"`);for(let t of e){if(S.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);S.set(t,w)}}return S});e._zod.parse=(E,D)=>{let O=E.value;if(!isObject$1(O))return E.issues.push({code:`invalid_type`,expected:`object`,input:O,inst:e}),E;let k=w.value.get(O?.[t.discriminator]);return k?k._zod.run(E,D):t.unionFallback?S(E,D):(E.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,input:O,path:[t.discriminator],inst:e}),E)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,S)=>{let w=e.value,E=t.left._zod.run({value:w,issues:[]},S),D=t.right._zod.run({value:w,issues:[]},S);return E instanceof Promise||D instanceof Promise?Promise.all([E,D]).then(([t,S])=>handleIntersectionResults(e,t,S)):handleIntersectionResults(e,E,D)}});function mergeValues$1(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject$4(e)&&isPlainObject$4(t)){let S=Object.keys(t),w=Object.keys(e).filter(e=>S.indexOf(e)!==-1),E={...e,...t};for(let S of w){let w=mergeValues$1(e[S],t[S]);if(!w.valid)return{valid:!1,mergeErrorPath:[S,...w.mergeErrorPath]};E[S]=w.data}return{valid:!0,data:E}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let S=[];for(let w=0;w<e.length;w++){let E=e[w],D=t[w],O=mergeValues$1(E,D);if(!O.valid)return{valid:!1,mergeErrorPath:[w,...O.mergeErrorPath]};S.push(O.data)}return{valid:!0,data:S}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,S){let w=new Map,E;for(let S of t.issues)if(S.code===`unrecognized_keys`){E??=S;for(let e of S.keys)w.has(e)||w.set(e,{}),w.get(e).l=!0}else e.issues.push(S);for(let t of S.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)w.has(e)||w.set(e,{}),w.get(e).r=!0;else e.issues.push(t);let D=[...w].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(D.length&&E&&e.issues.push({...E,keys:D}),aborted(e))return e;let O=mergeValues$1(t.value,S.value);if(!O.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(O.mergeErrorPath)}`);return e.value=O.data,e}const $ZodRecord=$constructor(`$ZodRecord`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(S,w)=>{let E=S.value;if(!isPlainObject$4(E))return S.issues.push({expected:`record`,code:`invalid_type`,input:E,inst:e}),S;let D=[],O=t.keyType._zod.values;if(O){S.value={};let k=new Set;for(let e of O)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){k.add(typeof e==`number`?e.toString():e);let O=t.valueType._zod.run({value:E[e],issues:[]},w);O instanceof Promise?D.push(O.then(t=>{t.issues.length&&S.issues.push(...prefixIssues(e,t.issues)),S.value[e]=t.value})):(O.issues.length&&S.issues.push(...prefixIssues(e,O.issues)),S.value[e]=O.value)}let j;for(let e in E)k.has(e)||(j??=[],j.push(e));j&&j.length>0&&S.issues.push({code:`unrecognized_keys`,input:E,inst:e,keys:j})}else{S.value={};for(let O of Reflect.ownKeys(E)){if(O===`__proto__`)continue;let k=t.keyType._zod.run({value:O,issues:[]},w);if(k instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof O==`string`&&number$2.test(O)&&k.issues.length){let e=t.keyType._zod.run({value:Number(O),issues:[]},w);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(k=e)}if(k.issues.length){t.mode===`loose`?S.value[O]=E[O]:S.issues.push({code:`invalid_key`,origin:`record`,issues:k.issues.map(e=>finalizeIssue(e,w,config())),input:O,path:[O],inst:e});continue}let j=t.valueType._zod.run({value:E[O],issues:[]},w);j instanceof Promise?D.push(j.then(e=>{e.issues.length&&S.issues.push(...prefixIssues(O,e.issues)),S.value[k.value]=e.value})):(j.issues.length&&S.issues.push(...prefixIssues(O,j.issues)),S.value[k.value]=j.value)}}return D.length?Promise.all(D).then(()=>S):S}}),$ZodEnum=$constructor(`$ZodEnum`,(e,t)=>{$ZodType.init(e,t);let S=getEnumValues(t.entries),w=new Set(S);e._zod.values=w,e._zod.pattern=RegExp(`^(${S.filter(e=>propertyKeyTypes.has(typeof e)).map(e=>typeof e==`string`?escapeRegex$1(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,E)=>{let D=t.value;return w.has(D)||t.issues.push({code:`invalid_value`,values:S,input:D,inst:e}),t}}),$ZodLiteral=$constructor(`$ZodLiteral`,(e,t)=>{if($ZodType.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let S=new Set(t.values);e._zod.values=S,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?escapeRegex$1(e):e?escapeRegex$1(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(w,E)=>{let D=w.value;return S.has(D)||w.issues.push({code:`invalid_value`,values:t.values,input:D,inst:e}),w}}),$ZodTransform=$constructor(`$ZodTransform`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let E=t.transform(S.value,S);if(w.async)return(E instanceof Promise?E:Promise.resolve(E)).then(e=>(S.value=e,S));if(E instanceof Promise)throw new $ZodAsyncError;return S.value=E,S}});function handleOptionalResult(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const $ZodOptional=$constructor(`$ZodOptional`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,S)=>{if(t.innerType._zod.optin===`optional`){let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(w,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,S)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(e,t)=>{$ZodOptional.init(e,t),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,S)=>t.innerType._zod.run(e,S)}),$ZodNullable=$constructor(`$ZodNullable`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.innerType._zod.optin),defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)}|null)$`):void 0}),defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,S)=>e.value===null?e:t.innerType._zod.run(e,S)}),$ZodDefault=$constructor(`$ZodDefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);if(e.value===void 0)return e.value=t.defaultValue,e;let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(e=>handleDefaultResult(e,t)):handleDefaultResult(w,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const $ZodPrefault=$constructor(`$ZodPrefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>(S.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,S))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(S,w)=>{let E=t.innerType._zod.run(S,w);return E instanceof Promise?E.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(E,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const $ZodCatch=$constructor(`$ZodCatch`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.innerType._zod.optin),defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(w=>(e.value=w.value,w.issues.length&&(e.value=t.catchValue({...e,error:{issues:w.issues.map(e=>finalizeIssue(e,S,config()))},input:e.value}),e.issues=[]),e)):(e.value=w.value,w.issues.length&&(e.value=t.catchValue({...e,error:{issues:w.issues.map(e=>finalizeIssue(e,S,config()))},input:e.value}),e.issues=[]),e)}}),$ZodPipe=$constructor(`$ZodPipe`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>t.in._zod.values),defineLazy(e._zod,`optin`,()=>t.in._zod.optin),defineLazy(e._zod,`optout`,()=>t.out._zod.optout),defineLazy(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,S)=>{if(S.direction===`backward`){let w=t.out._zod.run(e,S);return w instanceof Promise?w.then(e=>handlePipeResult(e,t.in,S)):handlePipeResult(w,t.in,S)}let w=t.in._zod.run(e,S);return w instanceof Promise?w.then(e=>handlePipeResult(e,t.out,S)):handlePipeResult(w,t.out,S)}});function handlePipeResult(e,t,S){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},S)}const $ZodReadonly=$constructor(`$ZodReadonly`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`propValues`,()=>t.innerType._zod.propValues),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`optin`,()=>t.innerType?._zod?.optin),defineLazy(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,S)=>{if(S.direction===`backward`)return t.innerType._zod.run(e,S);let w=t.innerType._zod.run(e,S);return w instanceof Promise?w.then(handleReadonlyResult):handleReadonlyResult(w)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}const $ZodCustom=$constructor(`$ZodCustom`,(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=S=>{let w=S.value,E=t.fn(w);if(E instanceof Promise)return E.then(t=>handleRefineResult(t,S,w,e));handleRefineResult(E,S,w,e)}});function handleRefineResult(e,t,S,w){if(!e){let e={code:`custom`,input:S,inst:w,path:[...w._zod.def.path??[]],continue:!w._zod.def.abort};w._zod.def.params&&(e.params=w._zod.def.params),t.issues.push(issue(e))}}var _a$2,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let S=t[0];return this._map.set(e,S),S&&typeof S==`object`&&`id`in S&&this._idmap.set(S.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let S={...this.get(t)??{}};delete S.id;let w={...S,...this._map.get(e)};return Object.keys(w).length?w:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry$1(){return new $ZodRegistry}(_a$2=globalThis).__zod_globalRegistry??(_a$2.__zod_globalRegistry=registry$1());const globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:`string`,...normalizeParams(t)})}function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}function _number(e,t){return new e({type:`number`,checks:[],...normalizeParams(t)})}function _coercedNumber(e,t){return new e({type:`number`,coerce:!0,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}function _null$1(e,t){return new e({type:`null`,...normalizeParams(t)})}function _any(e){return new e({type:`any`})}function _unknown(e){return new e({type:`unknown`})}function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:`multiple_of`,...normalizeParams(t),value:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:`overwrite`,tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _slugify(){return _overwrite(e=>slugify(e))}function _array(e,t,S){return new e({type:`array`,element:t,...normalizeParams(S)})}function _custom(e,t,S){let w=normalizeParams(S);return w.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...w})}function _refine(e,t,S){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(S)})}function _superRefine(e){let t=_check(S=>(S.addIssue=e=>{if(typeof e==`string`)S.issues.push(issue(e,S.value,t._zod.def));else{let w=e;w.fatal&&(w.continue=!1),w.code??=`custom`,w.input??=S.value,w.inst??=t,w.continue??=!t._zod.def.abort,S.issues.push(issue(w))}},e(S.value,S)));return t}function _check(e,t){let S=new $ZodCheck({check:`custom`,...normalizeParams(t)});return S._zod.check=e,S}function describe$2(e){let t=new $ZodCheck({check:`describe`});return t._zod.onattach=[t=>{let S=globalRegistry.get(t)??{};globalRegistry.add(t,{...S,description:e})}],t._zod.check=()=>{},t}function meta$2(e){let t=new $ZodCheck({check:`meta`});return t._zod.onattach=[t=>{let S=globalRegistry.get(t)??{};globalRegistry.add(t,{...S,...e})}],t._zod.check=()=>{},t}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function process$5(e,t,S={path:[],schemaPath:[]}){var w;let E=e._zod.def,D=t.seen.get(e);if(D)return D.count++,S.schemaPath.includes(e)&&(D.cycle=S.path),D.schema;let O={schema:{},count:1,cycle:void 0,path:S.path};t.seen.set(e,O);let k=e._zod.toJSONSchema?.();if(k)O.schema=k;else{let w={...S,schemaPath:[...S.schemaPath,e],path:S.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,O.schema,w);else{let S=O.schema,D=t.processors[E.type];if(!D)throw Error(`[toJSONSchema]: Non-representable type encountered: ${E.type}`);D(e,t,S,w)}let D=e._zod.parent;D&&(O.ref||=D,process$5(D,t,w),t.seen.get(D).isParent=!0)}let j=t.metadataRegistry.get(e);return j&&Object.assign(O.schema,j),t.io===`input`&&isTransforming(e)&&(delete O.schema.examples,delete O.schema.default),t.io===`input`&&O.schema._prefault&&((w=O.schema).default??(w.default=O.schema._prefault)),delete O.schema._prefault,t.seen.get(e).schema}function extractDefs(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=new Map;for(let t of e.seen.entries()){let S=e.metadataRegistry.get(t[0])?.id;if(S){let e=w.get(S);if(e&&e!==t[0])throw Error(`Duplicate schema id "${S}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);w.set(S,t[0])}}let E=t=>{let w=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let S=e.external.registry.get(t[0])?.id,E=e.external.uri??(e=>e);if(S)return{ref:E(S)};let D=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=D,{defId:D,ref:`${E(`__shared`)}#/${w}/${D}`}}if(t[1]===S)return{ref:`#`};let E=`#/${w}/`,D=t[1].schema.id??`__schema${e.counter++}`;return{defId:D,ref:E+D}},D=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:S,defId:w}=E(e);t.def={...t.schema},w&&(t.defId=w);let D=t.schema;for(let e in D)delete D[e];D.$ref=S};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
153
153
|
|
|
154
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let S of e.seen.entries()){let w=S[1];if(t===S[0]){D(S);continue}if(e.external){let w=e.external.registry.get(S[0])?.id;if(t!==S[0]&&w){D(S);continue}}if(e.metadataRegistry.get(S[0])?.id){D(S);continue}if(w.cycle){D(S);continue}if(w.count>1&&e.reused===`ref`){D(S);continue}}}function finalize(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=t=>{let S=e.seen.get(t);if(S.ref===null)return;let E=S.def??S.schema,D={...E},O=S.ref;if(S.ref=null,O){w(O);let S=e.seen.get(O),k=S.schema;if(k.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(E.allOf=E.allOf??[],E.allOf.push(k)):Object.assign(E,k),Object.assign(E,D),t._zod.parent===O)for(let e in E)e===`$ref`||e===`allOf`||e in D||delete E[e];if(k.$ref&&S.def)for(let e in E)e===`$ref`||e===`allOf`||e in S.def&&JSON.stringify(E[e])===JSON.stringify(S.def[e])&&delete E[e]}let k=t._zod.parent;if(k&&k!==O){w(k);let t=e.seen.get(k);if(t?.schema.$ref&&(E.$ref=t.schema.$ref,t.def))for(let e in E)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(E[e])===JSON.stringify(t.def[e])&&delete E[e]}e.override({zodSchema:t,jsonSchema:E,path:S.path??[]})};for(let t of[...e.seen.entries()].reverse())w(t[0]);let E={};if(e.target===`draft-2020-12`?E.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?E.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?E.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let S=e.external.registry.get(t)?.id;if(!S)throw Error("Schema is missing an `id` property");E.$id=e.external.uri(S)}Object.assign(E,S.def??S.schema);let D=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(D[e.defId]=e.def)}e.external||Object.keys(D).length>0&&(e.target===`draft-2020-12`?E.$defs=D:E.definitions=D);try{let S=JSON.parse(JSON.stringify(E));return Object.defineProperty(S,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),S}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let S=t??{seen:new Set};if(S.seen.has(e))return!1;S.seen.add(e);let w=e._zod.def;if(w.type===`transform`)return!0;if(w.type===`array`)return isTransforming(w.element,S);if(w.type===`set`)return isTransforming(w.valueType,S);if(w.type===`lazy`)return isTransforming(w.getter(),S);if(w.type===`promise`||w.type===`optional`||w.type===`nonoptional`||w.type===`nullable`||w.type===`readonly`||w.type===`default`||w.type===`prefault`)return isTransforming(w.innerType,S);if(w.type===`intersection`)return isTransforming(w.left,S)||isTransforming(w.right,S);if(w.type===`record`||w.type===`map`)return isTransforming(w.keyType,S)||isTransforming(w.valueType,S);if(w.type===`pipe`)return isTransforming(w.in,S)||isTransforming(w.out,S);if(w.type===`object`){for(let e in w.shape)if(isTransforming(w.shape[e],S))return!0;return!1}if(w.type===`union`){for(let e of w.options)if(isTransforming(e,S))return!0;return!1}if(w.type===`tuple`){for(let e of w.items)if(isTransforming(e,S))return!0;return!!(w.rest&&isTransforming(w.rest,S))}return!1}const createToJSONSchemaMethod=(e,t={})=>S=>{let w=initializeContext({...S,processors:t});return process$5(e,w),extractDefs(w,e),finalize(w,e)},createStandardJSONSchemaMethod=(e,t,S={})=>w=>{let{libraryOptions:E,target:D}=w??{},O=initializeContext({...E??{},target:D,io:t,processors:S});return process$5(e,O),extractDefs(O,e),finalize(O,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,S,w)=>{let E=S;E.type=`string`;let{minimum:D,maximum:O,format:k,patterns:j,contentEncoding:F}=e._zod.bag;if(typeof D==`number`&&(E.minLength=D),typeof O==`number`&&(E.maxLength=O),k&&(E.format=formatMap[k]??k,E.format===``&&delete E.format,k===`time`&&delete E.format),F&&(E.contentEncoding=F),j&&j.size>0){let e=[...j];e.length===1?E.pattern=e[0].source:e.length>1&&(E.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,S,w)=>{let E=S,{minimum:D,maximum:O,format:k,multipleOf:j,exclusiveMaximum:F,exclusiveMinimum:L}=e._zod.bag;typeof k==`string`&&k.includes(`int`)?E.type=`integer`:E.type=`number`,typeof L==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.minimum=L,E.exclusiveMinimum=!0):E.exclusiveMinimum=L),typeof D==`number`&&(E.minimum=D,typeof L==`number`&&t.target!==`draft-04`&&(L>=D?delete E.minimum:delete E.exclusiveMinimum)),typeof F==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.maximum=F,E.exclusiveMaximum=!0):E.exclusiveMaximum=F),typeof O==`number`&&(E.maximum=O,typeof F==`number`&&t.target!==`draft-04`&&(F<=O?delete E.maximum:delete E.exclusiveMaximum)),typeof j==`number`&&(E.multipleOf=j)},booleanProcessor=(e,t,S,w)=>{S.type=`boolean`},bigintProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,S,w)=>{t.target===`openapi-3.0`?(S.type=`string`,S.nullable=!0,S.enum=[null]):S.type=`null`},undefinedProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,S,w)=>{S.not={}},anyProcessor=(e,t,S,w)=>{},unknownProcessor=(e,t,S,w)=>{},dateProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,S,w)=>{let E=e._zod.def,D=getEnumValues(E.entries);D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),S.enum=D},literalProcessor=(e,t,S,w)=>{let E=e._zod.def,D=[];for(let e of E.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);D.push(Number(e))}else D.push(e);if(D.length!==0)if(D.length===1){let e=D[0];S.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?S.enum=[e]:S.const=e}else D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),D.every(e=>typeof e==`boolean`)&&(S.type=`boolean`),D.every(e=>e===null)&&(S.type=`null`),S.enum=D},nanProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,S,w)=>{let E=S,D=e._zod.pattern;if(!D)throw Error(`Pattern not found in template literal`);E.type=`string`,E.pattern=D.source},fileProcessor=(e,t,S,w)=>{let E=S,D={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:O,maximum:k,mime:j}=e._zod.bag;O!==void 0&&(D.minLength=O),k!==void 0&&(D.maxLength=k),j?j.length===1?(D.contentMediaType=j[0],Object.assign(E,D)):(Object.assign(E,D),E.anyOf=j.map(e=>({contentMediaType:e}))):Object.assign(E,D)},successProcessor=(e,t,S,w)=>{S.type=`boolean`},customProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def,{minimum:O,maximum:k}=e._zod.bag;typeof O==`number`&&(E.minItems=O),typeof k==`number`&&(E.maxItems=k),E.type=`array`,E.items=process$5(D.element,t,{...w,path:[...w.path,`items`]})},objectProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`,E.properties={};let O=D.shape;for(let e in O)E.properties[e]=process$5(O[e],t,{...w,path:[...w.path,`properties`,e]});let k=new Set(Object.keys(O)),j=new Set([...k].filter(e=>{let S=D.shape[e]._zod;return t.io===`input`?S.optin===void 0:S.optout===void 0}));j.size>0&&(E.required=Array.from(j)),D.catchall?._zod.def.type===`never`?E.additionalProperties=!1:D.catchall?D.catchall&&(E.additionalProperties=process$5(D.catchall,t,{...w,path:[...w.path,`additionalProperties`]})):t.io===`output`&&(E.additionalProperties=!1)},unionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=E.inclusive===!1,O=E.options.map((e,S)=>process$5(e,t,{...w,path:[...w.path,D?`oneOf`:`anyOf`,S]}));D?S.oneOf=O:S.anyOf=O},intersectionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.left,t,{...w,path:[...w.path,`allOf`,0]}),O=process$5(E.right,t,{...w,path:[...w.path,`allOf`,1]}),k=e=>`allOf`in e&&Object.keys(e).length===1;S.allOf=[...k(D)?D.allOf:[D],...k(O)?O.allOf:[O]]},tupleProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`array`;let O=t.target===`draft-2020-12`?`prefixItems`:`items`,k=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,j=D.items.map((e,S)=>process$5(e,t,{...w,path:[...w.path,O,S]})),F=D.rest?process$5(D.rest,t,{...w,path:[...w.path,k,...t.target===`openapi-3.0`?[D.items.length]:[]]}):null;t.target===`draft-2020-12`?(E.prefixItems=j,F&&(E.items=F)):t.target===`openapi-3.0`?(E.items={anyOf:j},F&&E.items.anyOf.push(F),E.minItems=j.length,F||(E.maxItems=j.length)):(E.items=j,F&&(E.additionalItems=F));let{minimum:L,maximum:B}=e._zod.bag;typeof L==`number`&&(E.minItems=L),typeof B==`number`&&(E.maxItems=B)},recordProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`;let O=D.keyType,k=O._zod.bag?.patterns;if(D.mode===`loose`&&k&&k.size>0){let e=process$5(D.valueType,t,{...w,path:[...w.path,`patternProperties`,`*`]});E.patternProperties={};for(let t of k)E.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(E.propertyNames=process$5(D.keyType,t,{...w,path:[...w.path,`propertyNames`]})),E.additionalProperties=process$5(D.valueType,t,{...w,path:[...w.path,`additionalProperties`]});let j=O._zod.values;if(j){let e=[...j].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(E.required=e)}},nullableProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.innerType,t,w),O=t.seen.get(e);t.target===`openapi-3.0`?(O.ref=E.innerType,S.nullable=!0):S.anyOf=[D,{type:`null`}]},nonoptionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},defaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.default=JSON.parse(JSON.stringify(E.defaultValue))},prefaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,t.io===`input`&&(S._prefault=JSON.parse(JSON.stringify(E.defaultValue)))},catchProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType;let O;try{O=E.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}S.default=O},pipeProcessor=(e,t,S,w)=>{let E=e._zod.def,D=t.io===`input`?E.in._zod.def.type===`transform`?E.out:E.in:E.out;process$5(D,t,w);let O=t.seen.get(e);O.ref=D},readonlyProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.readOnly=!0},promiseProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},optionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},lazyProcessor=(e,t,S,w)=>{let E=e._zod.innerType;process$5(E,t,w);let D=t.seen.get(e);D.ref=E},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if(`_idmap`in e){let S=e,w=initializeContext({...t,processors:allProcessors}),E={};for(let e of S._idmap.entries()){let[t,S]=e;process$5(S,w)}let D={};w.external={registry:S,uri:t?.uri,defs:E};for(let e of S._idmap.entries()){let[t,S]=e;extractDefs(w,S),D[t]=finalize(w,S)}return Object.keys(E).length>0&&(D.__shared={[w.target===`draft-2020-12`?`$defs`:`definitions`]:E}),{schemas:D}}let S=initializeContext({...t,processors:allProcessors});return process$5(e,S),extractDefs(S,e),finalize(S,e)}const ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodError$1=$constructor(`ZodError`,initializer),ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse$5=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse$1=_safeParse(ZodRealError),safeParseAsync$1=_safeParseAsync(ZodRealError),encode$1=_encode(ZodRealError),decode$1=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType$1=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...S)=>e.clone(mergeDefs(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.parse=(t,S)=>parse$5(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.spa=e.safeParseAsync,e.encode=(t,S)=>encode$1(e,t,S),e.decode=(t,S)=>decode$1(e,t,S),e.encodeAsync=async(t,S)=>encodeAsync(e,t,S),e.decodeAsync=async(t,S)=>decodeAsync(e,t,S),e.safeEncode=(t,S)=>safeEncode(e,t,S),e.safeDecode=(t,S)=>safeDecode(e,t,S),e.safeEncodeAsync=async(t,S)=>safeEncodeAsync(e,t,S),e.safeDecodeAsync=async(t,S)=>safeDecodeAsync(e,t,S),e.refine=(t,S)=>e.check(refine(t,S)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.exactOptional=()=>exactOptional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{let S=e.clone();return globalRegistry.add(S,{description:t}),S},Object.defineProperty(e,`description`,{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return globalRegistry.get(e);let S=e.clone();return globalRegistry.add(S,t[0]),S},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>stringProcessor(e,t,S,w);let S=e._zod.bag;e.format=S.format??null,e.minLength=S.minimum??null,e.maxLength=S.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase()),e.slugify=()=>e.check(_slugify())}),ZodString$1=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$2(e){return _string(ZodString$1,e)}const ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber$1=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>numberProcessor(e,t,S,w),e.gt=(t,S)=>e.check(_gt(t,S)),e.gte=(t,S)=>e.check(_gte(t,S)),e.min=(t,S)=>e.check(_gte(t,S)),e.lt=(t,S)=>e.check(_lt(t,S)),e.lte=(t,S)=>e.check(_lte(t,S)),e.max=(t,S)=>e.check(_lte(t,S)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,S)=>e.check(_multipleOf(t,S)),e.step=(t,S)=>e.check(_multipleOf(t,S)),e.finite=()=>e;let S=e._zod.bag;e.minValue=Math.max(S.minimum??-1/0,S.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(S.maximum??1/0,S.exclusiveMaximum??1/0)??null,e.isInt=(S.format??``).includes(`int`)||Number.isSafeInteger(S.multipleOf??.5),e.isFinite=!0,e.format=S.format??null});function number$1(e){return _number(ZodNumber$1,e)}const ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber$1.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean$1=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>booleanProcessor(e,t,S,w)});function boolean$1(e){return _boolean(ZodBoolean$1,e)}const ZodNull$1=$constructor(`ZodNull`,(e,t)=>{$ZodNull.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullProcessor(e,t,S,w)});function _null(e){return _null$1(ZodNull$1,e)}const ZodAny$1=$constructor(`ZodAny`,(e,t)=>{$ZodAny.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function any$1(){return _any(ZodAny$1)}const ZodUnknown$1=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function unknown$2(){return _unknown(ZodUnknown$1)}const ZodNever$1=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>neverProcessor(e,t,S,w)});function never(e){return _never(ZodNever$1,e)}const ZodArray$1=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>arrayProcessor(e,t,S,w),e.element=t.element,e.min=(t,S)=>e.check(_minLength(t,S)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,S)=>e.check(_maxLength(t,S)),e.length=(t,S)=>e.check(_length(t,S)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray$1,e,t)}const ZodObject$1=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>objectProcessor(e,t,S,w),defineLazy(e,`shape`,()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend$1(e,t),e.safeExtend=t=>safeExtend(e,t),e.merge=t=>merge$1(e,t),e.pick=t=>pick$2(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional$1,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object$1(e,t){return new ZodObject$1({type:`object`,shape:e??{},...normalizeParams(t)})}function looseObject(e,t){return new ZodObject$1({type:`object`,shape:e,catchall:unknown$2(),...normalizeParams(t)})}const ZodUnion$1=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>unionProcessor(e,t,S,w),e.options=t.options});function union(e,t){return new ZodUnion$1({type:`union`,options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion$1=$constructor(`ZodDiscriminatedUnion`,(e,t)=>{ZodUnion$1.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,S){return new ZodDiscriminatedUnion$1({type:`union`,options:t,discriminator:e,...normalizeParams(S)})}const ZodIntersection$1=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>intersectionProcessor(e,t,S,w)});function intersection(e,t){return new ZodIntersection$1({type:`intersection`,left:e,right:t})}const ZodRecord$1=$constructor(`ZodRecord`,(e,t)=>{$ZodRecord.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>recordProcessor(e,t,S,w),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,S){return new ZodRecord$1({type:`record`,keyType:e,valueType:t,...normalizeParams(S)})}const ZodEnum$1=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>enumProcessor(e,t,S,w),e.enum=t.entries,e.options=Object.values(t.entries);let S=new Set(Object.keys(t.entries));e.extract=(e,w)=>{let E={};for(let w of e)if(S.has(w))E[w]=t.entries[w];else throw Error(`Key ${w} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})},e.exclude=(e,w)=>{let E={...t.entries};for(let t of e)if(S.has(t))delete E[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})}});function _enum(e,t){return new ZodEnum$1({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}const ZodLiteral$1=$constructor(`ZodLiteral`,(e,t)=>{$ZodLiteral.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>literalProcessor(e,t,S,w),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral$1({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>transformProcessor(e,t,S,w),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);S.addIssue=w=>{if(typeof w==`string`)S.issues.push(issue(w,S.value,t));else{let t=w;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=S.value,t.inst??=e,S.issues.push(issue(t))}};let E=t.transform(S.value,S);return E instanceof Promise?E.then(e=>(S.value=e,S)):(S.value=E,S)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}const ZodOptional$1=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional$1({type:`optional`,innerType:e})}const ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}const ZodNullable$1=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullableProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable$1({type:`nullable`,innerType:e})}const ZodDefault$1=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>defaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault$1({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>prefaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nonoptionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const ZodCatch$1=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>catchProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch$1({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>pipeProcessor(e,t,S,w),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}const ZodReadonly$1=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>readonlyProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly$1({type:`readonly`,innerType:e})}const ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>customProcessor(e,t,S,w)});function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}const describe$1=describe$2,meta$1=meta$2;function preprocess$1(e,t){return pipe(transform(e),t)}var import_dist$1=require_dist$2();init_esm$2();const SINGLETON_KEY$1=Symbol.for(`@inkeep/open-knowledge/field-registry`),g$1=globalThis;g$1[SINGLETON_KEY$1]===void 0&&(g$1[SINGLETON_KEY$1]=registry$1());const fieldRegistry=g$1[SINGLETON_KEY$1];function getFieldMeta(e){let t=e;for(let e=0;e<16;e++){if(t==null)return;let e=isZodSchema$1(t)?fieldRegistry.get(t):void 0;if(e!==void 0)return e;let S=t._zod?.def?.innerType;if(S===void 0)return;t=S}}function isZodSchema$1(e){return typeof e==`object`&&!!e&&`_zod`in e&&`parse`in e}const FolderFrontmatterSchema=looseObject({title:string$2().optional(),description:string$2().optional(),tags:array(string$2()).optional()}),FolderRuleSchema=looseObject({match:string$2().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:FolderFrontmatterSchema}),ConfigSchema$1=looseObject({content:looseObject({dir:string$2().register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`.`)}).default({dir:`.`}),preview:looseObject({scriptSrc:_enum([`cdn-allowlist`,`inline-only`]).register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`cdn-allowlist`)}).default({scriptSrc:`cdn-allowlist`}),appearance:looseObject({theme:_enum([`light`,`dark`,`system`]).register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).optional(),sidebar:looseObject({showHiddenFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1),showAllFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1)}).optional()}).default({}),editor:looseObject({wordWrap:boolean$1().register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).default(!0)}).default({wordWrap:!0}),autoSync:looseObject({enabled:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).nullable().default(null)}).default({enabled:null})}),TRACER_NAME$1=`open-knowledge-config`;async function withConfigSpan(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,async e=>{try{return await S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withConfigSpanSync(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function addConfigSpanEvent(e,t){let S=trace.getActiveSpan();S&&S.addEvent(e,t)}function unwrapToShape(e){let t=e;for(let e=0;e<16;e++){if(t==null||t?._zod?.def?.shape!==void 0)return t;let e=t?._zod?.def?.innerType;if(e===void 0)return t;t=e}return t}function resolveLeafSchema(e,t){let S=e;for(let e of t){S=unwrapToShape(S);let t=S?._zod?.def?.shape;if(!t||(S=t[String(e)],S===void 0))return}return S}function getLeafFieldMeta(e,t){let S=resolveLeafSchema(e,t);if(S!==void 0)return getFieldMeta(S)}function isScopeCompatible(e,t){return e===`either`?!0:e===t}function validatePatchScopes(e,t){let S=null;function w(e,E){if(S!==null||e===void 0)return;if(typeof e==`object`&&e&&!Array.isArray(e)){for(let[t,D]of Object.entries(e))if(w(D,[...E,t]),S!==null)return;return}let D=getLeafFieldMeta(ConfigSchema$1,E);D?.scope!==void 0&&(isScopeCompatible(D.scope,t)||(S={code:`SCOPE_VIOLATION`,path:E,expectedScope:D.scope,actualScope:t}))}for(let[t,E]of Object.entries(e))if(w(E,[t]),S!==null)break;return S}function ensureCollectionAncestors(e,t){for(let S=1;S<t.length;S++){let w=t.slice(0,S);e.hasIn(w)&&((0,import_dist$1.isCollection)(e.getIn(w,!0))||e.deleteIn(w))}}function applyPatchToDocument(e,t){let S=[];function w(t,E){if(t!==void 0){if(t===null){e.deleteIn(E),S.push(E.join(`.`));return}if(Array.isArray(t)){ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`));return}if(typeof t==`object`){for(let[e,S]of Object.entries(t))w(S,[...E,e]);return}ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`))}}for(let[e,S]of Object.entries(t))w(S,[e]);return S}function toConfigIssue(e){return{path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}}const CONFIG_SCHEMA_MAJOR_PATH=`v0`;function resolveNode(e,t){if(t.length===0)return e.contents??null;let S=e.getIn(t,!0);if((0,import_dist$1.isNode)(S))return S;for(let S=t.length-1;S>=0;S--){let w=e.getIn(t.slice(0,S),!0);if((0,import_dist$1.isNode)(w))return w}return e.contents??null}function offsetToLineCol(e,t){let S=1,w=1,E=Math.min(t,e.length);for(let t=0;t<E;t++)e.charCodeAt(t)===10?(S++,w=1):w++;return{line:S,column:w}}function renderSnippet(e,t,S,w,E){let D=e.split(`
|
|
154
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let S of e.seen.entries()){let w=S[1];if(t===S[0]){D(S);continue}if(e.external){let w=e.external.registry.get(S[0])?.id;if(t!==S[0]&&w){D(S);continue}}if(e.metadataRegistry.get(S[0])?.id){D(S);continue}if(w.cycle){D(S);continue}if(w.count>1&&e.reused===`ref`){D(S);continue}}}function finalize(e,t){let S=e.seen.get(t);if(!S)throw Error(`Unprocessed schema. This is a bug in Zod.`);let w=t=>{let S=e.seen.get(t);if(S.ref===null)return;let E=S.def??S.schema,D={...E},O=S.ref;if(S.ref=null,O){w(O);let S=e.seen.get(O),k=S.schema;if(k.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(E.allOf=E.allOf??[],E.allOf.push(k)):Object.assign(E,k),Object.assign(E,D),t._zod.parent===O)for(let e in E)e===`$ref`||e===`allOf`||e in D||delete E[e];if(k.$ref&&S.def)for(let e in E)e===`$ref`||e===`allOf`||e in S.def&&JSON.stringify(E[e])===JSON.stringify(S.def[e])&&delete E[e]}let k=t._zod.parent;if(k&&k!==O){w(k);let t=e.seen.get(k);if(t?.schema.$ref&&(E.$ref=t.schema.$ref,t.def))for(let e in E)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(E[e])===JSON.stringify(t.def[e])&&delete E[e]}e.override({zodSchema:t,jsonSchema:E,path:S.path??[]})};for(let t of[...e.seen.entries()].reverse())w(t[0]);let E={};if(e.target===`draft-2020-12`?E.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?E.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?E.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let S=e.external.registry.get(t)?.id;if(!S)throw Error("Schema is missing an `id` property");E.$id=e.external.uri(S)}Object.assign(E,S.def??S.schema);let D=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(D[e.defId]=e.def)}e.external||Object.keys(D).length>0&&(e.target===`draft-2020-12`?E.$defs=D:E.definitions=D);try{let S=JSON.parse(JSON.stringify(E));return Object.defineProperty(S,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),S}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let S=t??{seen:new Set};if(S.seen.has(e))return!1;S.seen.add(e);let w=e._zod.def;if(w.type===`transform`)return!0;if(w.type===`array`)return isTransforming(w.element,S);if(w.type===`set`)return isTransforming(w.valueType,S);if(w.type===`lazy`)return isTransforming(w.getter(),S);if(w.type===`promise`||w.type===`optional`||w.type===`nonoptional`||w.type===`nullable`||w.type===`readonly`||w.type===`default`||w.type===`prefault`)return isTransforming(w.innerType,S);if(w.type===`intersection`)return isTransforming(w.left,S)||isTransforming(w.right,S);if(w.type===`record`||w.type===`map`)return isTransforming(w.keyType,S)||isTransforming(w.valueType,S);if(w.type===`pipe`)return isTransforming(w.in,S)||isTransforming(w.out,S);if(w.type===`object`){for(let e in w.shape)if(isTransforming(w.shape[e],S))return!0;return!1}if(w.type===`union`){for(let e of w.options)if(isTransforming(e,S))return!0;return!1}if(w.type===`tuple`){for(let e of w.items)if(isTransforming(e,S))return!0;return!!(w.rest&&isTransforming(w.rest,S))}return!1}const createToJSONSchemaMethod=(e,t={})=>S=>{let w=initializeContext({...S,processors:t});return process$5(e,w),extractDefs(w,e),finalize(w,e)},createStandardJSONSchemaMethod=(e,t,S={})=>w=>{let{libraryOptions:E,target:D}=w??{},O=initializeContext({...E??{},target:D,io:t,processors:S});return process$5(e,O),extractDefs(O,e),finalize(O,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,S,w)=>{let E=S;E.type=`string`;let{minimum:D,maximum:O,format:k,patterns:j,contentEncoding:F}=e._zod.bag;if(typeof D==`number`&&(E.minLength=D),typeof O==`number`&&(E.maxLength=O),k&&(E.format=formatMap[k]??k,E.format===``&&delete E.format,k===`time`&&delete E.format),F&&(E.contentEncoding=F),j&&j.size>0){let e=[...j];e.length===1?E.pattern=e[0].source:e.length>1&&(E.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,S,w)=>{let E=S,{minimum:D,maximum:O,format:k,multipleOf:j,exclusiveMaximum:F,exclusiveMinimum:L}=e._zod.bag;typeof k==`string`&&k.includes(`int`)?E.type=`integer`:E.type=`number`,typeof L==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.minimum=L,E.exclusiveMinimum=!0):E.exclusiveMinimum=L),typeof D==`number`&&(E.minimum=D,typeof L==`number`&&t.target!==`draft-04`&&(L>=D?delete E.minimum:delete E.exclusiveMinimum)),typeof F==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(E.maximum=F,E.exclusiveMaximum=!0):E.exclusiveMaximum=F),typeof O==`number`&&(E.maximum=O,typeof F==`number`&&t.target!==`draft-04`&&(F<=O?delete E.maximum:delete E.exclusiveMaximum)),typeof j==`number`&&(E.multipleOf=j)},booleanProcessor=(e,t,S,w)=>{S.type=`boolean`},bigintProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,S,w)=>{t.target===`openapi-3.0`?(S.type=`string`,S.nullable=!0,S.enum=[null]):S.type=`null`},undefinedProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,S,w)=>{S.not={}},anyProcessor=(e,t,S,w)=>{},unknownProcessor=(e,t,S,w)=>{},dateProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,S,w)=>{let E=e._zod.def,D=getEnumValues(E.entries);D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),S.enum=D},literalProcessor=(e,t,S,w)=>{let E=e._zod.def,D=[];for(let e of E.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);D.push(Number(e))}else D.push(e);if(D.length!==0)if(D.length===1){let e=D[0];S.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?S.enum=[e]:S.const=e}else D.every(e=>typeof e==`number`)&&(S.type=`number`),D.every(e=>typeof e==`string`)&&(S.type=`string`),D.every(e=>typeof e==`boolean`)&&(S.type=`boolean`),D.every(e=>e===null)&&(S.type=`null`),S.enum=D},nanProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,S,w)=>{let E=S,D=e._zod.pattern;if(!D)throw Error(`Pattern not found in template literal`);E.type=`string`,E.pattern=D.source},fileProcessor=(e,t,S,w)=>{let E=S,D={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:O,maximum:k,mime:j}=e._zod.bag;O!==void 0&&(D.minLength=O),k!==void 0&&(D.maxLength=k),j?j.length===1?(D.contentMediaType=j[0],Object.assign(E,D)):(Object.assign(E,D),E.anyOf=j.map(e=>({contentMediaType:e}))):Object.assign(E,D)},successProcessor=(e,t,S,w)=>{S.type=`boolean`},customProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,S,w)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def,{minimum:O,maximum:k}=e._zod.bag;typeof O==`number`&&(E.minItems=O),typeof k==`number`&&(E.maxItems=k),E.type=`array`,E.items=process$5(D.element,t,{...w,path:[...w.path,`items`]})},objectProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`,E.properties={};let O=D.shape;for(let e in O)E.properties[e]=process$5(O[e],t,{...w,path:[...w.path,`properties`,e]});let k=new Set(Object.keys(O)),j=new Set([...k].filter(e=>{let S=D.shape[e]._zod;return t.io===`input`?S.optin===void 0:S.optout===void 0}));j.size>0&&(E.required=Array.from(j)),D.catchall?._zod.def.type===`never`?E.additionalProperties=!1:D.catchall?D.catchall&&(E.additionalProperties=process$5(D.catchall,t,{...w,path:[...w.path,`additionalProperties`]})):t.io===`output`&&(E.additionalProperties=!1)},unionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=E.inclusive===!1,O=E.options.map((e,S)=>process$5(e,t,{...w,path:[...w.path,D?`oneOf`:`anyOf`,S]}));D?S.oneOf=O:S.anyOf=O},intersectionProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.left,t,{...w,path:[...w.path,`allOf`,0]}),O=process$5(E.right,t,{...w,path:[...w.path,`allOf`,1]}),k=e=>`allOf`in e&&Object.keys(e).length===1;S.allOf=[...k(D)?D.allOf:[D],...k(O)?O.allOf:[O]]},tupleProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`array`;let O=t.target===`draft-2020-12`?`prefixItems`:`items`,k=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,j=D.items.map((e,S)=>process$5(e,t,{...w,path:[...w.path,O,S]})),F=D.rest?process$5(D.rest,t,{...w,path:[...w.path,k,...t.target===`openapi-3.0`?[D.items.length]:[]]}):null;t.target===`draft-2020-12`?(E.prefixItems=j,F&&(E.items=F)):t.target===`openapi-3.0`?(E.items={anyOf:j},F&&E.items.anyOf.push(F),E.minItems=j.length,F||(E.maxItems=j.length)):(E.items=j,F&&(E.additionalItems=F));let{minimum:L,maximum:B}=e._zod.bag;typeof L==`number`&&(E.minItems=L),typeof B==`number`&&(E.maxItems=B)},recordProcessor=(e,t,S,w)=>{let E=S,D=e._zod.def;E.type=`object`;let O=D.keyType,k=O._zod.bag?.patterns;if(D.mode===`loose`&&k&&k.size>0){let e=process$5(D.valueType,t,{...w,path:[...w.path,`patternProperties`,`*`]});E.patternProperties={};for(let t of k)E.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(E.propertyNames=process$5(D.keyType,t,{...w,path:[...w.path,`propertyNames`]})),E.additionalProperties=process$5(D.valueType,t,{...w,path:[...w.path,`additionalProperties`]});let j=O._zod.values;if(j){let e=[...j].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(E.required=e)}},nullableProcessor=(e,t,S,w)=>{let E=e._zod.def,D=process$5(E.innerType,t,w),O=t.seen.get(e);t.target===`openapi-3.0`?(O.ref=E.innerType,S.nullable=!0):S.anyOf=[D,{type:`null`}]},nonoptionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},defaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.default=JSON.parse(JSON.stringify(E.defaultValue))},prefaultProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,t.io===`input`&&(S._prefault=JSON.parse(JSON.stringify(E.defaultValue)))},catchProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType;let O;try{O=E.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}S.default=O},pipeProcessor=(e,t,S,w)=>{let E=e._zod.def,D=t.io===`input`?E.in._zod.def.type===`transform`?E.out:E.in:E.out;process$5(D,t,w);let O=t.seen.get(e);O.ref=D},readonlyProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType,S.readOnly=!0},promiseProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},optionalProcessor=(e,t,S,w)=>{let E=e._zod.def;process$5(E.innerType,t,w);let D=t.seen.get(e);D.ref=E.innerType},lazyProcessor=(e,t,S,w)=>{let E=e._zod.innerType;process$5(E,t,w);let D=t.seen.get(e);D.ref=E},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(e,t){if(`_idmap`in e){let S=e,w=initializeContext({...t,processors:allProcessors}),E={};for(let e of S._idmap.entries()){let[t,S]=e;process$5(S,w)}let D={};w.external={registry:S,uri:t?.uri,defs:E};for(let e of S._idmap.entries()){let[t,S]=e;extractDefs(w,S),D[t]=finalize(w,S)}return Object.keys(E).length>0&&(D.__shared={[w.target===`draft-2020-12`?`$defs`:`definitions`]:E}),{schemas:D}}let S=initializeContext({...t,processors:allProcessors});return process$5(e,S),extractDefs(S,e),finalize(S,e)}const ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodError$1=$constructor(`ZodError`,initializer),ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse$5=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse$1=_safeParse(ZodRealError),safeParseAsync$1=_safeParseAsync(ZodRealError),encode$1=_encode(ZodRealError),decode$1=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),ZodType$1=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...S)=>e.clone(mergeDefs(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.parse=(t,S)=>parse$5(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.spa=e.safeParseAsync,e.encode=(t,S)=>encode$1(e,t,S),e.decode=(t,S)=>decode$1(e,t,S),e.encodeAsync=async(t,S)=>encodeAsync(e,t,S),e.decodeAsync=async(t,S)=>decodeAsync(e,t,S),e.safeEncode=(t,S)=>safeEncode(e,t,S),e.safeDecode=(t,S)=>safeDecode(e,t,S),e.safeEncodeAsync=async(t,S)=>safeEncodeAsync(e,t,S),e.safeDecodeAsync=async(t,S)=>safeDecodeAsync(e,t,S),e.refine=(t,S)=>e.check(refine(t,S)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.exactOptional=()=>exactOptional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{let S=e.clone();return globalRegistry.add(S,{description:t}),S},Object.defineProperty(e,`description`,{get(){return globalRegistry.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return globalRegistry.get(e);let S=e.clone();return globalRegistry.add(S,t[0]),S},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>stringProcessor(e,t,S,w);let S=e._zod.bag;e.format=S.format??null,e.minLength=S.minimum??null,e.maxLength=S.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase()),e.slugify=()=>e.check(_slugify())}),ZodString$1=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$2(e){return _string(ZodString$1,e)}const ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber$1=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>numberProcessor(e,t,S,w),e.gt=(t,S)=>e.check(_gt(t,S)),e.gte=(t,S)=>e.check(_gte(t,S)),e.min=(t,S)=>e.check(_gte(t,S)),e.lt=(t,S)=>e.check(_lt(t,S)),e.lte=(t,S)=>e.check(_lte(t,S)),e.max=(t,S)=>e.check(_lte(t,S)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,S)=>e.check(_multipleOf(t,S)),e.step=(t,S)=>e.check(_multipleOf(t,S)),e.finite=()=>e;let S=e._zod.bag;e.minValue=Math.max(S.minimum??-1/0,S.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(S.maximum??1/0,S.exclusiveMaximum??1/0)??null,e.isInt=(S.format??``).includes(`int`)||Number.isSafeInteger(S.multipleOf??.5),e.isFinite=!0,e.format=S.format??null});function number$1(e){return _number(ZodNumber$1,e)}const ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber$1.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean$1=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>booleanProcessor(e,t,S,w)});function boolean$1(e){return _boolean(ZodBoolean$1,e)}const ZodNull$1=$constructor(`ZodNull`,(e,t)=>{$ZodNull.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullProcessor(e,t,S,w)});function _null(e){return _null$1(ZodNull$1,e)}const ZodAny$1=$constructor(`ZodAny`,(e,t)=>{$ZodAny.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function any$1(){return _any(ZodAny$1)}const ZodUnknown$1=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(e,t,S)=>void 0});function unknown$2(){return _unknown(ZodUnknown$1)}const ZodNever$1=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>neverProcessor(e,t,S,w)});function never(e){return _never(ZodNever$1,e)}const ZodArray$1=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>arrayProcessor(e,t,S,w),e.element=t.element,e.min=(t,S)=>e.check(_minLength(t,S)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,S)=>e.check(_maxLength(t,S)),e.length=(t,S)=>e.check(_length(t,S)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray$1,e,t)}const ZodObject$1=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>objectProcessor(e,t,S,w),defineLazy(e,`shape`,()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown$2()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend$1(e,t),e.safeExtend=t=>safeExtend(e,t),e.merge=t=>merge$1(e,t),e.pick=t=>pick$2(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional$1,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object$1(e,t){return new ZodObject$1({type:`object`,shape:e??{},...normalizeParams(t)})}function looseObject(e,t){return new ZodObject$1({type:`object`,shape:e,catchall:unknown$2(),...normalizeParams(t)})}const ZodUnion$1=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>unionProcessor(e,t,S,w),e.options=t.options});function union(e,t){return new ZodUnion$1({type:`union`,options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion$1=$constructor(`ZodDiscriminatedUnion`,(e,t)=>{ZodUnion$1.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,S){return new ZodDiscriminatedUnion$1({type:`union`,options:t,discriminator:e,...normalizeParams(S)})}const ZodIntersection$1=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>intersectionProcessor(e,t,S,w)});function intersection(e,t){return new ZodIntersection$1({type:`intersection`,left:e,right:t})}const ZodRecord$1=$constructor(`ZodRecord`,(e,t)=>{$ZodRecord.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>recordProcessor(e,t,S,w),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,S){return new ZodRecord$1({type:`record`,keyType:e,valueType:t,...normalizeParams(S)})}const ZodEnum$1=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>enumProcessor(e,t,S,w),e.enum=t.entries,e.options=Object.values(t.entries);let S=new Set(Object.keys(t.entries));e.extract=(e,w)=>{let E={};for(let w of e)if(S.has(w))E[w]=t.entries[w];else throw Error(`Key ${w} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})},e.exclude=(e,w)=>{let E={...t.entries};for(let t of e)if(S.has(t))delete E[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum$1({...t,checks:[],...normalizeParams(w),entries:E})}});function _enum(e,t){return new ZodEnum$1({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}const ZodLiteral$1=$constructor(`ZodLiteral`,(e,t)=>{$ZodLiteral.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>literalProcessor(e,t,S,w),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral$1({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>transformProcessor(e,t,S,w),e._zod.parse=(S,w)=>{if(w.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);S.addIssue=w=>{if(typeof w==`string`)S.issues.push(issue(w,S.value,t));else{let t=w;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=S.value,t.inst??=e,S.issues.push(issue(t))}};let E=t.transform(S.value,S);return E instanceof Promise?E.then(e=>(S.value=e,S)):(S.value=E,S)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}const ZodOptional$1=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional$1({type:`optional`,innerType:e})}const ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>optionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}const ZodNullable$1=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nullableProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable$1({type:`nullable`,innerType:e})}const ZodDefault$1=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>defaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault$1({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>prefaultProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>nonoptionalProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const ZodCatch$1=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>catchProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch$1({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>pipeProcessor(e,t,S,w),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}const ZodReadonly$1=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>readonlyProcessor(e,t,S,w),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly$1({type:`readonly`,innerType:e})}const ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType$1.init(e,t),e._zod.processJSONSchema=(t,S,w)=>customProcessor(e,t,S,w)});function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}const describe$1=describe$2,meta$1=meta$2;function preprocess$1(e,t){return pipe(transform(e),t)}var import_dist$1=require_dist$1();init_esm$2();const SINGLETON_KEY$1=Symbol.for(`@inkeep/open-knowledge/field-registry`),g$1=globalThis;g$1[SINGLETON_KEY$1]===void 0&&(g$1[SINGLETON_KEY$1]=registry$1());const fieldRegistry=g$1[SINGLETON_KEY$1];function getFieldMeta(e){let t=e;for(let e=0;e<16;e++){if(t==null)return;let e=isZodSchema$1(t)?fieldRegistry.get(t):void 0;if(e!==void 0)return e;let S=t._zod?.def?.innerType;if(S===void 0)return;t=S}}function isZodSchema$1(e){return typeof e==`object`&&!!e&&`_zod`in e&&`parse`in e}const FolderFrontmatterSchema=looseObject({title:string$2().optional(),description:string$2().optional(),tags:array(string$2()).optional()}),FolderRuleSchema=looseObject({match:string$2().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:FolderFrontmatterSchema}),ConfigSchema$1=looseObject({content:looseObject({dir:string$2().register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`.`)}).default({dir:`.`}),preview:looseObject({scriptSrc:_enum([`cdn-allowlist`,`inline-only`]).register(fieldRegistry,{scope:`project`,agentSettable:!1,defaultScope:`project`}).default(`cdn-allowlist`)}).default({scriptSrc:`cdn-allowlist`}),appearance:looseObject({theme:_enum([`light`,`dark`,`system`]).register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).optional(),sidebar:looseObject({showHiddenFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1),showAllFiles:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).default(!1)}).optional()}).default({}),editor:looseObject({wordWrap:boolean$1().register(fieldRegistry,{scope:`user`,agentSettable:!1,defaultScope:`user`}).default(!0)}).default({wordWrap:!0}),autoSync:looseObject({enabled:boolean$1().register(fieldRegistry,{scope:`project-local`,agentSettable:!1,defaultScope:`project-local`}).nullable().default(null)}).default({enabled:null})}),TRACER_NAME$1=`open-knowledge-config`;async function withConfigSpan(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,async e=>{try{return await S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withConfigSpanSync(e,t,S){let w=trace.getTracer(TRACER_NAME$1),E=t?{attributes:t}:{};return w.startActiveSpan(e,E,e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function addConfigSpanEvent(e,t){let S=trace.getActiveSpan();S&&S.addEvent(e,t)}function unwrapToShape(e){let t=e;for(let e=0;e<16;e++){if(t==null||t?._zod?.def?.shape!==void 0)return t;let e=t?._zod?.def?.innerType;if(e===void 0)return t;t=e}return t}function resolveLeafSchema(e,t){let S=e;for(let e of t){S=unwrapToShape(S);let t=S?._zod?.def?.shape;if(!t||(S=t[String(e)],S===void 0))return}return S}function getLeafFieldMeta(e,t){let S=resolveLeafSchema(e,t);if(S!==void 0)return getFieldMeta(S)}function isScopeCompatible(e,t){return e===`either`?!0:e===t}function validatePatchScopes(e,t){let S=null;function w(e,E){if(S!==null||e===void 0)return;if(typeof e==`object`&&e&&!Array.isArray(e)){for(let[t,D]of Object.entries(e))if(w(D,[...E,t]),S!==null)return;return}let D=getLeafFieldMeta(ConfigSchema$1,E);D?.scope!==void 0&&(isScopeCompatible(D.scope,t)||(S={code:`SCOPE_VIOLATION`,path:E,expectedScope:D.scope,actualScope:t}))}for(let[t,E]of Object.entries(e))if(w(E,[t]),S!==null)break;return S}function ensureCollectionAncestors(e,t){for(let S=1;S<t.length;S++){let w=t.slice(0,S);e.hasIn(w)&&((0,import_dist$1.isCollection)(e.getIn(w,!0))||e.deleteIn(w))}}function applyPatchToDocument(e,t){let S=[];function w(t,E){if(t!==void 0){if(t===null){e.deleteIn(E),S.push(E.join(`.`));return}if(Array.isArray(t)){ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`));return}if(typeof t==`object`){for(let[e,S]of Object.entries(t))w(S,[...E,e]);return}ensureCollectionAncestors(e,E),e.setIn(E,t),S.push(E.join(`.`))}}for(let[e,S]of Object.entries(t))w(S,[e]);return S}function toConfigIssue(e){return{path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}}const CONFIG_SCHEMA_MAJOR_PATH=`v0`;function resolveNode(e,t){if(t.length===0)return e.contents??null;let S=e.getIn(t,!0);if((0,import_dist$1.isNode)(S))return S;for(let S=t.length-1;S>=0;S--){let w=e.getIn(t.slice(0,S),!0);if((0,import_dist$1.isNode)(w))return w}return e.contents??null}function offsetToLineCol(e,t){let S=1,w=1,E=Math.min(t,e.length);for(let t=0;t<E;t++)e.charCodeAt(t)===10?(S++,w=1):w++;return{line:S,column:w}}function renderSnippet(e,t,S,w,E){let D=e.split(`
|
|
155
155
|
`),O=w-1;if(O<0||O>=D.length)return``;let k=D[O]??``,j=t-(E-1)+k.length,F=Math.max(1,Math.min(S,j)-t),L=[],B=String(O+2).length;for(let e=Math.max(0,O-1);e<=Math.min(D.length-1,O+1);e++){let t=e===O,S=t?`>`:` `,w=String(e+1).padStart(B,` `);if(L.push(`${S} ${w} | ${D[e]??``}`),t){let e=` `.repeat(2+B+3+E-1);L.push(`${e}${`^`.repeat(F)}`)}}return L.join(`
|
|
156
156
|
`)}function locateIssue(e){let t=resolveNode(e.doc,e.path);if(!t)return;let S=t.range;if(!S)return;let[w,,E=w]=S,{line:D,column:O}=offsetToLineCol(e.source,w),k=(0,import_dist$1.isCollection)(t)?renderSnippet(e.source,w,w+1,D,O):renderSnippet(e.source,w,E,D,O);return{file:e.file,line:D,column:O,snippet:k.length>0?k:void 0}}const OK_PROJECT_MARKER=`.ok/config.yml`,LOCAL_DIR=`local`;function stringifyPosition(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?position$1(e.position):`start`in e||`end`in e?position$1(e):`line`in e||`column`in e?point$2(e):``}function point$2(e){return index(e&&e.line)+`:`+index(e&&e.column)}function position$1(e){return point$2(e&&e.start)+`-`+point$2(e&&e.end)}function index(e){return e&&typeof e==`number`?e:1}var VFileMessage=class extends Error{constructor(e,t,S){super(),typeof t==`string`&&(S=t,t=void 0);let w=``,E={},D=!1;if(t&&(E=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?w=e:!E.cause&&e&&(D=!0,w=e.message,E.cause=e),!E.ruleId&&!E.source&&typeof S==`string`){let e=S.indexOf(`:`);e===-1?E.ruleId=S:(E.source=S.slice(0,e),E.ruleId=S.slice(e+1))}if(!E.place&&E.ancestors&&E.ancestors){let e=E.ancestors[E.ancestors.length-1];e&&(E.place=e.position)}let O=E.place&&`start`in E.place?E.place.start:E.place;this.ancestors=E.ancestors||void 0,this.cause=E.cause||void 0,this.column=O?O.column:void 0,this.fatal=void 0,this.file=``,this.message=w,this.line=O?O.line:void 0,this.name=stringifyPosition(E.place)||`1:1`,this.place=E.place||void 0,this.reason=this.message,this.ruleId=E.ruleId||void 0,this.source=E.source||void 0,this.stack=D&&E.cause&&typeof E.cause.stack==`string`?E.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};VFileMessage.prototype.file=``,VFileMessage.prototype.name=``,VFileMessage.prototype.reason=``,VFileMessage.prototype.message=``,VFileMessage.prototype.stack=``,VFileMessage.prototype.column=void 0,VFileMessage.prototype.line=void 0,VFileMessage.prototype.ancestors=void 0,VFileMessage.prototype.cause=void 0,VFileMessage.prototype.fatal=void 0,VFileMessage.prototype.place=void 0,VFileMessage.prototype.ruleId=void 0,VFileMessage.prototype.source=void 0;var require_diff_match_patch=__commonJSMin$1(((e,t)=>{var S=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},w=-1,E=1,D=0;S.Diff=function(e,t){return[e,t]},S.prototype.diff_main=function(e,t,w,E){E===void 0&&(E=this.Diff_Timeout<=0?Number.MAX_VALUE:new Date().getTime()+this.Diff_Timeout*1e3);var O=E;if(e==null||t==null)throw Error(`Null input. (diff_main)`);if(e==t)return e?[new S.Diff(D,e)]:[];w===void 0&&(w=!0);var k=w,j=this.diff_commonPrefix(e,t),F=e.substring(0,j);e=e.substring(j),t=t.substring(j),j=this.diff_commonSuffix(e,t);var L=e.substring(e.length-j);e=e.substring(0,e.length-j),t=t.substring(0,t.length-j);var B=this.diff_compute_(e,t,k,O);return F&&B.unshift(new S.Diff(D,F)),L&&B.push(new S.Diff(D,L)),this.diff_cleanupMerge(B),B},S.prototype.diff_compute_=function(e,t,O,k){var j;if(!e)return[new S.Diff(E,t)];if(!t)return[new S.Diff(w,e)];var F=e.length>t.length?e:t,L=e.length>t.length?t:e,B=F.indexOf(L);if(B!=-1)return j=[new S.Diff(E,F.substring(0,B)),new S.Diff(D,L),new S.Diff(E,F.substring(B+L.length))],e.length>t.length&&(j[0][0]=j[2][0]=w),j;if(L.length==1)return[new S.Diff(w,e),new S.Diff(E,t)];var H=this.diff_halfMatch_(e,t);if(H){var q=H[0],J=H[1],Y=H[2],ee=H[3],te=H[4],ne=this.diff_main(q,Y,O,k),ae=this.diff_main(J,ee,O,k);return ne.concat([new S.Diff(D,te)],ae)}return O&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,k):this.diff_bisect_(e,t,k)},S.prototype.diff_lineMode_=function(e,t,O){var k=this.diff_linesToChars_(e,t);e=k.chars1,t=k.chars2;var j=k.lineArray,F=this.diff_main(e,t,!1,O);this.diff_charsToLines_(F,j),this.diff_cleanupSemantic(F),F.push(new S.Diff(D,``));for(var L=0,B=0,H=0,q=``,J=``;L<F.length;){switch(F[L][0]){case E:H++,J+=F[L][1];break;case w:B++,q+=F[L][1];break;case D:if(B>=1&&H>=1){F.splice(L-B-H,B+H),L=L-B-H;for(var Y=this.diff_main(q,J,!1,O),ee=Y.length-1;ee>=0;ee--)F.splice(L,0,Y[ee]);L+=Y.length}H=0,B=0,q=``,J=``;break}L++}return F.pop(),F},S.prototype.diff_bisect_=function(e,t,D){for(var O=e.length,k=t.length,j=Math.ceil((O+k)/2),F=j,L=2*j,B=Array(L),H=Array(L),q=0;q<L;q++)B[q]=-1,H[q]=-1;B[F+1]=0,H[F+1]=0;for(var J=O-k,Y=J%2!=0,ee=0,te=0,ne=0,ae=0,oe=0;oe<j&&!(new Date().getTime()>D);oe++){for(var se=-oe+ee;se<=oe-te;se+=2){for(var ce=F+se,ue=se==-oe||se!=oe&&B[ce-1]<B[ce+1]?B[ce+1]:B[ce-1]+1,de=ue-se;ue<O&&de<k&&e.charAt(ue)==t.charAt(de);)ue++,de++;if(B[ce]=ue,ue>O)te+=2;else if(de>k)ee+=2;else if(Y){var fe=F+J-se;if(fe>=0&&fe<L&&H[fe]!=-1){var me=O-H[fe];if(ue>=me)return this.diff_bisectSplit_(e,t,ue,de,D)}}}for(var ge=-oe+ne;ge<=oe-ae;ge+=2){for(var fe=F+ge,me=ge==-oe||ge!=oe&&H[fe-1]<H[fe+1]?H[fe+1]:H[fe-1]+1,_e=me-ge;me<O&&_e<k&&e.charAt(O-me-1)==t.charAt(k-_e-1);)me++,_e++;if(H[fe]=me,me>O)ae+=2;else if(_e>k)ne+=2;else if(!Y){var ce=F+J-ge;if(ce>=0&&ce<L&&B[ce]!=-1){var ue=B[ce],de=F+ue-ce;if(me=O-me,ue>=me)return this.diff_bisectSplit_(e,t,ue,de,D)}}}}return[new S.Diff(w,e),new S.Diff(E,t)]},S.prototype.diff_bisectSplit_=function(e,t,S,w,E){var D=e.substring(0,S),O=t.substring(0,w),k=e.substring(S),j=t.substring(w),F=this.diff_main(D,O,!1,E),L=this.diff_main(k,j,!1,E);return F.concat(L)},S.prototype.diff_linesToChars_=function(e,t){var S=[],w={};S[0]=``;function E(e){for(var t=``,E=0,O=-1,k=S.length;O<e.length-1;){O=e.indexOf(`
|
|
157
157
|
`,E),O==-1&&(O=e.length-1);var j=e.substring(E,O+1);(w.hasOwnProperty?w.hasOwnProperty(j):w[j]!==void 0)?t+=String.fromCharCode(w[j]):(k==D&&(j=e.substring(E),O=e.length),t+=String.fromCharCode(k),w[j]=k,S[k++]=j),E=O+1}return t}var D=4e4,O=E(e);return D=65535,{chars1:O,chars2:E(t),lineArray:S}},S.prototype.diff_charsToLines_=function(e,t){for(var S=0;S<e.length;S++){for(var w=e[S][1],E=[],D=0;D<w.length;D++)E[D]=t[w.charCodeAt(D)];e[S][1]=E.join(``)}},S.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var S=0,w=Math.min(e.length,t.length),E=w,D=0;S<E;)e.substring(D,E)==t.substring(D,E)?(S=E,D=S):w=E,E=Math.floor((w-S)/2+S);return E},S.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var S=0,w=Math.min(e.length,t.length),E=w,D=0;S<E;)e.substring(e.length-E,e.length-D)==t.substring(t.length-E,t.length-D)?(S=E,D=S):w=E,E=Math.floor((w-S)/2+S);return E},S.prototype.diff_commonOverlap_=function(e,t){var S=e.length,w=t.length;if(S==0||w==0)return 0;S>w?e=e.substring(S-w):S<w&&(t=t.substring(0,S));var E=Math.min(S,w);if(e==t)return E;for(var D=0,O=1;;){var k=e.substring(E-O),j=t.indexOf(k);if(j==-1)return D;O+=j,(j==0||e.substring(E-O)==t.substring(0,O))&&(D=O,O++)}},S.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var S=e.length>t.length?e:t,w=e.length>t.length?t:e;if(S.length<4||w.length*2<S.length)return null;var E=this;function D(e,t,S){for(var w=e.substring(S,S+Math.floor(e.length/4)),D=-1,O=``,k,j,F,L;(D=t.indexOf(w,D+1))!=-1;){var B=E.diff_commonPrefix(e.substring(S),t.substring(D)),H=E.diff_commonSuffix(e.substring(0,S),t.substring(0,D));O.length<H+B&&(O=t.substring(D-H,D)+t.substring(D,D+B),k=e.substring(0,S-H),j=e.substring(S+B),F=t.substring(0,D-H),L=t.substring(D+B))}return O.length*2>=e.length?[k,j,F,L,O]:null}var O=D(S,w,Math.ceil(S.length/4)),k=D(S,w,Math.ceil(S.length/2)),j;if(!O&&!k)return null;j=k?O&&O[4].length>k[4].length?O:k:O;var F,L,B,H;e.length>t.length?(F=j[0],L=j[1],B=j[2],H=j[3]):(B=j[0],H=j[1],F=j[2],L=j[3]);var q=j[4];return[F,L,B,H,q]},S.prototype.diff_cleanupSemantic=function(e){for(var t=!1,O=[],k=0,j=null,F=0,L=0,B=0,H=0,q=0;F<e.length;)e[F][0]==D?(O[k++]=F,L=H,B=q,H=0,q=0,j=e[F][1]):(e[F][0]==E?H+=e[F][1].length:q+=e[F][1].length,j&&j.length<=Math.max(L,B)&&j.length<=Math.max(H,q)&&(e.splice(O[k-1],0,new S.Diff(w,j)),e[O[k-1]+1][0]=E,k--,k--,F=k>0?O[k-1]:-1,L=0,B=0,H=0,q=0,j=null,t=!0)),F++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),F=1;F<e.length;){if(e[F-1][0]==w&&e[F][0]==E){var J=e[F-1][1],Y=e[F][1],ee=this.diff_commonOverlap_(J,Y),te=this.diff_commonOverlap_(Y,J);ee>=te?(ee>=J.length/2||ee>=Y.length/2)&&(e.splice(F,0,new S.Diff(D,Y.substring(0,ee))),e[F-1][1]=J.substring(0,J.length-ee),e[F+1][1]=Y.substring(ee),F++):(te>=J.length/2||te>=Y.length/2)&&(e.splice(F,0,new S.Diff(D,J.substring(0,te))),e[F-1][0]=E,e[F-1][1]=Y.substring(0,Y.length-te),e[F+1][0]=w,e[F+1][1]=J.substring(te),F++),F++}F++}},S.prototype.diff_cleanupSemanticLossless=function(e){function t(e,t){if(!e||!t)return 6;var w=e.charAt(e.length-1),E=t.charAt(0),D=w.match(S.nonAlphaNumericRegex_),O=E.match(S.nonAlphaNumericRegex_),k=D&&w.match(S.whitespaceRegex_),j=O&&E.match(S.whitespaceRegex_),F=k&&w.match(S.linebreakRegex_),L=j&&E.match(S.linebreakRegex_),B=F&&e.match(S.blanklineEndRegex_),H=L&&t.match(S.blanklineStartRegex_);return B||H?5:F||L?4:D&&!k&&j?3:k||j?2:D||O?1:0}for(var w=1;w<e.length-1;){if(e[w-1][0]==D&&e[w+1][0]==D){var E=e[w-1][1],O=e[w][1],k=e[w+1][1],j=this.diff_commonSuffix(E,O);if(j){var F=O.substring(O.length-j);E=E.substring(0,E.length-j),O=F+O.substring(0,O.length-j),k=F+k}for(var L=E,B=O,H=k,q=t(E,O)+t(O,k);O.charAt(0)===k.charAt(0);){E+=O.charAt(0),O=O.substring(1)+k.charAt(0),k=k.substring(1);var J=t(E,O)+t(O,k);J>=q&&(q=J,L=E,B=O,H=k)}e[w-1][1]!=L&&(L?e[w-1][1]=L:(e.splice(w-1,1),w--),e[w][1]=B,H?e[w+1][1]=H:(e.splice(w+1,1),w--))}w++}},S.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,S.whitespaceRegex_=/\s/,S.linebreakRegex_=/[\r\n]/,S.blanklineEndRegex_=/\n\r?\n$/,S.blanklineStartRegex_=/^\r?\n\r?\n/,S.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,O=[],k=0,j=null,F=0,L=!1,B=!1,H=!1,q=!1;F<e.length;)e[F][0]==D?(e[F][1].length<this.Diff_EditCost&&(H||q)?(O[k++]=F,L=H,B=q,j=e[F][1]):(k=0,j=null),H=q=!1):(e[F][0]==w?q=!0:H=!0,j&&(L&&B&&H&&q||j.length<this.Diff_EditCost/2&&L+B+H+q==3)&&(e.splice(O[k-1],0,new S.Diff(w,j)),e[O[k-1]+1][0]=E,k--,j=null,L&&B?(H=q=!0,k=0):(k--,F=k>0?O[k-1]:-1,H=q=!1),t=!0)),F++;t&&this.diff_cleanupMerge(e)},S.prototype.diff_cleanupMerge=function(e){e.push(new S.Diff(D,``));for(var t=0,O=0,k=0,j=``,F=``,L;t<e.length;)switch(e[t][0]){case E:k++,F+=e[t][1],t++;break;case w:O++,j+=e[t][1],t++;break;case D:O+k>1?(O!==0&&k!==0&&(L=this.diff_commonPrefix(F,j),L!==0&&(t-O-k>0&&e[t-O-k-1][0]==D?e[t-O-k-1][1]+=F.substring(0,L):(e.splice(0,0,new S.Diff(D,F.substring(0,L))),t++),F=F.substring(L),j=j.substring(L)),L=this.diff_commonSuffix(F,j),L!==0&&(e[t][1]=F.substring(F.length-L)+e[t][1],F=F.substring(0,F.length-L),j=j.substring(0,j.length-L))),t-=O+k,e.splice(t,O+k),j.length&&(e.splice(t,0,new S.Diff(w,j)),t++),F.length&&(e.splice(t,0,new S.Diff(E,F)),t++),t++):t!==0&&e[t-1][0]==D?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,k=0,O=0,j=``,F=``;break}e[e.length-1][1]===``&&e.pop();var B=!1;for(t=1;t<e.length-1;)e[t-1][0]==D&&e[t+1][0]==D&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),B=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),B=!0)),t++;B&&this.diff_cleanupMerge(e)},S.prototype.diff_xIndex=function(e,t){var S=0,D=0,O=0,k=0,j;for(j=0;j<e.length&&(e[j][0]!==E&&(S+=e[j][1].length),e[j][0]!==w&&(D+=e[j][1].length),!(S>t));j++)O=S,k=D;return e.length!=j&&e[j][0]===w?k:k+(t-O)},S.prototype.diff_prettyHtml=function(e){for(var t=[],S=/&/g,O=/</g,k=/>/g,j=/\n/g,F=0;F<e.length;F++){var L=e[F][0],B=e[F][1].replace(S,`&`).replace(O,`<`).replace(k,`>`).replace(j,`¶<br>`);switch(L){case E:t[F]=`<ins style="background:#e6ffe6;">`+B+`</ins>`;break;case w:t[F]=`<del style="background:#ffe6e6;">`+B+`</del>`;break;case D:t[F]=`<span>`+B+`</span>`;break}}return t.join(``)},S.prototype.diff_text1=function(e){for(var t=[],S=0;S<e.length;S++)e[S][0]!==E&&(t[S]=e[S][1]);return t.join(``)},S.prototype.diff_text2=function(e){for(var t=[],S=0;S<e.length;S++)e[S][0]!==w&&(t[S]=e[S][1]);return t.join(``)},S.prototype.diff_levenshtein=function(e){for(var t=0,S=0,O=0,k=0;k<e.length;k++){var j=e[k][0],F=e[k][1];switch(j){case E:S+=F.length;break;case w:O+=F.length;break;case D:t+=Math.max(S,O),S=0,O=0;break}}return t+=Math.max(S,O),t},S.prototype.diff_toDelta=function(e){for(var t=[],S=0;S<e.length;S++)switch(e[S][0]){case E:t[S]=`+`+encodeURI(e[S][1]);break;case w:t[S]=`-`+e[S][1].length;break;case D:t[S]=`=`+e[S][1].length;break}return t.join(` `).replace(/%20/g,` `)},S.prototype.diff_fromDelta=function(e,t){for(var O=[],k=0,j=0,F=t.split(/\t/g),L=0;L<F.length;L++){var B=F[L].substring(1);switch(F[L].charAt(0)){case`+`:try{O[k++]=new S.Diff(E,decodeURI(B))}catch{throw Error(`Illegal escape in diff_fromDelta: `+B)}break;case`-`:case`=`:var H=parseInt(B,10);if(isNaN(H)||H<0)throw Error(`Invalid number in diff_fromDelta: `+B);var q=e.substring(j,j+=H);F[L].charAt(0)==`=`?O[k++]=new S.Diff(D,q):O[k++]=new S.Diff(w,q);break;default:if(F[L])throw Error(`Invalid diff operation in diff_fromDelta: `+F[L])}}if(j!=e.length)throw Error(`Delta length (`+j+`) does not equal source text length (`+e.length+`).`);return O},S.prototype.match_main=function(e,t,S){if(e==null||t==null||S==null)throw Error(`Null input. (match_main)`);return S=Math.max(0,Math.min(S,e.length)),e==t?0:e.length?e.substring(S,S+t.length)==t?S:this.match_bitap_(e,t,S):-1},S.prototype.match_bitap_=function(e,t,S){if(t.length>this.Match_MaxBits)throw Error(`Pattern too long for this browser.`);var w=this.match_alphabet_(t),E=this;function D(e,w){var D=e/t.length,O=Math.abs(S-w);return E.Match_Distance?D+O/E.Match_Distance:O?1:D}var O=this.Match_Threshold,k=e.indexOf(t,S);k!=-1&&(O=Math.min(D(0,k),O),k=e.lastIndexOf(t,S+t.length),k!=-1&&(O=Math.min(D(0,k),O)));var j=1<<t.length-1;k=-1;for(var F,L,B=t.length+e.length,H,q=0;q<t.length;q++){for(F=0,L=B;F<L;)D(q,S+L)<=O?F=L:B=L,L=Math.floor((B-F)/2+F);B=L;var J=Math.max(1,S-L+1),Y=Math.min(S+L,e.length)+t.length,ee=Array(Y+2);ee[Y+1]=(1<<q)-1;for(var te=Y;te>=J;te--){var ne=w[e.charAt(te-1)];if(q===0?ee[te]=(ee[te+1]<<1|1)&ne:ee[te]=(ee[te+1]<<1|1)&ne|(H[te+1]|H[te])<<1|1|H[te+1],ee[te]&j){var ae=D(q,te-1);if(ae<=O)if(O=ae,k=te-1,k>S)J=Math.max(1,2*S-k);else break}}if(D(q+1,S)>O)break;H=ee}return k},S.prototype.match_alphabet_=function(e){for(var t={},S=0;S<e.length;S++)t[e.charAt(S)]=0;for(var S=0;S<e.length;S++)t[e.charAt(S)]|=1<<e.length-S-1;return t},S.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error(`patch not initialized`);for(var w=t.substring(e.start2,e.start2+e.length1),E=0;t.indexOf(w)!=t.lastIndexOf(w)&&w.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)E+=this.Patch_Margin,w=t.substring(e.start2-E,e.start2+e.length1+E);E+=this.Patch_Margin;var O=t.substring(e.start2-E,e.start2);O&&e.diffs.unshift(new S.Diff(D,O));var k=t.substring(e.start2+e.length1,e.start2+e.length1+E);k&&e.diffs.push(new S.Diff(D,k)),e.start1-=O.length,e.start2-=O.length,e.length1+=O.length+k.length,e.length2+=O.length+k.length}},S.prototype.patch_make=function(e,t,O){var k,j;if(typeof e==`string`&&typeof t==`string`&&O===void 0)k=e,j=this.diff_main(k,t,!0),j.length>2&&(this.diff_cleanupSemantic(j),this.diff_cleanupEfficiency(j));else if(e&&typeof e==`object`&&t===void 0&&O===void 0)j=e,k=this.diff_text1(j);else if(typeof e==`string`&&t&&typeof t==`object`&&O===void 0)k=e,j=t;else if(typeof e==`string`&&typeof t==`string`&&O&&typeof O==`object`)k=e,j=O;else throw Error(`Unknown call format to patch_make.`);if(j.length===0)return[];for(var F=[],L=new S.patch_obj,B=0,H=0,q=0,J=k,Y=k,ee=0;ee<j.length;ee++){var te=j[ee][0],ne=j[ee][1];switch(!B&&te!==D&&(L.start1=H,L.start2=q),te){case E:L.diffs[B++]=j[ee],L.length2+=ne.length,Y=Y.substring(0,q)+ne+Y.substring(q);break;case w:L.length1+=ne.length,L.diffs[B++]=j[ee],Y=Y.substring(0,q)+Y.substring(q+ne.length);break;case D:ne.length<=2*this.Patch_Margin&&B&&j.length!=ee+1?(L.diffs[B++]=j[ee],L.length1+=ne.length,L.length2+=ne.length):ne.length>=2*this.Patch_Margin&&B&&(this.patch_addContext_(L,J),F.push(L),L=new S.patch_obj,B=0,J=Y,H=q);break}te!==E&&(H+=ne.length),te!==w&&(q+=ne.length)}return B&&(this.patch_addContext_(L,J),F.push(L)),F},S.prototype.patch_deepCopy=function(e){for(var t=[],w=0;w<e.length;w++){var E=e[w],D=new S.patch_obj;D.diffs=[];for(var O=0;O<E.diffs.length;O++)D.diffs[O]=new S.Diff(E.diffs[O][0],E.diffs[O][1]);D.start1=E.start1,D.start2=E.start2,D.length1=E.length1,D.length2=E.length2,t[w]=D}return t},S.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var S=this.patch_addPadding(e);t=S+t+S,this.patch_splitMax(e);for(var O=0,k=[],j=0;j<e.length;j++){var F=e[j].start2+O,L=this.diff_text1(e[j].diffs),B,H=-1;if(L.length>this.Match_MaxBits?(B=this.match_main(t,L.substring(0,this.Match_MaxBits),F),B!=-1&&(H=this.match_main(t,L.substring(L.length-this.Match_MaxBits),F+L.length-this.Match_MaxBits),(H==-1||B>=H)&&(B=-1))):B=this.match_main(t,L,F),B==-1)k[j]=!1,O-=e[j].length2-e[j].length1;else{k[j]=!0,O=B-F;var q=H==-1?t.substring(B,B+L.length):t.substring(B,H+this.Match_MaxBits);if(L==q)t=t.substring(0,B)+this.diff_text2(e[j].diffs)+t.substring(B+L.length);else{var J=this.diff_main(L,q,!1);if(L.length>this.Match_MaxBits&&this.diff_levenshtein(J)/L.length>this.Patch_DeleteThreshold)k[j]=!1;else{this.diff_cleanupSemanticLossless(J);for(var Y=0,ee,te=0;te<e[j].diffs.length;te++){var ne=e[j].diffs[te];ne[0]!==D&&(ee=this.diff_xIndex(J,Y)),ne[0]===E?t=t.substring(0,B+ee)+ne[1]+t.substring(B+ee):ne[0]===w&&(t=t.substring(0,B+ee)+t.substring(B+this.diff_xIndex(J,Y+ne[1].length))),ne[0]!==w&&(Y+=ne[1].length)}}}}}return t=t.substring(S.length,t.length-S.length),[t,k]},S.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,w=``,E=1;E<=t;E++)w+=String.fromCharCode(E);for(var E=0;E<e.length;E++)e[E].start1+=t,e[E].start2+=t;var O=e[0],k=O.diffs;if(k.length==0||k[0][0]!=D)k.unshift(new S.Diff(D,w)),O.start1-=t,O.start2-=t,O.length1+=t,O.length2+=t;else if(t>k[0][1].length){var j=t-k[0][1].length;k[0][1]=w.substring(k[0][1].length)+k[0][1],O.start1-=j,O.start2-=j,O.length1+=j,O.length2+=j}if(O=e[e.length-1],k=O.diffs,k.length==0||k[k.length-1][0]!=D)k.push(new S.Diff(D,w)),O.length1+=t,O.length2+=t;else if(t>k[k.length-1][1].length){var j=t-k[k.length-1][1].length;k[k.length-1][1]+=w.substring(0,j),O.length1+=j,O.length2+=j}return w},S.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,O=0;O<e.length;O++)if(!(e[O].length1<=t)){var k=e[O];e.splice(O--,1);for(var j=k.start1,F=k.start2,L=``;k.diffs.length!==0;){var B=new S.patch_obj,H=!0;for(B.start1=j-L.length,B.start2=F-L.length,L!==``&&(B.length1=B.length2=L.length,B.diffs.push(new S.Diff(D,L)));k.diffs.length!==0&&B.length1<t-this.Patch_Margin;){var q=k.diffs[0][0],J=k.diffs[0][1];q===E?(B.length2+=J.length,F+=J.length,B.diffs.push(k.diffs.shift()),H=!1):q===w&&B.diffs.length==1&&B.diffs[0][0]==D&&J.length>2*t?(B.length1+=J.length,j+=J.length,H=!1,B.diffs.push(new S.Diff(q,J)),k.diffs.shift()):(J=J.substring(0,t-B.length1-this.Patch_Margin),B.length1+=J.length,j+=J.length,q===D?(B.length2+=J.length,F+=J.length):H=!1,B.diffs.push(new S.Diff(q,J)),J==k.diffs[0][1]?k.diffs.shift():k.diffs[0][1]=k.diffs[0][1].substring(J.length))}L=this.diff_text2(B.diffs),L=L.substring(L.length-this.Patch_Margin);var Y=this.diff_text1(k.diffs).substring(0,this.Patch_Margin);Y!==``&&(B.length1+=Y.length,B.length2+=Y.length,B.diffs.length!==0&&B.diffs[B.diffs.length-1][0]===D?B.diffs[B.diffs.length-1][1]+=Y:B.diffs.push(new S.Diff(D,Y))),H||e.splice(++O,0,B)}}},S.prototype.patch_toText=function(e){for(var t=[],S=0;S<e.length;S++)t[S]=e[S];return t.join(``)},S.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var O=e.split(`
|
|
@@ -161,12 +161,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
161
161
|
`)}};ContentMatch.empty=new ContentMatch(!0);var TokenStream=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function parseExpr(e){let t=[];do t.push(parseExprSeq(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function parseExprSeq(e){let t=[];do t.push(parseExprSubscript(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function parseExprSubscript(e){let t=parseExprAtom(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=parseExprRange(e,t);else break;return t}function parseNum(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function parseExprRange(e,t){let S=parseNum(e),w=S;return e.eat(`,`)&&(w=e.next==`}`?-1:parseNum(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:S,max:w,expr:t}}function resolveName(e,t){let S=e.nodeTypes,w=S[t];if(w)return[w];let E=[];for(let e in S){let w=S[e];w.isInGroup(t)&&E.push(w)}return E.length==0&&e.err(`No node type or group '`+t+`' found`),E}function parseExprAtom(e){if(e.eat(`(`)){let t=parseExpr(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}else if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=resolveName(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function nfa(e){let t=[[]];return E(D(e,0),S()),t;function S(){return t.push([])-1}function w(e,S,w){let E={term:w,to:S};return t[e].push(E),E}function E(e,t){e.forEach(e=>e.to=t)}function D(e,t){if(e.type==`choice`)return e.exprs.reduce((e,S)=>e.concat(D(S,t)),[]);if(e.type==`seq`)for(let w=0;;w++){let O=D(e.exprs[w],t);if(w==e.exprs.length-1)return O;E(O,t=S())}else if(e.type==`star`){let O=S();return w(t,O),E(D(e.expr,O),O),[w(O)]}else if(e.type==`plus`){let O=S();return E(D(e.expr,t),O),E(D(e.expr,O),O),[w(O)]}else if(e.type==`opt`)return[w(t)].concat(D(e.expr,t));else if(e.type==`range`){let O=t;for(let t=0;t<e.min;t++){let t=S();E(D(e.expr,O),t),O=t}if(e.max==-1)E(D(e.expr,O),O);else for(let t=e.min;t<e.max;t++){let t=S();w(O,t),E(D(e.expr,O),t),O=t}return[w(O)]}else if(e.type==`name`)return[w(t,void 0,e.value)];else throw Error(`Unknown expr type`)}}function cmp(e,t){return t-e}function nullFrom(e,t){let S=[];return w(t),S.sort(cmp);function w(t){let E=e[t];if(E.length==1&&!E[0].term)return w(E[0].to);S.push(t);for(let e=0;e<E.length;e++){let{term:t,to:D}=E[e];!t&&S.indexOf(D)==-1&&w(D)}}}function dfa(e){let t=Object.create(null);return S(nullFrom(e,0));function S(w){let E=[];w.forEach(t=>{e[t].forEach(({term:t,to:S})=>{if(!t)return;let w;for(let e=0;e<E.length;e++)E[e][0]==t&&(w=E[e][1]);nullFrom(e,S).forEach(e=>{w||E.push([t,w=[]]),w.indexOf(e)==-1&&w.push(e)})})});let D=t[w.join(`,`)]=new ContentMatch(w.indexOf(e.length-1)>-1);for(let e=0;e<E.length;e++){let w=E[e][1].sort(cmp);D.next.push({type:E[e][0],next:t[w.join(`,`)]||S(w)})}return D}}function checkForDeadEnds(e,t){for(let S=0,w=[e];S<w.length;S++){let e=w[S],E=!e.validEnd,D=[];for(let t=0;t<e.next.length;t++){let{type:S,next:O}=e.next[t];D.push(S.name),E&&!(S.isText||S.hasRequiredAttrs())&&(E=!1),w.indexOf(O)==-1&&w.push(O)}E&&t.err(`Only non-generatable nodes (`+D.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}function defaultAttrs(e){let t=Object.create(null);for(let S in e){let w=e[S];if(!w.hasDefault)return null;t[S]=w.default}return t}function computeAttrs(e,t){let S=Object.create(null);for(let w in e){let E=t&&t[w];if(E===void 0){let t=e[w];if(t.hasDefault)E=t.default;else throw RangeError(`No value supplied for attribute `+w)}S[w]=E}return S}function checkAttrs(e,t,S,w){for(let w in t)if(!(w in e))throw RangeError(`Unsupported attribute ${w} for ${S} of type ${w}`);for(let S in e){let w=e[S];w.validate&&w.validate(t[S])}}function initAttrs(e,t){let S=Object.create(null);if(t)for(let w in t)S[w]=new Attribute(e,w,t[w]);return S}var NodeType$1=class e{constructor(e,t,S){this.name=e,this.schema=t,this.spec=S,this.markSet=null,this.groups=S.group?S.group.split(` `):[],this.attrs=initAttrs(e,S.attrs),this.defaultAttrs=defaultAttrs(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(S.inline||e==`text`),this.isText=e==`text`}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==ContentMatch.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:computeAttrs(this.attrs,e)}create(e=null,t,S){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new Node(this,this.computeAttrs(e),Fragment.from(t),Mark$1.setFrom(S))}createChecked(e=null,t,S){return t=Fragment.from(t),this.checkContent(t),new Node(this,this.computeAttrs(e),t,Mark$1.setFrom(S))}createAndFill(e=null,t,S){if(e=this.computeAttrs(e),t=Fragment.from(t),t.size){let e=this.contentMatch.fillBefore(t);if(!e)return null;t=e.append(t)}let w=this.contentMatch.matchFragment(t),E=w&&w.fillBefore(Fragment.empty,!0);return E?new Node(this,e,t.append(E),Mark$1.setFrom(S)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let t=0;t<e.childCount;t++)if(!this.allowsMarks(e.child(t).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){checkAttrs(this.attrs,e,`node`,this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let S=0;S<e.length;S++)this.allowsMarkType(e[S].type)?t&&t.push(e[S]):t||=e.slice(0,S);return t?t.length?t:Mark$1.none:e}static compile(t,S){let w=Object.create(null);t.forEach((t,E)=>w[t]=new e(t,S,E));let E=S.spec.topNode||`doc`;if(!w[E])throw RangeError(`Schema is missing its top node type ('`+E+`')`);if(!w.text)throw RangeError(`Every schema needs a 'text' type`);for(let e in w.text.attrs)throw RangeError(`The text node type should not have attributes`);return w}};function validateType(e,t,S){let w=S.split(`|`);return S=>{let E=S===null?`null`:typeof S;if(w.indexOf(E)<0)throw RangeError(`Expected value of type ${w} for attribute ${t} on type ${e}, got ${E}`)}}var Attribute=class{constructor(e,t,S){this.hasDefault=Object.prototype.hasOwnProperty.call(S,`default`),this.default=S.default,this.validate=typeof S.validate==`string`?validateType(e,t,S.validate):S.validate}get isRequired(){return!this.hasDefault}},MarkType=class e{constructor(e,t,S,w){this.name=e,this.rank=t,this.schema=S,this.spec=w,this.attrs=initAttrs(e,w.attrs),this.excluded=null;let E=defaultAttrs(this.attrs);this.instance=E?new Mark$1(this,E):null}create(e=null){return!e&&this.instance?this.instance:new Mark$1(this,computeAttrs(this.attrs,e))}static compile(t,S){let w=Object.create(null),E=0;return t.forEach((t,D)=>w[t]=new e(t,E++,S,D)),w}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){checkAttrs(this.attrs,e,`mark`,this.name)}excludes(e){return this.excluded.indexOf(e)>-1}},Schema$1=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let S in e)t[S]=e[S];t.nodes=OrderedMap.from(e.nodes),t.marks=OrderedMap.from(e.marks||{}),this.nodes=NodeType$1.compile(this.spec.nodes,this),this.marks=MarkType.compile(this.spec.marks,this);let S=Object.create(null);for(let e in this.nodes){if(e in this.marks)throw RangeError(e+` can not be both a node and a mark`);let t=this.nodes[e],w=t.spec.content||``,E=t.spec.marks;if(t.contentMatch=S[w]||(S[w]=ContentMatch.parse(w,this.nodes)),t.inlineContent=t.contentMatch.inlineContent,t.spec.linebreakReplacement){if(this.linebreakReplacement)throw RangeError(`Multiple linebreak nodes defined`);if(!t.isInline||!t.isLeaf)throw RangeError(`Linebreak replacement nodes must be inline leaf nodes`);this.linebreakReplacement=t}t.markSet=E==`_`?null:E?gatherMarks(this,E.split(` `)):E==``||!t.inlineContent?[]:null}for(let e in this.marks){let t=this.marks[e],S=t.spec.excludes;t.excluded=S==null?[t]:S==``?[]:gatherMarks(this,S.split(` `))}this.nodeFromJSON=e=>Node.fromJSON(this,e),this.markFromJSON=e=>Mark$1.fromJSON(this,e),this.topNodeType=this.nodes[this.spec.topNode||`doc`],this.cached.wrappings=Object.create(null)}node(e,t=null,S,w){if(typeof e==`string`)e=this.nodeType(e);else if(!(e instanceof NodeType$1))throw RangeError(`Invalid node type: `+e);else if(e.schema!=this)throw RangeError(`Node type from different schema used (`+e.name+`)`);return e.createChecked(t,S,w)}text(e,t){let S=this.nodes.text;return new TextNode(S,S.defaultAttrs,e,Mark$1.setFrom(t))}mark(e,t){return typeof e==`string`&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw RangeError(`Unknown node type: `+e);return t}};function gatherMarks(e,t){let S=[];for(let w=0;w<t.length;w++){let E=t[w],D=e.marks[E],O=D;if(D)S.push(D);else for(let t in e.marks){let w=e.marks[t];(E==`_`||w.spec.group&&w.spec.group.split(` `).indexOf(E)>-1)&&S.push(O=w)}if(!O)throw SyntaxError(`Unknown mark type: '`+t[w]+`'`)}return S}function isTagRule(e){return e.tag!=null}function isStyleRule(e){return e.style!=null}var DOMParser=class e{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let S=this.matchedStyles=[];t.forEach(e=>{if(isTagRule(e))this.tags.push(e);else if(isStyleRule(e)){let t=/[^=]*/.exec(e.style)[0];S.indexOf(t)<0&&S.push(t),this.styles.push(e)}}),this.normalizeLists=!this.tags.some(t=>{if(!/^(ul|ol)\b/.test(t.tag)||!t.node)return!1;let S=e.nodes[t.node];return S.contentMatch.matchType(S)})}parse(e,t={}){let S=new ParseContext(this,t,!1);return S.addAll(e,Mark$1.none,t.from,t.to),S.finish()}parseSlice(e,t={}){let S=new ParseContext(this,t,!0);return S.addAll(e,Mark$1.none,t.from,t.to),Slice.maxOpen(S.finish())}matchTag(e,t,S){for(let w=S?this.tags.indexOf(S)+1:0;w<this.tags.length;w++){let S=this.tags[w];if(matches(e,S.tag)&&(S.namespace===void 0||e.namespaceURI==S.namespace)&&(!S.context||t.matchesContext(S.context))){if(S.getAttrs){let t=S.getAttrs(e);if(t===!1)continue;S.attrs=t||void 0}return S}}}matchStyle(e,t,S,w){for(let E=w?this.styles.indexOf(w)+1:0;E<this.styles.length;E++){let w=this.styles[E],D=w.style;if(!(D.indexOf(e)!=0||w.context&&!S.matchesContext(w.context)||D.length>e.length&&(D.charCodeAt(e.length)!=61||D.slice(e.length+1)!=t))){if(w.getAttrs){let e=w.getAttrs(t);if(e===!1)continue;w.attrs=e||void 0}return w}}}static schemaRules(e){let t=[];function S(e){let S=e.priority==null?50:e.priority,w=0;for(;w<t.length;w++){let e=t[w];if((e.priority==null?50:e.priority)<S)break}t.splice(w,0,e)}for(let t in e.marks){let w=e.marks[t].spec.parseDOM;w&&w.forEach(e=>{S(e=copy$1(e)),e.mark||e.ignore||e.clearMark||(e.mark=t)})}for(let t in e.nodes){let w=e.nodes[t].spec.parseDOM;w&&w.forEach(e=>{S(e=copy$1(e)),e.node||e.ignore||e.mark||(e.node=t)})}return t}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new e(t,e.schemaRules(t)))}};const blockTags={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},ignoreTags={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},listTags={ol:!0,ul:!0},OPT_PRESERVE_WS=1,OPT_PRESERVE_WS_FULL=2,OPT_OPEN_LEFT=4;function wsOptionsFor(e,t,S){return t==null?e&&e.whitespace==`pre`?OPT_PRESERVE_WS|OPT_PRESERVE_WS_FULL:S&~OPT_OPEN_LEFT:(t?OPT_PRESERVE_WS:0)|(t===`full`?OPT_PRESERVE_WS_FULL:0)}var NodeContext=class{constructor(e,t,S,w,E,D){this.type=e,this.attrs=t,this.marks=S,this.solid=w,this.options=D,this.content=[],this.activeMarks=Mark$1.none,this.match=E||(D&OPT_OPEN_LEFT?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(Fragment.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let t=this.type.contentMatch,S;return(S=t.findWrapping(e.type))?(this.match=t,S):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&OPT_PRESERVE_WS)){let e=this.content[this.content.length-1],t;if(e&&e.isText&&(t=/[ \t\r\n\u000c]+$/.exec(e.text))){let S=e;e.text.length==t[0].length?this.content.pop():this.content[this.content.length-1]=S.withText(S.text.slice(0,S.text.length-t[0].length))}}let t=Fragment.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(Fragment.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!blockTags.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},ParseContext=class{constructor(e,t,S){this.parser=e,this.options=t,this.isOpen=S,this.open=0,this.localPreserveWS=!1;let w=t.topNode,E,D=wsOptionsFor(null,t.preserveWhitespace,0)|(S?OPT_OPEN_LEFT:0);E=w?new NodeContext(w.type,w.attrs,Mark$1.none,!0,t.topMatch||w.type.contentMatch,D):S?new NodeContext(null,null,Mark$1.none,!0,null,D):new NodeContext(e.schema.topNodeType,null,Mark$1.none,!0,null,D),this.nodes=[E],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let S=e.nodeValue,w=this.top,E=w.options&OPT_PRESERVE_WS_FULL?`full`:this.localPreserveWS||(w.options&OPT_PRESERVE_WS)>0,{schema:D}=this.parser;if(E===`full`||w.inlineContext(e)||/[^ \t\r\n\u000c]/.test(S)){if(!E){if(S=S.replace(/[ \t\r\n\u000c]+/g,` `),/^[ \t\r\n\u000c]/.test(S)&&this.open==this.nodes.length-1){let t=w.content[w.content.length-1],E=e.previousSibling;(!t||E&&E.nodeName==`BR`||t.isText&&/[ \t\r\n\u000c]$/.test(t.text))&&(S=S.slice(1))}}else if(E===`full`)S=S.replace(/\r\n?/g,`
|
|
162
162
|
`);else if(D.linebreakReplacement&&/[\r\n]/.test(S)&&this.top.findWrapping(D.linebreakReplacement.create())){let e=S.split(/\r?\n|\r/);for(let S=0;S<e.length;S++)S&&this.insertNode(D.linebreakReplacement.create(),t,!0),e[S]&&this.insertNode(D.text(e[S]),t,!/\S/.test(e[S]));S=``}else S=S.replace(/\r?\n|\r/g,` `);S&&this.insertNode(D.text(S),t,!/\S/.test(S)),this.findInText(e)}else this.findInside(e)}addElement(e,t,S){let w=this.localPreserveWS,E=this.top;(e.tagName==`PRE`||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let D=e.nodeName.toLowerCase(),O;listTags.hasOwnProperty(D)&&this.parser.normalizeLists&&normalizeList(e);let k=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(O=this.parser.matchTag(e,this,S));out:if(k?k.ignore:ignoreTags.hasOwnProperty(D))this.findInside(e),this.ignoreFallback(e,t);else if(!k||k.skip||k.closeParent){k&&k.closeParent?this.open=Math.max(0,this.open-1):k&&k.skip.nodeType&&(e=k.skip);let S,w=this.needsBlock;if(blockTags.hasOwnProperty(D))E.content.length&&E.content[0].isInline&&this.open&&(this.open--,E=this.top),S=!0,E.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break out}let O=k&&k.skip?t:this.readStyles(e,t);O&&this.addAll(e,O),S&&this.sync(E),this.needsBlock=w}else{let S=this.readStyles(e,t);S&&this.addElementByRule(e,k,S,k.consuming===!1?O:void 0)}this.localPreserveWS=w}leafFallback(e,t){e.nodeName==`BR`&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
|
|
163
163
|
`),t)}ignoreFallback(e,t){e.nodeName==`BR`&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text(`-`),t,!0)}readStyles(e,t){let S=e.style;if(S&&S.length)for(let e=0;e<this.parser.matchedStyles.length;e++){let w=this.parser.matchedStyles[e],E=S.getPropertyValue(w);if(E)for(let e;;){let S=this.parser.matchStyle(w,E,this,e);if(!S)break;if(S.ignore)return null;if(t=S.clearMark?t.filter(e=>!S.clearMark(e)):t.concat(this.parser.schema.marks[S.mark].create(S.attrs)),S.consuming===!1)e=S;else break}}return t}addElementByRule(e,t,S,w){let E,D;if(t.node)if(D=this.parser.schema.nodes[t.node],D.isLeaf)this.insertNode(D.create(t.attrs),S,e.nodeName==`BR`)||this.leafFallback(e,S);else{let e=this.enter(D,t.attrs||null,S,t.preserveWhitespace);e&&(E=!0,S=e)}else{let e=this.parser.schema.marks[t.mark];S=S.concat(e.create(t.attrs))}let O=this.top;if(D&&D.isLeaf)this.findInside(e);else if(w)this.addElement(e,S,w);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,S,!1));else{let w=e;typeof t.contentElement==`string`?w=e.querySelector(t.contentElement):typeof t.contentElement==`function`?w=t.contentElement(e):t.contentElement&&(w=t.contentElement),this.findAround(e,w,!0),this.addAll(w,S),this.findAround(e,w,!1)}E&&this.sync(O)&&this.open--}addAll(e,t,S,w){let E=S||0;for(let D=S?e.childNodes[S]:e.firstChild,O=w==null?null:e.childNodes[w];D!=O;D=D.nextSibling,++E)this.findAtPoint(e,E),this.addDOM(D,t);this.findAtPoint(e,E)}findPlace(e,t,S){let w,E;for(let t=this.open,D=0;t>=0;t--){let O=this.nodes[t],k=O.findWrapping(e);if(k&&(!w||w.length>k.length+D)&&(w=k,E=O,!k.length))break;if(O.solid){if(S)break;D+=2}}if(!w)return null;this.sync(E);for(let e=0;e<w.length;e++)t=this.enterInner(w[e],null,t,!1);return t}insertNode(e,t,S){if(e.isInline&&this.needsBlock&&!this.top.type){let e=this.textblockFromContext();e&&(t=this.enterInner(e,null,t))}let w=this.findPlace(e,t,S);if(w){this.closeExtra();let t=this.top;t.match&&=t.match.matchType(e.type);let S=Mark$1.none;for(let E of w.concat(e.marks))(t.type?t.type.allowsMarkType(E.type):markMayApply(E.type,e.type))&&(S=E.addToSet(S));return t.content.push(e.mark(S)),!0}return!1}enter(e,t,S,w){let E=this.findPlace(e.create(t),S,!1);return E&&=this.enterInner(e,t,S,!0,w),E}enterInner(e,t,S,w=!1,E){this.closeExtra();let D=this.top;D.match=D.match&&D.match.matchType(e);let O=wsOptionsFor(e,E,D.options);D.options&OPT_OPEN_LEFT&&D.content.length==0&&(O|=OPT_OPEN_LEFT);let k=Mark$1.none;return S=S.filter(t=>(D.type?D.type.allowsMarkType(t.type):markMayApply(t.type,e))?(k=t.addToSet(k),!1):!0),this.nodes.push(new NodeContext(e,t,k,w,null,O)),this.open++,S}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=OPT_PRESERVE_WS);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let S=this.nodes[t].content;for(let t=S.length-1;t>=0;t--)e+=S[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let S=0;S<this.find.length;S++)this.find[S].node==e&&this.find[S].offset==t&&(this.find[S].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,S){if(e!=t&&this.find)for(let w=0;w<this.find.length;w++)this.find[w].pos==null&&e.nodeType==1&&e.contains(this.find[w].node)&&t.compareDocumentPosition(this.find[w].node)&(S?2:4)&&(this.find[w].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf(`|`)>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),S=this.options.context,w=!this.isOpen&&(!S||S.parent.type==this.nodes[0].type),E=-(S?S.depth+1:0)+(w?0:1),D=(e,O)=>{for(;e>=0;e--){let k=t[e];if(k==``){if(e==t.length-1||e==0)continue;for(;O>=E;O--)if(D(e-1,O))return!0;return!1}else{let e=O>0||O==0&&w?this.nodes[O].type:S&&O>=E?S.node(O-E).type:null;if(!e||e.name!=k&&!e.isInGroup(k))return!1;O--}}return!0};return D(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let S=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(S&&S.isTextblock&&S.defaultAttrs)return S}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function normalizeList(e){for(let t=e.firstChild,S=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&listTags.hasOwnProperty(e)&&S?(S.appendChild(t),t=S):e==`li`?S=t:e&&(S=null)}}function matches(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function copy$1(e){let t={};for(let S in e)t[S]=e[S];return t}function markMayApply(e,t){let S=t.schema.nodes;for(let w in S){let E=S[w];if(!E.allowsMarkType(e))continue;let D=[],O=e=>{D.push(e);for(let S=0;S<e.edgeCount;S++){let{type:w,next:E}=e.edge(S);if(w==t||D.indexOf(E)<0&&O(E))return!0}};if(O(E.contentMatch))return!0}}var DOMSerializer=class e{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},S){S||=doc$1(t).createDocumentFragment();let w=S,E=[];return e.forEach(e=>{if(E.length||e.marks.length){let S=0,D=0;for(;S<E.length&&D<e.marks.length;){let t=e.marks[D];if(!this.marks[t.type.name]){D++;continue}if(!t.eq(E[S][0])||t.type.spec.spanning===!1)break;S++,D++}for(;S<E.length;)w=E.pop()[1];for(;D<e.marks.length;){let S=e.marks[D++],O=this.serializeMark(S,e.isInline,t);O&&(E.push([S,w]),w.appendChild(O.dom),w=O.contentDOM||O.dom)}}w.appendChild(this.serializeNodeInner(e,t))}),S}serializeNodeInner(e,t){let{dom:S,contentDOM:w}=renderSpec(doc$1(t),this.nodes[e.type.name](e),null,e.attrs);if(w){if(e.isLeaf)throw RangeError(`Content hole not allowed in a leaf node spec`);this.serializeFragment(e.content,t,w)}return S}serializeNode(e,t={}){let S=this.serializeNodeInner(e,t);for(let w=e.marks.length-1;w>=0;w--){let E=this.serializeMark(e.marks[w],e.isInline,t);E&&((E.contentDOM||E.dom).appendChild(S),S=E.dom)}return S}serializeMark(e,t,S={}){let w=this.marks[e.type.name];return w&&renderSpec(doc$1(S),w(e,t),null,e.attrs)}static renderSpec(e,t,S=null,w){return renderSpec(e,t,S,w)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new e(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(e){let t=gatherToDOM(e.nodes);return t.text||=e=>e.text,t}static marksFromSchema(e){return gatherToDOM(e.marks)}};function gatherToDOM(e){let t={};for(let S in e){let w=e[S].spec.toDOM;w&&(t[S]=w)}return t}function doc$1(e){return e.document||window.document}const suspiciousAttributeCache=new WeakMap;function suspiciousAttributes(e){let t=suspiciousAttributeCache.get(e);return t===void 0&&suspiciousAttributeCache.set(e,t=suspiciousAttributesInner(e)),t}function suspiciousAttributesInner(e){let t=null;function S(e){if(e&&typeof e==`object`)if(Array.isArray(e))if(typeof e[0]==`string`)t||=[],t.push(e);else for(let t=0;t<e.length;t++)S(e[t]);else for(let t in e)S(e[t])}return S(e),t}function renderSpec(e,t,S,w){if(typeof t==`string`)return{dom:e.createTextNode(t)};if(t.nodeType!=null)return{dom:t};if(t.dom&&t.dom.nodeType!=null)return t;let E=t[0],D;if(typeof E!=`string`)throw RangeError(`Invalid array passed to renderSpec`);if(w&&(D=suspiciousAttributes(w))&&D.indexOf(t)>-1)throw RangeError(`Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.`);let O=E.indexOf(` `);O>0&&(S=E.slice(0,O),E=E.slice(O+1));let k,j=S?e.createElementNS(S,E):e.createElement(E),F=t[1],L=1;if(F&&typeof F==`object`&&F.nodeType==null&&!Array.isArray(F)){L=2;for(let e in F)if(F[e]!=null){let t=e.indexOf(` `);t>0?j.setAttributeNS(e.slice(0,t),e.slice(t+1),F[e]):e==`style`&&j.style?j.style.cssText=F[e]:j.setAttribute(e,F[e])}}for(let E=L;E<t.length;E++){let D=t[E];if(D===0){if(E<t.length-1||E>L)throw RangeError(`Content hole must be the only child of its parent node`);return{dom:j,contentDOM:j}}else{let{dom:t,contentDOM:E}=renderSpec(e,D,S,w);if(j.appendChild(t),E){if(k)throw RangeError(`Multiple content holes`);k=E}}}return{dom:j,contentDOM:k}}const lower16=65535,factor16=2**16;function makeRecover(e,t){return e+t*factor16}function recoverIndex(e){return e&lower16}function recoverOffset(e){return(e-(e&lower16))/factor16}const DEL_BEFORE=1,DEL_AFTER=2,DEL_ACROSS=4,DEL_SIDE=8;var MapResult=class{constructor(e,t,S){this.pos=e,this.delInfo=t,this.recover=S}get deleted(){return(this.delInfo&DEL_SIDE)>0}get deletedBefore(){return(this.delInfo&(DEL_BEFORE|DEL_ACROSS))>0}get deletedAfter(){return(this.delInfo&(DEL_AFTER|DEL_ACROSS))>0}get deletedAcross(){return(this.delInfo&DEL_ACROSS)>0}},StepMap=class e{constructor(t,S=!1){if(this.ranges=t,this.inverted=S,!t.length&&e.empty)return e.empty}recover(e){let t=0,S=recoverIndex(e);if(!this.inverted)for(let e=0;e<S;e++)t+=this.ranges[e*3+2]-this.ranges[e*3+1];return this.ranges[S*3]+t+recoverOffset(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,S){let w=0,E=this.inverted?2:1,D=this.inverted?1:2;for(let O=0;O<this.ranges.length;O+=3){let k=this.ranges[O]-(this.inverted?w:0);if(k>e)break;let j=this.ranges[O+E],F=this.ranges[O+D],L=k+j;if(e<=L){let E=j?e==k?-1:e==L?1:t:t,D=k+w+(E<0?0:F);if(S)return D;let B=e==(t<0?k:L)?null:makeRecover(O/3,e-k),H=e==k?DEL_AFTER:e==L?DEL_BEFORE:DEL_ACROSS;return(t<0?e!=k:e!=L)&&(H|=DEL_SIDE),new MapResult(D,H,B)}w+=F-j}return S?e+w:new MapResult(e+w,0,null)}touches(e,t){let S=0,w=recoverIndex(t),E=this.inverted?2:1,D=this.inverted?1:2;for(let t=0;t<this.ranges.length;t+=3){let O=this.ranges[t]-(this.inverted?S:0);if(O>e)break;let k=this.ranges[t+E];if(e<=O+k&&t==w*3)return!0;S+=this.ranges[t+D]-k}return!1}forEach(e){let t=this.inverted?2:1,S=this.inverted?1:2;for(let w=0,E=0;w<this.ranges.length;w+=3){let D=this.ranges[w],O=D-(this.inverted?E:0),k=D+(this.inverted?0:E),j=this.ranges[w+t],F=this.ranges[w+S];e(O,O+j,k,k+F),E+=F-j}}invert(){return new e(this.ranges,!this.inverted)}toString(){return(this.inverted?`-`:``)+JSON.stringify(this.ranges)}static offset(t){return t==0?e.empty:new e(t<0?[0,-t,0]:[0,0,t])}};StepMap.empty=new StepMap([]);var Mapping=class e{constructor(e,t,S=0,w=e?e.length:0){this.mirror=t,this.from=S,this.to=w,this._maps=e||[],this.ownData=!(e||t)}get maps(){return this._maps}slice(t=0,S=this.maps.length){return new e(this._maps,this.mirror,t,S)}appendMap(e,t){this.ownData||=(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),!0),this.to=this._maps.push(e),t!=null&&this.setMirror(this._maps.length-1,t)}appendMapping(e){for(let t=0,S=this._maps.length;t<e._maps.length;t++){let w=e.getMirror(t);this.appendMap(e._maps[t],w!=null&&w<t?S+w:void 0)}}getMirror(e){if(this.mirror){for(let t=0;t<this.mirror.length;t++)if(this.mirror[t]==e)return this.mirror[t+(t%2?-1:1)]}}setMirror(e,t){this.mirror||=[],this.mirror.push(e,t)}appendMappingInverted(e){for(let t=e.maps.length-1,S=this._maps.length+e._maps.length;t>=0;t--){let w=e.getMirror(t);this.appendMap(e._maps[t].invert(),w!=null&&w>t?S-w-1:void 0)}}invert(){let t=new e;return t.appendMappingInverted(this),t}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let S=this.from;S<this.to;S++)e=this._maps[S].map(e,t);return e}mapResult(e,t=1){return this._map(e,t,!1)}_map(e,t,S){let w=0;for(let S=this.from;S<this.to;S++){let E=this._maps[S].mapResult(e,t);if(E.recover!=null){let t=this.getMirror(S);if(t!=null&&t>S&&t<this.to){S=t,e=this._maps[t].recover(E.recover);continue}}w|=E.delInfo,e=E.pos}return S?e:new MapResult(e,w,null)}};const stepsByID=Object.create(null);var Step=class{getMap(){return StepMap.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw RangeError(`Invalid input for Step.fromJSON`);let S=stepsByID[t.stepType];if(!S)throw RangeError(`No step type ${t.stepType} defined`);return S.fromJSON(e,t)}static jsonID(e,t){if(e in stepsByID)throw RangeError(`Duplicate use of step JSON ID `+e);return stepsByID[e]=t,t.prototype.jsonID=e,t}},StepResult=class e{constructor(e,t){this.doc=e,this.failed=t}static ok(t){return new e(t,null)}static fail(t){return new e(null,t)}static fromReplace(t,S,w,E){try{return e.ok(t.replace(S,w,E))}catch(t){if(t instanceof ReplaceError)return e.fail(t.message);throw t}}};function mapFragment(e,t,S){let w=[];for(let E=0;E<e.childCount;E++){let D=e.child(E);D.content.size&&(D=D.copy(mapFragment(D.content,t,D))),D.isInline&&(D=t(D,S,E)),w.push(D)}return Fragment.fromArray(w)}var AddMarkStep=class e extends Step{constructor(e,t,S){super(),this.from=e,this.to=t,this.mark=S}apply(e){let t=e.slice(this.from,this.to),S=e.resolve(this.from),w=S.node(S.sharedDepth(this.to)),E=new Slice(mapFragment(t.content,(e,t)=>!e.isAtom||!t.type.allowsMarkType(this.mark.type)?e:e.mark(this.mark.addToSet(e.marks)),w),t.openStart,t.openEnd);return StepResult.fromReplace(e,this.from,this.to,E)}invert(){return new RemoveMarkStep(this.from,this.to,this.mark)}map(t){let S=t.mapResult(this.from,1),w=t.mapResult(this.to,-1);return S.deleted&&w.deleted||S.pos>=w.pos?null:new e(S.pos,w.pos,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`addMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,S){if(typeof S.from!=`number`||typeof S.to!=`number`)throw RangeError(`Invalid input for AddMarkStep.fromJSON`);return new e(S.from,S.to,t.markFromJSON(S.mark))}};Step.jsonID(`addMark`,AddMarkStep);var RemoveMarkStep=class e extends Step{constructor(e,t,S){super(),this.from=e,this.to=t,this.mark=S}apply(e){let t=e.slice(this.from,this.to),S=new Slice(mapFragment(t.content,e=>e.mark(this.mark.removeFromSet(e.marks)),e),t.openStart,t.openEnd);return StepResult.fromReplace(e,this.from,this.to,S)}invert(){return new AddMarkStep(this.from,this.to,this.mark)}map(t){let S=t.mapResult(this.from,1),w=t.mapResult(this.to,-1);return S.deleted&&w.deleted||S.pos>=w.pos?null:new e(S.pos,w.pos,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`removeMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,S){if(typeof S.from!=`number`||typeof S.to!=`number`)throw RangeError(`Invalid input for RemoveMarkStep.fromJSON`);return new e(S.from,S.to,t.markFromJSON(S.mark))}};Step.jsonID(`removeMark`,RemoveMarkStep);var AddNodeMarkStep=class e extends Step{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return StepResult.fail(`No node at mark step's position`);let S=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return StepResult.fromReplace(e,this.pos,this.pos+1,new Slice(Fragment.from(S),0,t.isLeaf?0:1))}invert(t){let S=t.nodeAt(this.pos);if(S){let t=this.mark.addToSet(S.marks);if(t.length==S.marks.length){for(let w=0;w<S.marks.length;w++)if(!S.marks[w].isInSet(t))return new e(this.pos,S.marks[w]);return new e(this.pos,this.mark)}}return new RemoveNodeMarkStep(this.pos,this.mark)}map(t){let S=t.mapResult(this.pos,1);return S.deletedAfter?null:new e(S.pos,this.mark)}toJSON(){return{stepType:`addNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,S){if(typeof S.pos!=`number`)throw RangeError(`Invalid input for AddNodeMarkStep.fromJSON`);return new e(S.pos,t.markFromJSON(S.mark))}};Step.jsonID(`addNodeMark`,AddNodeMarkStep);var RemoveNodeMarkStep=class e extends Step{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return StepResult.fail(`No node at mark step's position`);let S=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return StepResult.fromReplace(e,this.pos,this.pos+1,new Slice(Fragment.from(S),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new AddNodeMarkStep(this.pos,this.mark)}map(t){let S=t.mapResult(this.pos,1);return S.deletedAfter?null:new e(S.pos,this.mark)}toJSON(){return{stepType:`removeNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,S){if(typeof S.pos!=`number`)throw RangeError(`Invalid input for RemoveNodeMarkStep.fromJSON`);return new e(S.pos,t.markFromJSON(S.mark))}};Step.jsonID(`removeNodeMark`,RemoveNodeMarkStep);var ReplaceStep=class e extends Step{constructor(e,t,S,w=!1){super(),this.from=e,this.to=t,this.slice=S,this.structure=w}apply(e){return this.structure&&contentBetween(e,this.from,this.to)?StepResult.fail(`Structure replace would overwrite content`):StepResult.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new StepMap([this.from,this.to-this.from,this.slice.size])}invert(t){return new e(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let S=t.mapResult(this.to,-1),w=this.from==this.to&&e.MAP_BIAS<0?S:t.mapResult(this.from,1);return w.deletedAcross&&S.deletedAcross?null:new e(w.pos,Math.max(w.pos,S.pos),this.slice,this.structure)}merge(t){if(!(t instanceof e)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let S=this.slice.size+t.slice.size==0?Slice.empty:new Slice(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new e(this.from,this.to+(t.to-t.from),S,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let S=this.slice.size+t.slice.size==0?Slice.empty:new Slice(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new e(t.from,this.to,S,this.structure)}else return null}toJSON(){let e={stepType:`replace`,from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(t,S){if(typeof S.from!=`number`||typeof S.to!=`number`)throw RangeError(`Invalid input for ReplaceStep.fromJSON`);return new e(S.from,S.to,Slice.fromJSON(t,S.slice),!!S.structure)}};ReplaceStep.MAP_BIAS=1,Step.jsonID(`replace`,ReplaceStep);var ReplaceAroundStep=class e extends Step{constructor(e,t,S,w,E,D,O=!1){super(),this.from=e,this.to=t,this.gapFrom=S,this.gapTo=w,this.slice=E,this.insert=D,this.structure=O}apply(e){if(this.structure&&(contentBetween(e,this.from,this.gapFrom)||contentBetween(e,this.gapTo,this.to)))return StepResult.fail(`Structure gap-replace would overwrite content`);let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return StepResult.fail(`Gap is not a flat range`);let S=this.slice.insertAt(this.insert,t.content);return S?StepResult.fromReplace(e,this.from,this.to,S):StepResult.fail(`Content does not fit in gap`)}getMap(){return new StepMap([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let S=this.gapTo-this.gapFrom;return new e(this.from,this.from+this.slice.size+S,this.from+this.insert,this.from+this.insert+S,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let S=t.mapResult(this.from,1),w=t.mapResult(this.to,-1),E=this.from==this.gapFrom?S.pos:t.map(this.gapFrom,-1),D=this.to==this.gapTo?w.pos:t.map(this.gapTo,1);return S.deletedAcross&&w.deletedAcross||E<S.pos||D>w.pos?null:new e(S.pos,w.pos,E,D,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:`replaceAround`,from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(t,S){if(typeof S.from!=`number`||typeof S.to!=`number`||typeof S.gapFrom!=`number`||typeof S.gapTo!=`number`||typeof S.insert!=`number`)throw RangeError(`Invalid input for ReplaceAroundStep.fromJSON`);return new e(S.from,S.to,S.gapFrom,S.gapTo,Slice.fromJSON(t,S.slice),S.insert,!!S.structure)}};Step.jsonID(`replaceAround`,ReplaceAroundStep);function contentBetween(e,t,S){let w=e.resolve(t),E=S-t,D=w.depth;for(;E>0&&D>0&&w.indexAfter(D)==w.node(D).childCount;)D--,E--;if(E>0){let e=w.node(D).maybeChild(w.indexAfter(D));for(;E>0;){if(!e||e.isLeaf)return!0;e=e.firstChild,E--}}return!1}function addMark(e,t,S,w){let E=[],D=[],O,k;e.doc.nodesBetween(t,S,(e,j,F)=>{if(!e.isInline)return;let L=e.marks;if(!w.isInSet(L)&&F.type.allowsMarkType(w.type)){let F=Math.max(j,t),B=Math.min(j+e.nodeSize,S),H=w.addToSet(L);for(let e=0;e<L.length;e++)L[e].isInSet(H)||(O&&O.to==F&&O.mark.eq(L[e])?O.to=B:E.push(O=new RemoveMarkStep(F,B,L[e])));k&&k.to==F?k.to=B:D.push(k=new AddMarkStep(F,B,w))}}),E.forEach(t=>e.step(t)),D.forEach(t=>e.step(t))}function removeMark(e,t,S,w){let E=[],D=0;e.doc.nodesBetween(t,S,(e,O)=>{if(!e.isInline)return;D++;let k=null;if(w instanceof MarkType){let t=e.marks,S;for(;S=w.isInSet(t);)(k||=[]).push(S),t=S.removeFromSet(t)}else w?w.isInSet(e.marks)&&(k=[w]):k=e.marks;if(k&&k.length){let w=Math.min(O+e.nodeSize,S);for(let e=0;e<k.length;e++){let S=k[e],j;for(let e=0;e<E.length;e++){let t=E[e];t.step==D-1&&S.eq(E[e].style)&&(j=t)}j?(j.to=w,j.step=D):E.push({style:S,from:Math.max(O,t),to:w,step:D})}}}),E.forEach(t=>e.step(new RemoveMarkStep(t.from,t.to,t.style)))}function clearIncompatible(e,t,S,w=S.contentMatch,E=!0){let D=e.doc.nodeAt(t),O=[],k=t+1;for(let t=0;t<D.childCount;t++){let j=D.child(t),F=k+j.nodeSize,L=w.matchType(j.type);if(!L)O.push(new ReplaceStep(k,F,Slice.empty));else{w=L;for(let t=0;t<j.marks.length;t++)S.allowsMarkType(j.marks[t].type)||e.step(new RemoveMarkStep(k,F,j.marks[t]));if(E&&j.isText&&S.whitespace!=`pre`){let e,t=/\r?\n|\r/g,w;for(;e=t.exec(j.text);)w||=new Slice(Fragment.from(S.schema.text(` `,S.allowedMarks(j.marks))),0,0),O.push(new ReplaceStep(k+e.index,k+e.index+e[0].length,w))}}k=F}if(!w.validEnd){let t=w.fillBefore(Fragment.empty,!0);e.replace(k,k,new Slice(t,0,0))}for(let t=O.length-1;t>=0;t--)e.step(O[t])}function canCut(e,t,S){return(t==0||e.canReplace(t,e.childCount))&&(S==e.childCount||e.canReplace(0,S))}function liftTarget(e){let t=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let S=e.depth,w=0,E=0;;--S){let D=e.$from.node(S),O=e.$from.index(S)+w,k=e.$to.indexAfter(S)-E;if(S<e.depth&&D.canReplace(O,k,t))return S;if(S==0||D.type.spec.isolating||!canCut(D,O,k))break;O&&(w=1),k<D.childCount&&(E=1)}return null}function lift$2(e,t,S){let{$from:w,$to:E,depth:D}=t,O=w.before(D+1),k=E.after(D+1),j=O,F=k,L=Fragment.empty,B=0;for(let e=D,t=!1;e>S;e--)t||w.index(e)>0?(t=!0,L=Fragment.from(w.node(e).copy(L)),B++):j--;let H=Fragment.empty,q=0;for(let e=D,t=!1;e>S;e--)t||E.after(e+1)<E.end(e)?(t=!0,H=Fragment.from(E.node(e).copy(H)),q++):F++;e.step(new ReplaceAroundStep(j,F,O,k,new Slice(L.append(H),B,q),L.size-B,!0))}function findWrapping(e,t,S=null,w=e){let E=findWrappingOutside(e,t),D=E&&findWrappingInside(w,t);return D?E.map(withAttrs).concat({type:t,attrs:S}).concat(D.map(withAttrs)):null}function withAttrs(e){return{type:e,attrs:null}}function findWrappingOutside(e,t){let{parent:S,startIndex:w,endIndex:E}=e,D=S.contentMatchAt(w).findWrapping(t);if(!D)return null;let O=D.length?D[0]:t;return S.canReplaceWith(w,E,O)?D:null}function findWrappingInside(e,t){let{parent:S,startIndex:w,endIndex:E}=e,D=S.child(w),O=t.contentMatch.findWrapping(D.type);if(!O)return null;let k=(O.length?O[O.length-1]:t).contentMatch;for(let e=w;k&&e<E;e++)k=k.matchType(S.child(e).type);return!k||!k.validEnd?null:O}function wrap$1(e,t,S){let w=Fragment.empty;for(let e=S.length-1;e>=0;e--){if(w.size){let t=S[e].type.contentMatch.matchFragment(w);if(!t||!t.validEnd)throw RangeError(`Wrapper type given to Transform.wrap does not form valid content of its parent wrapper`)}w=Fragment.from(S[e].type.create(S[e].attrs,w))}let E=t.start,D=t.end;e.step(new ReplaceAroundStep(E,D,E,D,new Slice(w,0,0),S.length,!0))}function setBlockType$1(e,t,S,w,E){if(!w.isTextblock)throw RangeError(`Type given to setBlockType should be a textblock`);let D=e.steps.length;e.doc.nodesBetween(t,S,(t,S)=>{let O=typeof E==`function`?E(t):E;if(t.isTextblock&&!t.hasMarkup(w,O)&&canChangeType(e.doc,e.mapping.slice(D).map(S),w)){let E=null;if(w.schema.linebreakReplacement){let e=w.whitespace==`pre`,t=!!w.contentMatch.matchType(w.schema.linebreakReplacement);e&&!t?E=!1:!e&&t&&(E=!0)}E===!1&&replaceLinebreaks(e,t,S,D),clearIncompatible(e,e.mapping.slice(D).map(S,1),w,void 0,E===null);let k=e.mapping.slice(D),j=k.map(S,1),F=k.map(S+t.nodeSize,1);return e.step(new ReplaceAroundStep(j,F,j+1,F-1,new Slice(Fragment.from(w.create(O,null,t.marks)),0,0),1,!0)),E===!0&&replaceNewlines$1(e,t,S,D),!1}})}function replaceNewlines$1(e,t,S,w){t.forEach((E,D)=>{if(E.isText){let O,k=/\r?\n|\r/g;for(;O=k.exec(E.text);){let E=e.mapping.slice(w).map(S+1+D+O.index);e.replaceWith(E,E+1,t.type.schema.linebreakReplacement.create())}}})}function replaceLinebreaks(e,t,S,w){t.forEach((E,D)=>{if(E.type==E.type.schema.linebreakReplacement){let E=e.mapping.slice(w).map(S+1+D);e.replaceWith(E,E+1,t.type.schema.text(`
|
|
164
|
-
`))}})}function canChangeType(e,t,S){let w=e.resolve(t),E=w.index();return w.parent.canReplaceWith(E,E+1,S)}function setNodeMarkup(e,t,S,w,E){let D=e.doc.nodeAt(t);if(!D)throw RangeError(`No node at given position`);S||=D.type;let O=S.create(w,null,E||D.marks);if(D.isLeaf)return e.replaceWith(t,t+D.nodeSize,O);if(!S.validContent(D.content))throw RangeError(`Invalid content for node type `+S.name);e.step(new ReplaceAroundStep(t,t+D.nodeSize,t+1,t+D.nodeSize-1,new Slice(Fragment.from(O),0,0),1,!0))}function canSplit(e,t,S=1,w){let E=e.resolve(t),D=E.depth-S,O=w&&w[w.length-1]||E.parent;if(D<0||E.parent.type.spec.isolating||!E.parent.canReplace(E.index(),E.parent.childCount)||!O.type.validContent(E.parent.content.cutByIndex(E.index(),E.parent.childCount)))return!1;for(let e=E.depth-1,t=S-2;e>D;e--,t--){let S=E.node(e),D=E.index(e);if(S.type.spec.isolating)return!1;let O=S.content.cutByIndex(D,S.childCount),k=w&&w[t+1];k&&(O=O.replaceChild(0,k.type.create(k.attrs)));let j=w&&w[t]||S;if(!S.canReplace(D+1,S.childCount)||!j.type.validContent(O))return!1}let k=E.indexAfter(D),j=w&&w[0];return E.node(D).canReplaceWith(k,k,j?j.type:E.node(D+1).type)}function split(e,t,S=1,w){let E=e.doc.resolve(t),D=Fragment.empty,O=Fragment.empty;for(let e=E.depth,t=E.depth-S,k=S-1;e>t;e--,k--){D=Fragment.from(E.node(e).copy(D));let t=w&&w[k];O=Fragment.from(t?t.type.create(t.attrs,O):E.node(e).copy(O))}e.step(new ReplaceStep(t,t,new Slice(D.append(O),S,S),!0))}function canJoin(e,t){let S=e.resolve(t),w=S.index();return joinable(S.nodeBefore,S.nodeAfter)&&S.parent.canReplace(w,w+1)}function canAppendWithSubstitutedLinebreaks(e,t){t.content.size||e.type.compatibleContent(t.type);let S=e.contentMatchAt(e.childCount),{linebreakReplacement:w}=e.type.schema;for(let E=0;E<t.childCount;E++){let D=t.child(E),O=D.type==w?e.type.schema.nodes.text:D.type;if(S=S.matchType(O),!S||!e.type.allowsMarks(D.marks))return!1}return S.validEnd}function joinable(e,t){return!!(e&&t&&!e.isLeaf&&canAppendWithSubstitutedLinebreaks(e,t))}function joinPoint(e,t,S=-1){let w=e.resolve(t);for(let e=w.depth;;e--){let E,D,O=w.index(e);if(e==w.depth?(E=w.nodeBefore,D=w.nodeAfter):S>0?(E=w.node(e+1),O++,D=w.node(e).maybeChild(O)):(E=w.node(e).maybeChild(O-1),D=w.node(e+1)),E&&!E.isTextblock&&joinable(E,D)&&w.node(e).canReplace(O,O+1))return t;if(e==0)break;t=S<0?w.before(e):w.after(e)}}function join$4(e,t,S){let w=null,{linebreakReplacement:E}=e.doc.type.schema,D=e.doc.resolve(t-S),O=D.node().type;if(E&&O.inlineContent){let e=O.whitespace==`pre`,t=!!O.contentMatch.matchType(E);e&&!t?w=!1:!e&&t&&(w=!0)}let k=e.steps.length;if(w===!1){let w=e.doc.resolve(t+S);replaceLinebreaks(e,w.node(),w.before(),k)}O.inlineContent&&clearIncompatible(e,t+S-1,O,D.node().contentMatchAt(D.index()),w==null);let j=e.mapping.slice(k),F=j.map(t-S);if(e.step(new ReplaceStep(F,j.map(t+S,-1),Slice.empty,!0)),w===!0){let t=e.doc.resolve(F);replaceNewlines$1(e,t.node(),t.before(),e.steps.length)}return e}function insertPoint(e,t,S){let w=e.resolve(t);if(w.parent.canReplaceWith(w.index(),w.index(),S))return t;if(w.parentOffset==0)for(let e=w.depth-1;e>=0;e--){let t=w.index(e);if(w.node(e).canReplaceWith(t,t,S))return w.before(e+1);if(t>0)return null}if(w.parentOffset==w.parent.content.size)for(let e=w.depth-1;e>=0;e--){let t=w.indexAfter(e);if(w.node(e).canReplaceWith(t,t,S))return w.after(e+1);if(t<w.node(e).childCount)return null}return null}function dropPoint(e,t,S){let w=e.resolve(t);if(!S.content.size)return t;let E=S.content;for(let e=0;e<S.openStart;e++)E=E.firstChild.content;for(let e=1;e<=(S.openStart==0&&S.size?2:1);e++)for(let t=w.depth;t>=0;t--){let S=t==w.depth?0:w.pos<=(w.start(t+1)+w.end(t+1))/2?-1:1,D=w.index(t)+(S>0?1:0),O=w.node(t),k=!1;if(e==1)k=O.canReplace(D,D,E);else{let e=O.contentMatchAt(D).findWrapping(E.firstChild.type);k=e&&O.canReplaceWith(D,D,e[0])}if(k)return S==0?w.pos:S<0?w.before(t+1):w.after(t+1)}return null}function replaceStep(e,t,S=t,w=Slice.empty){if(t==S&&!w.size)return null;let E=e.resolve(t),D=e.resolve(S);return fitsTrivially(E,D,w)?new ReplaceStep(t,S,w):new Fitter(E,D,w).fit()}function fitsTrivially(e,t,S){return!S.openStart&&!S.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),S.content)}var Fitter=class{constructor(e,t,S){this.$from=e,this.$to=t,this.unplaced=S,this.frontier=[],this.placed=Fragment.empty;for(let t=0;t<=e.depth;t++){let S=e.node(t);this.frontier.push({type:S.type,match:S.contentMatchAt(e.indexAfter(t))})}for(let t=e.depth;t>0;t--)this.placed=Fragment.from(e.node(t).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let e=this.findFittable();e?this.placeNodes(e):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,S=this.$from,w=this.close(e<0?this.$to:S.doc.resolve(e));if(!w)return null;let E=this.placed,D=S.depth,O=w.depth;for(;D&&O&&E.childCount==1;)E=E.firstChild.content,D--,O--;let k=new Slice(E,D,O);return e>-1?new ReplaceAroundStep(S.pos,e,this.$to.pos,this.$to.end(),k,t):k.size||S.pos!=this.$to.pos?new ReplaceStep(S.pos,w.pos,k):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,S=0,w=this.unplaced.openEnd;S<e;S++){let E=t.firstChild;if(t.childCount>1&&(w=0),E.type.spec.isolating&&w<=S){e=S;break}t=E.content}for(let t=1;t<=2;t++)for(let S=t==1?e:this.unplaced.openStart;S>=0;S--){let e,w=null;S?(w=contentAt(this.unplaced.content,S-1).firstChild,e=w.content):e=this.unplaced.content;let E=e.firstChild;for(let e=this.depth;e>=0;e--){let{type:D,match:O}=this.frontier[e],k,j=null;if(t==1&&(E?O.matchType(E.type)||(j=O.fillBefore(Fragment.from(E),!1)):w&&D.compatibleContent(w.type)))return{sliceDepth:S,frontierDepth:e,parent:w,inject:j};if(t==2&&E&&(k=O.findWrapping(E.type)))return{sliceDepth:S,frontierDepth:e,parent:w,wrap:k};if(w&&O.matchType(w.type))break}}}openMore(){let{content:e,openStart:t,openEnd:S}=this.unplaced,w=contentAt(e,t);return!w.childCount||w.firstChild.isLeaf?!1:(this.unplaced=new Slice(e,t+1,Math.max(S,w.size+t>=e.size-S?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:S}=this.unplaced,w=contentAt(e,t);if(w.childCount<=1&&t>0){let E=e.size-t<=t+w.size;this.unplaced=new Slice(dropFromFragment(e,t-1,1),t-1,E?t-1:S)}else this.unplaced=new Slice(dropFromFragment(e,t,1),t,S)}placeNodes({sliceDepth:e,frontierDepth:t,parent:S,inject:w,wrap:E}){for(;this.depth>t;)this.closeFrontierNode();if(E)for(let e=0;e<E.length;e++)this.openFrontierNode(E[e]);let D=this.unplaced,O=S?S.content:D.content,k=D.openStart-e,j=0,F=[],{match:L,type:B}=this.frontier[t];if(w){for(let e=0;e<w.childCount;e++)F.push(w.child(e));L=L.matchFragment(w)}let H=O.size+e-(D.content.size-D.openEnd);for(;j<O.childCount;){let e=O.child(j),t=L.matchType(e.type);if(!t)break;j++,(j>1||k==0||e.content.size)&&(L=t,F.push(closeNodeStart(e.mark(B.allowedMarks(e.marks)),j==1?k:0,j==O.childCount?H:-1)))}let q=j==O.childCount;q||(H=-1),this.placed=addToFragment(this.placed,t,Fragment.from(F)),this.frontier[t].match=L,q&&H<0&&S&&S.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let e=0,t=O;e<H;e++){let e=t.lastChild;this.frontier.push({type:e.type,match:e.contentMatchAt(e.childCount)}),t=e.content}this.unplaced=q?e==0?Slice.empty:new Slice(dropFromFragment(D.content,e-1,1),e-1,H<0?D.openEnd:e-1):new Slice(dropFromFragment(D.content,e,j),D.openStart,D.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],t;if(!e.type.isTextblock||!contentAfterFits(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(t=this.findCloseLevel(this.$to))&&t.depth==this.depth)return-1;let{depth:S}=this.$to,w=this.$to.after(S);for(;S>1&&w==this.$to.end(--S);)++w;return w}findCloseLevel(e){scan:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:S,type:w}=this.frontier[t],E=t<e.depth&&e.end(t+1)==e.pos+(e.depth-(t+1)),D=contentAfterFits(e,t,w,S,E);if(D){for(let S=t-1;S>=0;S--){let{match:t,type:w}=this.frontier[S],E=contentAfterFits(e,S,w,t,!0);if(!E||E.childCount)continue scan}return{depth:t,fit:D,move:E?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=addToFragment(this.placed,t.depth,t.fit)),e=t.move;for(let S=t.depth+1;S<=e.depth;S++){let t=e.node(S),w=t.type.contentMatch.fillBefore(t.content,!0,e.index(S));this.openFrontierNode(t.type,t.attrs,w)}return e}openFrontierNode(e,t=null,S){let w=this.frontier[this.depth];w.match=w.match.matchType(e),this.placed=addToFragment(this.placed,this.depth,Fragment.from(e.create(t,S))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let e=this.frontier.pop().match.fillBefore(Fragment.empty,!0);e.childCount&&(this.placed=addToFragment(this.placed,this.frontier.length,e))}};function dropFromFragment(e,t,S){return t==0?e.cutByIndex(S,e.childCount):e.replaceChild(0,e.firstChild.copy(dropFromFragment(e.firstChild.content,t-1,S)))}function addToFragment(e,t,S){return t==0?e.append(S):e.replaceChild(e.childCount-1,e.lastChild.copy(addToFragment(e.lastChild.content,t-1,S)))}function contentAt(e,t){for(let S=0;S<t;S++)e=e.firstChild.content;return e}function closeNodeStart(e,t,S){if(t<=0)return e;let w=e.content;return t>1&&(w=w.replaceChild(0,closeNodeStart(w.firstChild,t-1,w.childCount==1?S-1:0))),t>0&&(w=e.type.contentMatch.fillBefore(w).append(w),S<=0&&(w=w.append(e.type.contentMatch.matchFragment(w).fillBefore(Fragment.empty,!0)))),e.copy(w)}function contentAfterFits(e,t,S,w,E){let D=e.node(t),O=E?e.indexAfter(t):e.index(t);if(O==D.childCount&&!S.compatibleContent(D.type))return null;let k=w.fillBefore(D.content,!0,O);return k&&!invalidMarks(S,D.content,O)?k:null}function invalidMarks(e,t,S){for(let w=S;w<t.childCount;w++)if(!e.allowsMarks(t.child(w).marks))return!0;return!1}function definesContent(e){return e.spec.defining||e.spec.definingForContent}function replaceRange(e,t,S,w){if(!w.size)return e.deleteRange(t,S);let E=e.doc.resolve(t),D=e.doc.resolve(S);if(fitsTrivially(E,D,w))return e.step(new ReplaceStep(t,S,w));let O=coveredDepths(E,D);O[O.length-1]==0&&O.pop();let k=-(E.depth+1);O.unshift(k);for(let e=E.depth,t=E.pos-1;e>0;e--,t--){let S=E.node(e).type.spec;if(S.defining||S.definingAsContext||S.isolating)break;O.indexOf(e)>-1?k=e:E.before(e)==t&&O.splice(1,0,-e)}let j=O.indexOf(k),F=[],L=w.openStart;for(let e=w.content,t=0;;t++){let S=e.firstChild;if(F.push(S),t==w.openStart)break;e=S.content}for(let e=L-1;e>=0;e--){let t=F[e],S=definesContent(t.type);if(S&&!t.sameMarkup(E.node(Math.abs(k)-1)))L=e;else if(S||!t.type.isTextblock)break}for(let t=w.openStart;t>=0;t--){let k=(t+L+1)%(w.openStart+1),B=F[k];if(B)for(let t=0;t<O.length;t++){let F=O[(t+j)%O.length],L=!0;F<0&&(L=!1,F=-F);let H=E.node(F-1),q=E.index(F-1);if(H.canReplaceWith(q,q,B.type,B.marks))return e.replace(E.before(F),L?D.after(F):S,new Slice(closeFragment(w.content,0,w.openStart,k),k,w.openEnd))}}let B=e.steps.length;for(let k=O.length-1;k>=0&&(e.replace(t,S,w),!(e.steps.length>B));k--){let e=O[k];e<0||(t=E.before(e),S=D.after(e))}}function closeFragment(e,t,S,w,E){if(t<S){let E=e.firstChild;e=e.replaceChild(0,E.copy(closeFragment(E.content,t+1,S,w,E)))}if(t>w){let t=E.contentMatchAt(0),S=t.fillBefore(e).append(e);e=S.append(t.matchFragment(S).fillBefore(Fragment.empty,!0))}return e}function replaceRangeWith(e,t,S,w){if(!w.isInline&&t==S&&e.doc.resolve(t).parent.content.size){let E=insertPoint(e.doc,t,w.type);E!=null&&(t=S=E)}e.replaceRange(t,S,new Slice(Fragment.from(w),0,0))}function deleteRange$1(e,t,S){let w=e.doc.resolve(t),E=e.doc.resolve(S);if(w.parent.isTextblock&&E.parent.isTextblock&&w.start()!=E.start()&&w.parentOffset==0&&E.parentOffset==0){let D=w.sharedDepth(S),O=!1;for(let e=w.depth;e>D;e--)w.node(e).type.spec.isolating&&(O=!0);for(let e=E.depth;e>D;e--)E.node(e).type.spec.isolating&&(O=!0);if(!O){for(let e=w.depth;e>0&&t==w.start(e);e--)t=w.before(e);for(let e=E.depth;e>0&&S==E.start(e);e--)S=E.before(e);w=e.doc.resolve(t),E=e.doc.resolve(S)}}let D=coveredDepths(w,E);for(let t=0;t<D.length;t++){let S=D[t],O=t==D.length-1;if(O&&S==0||w.node(S).type.contentMatch.validEnd)return e.delete(w.start(S),E.end(S));if(S>0&&(O||w.node(S-1).canReplace(w.index(S-1),E.indexAfter(S-1))))return e.delete(w.before(S),E.after(S))}for(let D=1;D<=w.depth&&D<=E.depth;D++)if(t-w.start(D)==w.depth-D&&S>w.end(D)&&E.end(D)-S!=E.depth-D&&w.start(D-1)==E.start(D-1)&&w.node(D-1).canReplace(w.index(D-1),E.index(D-1)))return e.delete(w.before(D),S);e.delete(t,S)}function coveredDepths(e,t){let S=[],w=Math.min(e.depth,t.depth);for(let E=w;E>=0;E--){let w=e.start(E);if(w<e.pos-(e.depth-E)||t.end(E)>t.pos+(t.depth-E)||e.node(E).type.spec.isolating||t.node(E).type.spec.isolating)break;(w==t.start(E)||E==e.depth&&E==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&E&&t.start(E-1)==w-1)&&S.push(E)}return S}var AttrStep=class e extends Step{constructor(e,t,S){super(),this.pos=e,this.attr=t,this.value=S}apply(e){let t=e.nodeAt(this.pos);if(!t)return StepResult.fail(`No node at attribute step's position`);let S=Object.create(null);for(let e in t.attrs)S[e]=t.attrs[e];S[this.attr]=this.value;let w=t.type.create(S,null,t.marks);return StepResult.fromReplace(e,this.pos,this.pos+1,new Slice(Fragment.from(w),0,t.isLeaf?0:1))}getMap(){return StepMap.empty}invert(t){return new e(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let S=t.mapResult(this.pos,1);return S.deletedAfter?null:new e(S.pos,this.attr,this.value)}toJSON(){return{stepType:`attr`,pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,S){if(typeof S.pos!=`number`||typeof S.attr!=`string`)throw RangeError(`Invalid input for AttrStep.fromJSON`);return new e(S.pos,S.attr,S.value)}};Step.jsonID(`attr`,AttrStep);var DocAttrStep=class e extends Step{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let S in e.attrs)t[S]=e.attrs[S];t[this.attr]=this.value;let S=e.type.create(t,e.content,e.marks);return StepResult.ok(S)}getMap(){return StepMap.empty}invert(t){return new e(this.attr,t.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:`docAttr`,attr:this.attr,value:this.value}}static fromJSON(t,S){if(typeof S.attr!=`string`)throw RangeError(`Invalid input for DocAttrStep.fromJSON`);return new e(S.attr,S.value)}};Step.jsonID(`docAttr`,DocAttrStep);let TransformError=class extends Error{};TransformError=function e(t){let S=Error.call(this,t);return S.__proto__=e.prototype,S},TransformError.prototype=Object.create(Error.prototype),TransformError.prototype.constructor=TransformError,TransformError.prototype.name=`TransformError`;var Transform$4=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Mapping}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new TransformError(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let S=0;S<this.mapping.maps.length;S++){let w=this.mapping.maps[S];S&&(e=w.map(e,1),t=w.map(t,-1)),w.forEach((S,w,E,D)=>{e=Math.min(e,E),t=Math.max(t,D)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,S=Slice.empty){let w=replaceStep(this.doc,e,t,S);return w&&this.step(w),this}replaceWith(e,t,S){return this.replace(e,t,new Slice(Fragment.from(S),0,0))}delete(e,t){return this.replace(e,t,Slice.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,S){return replaceRange(this,e,t,S),this}replaceRangeWith(e,t,S){return replaceRangeWith(this,e,t,S),this}deleteRange(e,t){return deleteRange$1(this,e,t),this}lift(e,t){return lift$2(this,e,t),this}join(e,t=1){return join$4(this,e,t),this}wrap(e,t){return wrap$1(this,e,t),this}setBlockType(e,t=e,S,w=null){return setBlockType$1(this,e,t,S,w),this}setNodeMarkup(e,t,S=null,w){return setNodeMarkup(this,e,t,S,w),this}setNodeAttribute(e,t,S){return this.step(new AttrStep(e,t,S)),this}setDocAttribute(e,t){return this.step(new DocAttrStep(e,t)),this}addNodeMark(e,t){return this.step(new AddNodeMarkStep(e,t)),this}removeNodeMark(e,t){let S=this.doc.nodeAt(e);if(!S)throw RangeError(`No node at position `+e);if(t instanceof Mark$1)t.isInSet(S.marks)&&this.step(new RemoveNodeMarkStep(e,t));else{let w=S.marks,E,D=[];for(;E=t.isInSet(w);)D.push(new RemoveNodeMarkStep(e,E)),w=E.removeFromSet(w);for(let e=D.length-1;e>=0;e--)this.step(D[e])}return this}split(e,t=1,S){return split(this,e,t,S),this}addMark(e,t,S){return addMark(this,e,t,S),this}removeMark(e,t,S){return removeMark(this,e,t,S),this}clearIncompatible(e,t,S){return clearIncompatible(this,e,t,S),this}};const classesById=Object.create(null);var Selection$1=class{constructor(e,t,S){this.$anchor=e,this.$head=t,this.ranges=S||[new SelectionRange(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t<e.length;t++)if(e[t].$from.pos!=e[t].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,t=Slice.empty){let S=t.content.lastChild,w=null;for(let e=0;e<t.openEnd;e++)w=S,S=S.lastChild;let E=e.steps.length,D=this.ranges;for(let O=0;O<D.length;O++){let{$from:k,$to:j}=D[O],F=e.mapping.slice(E);e.replaceRange(F.map(k.pos),F.map(j.pos),O?Slice.empty:t),O==0&&selectionToInsertionEnd$1(e,E,(S?S.isInline:w&&w.isTextblock)?-1:1)}}replaceWith(e,t){let S=e.steps.length,w=this.ranges;for(let E=0;E<w.length;E++){let{$from:D,$to:O}=w[E],k=e.mapping.slice(S),j=k.map(D.pos),F=k.map(O.pos);E?e.deleteRange(j,F):(e.replaceRangeWith(j,F,t),selectionToInsertionEnd$1(e,S,t.isInline?-1:1))}}static findFrom(e,t,S=!1){let w=e.parent.inlineContent?new TextSelection(e):findSelectionIn(e.node(0),e.parent,e.pos,e.index(),t,S);if(w)return w;for(let w=e.depth-1;w>=0;w--){let E=t<0?findSelectionIn(e.node(0),e.node(w),e.before(w+1),e.index(w),t,S):findSelectionIn(e.node(0),e.node(w),e.after(w+1),e.index(w)+1,t,S);if(E)return E}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new AllSelection(e.node(0))}static atStart(e){return findSelectionIn(e,e,0,0,1)||new AllSelection(e)}static atEnd(e){return findSelectionIn(e,e,e.content.size,e.childCount,-1)||new AllSelection(e)}static fromJSON(e,t){if(!t||!t.type)throw RangeError(`Invalid input for Selection.fromJSON`);let S=classesById[t.type];if(!S)throw RangeError(`No selection type ${t.type} defined`);return S.fromJSON(e,t)}static jsonID(e,t){if(e in classesById)throw RangeError(`Duplicate use of selection JSON ID `+e);return classesById[e]=t,t.prototype.jsonID=e,t}getBookmark(){return TextSelection.between(this.$anchor,this.$head).getBookmark()}};Selection$1.prototype.visible=!0;var SelectionRange=class{constructor(e,t){this.$from=e,this.$to=t}};let warnedAboutTextSelection=!1;function checkTextSelection(e){!warnedAboutTextSelection&&!e.parent.inlineContent&&(warnedAboutTextSelection=!0,console.warn(`TextSelection endpoint not pointing into a node with inline content (`+e.parent.type.name+`)`))}var TextSelection=class e extends Selection$1{constructor(e,t=e){checkTextSelection(e),checkTextSelection(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,S){let w=t.resolve(S.map(this.head));if(!w.parent.inlineContent)return Selection$1.near(w);let E=t.resolve(S.map(this.anchor));return new e(E.parent.inlineContent?E:w,w)}replace(e,t=Slice.empty){if(super.replace(e,t),t==Slice.empty){let t=this.$from.marksAcross(this.$to);t&&e.ensureMarks(t)}}eq(t){return t instanceof e&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new TextBookmark(this.anchor,this.head)}toJSON(){return{type:`text`,anchor:this.anchor,head:this.head}}static fromJSON(t,S){if(typeof S.anchor!=`number`||typeof S.head!=`number`)throw RangeError(`Invalid input for TextSelection.fromJSON`);return new e(t.resolve(S.anchor),t.resolve(S.head))}static create(e,t,S=t){let w=e.resolve(t);return new this(w,S==t?w:e.resolve(S))}static between(t,S,w){let E=t.pos-S.pos;if((!w||E)&&(w=E>=0?1:-1),!S.parent.inlineContent){let e=Selection$1.findFrom(S,w,!0)||Selection$1.findFrom(S,-w,!0);if(e)S=e.$head;else return Selection$1.near(S,w)}return t.parent.inlineContent||(E==0?t=S:(t=(Selection$1.findFrom(t,-w,!0)||Selection$1.findFrom(t,w,!0)).$anchor,t.pos<S.pos!=E<0&&(t=S))),new e(t,S)}};Selection$1.jsonID(`text`,TextSelection);var TextBookmark=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){return TextSelection.between(e.resolve(this.anchor),e.resolve(this.head))}},NodeSelection=class e extends Selection$1{constructor(e){let t=e.nodeAfter,S=e.node(0).resolve(e.pos+t.nodeSize);super(e,S),this.node=t}map(t,S){let{deleted:w,pos:E}=S.mapResult(this.anchor),D=t.resolve(E);return w?Selection$1.near(D):new e(D)}content(){return new Slice(Fragment.from(this.node),0,0)}eq(t){return t instanceof e&&t.anchor==this.anchor}toJSON(){return{type:`node`,anchor:this.anchor}}getBookmark(){return new NodeBookmark(this.anchor)}static fromJSON(t,S){if(typeof S.anchor!=`number`)throw RangeError(`Invalid input for NodeSelection.fromJSON`);return new e(t.resolve(S.anchor))}static create(t,S){return new e(t.resolve(S))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};NodeSelection.prototype.visible=!1,Selection$1.jsonID(`node`,NodeSelection);var NodeBookmark=class e{constructor(e){this.anchor=e}map(t){let{deleted:S,pos:w}=t.mapResult(this.anchor);return S?new TextBookmark(w,w):new e(w)}resolve(e){let t=e.resolve(this.anchor),S=t.nodeAfter;return S&&NodeSelection.isSelectable(S)?new NodeSelection(t):Selection$1.near(t)}},AllSelection=class e extends Selection$1{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=Slice.empty){if(t==Slice.empty){e.delete(0,e.doc.content.size);let t=Selection$1.atStart(e.doc);t.eq(e.selection)||e.setSelection(t)}else super.replace(e,t)}toJSON(){return{type:`all`}}static fromJSON(t){return new e(t)}map(t){return new e(t)}eq(t){return t instanceof e}getBookmark(){return AllBookmark}};Selection$1.jsonID(`all`,AllSelection);const AllBookmark={map(){return this},resolve(e){return new AllSelection(e)}};function findSelectionIn(e,t,S,w,E,D=!1){if(t.inlineContent)return TextSelection.create(e,S);for(let O=w-(E>0?0:1);E>0?O<t.childCount:O>=0;O+=E){let w=t.child(O);if(!w.isAtom){let t=findSelectionIn(e,w,S+E,E<0?w.childCount:0,E,D);if(t)return t}else if(!D&&NodeSelection.isSelectable(w))return NodeSelection.create(e,S-(E<0?w.nodeSize:0));S+=w.nodeSize*E}return null}function selectionToInsertionEnd$1(e,t,S){let w=e.steps.length-1;if(w<t)return;let E=e.steps[w];if(!(E instanceof ReplaceStep||E instanceof ReplaceAroundStep))return;let D=e.mapping.maps[w],O;D.forEach((e,t,S,w)=>{O??=w}),e.setSelection(Selection$1.near(e.doc.resolve(O),S))}function bind(e,t){return!t||!e?e:e.bind(t)}var FieldDesc=class{constructor(e,t,S){this.name=e,this.init=bind(t.init,S),this.apply=bind(t.apply,S)}};const baseFields=[new FieldDesc(`doc`,{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new FieldDesc(`selection`,{init(e,t){return e.selection||Selection$1.atStart(t.doc)},apply(e){return e.selection}}),new FieldDesc(`storedMarks`,{init(e){return e.storedMarks||null},apply(e,t,S,w){return w.selection.$cursor?e.storedMarks:null}}),new FieldDesc(`scrollToSelection`,{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}})];function bindProps(e,t,S){for(let w in e){let E=e[w];E instanceof Function?E=E.bind(t):w==`handleDOMEvents`&&(E=bindProps(E,t,{})),S[w]=E}return S}var Plugin=class{constructor(e){this.spec=e,this.props={},e.props&&bindProps(e.props,this,this.props),this.key=e.key?e.key.key:createKey(`plugin`)}getState(e){return e[this.key]}};const keys$2=Object.create(null);function createKey(e){return e in keys$2?e+`$`+ ++keys$2[e]:(keys$2[e]=0,e+`$`)}var PluginKey=class{constructor(e=`key`){this.key=createKey(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};const deleteSelection$1=(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function atBlockStart(e,t){let{$cursor:S}=e.selection;return!S||(t?!t.endOfTextblock(`backward`,e):S.parentOffset>0)?null:S}const joinBackward$1=(e,t,S)=>{let w=atBlockStart(e,S);if(!w)return!1;let E=findCutBefore(w);if(!E){let S=w.blockRange(),E=S&&liftTarget(S);return E==null?!1:(t&&t(e.tr.lift(S,E).scrollIntoView()),!0)}let D=E.nodeBefore;if(deleteBarrier(e,E,t,-1))return!0;if(w.parent.content.size==0&&(textblockAt(D,`end`)||NodeSelection.isSelectable(D)))for(let S=w.depth;;S--){let O=replaceStep(e.doc,w.before(S),w.after(S),Slice.empty);if(O&&O.slice.size<O.to-O.from){if(t){let S=e.tr.step(O);S.setSelection(textblockAt(D,`end`)?Selection$1.findFrom(S.doc.resolve(S.mapping.map(E.pos,-1)),-1):NodeSelection.create(S.doc,E.pos-D.nodeSize)),t(S.scrollIntoView())}return!0}if(S==1||w.node(S-1).childCount>1)break}return D.isAtom&&E.depth==w.depth-1?(t&&t(e.tr.delete(E.pos-D.nodeSize,E.pos).scrollIntoView()),!0):!1},joinTextblockBackward$1=(e,t,S)=>{let w=atBlockStart(e,S);if(!w)return!1;let E=findCutBefore(w);return E?joinTextblocksAround(e,E,t):!1},joinTextblockForward$1=(e,t,S)=>{let w=atBlockEnd(e,S);if(!w)return!1;let E=findCutAfter(w);return E?joinTextblocksAround(e,E,t):!1};function joinTextblocksAround(e,t,S){let w=t.nodeBefore,E=t.pos-1;for(;!w.isTextblock;E--){if(w.type.spec.isolating)return!1;let e=w.lastChild;if(!e)return!1;w=e}let D=t.nodeAfter,O=t.pos+1;for(;!D.isTextblock;O++){if(D.type.spec.isolating)return!1;let e=D.firstChild;if(!e)return!1;D=e}let k=replaceStep(e.doc,E,O,Slice.empty);if(!k||k.from!=E||k instanceof ReplaceStep&&k.slice.size>=O-E)return!1;if(S){let t=e.tr.step(k);t.setSelection(TextSelection.create(t.doc,E)),S(t.scrollIntoView())}return!0}function textblockAt(e,t,S=!1){for(let w=e;w;w=t==`start`?w.firstChild:w.lastChild){if(w.isTextblock)return!0;if(S&&w.childCount!=1)return!1}return!1}const selectNodeBackward$1=(e,t,S)=>{let{$head:w,empty:E}=e.selection,D=w;if(!E)return!1;if(w.parent.isTextblock){if(S?!S.endOfTextblock(`backward`,e):w.parentOffset>0)return!1;D=findCutBefore(w)}let O=D&&D.nodeBefore;return!O||!NodeSelection.isSelectable(O)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,D.pos-O.nodeSize)).scrollIntoView()),!0)};function findCutBefore(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function atBlockEnd(e,t){let{$cursor:S}=e.selection;return!S||(t?!t.endOfTextblock(`forward`,e):S.parentOffset<S.parent.content.size)?null:S}const joinForward$1=(e,t,S)=>{let w=atBlockEnd(e,S);if(!w)return!1;let E=findCutAfter(w);if(!E)return!1;let D=E.nodeAfter;if(deleteBarrier(e,E,t,1))return!0;if(w.parent.content.size==0&&(textblockAt(D,`start`)||NodeSelection.isSelectable(D))){let S=replaceStep(e.doc,w.before(),w.after(),Slice.empty);if(S&&S.slice.size<S.to-S.from){if(t){let w=e.tr.step(S);w.setSelection(textblockAt(D,`start`)?Selection$1.findFrom(w.doc.resolve(w.mapping.map(E.pos)),1):NodeSelection.create(w.doc,w.mapping.map(E.pos))),t(w.scrollIntoView())}return!0}}return D.isAtom&&E.depth==w.depth-1?(t&&t(e.tr.delete(E.pos,E.pos+D.nodeSize).scrollIntoView()),!0):!1},selectNodeForward$1=(e,t,S)=>{let{$head:w,empty:E}=e.selection,D=w;if(!E)return!1;if(w.parent.isTextblock){if(S?!S.endOfTextblock(`forward`,e):w.parentOffset<w.parent.content.size)return!1;D=findCutAfter(w)}let O=D&&D.nodeAfter;return!O||!NodeSelection.isSelectable(O)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,D.pos)).scrollIntoView()),!0)};function findCutAfter(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){let S=e.node(t);if(e.index(t)+1<S.childCount)return e.doc.resolve(e.after(t+1));if(S.type.spec.isolating)break}return null}const joinUp$1=(e,t)=>{let S=e.selection,w=S instanceof NodeSelection,E;if(w){if(S.node.isTextblock||!canJoin(e.doc,S.from))return!1;E=S.from}else if(E=joinPoint(e.doc,S.from,-1),E==null)return!1;if(t){let S=e.tr.join(E);w&&S.setSelection(NodeSelection.create(S.doc,E-e.doc.resolve(E).nodeBefore.nodeSize)),t(S.scrollIntoView())}return!0},joinDown$1=(e,t)=>{let S=e.selection,w;if(S instanceof NodeSelection){if(S.node.isTextblock||!canJoin(e.doc,S.to))return!1;w=S.to}else if(w=joinPoint(e.doc,S.to,1),w==null)return!1;return t&&t(e.tr.join(w).scrollIntoView()),!0},lift$1=(e,t)=>{let{$from:S,$to:w}=e.selection,E=S.blockRange(w),D=E&&liftTarget(E);return D==null?!1:(t&&t(e.tr.lift(E,D).scrollIntoView()),!0)},newlineInCode$1=(e,t)=>{let{$head:S,$anchor:w}=e.selection;return!S.parent.type.spec.code||!S.sameParent(w)?!1:(t&&t(e.tr.insertText(`
|
|
164
|
+
`))}})}function canChangeType(e,t,S){let w=e.resolve(t),E=w.index();return w.parent.canReplaceWith(E,E+1,S)}function setNodeMarkup(e,t,S,w,E){let D=e.doc.nodeAt(t);if(!D)throw RangeError(`No node at given position`);S||=D.type;let O=S.create(w,null,E||D.marks);if(D.isLeaf)return e.replaceWith(t,t+D.nodeSize,O);if(!S.validContent(D.content))throw RangeError(`Invalid content for node type `+S.name);e.step(new ReplaceAroundStep(t,t+D.nodeSize,t+1,t+D.nodeSize-1,new Slice(Fragment.from(O),0,0),1,!0))}function canSplit(e,t,S=1,w){let E=e.resolve(t),D=E.depth-S,O=w&&w[w.length-1]||E.parent;if(D<0||E.parent.type.spec.isolating||!E.parent.canReplace(E.index(),E.parent.childCount)||!O.type.validContent(E.parent.content.cutByIndex(E.index(),E.parent.childCount)))return!1;for(let e=E.depth-1,t=S-2;e>D;e--,t--){let S=E.node(e),D=E.index(e);if(S.type.spec.isolating)return!1;let O=S.content.cutByIndex(D,S.childCount),k=w&&w[t+1];k&&(O=O.replaceChild(0,k.type.create(k.attrs)));let j=w&&w[t]||S;if(!S.canReplace(D+1,S.childCount)||!j.type.validContent(O))return!1}let k=E.indexAfter(D),j=w&&w[0];return E.node(D).canReplaceWith(k,k,j?j.type:E.node(D+1).type)}function split(e,t,S=1,w){let E=e.doc.resolve(t),D=Fragment.empty,O=Fragment.empty;for(let e=E.depth,t=E.depth-S,k=S-1;e>t;e--,k--){D=Fragment.from(E.node(e).copy(D));let t=w&&w[k];O=Fragment.from(t?t.type.create(t.attrs,O):E.node(e).copy(O))}e.step(new ReplaceStep(t,t,new Slice(D.append(O),S,S),!0))}function canJoin(e,t){let S=e.resolve(t),w=S.index();return joinable(S.nodeBefore,S.nodeAfter)&&S.parent.canReplace(w,w+1)}function canAppendWithSubstitutedLinebreaks(e,t){t.content.size||e.type.compatibleContent(t.type);let S=e.contentMatchAt(e.childCount),{linebreakReplacement:w}=e.type.schema;for(let E=0;E<t.childCount;E++){let D=t.child(E),O=D.type==w?e.type.schema.nodes.text:D.type;if(S=S.matchType(O),!S||!e.type.allowsMarks(D.marks))return!1}return S.validEnd}function joinable(e,t){return!!(e&&t&&!e.isLeaf&&canAppendWithSubstitutedLinebreaks(e,t))}function joinPoint(e,t,S=-1){let w=e.resolve(t);for(let e=w.depth;;e--){let E,D,O=w.index(e);if(e==w.depth?(E=w.nodeBefore,D=w.nodeAfter):S>0?(E=w.node(e+1),O++,D=w.node(e).maybeChild(O)):(E=w.node(e).maybeChild(O-1),D=w.node(e+1)),E&&!E.isTextblock&&joinable(E,D)&&w.node(e).canReplace(O,O+1))return t;if(e==0)break;t=S<0?w.before(e):w.after(e)}}function join$2(e,t,S){let w=null,{linebreakReplacement:E}=e.doc.type.schema,D=e.doc.resolve(t-S),O=D.node().type;if(E&&O.inlineContent){let e=O.whitespace==`pre`,t=!!O.contentMatch.matchType(E);e&&!t?w=!1:!e&&t&&(w=!0)}let k=e.steps.length;if(w===!1){let w=e.doc.resolve(t+S);replaceLinebreaks(e,w.node(),w.before(),k)}O.inlineContent&&clearIncompatible(e,t+S-1,O,D.node().contentMatchAt(D.index()),w==null);let j=e.mapping.slice(k),F=j.map(t-S);if(e.step(new ReplaceStep(F,j.map(t+S,-1),Slice.empty,!0)),w===!0){let t=e.doc.resolve(F);replaceNewlines$1(e,t.node(),t.before(),e.steps.length)}return e}function insertPoint(e,t,S){let w=e.resolve(t);if(w.parent.canReplaceWith(w.index(),w.index(),S))return t;if(w.parentOffset==0)for(let e=w.depth-1;e>=0;e--){let t=w.index(e);if(w.node(e).canReplaceWith(t,t,S))return w.before(e+1);if(t>0)return null}if(w.parentOffset==w.parent.content.size)for(let e=w.depth-1;e>=0;e--){let t=w.indexAfter(e);if(w.node(e).canReplaceWith(t,t,S))return w.after(e+1);if(t<w.node(e).childCount)return null}return null}function dropPoint(e,t,S){let w=e.resolve(t);if(!S.content.size)return t;let E=S.content;for(let e=0;e<S.openStart;e++)E=E.firstChild.content;for(let e=1;e<=(S.openStart==0&&S.size?2:1);e++)for(let t=w.depth;t>=0;t--){let S=t==w.depth?0:w.pos<=(w.start(t+1)+w.end(t+1))/2?-1:1,D=w.index(t)+(S>0?1:0),O=w.node(t),k=!1;if(e==1)k=O.canReplace(D,D,E);else{let e=O.contentMatchAt(D).findWrapping(E.firstChild.type);k=e&&O.canReplaceWith(D,D,e[0])}if(k)return S==0?w.pos:S<0?w.before(t+1):w.after(t+1)}return null}function replaceStep(e,t,S=t,w=Slice.empty){if(t==S&&!w.size)return null;let E=e.resolve(t),D=e.resolve(S);return fitsTrivially(E,D,w)?new ReplaceStep(t,S,w):new Fitter(E,D,w).fit()}function fitsTrivially(e,t,S){return!S.openStart&&!S.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),S.content)}var Fitter=class{constructor(e,t,S){this.$from=e,this.$to=t,this.unplaced=S,this.frontier=[],this.placed=Fragment.empty;for(let t=0;t<=e.depth;t++){let S=e.node(t);this.frontier.push({type:S.type,match:S.contentMatchAt(e.indexAfter(t))})}for(let t=e.depth;t>0;t--)this.placed=Fragment.from(e.node(t).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let e=this.findFittable();e?this.placeNodes(e):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,S=this.$from,w=this.close(e<0?this.$to:S.doc.resolve(e));if(!w)return null;let E=this.placed,D=S.depth,O=w.depth;for(;D&&O&&E.childCount==1;)E=E.firstChild.content,D--,O--;let k=new Slice(E,D,O);return e>-1?new ReplaceAroundStep(S.pos,e,this.$to.pos,this.$to.end(),k,t):k.size||S.pos!=this.$to.pos?new ReplaceStep(S.pos,w.pos,k):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,S=0,w=this.unplaced.openEnd;S<e;S++){let E=t.firstChild;if(t.childCount>1&&(w=0),E.type.spec.isolating&&w<=S){e=S;break}t=E.content}for(let t=1;t<=2;t++)for(let S=t==1?e:this.unplaced.openStart;S>=0;S--){let e,w=null;S?(w=contentAt(this.unplaced.content,S-1).firstChild,e=w.content):e=this.unplaced.content;let E=e.firstChild;for(let e=this.depth;e>=0;e--){let{type:D,match:O}=this.frontier[e],k,j=null;if(t==1&&(E?O.matchType(E.type)||(j=O.fillBefore(Fragment.from(E),!1)):w&&D.compatibleContent(w.type)))return{sliceDepth:S,frontierDepth:e,parent:w,inject:j};if(t==2&&E&&(k=O.findWrapping(E.type)))return{sliceDepth:S,frontierDepth:e,parent:w,wrap:k};if(w&&O.matchType(w.type))break}}}openMore(){let{content:e,openStart:t,openEnd:S}=this.unplaced,w=contentAt(e,t);return!w.childCount||w.firstChild.isLeaf?!1:(this.unplaced=new Slice(e,t+1,Math.max(S,w.size+t>=e.size-S?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:S}=this.unplaced,w=contentAt(e,t);if(w.childCount<=1&&t>0){let E=e.size-t<=t+w.size;this.unplaced=new Slice(dropFromFragment(e,t-1,1),t-1,E?t-1:S)}else this.unplaced=new Slice(dropFromFragment(e,t,1),t,S)}placeNodes({sliceDepth:e,frontierDepth:t,parent:S,inject:w,wrap:E}){for(;this.depth>t;)this.closeFrontierNode();if(E)for(let e=0;e<E.length;e++)this.openFrontierNode(E[e]);let D=this.unplaced,O=S?S.content:D.content,k=D.openStart-e,j=0,F=[],{match:L,type:B}=this.frontier[t];if(w){for(let e=0;e<w.childCount;e++)F.push(w.child(e));L=L.matchFragment(w)}let H=O.size+e-(D.content.size-D.openEnd);for(;j<O.childCount;){let e=O.child(j),t=L.matchType(e.type);if(!t)break;j++,(j>1||k==0||e.content.size)&&(L=t,F.push(closeNodeStart(e.mark(B.allowedMarks(e.marks)),j==1?k:0,j==O.childCount?H:-1)))}let q=j==O.childCount;q||(H=-1),this.placed=addToFragment(this.placed,t,Fragment.from(F)),this.frontier[t].match=L,q&&H<0&&S&&S.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let e=0,t=O;e<H;e++){let e=t.lastChild;this.frontier.push({type:e.type,match:e.contentMatchAt(e.childCount)}),t=e.content}this.unplaced=q?e==0?Slice.empty:new Slice(dropFromFragment(D.content,e-1,1),e-1,H<0?D.openEnd:e-1):new Slice(dropFromFragment(D.content,e,j),D.openStart,D.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],t;if(!e.type.isTextblock||!contentAfterFits(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(t=this.findCloseLevel(this.$to))&&t.depth==this.depth)return-1;let{depth:S}=this.$to,w=this.$to.after(S);for(;S>1&&w==this.$to.end(--S);)++w;return w}findCloseLevel(e){scan:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:S,type:w}=this.frontier[t],E=t<e.depth&&e.end(t+1)==e.pos+(e.depth-(t+1)),D=contentAfterFits(e,t,w,S,E);if(D){for(let S=t-1;S>=0;S--){let{match:t,type:w}=this.frontier[S],E=contentAfterFits(e,S,w,t,!0);if(!E||E.childCount)continue scan}return{depth:t,fit:D,move:E?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=addToFragment(this.placed,t.depth,t.fit)),e=t.move;for(let S=t.depth+1;S<=e.depth;S++){let t=e.node(S),w=t.type.contentMatch.fillBefore(t.content,!0,e.index(S));this.openFrontierNode(t.type,t.attrs,w)}return e}openFrontierNode(e,t=null,S){let w=this.frontier[this.depth];w.match=w.match.matchType(e),this.placed=addToFragment(this.placed,this.depth,Fragment.from(e.create(t,S))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let e=this.frontier.pop().match.fillBefore(Fragment.empty,!0);e.childCount&&(this.placed=addToFragment(this.placed,this.frontier.length,e))}};function dropFromFragment(e,t,S){return t==0?e.cutByIndex(S,e.childCount):e.replaceChild(0,e.firstChild.copy(dropFromFragment(e.firstChild.content,t-1,S)))}function addToFragment(e,t,S){return t==0?e.append(S):e.replaceChild(e.childCount-1,e.lastChild.copy(addToFragment(e.lastChild.content,t-1,S)))}function contentAt(e,t){for(let S=0;S<t;S++)e=e.firstChild.content;return e}function closeNodeStart(e,t,S){if(t<=0)return e;let w=e.content;return t>1&&(w=w.replaceChild(0,closeNodeStart(w.firstChild,t-1,w.childCount==1?S-1:0))),t>0&&(w=e.type.contentMatch.fillBefore(w).append(w),S<=0&&(w=w.append(e.type.contentMatch.matchFragment(w).fillBefore(Fragment.empty,!0)))),e.copy(w)}function contentAfterFits(e,t,S,w,E){let D=e.node(t),O=E?e.indexAfter(t):e.index(t);if(O==D.childCount&&!S.compatibleContent(D.type))return null;let k=w.fillBefore(D.content,!0,O);return k&&!invalidMarks(S,D.content,O)?k:null}function invalidMarks(e,t,S){for(let w=S;w<t.childCount;w++)if(!e.allowsMarks(t.child(w).marks))return!0;return!1}function definesContent(e){return e.spec.defining||e.spec.definingForContent}function replaceRange(e,t,S,w){if(!w.size)return e.deleteRange(t,S);let E=e.doc.resolve(t),D=e.doc.resolve(S);if(fitsTrivially(E,D,w))return e.step(new ReplaceStep(t,S,w));let O=coveredDepths(E,D);O[O.length-1]==0&&O.pop();let k=-(E.depth+1);O.unshift(k);for(let e=E.depth,t=E.pos-1;e>0;e--,t--){let S=E.node(e).type.spec;if(S.defining||S.definingAsContext||S.isolating)break;O.indexOf(e)>-1?k=e:E.before(e)==t&&O.splice(1,0,-e)}let j=O.indexOf(k),F=[],L=w.openStart;for(let e=w.content,t=0;;t++){let S=e.firstChild;if(F.push(S),t==w.openStart)break;e=S.content}for(let e=L-1;e>=0;e--){let t=F[e],S=definesContent(t.type);if(S&&!t.sameMarkup(E.node(Math.abs(k)-1)))L=e;else if(S||!t.type.isTextblock)break}for(let t=w.openStart;t>=0;t--){let k=(t+L+1)%(w.openStart+1),B=F[k];if(B)for(let t=0;t<O.length;t++){let F=O[(t+j)%O.length],L=!0;F<0&&(L=!1,F=-F);let H=E.node(F-1),q=E.index(F-1);if(H.canReplaceWith(q,q,B.type,B.marks))return e.replace(E.before(F),L?D.after(F):S,new Slice(closeFragment(w.content,0,w.openStart,k),k,w.openEnd))}}let B=e.steps.length;for(let k=O.length-1;k>=0&&(e.replace(t,S,w),!(e.steps.length>B));k--){let e=O[k];e<0||(t=E.before(e),S=D.after(e))}}function closeFragment(e,t,S,w,E){if(t<S){let E=e.firstChild;e=e.replaceChild(0,E.copy(closeFragment(E.content,t+1,S,w,E)))}if(t>w){let t=E.contentMatchAt(0),S=t.fillBefore(e).append(e);e=S.append(t.matchFragment(S).fillBefore(Fragment.empty,!0))}return e}function replaceRangeWith(e,t,S,w){if(!w.isInline&&t==S&&e.doc.resolve(t).parent.content.size){let E=insertPoint(e.doc,t,w.type);E!=null&&(t=S=E)}e.replaceRange(t,S,new Slice(Fragment.from(w),0,0))}function deleteRange$1(e,t,S){let w=e.doc.resolve(t),E=e.doc.resolve(S);if(w.parent.isTextblock&&E.parent.isTextblock&&w.start()!=E.start()&&w.parentOffset==0&&E.parentOffset==0){let D=w.sharedDepth(S),O=!1;for(let e=w.depth;e>D;e--)w.node(e).type.spec.isolating&&(O=!0);for(let e=E.depth;e>D;e--)E.node(e).type.spec.isolating&&(O=!0);if(!O){for(let e=w.depth;e>0&&t==w.start(e);e--)t=w.before(e);for(let e=E.depth;e>0&&S==E.start(e);e--)S=E.before(e);w=e.doc.resolve(t),E=e.doc.resolve(S)}}let D=coveredDepths(w,E);for(let t=0;t<D.length;t++){let S=D[t],O=t==D.length-1;if(O&&S==0||w.node(S).type.contentMatch.validEnd)return e.delete(w.start(S),E.end(S));if(S>0&&(O||w.node(S-1).canReplace(w.index(S-1),E.indexAfter(S-1))))return e.delete(w.before(S),E.after(S))}for(let D=1;D<=w.depth&&D<=E.depth;D++)if(t-w.start(D)==w.depth-D&&S>w.end(D)&&E.end(D)-S!=E.depth-D&&w.start(D-1)==E.start(D-1)&&w.node(D-1).canReplace(w.index(D-1),E.index(D-1)))return e.delete(w.before(D),S);e.delete(t,S)}function coveredDepths(e,t){let S=[],w=Math.min(e.depth,t.depth);for(let E=w;E>=0;E--){let w=e.start(E);if(w<e.pos-(e.depth-E)||t.end(E)>t.pos+(t.depth-E)||e.node(E).type.spec.isolating||t.node(E).type.spec.isolating)break;(w==t.start(E)||E==e.depth&&E==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&E&&t.start(E-1)==w-1)&&S.push(E)}return S}var AttrStep=class e extends Step{constructor(e,t,S){super(),this.pos=e,this.attr=t,this.value=S}apply(e){let t=e.nodeAt(this.pos);if(!t)return StepResult.fail(`No node at attribute step's position`);let S=Object.create(null);for(let e in t.attrs)S[e]=t.attrs[e];S[this.attr]=this.value;let w=t.type.create(S,null,t.marks);return StepResult.fromReplace(e,this.pos,this.pos+1,new Slice(Fragment.from(w),0,t.isLeaf?0:1))}getMap(){return StepMap.empty}invert(t){return new e(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let S=t.mapResult(this.pos,1);return S.deletedAfter?null:new e(S.pos,this.attr,this.value)}toJSON(){return{stepType:`attr`,pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,S){if(typeof S.pos!=`number`||typeof S.attr!=`string`)throw RangeError(`Invalid input for AttrStep.fromJSON`);return new e(S.pos,S.attr,S.value)}};Step.jsonID(`attr`,AttrStep);var DocAttrStep=class e extends Step{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let S in e.attrs)t[S]=e.attrs[S];t[this.attr]=this.value;let S=e.type.create(t,e.content,e.marks);return StepResult.ok(S)}getMap(){return StepMap.empty}invert(t){return new e(this.attr,t.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:`docAttr`,attr:this.attr,value:this.value}}static fromJSON(t,S){if(typeof S.attr!=`string`)throw RangeError(`Invalid input for DocAttrStep.fromJSON`);return new e(S.attr,S.value)}};Step.jsonID(`docAttr`,DocAttrStep);let TransformError=class extends Error{};TransformError=function e(t){let S=Error.call(this,t);return S.__proto__=e.prototype,S},TransformError.prototype=Object.create(Error.prototype),TransformError.prototype.constructor=TransformError,TransformError.prototype.name=`TransformError`;var Transform$3=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Mapping}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new TransformError(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let S=0;S<this.mapping.maps.length;S++){let w=this.mapping.maps[S];S&&(e=w.map(e,1),t=w.map(t,-1)),w.forEach((S,w,E,D)=>{e=Math.min(e,E),t=Math.max(t,D)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,S=Slice.empty){let w=replaceStep(this.doc,e,t,S);return w&&this.step(w),this}replaceWith(e,t,S){return this.replace(e,t,new Slice(Fragment.from(S),0,0))}delete(e,t){return this.replace(e,t,Slice.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,S){return replaceRange(this,e,t,S),this}replaceRangeWith(e,t,S){return replaceRangeWith(this,e,t,S),this}deleteRange(e,t){return deleteRange$1(this,e,t),this}lift(e,t){return lift$2(this,e,t),this}join(e,t=1){return join$2(this,e,t),this}wrap(e,t){return wrap$1(this,e,t),this}setBlockType(e,t=e,S,w=null){return setBlockType$1(this,e,t,S,w),this}setNodeMarkup(e,t,S=null,w){return setNodeMarkup(this,e,t,S,w),this}setNodeAttribute(e,t,S){return this.step(new AttrStep(e,t,S)),this}setDocAttribute(e,t){return this.step(new DocAttrStep(e,t)),this}addNodeMark(e,t){return this.step(new AddNodeMarkStep(e,t)),this}removeNodeMark(e,t){let S=this.doc.nodeAt(e);if(!S)throw RangeError(`No node at position `+e);if(t instanceof Mark$1)t.isInSet(S.marks)&&this.step(new RemoveNodeMarkStep(e,t));else{let w=S.marks,E,D=[];for(;E=t.isInSet(w);)D.push(new RemoveNodeMarkStep(e,E)),w=E.removeFromSet(w);for(let e=D.length-1;e>=0;e--)this.step(D[e])}return this}split(e,t=1,S){return split(this,e,t,S),this}addMark(e,t,S){return addMark(this,e,t,S),this}removeMark(e,t,S){return removeMark(this,e,t,S),this}clearIncompatible(e,t,S){return clearIncompatible(this,e,t,S),this}};const classesById=Object.create(null);var Selection$1=class{constructor(e,t,S){this.$anchor=e,this.$head=t,this.ranges=S||[new SelectionRange(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t<e.length;t++)if(e[t].$from.pos!=e[t].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,t=Slice.empty){let S=t.content.lastChild,w=null;for(let e=0;e<t.openEnd;e++)w=S,S=S.lastChild;let E=e.steps.length,D=this.ranges;for(let O=0;O<D.length;O++){let{$from:k,$to:j}=D[O],F=e.mapping.slice(E);e.replaceRange(F.map(k.pos),F.map(j.pos),O?Slice.empty:t),O==0&&selectionToInsertionEnd$1(e,E,(S?S.isInline:w&&w.isTextblock)?-1:1)}}replaceWith(e,t){let S=e.steps.length,w=this.ranges;for(let E=0;E<w.length;E++){let{$from:D,$to:O}=w[E],k=e.mapping.slice(S),j=k.map(D.pos),F=k.map(O.pos);E?e.deleteRange(j,F):(e.replaceRangeWith(j,F,t),selectionToInsertionEnd$1(e,S,t.isInline?-1:1))}}static findFrom(e,t,S=!1){let w=e.parent.inlineContent?new TextSelection(e):findSelectionIn(e.node(0),e.parent,e.pos,e.index(),t,S);if(w)return w;for(let w=e.depth-1;w>=0;w--){let E=t<0?findSelectionIn(e.node(0),e.node(w),e.before(w+1),e.index(w),t,S):findSelectionIn(e.node(0),e.node(w),e.after(w+1),e.index(w)+1,t,S);if(E)return E}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new AllSelection(e.node(0))}static atStart(e){return findSelectionIn(e,e,0,0,1)||new AllSelection(e)}static atEnd(e){return findSelectionIn(e,e,e.content.size,e.childCount,-1)||new AllSelection(e)}static fromJSON(e,t){if(!t||!t.type)throw RangeError(`Invalid input for Selection.fromJSON`);let S=classesById[t.type];if(!S)throw RangeError(`No selection type ${t.type} defined`);return S.fromJSON(e,t)}static jsonID(e,t){if(e in classesById)throw RangeError(`Duplicate use of selection JSON ID `+e);return classesById[e]=t,t.prototype.jsonID=e,t}getBookmark(){return TextSelection.between(this.$anchor,this.$head).getBookmark()}};Selection$1.prototype.visible=!0;var SelectionRange=class{constructor(e,t){this.$from=e,this.$to=t}};let warnedAboutTextSelection=!1;function checkTextSelection(e){!warnedAboutTextSelection&&!e.parent.inlineContent&&(warnedAboutTextSelection=!0,console.warn(`TextSelection endpoint not pointing into a node with inline content (`+e.parent.type.name+`)`))}var TextSelection=class e extends Selection$1{constructor(e,t=e){checkTextSelection(e),checkTextSelection(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,S){let w=t.resolve(S.map(this.head));if(!w.parent.inlineContent)return Selection$1.near(w);let E=t.resolve(S.map(this.anchor));return new e(E.parent.inlineContent?E:w,w)}replace(e,t=Slice.empty){if(super.replace(e,t),t==Slice.empty){let t=this.$from.marksAcross(this.$to);t&&e.ensureMarks(t)}}eq(t){return t instanceof e&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new TextBookmark(this.anchor,this.head)}toJSON(){return{type:`text`,anchor:this.anchor,head:this.head}}static fromJSON(t,S){if(typeof S.anchor!=`number`||typeof S.head!=`number`)throw RangeError(`Invalid input for TextSelection.fromJSON`);return new e(t.resolve(S.anchor),t.resolve(S.head))}static create(e,t,S=t){let w=e.resolve(t);return new this(w,S==t?w:e.resolve(S))}static between(t,S,w){let E=t.pos-S.pos;if((!w||E)&&(w=E>=0?1:-1),!S.parent.inlineContent){let e=Selection$1.findFrom(S,w,!0)||Selection$1.findFrom(S,-w,!0);if(e)S=e.$head;else return Selection$1.near(S,w)}return t.parent.inlineContent||(E==0?t=S:(t=(Selection$1.findFrom(t,-w,!0)||Selection$1.findFrom(t,w,!0)).$anchor,t.pos<S.pos!=E<0&&(t=S))),new e(t,S)}};Selection$1.jsonID(`text`,TextSelection);var TextBookmark=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){return TextSelection.between(e.resolve(this.anchor),e.resolve(this.head))}},NodeSelection=class e extends Selection$1{constructor(e){let t=e.nodeAfter,S=e.node(0).resolve(e.pos+t.nodeSize);super(e,S),this.node=t}map(t,S){let{deleted:w,pos:E}=S.mapResult(this.anchor),D=t.resolve(E);return w?Selection$1.near(D):new e(D)}content(){return new Slice(Fragment.from(this.node),0,0)}eq(t){return t instanceof e&&t.anchor==this.anchor}toJSON(){return{type:`node`,anchor:this.anchor}}getBookmark(){return new NodeBookmark(this.anchor)}static fromJSON(t,S){if(typeof S.anchor!=`number`)throw RangeError(`Invalid input for NodeSelection.fromJSON`);return new e(t.resolve(S.anchor))}static create(t,S){return new e(t.resolve(S))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};NodeSelection.prototype.visible=!1,Selection$1.jsonID(`node`,NodeSelection);var NodeBookmark=class e{constructor(e){this.anchor=e}map(t){let{deleted:S,pos:w}=t.mapResult(this.anchor);return S?new TextBookmark(w,w):new e(w)}resolve(e){let t=e.resolve(this.anchor),S=t.nodeAfter;return S&&NodeSelection.isSelectable(S)?new NodeSelection(t):Selection$1.near(t)}},AllSelection=class e extends Selection$1{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=Slice.empty){if(t==Slice.empty){e.delete(0,e.doc.content.size);let t=Selection$1.atStart(e.doc);t.eq(e.selection)||e.setSelection(t)}else super.replace(e,t)}toJSON(){return{type:`all`}}static fromJSON(t){return new e(t)}map(t){return new e(t)}eq(t){return t instanceof e}getBookmark(){return AllBookmark}};Selection$1.jsonID(`all`,AllSelection);const AllBookmark={map(){return this},resolve(e){return new AllSelection(e)}};function findSelectionIn(e,t,S,w,E,D=!1){if(t.inlineContent)return TextSelection.create(e,S);for(let O=w-(E>0?0:1);E>0?O<t.childCount:O>=0;O+=E){let w=t.child(O);if(!w.isAtom){let t=findSelectionIn(e,w,S+E,E<0?w.childCount:0,E,D);if(t)return t}else if(!D&&NodeSelection.isSelectable(w))return NodeSelection.create(e,S-(E<0?w.nodeSize:0));S+=w.nodeSize*E}return null}function selectionToInsertionEnd$1(e,t,S){let w=e.steps.length-1;if(w<t)return;let E=e.steps[w];if(!(E instanceof ReplaceStep||E instanceof ReplaceAroundStep))return;let D=e.mapping.maps[w],O;D.forEach((e,t,S,w)=>{O??=w}),e.setSelection(Selection$1.near(e.doc.resolve(O),S))}function bind(e,t){return!t||!e?e:e.bind(t)}var FieldDesc=class{constructor(e,t,S){this.name=e,this.init=bind(t.init,S),this.apply=bind(t.apply,S)}};const baseFields=[new FieldDesc(`doc`,{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new FieldDesc(`selection`,{init(e,t){return e.selection||Selection$1.atStart(t.doc)},apply(e){return e.selection}}),new FieldDesc(`storedMarks`,{init(e){return e.storedMarks||null},apply(e,t,S,w){return w.selection.$cursor?e.storedMarks:null}}),new FieldDesc(`scrollToSelection`,{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}})];function bindProps(e,t,S){for(let w in e){let E=e[w];E instanceof Function?E=E.bind(t):w==`handleDOMEvents`&&(E=bindProps(E,t,{})),S[w]=E}return S}var Plugin=class{constructor(e){this.spec=e,this.props={},e.props&&bindProps(e.props,this,this.props),this.key=e.key?e.key.key:createKey(`plugin`)}getState(e){return e[this.key]}};const keys$2=Object.create(null);function createKey(e){return e in keys$2?e+`$`+ ++keys$2[e]:(keys$2[e]=0,e+`$`)}var PluginKey=class{constructor(e=`key`){this.key=createKey(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};const deleteSelection$1=(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function atBlockStart(e,t){let{$cursor:S}=e.selection;return!S||(t?!t.endOfTextblock(`backward`,e):S.parentOffset>0)?null:S}const joinBackward$1=(e,t,S)=>{let w=atBlockStart(e,S);if(!w)return!1;let E=findCutBefore(w);if(!E){let S=w.blockRange(),E=S&&liftTarget(S);return E==null?!1:(t&&t(e.tr.lift(S,E).scrollIntoView()),!0)}let D=E.nodeBefore;if(deleteBarrier(e,E,t,-1))return!0;if(w.parent.content.size==0&&(textblockAt(D,`end`)||NodeSelection.isSelectable(D)))for(let S=w.depth;;S--){let O=replaceStep(e.doc,w.before(S),w.after(S),Slice.empty);if(O&&O.slice.size<O.to-O.from){if(t){let S=e.tr.step(O);S.setSelection(textblockAt(D,`end`)?Selection$1.findFrom(S.doc.resolve(S.mapping.map(E.pos,-1)),-1):NodeSelection.create(S.doc,E.pos-D.nodeSize)),t(S.scrollIntoView())}return!0}if(S==1||w.node(S-1).childCount>1)break}return D.isAtom&&E.depth==w.depth-1?(t&&t(e.tr.delete(E.pos-D.nodeSize,E.pos).scrollIntoView()),!0):!1},joinTextblockBackward$1=(e,t,S)=>{let w=atBlockStart(e,S);if(!w)return!1;let E=findCutBefore(w);return E?joinTextblocksAround(e,E,t):!1},joinTextblockForward$1=(e,t,S)=>{let w=atBlockEnd(e,S);if(!w)return!1;let E=findCutAfter(w);return E?joinTextblocksAround(e,E,t):!1};function joinTextblocksAround(e,t,S){let w=t.nodeBefore,E=t.pos-1;for(;!w.isTextblock;E--){if(w.type.spec.isolating)return!1;let e=w.lastChild;if(!e)return!1;w=e}let D=t.nodeAfter,O=t.pos+1;for(;!D.isTextblock;O++){if(D.type.spec.isolating)return!1;let e=D.firstChild;if(!e)return!1;D=e}let k=replaceStep(e.doc,E,O,Slice.empty);if(!k||k.from!=E||k instanceof ReplaceStep&&k.slice.size>=O-E)return!1;if(S){let t=e.tr.step(k);t.setSelection(TextSelection.create(t.doc,E)),S(t.scrollIntoView())}return!0}function textblockAt(e,t,S=!1){for(let w=e;w;w=t==`start`?w.firstChild:w.lastChild){if(w.isTextblock)return!0;if(S&&w.childCount!=1)return!1}return!1}const selectNodeBackward$1=(e,t,S)=>{let{$head:w,empty:E}=e.selection,D=w;if(!E)return!1;if(w.parent.isTextblock){if(S?!S.endOfTextblock(`backward`,e):w.parentOffset>0)return!1;D=findCutBefore(w)}let O=D&&D.nodeBefore;return!O||!NodeSelection.isSelectable(O)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,D.pos-O.nodeSize)).scrollIntoView()),!0)};function findCutBefore(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function atBlockEnd(e,t){let{$cursor:S}=e.selection;return!S||(t?!t.endOfTextblock(`forward`,e):S.parentOffset<S.parent.content.size)?null:S}const joinForward$1=(e,t,S)=>{let w=atBlockEnd(e,S);if(!w)return!1;let E=findCutAfter(w);if(!E)return!1;let D=E.nodeAfter;if(deleteBarrier(e,E,t,1))return!0;if(w.parent.content.size==0&&(textblockAt(D,`start`)||NodeSelection.isSelectable(D))){let S=replaceStep(e.doc,w.before(),w.after(),Slice.empty);if(S&&S.slice.size<S.to-S.from){if(t){let w=e.tr.step(S);w.setSelection(textblockAt(D,`start`)?Selection$1.findFrom(w.doc.resolve(w.mapping.map(E.pos)),1):NodeSelection.create(w.doc,w.mapping.map(E.pos))),t(w.scrollIntoView())}return!0}}return D.isAtom&&E.depth==w.depth-1?(t&&t(e.tr.delete(E.pos,E.pos+D.nodeSize).scrollIntoView()),!0):!1},selectNodeForward$1=(e,t,S)=>{let{$head:w,empty:E}=e.selection,D=w;if(!E)return!1;if(w.parent.isTextblock){if(S?!S.endOfTextblock(`forward`,e):w.parentOffset<w.parent.content.size)return!1;D=findCutAfter(w)}let O=D&&D.nodeAfter;return!O||!NodeSelection.isSelectable(O)?!1:(t&&t(e.tr.setSelection(NodeSelection.create(e.doc,D.pos)).scrollIntoView()),!0)};function findCutAfter(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){let S=e.node(t);if(e.index(t)+1<S.childCount)return e.doc.resolve(e.after(t+1));if(S.type.spec.isolating)break}return null}const joinUp$1=(e,t)=>{let S=e.selection,w=S instanceof NodeSelection,E;if(w){if(S.node.isTextblock||!canJoin(e.doc,S.from))return!1;E=S.from}else if(E=joinPoint(e.doc,S.from,-1),E==null)return!1;if(t){let S=e.tr.join(E);w&&S.setSelection(NodeSelection.create(S.doc,E-e.doc.resolve(E).nodeBefore.nodeSize)),t(S.scrollIntoView())}return!0},joinDown$1=(e,t)=>{let S=e.selection,w;if(S instanceof NodeSelection){if(S.node.isTextblock||!canJoin(e.doc,S.to))return!1;w=S.to}else if(w=joinPoint(e.doc,S.to,1),w==null)return!1;return t&&t(e.tr.join(w).scrollIntoView()),!0},lift$1=(e,t)=>{let{$from:S,$to:w}=e.selection,E=S.blockRange(w),D=E&&liftTarget(E);return D==null?!1:(t&&t(e.tr.lift(E,D).scrollIntoView()),!0)},newlineInCode$1=(e,t)=>{let{$head:S,$anchor:w}=e.selection;return!S.parent.type.spec.code||!S.sameParent(w)?!1:(t&&t(e.tr.insertText(`
|
|
165
165
|
`).scrollIntoView()),!0)};function defaultBlockAt$1(e){for(let t=0;t<e.edgeCount;t++){let{type:S}=e.edge(t);if(S.isTextblock&&!S.hasRequiredAttrs())return S}return null}const exitCode$1=(e,t)=>{let{$head:S,$anchor:w}=e.selection;if(!S.parent.type.spec.code||!S.sameParent(w))return!1;let E=S.node(-1),D=S.indexAfter(-1),O=defaultBlockAt$1(E.contentMatchAt(D));if(!O||!E.canReplaceWith(D,D,O))return!1;if(t){let w=S.after(),E=e.tr.replaceWith(w,w,O.createAndFill());E.setSelection(Selection$1.near(E.doc.resolve(w),1)),t(E.scrollIntoView())}return!0},createParagraphNear$1=(e,t)=>{let S=e.selection,{$from:w,$to:E}=S;if(S instanceof AllSelection||w.parent.inlineContent||E.parent.inlineContent)return!1;let D=defaultBlockAt$1(E.parent.contentMatchAt(E.indexAfter()));if(!D||!D.isTextblock)return!1;if(t){let S=(!w.parentOffset&&E.index()<E.parent.childCount?w:E).pos,O=e.tr.insert(S,D.createAndFill());O.setSelection(TextSelection.create(O.doc,S+1)),t(O.scrollIntoView())}return!0},liftEmptyBlock$1=(e,t)=>{let{$cursor:S}=e.selection;if(!S||S.parent.content.size)return!1;if(S.depth>1&&S.after()!=S.end(-1)){let w=S.before();if(canSplit(e.doc,w))return t&&t(e.tr.split(w).scrollIntoView()),!0}let w=S.blockRange(),E=w&&liftTarget(w);return E==null?!1:(t&&t(e.tr.lift(w,E).scrollIntoView()),!0)};function splitBlockAs(e){return(t,S)=>{let{$from:w,$to:E}=t.selection;if(t.selection instanceof NodeSelection&&t.selection.node.isBlock)return!w.parentOffset||!canSplit(t.doc,w.pos)?!1:(S&&S(t.tr.split(w.pos).scrollIntoView()),!0);if(!w.depth)return!1;let D=[],O,k,j=!1,F=!1;for(let t=w.depth;;t--)if(w.node(t).isBlock){j=w.end(t)==w.pos+(w.depth-t),F=w.start(t)==w.pos-(w.depth-t),k=defaultBlockAt$1(w.node(t-1).contentMatchAt(w.indexAfter(t-1)));let S=e&&e(E.parent,j,w);D.unshift(S||(j&&k?{type:k}:null)),O=t;break}else{if(t==1)return!1;D.unshift(null)}let L=t.tr;(t.selection instanceof TextSelection||t.selection instanceof AllSelection)&&L.deleteSelection();let B=L.mapping.map(w.pos),H=canSplit(L.doc,B,D.length,D);if(H||=(D[0]=k?{type:k}:null,canSplit(L.doc,B,D.length,D)),!H)return!1;if(L.split(B,D.length,D),!j&&F&&w.node(O).type!=k){let e=L.mapping.map(w.before(O)),t=L.doc.resolve(e);k&&w.node(O-1).canReplaceWith(t.index(),t.index()+1,k)&&L.setNodeMarkup(L.mapping.map(w.before(O)),k)}return S&&S(L.scrollIntoView()),!0}}const splitBlock$1=splitBlockAs(),selectParentNode$1=(e,t)=>{let{$from:S,to:w}=e.selection,E,D=S.sharedDepth(w);return D==0?!1:(E=S.before(D),t&&t(e.tr.setSelection(NodeSelection.create(e.doc,E))),!0)},selectAll$1=(e,t)=>(t&&t(e.tr.setSelection(new AllSelection(e.doc))),!0);function joinMaybeClear(e,t,S){let w=t.nodeBefore,E=t.nodeAfter,D=t.index();return!w||!E||!w.type.compatibleContent(E.type)?!1:!w.content.size&&t.parent.canReplace(D-1,D)?(S&&S(e.tr.delete(t.pos-w.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(D,D+1)||!(E.isTextblock||canJoin(e.doc,t.pos))?!1:(S&&S(e.tr.join(t.pos).scrollIntoView()),!0)}function deleteBarrier(e,t,S,w){let E=t.nodeBefore,D=t.nodeAfter,O,k,j=E.type.spec.isolating||D.type.spec.isolating;if(!j&&joinMaybeClear(e,t,S))return!0;let F=!j&&t.parent.canReplace(t.index(),t.index()+1);if(F&&(O=(k=E.contentMatchAt(E.childCount)).findWrapping(D.type))&&k.matchType(O[0]||D.type).validEnd){if(S){let w=t.pos+D.nodeSize,k=Fragment.empty;for(let e=O.length-1;e>=0;e--)k=Fragment.from(O[e].create(null,k));k=Fragment.from(E.copy(k));let j=e.tr.step(new ReplaceAroundStep(t.pos-1,w,t.pos,w,new Slice(k,1,0),O.length,!0)),F=j.doc.resolve(w+2*O.length);F.nodeAfter&&F.nodeAfter.type==E.type&&canJoin(j.doc,F.pos)&&j.join(F.pos),S(j.scrollIntoView())}return!0}let L=D.type.spec.isolating||w>0&&j?null:Selection$1.findFrom(t,1),B=L&&L.$from.blockRange(L.$to),H=B&&liftTarget(B);if(H!=null&&H>=t.depth)return S&&S(e.tr.lift(B,H).scrollIntoView()),!0;if(F&&textblockAt(D,`start`,!0)&&textblockAt(E,`end`)){let w=E,O=[];for(;O.push(w),!w.isTextblock;)w=w.lastChild;let k=D,j=1;for(;!k.isTextblock;k=k.firstChild)j++;if(w.canReplace(w.childCount,w.childCount,k.content)){if(S){let w=Fragment.empty;for(let e=O.length-1;e>=0;e--)w=Fragment.from(O[e].copy(w));S(e.tr.step(new ReplaceAroundStep(t.pos-O.length,t.pos+D.nodeSize,t.pos+j,t.pos+D.nodeSize-j,new Slice(w,O.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function selectTextblockSide(e){return function(t,S){let w=t.selection,E=e<0?w.$from:w.$to,D=E.depth;for(;E.node(D).isInline;){if(!D)return!1;D--}return E.node(D).isTextblock?(S&&S(t.tr.setSelection(TextSelection.create(t.doc,e<0?E.start(D):E.end(D)))),!0):!1}}const selectTextblockStart$1=selectTextblockSide(-1),selectTextblockEnd$1=selectTextblockSide(1);function wrapIn$1(e,t=null){return function(S,w){let{$from:E,$to:D}=S.selection,O=E.blockRange(D),k=O&&findWrapping(O,e,t);return k?(w&&w(S.tr.wrap(O,k).scrollIntoView()),!0):!1}}function setBlockType(e,t=null){return function(S,w){let E=!1;for(let w=0;w<S.selection.ranges.length&&!E;w++){let{$from:{pos:D},$to:{pos:O}}=S.selection.ranges[w];S.doc.nodesBetween(D,O,(w,D)=>{if(E)return!1;if(!(!w.isTextblock||w.hasMarkup(e,t)))if(w.type==e)E=!0;else{let t=S.doc.resolve(D),w=t.index();E=t.parent.canReplaceWith(w,w+1,e)}})}if(!E)return!1;if(w){let E=S.tr;for(let w=0;w<S.selection.ranges.length;w++){let{$from:{pos:D},$to:{pos:O}}=S.selection.ranges[w];E.setBlockType(D,O,e,t)}w(E.scrollIntoView())}return!0}}function chainCommands(...e){return function(t,S,w){for(let E=0;E<e.length;E++)if(e[E](t,S,w))return!0;return!1}}let backspace=chainCommands(deleteSelection$1,joinBackward$1,selectNodeBackward$1),del=chainCommands(deleteSelection$1,joinForward$1,selectNodeForward$1);const pcBaseKeymap={Enter:chainCommands(newlineInCode$1,createParagraphNear$1,liftEmptyBlock$1,splitBlock$1),"Mod-Enter":exitCode$1,Backspace:backspace,"Mod-Backspace":backspace,"Shift-Backspace":backspace,Delete:del,"Mod-Delete":del,"Mod-a":selectAll$1},macBaseKeymap={"Ctrl-h":pcBaseKeymap.Backspace,"Alt-Backspace":pcBaseKeymap[`Mod-Backspace`],"Ctrl-d":pcBaseKeymap.Delete,"Ctrl-Alt-Backspace":pcBaseKeymap[`Mod-Delete`],"Alt-Delete":pcBaseKeymap[`Mod-Delete`],"Alt-d":pcBaseKeymap[`Mod-Delete`],"Ctrl-a":selectTextblockStart$1,"Ctrl-e":selectTextblockEnd$1};for(let e in pcBaseKeymap)macBaseKeymap[e]=pcBaseKeymap[e];const baseKeymap=(typeof navigator<`u`?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<`u`&&os.platform&&os.platform()==`darwin`)?macBaseKeymap:pcBaseKeymap;function wrapInList$1(e,t=null){return function(S,w){let{$from:E,$to:D}=S.selection,O=E.blockRange(D);if(!O)return!1;let k=w?S.tr:null;return wrapRangeInList(k,O,e,t)?(w&&w(k.scrollIntoView()),!0):!1}}function wrapRangeInList(e,t,S,w=null){let E=!1,D=t,O=t.$from.doc;if(t.depth>=2&&t.$from.node(t.depth-1).type.compatibleContent(S)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let e=O.resolve(t.start-2);D=new NodeRange(e,e,t.depth),t.endIndex<t.parent.childCount&&(t=new NodeRange(t.$from,O.resolve(t.$to.end(t.depth)),t.depth)),E=!0}let k=findWrapping(D,S,w,t);return k?(e&&doWrapInList(e,t,k,E,S),!0):!1}function doWrapInList(e,t,S,w,E){let D=Fragment.empty;for(let e=S.length-1;e>=0;e--)D=Fragment.from(S[e].type.create(S[e].attrs,D));e.step(new ReplaceAroundStep(t.start-(w?2:0),t.end,t.start,t.end,new Slice(D,0,0),S.length,!0));let O=0;for(let e=0;e<S.length;e++)S[e].type==E&&(O=e+1);let k=S.length-O,j=t.start+S.length-(w?2:0),F=t.parent;for(let S=t.startIndex,w=t.endIndex,E=!0;S<w;S++,E=!1)!E&&canSplit(e.doc,j,k)&&(e.split(j,k),j+=2*k),j+=F.child(S).nodeSize;return e}function liftListItem$1(e){return function(t,S){let{$from:w,$to:E}=t.selection,D=w.blockRange(E,t=>t.childCount>0&&t.firstChild.type==e);return D?S?w.node(D.depth-1).type==e?liftToOuterList(t,S,e,D):liftOutOfList(t,S,D):!0:!1}}function liftToOuterList(e,t,S,w){let E=e.tr,D=w.end,O=w.$to.end(w.depth);D<O&&(E.step(new ReplaceAroundStep(D-1,O,D,O,new Slice(Fragment.from(S.create(null,w.parent.copy())),1,0),1,!0)),w=new NodeRange(E.doc.resolve(w.$from.pos),E.doc.resolve(O),w.depth));let k=liftTarget(w);if(k==null)return!1;E.lift(w,k);let j=E.doc.resolve(E.mapping.map(D,-1)-1);return canJoin(E.doc,j.pos)&&j.nodeBefore.type==j.nodeAfter.type&&E.join(j.pos),t(E.scrollIntoView()),!0}function liftOutOfList(e,t,S){let w=e.tr,E=S.parent;for(let e=S.end,t=S.endIndex-1,D=S.startIndex;t>D;t--)e-=E.child(t).nodeSize,w.delete(e-1,e+1);let D=w.doc.resolve(S.start),O=D.nodeAfter;if(w.mapping.map(S.end)!=S.start+D.nodeAfter.nodeSize)return!1;let k=S.startIndex==0,j=S.endIndex==E.childCount,F=D.node(-1),L=D.index(-1);if(!F.canReplace(L+(k?0:1),L+1,O.content.append(j?Fragment.empty:Fragment.from(E))))return!1;let B=D.pos,H=B+O.nodeSize;return w.step(new ReplaceAroundStep(B-(k?1:0),H+(j?1:0),B+1,H-1,new Slice((k?Fragment.empty:Fragment.from(E.copy(Fragment.empty))).append(j?Fragment.empty:Fragment.from(E.copy(Fragment.empty))),k?0:1,j?0:1),k?0:1)),t(w.scrollIntoView()),!0}function sinkListItem$1(e){return function(t,S){let{$from:w,$to:E}=t.selection,D=w.blockRange(E,t=>t.childCount>0&&t.firstChild.type==e);if(!D)return!1;let O=D.startIndex;if(O==0)return!1;let k=D.parent,j=k.child(O-1);if(j.type!=e)return!1;if(S){let w=j.lastChild&&j.lastChild.type==k.type,E=Fragment.from(w?e.create():null),O=new Slice(Fragment.from(e.create(null,Fragment.from(k.type.create(null,E)))),w?3:1,0),F=D.start,L=D.end;S(t.tr.step(new ReplaceAroundStep(F-(w?3:1),L,F,L,O,1,!0)).scrollIntoView())}return!0}}const domIndex=function(e){for(var t=0;;t++)if(e=e.previousSibling,!e)return t},parentNode=function(e){let t=e.assignedSlot||e.parentNode;return t&&t.nodeType==11?t.host:t};let reusedRange=null;const textRange=function(e,t,S){let w=reusedRange||=document.createRange();return w.setEnd(e,S??e.nodeValue.length),w.setStart(e,t||0),w},clearReusedRange=function(){reusedRange=null},isEquivalentPosition=function(e,t,S,w){return S&&(scanFor(e,t,S,w,-1)||scanFor(e,t,S,w,1))},atomElements=/^(img|br|input|textarea|hr)$/i;function scanFor(e,t,S,w,E){for(var D;;){if(e==S&&t==w)return!0;if(t==(E<0?0:nodeSize(e))){let S=e.parentNode;if(!S||S.nodeType!=1||hasBlockDesc(e)||atomElements.test(e.nodeName)||e.contentEditable==`false`)return!1;t=domIndex(e)+(E<0?0:1),e=S}else if(e.nodeType==1){let S=e.childNodes[t+(E<0?-1:0)];if(S.nodeType==1&&S.contentEditable==`false`)if(S.pmViewDesc?.ignoreForSelection)t+=E;else return!1;else e=S,t=E<0?nodeSize(e):0}else return!1}}function nodeSize(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function textNodeBefore$1(e,t){for(;;){if(e.nodeType==3&&t)return e;if(e.nodeType==1&&t>0){if(e.contentEditable==`false`)return null;e=e.childNodes[t-1],t=nodeSize(e)}else if(e.parentNode&&!hasBlockDesc(e))t=domIndex(e),e=e.parentNode;else return null}}function textNodeAfter$1(e,t){for(;;){if(e.nodeType==3&&t<e.nodeValue.length)return e;if(e.nodeType==1&&t<e.childNodes.length){if(e.contentEditable==`false`)return null;e=e.childNodes[t],t=0}else if(e.parentNode&&!hasBlockDesc(e))t=domIndex(e)+1,e=e.parentNode;else return null}}function isOnEdge(e,t,S){for(let w=t==0,E=t==nodeSize(e);w||E;){if(e==S)return!0;let t=domIndex(e);if(e=e.parentNode,!e)return!1;w&&=t==0,E&&=t==nodeSize(e)}}function hasBlockDesc(e){let t;for(let S=e;S&&!(t=S.pmViewDesc);S=S.parentNode);return t&&t.node&&t.node.isBlock&&(t.dom==e||t.contentDOM==e)}const selectionCollapsed=function(e){return e.focusNode&&isEquivalentPosition(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)};function keyEvent(e,t){let S=document.createEvent(`Event`);return S.initEvent(`keydown`,!0,!0),S.keyCode=e,S.key=S.code=t,S}function deepActiveElement(e){let t=e.activeElement;for(;t&&t.shadowRoot;)t=t.shadowRoot.activeElement;return t}function caretFromPoint(e,t,S){if(e.caretPositionFromPoint)try{let w=e.caretPositionFromPoint(t,S);if(w)return{node:w.offsetNode,offset:Math.min(nodeSize(w.offsetNode),w.offset)}}catch{}if(e.caretRangeFromPoint){let w=e.caretRangeFromPoint(t,S);if(w)return{node:w.startContainer,offset:Math.min(nodeSize(w.startContainer),w.startOffset)}}}const nav=typeof navigator<`u`?navigator:null,doc=typeof document<`u`?document:null,agent=nav&&nav.userAgent||``,ie_edge=/Edge\/(\d+)/.exec(agent),ie_upto10=/MSIE \d/.exec(agent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent),ie$2=!!(ie_upto10||ie_11up||ie_edge),ie_version=ie_upto10?document.documentMode:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko=!ie$2&&/gecko\/(\d+)/i.test(agent);gecko&&+(/Firefox\/(\d+)/.exec(agent)||[0,0])[1];const _chrome=!ie$2&&/Chrome\/(\d+)/.exec(agent),chrome=!!_chrome,chrome_version=_chrome?+_chrome[1]:0,safari=!ie$2&&!!nav&&/Apple Computer/.test(nav.vendor),ios=safari&&(/Mobile\/\w+/.test(agent)||!!nav&&nav.maxTouchPoints>2),mac$2=ios||(nav?/Mac/.test(nav.platform):!1),windows$1=nav?/Win/.test(nav.platform):!1,android=/Android \d/.test(agent),webkit=!!doc&&`webkitFontSmoothing`in doc.documentElement.style,webkit_version=webkit?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function windowRect(e){let t=e.defaultView&&e.defaultView.visualViewport;return t?{left:0,right:t.width,top:0,bottom:t.height}:{left:0,right:e.documentElement.clientWidth,top:0,bottom:e.documentElement.clientHeight}}function getSide(e,t){return typeof e==`number`?e:e[t]}function clientRect(e){let t=e.getBoundingClientRect(),S=t.width/e.offsetWidth||1,w=t.height/e.offsetHeight||1;return{left:t.left,right:t.left+e.clientWidth*S,top:t.top,bottom:t.top+e.clientHeight*w}}function scrollRectIntoView(e,t,S){let w=e.someProp(`scrollThreshold`)||0,E=e.someProp(`scrollMargin`)||5,D=e.dom.ownerDocument;for(let O=S||e.dom;O;){if(O.nodeType!=1){O=parentNode(O);continue}let e=O,S=e==D.body,k=S?windowRect(D):clientRect(e),j=0,F=0;if(t.top<k.top+getSide(w,`top`)?F=-(k.top-t.top+getSide(E,`top`)):t.bottom>k.bottom-getSide(w,`bottom`)&&(F=t.bottom-t.top>k.bottom-k.top?t.top+getSide(E,`top`)-k.top:t.bottom-k.bottom+getSide(E,`bottom`)),t.left<k.left+getSide(w,`left`)?j=-(k.left-t.left+getSide(E,`left`)):t.right>k.right-getSide(w,`right`)&&(j=t.right-k.right+getSide(E,`right`)),j||F)if(S)D.defaultView.scrollBy(j,F);else{let S=e.scrollLeft,w=e.scrollTop;F&&(e.scrollTop+=F),j&&(e.scrollLeft+=j);let E=e.scrollLeft-S,D=e.scrollTop-w;t={left:t.left-E,top:t.top-D,right:t.right-E,bottom:t.bottom-D}}let L=S?`fixed`:getComputedStyle(O).position;if(/^(fixed|sticky)$/.test(L))break;O=L==`absolute`?O.offsetParent:parentNode(O)}}function storeScrollPos(e){let t=e.dom.getBoundingClientRect(),S=Math.max(0,t.top),w,E;for(let D=(t.left+t.right)/2,O=S+1;O<Math.min(innerHeight,t.bottom);O+=5){let t=e.root.elementFromPoint(D,O);if(!t||t==e.dom||!e.dom.contains(t))continue;let k=t.getBoundingClientRect();if(k.top>=S-20){w=t,E=k.top;break}}return{refDOM:w,refTop:E,stack:scrollStack(e.dom)}}function scrollStack(e){let t=[],S=e.ownerDocument;for(let w=e;w&&(t.push({dom:w,top:w.scrollTop,left:w.scrollLeft}),e!=S);w=parentNode(w));return t}function resetScrollPos({refDOM:e,refTop:t,stack:S}){let w=e?e.getBoundingClientRect().top:0;restoreScrollStack(S,w==0?0:w-t)}function restoreScrollStack(e,t){for(let S=0;S<e.length;S++){let{dom:w,top:E,left:D}=e[S];w.scrollTop!=E+t&&(w.scrollTop=E+t),w.scrollLeft!=D&&(w.scrollLeft=D)}}let preventScrollSupported=null;function focusPreventScroll(e){if(e.setActive)return e.setActive();if(preventScrollSupported)return e.focus(preventScrollSupported);let t=scrollStack(e);e.focus(preventScrollSupported==null?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),preventScrollSupported||(preventScrollSupported=!1,restoreScrollStack(t,0))}function findOffsetInNode(e,t){let S,w=2e8,E,D=0,O=t.top,k=t.top,j,F;for(let L=e.firstChild,B=0;L;L=L.nextSibling,B++){let e;if(L.nodeType==1)e=L.getClientRects();else if(L.nodeType==3)e=textRange(L).getClientRects();else continue;for(let H=0;H<e.length;H++){let q=e[H];if(q.top<=O&&q.bottom>=k){O=Math.max(q.bottom,O),k=Math.min(q.top,k);let e=q.left>t.left?q.left-t.left:q.right<t.left?t.left-q.right:0;if(e<w){S=L,w=e,E=e&&S.nodeType==3?{left:q.right<t.left?q.right:q.left,top:t.top}:t,L.nodeType==1&&e&&(D=B+(t.left>=(q.left+q.right)/2?1:0));continue}}else q.top>t.top&&!j&&q.left<=t.left&&q.right>=t.left&&(j=L,F={left:Math.max(q.left,Math.min(q.right,t.left)),top:q.top});!S&&(t.left>=q.right&&t.top>=q.top||t.left>=q.left&&t.top>=q.bottom)&&(D=B+1)}}return!S&&j&&(S=j,E=F,w=0),S&&S.nodeType==3?findOffsetInText(S,E):!S||w&&S.nodeType==1?{node:e,offset:D}:findOffsetInNode(S,E)}function findOffsetInText(e,t){let S=e.nodeValue.length,w=document.createRange(),E;for(let D=0;D<S;D++){w.setEnd(e,D+1),w.setStart(e,D);let S=singleRect(w,1);if(S.top!=S.bottom&&inRect(t,S)){E={node:e,offset:D+(t.left>=(S.left+S.right)/2?1:0)};break}}return w.detach(),E||{node:e,offset:0}}function inRect(e,t){return e.left>=t.left-1&&e.left<=t.right+1&&e.top>=t.top-1&&e.top<=t.bottom+1}function targetKludge(e,t){let S=e.parentNode;return S&&/^li$/i.test(S.nodeName)&&t.left<e.getBoundingClientRect().left?S:e}function posFromElement(e,t,S){let{node:w,offset:E}=findOffsetInNode(t,S),D=-1;if(w.nodeType==1&&!w.firstChild){let e=w.getBoundingClientRect();D=e.left!=e.right&&S.left>(e.left+e.right)/2?1:-1}return e.docView.posFromDOM(w,E,D)}function posFromCaret(e,t,S,w){let E=-1;for(let S=t,D=!1;S!=e.dom;){let t=e.docView.nearestDesc(S,!0),O;if(!t)return null;if(t.dom.nodeType==1&&(t.node.isBlock&&t.parent||!t.contentDOM)&&((O=t.dom.getBoundingClientRect()).width||O.height)&&(t.node.isBlock&&t.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(t.dom.nodeName)&&(!D&&O.left>w.left||O.top>w.top?E=t.posBefore:(!D&&O.right<w.left||O.bottom<w.top)&&(E=t.posAfter),D=!0),!t.contentDOM&&E<0&&!t.node.isText))return(t.node.isBlock?w.top<(O.top+O.bottom)/2:w.left<(O.left+O.right)/2)?t.posBefore:t.posAfter;S=t.dom.parentNode}return E>-1?E:e.docView.posFromDOM(t,S,-1)}function elementFromPoint(e,t,S){let w=e.childNodes.length;if(w&&S.top<S.bottom)for(let E=Math.max(0,Math.min(w-1,Math.floor(w*(t.top-S.top)/(S.bottom-S.top))-2)),D=E;;){let S=e.childNodes[D];if(S.nodeType==1){let e=S.getClientRects();for(let w=0;w<e.length;w++){let E=e[w];if(inRect(t,E))return elementFromPoint(S,t,E)}}if((D=(D+1)%w)==E)break}return e}function posAtCoords(e,t){let S=e.dom.ownerDocument,w,E=0,D=caretFromPoint(S,t.left,t.top);D&&({node:w,offset:E}=D);let O=(e.root.elementFromPoint?e.root:S).elementFromPoint(t.left,t.top),k;if(!O||!e.dom.contains(O.nodeType==1?O:O.parentNode)){let S=e.dom.getBoundingClientRect();if(!inRect(t,S)||(O=elementFromPoint(e.dom,t,S),!O))return null}if(safari)for(let e=O;w&&e;e=parentNode(e))e.draggable&&(w=void 0);if(O=targetKludge(O,t),w){if(gecko&&w.nodeType==1&&(E=Math.min(E,w.childNodes.length),E<w.childNodes.length)){let e=w.childNodes[E],S;e.nodeName==`IMG`&&(S=e.getBoundingClientRect()).right<=t.left&&S.bottom>t.top&&E++}let S;webkit&&E&&w.nodeType==1&&(S=w.childNodes[E-1]).nodeType==1&&S.contentEditable==`false`&&S.getBoundingClientRect().top>=t.top&&E--,w==e.dom&&E==w.childNodes.length-1&&w.lastChild.nodeType==1&&t.top>w.lastChild.getBoundingClientRect().bottom?k=e.state.doc.content.size:(E==0||w.nodeType!=1||w.childNodes[E-1].nodeName!=`BR`)&&(k=posFromCaret(e,w,E,t))}k??=posFromElement(e,O,t);let j=e.docView.nearestDesc(O,!0);return{pos:k,inside:j?j.posAtStart-j.border:-1}}function nonZero(e){return e.top<e.bottom||e.left<e.right}function singleRect(e,t){let S=e.getClientRects();if(S.length){let e=S[t<0?0:S.length-1];if(nonZero(e))return e}return Array.prototype.find.call(S,nonZero)||e.getBoundingClientRect()}const BIDI=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function coordsAtPos(e,t,S){let{node:w,offset:E,atom:D}=e.docView.domFromPos(t,S<0?-1:1),O=webkit||gecko;if(w.nodeType==3)if(O&&(BIDI.test(w.nodeValue)||(S<0?!E:E==w.nodeValue.length))){let e=singleRect(textRange(w,E,E),S);if(gecko&&E&&/\s/.test(w.nodeValue[E-1])&&E<w.nodeValue.length){let t=singleRect(textRange(w,E-1,E-1),-1);if(t.top==e.top){let S=singleRect(textRange(w,E,E+1),-1);if(S.top!=e.top)return flattenV(S,S.left<t.left)}}return e}else{let e=E,t=E,D=S<0?1:-1;return S<0&&!E?(t++,D=-1):S>=0&&E==w.nodeValue.length?(e--,D=1):S<0?e--:t++,flattenV(singleRect(textRange(w,e,t),D),D<0)}if(!e.state.doc.resolve(t-(D||0)).parent.inlineContent){if(D==null&&E&&(S<0||E==nodeSize(w))){let e=w.childNodes[E-1];if(e.nodeType==1)return flattenH(e.getBoundingClientRect(),!1)}if(D==null&&E<nodeSize(w)){let e=w.childNodes[E];if(e.nodeType==1)return flattenH(e.getBoundingClientRect(),!0)}return flattenH(w.getBoundingClientRect(),S>=0)}if(D==null&&E&&(S<0||E==nodeSize(w))){let e=w.childNodes[E-1],t=e.nodeType==3?textRange(e,nodeSize(e)-(O?0:1)):e.nodeType==1&&(e.nodeName!=`BR`||!e.nextSibling)?e:null;if(t)return flattenV(singleRect(t,1),!1)}if(D==null&&E<nodeSize(w)){let e=w.childNodes[E];for(;e.pmViewDesc&&e.pmViewDesc.ignoreForCoords;)e=e.nextSibling;let t=e?e.nodeType==3?textRange(e,0,O?0:1):e.nodeType==1?e:null:null;if(t)return flattenV(singleRect(t,-1),!0)}return flattenV(singleRect(w.nodeType==3?textRange(w):w,-S),S>=0)}function flattenV(e,t){if(e.width==0)return e;let S=t?e.left:e.right;return{top:e.top,bottom:e.bottom,left:S,right:S}}function flattenH(e,t){if(e.height==0)return e;let S=t?e.top:e.bottom;return{top:S,bottom:S,left:e.left,right:e.right}}function withFlushedState(e,t,S){let w=e.state,E=e.root.activeElement;w!=t&&e.updateState(t),E!=e.dom&&e.focus();try{return S()}finally{w!=t&&e.updateState(w),E!=e.dom&&E&&E.focus()}}function endOfTextblockVertical(e,t,S){let w=t.selection,E=S==`up`?w.$from:w.$to;return withFlushedState(e,t,()=>{let{node:t}=e.docView.domFromPos(E.pos,S==`up`?-1:1);for(;;){let S=e.docView.nearestDesc(t,!0);if(!S)break;if(S.node.isBlock){t=S.contentDOM||S.dom;break}t=S.dom.parentNode}let w=coordsAtPos(e,E.pos,1);for(let e=t.firstChild;e;e=e.nextSibling){let t;if(e.nodeType==1)t=e.getClientRects();else if(e.nodeType==3)t=textRange(e,0,e.nodeValue.length).getClientRects();else continue;for(let e=0;e<t.length;e++){let E=t[e];if(E.bottom>E.top+1&&(S==`up`?w.top-E.top>(E.bottom-w.top)*2:E.bottom-w.bottom>(w.bottom-E.top)*2))return!1}}return!0})}const maybeRTL=/[\u0590-\u08ac]/;function endOfTextblockHorizontal(e,t,S){let{$head:w}=t.selection;if(!w.parent.isTextblock)return!1;let E=w.parentOffset,D=!E,O=E==w.parent.content.size,k=e.domSelection();return k?!maybeRTL.test(w.parent.textContent)||!k.modify?S==`left`||S==`backward`?D:O:withFlushedState(e,t,()=>{let{focusNode:t,focusOffset:E,anchorNode:D,anchorOffset:O}=e.domSelectionRange(),j=k.caretBidiLevel;k.modify(`move`,S,`character`);let F=w.depth?e.docView.domAfterPos(w.before()):e.dom,{focusNode:L,focusOffset:B}=e.domSelectionRange(),H=L&&!F.contains(L.nodeType==1?L:L.parentNode)||t==L&&E==B;try{k.collapse(D,O),t&&(t!=D||E!=O)&&k.extend&&k.extend(t,E)}catch{}return j!=null&&(k.caretBidiLevel=j),H}):w.pos==w.start()||w.pos==w.end()}let cachedState=null,cachedDir=null,cachedResult=!1;function endOfTextblock(e,t,S){return cachedState==t&&cachedDir==S?cachedResult:(cachedState=t,cachedDir=S,cachedResult=S==`up`||S==`down`?endOfTextblockVertical(e,t,S):endOfTextblockHorizontal(e,t,S))}const NOT_DIRTY=0,CHILD_DIRTY=1,CONTENT_DIRTY=2,NODE_DIRTY=3;var ViewDesc=class{constructor(e,t,S,w){this.parent=e,this.children=t,this.dom=S,this.contentDOM=w,this.dirty=NOT_DIRTY,S.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,S){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;t<this.children.length;t++)e+=this.children[t].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let t=0,S=this.posAtStart;;t++){let w=this.children[t];if(w==e)return S;S+=w.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,t,S){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(S<0){let S,w;if(e==this.contentDOM)S=e.childNodes[t-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;S=e.previousSibling}for(;S&&!((w=S.pmViewDesc)&&w.parent==this);)S=S.previousSibling;return S?this.posBeforeChild(w)+w.size:this.posAtStart}else{let S,w;if(e==this.contentDOM)S=e.childNodes[t];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;S=e.nextSibling}for(;S&&!((w=S.pmViewDesc)&&w.parent==this);)S=S.nextSibling;return S?this.posBeforeChild(w):this.posAtEnd}let w;if(e==this.dom&&this.contentDOM)w=t>domIndex(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))w=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let t=e;;t=t.parentNode){if(t==this.dom){w=!1;break}if(t.previousSibling)break}if(w==null&&t==e.childNodes.length)for(let t=e;;t=t.parentNode){if(t==this.dom){w=!0;break}if(t.nextSibling)break}}return w??S>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let S=!0,w=e;w;w=w.parentNode){let E=this.getDesc(w),D;if(E&&(!t||E.node))if(S&&(D=E.nodeDOM)&&!(D.nodeType==1?D.contains(e.nodeType==1?e:e.parentNode):D==e))S=!1;else return E}}getDesc(e){let t=e.pmViewDesc;for(let e=t;e;e=e.parent)if(e==this)return t}posFromDOM(e,t,S){for(let w=e;w;w=w.parentNode){let E=this.getDesc(w);if(E)return E.localPosFromDOM(e,t,S)}return-1}descAt(e){for(let t=0,S=0;t<this.children.length;t++){let w=this.children[t],E=S+w.size;if(S==e&&E!=S){for(;!w.border&&w.children.length;)for(let e=0;e<w.children.length;e++){let t=w.children[e];if(t.size){w=t;break}}return w}if(e<E)return w.descAt(e-S-w.border);S=E}}domFromPos(e,t){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let S=0,w=0;for(let t=0;S<this.children.length;S++){let E=this.children[S],D=t+E.size;if(D>e||E instanceof TrailingHackViewDesc){w=e-t;break}t=D}if(w)return this.children[S].domFromPos(w-this.children[S].border,t);for(let e;S&&!(e=this.children[S-1]).size&&e instanceof WidgetViewDesc&&e.side>=0;S--);if(t<=0){let e,w=!0;for(;e=S?this.children[S-1]:null,!(!e||e.dom.parentNode==this.contentDOM);S--,w=!1);return e&&t&&w&&!e.border&&!e.domAtom?e.domFromPos(e.size,t):{node:this.contentDOM,offset:e?domIndex(e.dom)+1:0}}else{let e,w=!0;for(;e=S<this.children.length?this.children[S]:null,!(!e||e.dom.parentNode==this.contentDOM);S++,w=!1);return e&&w&&!e.border&&!e.domAtom?e.domFromPos(0,t):{node:this.contentDOM,offset:e?domIndex(e.dom):this.contentDOM.childNodes.length}}}parseRange(e,t,S=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:t,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let w=-1,E=-1;for(let D=S,O=0;;O++){let S=this.children[O],k=D+S.size;if(w==-1&&e<=k){let E=D+S.border;if(e>=E&&t<=k-S.border&&S.node&&S.contentDOM&&this.contentDOM.contains(S.contentDOM))return S.parseRange(e,t,E);e=D;for(let t=O;t>0;t--){let S=this.children[t-1];if(S.size&&S.dom.parentNode==this.contentDOM&&!S.emptyChildAt(1)){w=domIndex(S.dom)+1;break}e-=S.size}w==-1&&(w=0)}if(w>-1&&(k>t||O==this.children.length-1)){t=k;for(let e=O+1;e<this.children.length;e++){let S=this.children[e];if(S.size&&S.dom.parentNode==this.contentDOM&&!S.emptyChildAt(-1)){E=domIndex(S.dom);break}t+=S.size}E==-1&&(E=this.contentDOM.childNodes.length);break}D=k}return{node:this.contentDOM,from:e,to:t,fromOffset:w,toOffset:E}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let t=this.children[e<0?0:this.children.length-1];return t.size==0||t.emptyChildAt(e)}domAfterPos(e){let{node:t,offset:S}=this.domFromPos(e,0);if(t.nodeType!=1||S==t.childNodes.length)throw RangeError(`No node after pos `+e);return t.childNodes[S]}setSelection(e,t,S,w=!1){let E=Math.min(e,t),D=Math.max(e,t);for(let O=0,k=0;O<this.children.length;O++){let j=this.children[O],F=k+j.size;if(E>k&&D<F)return j.setSelection(e-k-j.border,t-k-j.border,S,w);k=F}let O=this.domFromPos(e,e?-1:1),k=t==e?O:this.domFromPos(t,t?-1:1),j=S.root.getSelection(),F=S.domSelectionRange(),L=!1;if((gecko||safari)&&e==t){let{node:e,offset:t}=O;if(e.nodeType==3){if(L=!!(t&&e.nodeValue[t-1]==`
|
|
166
166
|
`),L&&t==e.nodeValue.length)for(let t=e,S;t;t=t.parentNode){if(S=t.nextSibling){S.nodeName==`BR`&&(O=k={node:S.parentNode,offset:domIndex(S)+1});break}let e=t.pmViewDesc;if(e&&e.node&&e.node.isBlock)break}}else{let S=e.childNodes[t-1];L=S&&(S.nodeName==`BR`||S.contentEditable==`false`)}}if(gecko&&F.focusNode&&F.focusNode!=k.node&&F.focusNode.nodeType==1){let e=F.focusNode.childNodes[F.focusOffset];e&&e.contentEditable==`false`&&(w=!0)}if(!(w||L&&safari)&&isEquivalentPosition(O.node,O.offset,F.anchorNode,F.anchorOffset)&&isEquivalentPosition(k.node,k.offset,F.focusNode,F.focusOffset))return;let B=!1;if((j.extend||e==t)&&!(L&&gecko)){j.collapse(O.node,O.offset);try{e!=t&&j.extend(k.node,k.offset),B=!0}catch{}}if(!B){if(e>t){let e=O;O=k,k=e}let S=document.createRange();S.setEnd(k.node,k.offset),S.setStart(O.node,O.offset),j.removeAllRanges(),j.addRange(S)}}ignoreMutation(e){return!this.contentDOM&&e.type!=`selection`}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let S=0,w=0;w<this.children.length;w++){let E=this.children[w],D=S+E.size;if(S==D?e<=D&&t>=S:e<D&&t>S){let w=S+E.border,O=D-E.border;if(e>=w&&t<=O){this.dirty=e==S||t==D?CONTENT_DIRTY:CHILD_DIRTY,e==w&&t==O&&(E.contentLost||E.dom.parentNode!=this.contentDOM)?E.dirty=NODE_DIRTY:E.markDirty(e-w,t-w);return}else E.dirty=E.dom==E.contentDOM&&E.dom.parentNode==this.contentDOM&&!E.children.length?CONTENT_DIRTY:NODE_DIRTY}S=D}this.dirty=CONTENT_DIRTY}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let S=e==1?CONTENT_DIRTY:CHILD_DIRTY;t.dirty<S&&(t.dirty=S)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}},WidgetViewDesc=class extends ViewDesc{constructor(e,t,S,w){let E,D=t.type.toDOM;if(typeof D==`function`&&(D=D(S,()=>{if(!E)return w;if(E.parent)return E.parent.posBeforeChild(E)})),!t.type.spec.raw){if(D.nodeType!=1){let e=document.createElement(`span`);e.appendChild(D),D=e}D.contentEditable=`false`,D.classList.add(`ProseMirror-widget`)}super(e,[],D,null),this.widget=t,this.widget=t,E=this}matchesWidget(e){return this.dirty==NOT_DIRTY&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!=`selection`||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},CompositionViewDesc=class extends ViewDesc{constructor(e,t,S,w){super(e,[],t,null),this.textDOM=S,this.text=w}get size(){return this.text.length}localPosFromDOM(e,t){return e==this.textDOM?this.posAtStart+t:this.posAtStart+(t?this.size:0)}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type===`characterData`&&e.target.nodeValue==e.oldValue}},MarkViewDesc=class e extends ViewDesc{constructor(e,t,S,w,E){super(e,[],S,w),this.mark=t,this.spec=E}static create(t,S,w,E){let D=E.nodeViews[S.type.name],O=D&&D(S,E,w);return(!O||!O.dom)&&(O=DOMSerializer.renderSpec(document,S.type.spec.toDOM(S,w),null,S.attrs)),new e(t,S,O.dom,O.contentDOM||O.dom,O)}parseRule(){return this.dirty&NODE_DIRTY||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=NODE_DIRTY&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=NOT_DIRTY){let e=this.parent;for(;!e.node;)e=e.parent;e.dirty<this.dirty&&(e.dirty=this.dirty),this.dirty=NOT_DIRTY}}slice(t,S,w){let E=e.create(this.parent,this.mark,!0,w),D=this.children,O=this.size;S<O&&(D=replaceNodes(D,S,O,w)),t>0&&(D=replaceNodes(D,0,t,w));for(let e=0;e<D.length;e++)D[e].parent=E;return E.children=D,E}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},NodeViewDesc=class e extends ViewDesc{constructor(e,t,S,w,E,D,O,k,j){super(e,[],E,D),this.node=t,this.outerDeco=S,this.innerDeco=w,this.nodeDOM=O}static create(t,S,w,E,D,O){let k=D.nodeViews[S.type.name],j,F=k&&k(S,D,()=>{if(!j)return O;if(j.parent)return j.parent.posBeforeChild(j)},w,E),L=F&&F.dom,B=F&&F.contentDOM;if(S.isText){if(!L)L=document.createTextNode(S.text);else if(L.nodeType!=3)throw RangeError(`Text must be rendered as a DOM text node`)}else if(!L){let e=DOMSerializer.renderSpec(document,S.type.spec.toDOM(S),null,S.attrs);({dom:L,contentDOM:B}=e)}!B&&!S.isText&&L.nodeName!=`BR`&&(L.hasAttribute(`contenteditable`)||(L.contentEditable=`false`),S.type.spec.draggable&&(L.draggable=!0));let H=L;return L=applyOuterDeco(L,w,S),F?j=new CustomNodeViewDesc(t,S,w,E,L,B||null,H,F,D,O+1):S.isText?new TextViewDesc(t,S,w,E,L,H,D):new e(t,S,w,E,L,B||null,H,D,O+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace==`pre`&&(e.preserveWhitespace=`full`),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let S=this.children[t];if(this.dom.contains(S.dom.parentNode)){e.contentElement=S.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Fragment.empty)}return e}matchesNode(e,t,S){return this.dirty==NOT_DIRTY&&e.eq(this.node)&&sameOuterDeco(t,this.outerDeco)&&S.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let S=this.node.inlineContent,w=t,E=e.composing?this.localCompositionInfo(e,t):null,D=E&&E.pos>-1?E:null,O=E&&E.pos<0,k=new ViewTreeUpdater(this,D&&D.node,e);iterDeco(this.node,this.innerDeco,(t,E,D)=>{t.spec.marks?k.syncToMarks(t.spec.marks,S,e,E):t.type.side>=0&&!D&&k.syncToMarks(E==this.node.childCount?Mark$1.none:this.node.child(E).marks,S,e,E),k.placeWidget(t,e,w)},(t,D,j,F)=>{k.syncToMarks(t.marks,S,e,F);let L;k.findNodeMatch(t,D,j,F)||O&&e.state.selection.from>w&&e.state.selection.to<w+t.nodeSize&&(L=k.findIndexWithChild(E.node))>-1&&k.updateNodeAt(t,D,j,L,e)||k.updateNextNode(t,D,j,e,F,w)||k.addNode(t,D,j,e,w),w+=t.nodeSize}),k.syncToMarks([],S,e,0),this.node.isTextblock&&k.addTextblockHacks(),k.destroyRest(),(k.changed||this.dirty==CONTENT_DIRTY)&&(D&&this.protectLocalComposition(e,D),renderDescs(this.contentDOM,this.children,e),ios&&iosHacks(this.dom))}localCompositionInfo(e,t){let{from:S,to:w}=e.state.selection;if(!(e.state.selection instanceof TextSelection)||S<t||w>t+this.node.content.size)return null;let E=e.input.compositionNode;if(!E||!this.dom.contains(E.parentNode))return null;if(this.node.inlineContent){let e=E.nodeValue,D=findTextInFragment(this.node.content,e,S-t,w-t);return D<0?null:{node:E,pos:D,text:e}}else return{node:E,pos:-1,text:``}}protectLocalComposition(e,{node:t,pos:S,text:w}){if(this.getDesc(t))return;let E=t;for(;E.parentNode!=this.contentDOM;E=E.parentNode){for(;E.previousSibling;)E.parentNode.removeChild(E.previousSibling);for(;E.nextSibling;)E.parentNode.removeChild(E.nextSibling);E.pmViewDesc&&=void 0}let D=new CompositionViewDesc(this,E,t,w);e.input.compositionNodes.push(D),this.children=replaceNodes(this.children,S,S+w.length,e,D)}update(e,t,S,w){return this.dirty==NODE_DIRTY||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,S,w),!0)}updateInner(e,t,S,w){this.updateOuterDeco(t),this.node=e,this.innerDeco=S,this.contentDOM&&this.updateChildren(w,this.posAtStart),this.dirty=NOT_DIRTY}updateOuterDeco(e){if(sameOuterDeco(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,S=this.dom;this.dom=patchOuterDeco(this.dom,this.nodeDOM,computeOuterDeco(this.outerDeco,this.node,t),computeOuterDeco(e,this.node,t)),this.dom!=S&&(S.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add(`ProseMirror-selectednode`),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove(`ProseMirror-selectednode`),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute(`draggable`))}get domAtom(){return this.node.isAtom}};function docViewDesc(e,t,S,w,E){applyOuterDeco(w,t,e);let D=new NodeViewDesc(void 0,e,t,S,w,w,w,E,0);return D.contentDOM&&D.updateChildren(E,0),D}var TextViewDesc=class e extends NodeViewDesc{constructor(e,t,S,w,E,D,O){super(e,t,S,w,E,null,D,O,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,S,w){return this.dirty==NODE_DIRTY||this.dirty!=NOT_DIRTY&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=NOT_DIRTY||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,w.trackWrites==this.nodeDOM&&(w.trackWrites=null)),this.node=e,this.dirty=NOT_DIRTY,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,S){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,S)}ignoreMutation(e){return e.type!=`characterData`&&e.type!=`selection`}slice(t,S,w){let E=this.node.cut(t,S),D=document.createTextNode(E.text);return new e(this.parent,E,this.outerDeco,this.innerDeco,D,D,w)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=NODE_DIRTY)}get domAtom(){return!1}isText(e){return this.node.text==e}},TrailingHackViewDesc=class extends ViewDesc{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==NOT_DIRTY&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName==`IMG`}},CustomNodeViewDesc=class extends NodeViewDesc{constructor(e,t,S,w,E,D,O,k,j,F){super(e,t,S,w,E,D,O,j,F),this.spec=k}update(e,t,S,w){if(this.dirty==NODE_DIRTY)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let E=this.spec.update(e,t,S);return E&&this.updateInner(e,t,S,w),E}else if(!this.contentDOM&&!e.isLeaf)return!1;else return super.update(e,t,S,w)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,S,w){this.spec.setSelection?this.spec.setSelection(e,t,S.root):super.setSelection(e,t,S,w)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function renderDescs(e,t,S){let w=e.firstChild,E=!1;for(let D=0;D<t.length;D++){let O=t[D],k=O.dom;if(k.parentNode==e){for(;k!=w;)w=rm(w),E=!0;w=w.nextSibling}else E=!0,e.insertBefore(k,w);if(O instanceof MarkViewDesc){let t=w?w.previousSibling:e.lastChild;renderDescs(O.contentDOM,O.children,S),w=t?t.nextSibling:e.firstChild}}for(;w;)w=rm(w),E=!0;E&&S.trackWrites==e&&(S.trackWrites=null)}const OuterDecoLevel=function(e){e&&(this.nodeName=e)};OuterDecoLevel.prototype=Object.create(null);const noDeco=[new OuterDecoLevel];function computeOuterDeco(e,t,S){if(e.length==0)return noDeco;let w=S?noDeco[0]:new OuterDecoLevel,E=[w];for(let D=0;D<e.length;D++){let O=e[D].type.attrs;if(O){O.nodeName&&E.push(w=new OuterDecoLevel(O.nodeName));for(let e in O){let D=O[e];D!=null&&(S&&E.length==1&&E.push(w=new OuterDecoLevel(t.isInline?`span`:`div`)),e==`class`?w.class=(w.class?w.class+` `:``)+D:e==`style`?w.style=(w.style?w.style+`;`:``)+D:e!=`nodeName`&&(w[e]=D))}}}return E}function patchOuterDeco(e,t,S,w){if(S==noDeco&&w==noDeco)return t;let E=t;for(let t=0;t<w.length;t++){let D=w[t],O=S[t];if(t){let t;O&&O.nodeName==D.nodeName&&E!=e&&(t=E.parentNode)&&t.nodeName.toLowerCase()==D.nodeName?E=t:(t=document.createElement(D.nodeName),t.pmIsDeco=!0,t.appendChild(E),O=noDeco[0],E=t)}patchAttributes(E,O||noDeco[0],D)}return E}function patchAttributes(e,t,S){for(let w in t)w!=`class`&&w!=`style`&&w!=`nodeName`&&!(w in S)&&e.removeAttribute(w);for(let w in S)w!=`class`&&w!=`style`&&w!=`nodeName`&&S[w]!=t[w]&&e.setAttribute(w,S[w]);if(t.class!=S.class){let w=t.class?t.class.split(` `).filter(Boolean):[],E=S.class?S.class.split(` `).filter(Boolean):[];for(let t=0;t<w.length;t++)E.indexOf(w[t])==-1&&e.classList.remove(w[t]);for(let t=0;t<E.length;t++)w.indexOf(E[t])==-1&&e.classList.add(E[t]);e.classList.length==0&&e.removeAttribute(`class`)}if(t.style!=S.style){if(t.style){let S=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,w;for(;w=S.exec(t.style);)e.style.removeProperty(w[1])}S.style&&(e.style.cssText+=S.style)}}function applyOuterDeco(e,t,S){return patchOuterDeco(e,e,noDeco,computeOuterDeco(t,S,e.nodeType!=1))}function sameOuterDeco(e,t){if(e.length!=t.length)return!1;for(let S=0;S<e.length;S++)if(!e[S].type.eq(t[S].type))return!1;return!0}function rm(e){let t=e.nextSibling;return e.parentNode.removeChild(e),t}var ViewTreeUpdater=class{constructor(e,t,S){this.lock=t,this.view=S,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=preMatch(e.node.content,e)}destroyBetween(e,t){if(e!=t){for(let S=e;S<t;S++)this.top.children[S].destroy();this.top.children.splice(e,t-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,t,S,w){let E=0,D=this.stack.length>>1,O=Math.min(D,e.length);for(;E<O&&(E==D-1?this.top:this.stack[E+1<<1]).matchesMark(e[E])&&e[E].type.spec.spanning!==!1;)E++;for(;E<D;)this.destroyRest(),this.top.dirty=NOT_DIRTY,this.index=this.stack.pop(),this.top=this.stack.pop(),D--;for(;D<e.length;){this.stack.push(this.top,this.index+1);let E=-1,O=this.top.children.length;w<this.preMatch.index&&(O=Math.min(this.index+3,O));for(let t=this.index;t<O;t++){let S=this.top.children[t];if(S.matchesMark(e[D])&&!this.isLocked(S.dom)){E=t;break}}if(E>-1)E>this.index&&(this.changed=!0,this.destroyBetween(this.index,E)),this.top=this.top.children[this.index];else{let w=MarkViewDesc.create(this.top,e[D],t,S);this.top.children.splice(this.index,0,w),this.top=w,this.changed=!0}this.index=0,D++}}findNodeMatch(e,t,S,w){let E=-1,D;if(w>=this.preMatch.index&&(D=this.preMatch.matches[w-this.preMatch.index]).parent==this.top&&D.matchesNode(e,t,S))E=this.top.children.indexOf(D,this.index);else for(let w=this.index,D=Math.min(this.top.children.length,w+5);w<D;w++){let D=this.top.children[w];if(D.matchesNode(e,t,S)&&!this.preMatch.matched.has(D)){E=w;break}}return E<0?!1:(this.destroyBetween(this.index,E),this.index++,!0)}updateNodeAt(e,t,S,w,E){let D=this.top.children[w];return D.dirty==NODE_DIRTY&&D.dom==D.contentDOM&&(D.dirty=CONTENT_DIRTY),D.update(e,t,S,E)?(this.destroyBetween(this.index,w),this.index++,!0):!1}findIndexWithChild(e){for(;;){let t=e.parentNode;if(!t)return-1;if(t==this.top.contentDOM){let t=e.pmViewDesc;if(t){for(let e=this.index;e<this.top.children.length;e++)if(this.top.children[e]==t)return e}return-1}e=t}}updateNextNode(e,t,S,w,E,D){for(let O=this.index;O<this.top.children.length;O++){let k=this.top.children[O];if(k instanceof NodeViewDesc){let j=this.preMatch.matched.get(k);if(j!=null&&j!=E)return!1;let F=k.dom,L,B=this.isLocked(F)&&!(e.isText&&k.node&&k.node.isText&&k.nodeDOM.nodeValue==e.text&&k.dirty!=NODE_DIRTY&&sameOuterDeco(t,k.outerDeco));if(!B&&k.update(e,t,S,w))return this.destroyBetween(this.index,O),k.dom!=F&&(this.changed=!0),this.index++,!0;if(!B&&(L=this.recreateWrapper(k,e,t,S,w,D)))return this.destroyBetween(this.index,O),this.top.children[this.index]=L,L.contentDOM&&(L.dirty=CONTENT_DIRTY,L.updateChildren(w,D+1),L.dirty=NOT_DIRTY),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,t,S,w,E,D){if(e.dirty||t.isAtom||!e.children.length||!e.node.content.eq(t.content)||!sameOuterDeco(S,e.outerDeco)||!w.eq(e.innerDeco))return null;let O=NodeViewDesc.create(this.top,t,S,w,E,D);if(O.contentDOM){O.children=e.children,e.children=[];for(let e of O.children)e.parent=O}return e.destroy(),O}addNode(e,t,S,w,E){let D=NodeViewDesc.create(this.top,e,t,S,w,E);D.contentDOM&&D.updateChildren(w,E+1),this.top.children.splice(this.index++,0,D),this.changed=!0}placeWidget(e,t,S){let w=this.index<this.top.children.length?this.top.children[this.index]:null;if(w&&w.matchesWidget(e)&&(e==w.widget||!w.widget.type.toDOM.parentNode))this.index++;else{let w=new WidgetViewDesc(this.top,e,t,S);this.top.children.splice(this.index++,0,w),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],t=this.top;for(;e instanceof MarkViewDesc;)t=e,e=t.children[t.children.length-1];(!e||!(e instanceof TextViewDesc)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((safari||chrome)&&e&&e.dom.contentEditable==`false`&&this.addHackNode(`IMG`,t),this.addHackNode(`BR`,this.top))}addHackNode(e,t){if(t==this.top&&this.index<t.children.length&&t.children[this.index].matchesHack(e))this.index++;else{let S=document.createElement(e);e==`IMG`&&(S.className=`ProseMirror-separator`,S.alt=``),e==`BR`&&(S.className=`ProseMirror-trailingBreak`);let w=new TrailingHackViewDesc(this.top,[],S,null);t==this.top?t.children.splice(this.index++,0,w):t.children.push(w),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}};function preMatch(e,t){let S=t,w=S.children.length,E=e.childCount,D=new Map,O=[];outer:for(;E>0;){let k;for(;;)if(w){let e=S.children[w-1];if(e instanceof MarkViewDesc)S=e,w=e.children.length;else{k=e,w--;break}}else if(S==t)break outer;else w=S.parent.children.indexOf(S),S=S.parent;let j=k.node;if(j){if(j!=e.child(E-1))break;--E,D.set(k,E),O.push(k)}}return{index:E,matched:D,matches:O.reverse()}}function compareSide(e,t){return e.type.side-t.type.side}function iterDeco(e,t,S,w){let E=t.locals(e),D=0;if(E.length==0){for(let S=0;S<e.childCount;S++){let O=e.child(S);w(O,E,t.forChild(D,O),S),D+=O.nodeSize}return}let O=0,k=[],j=null;for(let F=0;;){let L,B;for(;O<E.length&&E[O].to==D;){let e=E[O++];e.widget&&(L?(B||=[L]).push(e):L=e)}if(L)if(B){B.sort(compareSide);for(let e=0;e<B.length;e++)S(B[e],F,!!j)}else S(L,F,!!j);let H,q;if(j)q=-1,H=j,j=null;else if(F<e.childCount)q=F,H=e.child(F++);else break;for(let e=0;e<k.length;e++)k[e].to<=D&&k.splice(e--,1);for(;O<E.length&&E[O].from<=D&&E[O].to>D;)k.push(E[O++]);let J=D+H.nodeSize;if(H.isText){let e=J;O<E.length&&E[O].from<e&&(e=E[O].from);for(let t=0;t<k.length;t++)k[t].to<e&&(e=k[t].to);e<J&&(j=H.cut(e-D),H=H.cut(0,e-D),J=e,q=-1)}else for(;O<E.length&&E[O].to<J;)O++;let Y=H.isInline&&!H.isLeaf?k.filter(e=>!e.inline):k.slice();w(H,Y,t.forChild(D,H),q),D=J}}function iosHacks(e){if(e.nodeName==`UL`||e.nodeName==`OL`){let t=e.style.cssText;e.style.cssText=t+`; list-style: square !important`,window.getComputedStyle(e).listStyle,e.style.cssText=t}}function findTextInFragment(e,t,S,w){for(let E=0,D=0;E<e.childCount&&D<=w;){let O=e.child(E++),k=D;if(D+=O.nodeSize,!O.isText)continue;let j=O.text;for(;E<e.childCount;){let t=e.child(E++);if(D+=t.nodeSize,!t.isText)break;j+=t.text}if(D>=S){if(D>=w&&j.slice(w-t.length-k,w-k)==t)return w-t.length;let e=k<w?j.lastIndexOf(t,w-k-1):-1;if(e>=0&&e+t.length+k>=S)return k+e;if(S==w&&j.length>=w+t.length-k&&j.slice(w-k,w-k+t.length)==t)return w}}return-1}function replaceNodes(e,t,S,w,E){let D=[];for(let O=0,k=0;O<e.length;O++){let j=e[O],F=k,L=k+=j.size;F>=S||L<=t?D.push(j):(F<t&&D.push(j.slice(0,t-F,w)),E&&=(D.push(E),void 0),L>S&&D.push(j.slice(S-F,j.size,w)))}return D}function selectionFromDOM(e,t=null){let S=e.domSelectionRange(),w=e.state.doc;if(!S.focusNode)return null;let E=e.docView.nearestDesc(S.focusNode),D=E&&E.size==0,O=e.docView.posFromDOM(S.focusNode,S.focusOffset,1);if(O<0)return null;let k=w.resolve(O),j,F;if(selectionCollapsed(S)){for(j=O;E&&!E.node;)E=E.parent;let e=E.node;if(E&&e.isAtom&&NodeSelection.isSelectable(e)&&E.parent&&!(e.isInline&&isOnEdge(S.focusNode,S.focusOffset,E.dom))){let e=E.posBefore;F=new NodeSelection(O==e?k:w.resolve(e))}}else{if(S instanceof e.dom.ownerDocument.defaultView.Selection&&S.rangeCount>1){let t=O,E=O;for(let w=0;w<S.rangeCount;w++){let D=S.getRangeAt(w);t=Math.min(t,e.docView.posFromDOM(D.startContainer,D.startOffset,1)),E=Math.max(E,e.docView.posFromDOM(D.endContainer,D.endOffset,-1))}if(t<0)return null;[j,O]=E==e.state.selection.anchor?[E,t]:[t,E],k=w.resolve(O)}else j=e.docView.posFromDOM(S.anchorNode,S.anchorOffset,1);if(j<0)return null}let L=w.resolve(j);if(!F){let S=t==`pointer`||e.state.selection.head<k.pos&&!D?1:-1;F=selectionBetween(e,L,k,S)}return F}function editorOwnsSelection(e){return e.editable?e.hasFocus():hasSelection(e)&&document.activeElement&&document.activeElement.contains(e.dom)}function selectionToDOM(e,t=!1){let S=e.state.selection;if(syncNodeSelection(e,S),editorOwnsSelection(e)){if(!t&&e.input.mouseDown&&e.input.mouseDown.allowDefault&&chrome){let t=e.domSelectionRange(),S=e.domObserver.currentSelection;if(t.anchorNode&&S.anchorNode&&isEquivalentPosition(t.anchorNode,t.anchorOffset,S.anchorNode,S.anchorOffset)){e.input.mouseDown.delayedSelectionSync=!0,e.domObserver.setCurSelection();return}}if(e.domObserver.disconnectSelection(),e.cursorWrapper)selectCursorWrapper(e);else{let{anchor:w,head:E}=S,D,O;brokenSelectBetweenUneditable&&!(S instanceof TextSelection)&&(S.$from.parent.inlineContent||(D=temporarilyEditableNear(e,S.from)),!S.empty&&!S.$from.parent.inlineContent&&(O=temporarilyEditableNear(e,S.to))),e.docView.setSelection(w,E,e,t),brokenSelectBetweenUneditable&&(D&&resetEditable(D),O&&resetEditable(O)),S.visible?e.dom.classList.remove(`ProseMirror-hideselection`):(e.dom.classList.add(`ProseMirror-hideselection`),`onselectionchange`in document&&removeClassOnSelectionChange(e))}e.domObserver.setCurSelection(),e.domObserver.connectSelection()}}const brokenSelectBetweenUneditable=safari||chrome&&chrome_version<63;function temporarilyEditableNear(e,t){let{node:S,offset:w}=e.docView.domFromPos(t,0),E=w<S.childNodes.length?S.childNodes[w]:null,D=w?S.childNodes[w-1]:null;if(safari&&E&&E.contentEditable==`false`)return setEditable(E);if((!E||E.contentEditable==`false`)&&(!D||D.contentEditable==`false`)){if(E)return setEditable(E);if(D)return setEditable(D)}}function setEditable(e){return e.contentEditable=`true`,safari&&e.draggable&&(e.draggable=!1,e.wasDraggable=!0),e}function resetEditable(e){e.contentEditable=`false`,e.wasDraggable&&=(e.draggable=!0,null)}function removeClassOnSelectionChange(e){let t=e.dom.ownerDocument;t.removeEventListener(`selectionchange`,e.input.hideSelectionGuard);let S=e.domSelectionRange(),w=S.anchorNode,E=S.anchorOffset;t.addEventListener(`selectionchange`,e.input.hideSelectionGuard=()=>{(S.anchorNode!=w||S.anchorOffset!=E)&&(t.removeEventListener(`selectionchange`,e.input.hideSelectionGuard),setTimeout(()=>{(!editorOwnsSelection(e)||e.state.selection.visible)&&e.dom.classList.remove(`ProseMirror-hideselection`)},20))})}function selectCursorWrapper(e){let t=e.domSelection();if(!t)return;let S=e.cursorWrapper.dom,w=S.nodeName==`IMG`;w?t.collapse(S.parentNode,domIndex(S)+1):t.collapse(S,0),!w&&!e.state.selection.visible&&ie$2&&ie_version<=11&&(S.disabled=!0,S.disabled=!1)}function syncNodeSelection(e,t){if(t instanceof NodeSelection){let S=e.docView.descAt(t.from);S!=e.lastSelectedViewDesc&&(clearNodeSelection(e),S&&S.selectNode(),e.lastSelectedViewDesc=S)}else clearNodeSelection(e)}function clearNodeSelection(e){e.lastSelectedViewDesc&&=(e.lastSelectedViewDesc.parent&&e.lastSelectedViewDesc.deselectNode(),void 0)}function selectionBetween(e,t,S,w){return e.someProp(`createSelectionBetween`,w=>w(e,t,S))||TextSelection.between(t,S,w)}function hasFocusAndSelection(e){return e.editable&&!e.hasFocus()?!1:hasSelection(e)}function hasSelection(e){let t=e.domSelectionRange();if(!t.anchorNode)return!1;try{return e.dom.contains(t.anchorNode.nodeType==3?t.anchorNode.parentNode:t.anchorNode)&&(e.editable||e.dom.contains(t.focusNode.nodeType==3?t.focusNode.parentNode:t.focusNode))}catch{return!1}}function anchorInRightPlace(e){let t=e.docView.domFromPos(e.state.selection.anchor,0),S=e.domSelectionRange();return isEquivalentPosition(t.node,t.offset,S.anchorNode,S.anchorOffset)}function moveSelectionBlock(e,t){let{$anchor:S,$head:w}=e.selection,E=t>0?S.max(w):S.min(w),D=E.parent.inlineContent?E.depth?e.doc.resolve(t>0?E.after():E.before()):null:E;return D&&Selection$1.findFrom(D,t)}function apply(e,t){return e.dispatch(e.state.tr.setSelection(t).scrollIntoView()),!0}function selectHorizontally(e,t,S){let w=e.state.selection;if(w instanceof TextSelection){if(S.indexOf(`s`)>-1){let{$head:S}=w,E=S.textOffset?null:t<0?S.nodeBefore:S.nodeAfter;if(!E||E.isText||!E.isLeaf)return!1;let D=e.state.doc.resolve(S.pos+E.nodeSize*(t<0?-1:1));return apply(e,new TextSelection(w.$anchor,D))}else if(!w.empty)return!1;else if(e.endOfTextblock(t>0?`forward`:`backward`)){let S=moveSelectionBlock(e.state,t);return S&&S instanceof NodeSelection?apply(e,S):!1}else if(!(mac$2&&S.indexOf(`m`)>-1)){let S=w.$head,E=S.textOffset?null:t<0?S.nodeBefore:S.nodeAfter,D;if(!E||E.isText)return!1;let O=t<0?S.pos-E.nodeSize:S.pos;return E.isAtom||(D=e.docView.descAt(O))&&!D.contentDOM?NodeSelection.isSelectable(E)?apply(e,new NodeSelection(t<0?e.state.doc.resolve(S.pos-E.nodeSize):S)):webkit?apply(e,new TextSelection(e.state.doc.resolve(t<0?O:O+E.nodeSize))):!1:!1}}else if(w instanceof NodeSelection&&w.node.isInline)return apply(e,new TextSelection(t>0?w.$to:w.$from));else{let S=moveSelectionBlock(e.state,t);return S?apply(e,S):!1}}function nodeLen(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function isIgnorable(e,t){let S=e.pmViewDesc;return S&&S.size==0&&(t<0||e.nextSibling||e.nodeName!=`BR`)}function skipIgnoredNodes(e,t){return t<0?skipIgnoredNodesBefore(e):skipIgnoredNodesAfter(e)}function skipIgnoredNodesBefore(e){let t=e.domSelectionRange(),S=t.focusNode,w=t.focusOffset;if(!S)return;let E,D,O=!1;for(gecko&&S.nodeType==1&&w<nodeLen(S)&&isIgnorable(S.childNodes[w],-1)&&(O=!0);;)if(w>0){if(S.nodeType!=1)break;{let e=S.childNodes[w-1];if(isIgnorable(e,-1))E=S,D=--w;else if(e.nodeType==3)S=e,w=S.nodeValue.length;else break}}else if(isBlockNode(S))break;else{let t=S.previousSibling;for(;t&&isIgnorable(t,-1);)E=S.parentNode,D=domIndex(t),t=t.previousSibling;if(t)S=t,w=nodeLen(S);else{if(S=S.parentNode,S==e.dom)break;w=0}}O?setSelFocus(e,S,w):E&&setSelFocus(e,E,D)}function skipIgnoredNodesAfter(e){let t=e.domSelectionRange(),S=t.focusNode,w=t.focusOffset;if(!S)return;let E=nodeLen(S),D,O;for(;;)if(w<E){if(S.nodeType!=1)break;let e=S.childNodes[w];if(isIgnorable(e,1))D=S,O=++w;else break}else if(isBlockNode(S))break;else{let t=S.nextSibling;for(;t&&isIgnorable(t,1);)D=t.parentNode,O=domIndex(t)+1,t=t.nextSibling;if(t)S=t,w=0,E=nodeLen(S);else{if(S=S.parentNode,S==e.dom)break;w=E=0}}D&&setSelFocus(e,D,O)}function isBlockNode(e){let t=e.pmViewDesc;return t&&t.node&&t.node.isBlock}function textNodeAfter(e,t){for(;e&&t==e.childNodes.length&&!hasBlockDesc(e);)t=domIndex(e)+1,e=e.parentNode;for(;e&&t<e.childNodes.length;){let S=e.childNodes[t];if(S.nodeType==3)return S;if(S.nodeType==1&&S.contentEditable==`false`)break;e=S,t=0}}function textNodeBefore(e,t){for(;e&&!t&&!hasBlockDesc(e);)t=domIndex(e),e=e.parentNode;for(;e&&t;){let S=e.childNodes[t-1];if(S.nodeType==3)return S;if(S.nodeType==1&&S.contentEditable==`false`)break;e=S,t=e.childNodes.length}}function setSelFocus(e,t,S){if(t.nodeType!=3){let e,w;(w=textNodeAfter(t,S))?(t=w,S=0):(e=textNodeBefore(t,S))&&(t=e,S=e.nodeValue.length)}let w=e.domSelection();if(!w)return;if(selectionCollapsed(w)){let e=document.createRange();e.setEnd(t,S),e.setStart(t,S),w.removeAllRanges(),w.addRange(e)}else w.extend&&w.extend(t,S);e.domObserver.setCurSelection();let{state:E}=e;setTimeout(()=>{e.state==E&&selectionToDOM(e)},50)}function findDirection(e,t){let S=e.state.doc.resolve(t);if(!(chrome||windows$1)&&S.parent.inlineContent){let w=e.coordsAtPos(t);if(t>S.start()){let S=e.coordsAtPos(t-1),E=(S.top+S.bottom)/2;if(E>w.top&&E<w.bottom&&Math.abs(S.left-w.left)>1)return S.left<w.left?`ltr`:`rtl`}if(t<S.end()){let S=e.coordsAtPos(t+1),E=(S.top+S.bottom)/2;if(E>w.top&&E<w.bottom&&Math.abs(S.left-w.left)>1)return S.left>w.left?`ltr`:`rtl`}}return getComputedStyle(e.dom).direction==`rtl`?`rtl`:`ltr`}function selectVertically(e,t,S){let w=e.state.selection;if(w instanceof TextSelection&&!w.empty||S.indexOf(`s`)>-1||mac$2&&S.indexOf(`m`)>-1)return!1;let{$from:E,$to:D}=w;if(!E.parent.inlineContent||e.endOfTextblock(t<0?`up`:`down`)){let S=moveSelectionBlock(e.state,t);if(S&&S instanceof NodeSelection)return apply(e,S)}if(!E.parent.inlineContent){let S=t<0?E:D,O=w instanceof AllSelection?Selection$1.near(S,t):Selection$1.findFrom(S,t);return O?apply(e,O):!1}return!1}function stopNativeHorizontalDelete(e,t){if(!(e.state.selection instanceof TextSelection))return!0;let{$head:S,$anchor:w,empty:E}=e.state.selection;if(!S.sameParent(w))return!0;if(!E)return!1;if(e.endOfTextblock(t>0?`forward`:`backward`))return!0;let D=!S.textOffset&&(t<0?S.nodeBefore:S.nodeAfter);if(D&&!D.isText){let w=e.state.tr;return t<0?w.delete(S.pos-D.nodeSize,S.pos):w.delete(S.pos,S.pos+D.nodeSize),e.dispatch(w),!0}return!1}function switchEditable(e,t,S){e.domObserver.stop(),t.contentEditable=S,e.domObserver.start()}function safariDownArrowBug(e){if(!safari||e.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:S}=e.domSelectionRange();if(t&&t.nodeType==1&&S==0&&t.firstChild&&t.firstChild.contentEditable==`false`){let S=t.firstChild;switchEditable(e,S,`true`),setTimeout(()=>switchEditable(e,S,`false`),20)}return!1}function getMods(e){let t=``;return e.ctrlKey&&(t+=`c`),e.metaKey&&(t+=`m`),e.altKey&&(t+=`a`),e.shiftKey&&(t+=`s`),t}function captureKeyDown(e,t){let S=t.keyCode,w=getMods(t);if(S==8||mac$2&&S==72&&w==`c`)return stopNativeHorizontalDelete(e,-1)||skipIgnoredNodes(e,-1);if(S==46&&!t.shiftKey||mac$2&&S==68&&w==`c`)return stopNativeHorizontalDelete(e,1)||skipIgnoredNodes(e,1);if(S==13||S==27)return!0;if(S==37||mac$2&&S==66&&w==`c`){let t=S==37?findDirection(e,e.state.selection.from)==`ltr`?-1:1:-1;return selectHorizontally(e,t,w)||skipIgnoredNodes(e,t)}else if(S==39||mac$2&&S==70&&w==`c`){let t=S==39?findDirection(e,e.state.selection.from)==`ltr`?1:-1:1;return selectHorizontally(e,t,w)||skipIgnoredNodes(e,t)}else if(S==38||mac$2&&S==80&&w==`c`)return selectVertically(e,-1,w)||skipIgnoredNodes(e,-1);else if(S==40||mac$2&&S==78&&w==`c`)return safariDownArrowBug(e)||selectVertically(e,1,w)||skipIgnoredNodes(e,1);else if(w==(mac$2?`m`:`c`)&&(S==66||S==73||S==89||S==90))return!0;return!1}function serializeForClipboard(e,t){e.someProp(`transformCopied`,S=>{t=S(t,e)});let S=[],{content:w,openStart:E,openEnd:D}=t;for(;E>1&&D>1&&w.childCount==1&&w.firstChild.childCount==1;){E--,D--;let e=w.firstChild;S.push(e.type.name,e.attrs==e.type.defaultAttrs?null:e.attrs),w=e.content}let O=e.someProp(`clipboardSerializer`)||DOMSerializer.fromSchema(e.state.schema),k=detachedDoc(),j=k.createElement(`div`);j.appendChild(O.serializeFragment(w,{document:k}));let F=j.firstChild,L,B=0;for(;F&&F.nodeType==1&&(L=wrapMap[F.nodeName.toLowerCase()]);){for(let e=L.length-1;e>=0;e--){let t=k.createElement(L[e]);for(;j.firstChild;)t.appendChild(j.firstChild);j.appendChild(t),B++}F=j.firstChild}return F&&F.nodeType==1&&F.setAttribute(`data-pm-slice`,`${E} ${D}${B?` -${B}`:``} ${JSON.stringify(S)}`),{dom:j,text:e.someProp(`clipboardTextSerializer`,S=>S(t,e))||t.content.textBetween(0,t.content.size,`
|
|
167
167
|
|
|
168
168
|
`),slice:t}}function parseFromClipboard(e,t,S,w,E){let D=E.parent.type.spec.code,O,k;if(!S&&!t)return null;let j=!!t&&(w||D||!S);if(j){if(e.someProp(`transformPastedText`,S=>{t=S(t,D||w,e)}),D)return k=new Slice(Fragment.from(e.state.schema.text(t.replace(/\r\n?/g,`
|
|
169
|
-
`))),0,0),e.someProp(`transformPasted`,t=>{k=t(k,e,!0)}),k;let S=e.someProp(`clipboardTextParser`,S=>S(t,E,w,e));if(S)k=S;else{let S=E.marks(),{schema:w}=e.state,D=DOMSerializer.fromSchema(w);O=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=O.appendChild(document.createElement(`p`));e&&t.appendChild(D.serializeNode(w.text(e,S)))})}}else e.someProp(`transformPastedHTML`,t=>{S=t(S,e)}),O=readHTML(S),webkit&&restoreReplacedSpaces(O);let F=O&&O.querySelector(`[data-pm-slice]`),L=F&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(F.getAttribute(`data-pm-slice`)||``);if(L&&L[3])for(let e=+L[3];e>0;e--){let e=O.firstChild;for(;e&&e.nodeType!=1;)e=e.nextSibling;if(!e)break;O=e}if(k||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||DOMParser.fromSchema(e.state.schema)).parseSlice(O,{preserveWhitespace:!!(j||L),context:E,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!inlineParents.test(e.parentNode.nodeName)?{ignore:!0}:null}}),L)k=addContext(closeSlice(k,+L[1],+L[2]),L[4]);else if(k=Slice.maxOpen(normalizeSiblings(k.content,E),!0),k.openStart||k.openEnd){let e=0,t=0;for(let t=k.content.firstChild;e<k.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=k.content.lastChild;t<k.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);k=closeSlice(k,e,t)}return e.someProp(`transformPasted`,t=>{k=t(k,e,j)}),k}const inlineParents=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function normalizeSiblings(e,t){if(e.childCount<2)return e;for(let S=t.depth;S>=0;S--){let w=t.node(S).contentMatchAt(t.index(S)),E,D=[];if(e.forEach(e=>{if(!D)return;let t=w.findWrapping(e.type),S;if(!t)return D=null;if(S=D.length&&E.length&&addToSibling(t,E,e,D[D.length-1],0))D[D.length-1]=S;else{D.length&&(D[D.length-1]=closeRight(D[D.length-1],E.length));let S=withWrappers(e,t);D.push(S),w=w.matchType(S.type),E=t}}),D)return Fragment.from(D)}return e}function withWrappers(e,t,S=0){for(let w=t.length-1;w>=S;w--)e=t[w].create(null,Fragment.from(e));return e}function addToSibling(e,t,S,w,E){if(E<e.length&&E<t.length&&e[E]==t[E]){let D=addToSibling(e,t,S,w.lastChild,E+1);if(D)return w.copy(w.content.replaceChild(w.childCount-1,D));if(w.contentMatchAt(w.childCount).matchType(E==e.length-1?S.type:e[E+1]))return w.copy(w.content.append(Fragment.from(withWrappers(S,e,E+1))))}}function closeRight(e,t){if(t==0)return e;let S=e.content.replaceChild(e.childCount-1,closeRight(e.lastChild,t-1)),w=e.contentMatchAt(e.childCount).fillBefore(Fragment.empty,!0);return e.copy(S.append(w))}function closeRange(e,t,S,w,E,D){let O=t<0?e.firstChild:e.lastChild,k=O.content;return e.childCount>1&&(D=0),E<w-1&&(k=closeRange(k,t,S,w,E+1,D)),E>=S&&(k=t<0?O.contentMatchAt(0).fillBefore(k,D<=E).append(k):k.append(O.contentMatchAt(O.childCount).fillBefore(Fragment.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,O.copy(k))}function closeSlice(e,t,S){return t<e.openStart&&(e=new Slice(closeRange(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),S<e.openEnd&&(e=new Slice(closeRange(e.content,1,S,e.openEnd,0,0),e.openStart,S)),e}const wrapMap={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]};let _detachedDoc=null;function detachedDoc(){return _detachedDoc||=document.implementation.createHTMLDocument(`title`)}let _policy=null;function maybeWrapTrusted(e){let t=window.trustedTypes;return t?(_policy||=t.defaultPolicy||t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e}),_policy.createHTML(e)):e}function readHTML(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let S=detachedDoc().createElement(`div`),w=/<([a-z][^>\s]+)/i.exec(e),E;if((E=w&&wrapMap[w[1].toLowerCase()])&&(e=E.map(e=>`<`+e+`>`).join(``)+e+E.map(e=>`</`+e+`>`).reverse().join(``)),S.innerHTML=maybeWrapTrusted(e),E)for(let e=0;e<E.length;e++)S=S.querySelector(E[e])||S;return S}function restoreReplacedSpaces(e){let t=e.querySelectorAll(chrome?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let S=0;S<t.length;S++){let w=t[S];w.childNodes.length==1&&w.textContent==`\xA0`&&w.parentNode&&w.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),w)}}function addContext(e,t){if(!e.size)return e;let S=e.content.firstChild.type.schema,w;try{w=JSON.parse(t)}catch{return e}let{content:E,openStart:D,openEnd:O}=e;for(let e=w.length-2;e>=0;e-=2){let t=S.nodes[w[e]];if(!t||t.hasRequiredAttrs())break;E=Fragment.from(t.create(w[e+1],E)),D++,O++}return new Slice(E,D,O)}const handlers={},editHandlers={},passiveHandlers={touchstart:!0,touchmove:!0};var InputState=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function initInput(e){for(let t in handlers){let S=handlers[t];e.dom.addEventListener(t,e.input.eventHandlers[t]=t=>{eventBelongsToView(e,t)&&!runCustomHandler(e,t)&&(e.editable||!(t.type in editHandlers))&&S(e,t)},passiveHandlers[t]?{passive:!0}:void 0)}safari&&e.dom.addEventListener(`input`,()=>null),ensureListeners(e)}function setSelectionOrigin(e,t){e.input.lastSelectionOrigin=t,e.input.lastSelectionTime=Date.now()}function destroyInput(e){e.domObserver.stop();for(let t in e.input.eventHandlers)e.dom.removeEventListener(t,e.input.eventHandlers[t]);clearTimeout(e.input.composingTimeout),clearTimeout(e.input.lastIOSEnterFallbackTimeout)}function ensureListeners(e){e.someProp(`handleDOMEvents`,t=>{for(let S in t)e.input.eventHandlers[S]||e.dom.addEventListener(S,e.input.eventHandlers[S]=t=>runCustomHandler(e,t))})}function runCustomHandler(e,t){return e.someProp(`handleDOMEvents`,S=>{let w=S[t.type];return w?w(e,t)||t.defaultPrevented:!1})}function eventBelongsToView(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let S=t.target;S!=e.dom;S=S.parentNode)if(!S||S.nodeType==11||S.pmViewDesc&&S.pmViewDesc.stopEvent(t))return!1;return!0}function dispatchEvent(e,t){!runCustomHandler(e,t)&&handlers[t.type]&&(e.editable||!(t.type in editHandlers))&&handlers[t.type](e,t)}editHandlers.keydown=(e,t)=>{let S=t;if(e.input.shiftKey=S.keyCode==16||S.shiftKey,!inOrNearComposition(e,S)&&(e.input.lastKeyCode=S.keyCode,e.input.lastKeyCodeTime=Date.now(),!(android&&chrome&&S.keyCode==13)))if(S.keyCode!=229&&e.domObserver.forceFlush(),ios&&S.keyCode==13&&!S.ctrlKey&&!S.altKey&&!S.metaKey){let t=Date.now();e.input.lastIOSEnter=t,e.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{e.input.lastIOSEnter==t&&(e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))),e.input.lastIOSEnter=0)},200)}else e.someProp(`handleKeyDown`,t=>t(e,S))||captureKeyDown(e,S)?S.preventDefault():setSelectionOrigin(e,`key`)},editHandlers.keyup=(e,t)=>{t.keyCode==16&&(e.input.shiftKey=!1)},editHandlers.keypress=(e,t)=>{let S=t;if(inOrNearComposition(e,S)||!S.charCode||S.ctrlKey&&!S.altKey||mac$2&&S.metaKey)return;if(e.someProp(`handleKeyPress`,t=>t(e,S))){S.preventDefault();return}let w=e.state.selection;if(!(w instanceof TextSelection)||!w.$from.sameParent(w.$to)){let t=String.fromCharCode(S.charCode),E=()=>e.state.tr.insertText(t).scrollIntoView();!/[\r\n]/.test(t)&&!e.someProp(`handleTextInput`,S=>S(e,w.$from.pos,w.$to.pos,t,E))&&e.dispatch(E()),S.preventDefault()}};function eventCoords(e){return{left:e.clientX,top:e.clientY}}function isNear(e,t){let S=t.x-e.clientX,w=t.y-e.clientY;return S*S+w*w<100}function runHandlerOnContext(e,t,S,w,E){if(w==-1)return!1;let D=e.state.doc.resolve(w);for(let w=D.depth+1;w>0;w--)if(e.someProp(t,t=>w>D.depth?t(e,S,D.nodeAfter,D.before(w),E,!0):t(e,S,D.node(w),D.before(w),E,!1)))return!0;return!1}function updateSelection(e,t,S){if(e.focused||e.focus(),e.state.selection.eq(t))return;let w=e.state.tr.setSelection(t);S==`pointer`&&w.setMeta(`pointer`,!0),e.dispatch(w)}function selectClickedLeaf(e,t){if(t==-1)return!1;let S=e.state.doc.resolve(t),w=S.nodeAfter;return w&&w.isAtom&&NodeSelection.isSelectable(w)?(updateSelection(e,new NodeSelection(S),`pointer`),!0):!1}function selectClickedNode(e,t){if(t==-1)return!1;let S=e.state.selection,w,E;S instanceof NodeSelection&&(w=S.node);let D=e.state.doc.resolve(t);for(let e=D.depth+1;e>0;e--){let t=e>D.depth?D.nodeAfter:D.node(e);if(NodeSelection.isSelectable(t)){E=w&&S.$from.depth>0&&e>=S.$from.depth&&D.before(S.$from.depth+1)==S.$from.pos?D.before(S.$from.depth):D.before(e);break}}return E==null?!1:(updateSelection(e,NodeSelection.create(e.state.doc,E),`pointer`),!0)}function handleSingleClick(e,t,S,w,E){return runHandlerOnContext(e,`handleClickOn`,t,S,w)||e.someProp(`handleClick`,S=>S(e,t,w))||(E?selectClickedNode(e,S):selectClickedLeaf(e,S))}function handleDoubleClick(e,t,S,w){return runHandlerOnContext(e,`handleDoubleClickOn`,t,S,w)||e.someProp(`handleDoubleClick`,S=>S(e,t,w))}function handleTripleClick$1(e,t,S,w){return runHandlerOnContext(e,`handleTripleClickOn`,t,S,w)||e.someProp(`handleTripleClick`,S=>S(e,t,w))||defaultTripleClick(e,S,w)}function defaultTripleClick(e,t,S){if(S.button!=0)return!1;let w=e.state.doc;if(t==-1)return w.inlineContent?(updateSelection(e,TextSelection.create(w,0,w.content.size),`pointer`),!0):!1;let E=w.resolve(t);for(let t=E.depth+1;t>0;t--){let S=t>E.depth?E.nodeAfter:E.node(t),D=E.before(t);if(S.inlineContent)updateSelection(e,TextSelection.create(w,D+1,D+1+S.content.size),`pointer`);else if(NodeSelection.isSelectable(S))updateSelection(e,NodeSelection.create(w,D),`pointer`);else continue;return!0}}function forceDOMFlush(e){return endComposition(e)}const selectNodeModifier=mac$2?`metaKey`:`ctrlKey`;handlers.mousedown=(e,t)=>{let S=t;e.input.shiftKey=S.shiftKey;let w=forceDOMFlush(e),E=Date.now(),D=`singleClick`;E-e.input.lastClick.time<500&&isNear(S,e.input.lastClick)&&!S[selectNodeModifier]&&e.input.lastClick.button==S.button&&(e.input.lastClick.type==`singleClick`?D=`doubleClick`:e.input.lastClick.type==`doubleClick`&&(D=`tripleClick`)),e.input.lastClick={time:E,x:S.clientX,y:S.clientY,type:D,button:S.button};let O=e.posAtCoords(eventCoords(S));O&&(D==`singleClick`?(e.input.mouseDown&&e.input.mouseDown.done(),e.input.mouseDown=new MouseDown(e,O,S,!!w)):(D==`doubleClick`?handleDoubleClick:handleTripleClick$1)(e,O.pos,O.inside,S)?S.preventDefault():setSelectionOrigin(e,`pointer`))};var MouseDown=class{constructor(e,t,S,w){this.view=e,this.pos=t,this.event=S,this.flushed=w,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!S[selectNodeModifier],this.allowDefault=S.shiftKey;let E,D;if(t.inside>-1)E=e.state.doc.nodeAt(t.inside),D=t.inside;else{let S=e.state.doc.resolve(t.pos);E=S.parent,D=S.depth?S.before():0}let O=w?null:S.target,k=O?e.docView.nearestDesc(O,!0):null;this.target=k&&k.nodeDOM.nodeType==1?k.nodeDOM:null;let{selection:j}=e.state;S.button==0&&(E.type.spec.draggable&&E.type.spec.selectable!==!1||j instanceof NodeSelection&&j.from<=D&&j.to>D)&&(this.mightDrag={node:E,pos:D,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&gecko&&!this.target.hasAttribute(`contentEditable`))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute(`contentEditable`,`false`)},20),this.view.domObserver.start()),e.root.addEventListener(`mouseup`,this.up=this.up.bind(this)),e.root.addEventListener(`mousemove`,this.move=this.move.bind(this)),setSelectionOrigin(e,`pointer`)}done(){this.view.root.removeEventListener(`mouseup`,this.up),this.view.root.removeEventListener(`mousemove`,this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute(`draggable`),this.mightDrag.setUneditable&&this.target.removeAttribute(`contentEditable`),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>selectionToDOM(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(eventCoords(e))),this.updateAllowDefault(e),this.allowDefault||!t?setSelectionOrigin(this.view,`pointer`):handleSingleClick(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||safari&&this.mightDrag&&!this.mightDrag.node.isAtom||chrome&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(updateSelection(this.view,Selection$1.near(this.view.state.doc.resolve(t.pos)),`pointer`),e.preventDefault()):setSelectionOrigin(this.view,`pointer`)}move(e){this.updateAllowDefault(e),setSelectionOrigin(this.view,`pointer`),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}};handlers.touchstart=e=>{e.input.lastTouch=Date.now(),forceDOMFlush(e),setSelectionOrigin(e,`pointer`)},handlers.touchmove=e=>{e.input.lastTouch=Date.now(),setSelectionOrigin(e,`pointer`)},handlers.contextmenu=e=>forceDOMFlush(e);function inOrNearComposition(e,t){return e.composing?!0:safari&&Math.abs(t.timeStamp-e.input.compositionEndedAt)<500?(e.input.compositionEndedAt=-2e8,!0):!1}const timeoutComposition=android?5e3:-1;editHandlers.compositionstart=editHandlers.compositionupdate=e=>{if(!e.composing){e.domObserver.flush();let{state:t}=e,S=t.selection.$to;if(t.selection instanceof TextSelection&&(t.storedMarks||!S.textOffset&&S.parentOffset&&S.nodeBefore.marks.some(e=>e.type.spec.inclusive===!1)||chrome&&windows$1&&selectionBeforeUneditable(e)))e.markCursor=e.state.storedMarks||S.marks(),endComposition(e,!0),e.markCursor=null;else if(endComposition(e,!t.selection.empty),gecko&&t.selection.empty&&S.parentOffset&&!S.textOffset&&S.nodeBefore.marks.length){let t=e.domSelectionRange();for(let S=t.focusNode,w=t.focusOffset;S&&S.nodeType==1&&w!=0;){let t=w<0?S.lastChild:S.childNodes[w-1];if(!t)break;if(t.nodeType==3){let S=e.domSelection();S&&S.collapse(t,t.nodeValue.length);break}else S=t,w=-1}}e.input.composing=!0}scheduleComposeEnd(e,timeoutComposition)};function selectionBeforeUneditable(e){let{focusNode:t,focusOffset:S}=e.domSelectionRange();if(!t||t.nodeType!=1||S>=t.childNodes.length)return!1;let w=t.childNodes[S];return w.nodeType==1&&w.contentEditable==`false`}editHandlers.compositionend=(e,t)=>{e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=t.timeStamp,e.input.compositionPendingChanges=e.domObserver.pendingRecords().length?e.input.compositionID:0,e.input.compositionNode=null,e.input.badSafariComposition?e.domObserver.forceFlush():e.input.compositionPendingChanges&&Promise.resolve().then(()=>e.domObserver.flush()),e.input.compositionID++,scheduleComposeEnd(e,20))};function scheduleComposeEnd(e,t){clearTimeout(e.input.composingTimeout),t>-1&&(e.input.composingTimeout=setTimeout(()=>endComposition(e),t))}function clearComposition(e){for(e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=timestampFromCustomEvent());e.input.compositionNodes.length>0;)e.input.compositionNodes.pop().markParentsDirty()}function findCompositionNode(e){let t=e.domSelectionRange();if(!t.focusNode)return null;let S=textNodeBefore$1(t.focusNode,t.focusOffset),w=textNodeAfter$1(t.focusNode,t.focusOffset);if(S&&w&&S!=w){let t=w.pmViewDesc,E=e.domObserver.lastChangedTextNode;if(S==E||w==E)return E;if(!t||!t.isText(w.nodeValue))return w;if(e.input.compositionNode==w){let e=S.pmViewDesc;if(!(!e||!e.isText(S.nodeValue)))return w}}return S||w}function timestampFromCustomEvent(){let e=document.createEvent(`Event`);return e.initEvent(`event`,!0,!0),e.timeStamp}function endComposition(e,t=!1){if(!(android&&e.domObserver.flushingSoon>=0)){if(e.domObserver.forceFlush(),clearComposition(e),t||e.docView&&e.docView.dirty){let S=selectionFromDOM(e),w=e.state.selection;return S&&!S.eq(w)?e.dispatch(e.state.tr.setSelection(S)):(e.markCursor||t)&&!w.$from.node(w.$from.sharedDepth(w.to)).inlineContent?e.dispatch(e.state.tr.deleteSelection()):e.updateState(e.state),!0}return!1}}function captureCopy(e,t){if(!e.dom.parentNode)return;let S=e.dom.parentNode.appendChild(document.createElement(`div`));S.appendChild(t),S.style.cssText=`position: fixed; left: -10000px; top: 10px`;let w=getSelection(),E=document.createRange();E.selectNodeContents(t),e.dom.blur(),w.removeAllRanges(),w.addRange(E),setTimeout(()=>{S.parentNode&&S.parentNode.removeChild(S),e.focus()},50)}const brokenClipboardAPI=ie$2&&ie_version<15||ios&&webkit_version<604;handlers.copy=editHandlers.cut=(e,t)=>{let S=t,w=e.state.selection,E=S.type==`cut`;if(w.empty)return;let D=brokenClipboardAPI?null:S.clipboardData,{dom:O,text:k}=serializeForClipboard(e,w.content());D?(S.preventDefault(),D.clearData(),D.setData(`text/html`,O.innerHTML),D.setData(`text/plain`,k)):captureCopy(e,O),E&&e.dispatch(e.state.tr.deleteSelection().scrollIntoView().setMeta(`uiEvent`,`cut`))};function sliceSingleNode(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function capturePaste(e,t){if(!e.dom.parentNode)return;let S=e.input.shiftKey||e.state.selection.$from.parent.type.spec.code,w=e.dom.parentNode.appendChild(document.createElement(S?`textarea`:`div`));S||(w.contentEditable=`true`),w.style.cssText=`position: fixed; left: -10000px; top: 10px`,w.focus();let E=e.input.shiftKey&&e.input.lastKeyCode!=45;setTimeout(()=>{e.focus(),w.parentNode&&w.parentNode.removeChild(w),S?doPaste(e,w.value,null,E,t):doPaste(e,w.textContent,w.innerHTML,E,t)},50)}function doPaste(e,t,S,w,E){let D=parseFromClipboard(e,t,S,w,e.state.selection.$from);if(e.someProp(`handlePaste`,t=>t(e,E,D||Slice.empty)))return!0;if(!D)return!1;let O=sliceSingleNode(D),k=O?e.state.tr.replaceSelectionWith(O,w):e.state.tr.replaceSelection(D);return e.dispatch(k.scrollIntoView().setMeta(`paste`,!0).setMeta(`uiEvent`,`paste`)),!0}function getText(e){let t=e.getData(`text/plain`)||e.getData(`Text`);if(t)return t;let S=e.getData(`text/uri-list`);return S?S.replace(/\r?\n/g,` `):``}editHandlers.paste=(e,t)=>{let S=t;if(e.composing&&!android)return;let w=brokenClipboardAPI?null:S.clipboardData,E=e.input.shiftKey&&e.input.lastKeyCode!=45;w&&doPaste(e,getText(w),w.getData(`text/html`),E,S)?S.preventDefault():capturePaste(e,S)};var Dragging=class{constructor(e,t,S){this.slice=e,this.move=t,this.node=S}};const dragCopyModifier=mac$2?`altKey`:`ctrlKey`;function dragMoves(e,t){let S;return e.someProp(`dragCopies`,e=>{S||=e(t)}),S==null?!t[dragCopyModifier]:!S}handlers.dragstart=(e,t)=>{let S=t,w=e.input.mouseDown;if(w&&w.done(),!S.dataTransfer)return;let E=e.state.selection,D=E.empty?null:e.posAtCoords(eventCoords(S)),O;if(!(D&&D.pos>=E.from&&D.pos<=(E instanceof NodeSelection?E.to-1:E.to))){if(w&&w.mightDrag)O=NodeSelection.create(e.state.doc,w.mightDrag.pos);else if(S.target&&S.target.nodeType==1){let t=e.docView.nearestDesc(S.target,!0);t&&t.node.type.spec.draggable&&t!=e.docView&&(O=NodeSelection.create(e.state.doc,t.posBefore))}}let{dom:k,text:j,slice:F}=serializeForClipboard(e,(O||e.state.selection).content());(!S.dataTransfer.files.length||!chrome||chrome_version>120)&&S.dataTransfer.clearData(),S.dataTransfer.setData(brokenClipboardAPI?`Text`:`text/html`,k.innerHTML),S.dataTransfer.effectAllowed=`copyMove`,brokenClipboardAPI||S.dataTransfer.setData(`text/plain`,j),e.dragging=new Dragging(F,dragMoves(e,S),O)},handlers.dragend=e=>{let t=e.dragging;window.setTimeout(()=>{e.dragging==t&&(e.dragging=null)},50)},editHandlers.dragover=editHandlers.dragenter=(e,t)=>t.preventDefault(),editHandlers.drop=(e,t)=>{try{handleDrop(e,t,e.dragging)}finally{e.dragging=null}};function handleDrop(e,t,S){if(!t.dataTransfer)return;let w=e.posAtCoords(eventCoords(t));if(!w)return;let E=e.state.doc.resolve(w.pos),D=S&&S.slice;D?e.someProp(`transformPasted`,t=>{D=t(D,e,!1)}):D=parseFromClipboard(e,getText(t.dataTransfer),brokenClipboardAPI?null:t.dataTransfer.getData(`text/html`),!1,E);let O=!!(S&&dragMoves(e,t));if(e.someProp(`handleDrop`,S=>S(e,t,D||Slice.empty,O))){t.preventDefault();return}if(!D)return;t.preventDefault();let k=D?dropPoint(e.state.doc,E.pos,D):E.pos;k??=E.pos;let j=e.state.tr;if(O){let{node:e}=S;e?e.replace(j):j.deleteSelection()}let F=j.mapping.map(k),L=D.openStart==0&&D.openEnd==0&&D.content.childCount==1,B=j.doc;if(L?j.replaceRangeWith(F,F,D.content.firstChild):j.replaceRange(F,F,D),j.doc.eq(B))return;let H=j.doc.resolve(F);if(L&&NodeSelection.isSelectable(D.content.firstChild)&&H.nodeAfter&&H.nodeAfter.sameMarkup(D.content.firstChild))j.setSelection(new NodeSelection(H));else{let t=j.mapping.map(k);j.mapping.maps[j.mapping.maps.length-1].forEach((e,S,w,E)=>t=E),j.setSelection(selectionBetween(e,H,j.doc.resolve(t)))}e.focus(),e.dispatch(j.setMeta(`uiEvent`,`drop`))}handlers.focus=e=>{e.input.lastFocus=Date.now(),e.focused||(e.domObserver.stop(),e.dom.classList.add(`ProseMirror-focused`),e.domObserver.start(),e.focused=!0,setTimeout(()=>{e.docView&&e.hasFocus()&&!e.domObserver.currentSelection.eq(e.domSelectionRange())&&selectionToDOM(e)},20))},handlers.blur=(e,t)=>{let S=t;e.focused&&=(e.domObserver.stop(),e.dom.classList.remove(`ProseMirror-focused`),e.domObserver.start(),S.relatedTarget&&e.dom.contains(S.relatedTarget)&&e.domObserver.currentSelection.clear(),!1)},handlers.beforeinput=(e,t)=>{if(chrome&&android&&t.inputType==`deleteContentBackward`){e.domObserver.flushSoon();let{domChangeCount:t}=e.input;setTimeout(()=>{if(e.input.domChangeCount!=t||(e.dom.blur(),e.focus(),e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))))return;let{$cursor:S}=e.state.selection;S&&S.pos>0&&e.dispatch(e.state.tr.delete(S.pos-1,S.pos).scrollIntoView())},50)}};for(let e in editHandlers)handlers[e]=editHandlers[e];function compareObjs(e,t){if(e==t)return!0;for(let S in e)if(e[S]!==t[S])return!1;for(let S in t)if(!(S in e))return!1;return!0}var WidgetType=class e{constructor(e,t){this.toDOM=e,this.spec=t||noSpec,this.side=this.spec.side||0}map(e,t,S,w){let{pos:E,deleted:D}=e.mapResult(t.from+w,this.side<0?-1:1);return D?null:new Decoration(E-S,E-S,this)}valid(){return!0}eq(t){return this==t||t instanceof e&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&compareObjs(this.spec,t.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},InlineType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,S,w){let E=e.map(t.from+w,this.spec.inclusiveStart?-1:1)-S,D=e.map(t.to+w,this.spec.inclusiveEnd?1:-1)-S;return E>=D?null:new Decoration(E,D,this)}valid(e,t){return t.from<t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}static is(t){return t.type instanceof e}destroy(){}},NodeType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,S,w){let E=e.mapResult(t.from+w,1);if(E.deleted)return null;let D=e.mapResult(t.to+w,-1);return D.deleted||D.pos<=E.pos?null:new Decoration(E.pos-S,D.pos-S,this)}valid(e,t){let{index:S,offset:w}=e.content.findIndex(t.from),E;return w==t.from&&!(E=e.child(S)).isText&&w+E.nodeSize==t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}destroy(){}},Decoration=class e{constructor(e,t,S){this.from=e,this.to=t,this.type=S}copy(t,S){return new e(t,S,this.type)}eq(e,t=0){return this.type.eq(e.type)&&this.from+t==e.from&&this.to+t==e.to}map(e,t,S){return this.type.map(e,this,t,S)}static widget(t,S,w){return new e(t,t,new WidgetType(S,w))}static inline(t,S,w,E){return new e(t,S,new InlineType(w,E))}static node(t,S,w,E){return new e(t,S,new NodeType(w,E))}get spec(){return this.type.spec}get inline(){return this.type instanceof InlineType}get widget(){return this.type instanceof WidgetType}};const none=[],noSpec={};var DecorationSet=class e{constructor(e,t){this.local=e.length?e:none,this.children=t.length?t:none}static create(e,t){return t.length?buildTree(t,e,0,noSpec):empty$2}find(e,t,S){let w=[];return this.findInner(e??0,t??1e9,w,0,S),w}findInner(e,t,S,w,E){for(let D=0;D<this.local.length;D++){let O=this.local[D];O.from<=t&&O.to>=e&&(!E||E(O.spec))&&S.push(O.copy(O.from+w,O.to+w))}for(let D=0;D<this.children.length;D+=3)if(this.children[D]<t&&this.children[D+1]>e){let O=this.children[D]+1;this.children[D+2].findInner(e-O,t-O,S,w+O,E)}}map(e,t,S){return this==empty$2||e.maps.length==0?this:this.mapInner(e,t,0,0,S||noSpec)}mapInner(t,S,w,E,D){let O;for(let e=0;e<this.local.length;e++){let k=this.local[e].map(t,w,E);k&&k.type.valid(S,k)?(O||=[]).push(k):D.onRemove&&D.onRemove(this.local[e].spec)}return this.children.length?mapChildren(this.children,O||[],t,S,w,E,D):O?new e(O.sort(byPos),none):empty$2}add(t,S){return S.length?this==empty$2?e.create(t,S):this.addInner(t,S,0):this}addInner(t,S,w){let E,D=0;t.forEach((e,t)=>{let O=t+w,k;if(k=takeSpansForNode(S,e,O)){for(E||=this.children.slice();D<E.length&&E[D]<t;)D+=3;E[D]==t?E[D+2]=E[D+2].addInner(e,k,O+1):E.splice(D,0,t,t+e.nodeSize,buildTree(k,e,O+1,noSpec)),D+=3}});let O=moveSpans(D?withoutNulls(S):S,-w);for(let e=0;e<O.length;e++)O[e].type.valid(t,O[e])||O.splice(e--,1);return new e(O.length?this.local.concat(O).sort(byPos):this.local,E||this.children)}remove(e){return e.length==0||this==empty$2?this:this.removeInner(e,0)}removeInner(t,S){let w=this.children,E=this.local;for(let e=0;e<w.length;e+=3){let E,D=w[e]+S,O=w[e+1]+S;for(let e=0,S;e<t.length;e++)(S=t[e])&&S.from>D&&S.to<O&&(t[e]=null,(E||=[]).push(S));if(!E)continue;w==this.children&&(w=this.children.slice());let k=w[e+2].removeInner(E,D+1);k==empty$2?(w.splice(e,3),e-=3):w[e+2]=k}if(E.length){for(let e=0,w;e<t.length;e++)if(w=t[e])for(let e=0;e<E.length;e++)E[e].eq(w,S)&&(E==this.local&&(E=this.local.slice()),E.splice(e--,1))}return w==this.children&&E==this.local?this:E.length||w.length?new e(E,w):empty$2}forChild(t,S){if(this==empty$2)return this;if(S.isLeaf)return e.empty;let w,E;for(let e=0;e<this.children.length;e+=3)if(this.children[e]>=t){this.children[e]==t&&(w=this.children[e+2]);break}let D=t+1,O=D+S.content.size;for(let e=0;e<this.local.length;e++){let t=this.local[e];if(t.from<O&&t.to>D&&t.type instanceof InlineType){let e=Math.max(D,t.from)-D,S=Math.min(O,t.to)-D;e<S&&(E||=[]).push(t.copy(e,S))}}if(E){let t=new e(E.sort(byPos),none);return w?new DecorationGroup([t,w]):t}return w||empty$2}eq(t){if(this==t)return!0;if(!(t instanceof e)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let e=0;e<this.local.length;e++)if(!this.local[e].eq(t.local[e]))return!1;for(let e=0;e<this.children.length;e+=3)if(this.children[e]!=t.children[e]||this.children[e+1]!=t.children[e+1]||!this.children[e+2].eq(t.children[e+2]))return!1;return!0}locals(e){return removeOverlap(this.localsInner(e))}localsInner(e){if(this==empty$2)return none;if(e.inlineContent||!this.local.some(InlineType.is))return this.local;let t=[];for(let e=0;e<this.local.length;e++)this.local[e].type instanceof InlineType||t.push(this.local[e]);return t}forEachSet(e){e(this)}};DecorationSet.empty=new DecorationSet([],[]),DecorationSet.removeOverlap=removeOverlap;const empty$2=DecorationSet.empty;var DecorationGroup=class e{constructor(e){this.members=e}map(t,S){let w=this.members.map(e=>e.map(t,S,noSpec));return e.from(w)}forChild(t,S){if(S.isLeaf)return DecorationSet.empty;let w=[];for(let E=0;E<this.members.length;E++){let D=this.members[E].forChild(t,S);D!=empty$2&&(D instanceof e?w=w.concat(D.members):w.push(D))}return e.from(w)}eq(t){if(!(t instanceof e)||t.members.length!=this.members.length)return!1;for(let e=0;e<this.members.length;e++)if(!this.members[e].eq(t.members[e]))return!1;return!0}locals(e){let t,S=!0;for(let w=0;w<this.members.length;w++){let E=this.members[w].localsInner(e);if(E.length)if(!t)t=E;else{S&&=(t=t.slice(),!1);for(let e=0;e<E.length;e++)t.push(E[e])}}return t?removeOverlap(S?t:t.sort(byPos)):none}static from(t){switch(t.length){case 0:return empty$2;case 1:return t[0];default:return new e(t.every(e=>e instanceof DecorationSet)?t:t.reduce((e,t)=>e.concat(t instanceof DecorationSet?t:t.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}};function mapChildren(e,t,S,w,E,D,O){let k=e.slice();for(let e=0,t=D;e<S.maps.length;e++){let w=0;S.maps[e].forEach((e,S,E,D)=>{let O=D-E-(S-e);for(let E=0;E<k.length;E+=3){let D=k[E+1];if(D<0||e>D+t-w)continue;let j=k[E]+t-w;S>=j?k[E+1]=e<=j?-2:-1:e>=t&&O&&(k[E]+=O,k[E+1]+=O)}w+=O}),t=S.maps[e].map(t,-1)}let j=!1;for(let t=0;t<k.length;t+=3)if(k[t+1]<0){if(k[t+1]==-2){j=!0,k[t+1]=-1;continue}let F=S.map(e[t]+D),L=F-E;if(L<0||L>=w.content.size){j=!0;continue}let B=S.map(e[t+1]+D,-1)-E,{index:H,offset:q}=w.content.findIndex(L),J=w.maybeChild(H);if(J&&q==L&&q+J.nodeSize==B){let w=k[t+2].mapInner(S,J,F+1,e[t]+D+1,O);w==empty$2?(k[t+1]=-2,j=!0):(k[t]=L,k[t+1]=B,k[t+2]=w)}else j=!0}if(j){let j=buildTree(mapAndGatherRemainingDecorations(k,e,t,S,E,D,O),w,0,O);t=j.local;for(let e=0;e<k.length;e+=3)k[e+1]<0&&(k.splice(e,3),e-=3);for(let e=0,t=0;e<j.children.length;e+=3){let S=j.children[e];for(;t<k.length&&k[t]<S;)t+=3;k.splice(t,0,j.children[e],j.children[e+1],j.children[e+2])}}return new DecorationSet(t.sort(byPos),k)}function moveSpans(e,t){if(!t||!e.length)return e;let S=[];for(let w=0;w<e.length;w++){let E=e[w];S.push(new Decoration(E.from+t,E.to+t,E.type))}return S}function mapAndGatherRemainingDecorations(e,t,S,w,E,D,O){function k(e,t){for(let D=0;D<e.local.length;D++){let k=e.local[D].map(w,E,t);k?S.push(k):O.onRemove&&O.onRemove(e.local[D].spec)}for(let S=0;S<e.children.length;S+=3)k(e.children[S+2],e.children[S]+t+1)}for(let S=0;S<e.length;S+=3)e[S+1]==-1&&k(e[S+2],t[S]+D+1);return S}function takeSpansForNode(e,t,S){if(t.isLeaf)return null;let w=S+t.nodeSize,E=null;for(let t=0,D;t<e.length;t++)(D=e[t])&&D.from>S&&D.to<w&&((E||=[]).push(D),e[t]=null);return E}function withoutNulls(e){let t=[];for(let S=0;S<e.length;S++)e[S]!=null&&t.push(e[S]);return t}function buildTree(e,t,S,w){let E=[],D=!1;t.forEach((t,O)=>{let k=takeSpansForNode(e,t,O+S);if(k){D=!0;let e=buildTree(k,t,S+O+1,w);e!=empty$2&&E.push(O,O+t.nodeSize,e)}});let O=moveSpans(D?withoutNulls(e):e,-S).sort(byPos);for(let e=0;e<O.length;e++)O[e].type.valid(t,O[e])||(w.onRemove&&w.onRemove(O[e].spec),O.splice(e--,1));return O.length||E.length?new DecorationSet(O,E):empty$2}function byPos(e,t){return e.from-t.from||e.to-t.to}function removeOverlap(e){let t=e;for(let S=0;S<t.length-1;S++){let w=t[S];if(w.from!=w.to)for(let E=S+1;E<t.length;E++){let D=t[E];if(D.from==w.from){D.to!=w.to&&(t==e&&(t=e.slice()),t[E]=D.copy(D.from,w.to),insertAhead(t,E+1,D.copy(w.to,D.to)));continue}else{D.from<w.to&&(t==e&&(t=e.slice()),t[S]=w.copy(w.from,D.from),insertAhead(t,E,w.copy(D.from,w.to)));break}}}return t}function insertAhead(e,t,S){for(;t<e.length&&byPos(S,e[t])>0;)t++;e.splice(t,0,S)}function viewDecorations(e){let t=[];return e.someProp(`decorations`,S=>{let w=S(e.state);w&&w!=empty$2&&t.push(w)}),e.cursorWrapper&&t.push(DecorationSet.create(e.state.doc,[e.cursorWrapper.deco])),DecorationGroup.from(t)}const observeOptions={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},useCharData=ie$2&&ie_version<=11;var SelectionState=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},DOMObserver=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new SelectionState,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(t=>{for(let e=0;e<t.length;e++)this.queue.push(t[e]);ie$2&&ie_version<=11&&t.some(e=>e.type==`childList`&&e.removedNodes.length||e.type==`characterData`&&e.oldValue.length>e.target.nodeValue.length)?this.flushSoon():safari&&e.composing&&t.some(e=>e.type==`childList`&&e.target.nodeName==`TR`)?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),useCharData&&(this.onCharData=e=>{this.queue.push({target:e.target,type:`characterData`,oldValue:e.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,observeOptions)),this.onCharData&&this.view.dom.addEventListener(`DOMCharacterDataModified`,this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;t<e.length;t++)this.queue.push(e[t]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener(`DOMCharacterDataModified`,this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener(`selectionchange`,this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener(`selectionchange`,this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(hasFocusAndSelection(this.view)){if(this.suppressingSelectionUpdates)return selectionToDOM(this.view);if(ie$2&&ie_version<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&isEquivalentPosition(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,S;for(let S=e.focusNode;S;S=parentNode(S))t.add(S);for(let w=e.anchorNode;w;w=parentNode(w))if(t.has(w)){S=w;break}let w=S&&this.view.docView.nearestDesc(S);if(w&&w.ignoreMutation({type:`selection`,target:S.nodeType==3?S.parentNode:S}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let S=e.domSelectionRange(),w=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(S)&&hasFocusAndSelection(e)&&!this.ignoreSelectionChange(S),E=-1,D=-1,O=!1,k=[];if(e.editable)for(let e=0;e<t.length;e++){let S=this.registerMutation(t[e],k);S&&(E=E<0?S.from:Math.min(S.from,E),D=D<0?S.to:Math.max(S.to,D),S.typeOver&&(O=!0))}if(k.some(e=>e.nodeName==`BR`)&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let e of k)if(e.nodeName==`BR`&&e.parentNode){let t=e.nextSibling;for(;t&&t.nodeType==1;){if(t.contentEditable==`false`){e.parentNode.removeChild(e);break}t=t.firstChild}}}else if(gecko&&k.length){let t=k.filter(e=>e.nodeName==`BR`);if(t.length==2){let[e,S]=t;e.parentNode&&e.parentNode.parentNode==S.parentNode?S.remove():e.remove()}else{let{focusNode:S}=this.currentSelection;for(let w of t){let t=w.parentNode;t&&t.nodeName==`LI`&&(!S||blockParent(e,S)!=t)&&w.remove()}}}let j=null;E<0&&w&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&selectionCollapsed(S)&&(j=selectionFromDOM(e))&&j.eq(Selection$1.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,selectionToDOM(e),this.currentSelection.set(S),e.scrollToSelection()):(E>-1||w)&&(E>-1&&(e.docView.markDirty(E,D),checkCSS(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,fixUpBadSafariComposition(e,k)),this.handleDOMChange(E,D,O,k),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(S)||selectionToDOM(e),this.currentSelection.set(S))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let S=this.view.docView.nearestDesc(e.target);if(e.type==`attributes`&&(S==this.view.docView||e.attributeName==`contenteditable`||e.attributeName==`style`&&!e.oldValue&&!e.target.getAttribute(`style`))||!S||S.ignoreMutation(e))return null;if(e.type==`childList`){for(let S=0;S<e.addedNodes.length;S++){let w=e.addedNodes[S];t.push(w),w.nodeType==3&&(this.lastChangedTextNode=w)}if(S.contentDOM&&S.contentDOM!=S.dom&&!S.contentDOM.contains(e.target))return{from:S.posBefore,to:S.posAfter};let w=e.previousSibling,E=e.nextSibling;if(ie$2&&ie_version<=11&&e.addedNodes.length)for(let t=0;t<e.addedNodes.length;t++){let{previousSibling:S,nextSibling:D}=e.addedNodes[t];(!S||Array.prototype.indexOf.call(e.addedNodes,S)<0)&&(w=S),(!D||Array.prototype.indexOf.call(e.addedNodes,D)<0)&&(E=D)}let D=w&&w.parentNode==e.target?domIndex(w)+1:0,O=S.localPosFromDOM(e.target,D,-1),k=E&&E.parentNode==e.target?domIndex(E):e.target.childNodes.length;return{from:O,to:S.localPosFromDOM(e.target,k,1)}}else if(e.type==`attributes`)return{from:S.posAtStart-S.border,to:S.posAtEnd+S.border};else return this.lastChangedTextNode=e.target,{from:S.posAtStart,to:S.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}}};let cssChecked=new WeakMap,cssCheckWarned=!1;function checkCSS(e){if(!cssChecked.has(e)&&(cssChecked.set(e,null),[`normal`,`nowrap`,`pre-line`].indexOf(getComputedStyle(e.dom).whiteSpace)!==-1)){if(e.requiresGeckoHackNode=gecko,cssCheckWarned)return;console.warn(`ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.`),cssCheckWarned=!0}}function rangeToSelectionRange(e,t){let S=t.startContainer,w=t.startOffset,E=t.endContainer,D=t.endOffset,O=e.domAtPos(e.state.selection.anchor);return isEquivalentPosition(O.node,O.offset,E,D)&&([S,w,E,D]=[E,D,S,w]),{anchorNode:S,anchorOffset:w,focusNode:E,focusOffset:D}}function safariShadowSelectionRange(e,t){if(t.getComposedRanges){let S=t.getComposedRanges(e.root)[0];if(S)return rangeToSelectionRange(e,S)}let S;function w(e){e.preventDefault(),e.stopImmediatePropagation(),S=e.getTargetRanges()[0]}return e.dom.addEventListener(`beforeinput`,w,!0),document.execCommand(`indent`),e.dom.removeEventListener(`beforeinput`,w,!0),S?rangeToSelectionRange(e,S):null}function blockParent(e,t){for(let S=t.parentNode;S&&S!=e.dom;S=S.parentNode){let t=e.docView.nearestDesc(S,!0);if(t&&t.node.isBlock)return S}return null}function fixUpBadSafariComposition(e,t){var S;let{focusNode:w,focusOffset:E}=e.domSelectionRange();for(let S of t)if(S.parentNode?.nodeName==`TR`){let t=S.nextSibling;for(;t&&t.nodeName!=`TD`&&t.nodeName!=`TH`;)t=t.nextSibling;if(t){let D=t;for(;;){let e=D.firstChild;if(!e||e.nodeType!=1||e.contentEditable==`false`||/^(BR|IMG)$/.test(e.nodeName))break;D=e}D.insertBefore(S,D.firstChild),w==S&&e.domSelection().collapse(S,E)}else S.parentNode.removeChild(S)}}function parseBetween(e,t,S){let{node:w,fromOffset:E,toOffset:D,from:O,to:k}=e.docView.parseRange(t,S),j=e.domSelectionRange(),F,L=j.anchorNode;if(L&&e.dom.contains(L.nodeType==1?L:L.parentNode)&&(F=[{node:L,offset:j.anchorOffset}],selectionCollapsed(j)||F.push({node:j.focusNode,offset:j.focusOffset})),chrome&&e.input.lastKeyCode===8)for(let e=D;e>E;e--){let t=w.childNodes[e-1],S=t.pmViewDesc;if(t.nodeName==`BR`&&!S){D=e;break}if(!S||S.size)break}let B=e.state.doc,H=e.someProp(`domParser`)||DOMParser.fromSchema(e.state.schema),q=B.resolve(O),J=null,Y=H.parse(w,{topNode:q.parent,topMatch:q.parent.contentMatchAt(q.index()),topOpen:!0,from:E,to:D,preserveWhitespace:q.parent.type.whitespace==`pre`?`full`:!0,findPositions:F,ruleFromNode,context:q});if(F&&F[0].pos!=null){let e=F[0].pos,t=F[1]&&F[1].pos;t??=e,J={anchor:e+O,head:t+O}}return{doc:Y,sel:J,from:O,to:k}}function ruleFromNode(e){let t=e.pmViewDesc;if(t)return t.parseRule();if(e.nodeName==`BR`&&e.parentNode){if(safari&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let e=document.createElement(`div`);return e.appendChild(document.createElement(`li`)),{skip:e}}else if(e.parentNode.lastChild==e||safari&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName==`IMG`&&e.getAttribute(`mark-placeholder`))return{ignore:!0};return null}const isInline=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function readDOMChange(e,t,S,w,E){let D=e.input.compositionPendingChanges||(e.composing?e.input.compositionID:0);if(e.input.compositionPendingChanges=0,t<0){let t=e.input.lastSelectionTime>Date.now()-50?e.input.lastSelectionOrigin:null,S=selectionFromDOM(e,t);if(S&&!e.state.selection.eq(S)){if(chrome&&android&&e.input.lastKeyCode===13&&Date.now()-100<e.input.lastKeyCodeTime&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))))return;let w=e.state.tr.setSelection(S);t==`pointer`?w.setMeta(`pointer`,!0):t==`key`&&w.scrollIntoView(),D&&w.setMeta(`composition`,D),e.dispatch(w)}return}let O=e.state.doc.resolve(t),k=O.sharedDepth(S);t=O.before(k+1),S=e.state.doc.resolve(S).after(k+1);let j=e.state.selection,F=parseBetween(e,t,S),L=e.state.doc,B=L.slice(F.from,F.to),H,q;e.input.lastKeyCode===8&&Date.now()-100<e.input.lastKeyCodeTime?(H=e.state.selection.to,q=`end`):(H=e.state.selection.from,q=`start`),e.input.lastKeyCode=null;let J=findDiff(B.content,F.doc.content,F.from,H,q);if(J&&e.input.domChangeCount++,(ios&&e.input.lastIOSEnter>Date.now()-225||android)&&E.some(e=>e.nodeType==1&&!isInline.test(e.nodeName))&&(!J||J.endA>=J.endB)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(!J)if(w&&j instanceof TextSelection&&!j.empty&&j.$head.sameParent(j.$anchor)&&!e.composing&&!(F.sel&&F.sel.anchor!=F.sel.head))J={start:j.from,endA:j.to,endB:j.to};else{if(F.sel){let t=resolveSelection(e,e.state.doc,F.sel);if(t&&!t.eq(e.state.selection)){let S=e.state.tr.setSelection(t);D&&S.setMeta(`composition`,D),e.dispatch(S)}}return}e.state.selection.from<e.state.selection.to&&J.start==J.endB&&e.state.selection instanceof TextSelection&&(J.start>e.state.selection.from&&J.start<=e.state.selection.from+2&&e.state.selection.from>=F.from?J.start=e.state.selection.from:J.endA<e.state.selection.to&&J.endA>=e.state.selection.to-2&&e.state.selection.to<=F.to&&(J.endB+=e.state.selection.to-J.endA,J.endA=e.state.selection.to)),ie$2&&ie_version<=11&&J.endB==J.start+1&&J.endA==J.start&&J.start>F.from&&F.doc.textBetween(J.start-F.from-1,J.start-F.from+1)==` \xA0`&&(J.start--,J.endA--,J.endB--);let Y=F.doc.resolveNoCache(J.start-F.from),ee=F.doc.resolveNoCache(J.endB-F.from),te=L.resolve(J.start),ne=Y.sameParent(ee)&&Y.parent.inlineContent&&te.end()>=J.endA;if((ios&&e.input.lastIOSEnter>Date.now()-225&&(!ne||E.some(e=>e.nodeName==`DIV`||e.nodeName==`P`))||!ne&&Y.pos<F.doc.content.size&&(!Y.sameParent(ee)||!Y.parent.inlineContent)&&Y.pos<ee.pos&&!/\S/.test(F.doc.textBetween(Y.pos,ee.pos,``,``)))&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(e.state.selection.anchor>J.start&&looksLikeBackspace(L,J.start,J.endA,Y,ee)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))){android&&chrome&&e.domObserver.suppressSelectionUpdates();return}chrome&&J.endB==J.start&&(e.input.lastChromeDelete=Date.now()),android&&!ne&&Y.start()!=ee.start()&&ee.parentOffset==0&&Y.depth==ee.depth&&F.sel&&F.sel.anchor==F.sel.head&&F.sel.head==J.endA&&(J.endB-=2,ee=F.doc.resolveNoCache(J.endB-F.from),setTimeout(()=>{e.someProp(`handleKeyDown`,function(t){return t(e,keyEvent(13,`Enter`))})},20));let ae=J.start,oe=J.endA,se=t=>{let S=t||e.state.tr.replace(ae,oe,F.doc.slice(J.start-F.from,J.endB-F.from));if(F.sel){let t=resolveSelection(e,S.doc,F.sel);t&&!(chrome&&e.composing&&t.empty&&(J.start!=J.endB||e.input.lastChromeDelete<Date.now()-100)&&(t.head==ae||t.head==S.mapping.map(oe)-1)||ie$2&&t.empty&&t.head==ae)&&S.setSelection(t)}return D&&S.setMeta(`composition`,D),S.scrollIntoView()},ce;if(ne)if(Y.pos==ee.pos){ie$2&&ie_version<=11&&Y.parentOffset==0&&(e.domObserver.suppressSelectionUpdates(),setTimeout(()=>selectionToDOM(e),20));let t=se(e.state.tr.delete(ae,oe)),S=L.resolve(J.start).marksAcross(L.resolve(J.endA));S&&t.ensureMarks(S),e.dispatch(t)}else if(J.endA==J.endB&&(ce=isMarkChange(Y.parent.content.cut(Y.parentOffset,ee.parentOffset),te.parent.content.cut(te.parentOffset,J.endA-te.start())))){let t=se(e.state.tr);ce.type==`add`?t.addMark(ae,oe,ce.mark):t.removeMark(ae,oe,ce.mark),e.dispatch(t)}else if(Y.parent.child(Y.index()).isText&&Y.index()==ee.index()-(ee.textOffset?0:1)){let t=Y.parent.textBetween(Y.parentOffset,ee.parentOffset),S=()=>se(e.state.tr.insertText(t,ae,oe));e.someProp(`handleTextInput`,w=>w(e,ae,oe,t,S))||e.dispatch(S())}else e.dispatch(se());else e.dispatch(se())}function resolveSelection(e,t,S){return Math.max(S.anchor,S.head)>t.content.size?null:selectionBetween(e,t.resolve(S.anchor),t.resolve(S.head))}function isMarkChange(e,t){let S=e.firstChild.marks,w=t.firstChild.marks,E=S,D=w,O,k,j;for(let e=0;e<w.length;e++)E=w[e].removeFromSet(E);for(let e=0;e<S.length;e++)D=S[e].removeFromSet(D);if(E.length==1&&D.length==0)k=E[0],O=`add`,j=e=>e.mark(k.addToSet(e.marks));else if(E.length==0&&D.length==1)k=D[0],O=`remove`,j=e=>e.mark(k.removeFromSet(e.marks));else return null;let F=[];for(let e=0;e<t.childCount;e++)F.push(j(t.child(e)));if(Fragment.from(F).eq(e))return{mark:k,type:O}}function looksLikeBackspace(e,t,S,w,E){if(S-t<=E.pos-w.pos||skipClosingAndOpening(w,!0,!1)<E.pos)return!1;let D=e.resolve(t);if(!w.parent.isTextblock){let e=D.nodeAfter;return e!=null&&S==t+e.nodeSize}if(D.parentOffset<D.parent.content.size||!D.parent.isTextblock)return!1;let O=e.resolve(skipClosingAndOpening(D,!0,!0));return!O.parent.isTextblock||O.pos>S||skipClosingAndOpening(O,!0,!1)<S?!1:w.parent.content.cut(w.parentOffset).eq(O.parent.content)}function skipClosingAndOpening(e,t,S){let w=e.depth,E=t?e.end():e.pos;for(;w>0&&(t||e.indexAfter(w)==e.node(w).childCount);)w--,E++,t=!1;if(S){let t=e.node(w).maybeChild(e.indexAfter(w));for(;t&&!t.isLeaf;)t=t.firstChild,E++}return E}function findDiff(e,t,S,w,E){let D=e.findDiffStart(t,S);if(D==null)return null;let{a:O,b:k}=e.findDiffEnd(t,S+e.size,S+t.size);if(E==`end`){let e=Math.max(0,D-Math.min(O,k));w-=O+e-D}if(O<D&&e.size<t.size){let e=w<=D&&w>=O?D-w:0;D-=e,D&&D<t.size&&isSurrogatePair$1(t.textBetween(D-1,D+1))&&(D+=e?1:-1),k=D+(k-O),O=D}else if(k<D){let t=w<=D&&w>=k?D-w:0;D-=t,D&&D<e.size&&isSurrogatePair$1(e.textBetween(D-1,D+1))&&(D+=t?1:-1),O=D+(O-k),k=D}return{start:D,endA:O,endB:k}}function isSurrogatePair$1(e){if(e.length!=2)return!1;let t=e.charCodeAt(0),S=e.charCodeAt(1);return t>=56320&&t<=57343&&S>=55296&&S<=56319}var EditorView=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new InputState,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(checkStateComponent),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement(`div`),e&&(e.appendChild?e.appendChild(this.dom):typeof e==`function`?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=getEditable(this),updateCursorWrapper(this),this.nodeViews=buildNodeViews(this),this.docView=docViewDesc(this.state.doc,computeDocDeco(this),viewDecorations(this),this.dom,this),this.domObserver=new DOMObserver(this,(e,t,S,w)=>readDOMChange(this,e,t,S,w)),this.domObserver.start(),initInput(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ensureListeners(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(checkStateComponent),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let e in this._props)t[e]=this._props[e];t.state=this.state;for(let S in e)t[S]=e[S];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var S;let w=this.state,E=!1,D=!1;e.storedMarks&&this.composing&&(clearComposition(this),D=!0),this.state=e;let O=w.plugins!=e.plugins||this._props.plugins!=t.plugins;if(O||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let e=buildNodeViews(this);changedNodeViews(e,this.nodeViews)&&(this.nodeViews=e,E=!0)}(O||t.handleDOMEvents!=this._props.handleDOMEvents)&&ensureListeners(this),this.editable=getEditable(this),updateCursorWrapper(this);let k=viewDecorations(this),j=computeDocDeco(this),F=w.plugins!=e.plugins&&!w.doc.eq(e.doc)?`reset`:e.scrollToSelection>w.scrollToSelection?`to selection`:`preserve`,L=E||!this.docView.matchesNode(e.doc,j,k);(L||!e.selection.eq(w.selection))&&(D=!0);let B=F==`preserve`&&D&&this.dom.style.overflowAnchor==null&&storeScrollPos(this);if(D){this.domObserver.stop();let t=L&&(ie$2||chrome)&&!this.composing&&!w.selection.empty&&!e.selection.empty&&selectionContextChanged(w.selection,e.selection);if(L){let S=chrome?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=findCompositionNode(this)),(E||!this.docView.update(e.doc,j,k,this))&&(this.docView.updateOuterDeco(j),this.docView.destroy(),this.docView=docViewDesc(e.doc,j,k,this.dom,this)),S&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(t=!0)}t||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&anchorInRightPlace(this))?selectionToDOM(this,t):(syncNodeSelection(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(w),this.dragging?.node&&!w.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,w),F==`reset`?this.dom.scrollTop=0:F==`to selection`?this.scrollToSelection():B&&resetScrollPos(B)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))&&!this.someProp(`handleScrollToSelection`,e=>e(this)))if(this.state.selection instanceof NodeSelection){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&scrollRectIntoView(this,t.getBoundingClientRect(),e)}else scrollRectIntoView(this,this.coordsAtPos(this.state.selection.head,1),e)}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e<this.directPlugins.length;e++){let t=this.directPlugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let t=this.state.plugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let S=this.pluginViews[t];S.update&&S.update(this,e)}}updateDraggedNode(e,t){let S=e.node,w=-1;if(S.from<this.state.doc.content.size&&this.state.doc.nodeAt(S.from)==S.node)w=S.from;else{let e=S.from+(this.state.doc.content.size-t.doc.content.size);(e>0&&e<this.state.doc.content.size&&this.state.doc.nodeAt(e))==S.node&&(w=e)}this.dragging=new Dragging(e.slice,e.move,w<0?void 0:NodeSelection.create(this.state.doc,w))}someProp(e,t){let S=this._props&&this._props[e],w;if(S!=null&&(w=t?t(S):S))return w;for(let S=0;S<this.directPlugins.length;S++){let E=this.directPlugins[S].props[e];if(E!=null&&(w=t?t(E):E))return w}let E=this.state.plugins;if(E)for(let S=0;S<E.length;S++){let D=E[S].props[e];if(D!=null&&(w=t?t(D):D))return w}}hasFocus(){if(ie$2){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable==`false`)return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&focusPreventScroll(this.dom),selectionToDOM(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let e=this.dom.parentNode;e;e=e.parentNode)if(e.nodeType==9||e.nodeType==11&&e.host)return e.getSelection||(Object.getPrototypeOf(e).getSelection=()=>e.ownerDocument.getSelection()),this._root=e}return e||document}updateRoot(){this._root=null}posAtCoords(e){return posAtCoords(this,e)}coordsAtPos(e,t=1){return coordsAtPos(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,S=-1){let w=this.docView.posFromDOM(e,t,S);if(w==null)throw RangeError(`DOM position not inside the editor`);return w}endOfTextblock(e,t){return endOfTextblock(this,t||this.state,e)}pasteHTML(e,t){return doPaste(this,``,e,!1,t||new ClipboardEvent(`paste`))}pasteText(e,t){return doPaste(this,e,null,!0,t||new ClipboardEvent(`paste`))}serializeForClipboard(e){return serializeForClipboard(this,e)}destroy(){this.docView&&(destroyInput(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],viewDecorations(this),this),this.dom.textContent=``):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,clearReusedRange())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dispatchEvent(this,e)}domSelectionRange(){let e=this.domSelection();return e?safari&&this.root.nodeType===11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariShadowSelectionRange(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};EditorView.prototype.dispatch=function(e){let t=this._props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function computeDocDeco(e){let t=Object.create(null);return t.class=`ProseMirror`,t.contenteditable=String(e.editable),e.someProp(`attributes`,S=>{if(typeof S==`function`&&(S=S(e.state)),S)for(let e in S)e==`class`?t.class+=` `+S[e]:e==`style`?t.style=(t.style?t.style+`;`:``)+S[e]:!t[e]&&e!=`contenteditable`&&e!=`nodeName`&&(t[e]=String(S[e]))}),t.translate||=`no`,[Decoration.node(0,e.state.doc.content.size,t)]}function updateCursorWrapper(e){if(e.markCursor){let t=document.createElement(`img`);t.className=`ProseMirror-separator`,t.setAttribute(`mark-placeholder`,`true`),t.setAttribute(`alt`,``),e.cursorWrapper={dom:t,deco:Decoration.widget(e.state.selection.from,t,{raw:!0,marks:e.markCursor})}}else e.cursorWrapper=null}function getEditable(e){return!e.someProp(`editable`,t=>t(e.state)===!1)}function selectionContextChanged(e,t){let S=Math.min(e.$anchor.sharedDepth(e.head),t.$anchor.sharedDepth(t.head));return e.$anchor.start(S)!=t.$anchor.start(S)}function buildNodeViews(e){let t=Object.create(null);function S(e){for(let S in e)Object.prototype.hasOwnProperty.call(t,S)||(t[S]=e[S])}return e.someProp(`nodeViews`,S),e.someProp(`markViews`,S),t}function changedNodeViews(e,t){let S=0,w=0;for(let w in e){if(e[w]!=t[w])return!0;S++}for(let e in t)w++;return S!=w}function checkStateComponent(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw RangeError(`Plugins passed directly to the view must not have a state component`)}for(var base$1={8:`Backspace`,9:`Tab`,10:`Enter`,12:`NumLock`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,44:`PrintScreen`,45:`Insert`,46:`Delete`,59:`;`,61:`=`,91:`Meta`,92:`Meta`,106:`*`,107:`+`,108:`,`,109:`-`,110:`.`,111:`/`,144:`NumLock`,145:`ScrollLock`,160:`Shift`,161:`Shift`,162:`Control`,163:`Control`,164:`Alt`,165:`Alt`,173:`-`,186:`;`,187:`=`,188:`,`,189:`-`,190:`.`,191:`/`,192:"`",219:`[`,220:`\\`,221:`]`,222:`'`},shift={48:`)`,49:`!`,50:`@`,51:`#`,52:`$`,53:`%`,54:`^`,55:`&`,56:`*`,57:`(`,59:`:`,61:`+`,173:`_`,186:`:`,187:`+`,188:`<`,189:`_`,190:`>`,191:`?`,192:`~`,219:`{`,220:`|`,221:`}`,222:`"`},mac$1=typeof navigator<`u`&&/Mac/.test(navigator.platform),ie$1=typeof navigator<`u`&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base$1[48+i]=base$1[96+i]=String(i);for(var i=1;i<=24;i++)base$1[i+111]=`F`+i;for(var i=65;i<=90;i++)base$1[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code$2 in base$1)shift.hasOwnProperty(code$2)||(shift[code$2]=base$1[code$2]);function keyName(e){var t=!(mac$1&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||ie$1&&e.shiftKey&&e.key&&e.key.length==1||e.key==`Unidentified`)&&e.key||(e.shiftKey?shift:base$1)[e.keyCode]||e.key||`Unidentified`;return t==`Esc`&&(t=`Escape`),t==`Del`&&(t=`Delete`),t==`Left`&&(t=`ArrowLeft`),t==`Up`&&(t=`ArrowUp`),t==`Right`&&(t=`ArrowRight`),t==`Down`&&(t=`ArrowDown`),t}const mac=typeof navigator<`u`&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),windows=typeof navigator<`u`&&/Win/.test(navigator.platform);function normalizeKeyName$1(e){let t=e.split(/-(?!$)/),S=t[t.length-1];S==`Space`&&(S=` `);let w,E,D,O;for(let e=0;e<t.length-1;e++){let S=t[e];if(/^(cmd|meta|m)$/i.test(S))O=!0;else if(/^a(lt)?$/i.test(S))w=!0;else if(/^(c|ctrl|control)$/i.test(S))E=!0;else if(/^s(hift)?$/i.test(S))D=!0;else if(/^mod$/i.test(S))mac?O=!0:E=!0;else throw Error(`Unrecognized modifier name: `+S)}return w&&(S=`Alt-`+S),E&&(S=`Ctrl-`+S),O&&(S=`Meta-`+S),D&&(S=`Shift-`+S),S}function normalize$4(e){let t=Object.create(null);for(let S in e)t[normalizeKeyName$1(S)]=e[S];return t}function modifiers(e,t,S=!0){return t.altKey&&(e=`Alt-`+e),t.ctrlKey&&(e=`Ctrl-`+e),t.metaKey&&(e=`Meta-`+e),S&&t.shiftKey&&(e=`Shift-`+e),e}function keymap(e){return new Plugin({props:{handleKeyDown:keydownHandler(e)}})}function keydownHandler(e){let t=normalize$4(e);return function(e,S){let w=keyName(S),E,D=t[modifiers(w,S)];if(D&&D(e.state,e.dispatch,e))return!0;if(w.length==1&&w!=` `){if(S.shiftKey){let E=t[modifiers(w,S,!1)];if(E&&E(e.state,e.dispatch,e))return!0}if((S.altKey||S.metaKey||S.ctrlKey)&&!(windows&&S.ctrlKey&&S.altKey)&&(E=base$1[S.keyCode])&&E!=w){let w=t[modifiers(E,S)];if(w&&w(e.state,e.dispatch,e))return!0}}return!1}}var __defProp$2=Object.defineProperty,__export$1=(e,t)=>{for(var S in t)__defProp$2(e,S,{get:t[S],enumerable:!0})};function createChainableState(e){let{state:t,transaction:S}=e,{selection:w}=S,{doc:E}=S,{storedMarks:D}=S;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return D},get selection(){return w},get doc(){return E},get tr(){return w=S.selection,E=S.doc,D=S.storedMarks,S}}}var CommandManager=class{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){let{rawCommands:e,editor:t,state:S}=this,{view:w}=t,{tr:E}=S,D=this.buildProps(E);return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,(...e)=>{let S=t(...e)(D);return!E.getMeta(`preventDispatch`)&&!this.hasCustomState&&w.dispatch(E),S}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){let{rawCommands:S,editor:w,state:E}=this,{view:D}=w,O=[],k=!!e,j=e||E.tr,F=()=>(!k&&t&&!j.getMeta(`preventDispatch`)&&!this.hasCustomState&&D.dispatch(j),O.every(e=>e===!0)),L={...Object.fromEntries(Object.entries(S).map(([e,S])=>[e,(...e)=>{let w=this.buildProps(j,t),E=S(...e)(w);return O.push(E),L}])),run:F};return L}createCan(e){let{rawCommands:t,state:S}=this,w=!1,E=e||S.tr,D=this.buildProps(E,!1);return{...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>t(...e)({...D,dispatch:void 0})])),chain:()=>this.createChain(E,!1)}}buildProps(e,t=!0){let{rawCommands:S,editor:w,state:E}=this,{view:D}=w,O={tr:e,editor:w,view:D,state:createChainableState({state:E,transaction:e}),dispatch:t?()=>void 0:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(S).map(([e,t])=>[e,(...e)=>t(...e)(O)]))}};return O}},commands_exports={};__export$1(commands_exports,{blur:()=>blur,clearContent:()=>clearContent,clearNodes:()=>clearNodes,command:()=>command,createParagraphNear:()=>createParagraphNear,cut:()=>cut,deleteCurrentNode:()=>deleteCurrentNode,deleteNode:()=>deleteNode,deleteRange:()=>deleteRange,deleteSelection:()=>deleteSelection,enter:()=>enter,exitCode:()=>exitCode,extendMarkRange:()=>extendMarkRange,first:()=>first,focus:()=>focus,forEach:()=>forEach$1,insertContent:()=>insertContent,insertContentAt:()=>insertContentAt,joinBackward:()=>joinBackward,joinDown:()=>joinDown,joinForward:()=>joinForward,joinItemBackward:()=>joinItemBackward,joinItemForward:()=>joinItemForward,joinTextblockBackward:()=>joinTextblockBackward,joinTextblockForward:()=>joinTextblockForward,joinUp:()=>joinUp,keyboardShortcut:()=>keyboardShortcut,lift:()=>lift,liftEmptyBlock:()=>liftEmptyBlock,liftListItem:()=>liftListItem,newlineInCode:()=>newlineInCode,resetAttributes:()=>resetAttributes,scrollIntoView:()=>scrollIntoView,selectAll:()=>selectAll,selectNodeBackward:()=>selectNodeBackward,selectNodeForward:()=>selectNodeForward,selectParentNode:()=>selectParentNode,selectTextblockEnd:()=>selectTextblockEnd,selectTextblockStart:()=>selectTextblockStart,setContent:()=>setContent,setMark:()=>setMark,setMeta:()=>setMeta,setNode:()=>setNode,setNodeSelection:()=>setNodeSelection,setTextDirection:()=>setTextDirection,setTextSelection:()=>setTextSelection,sinkListItem:()=>sinkListItem,splitBlock:()=>splitBlock,splitListItem:()=>splitListItem,toggleList:()=>toggleList,toggleMark:()=>toggleMark,toggleNode:()=>toggleNode,toggleWrap:()=>toggleWrap,undoInputRule:()=>undoInputRule,unsetAllMarks:()=>unsetAllMarks,unsetMark:()=>unsetMark,unsetTextDirection:()=>unsetTextDirection,updateAttributes:()=>updateAttributes,wrapIn:()=>wrapIn,wrapInList:()=>wrapInList});var blur=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var S;e.isDestroyed||(t.dom.blur(),(S=window==null?void 0:window.getSelection())==null||S.removeAllRanges())}),!0),clearContent=(e=!0)=>({commands:t})=>t.setContent(``,{emitUpdate:e}),clearNodes=()=>({state:e,tr:t,dispatch:S})=>{let{selection:w}=t,{ranges:E}=w;return S&&E.forEach(({$from:S,$to:w})=>{e.doc.nodesBetween(S.pos,w.pos,(e,S)=>{if(e.type.isText)return;let{doc:w,mapping:E}=t,D=w.resolve(E.map(S)),O=w.resolve(E.map(S+e.nodeSize)),k=D.blockRange(O);if(!k)return;let j=liftTarget(k);if(e.type.isTextblock){let{defaultType:e}=D.parent.contentMatchAt(D.index());t.setNodeMarkup(k.start,e)}(j||j===0)&&t.lift(k,j)})}),!0},command=e=>t=>e(t),createParagraphNear=()=>({state:e,dispatch:t})=>createParagraphNear$1(e,t),cut=(e,t)=>({editor:S,tr:w})=>{let{state:E}=S,D=E.doc.slice(e.from,e.to);w.deleteRange(e.from,e.to);let O=w.mapping.map(t);return w.insert(O,D.content),w.setSelection(new TextSelection(w.doc.resolve(Math.max(O-1,0)))),!0},deleteCurrentNode=()=>({tr:e,dispatch:t})=>{let{selection:S}=e,w=S.$anchor.node();if(w.content.size>0)return!1;let E=e.selection.$anchor;for(let S=E.depth;S>0;--S)if(E.node(S).type===w.type){if(t){let t=E.before(S),w=E.after(S);e.delete(t,w).scrollIntoView()}return!0}return!1};function getNodeType(e,t){if(typeof e==`string`){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}var deleteNode=e=>({tr:t,state:S,dispatch:w})=>{let E=getNodeType(e,S.schema),D=t.selection.$anchor;for(let e=D.depth;e>0;--e)if(D.node(e).type===E){if(w){let S=D.before(e),w=D.after(e);t.delete(S,w).scrollIntoView()}return!0}return!1},deleteRange=e=>({tr:t,dispatch:S})=>{let{from:w,to:E}=e;return S&&t.delete(w,E),!0},deleteSelection=()=>({state:e,dispatch:t})=>deleteSelection$1(e,t),enter=()=>({commands:e})=>e.keyboardShortcut(`Enter`),exitCode=()=>({state:e,dispatch:t})=>exitCode$1(e,t);function isRegExp(e){return Object.prototype.toString.call(e)===`[object RegExp]`}function objectIncludes(e,t,S={strict:!0}){let w=Object.keys(t);return w.length?w.every(w=>S.strict?t[w]===e[w]:isRegExp(t[w])?t[w].test(e[w]):t[w]===e[w]):!0}function findMarkInSet(e,t,S={}){return e.find(e=>e.type===t&&objectIncludes(Object.fromEntries(Object.keys(S).map(t=>[t,e.attrs[t]])),S))}function isMarkInSet(e,t,S={}){return!!findMarkInSet(e,t,S)}function getMarkRange(e,t,S){if(!e||!t)return;let w=e.parent.childAfter(e.parentOffset);if((!w.node||!w.node.marks.some(e=>e.type===t))&&(w=e.parent.childBefore(e.parentOffset)),!w.node||!w.node.marks.some(e=>e.type===t))return;if(!S){let e=w.node.marks.find(e=>e.type===t);e&&(S=e.attrs)}if(!findMarkInSet([...w.node.marks],t,S))return;let E=w.index,D=e.start()+w.offset,O=E+1,k=D+w.node.nodeSize;for(;E>0&&isMarkInSet([...e.parent.child(E-1).marks],t,S);)--E,D-=e.parent.child(E).nodeSize;for(;O<e.parent.childCount&&isMarkInSet([...e.parent.child(O).marks],t,S);)k+=e.parent.child(O).nodeSize,O+=1;return{from:D,to:k}}function getMarkType(e,t){if(typeof e==`string`){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}var extendMarkRange=(e,t)=>({tr:S,state:w,dispatch:E})=>{let D=getMarkType(e,w.schema),{doc:O,selection:k}=S,{$from:j,from:F,to:L}=k;if(E){let e=getMarkRange(j,D,t);if(e&&e.from<=F&&e.to>=L){let t=TextSelection.create(O,e.from,e.to);S.setSelection(t)}}return!0},first=e=>t=>{let S=typeof e==`function`?e(t):e;for(let e=0;e<S.length;e+=1)if(S[e](t))return!0;return!1};function isTextSelection(e){return e instanceof TextSelection}function minMax(e=0,t=0,S=0){return Math.min(Math.max(e,t),S)}function resolveFocusPosition(e,t=null){if(!t)return null;let S=Selection$1.atStart(e),w=Selection$1.atEnd(e);if(t===`start`||t===!0)return S;if(t===`end`)return w;let E=S.from,D=w.to;return t===`all`?TextSelection.create(e,minMax(0,E,D),minMax(e.content.size,E,D)):TextSelection.create(e,minMax(t,E,D),minMax(t,E,D))}function isAndroid(){return navigator.platform===`Android`||/android/i.test(navigator.userAgent)}function isiOS(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}function isSafari(){return typeof navigator<`u`?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var focus=(e=null,t={})=>({editor:S,view:w,tr:E,dispatch:D})=>{t={scrollIntoView:!0,...t};let O=()=>{(isiOS()||isAndroid())&&w.dom.focus(),isSafari()&&!isiOS()&&!isAndroid()&&w.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{S.isDestroyed||(w.focus(),t?.scrollIntoView&&S.commands.scrollIntoView())})};try{if(w.hasFocus()&&e===null||e===!1)return!0}catch{return!1}if(D&&e===null&&!isTextSelection(S.state.selection))return O(),!0;let k=resolveFocusPosition(E.doc,e)||S.state.selection,j=S.state.selection.eq(k);return D&&(j||E.setSelection(k),j&&E.storedMarks&&E.setStoredMarks(E.storedMarks),O()),!0},forEach$1=(e,t)=>S=>e.every((e,w)=>t(e,{...S,index:w})),insertContent=(e,t)=>({tr:S,commands:w})=>w.insertContentAt({from:S.selection.from,to:S.selection.to},e,t),removeWhitespaces=e=>{let t=e.childNodes;for(let S=t.length-1;S>=0;--S){let w=t[S];w.nodeType===3&&w.nodeValue&&/^(\n\s\s|\n)$/.test(w.nodeValue)?e.removeChild(w):w.nodeType===1&&removeWhitespaces(w)}return e};function elementFromString(e){if(typeof window>`u`)throw Error(`[tiptap error]: there is no window object available, so this function cannot be used`);let t=`<body>${e}</body>`,S=new window.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces(S)}function createNodeFromContent(e,t,S){if(e instanceof Node||e instanceof Fragment)return e;S={slice:!0,parseOptions:{},...S};let w=typeof e==`object`&&!!e,E=typeof e==`string`;if(w)try{if(Array.isArray(e)&&e.length>0)return Fragment.fromArray(e.map(e=>t.nodeFromJSON(e)));let w=t.nodeFromJSON(e);return S.errorOnInvalidContent&&w.check(),w}catch(w){if(S.errorOnInvalidContent)throw Error(`[tiptap error]: Invalid JSON content`,{cause:w});return console.warn(`[tiptap warn]: Invalid content.`,`Passed value:`,e,`Error:`,w),createNodeFromContent(``,t,S)}if(E){if(S.errorOnInvalidContent){let w=!1,E=``,D=new Schema$1({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:`inline*`,group:`block`,parseDOM:[{tag:`*`,getAttrs:e=>(w=!0,E=typeof e==`string`?e:e.outerHTML,null)}]}})});if(S.slice?DOMParser.fromSchema(D).parseSlice(elementFromString(e),S.parseOptions):DOMParser.fromSchema(D).parse(elementFromString(e),S.parseOptions),S.errorOnInvalidContent&&w)throw Error(`[tiptap error]: Invalid HTML content`,{cause:Error(`Invalid element found: ${E}`)})}let w=DOMParser.fromSchema(t);return S.slice?w.parseSlice(elementFromString(e),S.parseOptions).content:w.parse(elementFromString(e),S.parseOptions)}return createNodeFromContent(``,t,S)}function selectionToInsertionEnd(e,t,S){let w=e.steps.length-1;if(w<t)return;let E=e.steps[w];if(!(E instanceof ReplaceStep||E instanceof ReplaceAroundStep))return;let D=e.mapping.maps[w],O=0;D.forEach((e,t,S,w)=>{O===0&&(O=w)}),e.setSelection(Selection$1.near(e.doc.resolve(O),S))}var isFragment=e=>!(`type`in e),insertContentAt=(e,t,S)=>({tr:w,dispatch:E,editor:D})=>{var O;if(E){S={parseOptions:D.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...S};let E,O=e=>{D.emit(`contentError`,{editor:D,error:e,disableCollaboration:()=>{`collaboration`in D.storage&&typeof D.storage.collaboration==`object`&&D.storage.collaboration&&(D.storage.collaboration.isDisabled=!0)}})},k={preserveWhitespace:`full`,...S.parseOptions};if(!S.errorOnInvalidContent&&!D.options.enableContentCheck&&D.options.emitContentError)try{createNodeFromContent(t,D.schema,{parseOptions:k,errorOnInvalidContent:!0})}catch(e){O(e)}try{E=createNodeFromContent(t,D.schema,{parseOptions:k,errorOnInvalidContent:S.errorOnInvalidContent??D.options.enableContentCheck})}catch(e){return O(e),!1}let{from:j,to:F}=typeof e==`number`?{from:e,to:e}:{from:e.from,to:e.to},L=!0,B=!0;if((isFragment(E)?E:[E]).forEach(e=>{e.check(),L=L?e.isText&&e.marks.length===0:!1,B=B?e.isBlock:!1}),j===F&&B){let{parent:e}=w.doc.resolve(j);e.isTextblock&&!e.type.spec.code&&!e.childCount&&(--j,F+=1)}let H;if(L){if(Array.isArray(t))H=t.map(e=>e.text||``).join(``);else if(t instanceof Fragment){let e=``;t.forEach(t=>{t.text&&(e+=t.text)}),H=e}else H=typeof t==`object`&&t&&t.text?t.text:t;w.insertText(H,j,F)}else{H=E;let e=w.doc.resolve(j),t=e.node(),S=e.parentOffset===0,D=t.isText||t.isTextblock,O=t.content.size>0;S&&D&&O&&B&&(j=Math.max(0,j-1)),w.replaceWith(j,F,H)}S.updateSelection&&selectionToInsertionEnd(w,w.steps.length-1,-1),S.applyInputRules&&w.setMeta(`applyInputRules`,{from:j,text:H}),S.applyPasteRules&&w.setMeta(`applyPasteRules`,{from:j,text:H})}return!0},joinUp=()=>({state:e,dispatch:t})=>joinUp$1(e,t),joinDown=()=>({state:e,dispatch:t})=>joinDown$1(e,t),joinBackward=()=>({state:e,dispatch:t})=>joinBackward$1(e,t),joinForward=()=>({state:e,dispatch:t})=>joinForward$1(e,t),joinItemBackward=()=>({state:e,dispatch:t,tr:S})=>{try{let w=joinPoint(e.doc,e.selection.$from.pos,-1);return w==null?!1:(S.join(w,2),t&&t(S),!0)}catch{return!1}},joinItemForward=()=>({state:e,dispatch:t,tr:S})=>{try{let w=joinPoint(e.doc,e.selection.$from.pos,1);return w==null?!1:(S.join(w,2),t&&t(S),!0)}catch{return!1}},joinTextblockBackward=()=>({state:e,dispatch:t})=>joinTextblockBackward$1(e,t),joinTextblockForward=()=>({state:e,dispatch:t})=>joinTextblockForward$1(e,t);function isMacOS(){return typeof navigator<`u`?/Mac/.test(navigator.platform):!1}function normalizeKeyName(e){let t=e.split(/-(?!$)/),S=t[t.length-1];S===`Space`&&(S=` `);let w,E,D,O;for(let e=0;e<t.length-1;e+=1){let S=t[e];if(/^(cmd|meta|m)$/i.test(S))O=!0;else if(/^a(lt)?$/i.test(S))w=!0;else if(/^(c|ctrl|control)$/i.test(S))E=!0;else if(/^s(hift)?$/i.test(S))D=!0;else if(/^mod$/i.test(S))isiOS()||isMacOS()?O=!0:E=!0;else throw Error(`Unrecognized modifier name: ${S}`)}return w&&(S=`Alt-${S}`),E&&(S=`Ctrl-${S}`),O&&(S=`Meta-${S}`),D&&(S=`Shift-${S}`),S}var keyboardShortcut=e=>({editor:t,view:S,tr:w,dispatch:E})=>{let D=normalizeKeyName(e).split(/-(?!$)/),O=D.find(e=>![`Alt`,`Ctrl`,`Meta`,`Shift`].includes(e)),k=new KeyboardEvent(`keydown`,{key:O===`Space`?` `:O,altKey:D.includes(`Alt`),ctrlKey:D.includes(`Ctrl`),metaKey:D.includes(`Meta`),shiftKey:D.includes(`Shift`),bubbles:!0,cancelable:!0});return t.captureTransaction(()=>{S.someProp(`handleKeyDown`,e=>e(S,k))})?.steps.forEach(e=>{let t=e.map(w.mapping);t&&E&&w.maybeStep(t)}),!0};function isNodeActive(e,t,S={}){let{from:w,to:E,empty:D}=e.selection,O=t?getNodeType(t,e.schema):null,k=[];e.doc.nodesBetween(w,E,(e,t)=>{if(e.isText)return;let S=Math.max(w,t),D=Math.min(E,t+e.nodeSize);k.push({node:e,from:S,to:D})});let j=E-w,F=k.filter(e=>O?O.name===e.node.type.name:!0).filter(e=>objectIncludes(e.node.attrs,S,{strict:!1}));return D?!!F.length:F.reduce((e,t)=>e+t.to-t.from,0)>=j}var lift=(e,t={})=>({state:S,dispatch:w})=>isNodeActive(S,getNodeType(e,S.schema),t)?lift$1(S,w):!1,liftEmptyBlock=()=>({state:e,dispatch:t})=>liftEmptyBlock$1(e,t),liftListItem=e=>({state:t,dispatch:S})=>liftListItem$1(getNodeType(e,t.schema))(t,S),newlineInCode=()=>({state:e,dispatch:t})=>newlineInCode$1(e,t);function getSchemaTypeNameByName(e,t){return t.nodes[e]?`node`:t.marks[e]?`mark`:null}function deleteProps(e,t){let S=typeof t==`string`?[t]:t;return Object.keys(e).reduce((t,w)=>(S.includes(w)||(t[w]=e[w]),t),{})}var resetAttributes=(e,t)=>({tr:S,state:w,dispatch:E})=>{let D=null,O=null,k=getSchemaTypeNameByName(typeof e==`string`?e:e.name,w.schema);if(!k)return!1;k===`node`&&(D=getNodeType(e,w.schema)),k===`mark`&&(O=getMarkType(e,w.schema));let j=!1;return S.selection.ranges.forEach(e=>{w.doc.nodesBetween(e.$from.pos,e.$to.pos,(e,w)=>{D&&D===e.type&&(j=!0,E&&S.setNodeMarkup(w,void 0,deleteProps(e.attrs,t))),O&&e.marks.length&&e.marks.forEach(D=>{O===D.type&&(j=!0,E&&S.addMark(w,w+e.nodeSize,O.create(deleteProps(D.attrs,t))))})})}),j},scrollIntoView=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),selectAll=()=>({tr:e,dispatch:t})=>{if(t){let t=new AllSelection(e.doc);e.setSelection(t)}return!0},selectNodeBackward=()=>({state:e,dispatch:t})=>selectNodeBackward$1(e,t),selectNodeForward=()=>({state:e,dispatch:t})=>selectNodeForward$1(e,t),selectParentNode=()=>({state:e,dispatch:t})=>selectParentNode$1(e,t),selectTextblockEnd=()=>({state:e,dispatch:t})=>selectTextblockEnd$1(e,t),selectTextblockStart=()=>({state:e,dispatch:t})=>selectTextblockStart$1(e,t);function createDocument(e,t,S={},w={}){return createNodeFromContent(e,t,{slice:!1,parseOptions:S,errorOnInvalidContent:w.errorOnInvalidContent})}var setContent=(e,{errorOnInvalidContent:t,emitUpdate:S=!0,parseOptions:w={}}={})=>({editor:E,tr:D,dispatch:O,commands:k})=>{let{doc:j}=D;if(w.preserveWhitespace!==`full`){let k=createDocument(e,E.schema,w,{errorOnInvalidContent:t??E.options.enableContentCheck});return O&&D.replaceWith(0,j.content.size,k).setMeta(`preventUpdate`,!S),!0}return O&&D.setMeta(`preventUpdate`,!S),k.insertContentAt({from:0,to:j.content.size},e,{parseOptions:w,errorOnInvalidContent:t??E.options.enableContentCheck})};function getMarkAttributes(e,t){let S=getMarkType(t,e.schema),{from:w,to:E,empty:D}=e.selection,O=[];D?(e.storedMarks&&O.push(...e.storedMarks),O.push(...e.selection.$head.marks())):e.doc.nodesBetween(w,E,e=>{O.push(...e.marks)});let k=O.find(e=>e.type.name===S.name);return k?{...k.attrs}:{}}function combineTransactionSteps(e,t){let S=new Transform$4(e);return t.forEach(e=>{e.steps.forEach(e=>{S.step(e)})}),S}function defaultBlockAt(e){for(let t=0;t<e.edgeCount;t+=1){let{type:S}=e.edge(t);if(S.isTextblock&&!S.hasRequiredAttrs())return S}return null}function findChildrenInRange(e,t,S){let w=[];return e.nodesBetween(t.from,t.to,(e,t)=>{S(e)&&w.push({node:e,pos:t})}),w}function findParentNodeClosestToPos(e,t){for(let S=e.depth;S>0;--S){let w=e.node(S);if(t(w))return{pos:S>0?e.before(S):0,start:e.start(S),depth:S,node:w}}}function findParentNode(e){return t=>findParentNodeClosestToPos(t.$from,e)}function getExtensionField(e,t,S){return e.config[t]===void 0&&e.parent?getExtensionField(e.parent,t,S):typeof e.config[t]==`function`?e.config[t].bind({...S,parent:e.parent?getExtensionField(e.parent,t,S):null}):e.config[t]}function flattenExtensions(e){return e.map(e=>{let t=getExtensionField(e,`addExtensions`,{name:e.name,options:e.options,storage:e.storage});return t?[e,...flattenExtensions(t())]:e}).flat(10)}function getHTMLFromFragment(e,t){let S=DOMSerializer.fromSchema(t).serializeFragment(e),w=document.implementation.createHTMLDocument().createElement(`div`);return w.appendChild(S),w.innerHTML}function isFunction(e){return typeof e==`function`}function callOrReturn(e,t=void 0,...S){return isFunction(e)?t?e.bind(t)(...S):e(...S):e}function isEmptyObject(e={}){return Object.keys(e).length===0&&e.constructor===Object}function splitExtensions(e){return{baseExtensions:e.filter(e=>e.type===`extension`),nodeExtensions:e.filter(e=>e.type===`node`),markExtensions:e.filter(e=>e.type===`mark`)}}function getAttributesFromExtensions(e){let t=[],{nodeExtensions:S,markExtensions:w}=splitExtensions(e),E=[...S,...w],D={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},O=S.filter(e=>e.name!==`text`).map(e=>e.name),k=w.map(e=>e.name),j=[...O,...k];return e.forEach(e=>{let S=getExtensionField(e,`addGlobalAttributes`,{name:e.name,options:e.options,storage:e.storage,extensions:E});S&&S().forEach(e=>{let S;S=Array.isArray(e.types)?e.types:e.types===`*`?j:e.types===`nodes`?O:e.types===`marks`?k:[],S.forEach(S=>{Object.entries(e.attributes).forEach(([e,w])=>{t.push({type:S,name:e,attribute:{...D,...w}})})})})}),E.forEach(e=>{let S=getExtensionField(e,`addAttributes`,{name:e.name,options:e.options,storage:e.storage});if(!S)return;let w=S();Object.entries(w).forEach(([S,w])=>{let E={...D,...w};typeof E?.default==`function`&&(E.default=E.default()),E?.isRequired&&E?.default===void 0&&delete E.default,t.push({type:e.name,name:S,attribute:E})})}),t}function splitStyleDeclarations(e){let t=[],S=``,w=!1,E=!1,D=0,O=e.length;for(let k=0;k<O;k+=1){let O=e[k];if(O===`'`&&!E){w=!w,S+=O;continue}if(O===`"`&&!w){E=!E,S+=O;continue}if(!w&&!E){if(O===`(`){D+=1,S+=O;continue}if(O===`)`&&D>0){--D,S+=O;continue}if(O===`;`&&D===0){t.push(S),S=``;continue}}S+=O}return S&&t.push(S),t}function parseStyleEntries(e){let t=[],S=splitStyleDeclarations(e||``),w=S.length;for(let e=0;e<w;e+=1){let w=S[e],E=w.indexOf(`:`);if(E===-1)continue;let D=w.slice(0,E).trim(),O=w.slice(E+1).trim();D&&O&&t.push([D,O])}return t}function mergeAttributes(...e){return e.filter(e=>!!e).reduce((e,t)=>{let S={...e};return Object.entries(t).forEach(([e,t])=>{if(!S[e]){S[e]=t;return}if(e===`class`){let w=t?String(t).split(` `):[],E=S[e]?S[e].split(` `):[],D=w.filter(e=>!E.includes(e));S[e]=[...E,...D].join(` `)}else if(e===`style`){let w=new Map([...parseStyleEntries(S[e]),...parseStyleEntries(t)]);S[e]=Array.from(w.entries()).map(([e,t])=>`${e}: ${t}`).join(`; `)}else S[e]=t}),S},{})}function getRenderedAttributes(e,t){return t.filter(t=>t.type===e.type.name).filter(e=>e.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(e.attrs)||{}:{[t.name]:e.attrs[t.name]}).reduce((e,t)=>mergeAttributes(e,t),{})}function fromString(e){return typeof e==`string`?e.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(e):e===`true`?!0:e===`false`?!1:e:e}function injectExtensionAttributesToParseRule(e,t){return`style`in e?e:{...e,getAttrs:S=>{let w=e.getAttrs?e.getAttrs(S):e.attrs;if(w===!1)return!1;let E=t.reduce((e,t)=>{let w=t.attribute.parseHTML?t.attribute.parseHTML(S):fromString(S.getAttribute(t.name));return w==null?e:{...e,[t.name]:w}},{});return{...w,...E}}}}function cleanUpSchemaItem(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>e===`attrs`&&isEmptyObject(t)?!1:t!=null))}function buildAttributeSpec(e){var t,S;let w={};return!e?.attribute?.isRequired&&`default`in(e?.attribute||{})&&(w.default=e.attribute.default),e?.attribute?.validate!==void 0&&(w.validate=e.attribute.validate),[e.name,w]}function getSchemaByResolvedExtensions(e,t){var S;let w=getAttributesFromExtensions(e),{nodeExtensions:E,markExtensions:D}=splitExtensions(e);return new Schema$1({topNode:E.find(e=>getExtensionField(e,`topNode`))?.name,nodes:Object.fromEntries(E.map(S=>{let E=w.filter(e=>e.type===S.name),D={name:S.name,options:S.options,storage:S.storage,editor:t},O=cleanUpSchemaItem({...e.reduce((e,t)=>{let w=getExtensionField(t,`extendNodeSchema`,D);return{...e,...w?w(S):{}}},{}),content:callOrReturn(getExtensionField(S,`content`,D)),marks:callOrReturn(getExtensionField(S,`marks`,D)),group:callOrReturn(getExtensionField(S,`group`,D)),inline:callOrReturn(getExtensionField(S,`inline`,D)),atom:callOrReturn(getExtensionField(S,`atom`,D)),selectable:callOrReturn(getExtensionField(S,`selectable`,D)),draggable:callOrReturn(getExtensionField(S,`draggable`,D)),code:callOrReturn(getExtensionField(S,`code`,D)),whitespace:callOrReturn(getExtensionField(S,`whitespace`,D)),linebreakReplacement:callOrReturn(getExtensionField(S,`linebreakReplacement`,D)),defining:callOrReturn(getExtensionField(S,`defining`,D)),isolating:callOrReturn(getExtensionField(S,`isolating`,D)),attrs:Object.fromEntries(E.map(buildAttributeSpec))}),k=callOrReturn(getExtensionField(S,`parseHTML`,D));k&&(O.parseDOM=k.map(e=>injectExtensionAttributesToParseRule(e,E)));let j=getExtensionField(S,`renderHTML`,D);j&&(O.toDOM=e=>j({node:e,HTMLAttributes:getRenderedAttributes(e,E)}));let F=getExtensionField(S,`renderText`,D);return F&&(O.toText=F),[S.name,O]})),marks:Object.fromEntries(D.map(S=>{let E=w.filter(e=>e.type===S.name),D={name:S.name,options:S.options,storage:S.storage,editor:t},O=cleanUpSchemaItem({...e.reduce((e,t)=>{let w=getExtensionField(t,`extendMarkSchema`,D);return{...e,...w?w(S):{}}},{}),inclusive:callOrReturn(getExtensionField(S,`inclusive`,D)),excludes:callOrReturn(getExtensionField(S,`excludes`,D)),group:callOrReturn(getExtensionField(S,`group`,D)),spanning:callOrReturn(getExtensionField(S,`spanning`,D)),code:callOrReturn(getExtensionField(S,`code`,D)),attrs:Object.fromEntries(E.map(buildAttributeSpec))}),k=callOrReturn(getExtensionField(S,`parseHTML`,D));k&&(O.parseDOM=k.map(e=>injectExtensionAttributesToParseRule(e,E)));let j=getExtensionField(S,`renderHTML`,D);return j&&(O.toDOM=e=>j({mark:e,HTMLAttributes:getRenderedAttributes(e,E)})),[S.name,O]}))})}function findDuplicates(e){let t=e.filter((t,S)=>e.indexOf(t)!==S);return Array.from(new Set(t))}function sortExtensions(e){let t=100;return e.sort((e,t)=>{let S=getExtensionField(e,`priority`)||100,w=getExtensionField(t,`priority`)||100;return S>w?-1:S<w?1:0})}function resolveExtensions(e){let t=sortExtensions(flattenExtensions(e)),S=findDuplicates(t.map(e=>e.name));return S.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${S.map(e=>`'${e}'`).join(`, `)}]. This can lead to issues.`),t}function getSchema(e,t){return getSchemaByResolvedExtensions(resolveExtensions(e),t)}function getTextBetween(e,t,S){let{from:w,to:E}=t,{blockSeparator:D=`
|
|
169
|
+
`))),0,0),e.someProp(`transformPasted`,t=>{k=t(k,e,!0)}),k;let S=e.someProp(`clipboardTextParser`,S=>S(t,E,w,e));if(S)k=S;else{let S=E.marks(),{schema:w}=e.state,D=DOMSerializer.fromSchema(w);O=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=O.appendChild(document.createElement(`p`));e&&t.appendChild(D.serializeNode(w.text(e,S)))})}}else e.someProp(`transformPastedHTML`,t=>{S=t(S,e)}),O=readHTML(S),webkit&&restoreReplacedSpaces(O);let F=O&&O.querySelector(`[data-pm-slice]`),L=F&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(F.getAttribute(`data-pm-slice`)||``);if(L&&L[3])for(let e=+L[3];e>0;e--){let e=O.firstChild;for(;e&&e.nodeType!=1;)e=e.nextSibling;if(!e)break;O=e}if(k||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||DOMParser.fromSchema(e.state.schema)).parseSlice(O,{preserveWhitespace:!!(j||L),context:E,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!inlineParents.test(e.parentNode.nodeName)?{ignore:!0}:null}}),L)k=addContext(closeSlice(k,+L[1],+L[2]),L[4]);else if(k=Slice.maxOpen(normalizeSiblings(k.content,E),!0),k.openStart||k.openEnd){let e=0,t=0;for(let t=k.content.firstChild;e<k.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=k.content.lastChild;t<k.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);k=closeSlice(k,e,t)}return e.someProp(`transformPasted`,t=>{k=t(k,e,j)}),k}const inlineParents=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function normalizeSiblings(e,t){if(e.childCount<2)return e;for(let S=t.depth;S>=0;S--){let w=t.node(S).contentMatchAt(t.index(S)),E,D=[];if(e.forEach(e=>{if(!D)return;let t=w.findWrapping(e.type),S;if(!t)return D=null;if(S=D.length&&E.length&&addToSibling(t,E,e,D[D.length-1],0))D[D.length-1]=S;else{D.length&&(D[D.length-1]=closeRight(D[D.length-1],E.length));let S=withWrappers(e,t);D.push(S),w=w.matchType(S.type),E=t}}),D)return Fragment.from(D)}return e}function withWrappers(e,t,S=0){for(let w=t.length-1;w>=S;w--)e=t[w].create(null,Fragment.from(e));return e}function addToSibling(e,t,S,w,E){if(E<e.length&&E<t.length&&e[E]==t[E]){let D=addToSibling(e,t,S,w.lastChild,E+1);if(D)return w.copy(w.content.replaceChild(w.childCount-1,D));if(w.contentMatchAt(w.childCount).matchType(E==e.length-1?S.type:e[E+1]))return w.copy(w.content.append(Fragment.from(withWrappers(S,e,E+1))))}}function closeRight(e,t){if(t==0)return e;let S=e.content.replaceChild(e.childCount-1,closeRight(e.lastChild,t-1)),w=e.contentMatchAt(e.childCount).fillBefore(Fragment.empty,!0);return e.copy(S.append(w))}function closeRange(e,t,S,w,E,D){let O=t<0?e.firstChild:e.lastChild,k=O.content;return e.childCount>1&&(D=0),E<w-1&&(k=closeRange(k,t,S,w,E+1,D)),E>=S&&(k=t<0?O.contentMatchAt(0).fillBefore(k,D<=E).append(k):k.append(O.contentMatchAt(O.childCount).fillBefore(Fragment.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,O.copy(k))}function closeSlice(e,t,S){return t<e.openStart&&(e=new Slice(closeRange(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),S<e.openEnd&&(e=new Slice(closeRange(e.content,1,S,e.openEnd,0,0),e.openStart,S)),e}const wrapMap={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]};let _detachedDoc=null;function detachedDoc(){return _detachedDoc||=document.implementation.createHTMLDocument(`title`)}let _policy=null;function maybeWrapTrusted(e){let t=window.trustedTypes;return t?(_policy||=t.defaultPolicy||t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e}),_policy.createHTML(e)):e}function readHTML(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let S=detachedDoc().createElement(`div`),w=/<([a-z][^>\s]+)/i.exec(e),E;if((E=w&&wrapMap[w[1].toLowerCase()])&&(e=E.map(e=>`<`+e+`>`).join(``)+e+E.map(e=>`</`+e+`>`).reverse().join(``)),S.innerHTML=maybeWrapTrusted(e),E)for(let e=0;e<E.length;e++)S=S.querySelector(E[e])||S;return S}function restoreReplacedSpaces(e){let t=e.querySelectorAll(chrome?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let S=0;S<t.length;S++){let w=t[S];w.childNodes.length==1&&w.textContent==`\xA0`&&w.parentNode&&w.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),w)}}function addContext(e,t){if(!e.size)return e;let S=e.content.firstChild.type.schema,w;try{w=JSON.parse(t)}catch{return e}let{content:E,openStart:D,openEnd:O}=e;for(let e=w.length-2;e>=0;e-=2){let t=S.nodes[w[e]];if(!t||t.hasRequiredAttrs())break;E=Fragment.from(t.create(w[e+1],E)),D++,O++}return new Slice(E,D,O)}const handlers={},editHandlers={},passiveHandlers={touchstart:!0,touchmove:!0};var InputState=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function initInput(e){for(let t in handlers){let S=handlers[t];e.dom.addEventListener(t,e.input.eventHandlers[t]=t=>{eventBelongsToView(e,t)&&!runCustomHandler(e,t)&&(e.editable||!(t.type in editHandlers))&&S(e,t)},passiveHandlers[t]?{passive:!0}:void 0)}safari&&e.dom.addEventListener(`input`,()=>null),ensureListeners(e)}function setSelectionOrigin(e,t){e.input.lastSelectionOrigin=t,e.input.lastSelectionTime=Date.now()}function destroyInput(e){e.domObserver.stop();for(let t in e.input.eventHandlers)e.dom.removeEventListener(t,e.input.eventHandlers[t]);clearTimeout(e.input.composingTimeout),clearTimeout(e.input.lastIOSEnterFallbackTimeout)}function ensureListeners(e){e.someProp(`handleDOMEvents`,t=>{for(let S in t)e.input.eventHandlers[S]||e.dom.addEventListener(S,e.input.eventHandlers[S]=t=>runCustomHandler(e,t))})}function runCustomHandler(e,t){return e.someProp(`handleDOMEvents`,S=>{let w=S[t.type];return w?w(e,t)||t.defaultPrevented:!1})}function eventBelongsToView(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let S=t.target;S!=e.dom;S=S.parentNode)if(!S||S.nodeType==11||S.pmViewDesc&&S.pmViewDesc.stopEvent(t))return!1;return!0}function dispatchEvent(e,t){!runCustomHandler(e,t)&&handlers[t.type]&&(e.editable||!(t.type in editHandlers))&&handlers[t.type](e,t)}editHandlers.keydown=(e,t)=>{let S=t;if(e.input.shiftKey=S.keyCode==16||S.shiftKey,!inOrNearComposition(e,S)&&(e.input.lastKeyCode=S.keyCode,e.input.lastKeyCodeTime=Date.now(),!(android&&chrome&&S.keyCode==13)))if(S.keyCode!=229&&e.domObserver.forceFlush(),ios&&S.keyCode==13&&!S.ctrlKey&&!S.altKey&&!S.metaKey){let t=Date.now();e.input.lastIOSEnter=t,e.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{e.input.lastIOSEnter==t&&(e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))),e.input.lastIOSEnter=0)},200)}else e.someProp(`handleKeyDown`,t=>t(e,S))||captureKeyDown(e,S)?S.preventDefault():setSelectionOrigin(e,`key`)},editHandlers.keyup=(e,t)=>{t.keyCode==16&&(e.input.shiftKey=!1)},editHandlers.keypress=(e,t)=>{let S=t;if(inOrNearComposition(e,S)||!S.charCode||S.ctrlKey&&!S.altKey||mac$2&&S.metaKey)return;if(e.someProp(`handleKeyPress`,t=>t(e,S))){S.preventDefault();return}let w=e.state.selection;if(!(w instanceof TextSelection)||!w.$from.sameParent(w.$to)){let t=String.fromCharCode(S.charCode),E=()=>e.state.tr.insertText(t).scrollIntoView();!/[\r\n]/.test(t)&&!e.someProp(`handleTextInput`,S=>S(e,w.$from.pos,w.$to.pos,t,E))&&e.dispatch(E()),S.preventDefault()}};function eventCoords(e){return{left:e.clientX,top:e.clientY}}function isNear(e,t){let S=t.x-e.clientX,w=t.y-e.clientY;return S*S+w*w<100}function runHandlerOnContext(e,t,S,w,E){if(w==-1)return!1;let D=e.state.doc.resolve(w);for(let w=D.depth+1;w>0;w--)if(e.someProp(t,t=>w>D.depth?t(e,S,D.nodeAfter,D.before(w),E,!0):t(e,S,D.node(w),D.before(w),E,!1)))return!0;return!1}function updateSelection(e,t,S){if(e.focused||e.focus(),e.state.selection.eq(t))return;let w=e.state.tr.setSelection(t);S==`pointer`&&w.setMeta(`pointer`,!0),e.dispatch(w)}function selectClickedLeaf(e,t){if(t==-1)return!1;let S=e.state.doc.resolve(t),w=S.nodeAfter;return w&&w.isAtom&&NodeSelection.isSelectable(w)?(updateSelection(e,new NodeSelection(S),`pointer`),!0):!1}function selectClickedNode(e,t){if(t==-1)return!1;let S=e.state.selection,w,E;S instanceof NodeSelection&&(w=S.node);let D=e.state.doc.resolve(t);for(let e=D.depth+1;e>0;e--){let t=e>D.depth?D.nodeAfter:D.node(e);if(NodeSelection.isSelectable(t)){E=w&&S.$from.depth>0&&e>=S.$from.depth&&D.before(S.$from.depth+1)==S.$from.pos?D.before(S.$from.depth):D.before(e);break}}return E==null?!1:(updateSelection(e,NodeSelection.create(e.state.doc,E),`pointer`),!0)}function handleSingleClick(e,t,S,w,E){return runHandlerOnContext(e,`handleClickOn`,t,S,w)||e.someProp(`handleClick`,S=>S(e,t,w))||(E?selectClickedNode(e,S):selectClickedLeaf(e,S))}function handleDoubleClick(e,t,S,w){return runHandlerOnContext(e,`handleDoubleClickOn`,t,S,w)||e.someProp(`handleDoubleClick`,S=>S(e,t,w))}function handleTripleClick$1(e,t,S,w){return runHandlerOnContext(e,`handleTripleClickOn`,t,S,w)||e.someProp(`handleTripleClick`,S=>S(e,t,w))||defaultTripleClick(e,S,w)}function defaultTripleClick(e,t,S){if(S.button!=0)return!1;let w=e.state.doc;if(t==-1)return w.inlineContent?(updateSelection(e,TextSelection.create(w,0,w.content.size),`pointer`),!0):!1;let E=w.resolve(t);for(let t=E.depth+1;t>0;t--){let S=t>E.depth?E.nodeAfter:E.node(t),D=E.before(t);if(S.inlineContent)updateSelection(e,TextSelection.create(w,D+1,D+1+S.content.size),`pointer`);else if(NodeSelection.isSelectable(S))updateSelection(e,NodeSelection.create(w,D),`pointer`);else continue;return!0}}function forceDOMFlush(e){return endComposition(e)}const selectNodeModifier=mac$2?`metaKey`:`ctrlKey`;handlers.mousedown=(e,t)=>{let S=t;e.input.shiftKey=S.shiftKey;let w=forceDOMFlush(e),E=Date.now(),D=`singleClick`;E-e.input.lastClick.time<500&&isNear(S,e.input.lastClick)&&!S[selectNodeModifier]&&e.input.lastClick.button==S.button&&(e.input.lastClick.type==`singleClick`?D=`doubleClick`:e.input.lastClick.type==`doubleClick`&&(D=`tripleClick`)),e.input.lastClick={time:E,x:S.clientX,y:S.clientY,type:D,button:S.button};let O=e.posAtCoords(eventCoords(S));O&&(D==`singleClick`?(e.input.mouseDown&&e.input.mouseDown.done(),e.input.mouseDown=new MouseDown(e,O,S,!!w)):(D==`doubleClick`?handleDoubleClick:handleTripleClick$1)(e,O.pos,O.inside,S)?S.preventDefault():setSelectionOrigin(e,`pointer`))};var MouseDown=class{constructor(e,t,S,w){this.view=e,this.pos=t,this.event=S,this.flushed=w,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!S[selectNodeModifier],this.allowDefault=S.shiftKey;let E,D;if(t.inside>-1)E=e.state.doc.nodeAt(t.inside),D=t.inside;else{let S=e.state.doc.resolve(t.pos);E=S.parent,D=S.depth?S.before():0}let O=w?null:S.target,k=O?e.docView.nearestDesc(O,!0):null;this.target=k&&k.nodeDOM.nodeType==1?k.nodeDOM:null;let{selection:j}=e.state;S.button==0&&(E.type.spec.draggable&&E.type.spec.selectable!==!1||j instanceof NodeSelection&&j.from<=D&&j.to>D)&&(this.mightDrag={node:E,pos:D,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&gecko&&!this.target.hasAttribute(`contentEditable`))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute(`contentEditable`,`false`)},20),this.view.domObserver.start()),e.root.addEventListener(`mouseup`,this.up=this.up.bind(this)),e.root.addEventListener(`mousemove`,this.move=this.move.bind(this)),setSelectionOrigin(e,`pointer`)}done(){this.view.root.removeEventListener(`mouseup`,this.up),this.view.root.removeEventListener(`mousemove`,this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute(`draggable`),this.mightDrag.setUneditable&&this.target.removeAttribute(`contentEditable`),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>selectionToDOM(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(eventCoords(e))),this.updateAllowDefault(e),this.allowDefault||!t?setSelectionOrigin(this.view,`pointer`):handleSingleClick(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||safari&&this.mightDrag&&!this.mightDrag.node.isAtom||chrome&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(updateSelection(this.view,Selection$1.near(this.view.state.doc.resolve(t.pos)),`pointer`),e.preventDefault()):setSelectionOrigin(this.view,`pointer`)}move(e){this.updateAllowDefault(e),setSelectionOrigin(this.view,`pointer`),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}};handlers.touchstart=e=>{e.input.lastTouch=Date.now(),forceDOMFlush(e),setSelectionOrigin(e,`pointer`)},handlers.touchmove=e=>{e.input.lastTouch=Date.now(),setSelectionOrigin(e,`pointer`)},handlers.contextmenu=e=>forceDOMFlush(e);function inOrNearComposition(e,t){return e.composing?!0:safari&&Math.abs(t.timeStamp-e.input.compositionEndedAt)<500?(e.input.compositionEndedAt=-2e8,!0):!1}const timeoutComposition=android?5e3:-1;editHandlers.compositionstart=editHandlers.compositionupdate=e=>{if(!e.composing){e.domObserver.flush();let{state:t}=e,S=t.selection.$to;if(t.selection instanceof TextSelection&&(t.storedMarks||!S.textOffset&&S.parentOffset&&S.nodeBefore.marks.some(e=>e.type.spec.inclusive===!1)||chrome&&windows$1&&selectionBeforeUneditable(e)))e.markCursor=e.state.storedMarks||S.marks(),endComposition(e,!0),e.markCursor=null;else if(endComposition(e,!t.selection.empty),gecko&&t.selection.empty&&S.parentOffset&&!S.textOffset&&S.nodeBefore.marks.length){let t=e.domSelectionRange();for(let S=t.focusNode,w=t.focusOffset;S&&S.nodeType==1&&w!=0;){let t=w<0?S.lastChild:S.childNodes[w-1];if(!t)break;if(t.nodeType==3){let S=e.domSelection();S&&S.collapse(t,t.nodeValue.length);break}else S=t,w=-1}}e.input.composing=!0}scheduleComposeEnd(e,timeoutComposition)};function selectionBeforeUneditable(e){let{focusNode:t,focusOffset:S}=e.domSelectionRange();if(!t||t.nodeType!=1||S>=t.childNodes.length)return!1;let w=t.childNodes[S];return w.nodeType==1&&w.contentEditable==`false`}editHandlers.compositionend=(e,t)=>{e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=t.timeStamp,e.input.compositionPendingChanges=e.domObserver.pendingRecords().length?e.input.compositionID:0,e.input.compositionNode=null,e.input.badSafariComposition?e.domObserver.forceFlush():e.input.compositionPendingChanges&&Promise.resolve().then(()=>e.domObserver.flush()),e.input.compositionID++,scheduleComposeEnd(e,20))};function scheduleComposeEnd(e,t){clearTimeout(e.input.composingTimeout),t>-1&&(e.input.composingTimeout=setTimeout(()=>endComposition(e),t))}function clearComposition(e){for(e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=timestampFromCustomEvent());e.input.compositionNodes.length>0;)e.input.compositionNodes.pop().markParentsDirty()}function findCompositionNode(e){let t=e.domSelectionRange();if(!t.focusNode)return null;let S=textNodeBefore$1(t.focusNode,t.focusOffset),w=textNodeAfter$1(t.focusNode,t.focusOffset);if(S&&w&&S!=w){let t=w.pmViewDesc,E=e.domObserver.lastChangedTextNode;if(S==E||w==E)return E;if(!t||!t.isText(w.nodeValue))return w;if(e.input.compositionNode==w){let e=S.pmViewDesc;if(!(!e||!e.isText(S.nodeValue)))return w}}return S||w}function timestampFromCustomEvent(){let e=document.createEvent(`Event`);return e.initEvent(`event`,!0,!0),e.timeStamp}function endComposition(e,t=!1){if(!(android&&e.domObserver.flushingSoon>=0)){if(e.domObserver.forceFlush(),clearComposition(e),t||e.docView&&e.docView.dirty){let S=selectionFromDOM(e),w=e.state.selection;return S&&!S.eq(w)?e.dispatch(e.state.tr.setSelection(S)):(e.markCursor||t)&&!w.$from.node(w.$from.sharedDepth(w.to)).inlineContent?e.dispatch(e.state.tr.deleteSelection()):e.updateState(e.state),!0}return!1}}function captureCopy(e,t){if(!e.dom.parentNode)return;let S=e.dom.parentNode.appendChild(document.createElement(`div`));S.appendChild(t),S.style.cssText=`position: fixed; left: -10000px; top: 10px`;let w=getSelection(),E=document.createRange();E.selectNodeContents(t),e.dom.blur(),w.removeAllRanges(),w.addRange(E),setTimeout(()=>{S.parentNode&&S.parentNode.removeChild(S),e.focus()},50)}const brokenClipboardAPI=ie$2&&ie_version<15||ios&&webkit_version<604;handlers.copy=editHandlers.cut=(e,t)=>{let S=t,w=e.state.selection,E=S.type==`cut`;if(w.empty)return;let D=brokenClipboardAPI?null:S.clipboardData,{dom:O,text:k}=serializeForClipboard(e,w.content());D?(S.preventDefault(),D.clearData(),D.setData(`text/html`,O.innerHTML),D.setData(`text/plain`,k)):captureCopy(e,O),E&&e.dispatch(e.state.tr.deleteSelection().scrollIntoView().setMeta(`uiEvent`,`cut`))};function sliceSingleNode(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function capturePaste(e,t){if(!e.dom.parentNode)return;let S=e.input.shiftKey||e.state.selection.$from.parent.type.spec.code,w=e.dom.parentNode.appendChild(document.createElement(S?`textarea`:`div`));S||(w.contentEditable=`true`),w.style.cssText=`position: fixed; left: -10000px; top: 10px`,w.focus();let E=e.input.shiftKey&&e.input.lastKeyCode!=45;setTimeout(()=>{e.focus(),w.parentNode&&w.parentNode.removeChild(w),S?doPaste(e,w.value,null,E,t):doPaste(e,w.textContent,w.innerHTML,E,t)},50)}function doPaste(e,t,S,w,E){let D=parseFromClipboard(e,t,S,w,e.state.selection.$from);if(e.someProp(`handlePaste`,t=>t(e,E,D||Slice.empty)))return!0;if(!D)return!1;let O=sliceSingleNode(D),k=O?e.state.tr.replaceSelectionWith(O,w):e.state.tr.replaceSelection(D);return e.dispatch(k.scrollIntoView().setMeta(`paste`,!0).setMeta(`uiEvent`,`paste`)),!0}function getText(e){let t=e.getData(`text/plain`)||e.getData(`Text`);if(t)return t;let S=e.getData(`text/uri-list`);return S?S.replace(/\r?\n/g,` `):``}editHandlers.paste=(e,t)=>{let S=t;if(e.composing&&!android)return;let w=brokenClipboardAPI?null:S.clipboardData,E=e.input.shiftKey&&e.input.lastKeyCode!=45;w&&doPaste(e,getText(w),w.getData(`text/html`),E,S)?S.preventDefault():capturePaste(e,S)};var Dragging=class{constructor(e,t,S){this.slice=e,this.move=t,this.node=S}};const dragCopyModifier=mac$2?`altKey`:`ctrlKey`;function dragMoves(e,t){let S;return e.someProp(`dragCopies`,e=>{S||=e(t)}),S==null?!t[dragCopyModifier]:!S}handlers.dragstart=(e,t)=>{let S=t,w=e.input.mouseDown;if(w&&w.done(),!S.dataTransfer)return;let E=e.state.selection,D=E.empty?null:e.posAtCoords(eventCoords(S)),O;if(!(D&&D.pos>=E.from&&D.pos<=(E instanceof NodeSelection?E.to-1:E.to))){if(w&&w.mightDrag)O=NodeSelection.create(e.state.doc,w.mightDrag.pos);else if(S.target&&S.target.nodeType==1){let t=e.docView.nearestDesc(S.target,!0);t&&t.node.type.spec.draggable&&t!=e.docView&&(O=NodeSelection.create(e.state.doc,t.posBefore))}}let{dom:k,text:j,slice:F}=serializeForClipboard(e,(O||e.state.selection).content());(!S.dataTransfer.files.length||!chrome||chrome_version>120)&&S.dataTransfer.clearData(),S.dataTransfer.setData(brokenClipboardAPI?`Text`:`text/html`,k.innerHTML),S.dataTransfer.effectAllowed=`copyMove`,brokenClipboardAPI||S.dataTransfer.setData(`text/plain`,j),e.dragging=new Dragging(F,dragMoves(e,S),O)},handlers.dragend=e=>{let t=e.dragging;window.setTimeout(()=>{e.dragging==t&&(e.dragging=null)},50)},editHandlers.dragover=editHandlers.dragenter=(e,t)=>t.preventDefault(),editHandlers.drop=(e,t)=>{try{handleDrop(e,t,e.dragging)}finally{e.dragging=null}};function handleDrop(e,t,S){if(!t.dataTransfer)return;let w=e.posAtCoords(eventCoords(t));if(!w)return;let E=e.state.doc.resolve(w.pos),D=S&&S.slice;D?e.someProp(`transformPasted`,t=>{D=t(D,e,!1)}):D=parseFromClipboard(e,getText(t.dataTransfer),brokenClipboardAPI?null:t.dataTransfer.getData(`text/html`),!1,E);let O=!!(S&&dragMoves(e,t));if(e.someProp(`handleDrop`,S=>S(e,t,D||Slice.empty,O))){t.preventDefault();return}if(!D)return;t.preventDefault();let k=D?dropPoint(e.state.doc,E.pos,D):E.pos;k??=E.pos;let j=e.state.tr;if(O){let{node:e}=S;e?e.replace(j):j.deleteSelection()}let F=j.mapping.map(k),L=D.openStart==0&&D.openEnd==0&&D.content.childCount==1,B=j.doc;if(L?j.replaceRangeWith(F,F,D.content.firstChild):j.replaceRange(F,F,D),j.doc.eq(B))return;let H=j.doc.resolve(F);if(L&&NodeSelection.isSelectable(D.content.firstChild)&&H.nodeAfter&&H.nodeAfter.sameMarkup(D.content.firstChild))j.setSelection(new NodeSelection(H));else{let t=j.mapping.map(k);j.mapping.maps[j.mapping.maps.length-1].forEach((e,S,w,E)=>t=E),j.setSelection(selectionBetween(e,H,j.doc.resolve(t)))}e.focus(),e.dispatch(j.setMeta(`uiEvent`,`drop`))}handlers.focus=e=>{e.input.lastFocus=Date.now(),e.focused||(e.domObserver.stop(),e.dom.classList.add(`ProseMirror-focused`),e.domObserver.start(),e.focused=!0,setTimeout(()=>{e.docView&&e.hasFocus()&&!e.domObserver.currentSelection.eq(e.domSelectionRange())&&selectionToDOM(e)},20))},handlers.blur=(e,t)=>{let S=t;e.focused&&=(e.domObserver.stop(),e.dom.classList.remove(`ProseMirror-focused`),e.domObserver.start(),S.relatedTarget&&e.dom.contains(S.relatedTarget)&&e.domObserver.currentSelection.clear(),!1)},handlers.beforeinput=(e,t)=>{if(chrome&&android&&t.inputType==`deleteContentBackward`){e.domObserver.flushSoon();let{domChangeCount:t}=e.input;setTimeout(()=>{if(e.input.domChangeCount!=t||(e.dom.blur(),e.focus(),e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))))return;let{$cursor:S}=e.state.selection;S&&S.pos>0&&e.dispatch(e.state.tr.delete(S.pos-1,S.pos).scrollIntoView())},50)}};for(let e in editHandlers)handlers[e]=editHandlers[e];function compareObjs(e,t){if(e==t)return!0;for(let S in e)if(e[S]!==t[S])return!1;for(let S in t)if(!(S in e))return!1;return!0}var WidgetType=class e{constructor(e,t){this.toDOM=e,this.spec=t||noSpec,this.side=this.spec.side||0}map(e,t,S,w){let{pos:E,deleted:D}=e.mapResult(t.from+w,this.side<0?-1:1);return D?null:new Decoration(E-S,E-S,this)}valid(){return!0}eq(t){return this==t||t instanceof e&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&compareObjs(this.spec,t.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},InlineType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,S,w){let E=e.map(t.from+w,this.spec.inclusiveStart?-1:1)-S,D=e.map(t.to+w,this.spec.inclusiveEnd?1:-1)-S;return E>=D?null:new Decoration(E,D,this)}valid(e,t){return t.from<t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}static is(t){return t.type instanceof e}destroy(){}},NodeType=class e{constructor(e,t){this.attrs=e,this.spec=t||noSpec}map(e,t,S,w){let E=e.mapResult(t.from+w,1);if(E.deleted)return null;let D=e.mapResult(t.to+w,-1);return D.deleted||D.pos<=E.pos?null:new Decoration(E.pos-S,D.pos-S,this)}valid(e,t){let{index:S,offset:w}=e.content.findIndex(t.from),E;return w==t.from&&!(E=e.child(S)).isText&&w+E.nodeSize==t.to}eq(t){return this==t||t instanceof e&&compareObjs(this.attrs,t.attrs)&&compareObjs(this.spec,t.spec)}destroy(){}},Decoration=class e{constructor(e,t,S){this.from=e,this.to=t,this.type=S}copy(t,S){return new e(t,S,this.type)}eq(e,t=0){return this.type.eq(e.type)&&this.from+t==e.from&&this.to+t==e.to}map(e,t,S){return this.type.map(e,this,t,S)}static widget(t,S,w){return new e(t,t,new WidgetType(S,w))}static inline(t,S,w,E){return new e(t,S,new InlineType(w,E))}static node(t,S,w,E){return new e(t,S,new NodeType(w,E))}get spec(){return this.type.spec}get inline(){return this.type instanceof InlineType}get widget(){return this.type instanceof WidgetType}};const none=[],noSpec={};var DecorationSet=class e{constructor(e,t){this.local=e.length?e:none,this.children=t.length?t:none}static create(e,t){return t.length?buildTree(t,e,0,noSpec):empty$2}find(e,t,S){let w=[];return this.findInner(e??0,t??1e9,w,0,S),w}findInner(e,t,S,w,E){for(let D=0;D<this.local.length;D++){let O=this.local[D];O.from<=t&&O.to>=e&&(!E||E(O.spec))&&S.push(O.copy(O.from+w,O.to+w))}for(let D=0;D<this.children.length;D+=3)if(this.children[D]<t&&this.children[D+1]>e){let O=this.children[D]+1;this.children[D+2].findInner(e-O,t-O,S,w+O,E)}}map(e,t,S){return this==empty$2||e.maps.length==0?this:this.mapInner(e,t,0,0,S||noSpec)}mapInner(t,S,w,E,D){let O;for(let e=0;e<this.local.length;e++){let k=this.local[e].map(t,w,E);k&&k.type.valid(S,k)?(O||=[]).push(k):D.onRemove&&D.onRemove(this.local[e].spec)}return this.children.length?mapChildren(this.children,O||[],t,S,w,E,D):O?new e(O.sort(byPos),none):empty$2}add(t,S){return S.length?this==empty$2?e.create(t,S):this.addInner(t,S,0):this}addInner(t,S,w){let E,D=0;t.forEach((e,t)=>{let O=t+w,k;if(k=takeSpansForNode(S,e,O)){for(E||=this.children.slice();D<E.length&&E[D]<t;)D+=3;E[D]==t?E[D+2]=E[D+2].addInner(e,k,O+1):E.splice(D,0,t,t+e.nodeSize,buildTree(k,e,O+1,noSpec)),D+=3}});let O=moveSpans(D?withoutNulls(S):S,-w);for(let e=0;e<O.length;e++)O[e].type.valid(t,O[e])||O.splice(e--,1);return new e(O.length?this.local.concat(O).sort(byPos):this.local,E||this.children)}remove(e){return e.length==0||this==empty$2?this:this.removeInner(e,0)}removeInner(t,S){let w=this.children,E=this.local;for(let e=0;e<w.length;e+=3){let E,D=w[e]+S,O=w[e+1]+S;for(let e=0,S;e<t.length;e++)(S=t[e])&&S.from>D&&S.to<O&&(t[e]=null,(E||=[]).push(S));if(!E)continue;w==this.children&&(w=this.children.slice());let k=w[e+2].removeInner(E,D+1);k==empty$2?(w.splice(e,3),e-=3):w[e+2]=k}if(E.length){for(let e=0,w;e<t.length;e++)if(w=t[e])for(let e=0;e<E.length;e++)E[e].eq(w,S)&&(E==this.local&&(E=this.local.slice()),E.splice(e--,1))}return w==this.children&&E==this.local?this:E.length||w.length?new e(E,w):empty$2}forChild(t,S){if(this==empty$2)return this;if(S.isLeaf)return e.empty;let w,E;for(let e=0;e<this.children.length;e+=3)if(this.children[e]>=t){this.children[e]==t&&(w=this.children[e+2]);break}let D=t+1,O=D+S.content.size;for(let e=0;e<this.local.length;e++){let t=this.local[e];if(t.from<O&&t.to>D&&t.type instanceof InlineType){let e=Math.max(D,t.from)-D,S=Math.min(O,t.to)-D;e<S&&(E||=[]).push(t.copy(e,S))}}if(E){let t=new e(E.sort(byPos),none);return w?new DecorationGroup([t,w]):t}return w||empty$2}eq(t){if(this==t)return!0;if(!(t instanceof e)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let e=0;e<this.local.length;e++)if(!this.local[e].eq(t.local[e]))return!1;for(let e=0;e<this.children.length;e+=3)if(this.children[e]!=t.children[e]||this.children[e+1]!=t.children[e+1]||!this.children[e+2].eq(t.children[e+2]))return!1;return!0}locals(e){return removeOverlap(this.localsInner(e))}localsInner(e){if(this==empty$2)return none;if(e.inlineContent||!this.local.some(InlineType.is))return this.local;let t=[];for(let e=0;e<this.local.length;e++)this.local[e].type instanceof InlineType||t.push(this.local[e]);return t}forEachSet(e){e(this)}};DecorationSet.empty=new DecorationSet([],[]),DecorationSet.removeOverlap=removeOverlap;const empty$2=DecorationSet.empty;var DecorationGroup=class e{constructor(e){this.members=e}map(t,S){let w=this.members.map(e=>e.map(t,S,noSpec));return e.from(w)}forChild(t,S){if(S.isLeaf)return DecorationSet.empty;let w=[];for(let E=0;E<this.members.length;E++){let D=this.members[E].forChild(t,S);D!=empty$2&&(D instanceof e?w=w.concat(D.members):w.push(D))}return e.from(w)}eq(t){if(!(t instanceof e)||t.members.length!=this.members.length)return!1;for(let e=0;e<this.members.length;e++)if(!this.members[e].eq(t.members[e]))return!1;return!0}locals(e){let t,S=!0;for(let w=0;w<this.members.length;w++){let E=this.members[w].localsInner(e);if(E.length)if(!t)t=E;else{S&&=(t=t.slice(),!1);for(let e=0;e<E.length;e++)t.push(E[e])}}return t?removeOverlap(S?t:t.sort(byPos)):none}static from(t){switch(t.length){case 0:return empty$2;case 1:return t[0];default:return new e(t.every(e=>e instanceof DecorationSet)?t:t.reduce((e,t)=>e.concat(t instanceof DecorationSet?t:t.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}};function mapChildren(e,t,S,w,E,D,O){let k=e.slice();for(let e=0,t=D;e<S.maps.length;e++){let w=0;S.maps[e].forEach((e,S,E,D)=>{let O=D-E-(S-e);for(let E=0;E<k.length;E+=3){let D=k[E+1];if(D<0||e>D+t-w)continue;let j=k[E]+t-w;S>=j?k[E+1]=e<=j?-2:-1:e>=t&&O&&(k[E]+=O,k[E+1]+=O)}w+=O}),t=S.maps[e].map(t,-1)}let j=!1;for(let t=0;t<k.length;t+=3)if(k[t+1]<0){if(k[t+1]==-2){j=!0,k[t+1]=-1;continue}let F=S.map(e[t]+D),L=F-E;if(L<0||L>=w.content.size){j=!0;continue}let B=S.map(e[t+1]+D,-1)-E,{index:H,offset:q}=w.content.findIndex(L),J=w.maybeChild(H);if(J&&q==L&&q+J.nodeSize==B){let w=k[t+2].mapInner(S,J,F+1,e[t]+D+1,O);w==empty$2?(k[t+1]=-2,j=!0):(k[t]=L,k[t+1]=B,k[t+2]=w)}else j=!0}if(j){let j=buildTree(mapAndGatherRemainingDecorations(k,e,t,S,E,D,O),w,0,O);t=j.local;for(let e=0;e<k.length;e+=3)k[e+1]<0&&(k.splice(e,3),e-=3);for(let e=0,t=0;e<j.children.length;e+=3){let S=j.children[e];for(;t<k.length&&k[t]<S;)t+=3;k.splice(t,0,j.children[e],j.children[e+1],j.children[e+2])}}return new DecorationSet(t.sort(byPos),k)}function moveSpans(e,t){if(!t||!e.length)return e;let S=[];for(let w=0;w<e.length;w++){let E=e[w];S.push(new Decoration(E.from+t,E.to+t,E.type))}return S}function mapAndGatherRemainingDecorations(e,t,S,w,E,D,O){function k(e,t){for(let D=0;D<e.local.length;D++){let k=e.local[D].map(w,E,t);k?S.push(k):O.onRemove&&O.onRemove(e.local[D].spec)}for(let S=0;S<e.children.length;S+=3)k(e.children[S+2],e.children[S]+t+1)}for(let S=0;S<e.length;S+=3)e[S+1]==-1&&k(e[S+2],t[S]+D+1);return S}function takeSpansForNode(e,t,S){if(t.isLeaf)return null;let w=S+t.nodeSize,E=null;for(let t=0,D;t<e.length;t++)(D=e[t])&&D.from>S&&D.to<w&&((E||=[]).push(D),e[t]=null);return E}function withoutNulls(e){let t=[];for(let S=0;S<e.length;S++)e[S]!=null&&t.push(e[S]);return t}function buildTree(e,t,S,w){let E=[],D=!1;t.forEach((t,O)=>{let k=takeSpansForNode(e,t,O+S);if(k){D=!0;let e=buildTree(k,t,S+O+1,w);e!=empty$2&&E.push(O,O+t.nodeSize,e)}});let O=moveSpans(D?withoutNulls(e):e,-S).sort(byPos);for(let e=0;e<O.length;e++)O[e].type.valid(t,O[e])||(w.onRemove&&w.onRemove(O[e].spec),O.splice(e--,1));return O.length||E.length?new DecorationSet(O,E):empty$2}function byPos(e,t){return e.from-t.from||e.to-t.to}function removeOverlap(e){let t=e;for(let S=0;S<t.length-1;S++){let w=t[S];if(w.from!=w.to)for(let E=S+1;E<t.length;E++){let D=t[E];if(D.from==w.from){D.to!=w.to&&(t==e&&(t=e.slice()),t[E]=D.copy(D.from,w.to),insertAhead(t,E+1,D.copy(w.to,D.to)));continue}else{D.from<w.to&&(t==e&&(t=e.slice()),t[S]=w.copy(w.from,D.from),insertAhead(t,E,w.copy(D.from,w.to)));break}}}return t}function insertAhead(e,t,S){for(;t<e.length&&byPos(S,e[t])>0;)t++;e.splice(t,0,S)}function viewDecorations(e){let t=[];return e.someProp(`decorations`,S=>{let w=S(e.state);w&&w!=empty$2&&t.push(w)}),e.cursorWrapper&&t.push(DecorationSet.create(e.state.doc,[e.cursorWrapper.deco])),DecorationGroup.from(t)}const observeOptions={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},useCharData=ie$2&&ie_version<=11;var SelectionState=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},DOMObserver=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new SelectionState,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(t=>{for(let e=0;e<t.length;e++)this.queue.push(t[e]);ie$2&&ie_version<=11&&t.some(e=>e.type==`childList`&&e.removedNodes.length||e.type==`characterData`&&e.oldValue.length>e.target.nodeValue.length)?this.flushSoon():safari&&e.composing&&t.some(e=>e.type==`childList`&&e.target.nodeName==`TR`)?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),useCharData&&(this.onCharData=e=>{this.queue.push({target:e.target,type:`characterData`,oldValue:e.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,observeOptions)),this.onCharData&&this.view.dom.addEventListener(`DOMCharacterDataModified`,this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;t<e.length;t++)this.queue.push(e[t]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener(`DOMCharacterDataModified`,this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener(`selectionchange`,this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener(`selectionchange`,this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(hasFocusAndSelection(this.view)){if(this.suppressingSelectionUpdates)return selectionToDOM(this.view);if(ie$2&&ie_version<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&isEquivalentPosition(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,S;for(let S=e.focusNode;S;S=parentNode(S))t.add(S);for(let w=e.anchorNode;w;w=parentNode(w))if(t.has(w)){S=w;break}let w=S&&this.view.docView.nearestDesc(S);if(w&&w.ignoreMutation({type:`selection`,target:S.nodeType==3?S.parentNode:S}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let S=e.domSelectionRange(),w=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(S)&&hasFocusAndSelection(e)&&!this.ignoreSelectionChange(S),E=-1,D=-1,O=!1,k=[];if(e.editable)for(let e=0;e<t.length;e++){let S=this.registerMutation(t[e],k);S&&(E=E<0?S.from:Math.min(S.from,E),D=D<0?S.to:Math.max(S.to,D),S.typeOver&&(O=!0))}if(k.some(e=>e.nodeName==`BR`)&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let e of k)if(e.nodeName==`BR`&&e.parentNode){let t=e.nextSibling;for(;t&&t.nodeType==1;){if(t.contentEditable==`false`){e.parentNode.removeChild(e);break}t=t.firstChild}}}else if(gecko&&k.length){let t=k.filter(e=>e.nodeName==`BR`);if(t.length==2){let[e,S]=t;e.parentNode&&e.parentNode.parentNode==S.parentNode?S.remove():e.remove()}else{let{focusNode:S}=this.currentSelection;for(let w of t){let t=w.parentNode;t&&t.nodeName==`LI`&&(!S||blockParent(e,S)!=t)&&w.remove()}}}let j=null;E<0&&w&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&selectionCollapsed(S)&&(j=selectionFromDOM(e))&&j.eq(Selection$1.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,selectionToDOM(e),this.currentSelection.set(S),e.scrollToSelection()):(E>-1||w)&&(E>-1&&(e.docView.markDirty(E,D),checkCSS(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,fixUpBadSafariComposition(e,k)),this.handleDOMChange(E,D,O,k),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(S)||selectionToDOM(e),this.currentSelection.set(S))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let S=this.view.docView.nearestDesc(e.target);if(e.type==`attributes`&&(S==this.view.docView||e.attributeName==`contenteditable`||e.attributeName==`style`&&!e.oldValue&&!e.target.getAttribute(`style`))||!S||S.ignoreMutation(e))return null;if(e.type==`childList`){for(let S=0;S<e.addedNodes.length;S++){let w=e.addedNodes[S];t.push(w),w.nodeType==3&&(this.lastChangedTextNode=w)}if(S.contentDOM&&S.contentDOM!=S.dom&&!S.contentDOM.contains(e.target))return{from:S.posBefore,to:S.posAfter};let w=e.previousSibling,E=e.nextSibling;if(ie$2&&ie_version<=11&&e.addedNodes.length)for(let t=0;t<e.addedNodes.length;t++){let{previousSibling:S,nextSibling:D}=e.addedNodes[t];(!S||Array.prototype.indexOf.call(e.addedNodes,S)<0)&&(w=S),(!D||Array.prototype.indexOf.call(e.addedNodes,D)<0)&&(E=D)}let D=w&&w.parentNode==e.target?domIndex(w)+1:0,O=S.localPosFromDOM(e.target,D,-1),k=E&&E.parentNode==e.target?domIndex(E):e.target.childNodes.length;return{from:O,to:S.localPosFromDOM(e.target,k,1)}}else if(e.type==`attributes`)return{from:S.posAtStart-S.border,to:S.posAtEnd+S.border};else return this.lastChangedTextNode=e.target,{from:S.posAtStart,to:S.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}}};let cssChecked=new WeakMap,cssCheckWarned=!1;function checkCSS(e){if(!cssChecked.has(e)&&(cssChecked.set(e,null),[`normal`,`nowrap`,`pre-line`].indexOf(getComputedStyle(e.dom).whiteSpace)!==-1)){if(e.requiresGeckoHackNode=gecko,cssCheckWarned)return;console.warn(`ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.`),cssCheckWarned=!0}}function rangeToSelectionRange(e,t){let S=t.startContainer,w=t.startOffset,E=t.endContainer,D=t.endOffset,O=e.domAtPos(e.state.selection.anchor);return isEquivalentPosition(O.node,O.offset,E,D)&&([S,w,E,D]=[E,D,S,w]),{anchorNode:S,anchorOffset:w,focusNode:E,focusOffset:D}}function safariShadowSelectionRange(e,t){if(t.getComposedRanges){let S=t.getComposedRanges(e.root)[0];if(S)return rangeToSelectionRange(e,S)}let S;function w(e){e.preventDefault(),e.stopImmediatePropagation(),S=e.getTargetRanges()[0]}return e.dom.addEventListener(`beforeinput`,w,!0),document.execCommand(`indent`),e.dom.removeEventListener(`beforeinput`,w,!0),S?rangeToSelectionRange(e,S):null}function blockParent(e,t){for(let S=t.parentNode;S&&S!=e.dom;S=S.parentNode){let t=e.docView.nearestDesc(S,!0);if(t&&t.node.isBlock)return S}return null}function fixUpBadSafariComposition(e,t){var S;let{focusNode:w,focusOffset:E}=e.domSelectionRange();for(let S of t)if(S.parentNode?.nodeName==`TR`){let t=S.nextSibling;for(;t&&t.nodeName!=`TD`&&t.nodeName!=`TH`;)t=t.nextSibling;if(t){let D=t;for(;;){let e=D.firstChild;if(!e||e.nodeType!=1||e.contentEditable==`false`||/^(BR|IMG)$/.test(e.nodeName))break;D=e}D.insertBefore(S,D.firstChild),w==S&&e.domSelection().collapse(S,E)}else S.parentNode.removeChild(S)}}function parseBetween(e,t,S){let{node:w,fromOffset:E,toOffset:D,from:O,to:k}=e.docView.parseRange(t,S),j=e.domSelectionRange(),F,L=j.anchorNode;if(L&&e.dom.contains(L.nodeType==1?L:L.parentNode)&&(F=[{node:L,offset:j.anchorOffset}],selectionCollapsed(j)||F.push({node:j.focusNode,offset:j.focusOffset})),chrome&&e.input.lastKeyCode===8)for(let e=D;e>E;e--){let t=w.childNodes[e-1],S=t.pmViewDesc;if(t.nodeName==`BR`&&!S){D=e;break}if(!S||S.size)break}let B=e.state.doc,H=e.someProp(`domParser`)||DOMParser.fromSchema(e.state.schema),q=B.resolve(O),J=null,Y=H.parse(w,{topNode:q.parent,topMatch:q.parent.contentMatchAt(q.index()),topOpen:!0,from:E,to:D,preserveWhitespace:q.parent.type.whitespace==`pre`?`full`:!0,findPositions:F,ruleFromNode,context:q});if(F&&F[0].pos!=null){let e=F[0].pos,t=F[1]&&F[1].pos;t??=e,J={anchor:e+O,head:t+O}}return{doc:Y,sel:J,from:O,to:k}}function ruleFromNode(e){let t=e.pmViewDesc;if(t)return t.parseRule();if(e.nodeName==`BR`&&e.parentNode){if(safari&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let e=document.createElement(`div`);return e.appendChild(document.createElement(`li`)),{skip:e}}else if(e.parentNode.lastChild==e||safari&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName==`IMG`&&e.getAttribute(`mark-placeholder`))return{ignore:!0};return null}const isInline=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function readDOMChange(e,t,S,w,E){let D=e.input.compositionPendingChanges||(e.composing?e.input.compositionID:0);if(e.input.compositionPendingChanges=0,t<0){let t=e.input.lastSelectionTime>Date.now()-50?e.input.lastSelectionOrigin:null,S=selectionFromDOM(e,t);if(S&&!e.state.selection.eq(S)){if(chrome&&android&&e.input.lastKeyCode===13&&Date.now()-100<e.input.lastKeyCodeTime&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`))))return;let w=e.state.tr.setSelection(S);t==`pointer`?w.setMeta(`pointer`,!0):t==`key`&&w.scrollIntoView(),D&&w.setMeta(`composition`,D),e.dispatch(w)}return}let O=e.state.doc.resolve(t),k=O.sharedDepth(S);t=O.before(k+1),S=e.state.doc.resolve(S).after(k+1);let j=e.state.selection,F=parseBetween(e,t,S),L=e.state.doc,B=L.slice(F.from,F.to),H,q;e.input.lastKeyCode===8&&Date.now()-100<e.input.lastKeyCodeTime?(H=e.state.selection.to,q=`end`):(H=e.state.selection.from,q=`start`),e.input.lastKeyCode=null;let J=findDiff(B.content,F.doc.content,F.from,H,q);if(J&&e.input.domChangeCount++,(ios&&e.input.lastIOSEnter>Date.now()-225||android)&&E.some(e=>e.nodeType==1&&!isInline.test(e.nodeName))&&(!J||J.endA>=J.endB)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(!J)if(w&&j instanceof TextSelection&&!j.empty&&j.$head.sameParent(j.$anchor)&&!e.composing&&!(F.sel&&F.sel.anchor!=F.sel.head))J={start:j.from,endA:j.to,endB:j.to};else{if(F.sel){let t=resolveSelection(e,e.state.doc,F.sel);if(t&&!t.eq(e.state.selection)){let S=e.state.tr.setSelection(t);D&&S.setMeta(`composition`,D),e.dispatch(S)}}return}e.state.selection.from<e.state.selection.to&&J.start==J.endB&&e.state.selection instanceof TextSelection&&(J.start>e.state.selection.from&&J.start<=e.state.selection.from+2&&e.state.selection.from>=F.from?J.start=e.state.selection.from:J.endA<e.state.selection.to&&J.endA>=e.state.selection.to-2&&e.state.selection.to<=F.to&&(J.endB+=e.state.selection.to-J.endA,J.endA=e.state.selection.to)),ie$2&&ie_version<=11&&J.endB==J.start+1&&J.endA==J.start&&J.start>F.from&&F.doc.textBetween(J.start-F.from-1,J.start-F.from+1)==` \xA0`&&(J.start--,J.endA--,J.endB--);let Y=F.doc.resolveNoCache(J.start-F.from),ee=F.doc.resolveNoCache(J.endB-F.from),te=L.resolve(J.start),ne=Y.sameParent(ee)&&Y.parent.inlineContent&&te.end()>=J.endA;if((ios&&e.input.lastIOSEnter>Date.now()-225&&(!ne||E.some(e=>e.nodeName==`DIV`||e.nodeName==`P`))||!ne&&Y.pos<F.doc.content.size&&(!Y.sameParent(ee)||!Y.parent.inlineContent)&&Y.pos<ee.pos&&!/\S/.test(F.doc.textBetween(Y.pos,ee.pos,``,``)))&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(13,`Enter`)))){e.input.lastIOSEnter=0;return}if(e.state.selection.anchor>J.start&&looksLikeBackspace(L,J.start,J.endA,Y,ee)&&e.someProp(`handleKeyDown`,t=>t(e,keyEvent(8,`Backspace`)))){android&&chrome&&e.domObserver.suppressSelectionUpdates();return}chrome&&J.endB==J.start&&(e.input.lastChromeDelete=Date.now()),android&&!ne&&Y.start()!=ee.start()&&ee.parentOffset==0&&Y.depth==ee.depth&&F.sel&&F.sel.anchor==F.sel.head&&F.sel.head==J.endA&&(J.endB-=2,ee=F.doc.resolveNoCache(J.endB-F.from),setTimeout(()=>{e.someProp(`handleKeyDown`,function(t){return t(e,keyEvent(13,`Enter`))})},20));let ae=J.start,oe=J.endA,se=t=>{let S=t||e.state.tr.replace(ae,oe,F.doc.slice(J.start-F.from,J.endB-F.from));if(F.sel){let t=resolveSelection(e,S.doc,F.sel);t&&!(chrome&&e.composing&&t.empty&&(J.start!=J.endB||e.input.lastChromeDelete<Date.now()-100)&&(t.head==ae||t.head==S.mapping.map(oe)-1)||ie$2&&t.empty&&t.head==ae)&&S.setSelection(t)}return D&&S.setMeta(`composition`,D),S.scrollIntoView()},ce;if(ne)if(Y.pos==ee.pos){ie$2&&ie_version<=11&&Y.parentOffset==0&&(e.domObserver.suppressSelectionUpdates(),setTimeout(()=>selectionToDOM(e),20));let t=se(e.state.tr.delete(ae,oe)),S=L.resolve(J.start).marksAcross(L.resolve(J.endA));S&&t.ensureMarks(S),e.dispatch(t)}else if(J.endA==J.endB&&(ce=isMarkChange(Y.parent.content.cut(Y.parentOffset,ee.parentOffset),te.parent.content.cut(te.parentOffset,J.endA-te.start())))){let t=se(e.state.tr);ce.type==`add`?t.addMark(ae,oe,ce.mark):t.removeMark(ae,oe,ce.mark),e.dispatch(t)}else if(Y.parent.child(Y.index()).isText&&Y.index()==ee.index()-(ee.textOffset?0:1)){let t=Y.parent.textBetween(Y.parentOffset,ee.parentOffset),S=()=>se(e.state.tr.insertText(t,ae,oe));e.someProp(`handleTextInput`,w=>w(e,ae,oe,t,S))||e.dispatch(S())}else e.dispatch(se());else e.dispatch(se())}function resolveSelection(e,t,S){return Math.max(S.anchor,S.head)>t.content.size?null:selectionBetween(e,t.resolve(S.anchor),t.resolve(S.head))}function isMarkChange(e,t){let S=e.firstChild.marks,w=t.firstChild.marks,E=S,D=w,O,k,j;for(let e=0;e<w.length;e++)E=w[e].removeFromSet(E);for(let e=0;e<S.length;e++)D=S[e].removeFromSet(D);if(E.length==1&&D.length==0)k=E[0],O=`add`,j=e=>e.mark(k.addToSet(e.marks));else if(E.length==0&&D.length==1)k=D[0],O=`remove`,j=e=>e.mark(k.removeFromSet(e.marks));else return null;let F=[];for(let e=0;e<t.childCount;e++)F.push(j(t.child(e)));if(Fragment.from(F).eq(e))return{mark:k,type:O}}function looksLikeBackspace(e,t,S,w,E){if(S-t<=E.pos-w.pos||skipClosingAndOpening(w,!0,!1)<E.pos)return!1;let D=e.resolve(t);if(!w.parent.isTextblock){let e=D.nodeAfter;return e!=null&&S==t+e.nodeSize}if(D.parentOffset<D.parent.content.size||!D.parent.isTextblock)return!1;let O=e.resolve(skipClosingAndOpening(D,!0,!0));return!O.parent.isTextblock||O.pos>S||skipClosingAndOpening(O,!0,!1)<S?!1:w.parent.content.cut(w.parentOffset).eq(O.parent.content)}function skipClosingAndOpening(e,t,S){let w=e.depth,E=t?e.end():e.pos;for(;w>0&&(t||e.indexAfter(w)==e.node(w).childCount);)w--,E++,t=!1;if(S){let t=e.node(w).maybeChild(e.indexAfter(w));for(;t&&!t.isLeaf;)t=t.firstChild,E++}return E}function findDiff(e,t,S,w,E){let D=e.findDiffStart(t,S);if(D==null)return null;let{a:O,b:k}=e.findDiffEnd(t,S+e.size,S+t.size);if(E==`end`){let e=Math.max(0,D-Math.min(O,k));w-=O+e-D}if(O<D&&e.size<t.size){let e=w<=D&&w>=O?D-w:0;D-=e,D&&D<t.size&&isSurrogatePair$1(t.textBetween(D-1,D+1))&&(D+=e?1:-1),k=D+(k-O),O=D}else if(k<D){let t=w<=D&&w>=k?D-w:0;D-=t,D&&D<e.size&&isSurrogatePair$1(e.textBetween(D-1,D+1))&&(D+=t?1:-1),O=D+(O-k),k=D}return{start:D,endA:O,endB:k}}function isSurrogatePair$1(e){if(e.length!=2)return!1;let t=e.charCodeAt(0),S=e.charCodeAt(1);return t>=56320&&t<=57343&&S>=55296&&S<=56319}var EditorView=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new InputState,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(checkStateComponent),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement(`div`),e&&(e.appendChild?e.appendChild(this.dom):typeof e==`function`?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=getEditable(this),updateCursorWrapper(this),this.nodeViews=buildNodeViews(this),this.docView=docViewDesc(this.state.doc,computeDocDeco(this),viewDecorations(this),this.dom,this),this.domObserver=new DOMObserver(this,(e,t,S,w)=>readDOMChange(this,e,t,S,w)),this.domObserver.start(),initInput(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ensureListeners(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(checkStateComponent),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let e in this._props)t[e]=this._props[e];t.state=this.state;for(let S in e)t[S]=e[S];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var S;let w=this.state,E=!1,D=!1;e.storedMarks&&this.composing&&(clearComposition(this),D=!0),this.state=e;let O=w.plugins!=e.plugins||this._props.plugins!=t.plugins;if(O||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let e=buildNodeViews(this);changedNodeViews(e,this.nodeViews)&&(this.nodeViews=e,E=!0)}(O||t.handleDOMEvents!=this._props.handleDOMEvents)&&ensureListeners(this),this.editable=getEditable(this),updateCursorWrapper(this);let k=viewDecorations(this),j=computeDocDeco(this),F=w.plugins!=e.plugins&&!w.doc.eq(e.doc)?`reset`:e.scrollToSelection>w.scrollToSelection?`to selection`:`preserve`,L=E||!this.docView.matchesNode(e.doc,j,k);(L||!e.selection.eq(w.selection))&&(D=!0);let B=F==`preserve`&&D&&this.dom.style.overflowAnchor==null&&storeScrollPos(this);if(D){this.domObserver.stop();let t=L&&(ie$2||chrome)&&!this.composing&&!w.selection.empty&&!e.selection.empty&&selectionContextChanged(w.selection,e.selection);if(L){let S=chrome?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=findCompositionNode(this)),(E||!this.docView.update(e.doc,j,k,this))&&(this.docView.updateOuterDeco(j),this.docView.destroy(),this.docView=docViewDesc(e.doc,j,k,this.dom,this)),S&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(t=!0)}t||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&anchorInRightPlace(this))?selectionToDOM(this,t):(syncNodeSelection(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(w),this.dragging?.node&&!w.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,w),F==`reset`?this.dom.scrollTop=0:F==`to selection`?this.scrollToSelection():B&&resetScrollPos(B)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))&&!this.someProp(`handleScrollToSelection`,e=>e(this)))if(this.state.selection instanceof NodeSelection){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&scrollRectIntoView(this,t.getBoundingClientRect(),e)}else scrollRectIntoView(this,this.coordsAtPos(this.state.selection.head,1),e)}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let e=0;e<this.directPlugins.length;e++){let t=this.directPlugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}for(let e=0;e<this.state.plugins.length;e++){let t=this.state.plugins[e];t.spec.view&&this.pluginViews.push(t.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let S=this.pluginViews[t];S.update&&S.update(this,e)}}updateDraggedNode(e,t){let S=e.node,w=-1;if(S.from<this.state.doc.content.size&&this.state.doc.nodeAt(S.from)==S.node)w=S.from;else{let e=S.from+(this.state.doc.content.size-t.doc.content.size);(e>0&&e<this.state.doc.content.size&&this.state.doc.nodeAt(e))==S.node&&(w=e)}this.dragging=new Dragging(e.slice,e.move,w<0?void 0:NodeSelection.create(this.state.doc,w))}someProp(e,t){let S=this._props&&this._props[e],w;if(S!=null&&(w=t?t(S):S))return w;for(let S=0;S<this.directPlugins.length;S++){let E=this.directPlugins[S].props[e];if(E!=null&&(w=t?t(E):E))return w}let E=this.state.plugins;if(E)for(let S=0;S<E.length;S++){let D=E[S].props[e];if(D!=null&&(w=t?t(D):D))return w}}hasFocus(){if(ie$2){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable==`false`)return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&focusPreventScroll(this.dom),selectionToDOM(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let e=this.dom.parentNode;e;e=e.parentNode)if(e.nodeType==9||e.nodeType==11&&e.host)return e.getSelection||(Object.getPrototypeOf(e).getSelection=()=>e.ownerDocument.getSelection()),this._root=e}return e||document}updateRoot(){this._root=null}posAtCoords(e){return posAtCoords(this,e)}coordsAtPos(e,t=1){return coordsAtPos(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,S=-1){let w=this.docView.posFromDOM(e,t,S);if(w==null)throw RangeError(`DOM position not inside the editor`);return w}endOfTextblock(e,t){return endOfTextblock(this,t||this.state,e)}pasteHTML(e,t){return doPaste(this,``,e,!1,t||new ClipboardEvent(`paste`))}pasteText(e,t){return doPaste(this,e,null,!0,t||new ClipboardEvent(`paste`))}serializeForClipboard(e){return serializeForClipboard(this,e)}destroy(){this.docView&&(destroyInput(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],viewDecorations(this),this),this.dom.textContent=``):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,clearReusedRange())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dispatchEvent(this,e)}domSelectionRange(){let e=this.domSelection();return e?safari&&this.root.nodeType===11&&deepActiveElement(this.dom.ownerDocument)==this.dom&&safariShadowSelectionRange(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};EditorView.prototype.dispatch=function(e){let t=this._props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function computeDocDeco(e){let t=Object.create(null);return t.class=`ProseMirror`,t.contenteditable=String(e.editable),e.someProp(`attributes`,S=>{if(typeof S==`function`&&(S=S(e.state)),S)for(let e in S)e==`class`?t.class+=` `+S[e]:e==`style`?t.style=(t.style?t.style+`;`:``)+S[e]:!t[e]&&e!=`contenteditable`&&e!=`nodeName`&&(t[e]=String(S[e]))}),t.translate||=`no`,[Decoration.node(0,e.state.doc.content.size,t)]}function updateCursorWrapper(e){if(e.markCursor){let t=document.createElement(`img`);t.className=`ProseMirror-separator`,t.setAttribute(`mark-placeholder`,`true`),t.setAttribute(`alt`,``),e.cursorWrapper={dom:t,deco:Decoration.widget(e.state.selection.from,t,{raw:!0,marks:e.markCursor})}}else e.cursorWrapper=null}function getEditable(e){return!e.someProp(`editable`,t=>t(e.state)===!1)}function selectionContextChanged(e,t){let S=Math.min(e.$anchor.sharedDepth(e.head),t.$anchor.sharedDepth(t.head));return e.$anchor.start(S)!=t.$anchor.start(S)}function buildNodeViews(e){let t=Object.create(null);function S(e){for(let S in e)Object.prototype.hasOwnProperty.call(t,S)||(t[S]=e[S])}return e.someProp(`nodeViews`,S),e.someProp(`markViews`,S),t}function changedNodeViews(e,t){let S=0,w=0;for(let w in e){if(e[w]!=t[w])return!0;S++}for(let e in t)w++;return S!=w}function checkStateComponent(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw RangeError(`Plugins passed directly to the view must not have a state component`)}for(var base$1={8:`Backspace`,9:`Tab`,10:`Enter`,12:`NumLock`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,44:`PrintScreen`,45:`Insert`,46:`Delete`,59:`;`,61:`=`,91:`Meta`,92:`Meta`,106:`*`,107:`+`,108:`,`,109:`-`,110:`.`,111:`/`,144:`NumLock`,145:`ScrollLock`,160:`Shift`,161:`Shift`,162:`Control`,163:`Control`,164:`Alt`,165:`Alt`,173:`-`,186:`;`,187:`=`,188:`,`,189:`-`,190:`.`,191:`/`,192:"`",219:`[`,220:`\\`,221:`]`,222:`'`},shift={48:`)`,49:`!`,50:`@`,51:`#`,52:`$`,53:`%`,54:`^`,55:`&`,56:`*`,57:`(`,59:`:`,61:`+`,173:`_`,186:`:`,187:`+`,188:`<`,189:`_`,190:`>`,191:`?`,192:`~`,219:`{`,220:`|`,221:`}`,222:`"`},mac$1=typeof navigator<`u`&&/Mac/.test(navigator.platform),ie$1=typeof navigator<`u`&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base$1[48+i]=base$1[96+i]=String(i);for(var i=1;i<=24;i++)base$1[i+111]=`F`+i;for(var i=65;i<=90;i++)base$1[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code$2 in base$1)shift.hasOwnProperty(code$2)||(shift[code$2]=base$1[code$2]);function keyName(e){var t=!(mac$1&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||ie$1&&e.shiftKey&&e.key&&e.key.length==1||e.key==`Unidentified`)&&e.key||(e.shiftKey?shift:base$1)[e.keyCode]||e.key||`Unidentified`;return t==`Esc`&&(t=`Escape`),t==`Del`&&(t=`Delete`),t==`Left`&&(t=`ArrowLeft`),t==`Up`&&(t=`ArrowUp`),t==`Right`&&(t=`ArrowRight`),t==`Down`&&(t=`ArrowDown`),t}const mac=typeof navigator<`u`&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),windows=typeof navigator<`u`&&/Win/.test(navigator.platform);function normalizeKeyName$1(e){let t=e.split(/-(?!$)/),S=t[t.length-1];S==`Space`&&(S=` `);let w,E,D,O;for(let e=0;e<t.length-1;e++){let S=t[e];if(/^(cmd|meta|m)$/i.test(S))O=!0;else if(/^a(lt)?$/i.test(S))w=!0;else if(/^(c|ctrl|control)$/i.test(S))E=!0;else if(/^s(hift)?$/i.test(S))D=!0;else if(/^mod$/i.test(S))mac?O=!0:E=!0;else throw Error(`Unrecognized modifier name: `+S)}return w&&(S=`Alt-`+S),E&&(S=`Ctrl-`+S),O&&(S=`Meta-`+S),D&&(S=`Shift-`+S),S}function normalize$4(e){let t=Object.create(null);for(let S in e)t[normalizeKeyName$1(S)]=e[S];return t}function modifiers(e,t,S=!0){return t.altKey&&(e=`Alt-`+e),t.ctrlKey&&(e=`Ctrl-`+e),t.metaKey&&(e=`Meta-`+e),S&&t.shiftKey&&(e=`Shift-`+e),e}function keymap(e){return new Plugin({props:{handleKeyDown:keydownHandler(e)}})}function keydownHandler(e){let t=normalize$4(e);return function(e,S){let w=keyName(S),E,D=t[modifiers(w,S)];if(D&&D(e.state,e.dispatch,e))return!0;if(w.length==1&&w!=` `){if(S.shiftKey){let E=t[modifiers(w,S,!1)];if(E&&E(e.state,e.dispatch,e))return!0}if((S.altKey||S.metaKey||S.ctrlKey)&&!(windows&&S.ctrlKey&&S.altKey)&&(E=base$1[S.keyCode])&&E!=w){let w=t[modifiers(E,S)];if(w&&w(e.state,e.dispatch,e))return!0}}return!1}}var __defProp$2=Object.defineProperty,__export$1=(e,t)=>{for(var S in t)__defProp$2(e,S,{get:t[S],enumerable:!0})};function createChainableState(e){let{state:t,transaction:S}=e,{selection:w}=S,{doc:E}=S,{storedMarks:D}=S;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return D},get selection(){return w},get doc(){return E},get tr(){return w=S.selection,E=S.doc,D=S.storedMarks,S}}}var CommandManager=class{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){let{rawCommands:e,editor:t,state:S}=this,{view:w}=t,{tr:E}=S,D=this.buildProps(E);return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,(...e)=>{let S=t(...e)(D);return!E.getMeta(`preventDispatch`)&&!this.hasCustomState&&w.dispatch(E),S}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){let{rawCommands:S,editor:w,state:E}=this,{view:D}=w,O=[],k=!!e,j=e||E.tr,F=()=>(!k&&t&&!j.getMeta(`preventDispatch`)&&!this.hasCustomState&&D.dispatch(j),O.every(e=>e===!0)),L={...Object.fromEntries(Object.entries(S).map(([e,S])=>[e,(...e)=>{let w=this.buildProps(j,t),E=S(...e)(w);return O.push(E),L}])),run:F};return L}createCan(e){let{rawCommands:t,state:S}=this,w=!1,E=e||S.tr,D=this.buildProps(E,!1);return{...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>t(...e)({...D,dispatch:void 0})])),chain:()=>this.createChain(E,!1)}}buildProps(e,t=!0){let{rawCommands:S,editor:w,state:E}=this,{view:D}=w,O={tr:e,editor:w,view:D,state:createChainableState({state:E,transaction:e}),dispatch:t?()=>void 0:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(S).map(([e,t])=>[e,(...e)=>t(...e)(O)]))}};return O}},commands_exports={};__export$1(commands_exports,{blur:()=>blur,clearContent:()=>clearContent,clearNodes:()=>clearNodes,command:()=>command,createParagraphNear:()=>createParagraphNear,cut:()=>cut,deleteCurrentNode:()=>deleteCurrentNode,deleteNode:()=>deleteNode,deleteRange:()=>deleteRange,deleteSelection:()=>deleteSelection,enter:()=>enter,exitCode:()=>exitCode,extendMarkRange:()=>extendMarkRange,first:()=>first,focus:()=>focus,forEach:()=>forEach$1,insertContent:()=>insertContent,insertContentAt:()=>insertContentAt,joinBackward:()=>joinBackward,joinDown:()=>joinDown,joinForward:()=>joinForward,joinItemBackward:()=>joinItemBackward,joinItemForward:()=>joinItemForward,joinTextblockBackward:()=>joinTextblockBackward,joinTextblockForward:()=>joinTextblockForward,joinUp:()=>joinUp,keyboardShortcut:()=>keyboardShortcut,lift:()=>lift,liftEmptyBlock:()=>liftEmptyBlock,liftListItem:()=>liftListItem,newlineInCode:()=>newlineInCode,resetAttributes:()=>resetAttributes,scrollIntoView:()=>scrollIntoView,selectAll:()=>selectAll,selectNodeBackward:()=>selectNodeBackward,selectNodeForward:()=>selectNodeForward,selectParentNode:()=>selectParentNode,selectTextblockEnd:()=>selectTextblockEnd,selectTextblockStart:()=>selectTextblockStart,setContent:()=>setContent,setMark:()=>setMark,setMeta:()=>setMeta,setNode:()=>setNode,setNodeSelection:()=>setNodeSelection,setTextDirection:()=>setTextDirection,setTextSelection:()=>setTextSelection,sinkListItem:()=>sinkListItem,splitBlock:()=>splitBlock,splitListItem:()=>splitListItem,toggleList:()=>toggleList,toggleMark:()=>toggleMark,toggleNode:()=>toggleNode,toggleWrap:()=>toggleWrap,undoInputRule:()=>undoInputRule,unsetAllMarks:()=>unsetAllMarks,unsetMark:()=>unsetMark,unsetTextDirection:()=>unsetTextDirection,updateAttributes:()=>updateAttributes,wrapIn:()=>wrapIn,wrapInList:()=>wrapInList});var blur=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var S;e.isDestroyed||(t.dom.blur(),(S=window==null?void 0:window.getSelection())==null||S.removeAllRanges())}),!0),clearContent=(e=!0)=>({commands:t})=>t.setContent(``,{emitUpdate:e}),clearNodes=()=>({state:e,tr:t,dispatch:S})=>{let{selection:w}=t,{ranges:E}=w;return S&&E.forEach(({$from:S,$to:w})=>{e.doc.nodesBetween(S.pos,w.pos,(e,S)=>{if(e.type.isText)return;let{doc:w,mapping:E}=t,D=w.resolve(E.map(S)),O=w.resolve(E.map(S+e.nodeSize)),k=D.blockRange(O);if(!k)return;let j=liftTarget(k);if(e.type.isTextblock){let{defaultType:e}=D.parent.contentMatchAt(D.index());t.setNodeMarkup(k.start,e)}(j||j===0)&&t.lift(k,j)})}),!0},command=e=>t=>e(t),createParagraphNear=()=>({state:e,dispatch:t})=>createParagraphNear$1(e,t),cut=(e,t)=>({editor:S,tr:w})=>{let{state:E}=S,D=E.doc.slice(e.from,e.to);w.deleteRange(e.from,e.to);let O=w.mapping.map(t);return w.insert(O,D.content),w.setSelection(new TextSelection(w.doc.resolve(Math.max(O-1,0)))),!0},deleteCurrentNode=()=>({tr:e,dispatch:t})=>{let{selection:S}=e,w=S.$anchor.node();if(w.content.size>0)return!1;let E=e.selection.$anchor;for(let S=E.depth;S>0;--S)if(E.node(S).type===w.type){if(t){let t=E.before(S),w=E.after(S);e.delete(t,w).scrollIntoView()}return!0}return!1};function getNodeType(e,t){if(typeof e==`string`){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}var deleteNode=e=>({tr:t,state:S,dispatch:w})=>{let E=getNodeType(e,S.schema),D=t.selection.$anchor;for(let e=D.depth;e>0;--e)if(D.node(e).type===E){if(w){let S=D.before(e),w=D.after(e);t.delete(S,w).scrollIntoView()}return!0}return!1},deleteRange=e=>({tr:t,dispatch:S})=>{let{from:w,to:E}=e;return S&&t.delete(w,E),!0},deleteSelection=()=>({state:e,dispatch:t})=>deleteSelection$1(e,t),enter=()=>({commands:e})=>e.keyboardShortcut(`Enter`),exitCode=()=>({state:e,dispatch:t})=>exitCode$1(e,t);function isRegExp(e){return Object.prototype.toString.call(e)===`[object RegExp]`}function objectIncludes(e,t,S={strict:!0}){let w=Object.keys(t);return w.length?w.every(w=>S.strict?t[w]===e[w]:isRegExp(t[w])?t[w].test(e[w]):t[w]===e[w]):!0}function findMarkInSet(e,t,S={}){return e.find(e=>e.type===t&&objectIncludes(Object.fromEntries(Object.keys(S).map(t=>[t,e.attrs[t]])),S))}function isMarkInSet(e,t,S={}){return!!findMarkInSet(e,t,S)}function getMarkRange(e,t,S){if(!e||!t)return;let w=e.parent.childAfter(e.parentOffset);if((!w.node||!w.node.marks.some(e=>e.type===t))&&(w=e.parent.childBefore(e.parentOffset)),!w.node||!w.node.marks.some(e=>e.type===t))return;if(!S){let e=w.node.marks.find(e=>e.type===t);e&&(S=e.attrs)}if(!findMarkInSet([...w.node.marks],t,S))return;let E=w.index,D=e.start()+w.offset,O=E+1,k=D+w.node.nodeSize;for(;E>0&&isMarkInSet([...e.parent.child(E-1).marks],t,S);)--E,D-=e.parent.child(E).nodeSize;for(;O<e.parent.childCount&&isMarkInSet([...e.parent.child(O).marks],t,S);)k+=e.parent.child(O).nodeSize,O+=1;return{from:D,to:k}}function getMarkType(e,t){if(typeof e==`string`){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}var extendMarkRange=(e,t)=>({tr:S,state:w,dispatch:E})=>{let D=getMarkType(e,w.schema),{doc:O,selection:k}=S,{$from:j,from:F,to:L}=k;if(E){let e=getMarkRange(j,D,t);if(e&&e.from<=F&&e.to>=L){let t=TextSelection.create(O,e.from,e.to);S.setSelection(t)}}return!0},first=e=>t=>{let S=typeof e==`function`?e(t):e;for(let e=0;e<S.length;e+=1)if(S[e](t))return!0;return!1};function isTextSelection(e){return e instanceof TextSelection}function minMax(e=0,t=0,S=0){return Math.min(Math.max(e,t),S)}function resolveFocusPosition(e,t=null){if(!t)return null;let S=Selection$1.atStart(e),w=Selection$1.atEnd(e);if(t===`start`||t===!0)return S;if(t===`end`)return w;let E=S.from,D=w.to;return t===`all`?TextSelection.create(e,minMax(0,E,D),minMax(e.content.size,E,D)):TextSelection.create(e,minMax(t,E,D),minMax(t,E,D))}function isAndroid(){return navigator.platform===`Android`||/android/i.test(navigator.userAgent)}function isiOS(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}function isSafari(){return typeof navigator<`u`?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var focus=(e=null,t={})=>({editor:S,view:w,tr:E,dispatch:D})=>{t={scrollIntoView:!0,...t};let O=()=>{(isiOS()||isAndroid())&&w.dom.focus(),isSafari()&&!isiOS()&&!isAndroid()&&w.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{S.isDestroyed||(w.focus(),t?.scrollIntoView&&S.commands.scrollIntoView())})};try{if(w.hasFocus()&&e===null||e===!1)return!0}catch{return!1}if(D&&e===null&&!isTextSelection(S.state.selection))return O(),!0;let k=resolveFocusPosition(E.doc,e)||S.state.selection,j=S.state.selection.eq(k);return D&&(j||E.setSelection(k),j&&E.storedMarks&&E.setStoredMarks(E.storedMarks),O()),!0},forEach$1=(e,t)=>S=>e.every((e,w)=>t(e,{...S,index:w})),insertContent=(e,t)=>({tr:S,commands:w})=>w.insertContentAt({from:S.selection.from,to:S.selection.to},e,t),removeWhitespaces=e=>{let t=e.childNodes;for(let S=t.length-1;S>=0;--S){let w=t[S];w.nodeType===3&&w.nodeValue&&/^(\n\s\s|\n)$/.test(w.nodeValue)?e.removeChild(w):w.nodeType===1&&removeWhitespaces(w)}return e};function elementFromString(e){if(typeof window>`u`)throw Error(`[tiptap error]: there is no window object available, so this function cannot be used`);let t=`<body>${e}</body>`,S=new window.DOMParser().parseFromString(t,`text/html`).body;return removeWhitespaces(S)}function createNodeFromContent(e,t,S){if(e instanceof Node||e instanceof Fragment)return e;S={slice:!0,parseOptions:{},...S};let w=typeof e==`object`&&!!e,E=typeof e==`string`;if(w)try{if(Array.isArray(e)&&e.length>0)return Fragment.fromArray(e.map(e=>t.nodeFromJSON(e)));let w=t.nodeFromJSON(e);return S.errorOnInvalidContent&&w.check(),w}catch(w){if(S.errorOnInvalidContent)throw Error(`[tiptap error]: Invalid JSON content`,{cause:w});return console.warn(`[tiptap warn]: Invalid content.`,`Passed value:`,e,`Error:`,w),createNodeFromContent(``,t,S)}if(E){if(S.errorOnInvalidContent){let w=!1,E=``,D=new Schema$1({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:`inline*`,group:`block`,parseDOM:[{tag:`*`,getAttrs:e=>(w=!0,E=typeof e==`string`?e:e.outerHTML,null)}]}})});if(S.slice?DOMParser.fromSchema(D).parseSlice(elementFromString(e),S.parseOptions):DOMParser.fromSchema(D).parse(elementFromString(e),S.parseOptions),S.errorOnInvalidContent&&w)throw Error(`[tiptap error]: Invalid HTML content`,{cause:Error(`Invalid element found: ${E}`)})}let w=DOMParser.fromSchema(t);return S.slice?w.parseSlice(elementFromString(e),S.parseOptions).content:w.parse(elementFromString(e),S.parseOptions)}return createNodeFromContent(``,t,S)}function selectionToInsertionEnd(e,t,S){let w=e.steps.length-1;if(w<t)return;let E=e.steps[w];if(!(E instanceof ReplaceStep||E instanceof ReplaceAroundStep))return;let D=e.mapping.maps[w],O=0;D.forEach((e,t,S,w)=>{O===0&&(O=w)}),e.setSelection(Selection$1.near(e.doc.resolve(O),S))}var isFragment=e=>!(`type`in e),insertContentAt=(e,t,S)=>({tr:w,dispatch:E,editor:D})=>{var O;if(E){S={parseOptions:D.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...S};let E,O=e=>{D.emit(`contentError`,{editor:D,error:e,disableCollaboration:()=>{`collaboration`in D.storage&&typeof D.storage.collaboration==`object`&&D.storage.collaboration&&(D.storage.collaboration.isDisabled=!0)}})},k={preserveWhitespace:`full`,...S.parseOptions};if(!S.errorOnInvalidContent&&!D.options.enableContentCheck&&D.options.emitContentError)try{createNodeFromContent(t,D.schema,{parseOptions:k,errorOnInvalidContent:!0})}catch(e){O(e)}try{E=createNodeFromContent(t,D.schema,{parseOptions:k,errorOnInvalidContent:S.errorOnInvalidContent??D.options.enableContentCheck})}catch(e){return O(e),!1}let{from:j,to:F}=typeof e==`number`?{from:e,to:e}:{from:e.from,to:e.to},L=!0,B=!0;if((isFragment(E)?E:[E]).forEach(e=>{e.check(),L=L?e.isText&&e.marks.length===0:!1,B=B?e.isBlock:!1}),j===F&&B){let{parent:e}=w.doc.resolve(j);e.isTextblock&&!e.type.spec.code&&!e.childCount&&(--j,F+=1)}let H;if(L){if(Array.isArray(t))H=t.map(e=>e.text||``).join(``);else if(t instanceof Fragment){let e=``;t.forEach(t=>{t.text&&(e+=t.text)}),H=e}else H=typeof t==`object`&&t&&t.text?t.text:t;w.insertText(H,j,F)}else{H=E;let e=w.doc.resolve(j),t=e.node(),S=e.parentOffset===0,D=t.isText||t.isTextblock,O=t.content.size>0;S&&D&&O&&B&&(j=Math.max(0,j-1)),w.replaceWith(j,F,H)}S.updateSelection&&selectionToInsertionEnd(w,w.steps.length-1,-1),S.applyInputRules&&w.setMeta(`applyInputRules`,{from:j,text:H}),S.applyPasteRules&&w.setMeta(`applyPasteRules`,{from:j,text:H})}return!0},joinUp=()=>({state:e,dispatch:t})=>joinUp$1(e,t),joinDown=()=>({state:e,dispatch:t})=>joinDown$1(e,t),joinBackward=()=>({state:e,dispatch:t})=>joinBackward$1(e,t),joinForward=()=>({state:e,dispatch:t})=>joinForward$1(e,t),joinItemBackward=()=>({state:e,dispatch:t,tr:S})=>{try{let w=joinPoint(e.doc,e.selection.$from.pos,-1);return w==null?!1:(S.join(w,2),t&&t(S),!0)}catch{return!1}},joinItemForward=()=>({state:e,dispatch:t,tr:S})=>{try{let w=joinPoint(e.doc,e.selection.$from.pos,1);return w==null?!1:(S.join(w,2),t&&t(S),!0)}catch{return!1}},joinTextblockBackward=()=>({state:e,dispatch:t})=>joinTextblockBackward$1(e,t),joinTextblockForward=()=>({state:e,dispatch:t})=>joinTextblockForward$1(e,t);function isMacOS(){return typeof navigator<`u`?/Mac/.test(navigator.platform):!1}function normalizeKeyName(e){let t=e.split(/-(?!$)/),S=t[t.length-1];S===`Space`&&(S=` `);let w,E,D,O;for(let e=0;e<t.length-1;e+=1){let S=t[e];if(/^(cmd|meta|m)$/i.test(S))O=!0;else if(/^a(lt)?$/i.test(S))w=!0;else if(/^(c|ctrl|control)$/i.test(S))E=!0;else if(/^s(hift)?$/i.test(S))D=!0;else if(/^mod$/i.test(S))isiOS()||isMacOS()?O=!0:E=!0;else throw Error(`Unrecognized modifier name: ${S}`)}return w&&(S=`Alt-${S}`),E&&(S=`Ctrl-${S}`),O&&(S=`Meta-${S}`),D&&(S=`Shift-${S}`),S}var keyboardShortcut=e=>({editor:t,view:S,tr:w,dispatch:E})=>{let D=normalizeKeyName(e).split(/-(?!$)/),O=D.find(e=>![`Alt`,`Ctrl`,`Meta`,`Shift`].includes(e)),k=new KeyboardEvent(`keydown`,{key:O===`Space`?` `:O,altKey:D.includes(`Alt`),ctrlKey:D.includes(`Ctrl`),metaKey:D.includes(`Meta`),shiftKey:D.includes(`Shift`),bubbles:!0,cancelable:!0});return t.captureTransaction(()=>{S.someProp(`handleKeyDown`,e=>e(S,k))})?.steps.forEach(e=>{let t=e.map(w.mapping);t&&E&&w.maybeStep(t)}),!0};function isNodeActive(e,t,S={}){let{from:w,to:E,empty:D}=e.selection,O=t?getNodeType(t,e.schema):null,k=[];e.doc.nodesBetween(w,E,(e,t)=>{if(e.isText)return;let S=Math.max(w,t),D=Math.min(E,t+e.nodeSize);k.push({node:e,from:S,to:D})});let j=E-w,F=k.filter(e=>O?O.name===e.node.type.name:!0).filter(e=>objectIncludes(e.node.attrs,S,{strict:!1}));return D?!!F.length:F.reduce((e,t)=>e+t.to-t.from,0)>=j}var lift=(e,t={})=>({state:S,dispatch:w})=>isNodeActive(S,getNodeType(e,S.schema),t)?lift$1(S,w):!1,liftEmptyBlock=()=>({state:e,dispatch:t})=>liftEmptyBlock$1(e,t),liftListItem=e=>({state:t,dispatch:S})=>liftListItem$1(getNodeType(e,t.schema))(t,S),newlineInCode=()=>({state:e,dispatch:t})=>newlineInCode$1(e,t);function getSchemaTypeNameByName(e,t){return t.nodes[e]?`node`:t.marks[e]?`mark`:null}function deleteProps(e,t){let S=typeof t==`string`?[t]:t;return Object.keys(e).reduce((t,w)=>(S.includes(w)||(t[w]=e[w]),t),{})}var resetAttributes=(e,t)=>({tr:S,state:w,dispatch:E})=>{let D=null,O=null,k=getSchemaTypeNameByName(typeof e==`string`?e:e.name,w.schema);if(!k)return!1;k===`node`&&(D=getNodeType(e,w.schema)),k===`mark`&&(O=getMarkType(e,w.schema));let j=!1;return S.selection.ranges.forEach(e=>{w.doc.nodesBetween(e.$from.pos,e.$to.pos,(e,w)=>{D&&D===e.type&&(j=!0,E&&S.setNodeMarkup(w,void 0,deleteProps(e.attrs,t))),O&&e.marks.length&&e.marks.forEach(D=>{O===D.type&&(j=!0,E&&S.addMark(w,w+e.nodeSize,O.create(deleteProps(D.attrs,t))))})})}),j},scrollIntoView=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),selectAll=()=>({tr:e,dispatch:t})=>{if(t){let t=new AllSelection(e.doc);e.setSelection(t)}return!0},selectNodeBackward=()=>({state:e,dispatch:t})=>selectNodeBackward$1(e,t),selectNodeForward=()=>({state:e,dispatch:t})=>selectNodeForward$1(e,t),selectParentNode=()=>({state:e,dispatch:t})=>selectParentNode$1(e,t),selectTextblockEnd=()=>({state:e,dispatch:t})=>selectTextblockEnd$1(e,t),selectTextblockStart=()=>({state:e,dispatch:t})=>selectTextblockStart$1(e,t);function createDocument(e,t,S={},w={}){return createNodeFromContent(e,t,{slice:!1,parseOptions:S,errorOnInvalidContent:w.errorOnInvalidContent})}var setContent=(e,{errorOnInvalidContent:t,emitUpdate:S=!0,parseOptions:w={}}={})=>({editor:E,tr:D,dispatch:O,commands:k})=>{let{doc:j}=D;if(w.preserveWhitespace!==`full`){let k=createDocument(e,E.schema,w,{errorOnInvalidContent:t??E.options.enableContentCheck});return O&&D.replaceWith(0,j.content.size,k).setMeta(`preventUpdate`,!S),!0}return O&&D.setMeta(`preventUpdate`,!S),k.insertContentAt({from:0,to:j.content.size},e,{parseOptions:w,errorOnInvalidContent:t??E.options.enableContentCheck})};function getMarkAttributes(e,t){let S=getMarkType(t,e.schema),{from:w,to:E,empty:D}=e.selection,O=[];D?(e.storedMarks&&O.push(...e.storedMarks),O.push(...e.selection.$head.marks())):e.doc.nodesBetween(w,E,e=>{O.push(...e.marks)});let k=O.find(e=>e.type.name===S.name);return k?{...k.attrs}:{}}function combineTransactionSteps(e,t){let S=new Transform$3(e);return t.forEach(e=>{e.steps.forEach(e=>{S.step(e)})}),S}function defaultBlockAt(e){for(let t=0;t<e.edgeCount;t+=1){let{type:S}=e.edge(t);if(S.isTextblock&&!S.hasRequiredAttrs())return S}return null}function findChildrenInRange(e,t,S){let w=[];return e.nodesBetween(t.from,t.to,(e,t)=>{S(e)&&w.push({node:e,pos:t})}),w}function findParentNodeClosestToPos(e,t){for(let S=e.depth;S>0;--S){let w=e.node(S);if(t(w))return{pos:S>0?e.before(S):0,start:e.start(S),depth:S,node:w}}}function findParentNode(e){return t=>findParentNodeClosestToPos(t.$from,e)}function getExtensionField(e,t,S){return e.config[t]===void 0&&e.parent?getExtensionField(e.parent,t,S):typeof e.config[t]==`function`?e.config[t].bind({...S,parent:e.parent?getExtensionField(e.parent,t,S):null}):e.config[t]}function flattenExtensions(e){return e.map(e=>{let t=getExtensionField(e,`addExtensions`,{name:e.name,options:e.options,storage:e.storage});return t?[e,...flattenExtensions(t())]:e}).flat(10)}function getHTMLFromFragment(e,t){let S=DOMSerializer.fromSchema(t).serializeFragment(e),w=document.implementation.createHTMLDocument().createElement(`div`);return w.appendChild(S),w.innerHTML}function isFunction(e){return typeof e==`function`}function callOrReturn(e,t=void 0,...S){return isFunction(e)?t?e.bind(t)(...S):e(...S):e}function isEmptyObject(e={}){return Object.keys(e).length===0&&e.constructor===Object}function splitExtensions(e){return{baseExtensions:e.filter(e=>e.type===`extension`),nodeExtensions:e.filter(e=>e.type===`node`),markExtensions:e.filter(e=>e.type===`mark`)}}function getAttributesFromExtensions(e){let t=[],{nodeExtensions:S,markExtensions:w}=splitExtensions(e),E=[...S,...w],D={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},O=S.filter(e=>e.name!==`text`).map(e=>e.name),k=w.map(e=>e.name),j=[...O,...k];return e.forEach(e=>{let S=getExtensionField(e,`addGlobalAttributes`,{name:e.name,options:e.options,storage:e.storage,extensions:E});S&&S().forEach(e=>{let S;S=Array.isArray(e.types)?e.types:e.types===`*`?j:e.types===`nodes`?O:e.types===`marks`?k:[],S.forEach(S=>{Object.entries(e.attributes).forEach(([e,w])=>{t.push({type:S,name:e,attribute:{...D,...w}})})})})}),E.forEach(e=>{let S=getExtensionField(e,`addAttributes`,{name:e.name,options:e.options,storage:e.storage});if(!S)return;let w=S();Object.entries(w).forEach(([S,w])=>{let E={...D,...w};typeof E?.default==`function`&&(E.default=E.default()),E?.isRequired&&E?.default===void 0&&delete E.default,t.push({type:e.name,name:S,attribute:E})})}),t}function splitStyleDeclarations(e){let t=[],S=``,w=!1,E=!1,D=0,O=e.length;for(let k=0;k<O;k+=1){let O=e[k];if(O===`'`&&!E){w=!w,S+=O;continue}if(O===`"`&&!w){E=!E,S+=O;continue}if(!w&&!E){if(O===`(`){D+=1,S+=O;continue}if(O===`)`&&D>0){--D,S+=O;continue}if(O===`;`&&D===0){t.push(S),S=``;continue}}S+=O}return S&&t.push(S),t}function parseStyleEntries(e){let t=[],S=splitStyleDeclarations(e||``),w=S.length;for(let e=0;e<w;e+=1){let w=S[e],E=w.indexOf(`:`);if(E===-1)continue;let D=w.slice(0,E).trim(),O=w.slice(E+1).trim();D&&O&&t.push([D,O])}return t}function mergeAttributes(...e){return e.filter(e=>!!e).reduce((e,t)=>{let S={...e};return Object.entries(t).forEach(([e,t])=>{if(!S[e]){S[e]=t;return}if(e===`class`){let w=t?String(t).split(` `):[],E=S[e]?S[e].split(` `):[],D=w.filter(e=>!E.includes(e));S[e]=[...E,...D].join(` `)}else if(e===`style`){let w=new Map([...parseStyleEntries(S[e]),...parseStyleEntries(t)]);S[e]=Array.from(w.entries()).map(([e,t])=>`${e}: ${t}`).join(`; `)}else S[e]=t}),S},{})}function getRenderedAttributes(e,t){return t.filter(t=>t.type===e.type.name).filter(e=>e.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(e.attrs)||{}:{[t.name]:e.attrs[t.name]}).reduce((e,t)=>mergeAttributes(e,t),{})}function fromString(e){return typeof e==`string`?e.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(e):e===`true`?!0:e===`false`?!1:e:e}function injectExtensionAttributesToParseRule(e,t){return`style`in e?e:{...e,getAttrs:S=>{let w=e.getAttrs?e.getAttrs(S):e.attrs;if(w===!1)return!1;let E=t.reduce((e,t)=>{let w=t.attribute.parseHTML?t.attribute.parseHTML(S):fromString(S.getAttribute(t.name));return w==null?e:{...e,[t.name]:w}},{});return{...w,...E}}}}function cleanUpSchemaItem(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>e===`attrs`&&isEmptyObject(t)?!1:t!=null))}function buildAttributeSpec(e){var t,S;let w={};return!e?.attribute?.isRequired&&`default`in(e?.attribute||{})&&(w.default=e.attribute.default),e?.attribute?.validate!==void 0&&(w.validate=e.attribute.validate),[e.name,w]}function getSchemaByResolvedExtensions(e,t){var S;let w=getAttributesFromExtensions(e),{nodeExtensions:E,markExtensions:D}=splitExtensions(e);return new Schema$1({topNode:E.find(e=>getExtensionField(e,`topNode`))?.name,nodes:Object.fromEntries(E.map(S=>{let E=w.filter(e=>e.type===S.name),D={name:S.name,options:S.options,storage:S.storage,editor:t},O=cleanUpSchemaItem({...e.reduce((e,t)=>{let w=getExtensionField(t,`extendNodeSchema`,D);return{...e,...w?w(S):{}}},{}),content:callOrReturn(getExtensionField(S,`content`,D)),marks:callOrReturn(getExtensionField(S,`marks`,D)),group:callOrReturn(getExtensionField(S,`group`,D)),inline:callOrReturn(getExtensionField(S,`inline`,D)),atom:callOrReturn(getExtensionField(S,`atom`,D)),selectable:callOrReturn(getExtensionField(S,`selectable`,D)),draggable:callOrReturn(getExtensionField(S,`draggable`,D)),code:callOrReturn(getExtensionField(S,`code`,D)),whitespace:callOrReturn(getExtensionField(S,`whitespace`,D)),linebreakReplacement:callOrReturn(getExtensionField(S,`linebreakReplacement`,D)),defining:callOrReturn(getExtensionField(S,`defining`,D)),isolating:callOrReturn(getExtensionField(S,`isolating`,D)),attrs:Object.fromEntries(E.map(buildAttributeSpec))}),k=callOrReturn(getExtensionField(S,`parseHTML`,D));k&&(O.parseDOM=k.map(e=>injectExtensionAttributesToParseRule(e,E)));let j=getExtensionField(S,`renderHTML`,D);j&&(O.toDOM=e=>j({node:e,HTMLAttributes:getRenderedAttributes(e,E)}));let F=getExtensionField(S,`renderText`,D);return F&&(O.toText=F),[S.name,O]})),marks:Object.fromEntries(D.map(S=>{let E=w.filter(e=>e.type===S.name),D={name:S.name,options:S.options,storage:S.storage,editor:t},O=cleanUpSchemaItem({...e.reduce((e,t)=>{let w=getExtensionField(t,`extendMarkSchema`,D);return{...e,...w?w(S):{}}},{}),inclusive:callOrReturn(getExtensionField(S,`inclusive`,D)),excludes:callOrReturn(getExtensionField(S,`excludes`,D)),group:callOrReturn(getExtensionField(S,`group`,D)),spanning:callOrReturn(getExtensionField(S,`spanning`,D)),code:callOrReturn(getExtensionField(S,`code`,D)),attrs:Object.fromEntries(E.map(buildAttributeSpec))}),k=callOrReturn(getExtensionField(S,`parseHTML`,D));k&&(O.parseDOM=k.map(e=>injectExtensionAttributesToParseRule(e,E)));let j=getExtensionField(S,`renderHTML`,D);return j&&(O.toDOM=e=>j({mark:e,HTMLAttributes:getRenderedAttributes(e,E)})),[S.name,O]}))})}function findDuplicates(e){let t=e.filter((t,S)=>e.indexOf(t)!==S);return Array.from(new Set(t))}function sortExtensions(e){let t=100;return e.sort((e,t)=>{let S=getExtensionField(e,`priority`)||100,w=getExtensionField(t,`priority`)||100;return S>w?-1:S<w?1:0})}function resolveExtensions(e){let t=sortExtensions(flattenExtensions(e)),S=findDuplicates(t.map(e=>e.name));return S.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${S.map(e=>`'${e}'`).join(`, `)}]. This can lead to issues.`),t}function getSchema(e,t){return getSchemaByResolvedExtensions(resolveExtensions(e),t)}function getTextBetween(e,t,S){let{from:w,to:E}=t,{blockSeparator:D=`
|
|
170
170
|
|
|
171
171
|
`,textSerializers:O={}}=S||{},k=``;return e.nodesBetween(w,E,(e,S,j,F)=>{var L;e.isBlock&&S>w&&(k+=D);let B=O?.[e.type.name];if(B)return j&&(k+=B({node:e,pos:S,parent:j,index:F,range:t})),!1;e.isText&&(k+=(e?.text)?.slice(Math.max(w,S)-S,E-S))}),k}function getTextSerializersFromSchema(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function getNodeAttributes(e,t){let S=getNodeType(t,e.schema),{from:w,to:E}=e.selection,D=[];e.doc.nodesBetween(w,E,e=>{D.push(e)});let O=D.reverse().find(e=>e.type.name===S.name);return O?{...O.attrs}:{}}function getAttributes(e,t){let S=getSchemaTypeNameByName(typeof t==`string`?t:t.name,e.schema);return S===`node`?getNodeAttributes(e,t):S===`mark`?getMarkAttributes(e,t):{}}function removeDuplicates(e,t=JSON.stringify){let S={};return e.filter(e=>{let w=t(e);return Object.prototype.hasOwnProperty.call(S,w)?!1:S[w]=!0})}function simplifyChangedRanges(e){let t=removeDuplicates(e);return t.length===1?t:t.filter((e,S)=>!t.filter((e,t)=>t!==S).some(t=>e.oldRange.from>=t.oldRange.from&&e.oldRange.to<=t.oldRange.to&&e.newRange.from>=t.newRange.from&&e.newRange.to<=t.newRange.to))}function getChangedRanges(e){let{mapping:t,steps:S}=e,w=[];return t.maps.forEach((e,E)=>{let D=[];if(e.ranges.length)e.forEach((e,t)=>{D.push({from:e,to:t})});else{let{from:e,to:t}=S[E];if(e===void 0||t===void 0)return;D.push({from:e,to:t})}D.forEach(({from:e,to:S})=>{let D=t.slice(E).map(e,-1),O=t.slice(E).map(S),k=t.invert().map(D,-1),j=t.invert().map(O);w.push({oldRange:{from:k,to:j},newRange:{from:D,to:O}})})}),simplifyChangedRanges(w)}function getMarksBetween(e,t,S){let w=[];return e===t?S.resolve(e).marks().forEach(t=>{let E=getMarkRange(S.resolve(e),t.type);E&&w.push({mark:t,...E})}):S.nodesBetween(e,t,(e,t)=>{!e||e?.nodeSize===void 0||w.push(...e.marks.map(S=>({from:t,to:t+e.nodeSize,mark:S})))}),w}var getNodeAtPosition=(e,t,S,w=20)=>{let E=e.doc.resolve(S),D=w,O=null;for(;D>0&&O===null;){let e=E.node(D);e?.type.name===t?O=e:--D}return[O,D]};function getSchemaTypeByName(e,t){return t.nodes[e]||t.marks[e]||null}function getSplittedAttributes(e,t,S){return Object.fromEntries(Object.entries(S).filter(([S])=>{let w=e.find(e=>e.type===t&&e.name===S);return w?w.attribute.keepOnSplit:!1}))}var getTextContentFromNodes=(e,t=500)=>{let S=``,w=e.parentOffset;return e.parent.nodesBetween(Math.max(0,w-t),w,(e,t,E,D)=>{var O,k;let j=(O=e.type.spec).toText?.call(O,{node:e,pos:t,parent:E,index:D})||e.textContent||`%leaf%`;S+=e.isAtom&&!e.isText?j:j.slice(0,Math.max(0,w-t))}),S};function isMarkActive(e,t,S={}){let{empty:w,ranges:E}=e.selection,D=t?getMarkType(t,e.schema):null;if(w)return!!(e.storedMarks||e.selection.$from.marks()).filter(e=>D?D.name===e.type.name:!0).find(e=>objectIncludes(e.attrs,S,{strict:!1}));let O=0,k=[];if(E.forEach(({$from:t,$to:S})=>{let w=t.pos,E=S.pos;e.doc.nodesBetween(w,E,(e,t)=>{if(D&&e.inlineContent&&!e.type.allowsMarkType(D))return!1;if(!e.isText&&!e.marks.length)return;let S=Math.max(w,t),j=Math.min(E,t+e.nodeSize),F=j-S;O+=F,k.push(...e.marks.map(e=>({mark:e,from:S,to:j})))})}),O===0)return!1;let j=k.filter(e=>D?D.name===e.mark.type.name:!0).filter(e=>objectIncludes(e.mark.attrs,S,{strict:!1})).reduce((e,t)=>e+t.to-t.from,0),F=k.filter(e=>D?e.mark.type!==D&&e.mark.type.excludes(D):!0).reduce((e,t)=>e+t.to-t.from,0);return(j>0?j+F:j)>=O}var isAtEndOfNode=(e,t)=>{let{$from:S,$to:w,$anchor:E}=e.selection;if(t){let S=findParentNode(e=>e.type.name===t)(e.selection);if(!S)return!1;let w=e.doc.resolve(S.pos+1);return E.pos+1===w.end()}return!(w.parentOffset<w.parent.nodeSize-2||S.pos!==w.pos)},isAtStartOfNode=e=>{let{$from:t,$to:S}=e.selection;return!(t.parentOffset>0||t.pos!==S.pos)};function isExtensionRulesEnabled(e,t){return Array.isArray(t)?t.some(t=>(typeof t==`string`?t:t.name)===e.name):t}function isList(e,t){let{nodeExtensions:S}=splitExtensions(t),w=S.find(t=>t.name===e);if(!w)return!1;let E=callOrReturn(getExtensionField(w,`group`,{name:w.name,options:w.options,storage:w.storage}));return typeof E==`string`?E.split(` `).includes(`list`):!1}function isNodeEmpty(e,{checkChildren:t=!0,ignoreWhitespace:S=!1}={}){var w;if(S){if(e.type.name===`hardBreak`)return!0;if(e.isText)return!/\S/.test(e.text??``)}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let w=!0;return e.content.forEach(e=>{w!==!1&&(isNodeEmpty(e,{ignoreWhitespace:S,checkChildren:t})||(w=!1))}),w}return!1}function isNodeSelection(e){return e instanceof NodeSelection}function canSetMark(e,t,S){var w;let{selection:E}=t,D=null;if(isTextSelection(E)&&(D=E.$cursor),D){let t=e.storedMarks??D.marks();return D.parent.type.allowsMarkType(S)&&(!!S.isInSet(t)||!t.some(e=>e.type.excludes(S)))}let{ranges:O}=E;return O.some(({$from:t,$to:w})=>{let E=t.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(S):!1;return e.doc.nodesBetween(t.pos,w.pos,(e,t,w)=>{if(E)return!1;if(e.isInline){let t=!w||w.type.allowsMarkType(S),D=!!S.isInSet(e.marks)||!e.marks.some(e=>e.type.excludes(S));E=t&&D}return!E}),E})}var setMark=(e,t={})=>({tr:S,state:w,dispatch:E})=>{let{selection:D}=S,{empty:O,ranges:k}=D,j=getMarkType(e,w.schema);if(E)if(O){let e=getMarkAttributes(w,j);S.addStoredMark(j.create({...e,...t}))}else k.forEach(e=>{let E=e.$from.pos,D=e.$to.pos;w.doc.nodesBetween(E,D,(e,w)=>{let O=Math.max(w,E),k=Math.min(w+e.nodeSize,D);e.marks.find(e=>e.type===j)?e.marks.forEach(e=>{j===e.type&&S.addMark(O,k,j.create({...e.attrs,...t}))}):S.addMark(O,k,j.create(t))})});return canSetMark(w,S,j)},setMeta=(e,t)=>({tr:S})=>(S.setMeta(e,t),!0),setNode=(e,t={})=>({state:S,dispatch:w,chain:E})=>{let D=getNodeType(e,S.schema),O;return S.selection.$anchor.sameParent(S.selection.$head)&&(O=S.selection.$anchor.parent.attrs),D.isTextblock?E().command(({commands:e})=>setBlockType(D,{...O,...t})(S)?!0:e.clearNodes()).command(({state:e})=>setBlockType(D,{...O,...t})(e,w)).run():(console.warn(`[tiptap warn]: Currently "setNode()" only supports text block nodes.`),!1)},setNodeSelection=e=>({tr:t,dispatch:S})=>{if(S){let{doc:S}=t,w=minMax(e,0,S.content.size),E=NodeSelection.create(S,w);t.setSelection(E)}return!0},setTextDirection=(e,t)=>({tr:S,state:w,dispatch:E})=>{let{selection:D}=w,O,k;return typeof t==`number`?(O=t,k=t):t&&`from`in t&&`to`in t?(O=t.from,k=t.to):(O=D.from,k=D.to),E&&S.doc.nodesBetween(O,k,(t,w)=>{t.isText||S.setNodeMarkup(w,void 0,{...t.attrs,dir:e})}),!0},setTextSelection=e=>({tr:t,dispatch:S})=>{if(S){let{doc:S}=t,{from:w,to:E}=typeof e==`number`?{from:e,to:e}:e,D=TextSelection.atStart(S).from,O=TextSelection.atEnd(S).to,k=minMax(w,D,O),j=minMax(E,D,O),F=TextSelection.create(S,k,j);t.setSelection(F)}return!0},sinkListItem=e=>({state:t,dispatch:S})=>sinkListItem$1(getNodeType(e,t.schema))(t,S);function ensureMarks(e,t){let S=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(S){let w=S.filter(e=>t?.includes(e.type.name));e.tr.ensureMarks(w)}}var splitBlock=({keepMarks:e=!0}={})=>({tr:t,state:S,dispatch:w,editor:E})=>{let{selection:D,doc:O}=t,{$from:k,$to:j}=D,F=E.extensionManager.attributes,L=getSplittedAttributes(F,k.node().type.name,k.node().attrs);if(D instanceof NodeSelection&&D.node.isBlock)return!k.parentOffset||!canSplit(O,k.pos)?!1:(w&&(e&&ensureMarks(S,E.extensionManager.splittableMarks),t.split(k.pos).scrollIntoView()),!0);if(!k.parent.isBlock)return!1;let B=j.parentOffset===j.parent.content.size,H=k.depth===0?void 0:defaultBlockAt(k.node(-1).contentMatchAt(k.indexAfter(-1))),q=B&&H?[{type:H,attrs:L}]:void 0,J=canSplit(t.doc,t.mapping.map(k.pos),1,q);if(!q&&!J&&canSplit(t.doc,t.mapping.map(k.pos),1,H?[{type:H}]:void 0)&&(J=!0,q=H?[{type:H,attrs:L}]:void 0),w){if(J&&(D instanceof TextSelection&&t.deleteSelection(),t.split(t.mapping.map(k.pos),1,q),H&&!B&&!k.parentOffset&&k.parent.type!==H)){let e=t.mapping.map(k.before()),S=t.doc.resolve(e);k.node(-1).canReplaceWith(S.index(),S.index()+1,H)&&t.setNodeMarkup(t.mapping.map(k.before()),H)}e&&ensureMarks(S,E.extensionManager.splittableMarks),t.scrollIntoView()}return J},splitListItem=(e,t={})=>({tr:S,state:w,dispatch:E,editor:D})=>{var O;let k=getNodeType(e,w.schema),{$from:j,$to:F}=w.selection,L=w.selection.node;if(L&&L.isBlock||j.depth<2||!j.sameParent(F))return!1;let B=j.node(-1);if(B.type!==k)return!1;let H=D.extensionManager.attributes;if(j.parent.content.size===0&&j.node(-1).childCount===j.indexAfter(-1)){if(j.depth===2||j.node(-3).type!==k||j.index(-2)!==j.node(-2).childCount-1)return!1;if(E){let e=Fragment.empty,w=j.index(-1)?1:j.index(-2)?2:3;for(let t=j.depth-w;t>=j.depth-3;--t)e=Fragment.from(j.node(t).copy(e));let E=j.indexAfter(-1)<j.node(-2).childCount?1:j.indexAfter(-2)<j.node(-3).childCount?2:3,D={...getSplittedAttributes(H,j.node().type.name,j.node().attrs),...t},O=k.contentMatch.defaultType?.createAndFill(D)||void 0;e=e.append(Fragment.from(k.createAndFill(null,O)||void 0));let F=j.before(j.depth-(w-1));S.replace(F,j.after(-E),new Slice(e,4-w,0));let L=-1;S.doc.nodesBetween(F,S.doc.content.size,(e,t)=>{if(L>-1)return!1;e.isTextblock&&e.content.size===0&&(L=t+1)}),L>-1&&S.setSelection(TextSelection.near(S.doc.resolve(L))),S.scrollIntoView()}return!0}let q=F.pos===j.end()?B.contentMatchAt(0).defaultType:null,J={...getSplittedAttributes(H,B.type.name,B.attrs),...t},Y={...getSplittedAttributes(H,j.node().type.name,j.node().attrs),...t};S.delete(j.pos,F.pos);let ee=q?[{type:k,attrs:J},{type:q,attrs:Y}]:[{type:k,attrs:J}];if(!canSplit(S.doc,j.pos,2))return!1;if(E){let{selection:e,storedMarks:t}=w,{splittableMarks:O}=D.extensionManager,k=t||e.$to.parentOffset&&e.$from.marks();if(S.split(j.pos,2,ee).scrollIntoView(),!k||!E)return!0;let F=k.filter(e=>O.includes(e.type.name));S.ensureMarks(F)}return!0},joinListBackwards=(e,t)=>{let S=findParentNode(e=>e.type===t)(e.selection);if(!S)return!0;let w=e.doc.resolve(Math.max(0,S.pos-1)).before(S.depth);if(w===void 0)return!0;let E=e.doc.nodeAt(w);return S.node.type===E?.type&&canJoin(e.doc,S.pos)&&e.join(S.pos),!0},joinListForwards=(e,t)=>{let S=findParentNode(e=>e.type===t)(e.selection);if(!S)return!0;let w=e.doc.resolve(S.start).after(S.depth);if(w===void 0)return!0;let E=e.doc.nodeAt(w);return S.node.type===E?.type&&canJoin(e.doc,w)&&e.join(w),!0};function createInnerSelectionForWholeDocList(e){let t=e.doc,S=t.firstChild;if(!S)return null;let w=1,E=S.nodeSize-1;return TextSelection.create(t,1,E)}var toggleList=(e,t,S,w={})=>({editor:E,tr:D,state:O,dispatch:k,chain:j,commands:F,can:L})=>{let{extensions:B,splittableMarks:H}=E.extensionManager,q=getNodeType(e,O.schema),J=getNodeType(t,O.schema),{selection:Y,storedMarks:ee}=O,{$from:te,$to:ne}=Y,ae=te.blockRange(ne),oe=ee||Y.$to.parentOffset&&Y.$from.marks();if(!ae)return!1;let se=findParentNode(e=>isList(e.type.name,B))(Y),ce=Y.from===0&&Y.to===O.doc.content.size,ue=O.doc.content.content,de=ue.length===1?ue[0]:null,fe=ce&&de&&isList(de.type.name,B)?{node:de,pos:0,depth:0}:null,me=se??fe,ge=!!se&&ae.depth>=1&&ae.depth-se.depth<=1,_e=!!fe;if((ge||_e)&&me){if(me.node.type===q)return ce&&_e?j().command(({tr:e,dispatch:t})=>{let S=createInnerSelectionForWholeDocList(e);return S?(e.setSelection(S),t&&t(e),!0):!1}).liftListItem(J).run():F.liftListItem(J);if(isList(me.node.type.name,B)&&q.validContent(me.node.content))return j().command(()=>(D.setNodeMarkup(me.pos,q),!0)).command(()=>joinListBackwards(D,q)).command(()=>joinListForwards(D,q)).run()}return!S||!oe||!k?j().command(()=>L().wrapInList(q,w)?!0:F.clearNodes()).wrapInList(q,w).command(()=>joinListBackwards(D,q)).command(()=>joinListForwards(D,q)).run():j().command(()=>{let e=L().wrapInList(q,w),t=oe.filter(e=>H.includes(e.type.name));return D.ensureMarks(t),e?!0:F.clearNodes()}).wrapInList(q,w).command(()=>joinListBackwards(D,q)).command(()=>joinListForwards(D,q)).run()},toggleMark=(e,t={},S={})=>({state:w,commands:E})=>{let{extendEmptyMarkRange:D=!1}=S,O=getMarkType(e,w.schema);return isMarkActive(w,O,t)?E.unsetMark(O,{extendEmptyMarkRange:D}):E.setMark(O,t)},toggleNode=(e,t,S={})=>({state:w,commands:E})=>{let D=getNodeType(e,w.schema),O=getNodeType(t,w.schema),k=isNodeActive(w,D,S),j;return w.selection.$anchor.sameParent(w.selection.$head)&&(j=w.selection.$anchor.parent.attrs),k?E.setNode(O,j):E.setNode(D,{...j,...S})},toggleWrap=(e,t={})=>({state:S,commands:w})=>{let E=getNodeType(e,S.schema);return isNodeActive(S,E,t)?w.lift(E):w.wrapIn(E,t)},undoInputRule=()=>({state:e,dispatch:t})=>{let S=e.plugins;for(let w=0;w<S.length;w+=1){let E=S[w],D;if(E.spec.isInputRules&&(D=E.getState(e))){if(t){let t=e.tr,S=D.transform;for(let e=S.steps.length-1;e>=0;--e)t.step(S.steps[e].invert(S.docs[e]));if(D.text){let S=t.doc.resolve(D.from).marks();t.replaceWith(D.from,D.to,e.schema.text(D.text,S))}else t.delete(D.from,D.to)}return!0}}return!1},unsetAllMarks=()=>({tr:e,dispatch:t})=>{let{selection:S}=e,{empty:w,ranges:E}=S;return w||t&&E.forEach(t=>{e.removeMark(t.$from.pos,t.$to.pos)}),!0},unsetMark=(e,t={})=>({tr:S,state:w,dispatch:E})=>{var D;let{extendEmptyMarkRange:O=!1}=t,{selection:k}=S,j=getMarkType(e,w.schema),{$from:F,empty:L,ranges:B}=k;if(!E)return!0;if(L&&O){let{from:e,to:t}=k,w=getMarkRange(F,j,F.marks().find(e=>e.type===j)?.attrs);w&&(e=w.from,t=w.to),S.removeMark(e,t,j)}else B.forEach(e=>{S.removeMark(e.$from.pos,e.$to.pos,j)});return S.removeStoredMark(j),!0},unsetTextDirection=e=>({tr:t,state:S,dispatch:w})=>{let{selection:E}=S,D,O;return typeof e==`number`?(D=e,O=e):e&&`from`in e&&`to`in e?(D=e.from,O=e.to):(D=E.from,O=E.to),w&&t.doc.nodesBetween(D,O,(e,S)=>{if(e.isText)return;let w={...e.attrs};delete w.dir,t.setNodeMarkup(S,void 0,w)}),!0},updateAttributes=(e,t={})=>({tr:S,state:w,dispatch:E})=>{let D=null,O=null,k=getSchemaTypeNameByName(typeof e==`string`?e:e.name,w.schema);if(!k)return!1;k===`node`&&(D=getNodeType(e,w.schema)),k===`mark`&&(O=getMarkType(e,w.schema));let j=!1;return S.selection.ranges.forEach(e=>{let k=e.$from.pos,F=e.$to.pos,L,B,H,q;S.selection.empty?w.doc.nodesBetween(k,F,(e,t)=>{D&&D===e.type&&(j=!0,H=Math.max(t,k),q=Math.min(t+e.nodeSize,F),L=t,B=e)}):w.doc.nodesBetween(k,F,(e,w)=>{w<k&&D&&D===e.type&&(j=!0,H=Math.max(w,k),q=Math.min(w+e.nodeSize,F),L=w,B=e),w>=k&&w<=F&&(D&&D===e.type&&(j=!0,E&&S.setNodeMarkup(w,void 0,{...e.attrs,...t})),O&&e.marks.length&&e.marks.forEach(D=>{if(O===D.type&&(j=!0,E)){let E=Math.max(w,k),j=Math.min(w+e.nodeSize,F);S.addMark(E,j,O.create({...D.attrs,...t}))}}))}),B&&(L!==void 0&&E&&S.setNodeMarkup(L,void 0,{...B.attrs,...t}),O&&B.marks.length&&B.marks.forEach(e=>{O===e.type&&E&&S.addMark(H,q,O.create({...e.attrs,...t}))}))}),j},wrapIn=(e,t={})=>({state:S,dispatch:w})=>wrapIn$1(getNodeType(e,S.schema),t)(S,w),wrapInList=(e,t={})=>({state:S,dispatch:w})=>wrapInList$1(getNodeType(e,S.schema),t)(S,w),InputRule=class{constructor(e){var t;this.find=e.find,this.handler=e.handler,this.undoable=e.undoable??!0}},inputRuleMatcherHandler=(e,t)=>{if(isRegExp(t))return t.exec(e);let S=t(e);if(!S)return null;let w=[S.text];return w.index=S.index,w.input=e,w.data=S.data,S.replaceWith&&(S.text.includes(S.replaceWith)||console.warn(`[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".`),w.push(S.replaceWith)),w};function run$1(e){var t;let{editor:S,from:w,to:E,text:D,rules:O,plugin:k}=e,{view:j}=S;if(j.composing)return!1;let F=j.state.doc.resolve(w);if(F.parent.type.spec.code||(F.nodeBefore||F.nodeAfter)?.marks.find(e=>e.type.spec.code))return!1;let L=!1,B=getTextContentFromNodes(F)+D;return O.forEach(e=>{if(L)return;let t=inputRuleMatcherHandler(B,e.find);if(!t)return;let O=j.state.tr,F=createChainableState({state:j.state,transaction:O}),H={from:w-(t[0].length-D.length),to:E},{commands:q,chain:J,can:Y}=new CommandManager({editor:S,state:F});e.handler({state:F,range:H,match:t,commands:q,chain:J,can:Y})===null||!O.steps.length||(e.undoable&&O.setMeta(k,{transform:O,from:w,to:E,text:D}),j.dispatch(O),L=!0)}),L}function inputRulesPlugin(e){let{editor:t,rules:S}=e,w=new Plugin({state:{init(){return null},apply(e,E,D){let O=e.getMeta(w);if(O)return O;let k=e.getMeta(`applyInputRules`);return k&&setTimeout(()=>{let{text:e}=k;e=typeof e==`string`?e:getHTMLFromFragment(Fragment.from(e),D.schema);let{from:E}=k;run$1({editor:t,from:E,to:E+e.length,text:e,rules:S,plugin:w})}),e.selectionSet||e.docChanged?null:E}},props:{handleTextInput(e,E,D,O){return run$1({editor:t,from:E,to:D,text:O,rules:S,plugin:w})},handleDOMEvents:{compositionend:e=>(setTimeout(()=>{let{$cursor:E}=e.state.selection;E&&run$1({editor:t,from:E.pos,to:E.pos,text:``,rules:S,plugin:w})}),!1)},handleKeyDown(e,E){if(E.key!==`Enter`)return!1;let{$cursor:D}=e.state.selection;return D?run$1({editor:t,from:D.pos,to:D.pos,text:`
|
|
172
172
|
`,rules:S,plugin:w}):!1}},isInputRules:!0});return w}function getType(e){return Object.prototype.toString.call(e).slice(8,-1)}function isPlainObject$3(e){return getType(e)===`Object`?e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype:!1}function mergeDeep(e,t){let S={...e};return isPlainObject$3(e)&&isPlainObject$3(t)&&Object.keys(t).forEach(w=>{isPlainObject$3(t[w])&&isPlainObject$3(e[w])?S[w]=mergeDeep(e[w],t[w]):S[w]=t[w]}),S}var Extendable=class{constructor(e={}){this.type=`extendable`,this.parent=null,this.child=null,this.name=``,this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...callOrReturn(getExtensionField(this,`addOptions`,{name:this.name}))||{}}}get storage(){return{...callOrReturn(getExtensionField(this,`addStorage`,{name:this.name,options:this.options}))||{}}}configure(e={}){let t=this.extend({...this.config,addOptions:()=>mergeDeep(this.options,e)});return t.name=this.name,t.parent=this.parent,t}extend(e={}){let t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name=`name`in e?e.name:t.parent.name,t}},Mark=class e extends Extendable{constructor(){super(...arguments),this.type=`mark`}static create(t={}){return new e(typeof t==`function`?t():t)}static handleExit({editor:e,mark:t}){let{tr:S}=e.state,w=e.state.selection.$from;if(w.pos===w.end()){let E=w.marks();if(!E.find(e=>e?.type.name===t.name))return!1;let D=E.find(e=>e?.type.name===t.name);return D&&S.removeStoredMark(D),S.insertText(` `,w.pos),e.view.dispatch(S),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}};function isNumber$1(e){return typeof e==`number`}var PasteRule=class{constructor(e){this.find=e.find,this.handler=e.handler}},pasteRuleMatcherHandler=(e,t,S)=>{if(isRegExp(t))return[...e.matchAll(t)];let w=t(e,S);return w?w.map(t=>{let S=[t.text];return S.index=t.index,S.input=e,S.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn(`[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".`),S.push(t.replaceWith)),S}):[]};function run2(e){let{editor:t,state:S,from:w,to:E,rule:D,pasteEvent:O,dropEvent:k}=e,{commands:j,chain:F,can:L}=new CommandManager({editor:t,state:S}),B=[];return S.doc.nodesBetween(w,E,(e,t)=>{var H,q,J,Y,ee;if(e.type?.spec?.code||!(e.isText||e.isTextblock||e.isInline))return;let te=e.content?.size??e.nodeSize??0,ne=Math.max(w,t),ae=Math.min(E,t+te);ne>=ae||pasteRuleMatcherHandler(e.isText?e.text||``:e.textBetween(ne-t,ae-t,void 0,``),D.find,O).forEach(e=>{if(e.index===void 0)return;let t=ne+e.index+1,w=t+e[0].length,E={from:S.tr.mapping.map(t),to:S.tr.mapping.map(w)},H=D.handler({state:S,range:E,match:e,commands:j,chain:F,can:L,pasteEvent:O,dropEvent:k});B.push(H)})}),B.every(e=>e!==null)}var tiptapDragFromOtherEditor=null,createClipboardPasteEvent=e=>{var t;let S=new ClipboardEvent(`paste`,{clipboardData:new DataTransfer});return(t=S.clipboardData)==null||t.setData(`text/html`,e),S};function pasteRulesPlugin(e){let{editor:t,rules:S}=e,w=null,E=!1,D=!1,O=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,k;try{k=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{k=null}let j=({state:e,from:S,to:w,rule:E,pasteEvt:D})=>{let j=e.tr;if(!(!run2({editor:t,state:createChainableState({state:e,transaction:j}),from:Math.max(S-1,0),to:w.b-1,rule:E,pasteEvent:D,dropEvent:k})||!j.steps.length)){try{k=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{k=null}return O=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,j}};return S.map(e=>new Plugin({view(e){let S=S=>{var E;w=e.dom.parentElement?.contains(S.target)?e.dom.parentElement:null,w&&(tiptapDragFromOtherEditor=t)},E=()=>{tiptapDragFromOtherEditor&&=null};return window.addEventListener(`dragstart`,S),window.addEventListener(`dragend`,E),{destroy(){window.removeEventListener(`dragstart`,S),window.removeEventListener(`dragend`,E)}}},props:{handleDOMEvents:{drop:(e,t)=>{if(D=w===e.dom.parentElement,k=t,!D){let e=tiptapDragFromOtherEditor;e?.isEditable&&setTimeout(()=>{let t=e.state.selection;t&&e.commands.deleteRange({from:t.from,to:t.to})},10)}return!1},paste:(e,t)=>{var S;let w=t.clipboardData?.getData(`text/html`);return O=t,E=!!w?.includes(`data-pm-slice`),!1}}},appendTransaction:(t,S,w)=>{let k=t[0],F=k.getMeta(`uiEvent`)===`paste`&&!E,L=k.getMeta(`uiEvent`)===`drop`&&!D,B=k.getMeta(`applyPasteRules`),H=!!B;if(!F&&!L&&!H)return;if(H){let{text:t}=B;t=typeof t==`string`?t:getHTMLFromFragment(Fragment.from(t),w.schema);let{from:S}=B,E=S+t.length,D=createClipboardPasteEvent(t);return j({rule:e,state:w,from:S,to:{b:E},pasteEvt:D})}let q=S.doc.content.findDiffStart(w.doc.content),J=S.doc.content.findDiffEnd(w.doc.content);if(!(!isNumber$1(q)||!J||q===J.b))return j({rule:e,state:w,from:q,to:J,pasteEvt:O})}}))}var ExtensionManager=class{constructor(e,t){this.splittableMarks=[],this.editor=t,this.baseExtensions=e,this.extensions=resolveExtensions(e),this.schema=getSchemaByResolvedExtensions(this.extensions,t),this.setupExtensions()}get commands(){return this.extensions.reduce((e,t)=>{let S=getExtensionField(t,`addCommands`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:getSchemaTypeByName(t.name,this.schema)});return S?{...e,...S()}:e},{})}get plugins(){let{editor:e}=this;return sortExtensions([...this.extensions].reverse()).flatMap(t=>{let S={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:getSchemaTypeByName(t.name,this.schema)},w=[],E=getExtensionField(t,`addKeyboardShortcuts`,S),D={};if(t.type===`mark`&&getExtensionField(t,`exitable`,S)&&(D.ArrowRight=()=>Mark.handleExit({editor:e,mark:t})),E){let t=Object.fromEntries(Object.entries(E()).map(([t,S])=>[t,()=>S({editor:e})]));D={...D,...t}}let O=keymap(D);w.push(O);let k=getExtensionField(t,`addInputRules`,S);if(isExtensionRulesEnabled(t,e.options.enableInputRules)&&k){let t=k();if(t&&t.length){let S=inputRulesPlugin({editor:e,rules:t}),E=Array.isArray(S)?S:[S];w.push(...E)}}let j=getExtensionField(t,`addPasteRules`,S);if(isExtensionRulesEnabled(t,e.options.enablePasteRules)&&j){let t=j();if(t&&t.length){let S=pasteRulesPlugin({editor:e,rules:t});w.push(...S)}}let F=getExtensionField(t,`addProseMirrorPlugins`,S);if(F){let e=F();w.push(...e)}return w})}get attributes(){return getAttributesFromExtensions(this.extensions)}get nodeViews(){let{editor:e}=this,{nodeExtensions:t}=splitExtensions(this.extensions);return Object.fromEntries(t.filter(e=>!!getExtensionField(e,`addNodeView`)).map(t=>{let S=this.attributes.filter(e=>e.type===t.name),w=getExtensionField(t,`addNodeView`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:getNodeType(t.name,this.schema)});if(!w)return[];let E=w();return E?[t.name,(w,D,O,k,j)=>E({node:w,view:D,getPos:O,decorations:k,innerDecorations:j,editor:e,extension:t,HTMLAttributes:getRenderedAttributes(w,S)})]:[]}))}dispatchTransaction(e){let{editor:t}=this;return sortExtensions([...this.extensions].reverse()).reduceRight((e,S)=>{let w={name:S.name,options:S.options,storage:this.editor.extensionStorage[S.name],editor:t,type:getSchemaTypeByName(S.name,this.schema)},E=getExtensionField(S,`dispatchTransaction`,w);return E?t=>{E.call(w,{transaction:t,next:e})}:e},e)}transformPastedHTML(e){let{editor:t}=this;return sortExtensions([...this.extensions]).reduce((e,S)=>{let w={name:S.name,options:S.options,storage:this.editor.extensionStorage[S.name],editor:t,type:getSchemaTypeByName(S.name,this.schema)},E=getExtensionField(S,`transformPastedHTML`,w);return E?(t,S)=>{let D=e(t,S);return E.call(w,D)}:e},e||(e=>e))}get markViews(){let{editor:e}=this,{markExtensions:t}=splitExtensions(this.extensions);return Object.fromEntries(t.filter(e=>!!getExtensionField(e,`addMarkView`)).map(t=>{let S=this.attributes.filter(e=>e.type===t.name),w=getExtensionField(t,`addMarkView`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:getMarkType(t.name,this.schema)});return w?[t.name,(E,D,O)=>{let k=getRenderedAttributes(E,S);return w()({mark:E,view:D,inline:O,editor:e,extension:t,HTMLAttributes:k,updateAttributes:t=>{updateMarkViewAttributes(E,e,t)}})}]:[]}))}setupExtensions(){let e=this.extensions;this.editor.extensionStorage=Object.fromEntries(e.map(e=>[e.name,e.storage])),e.forEach(e=>{var t;let S={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:getSchemaTypeByName(e.name,this.schema)};e.type===`mark`&&(callOrReturn(getExtensionField(e,`keepOnSplit`,S))??!0)&&this.splittableMarks.push(e.name);let w=getExtensionField(e,`onBeforeCreate`,S),E=getExtensionField(e,`onCreate`,S),D=getExtensionField(e,`onUpdate`,S),O=getExtensionField(e,`onSelectionUpdate`,S),k=getExtensionField(e,`onTransaction`,S),j=getExtensionField(e,`onFocus`,S),F=getExtensionField(e,`onBlur`,S),L=getExtensionField(e,`onDestroy`,S);w&&this.editor.on(`beforeCreate`,w),E&&this.editor.on(`create`,E),D&&this.editor.on(`update`,D),O&&this.editor.on(`selectionUpdate`,O),k&&this.editor.on(`transaction`,k),j&&this.editor.on(`focus`,j),F&&this.editor.on(`blur`,F),L&&this.editor.on(`destroy`,L)})}};ExtensionManager.resolve=resolveExtensions,ExtensionManager.sort=sortExtensions,ExtensionManager.flatten=flattenExtensions;var extensions_exports={};__export$1(extensions_exports,{ClipboardTextSerializer:()=>ClipboardTextSerializer,Commands:()=>Commands,Delete:()=>Delete,Drop:()=>Drop,Editable:()=>Editable,FocusEvents:()=>FocusEvents,Keymap:()=>Keymap,Paste:()=>Paste,Tabindex:()=>Tabindex,TextDirection:()=>TextDirection,focusEventsPluginKey:()=>focusEventsPluginKey});var Extension=class e extends Extendable{constructor(){super(...arguments),this.type=`extension`}static create(t={}){return new e(typeof t==`function`?t():t)}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}},ClipboardTextSerializer=Extension.create({name:`clipboardTextSerializer`,addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`clipboardTextSerializer`),props:{clipboardTextSerializer:()=>{let{editor:e}=this,{state:t,schema:S}=e,{doc:w,selection:E}=t,{ranges:D}=E,O=Math.min(...D.map(e=>e.$from.pos)),k=Math.max(...D.map(e=>e.$to.pos)),j=getTextSerializersFromSchema(S);return getTextBetween(w,{from:O,to:k},{...this.options.blockSeparator===void 0?{}:{blockSeparator:this.options.blockSeparator},textSerializers:j})}}})]}}),Commands=Extension.create({name:`commands`,addCommands(){return{...commands_exports}}}),Delete=Extension.create({name:`delete`,onUpdate({transaction:e,appendedTransactions:t}){var S,w,E;let D=()=>{var S,w,E,D;if(((w=this.editor.options.coreExtensionOptions?.delete)?.filterTransaction)?.call(w,e)??e.getMeta(`y-sync$`))return;let O=combineTransactionSteps(e.before,[e,...t]);getChangedRanges(O).forEach(t=>{O.mapping.mapResult(t.oldRange.from).deletedAfter&&O.mapping.mapResult(t.oldRange.to).deletedBefore&&O.before.nodesBetween(t.oldRange.from,t.oldRange.to,(S,w)=>{let E=w+S.nodeSize-2,D=t.oldRange.from<=w&&E<=t.oldRange.to;this.editor.emit(`delete`,{type:`node`,node:S,from:w,to:E,newFrom:O.mapping.map(w),newTo:O.mapping.map(E),deletedRange:t.oldRange,newRange:t.newRange,partial:!D,editor:this.editor,transaction:e,combinedTransform:O})})});let k=O.mapping;O.steps.forEach((t,S)=>{var w,E;if(t instanceof RemoveMarkStep){let w=k.slice(S).map(t.from,-1),E=k.slice(S).map(t.to),D=k.invert().map(w,-1),j=k.invert().map(E),F=w>0?O.doc.nodeAt(w-1)?.marks.some(e=>e.eq(t.mark)):!1,L=O.doc.nodeAt(E)?.marks.some(e=>e.eq(t.mark));this.editor.emit(`delete`,{type:`mark`,mark:t.mark,from:t.from,to:t.to,deletedRange:{from:D,to:j},newRange:{from:w,to:E},partial:!!(L||F),editor:this.editor,transaction:e,combinedTransform:O})}})};this.editor.options.coreExtensionOptions?.delete?.async??!0?setTimeout(D,0):D()}}),Drop=Extension.create({name:`drop`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`tiptapDrop`),props:{handleDrop:(e,t,S,w)=>{this.editor.emit(`drop`,{editor:this.editor,event:t,slice:S,moved:w})}}})]}}),Editable=Extension.create({name:`editable`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`editable`),props:{editable:()=>this.editor.options.editable}})]}}),focusEventsPluginKey=new PluginKey(`focusEvents`),FocusEvents=Extension.create({name:`focusEvents`,addProseMirrorPlugins(){let{editor:e}=this;return[new Plugin({key:focusEventsPluginKey,props:{handleDOMEvents:{focus:(t,S)=>{e.isFocused=!0;let w=e.state.tr.setMeta(`focus`,{event:S}).setMeta(`addToHistory`,!1);return t.dispatch(w),!1},blur:(t,S)=>{e.isFocused=!1;let w=e.state.tr.setMeta(`blur`,{event:S}).setMeta(`addToHistory`,!1);return t.dispatch(w),!1}}}})]}}),Keymap=Extension.create({name:`keymap`,addKeyboardShortcuts(){let e=()=>this.editor.commands.first(({commands:e})=>[()=>e.undoInputRule(),()=>e.command(({tr:t})=>{let{selection:S,doc:w}=t,{empty:E,$anchor:D}=S,{pos:O,parent:k}=D,j=D.parent.isTextblock&&O>0?t.doc.resolve(O-1):D,F=j.parent.type.spec.isolating,L=D.pos-D.parentOffset,B=F&&j.parent.childCount===1?L===D.pos:Selection$1.atStart(w).from===O;return!E||!k.type.isTextblock||k.textContent.length||!B||B&&D.parent.type.name===`paragraph`?!1:e.clearNodes()}),()=>e.deleteSelection(),()=>e.joinBackward(),()=>e.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:e})=>[()=>e.deleteSelection(),()=>e.deleteCurrentNode(),()=>e.joinForward(),()=>e.selectNodeForward()]),S={Enter:()=>this.editor.commands.first(({commands:e})=>[()=>e.newlineInCode(),()=>e.createParagraphNear(),()=>e.liftEmptyBlock(),()=>e.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},w={...S},E={...S,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return isiOS()||isMacOS()?E:w},addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`clearDocument`),appendTransaction:(e,t,S)=>{if(e.some(e=>e.getMeta(`composition`)))return;let w=e.some(e=>e.docChanged)&&!t.doc.eq(S.doc),E=e.some(e=>e.getMeta(`preventClearDocument`));if(!w||E)return;let{empty:D,from:O,to:k}=t.selection,j=Selection$1.atStart(t.doc).from,F=Selection$1.atEnd(t.doc).to;if(D||!(O===j&&k===F)||!isNodeEmpty(S.doc))return;let L=S.tr,B=createChainableState({state:S,transaction:L}),{commands:H}=new CommandManager({editor:this.editor,state:B});if(H.clearNodes(),L.steps.length)return L}})]}}),Paste=Extension.create({name:`paste`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`tiptapPaste`),props:{handlePaste:(e,t,S)=>{this.editor.emit(`paste`,{editor:this.editor,event:t,slice:S})}}})]}}),Tabindex=Extension.create({name:`tabindex`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`tabindex`),props:{attributes:()=>this.editor.isEditable?{tabindex:`0`}:{}}})]}}),TextDirection=Extension.create({name:`textDirection`,addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:e}=splitExtensions(this.extensions);return[{types:e.filter(e=>e.name!==`text`).map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute(`dir`);return t&&(t===`ltr`||t===`rtl`||t===`auto`)?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`textDirection`),props:{attributes:()=>{let e=this.options.direction;return e?{dir:e}:{}}}})]}});function markInputRule(e){return new InputRule({find:e.find,handler:({state:t,range:S,match:w})=>{let E=callOrReturn(e.getAttributes,void 0,w);if(E===!1||E===null)return null;let{tr:D}=t,O=w[w.length-1],k=w[0];if(O){let w=k.search(/\S/),j=S.from+k.indexOf(O),F=j+O.length;if(getMarksBetween(S.from,S.to,t.doc).filter(t=>t.mark.type.excluded.find(S=>S===e.type&&S!==t.mark.type)).filter(e=>e.to>j).length)return null;F<S.to&&D.delete(F,S.to),j>S.from&&D.delete(S.from+w,j);let L=S.from+w+O.length;D.addMark(S.from+w,L,e.type.create(E||{})),D.removeStoredMark(e.type)}},undoable:e.undoable})}function nodeInputRule(e){return new InputRule({find:e.find,handler:({state:t,range:S,match:w})=>{let E=callOrReturn(e.getAttributes,void 0,w)||{},{tr:D}=t,O=S.from,k=S.to,j=e.type.create(E);if(w[1]){let e=O+w[0].lastIndexOf(w[1]);e>k?e=k:k=e+w[1].length;let t=w[0][w[0].length-1];D.insertText(t,O+w[0].length-1),D.replaceWith(e,k,j)}else if(w[0]){let t=e.type.isInline?O:O-1;D.insert(t,e.type.create(E)).delete(D.mapping.map(O),D.mapping.map(k))}D.scrollIntoView()},undoable:e.undoable})}function textblockTypeInputRule(e){return new InputRule({find:e.find,handler:({state:t,range:S,match:w})=>{let E=t.doc.resolve(S.from),D=callOrReturn(e.getAttributes,void 0,w)||{};if(!E.node(-1).canReplaceWith(E.index(-1),E.indexAfter(-1),e.type))return null;t.tr.delete(S.from,S.to).setBlockType(S.from,S.from,e.type,D)},undoable:e.undoable})}function wrappingInputRule(e){return new InputRule({find:e.find,handler:({state:t,range:S,match:w,chain:E})=>{let D=callOrReturn(e.getAttributes,void 0,w)||{},O=t.tr.delete(S.from,S.to),k=O.doc.resolve(S.from).blockRange(),j=k&&findWrapping(k,e.type,D);if(!j)return null;if(O.wrap(k,j),e.keepMarks&&e.editor){let{selection:S,storedMarks:w}=t,{splittableMarks:E}=e.editor.extensionManager,D=w||S.$to.parentOffset&&S.$from.marks();if(D){let e=D.filter(e=>E.includes(e.type.name));O.ensureMarks(e)}}if(e.keepAttributes){let t=e.type.name===`bulletList`||e.type.name===`orderedList`?`listItem`:`taskList`;E().updateAttributes(t,D).run()}let F=O.doc.resolve(S.from-1).nodeBefore;F&&F.type===e.type&&canJoin(O.doc,S.from-1)&&(!e.joinPredicate||e.joinPredicate(w,F))&&O.join(S.from-1)},undoable:e.undoable})}var isTouchEvent=e=>`touches`in e,ResizableNodeView=class{constructor(e){this.directions=[`bottom-left`,`bottom-right`,`top-left`,`top-right`],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:``,wrapper:``,handle:``,resizing:``},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.clientX-this.startX,S=e.clientY-this.startY;this.handleResize(t,S)},this.handleTouchMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.touches[0];if(!t)return;let S=t.clientX-this.startX,w=t.clientY-this.startY;this.handleResize(S,w)},this.handleMouseUp=()=>{if(!this.isResizing)return;let e=this.element.offsetWidth,t=this.element.offsetHeight;this.onCommit(e,t),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState=`false`,this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener(`mousemove`,this.handleMouseMove),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`keydown`,this.handleKeyDown),document.removeEventListener(`keyup`,this.handleKeyUp)},this.handleKeyDown=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!1)};var t,S,w,E,D,O;this.node=e.node,this.editor=e.editor,this.element=e.element,this.contentElement=e.contentElement,this.getPos=e.getPos,this.onResize=e.onResize,this.onCommit=e.onCommit,this.onUpdate=e.onUpdate,e.options?.min&&(this.minSize={...this.minSize,...e.options.min}),e.options?.max&&(this.maxSize=e.options.max),e?.options?.directions&&(this.directions=e.options.directions),e.options?.preserveAspectRatio&&(this.preserveAspectRatio=e.options.preserveAspectRatio),e.options?.className&&(this.classNames={container:e.options.className.container||``,wrapper:e.options.className.wrapper||``,handle:e.options.className.handle||``,resizing:e.options.className.resizing||``}),e.options?.createCustomHandle&&(this.createCustomHandle=e.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on(`update`,this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var e;return this.contentElement??null}handleEditorUpdate(){let e=this.editor.isEditable;e!==this.lastEditableState&&(this.lastEditableState=e,e?e&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}update(e,t,S){return e.type===this.node.type?(this.node=e,this.onUpdate?this.onUpdate(e,t,S):!0):!1}destroy(){this.isResizing&&(this.container.dataset.resizeState=`false`,this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener(`mousemove`,this.handleMouseMove),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`keydown`,this.handleKeyDown),document.removeEventListener(`keyup`,this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.editor.off(`update`,this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){let e=document.createElement(`div`);return e.dataset.resizeContainer=``,e.dataset.node=this.node.type.name,e.style.display=this.node.type.isInline?`inline-flex`:`flex`,this.classNames.container&&(e.className=this.classNames.container),e.appendChild(this.wrapper),e}createWrapper(){let e=document.createElement(`div`);return e.style.position=`relative`,e.style.display=`block`,e.dataset.resizeWrapper=``,this.classNames.wrapper&&(e.className=this.classNames.wrapper),e.appendChild(this.element),e}createHandle(e){let t=document.createElement(`div`);return t.dataset.resizeHandle=e,t.style.position=`absolute`,this.classNames.handle&&(t.className=this.classNames.handle),t}positionHandle(e,t){let S=t.includes(`top`),w=t.includes(`bottom`),E=t.includes(`left`),D=t.includes(`right`);S&&(e.style.top=`0`),w&&(e.style.bottom=`0`),E&&(e.style.left=`0`),D&&(e.style.right=`0`),(t===`top`||t===`bottom`)&&(e.style.left=`0`,e.style.right=`0`),(t===`left`||t===`right`)&&(e.style.top=`0`,e.style.bottom=`0`)}attachHandles(){this.directions.forEach(e=>{let t;t=this.createCustomHandle?this.createCustomHandle(e):this.createHandle(e),t instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${e}") did not return an HTMLElement. Falling back to default handle.`),t=this.createHandle(e)),this.createCustomHandle||this.positionHandle(t,e),t.addEventListener(`mousedown`,t=>this.handleResizeStart(t,e)),t.addEventListener(`touchstart`,t=>this.handleResizeStart(t,e)),this.handleMap.set(e,t),this.wrapper.appendChild(t)})}removeHandles(){this.handleMap.forEach(e=>e.remove()),this.handleMap.clear()}applyInitialSize(){let e=this.node.attrs.width,t=this.node.attrs.height;e?(this.element.style.width=`${e}px`,this.initialWidth=e):this.initialWidth=this.element.offsetWidth,t?(this.element.style.height=`${t}px`,this.initialHeight=t):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(e,t){e.preventDefault(),e.stopPropagation(),this.isResizing=!0,this.activeHandle=t,isTouchEvent(e)?(this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY):(this.startX=e.clientX,this.startY=e.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState=`true`,this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener(`mousemove`,this.handleMouseMove),document.addEventListener(`touchmove`,this.handleTouchMove),document.addEventListener(`mouseup`,this.handleMouseUp),document.addEventListener(`keydown`,this.handleKeyDown),document.addEventListener(`keyup`,this.handleKeyUp)}handleResize(e,t){if(!this.activeHandle)return;let S=this.preserveAspectRatio||this.isShiftKeyPressed,{width:w,height:E}=this.calculateNewDimensions(this.activeHandle,e,t),D=this.applyConstraints(w,E,S);this.element.style.width=`${D.width}px`,this.element.style.height=`${D.height}px`,this.onResize&&this.onResize(D.width,D.height)}calculateNewDimensions(e,t,S){let w=this.startWidth,E=this.startHeight,D=e.includes(`right`),O=e.includes(`left`),k=e.includes(`bottom`),j=e.includes(`top`);return D?w=this.startWidth+t:O&&(w=this.startWidth-t),k?E=this.startHeight+S:j&&(E=this.startHeight-S),(e===`right`||e===`left`)&&(w=this.startWidth+(D?t:-t)),(e===`top`||e===`bottom`)&&(E=this.startHeight+(k?S:-S)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(w,E,e):{width:w,height:E}}applyConstraints(e,t,S){var w,E,D,O;if(!S){let S=Math.max(this.minSize.width,e),w=Math.max(this.minSize.height,t);return this.maxSize?.width&&(S=Math.min(this.maxSize.width,S)),this.maxSize?.height&&(w=Math.min(this.maxSize.height,w)),{width:S,height:w}}let k=e,j=t;return k<this.minSize.width&&(k=this.minSize.width,j=k/this.aspectRatio),j<this.minSize.height&&(j=this.minSize.height,k=j*this.aspectRatio),this.maxSize?.width&&k>this.maxSize.width&&(k=this.maxSize.width,j=k/this.aspectRatio),this.maxSize?.height&&j>this.maxSize.height&&(j=this.maxSize.height,k=j*this.aspectRatio),{width:k,height:j}}applyAspectRatio(e,t,S){return S===`left`||S===`right`?{width:e,height:e/this.aspectRatio}:S===`top`||S===`bottom`?{width:t*this.aspectRatio,height:t}:{width:e,height:e/this.aspectRatio}}};function canInsertNode(e,t){let{selection:S}=e,{$from:w}=S;if(S instanceof NodeSelection){let e=w.index();return w.parent.canReplaceWith(e,e+1,t)}let E=w.depth;for(;E>=0;){let e=w.index(E);if(w.node(E).contentMatchAt(e).matchType(t))return!0;--E}return!1}var markdown_exports={};__export$1(markdown_exports,{createAtomBlockMarkdownSpec:()=>createAtomBlockMarkdownSpec,createBlockMarkdownSpec:()=>createBlockMarkdownSpec,createInlineMarkdownSpec:()=>createInlineMarkdownSpec,parseAttributes:()=>parseAttributes,parseIndentedBlocks:()=>parseIndentedBlocks,renderNestedMarkdownContent:()=>renderNestedMarkdownContent,serializeAttributes:()=>serializeAttributes});function parseAttributes(e){if(!e?.trim())return{};let t={},S=[],w=e.replace(/["']([^"']*)["']/g,e=>(S.push(e),`__QUOTED_${S.length-1}__`)),E=w.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);E&&(t.class=E.map(e=>e.trim().slice(1)).join(` `));let D=w.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);D&&(t.id=D[1]),Array.from(w.matchAll(/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g)).forEach(([,e,w])=>{var E;let D=S[parseInt(w.match(/__QUOTED_(\d+)__/)?.[1]||`0`,10)];D&&(t[e]=D.slice(1,-1))});let O=w.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,``).replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,``).replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,``).trim();return O&&O.split(/\s+/).filter(Boolean).forEach(e=>{e.match(/^[a-zA-Z][\w-]*$/)&&(t[e]=!0)}),t}function serializeAttributes(e){if(!e||Object.keys(e).length===0)return``;let t=[];return e.class&&String(e.class).split(/\s+/).filter(Boolean).forEach(e=>t.push(`.${e}`)),e.id&&t.push(`#${e.id}`),Object.entries(e).forEach(([e,S])=>{e===`class`||e===`id`||(S===!0?t.push(e):S!==!1&&S!=null&&t.push(`${e}="${String(S)}"`))}),t.join(` `)}function createAtomBlockMarkdownSpec(e){let{nodeName:t,name:S,parseAttributes:w=parseAttributes,serializeAttributes:E=serializeAttributes,defaultAttributes:D={},requiredAttributes:O=[],allowedAttributes:k}=e,j=S||t,F=e=>{if(!k)return e;let t={};return k.forEach(S=>{S in e&&(t[S]=e[S])}),t};return{parseMarkdown:(e,S)=>{let w={...D,...e.attributes};return S.createNode(t,w,[])},markdownTokenizer:{name:t,level:`block`,start(e){var t;let S=RegExp(`^:::${j}(?:\\s|$)`,`m`),w=e.match(S)?.index;return w===void 0?-1:w},tokenize(e,S,E){let D=RegExp(`^:::${j}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),k=e.match(D);if(!k)return;let F=w(k[1]||``);if(!O.find(e=>!(e in F)))return{type:t,raw:k[0],attributes:F}}},renderMarkdown:e=>{let t=E(F(e.attrs||{}));return`:::${j}${t?` {${t}}`:``} :::`}}}function createBlockMarkdownSpec(e){let{nodeName:t,name:S,getContent:w,parseAttributes:E=parseAttributes,serializeAttributes:D=serializeAttributes,defaultAttributes:O={},content:k=`block`,allowedAttributes:j}=e,F=S||t,L=e=>{if(!j)return e;let t={};return j.forEach(S=>{S in e&&(t[S]=e[S])}),t};return{parseMarkdown:(e,S)=>{let E;if(w){let t=w(e);E=typeof t==`string`?[{type:`text`,text:t}]:t}else E=k===`block`?S.parseChildren(e.tokens||[]):S.parseInline(e.tokens||[]);let D={...O,...e.attributes};return S.createNode(t,D,E)},markdownTokenizer:{name:t,level:`block`,start(e){var t;let S=RegExp(`^:::${F}`,`m`),w=e.match(S)?.index;return w===void 0?-1:w},tokenize(e,S,w){var D;let O=RegExp(`^:::${F}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),j=e.match(O);if(!j)return;let[L,B=``]=j,H=E(B),q=1,J=L.length,Y=``,ee=/^:::([\w-]*)(\s.*)?/gm,te=e.slice(J);for(ee.lastIndex=0;;){let S=ee.exec(te);if(S===null)break;let E=S.index,D=S[1];if(!S[2]?.endsWith(`:::`)){if(D)q+=1;else if(--q,q===0){let D=te.slice(0,E);Y=D.trim();let O=e.slice(0,J+E+S[0].length),j=[];if(Y)if(k===`block`)for(j=w.blockTokens(D),j.forEach(e=>{e.text&&(!e.tokens||e.tokens.length===0)&&(e.tokens=w.inlineTokens(e.text))});j.length>0;){let e=j[j.length-1];if(e.type===`paragraph`&&(!e.text||e.text.trim()===``))j.pop();else break}else j=w.inlineTokens(Y);return{type:t,raw:O,attributes:H,content:Y,tokens:j}}}}}},renderMarkdown:(e,t)=>{let S=D(L(e.attrs||{}));return`:::${F}${S?` {${S}}`:``}
|
|
@@ -212,7 +212,7 @@ ${S}`}}),k}function updateMarkViewAttributes(e,t,S={}){let{state:w}=t,{doc:E,tr:
|
|
|
212
212
|
`),ne(Ce,Hr,Ce),oe(Ce,``,Ce);let we=ne(S,Br,Mr,{[F]:!0});oe(we,`#`),ne(we,Br,we),oe(we,`️`,we);let at=oe(we,``);oe(at,`#`),ne(at,Br,we);let Mt=[[Lr,Y],[Vr,B]],Fr=[[Lr,null],[zr,te],[Vr,q]];for(let e=0;e<Jr.length;e++)ji(S,Jr[e],`TLD`,se,Mt);for(let e=0;e<Yr.length;e++)ji(S,Yr[e],ge,ce,Fr);J(`TLD`,{tld:!0,ascii:!0},t),J(ge,{utld:!0,alpha:!0},t),ji(S,`file`,_e,se,Mt),ji(S,`mailto`,_e,se,Mt),ji(S,`http`,ve,se,Mt),ji(S,`https`,ve,se,Mt),ji(S,`ftp`,ve,se,Mt),ji(S,`ftps`,ve,se,Mt),J(_e,{scheme:!0,ascii:!0},t),J(ve,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let D=e[t][0],k=e[t][1]?{scheme:!0}:{slashscheme:!0};D.indexOf(`-`)>=0?k[j]=!0:Lr.test(D)?Vr.test(D)?k[O]=!0:k[E]=!0:k[w]=!0,ae(S,D,D,k)}return ae(S,`localhost`,fe,{ascii:!0}),S.jd=new ee(`SYM`),{start:S,tokens:Object.assign({groups:t},Ir)}}function Zr(e,t){let S=Qr(t.replace(/[A-Z]/g,e=>e.toLowerCase())),w=S.length,E=[],D=0,O=0;for(;O<w;){let k=e,j=null,F=0,L=null,B=-1,H=-1;for(;O<w&&(j=k.go(S[O]));)k=j,k.accepts()?(B=0,H=0,L=k):B>=0&&(B+=S[O].length,H++),F+=S[O].length,D+=S[O].length,O++;D-=B,O-=H,F-=B,E.push({t:L.t,v:t.slice(D-F,D),s:D-F,e:D})}return E}function Qr(e){let t=[],S=e.length,w=0;for(;w<S;){let E=e.charCodeAt(w),D,O=E<55296||E>56319||w+1===S||(D=e.charCodeAt(w+1))<56320||D>57343?e[w]:e.slice(w,w+2);t.push(O),w+=O.length}return t}function ji(e,t,S,w,E){let D,O=t.length;for(let S=0;S<O-1;S++){let O=t[S];e.j[O]?D=e.j[O]:(D=new ee(w),D.jr=E.slice(),e.j[O]=D),e=D}return D=new ee(S),D.jr=E.slice(),e.j[t[O-1]]=D,D}function Hi(e){let t=[],S=[],w=0,E=`0123456789`;for(;w<e.length;){let E=0;for(;`0123456789`.indexOf(e[w+E])>=0;)E++;if(E>0){t.push(S.join(``));for(let t=parseInt(e.substring(w,w+E),10);t>0;t--)S.pop();w+=E}else S.push(e[w]),w++}return t}let Ui={defaultProtocol:`http`,events:null,format:Ki,formatHref:Ki,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Gi(e,t=null){let S=Object.assign({},Ui);e&&(S=Object.assign(S,e instanceof Gi?e.o:e));let w=S.ignoreTags,E=[];for(let e=0;e<w.length;e++)E.push(w[e].toUpperCase());this.o=S,t&&(this.defaultRender=t),this.ignoreTags=E}Gi.prototype={o:Ui,ignoreTags:[],defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,S){let w=t!=null,E=this.o[e];return E&&(typeof E==`object`?(E=S.t in E?E[S.t]:Ui[e],typeof E==`function`&&w&&(E=E(t,S))):typeof E==`function`&&w&&(E=E(t,S.t,S)),E)},getObj(e,t,S){let w=this.o[e];return typeof w==`function`&&t!=null&&(w=w(t,S.t,S)),w},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function Ki(e){return e}function Yi(e,t){this.t=`token`,this.v=e,this.tk=t}Yi.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),S=e.get(`truncate`,t,this),w=e.get(`format`,t,this);return S&&w.length>S?w.substring(0,S)+`…`:w},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=Ui.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,S=this.toHref(e.get(`defaultProtocol`)),w=e.get(`formatHref`,S,this),E=e.get(`tagName`,S,t),D=this.toFormattedString(e),O={},k=e.get(`className`,S,t),j=e.get(`target`,S,t),F=e.get(`rel`,S,t),L=e.getObj(`attributes`,S,t),B=e.getObj(`events`,S,t);return O.href=w,k&&(O.class=k),j&&(O.target=j),F&&(O.rel=F),L&&Object.assign(O,L),{tagName:E,attributes:O,content:D,eventListeners:B}}};function Xi(e,t){class S extends Yi{constructor(t,S){super(t,S),this.t=e}}for(let e in t)S.prototype[e]=t[e];return S.t=e,S}let Zi=Xi(`email`,{isLink:!0,toHref(){return`mailto:`+this.toString()}}),ka=Xi(`text`),_s=Xi(`nl`),xs=Xi(`url`,{isLink:!0,toHref(e=Ui.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){let e=this.tk;return e.length>=2&&e[0].t!==fe&&e[1].t===Et}}),Cs=e=>new ee(e);function Ts({groups:e}){let t=e.domain.concat([nt,it,`AT`,st,vt,Tt,jt,Ft,Lt,`NUM`,Rt,zt,Bt,Vt,$t,`SYM`,en,jr]),S=[rt,Et,Dt,`DOT`,It,Rt,Ht,Ut,Kt,Re,ze,Te,De,Me,je,Pe,Ie,Be,Ve,Ue,We,Ge,Ke,Xe,$e],w=[nt,rt,it,st,vt,Tt,jt,Ft,Lt,Te,De,Rt,zt,Bt,Vt,Ht,$t,`SYM`,en,jr],E=Cs(),D=oe(E,en);te(D,w,D),te(D,e.domain,D);let O=Cs(),k=Cs(),j=Cs();te(E,e.domain,O),te(E,e.scheme,k),te(E,e.slashscheme,j),te(O,w,D),te(O,e.domain,O);let F=oe(O,`AT`);oe(D,`AT`,F),oe(k,`AT`,F),oe(j,`AT`,F);let L=oe(D,`DOT`);te(L,w,D),te(L,e.domain,D);let B=Cs();te(F,e.domain,B),te(B,e.domain,B);let H=oe(B,`DOT`);te(H,e.domain,B);let q=Cs(Zi);te(H,e.tld,q),te(H,e.utld,q),oe(F,fe,q);let J=oe(B,Lt);oe(J,Lt,J),te(J,e.domain,B),te(q,e.domain,B),oe(q,`DOT`,H),oe(q,Lt,J),te(oe(q,Et),e.numeric,Zi);let Y=oe(O,Lt),ee=oe(O,`DOT`);oe(Y,Lt,Y),te(Y,e.domain,O),te(ee,w,D),te(ee,e.domain,O);let ne=Cs(xs);te(ee,e.tld,ne),te(ee,e.utld,ne),te(ne,e.domain,O),te(ne,w,D),oe(ne,`DOT`,ee),oe(ne,Lt,Y),oe(ne,`AT`,F);let ae=oe(ne,Et),se=Cs(xs);te(ae,e.numeric,se);let ce=Cs(xs),ue=Cs();te(ce,t,ce),te(ce,S,ue),te(ue,t,ce),te(ue,S,ue),oe(ne,$t,ce),oe(se,$t,ce);let de=oe(k,Et),me=oe(oe(oe(j,Et),$t),$t);te(k,e.domain,O),oe(k,`DOT`,ee),oe(k,Lt,Y),te(j,e.domain,O),oe(j,`DOT`,ee),oe(j,Lt,Y),te(de,e.domain,ce),oe(de,$t,ce),oe(de,Ht,ce),te(me,e.domain,ce),te(me,t,ce),oe(me,$t,ce);let ge=[[Te,De],[je,Me],[Pe,Ie],[Re,ze],[Be,Ve],[Ue,We],[Ge,Ke],[Xe,$e]];for(let e=0;e<ge.length;e++){let[w,E]=ge[e],D=oe(ce,w);oe(ue,w,D),oe(D,E,ce);let O=Cs(xs);te(D,t,O);let k=Cs();te(D,S),te(O,t,O),te(O,S,k),te(k,t,O),te(k,S,k),oe(O,E,ce),oe(k,E,ce)}return oe(E,fe,ne),oe(E,`NL`,_s),{start:E,tokens:Ir}}function Ds(e,t,S){let w=S.length,E=0,D=[],O=[];for(;E<w;){let k=e,j=null,F=null,L=0,B=null,H=-1;for(;E<w&&!(j=k.go(S[E].t));)O.push(S[E++]);for(;E<w&&(F=j||k.go(S[E].t));)j=null,k=F,k.accepts()?(H=0,B=k):H>=0&&H++,E++,L++;if(H<0)E-=L,E<w&&(O.push(S[E]),E++);else{O.length>0&&(D.push(Os(ka,t,O)),O=[]),E-=H,L-=H;let e=B.t,w=S.slice(E-L,E);D.push(Os(e,t,w))}}return O.length>0&&D.push(Os(ka,t,O)),D}function Os(e,t,S){let w=S[0].s,E=S[S.length-1].e;return new e(t.slice(w,E),S)}let ks=typeof console<`u`&&console&&console.warn||(()=>{}),As=`until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.`,Ns={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Ps(){return ee.groups={},Ns.scanner=null,Ns.parser=null,Ns.tokenQueue=[],Ns.pluginQueue=[],Ns.customSchemes=[],Ns.initialized=!1,Ns}function Is(e,t=!1){if(Ns.initialized&&ks(`linkifyjs: already initialized - will not register custom scheme "${e}" until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(e))throw Error(`linkifyjs: incorrect scheme format.
|
|
213
213
|
1. Must only contain digits, lowercase ASCII letters or "-"
|
|
214
214
|
2. Cannot start or end with "-"
|
|
215
|
-
3. "-" cannot repeat`);Ns.customSchemes.push([e,t])}function Rs(){Ns.scanner=Xr(Ns.customSchemes);for(let e=0;e<Ns.tokenQueue.length;e++)Ns.tokenQueue[e][1]({scanner:Ns.scanner});Ns.parser=Ts(Ns.scanner.tokens);for(let e=0;e<Ns.pluginQueue.length;e++)Ns.pluginQueue[e][1]({scanner:Ns.scanner,parser:Ns.parser});return Ns.initialized=!0,Ns}function $s(e){return Ns.initialized||Rs(),Ds(Ns.parser.start,e,Zr(Ns.scanner.start,e))}$s.scan=Zr;function ec(e,t=null,S=null){if(t&&typeof t==`object`){if(S)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);S=t,t=null}let w=new Gi(S),E=$s(e),D=[];for(let e=0;e<E.length;e++){let S=E[e];S.isLink&&(!t||S.t===t)&&w.check(S)&&D.push(S.toFormattedObject(w))}return D}e.find=ec,e.registerCustomProtocol=Is,e.reset=Ps,e.tokenize=$s})),import_linkify=require_linkify(),UNICODE_WHITESPACE_PATTERN=`[\0- \xA0 -\u2029 ]`,UNICODE_WHITESPACE_REGEX=new RegExp(UNICODE_WHITESPACE_PATTERN),UNICODE_WHITESPACE_REGEX_END=RegExp(`${UNICODE_WHITESPACE_PATTERN}$`),UNICODE_WHITESPACE_REGEX_GLOBAL=new RegExp(UNICODE_WHITESPACE_PATTERN,`g`);function isValidLinkStructure(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function autolink$1(e){return new Plugin({key:new PluginKey(`autolink`),appendTransaction:(t,S,w)=>{let E=t.some(e=>e.docChanged)&&!S.doc.eq(w.doc),D=t.some(e=>e.getMeta(`preventAutolink`));if(!E||D)return;let{tr:O}=w;if(getChangedRanges(combineTransactionSteps(S.doc,[...t])).forEach(({newRange:t})=>{let S=findChildrenInRange(w.doc,t,e=>e.isTextblock),E,D;if(S.length>1)E=S[0],D=w.doc.textBetween(E.pos,E.pos+E.node.nodeSize,void 0,` `);else if(S.length){let e=w.doc.textBetween(t.from,t.to,` `,` `);if(!UNICODE_WHITESPACE_REGEX_END.test(e))return;E=S[0],D=w.doc.textBetween(E.pos,t.to,void 0,` `)}if(E&&D){let t=D.split(UNICODE_WHITESPACE_REGEX).filter(Boolean);if(t.length<=0)return!1;let S=t[t.length-1],k=E.pos+D.lastIndexOf(S);if(!S)return!1;let j=(0,import_linkify.tokenize)(S).map(t=>t.toObject(e.defaultProtocol));if(!isValidLinkStructure(j))return!1;j.filter(e=>e.isLink).map(e=>({...e,from:k+e.start+1,to:k+e.end+1})).filter(e=>w.schema.marks.code?!w.doc.rangeHasMark(e.from,e.to,w.schema.marks.code):!0).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{getMarksBetween(t.from,t.to,w.doc).some(t=>t.mark.type===e.type)||O.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),O.steps.length)return O}})}function clickHandler(e){return new Plugin({key:new PluginKey(`handleClickLink`),props:{handleClick:(t,S,w)=>{var E,D;if(w.button!==0||!t.editable)return!1;let O=null;if(w.target instanceof HTMLAnchorElement)O=w.target;else{let t=w.target;if(!t)return!1;let S=e.editor.view.dom;O=t.closest(`a`),O&&!S.contains(O)&&(O=null)}if(!O)return!1;let k=!1;if(e.enableClickSelection&&(k=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let S=getAttributes(t.state,e.type.name),w=O.href??S.href,E=O.target??S.target;w&&(window.open(w,E),k=!0)}return k}}})}function pasteHandler(e){return new Plugin({key:new PluginKey(`handlePasteLink`),props:{handlePaste:(t,S,w)=>{let{shouldAutoLink:E}=e,{state:D}=t,{selection:O}=D,{empty:k}=O;if(k)return!1;let j=``;w.content.forEach(e=>{j+=e.textContent});let F=(0,import_linkify.find)(j,{defaultProtocol:e.defaultProtocol}).find(e=>e.isLink&&e.value===j);return!j||!F||E!==void 0&&!E(F.value)?!1:e.editor.commands.setMark(e.type,{href:F.href})}}})}function isAllowedUri(e,t){let S=[`http`,`https`,`ftp`,`ftps`,`mailto`,`tel`,`callto`,`sms`,`cid`,`xmpp`];return t&&t.forEach(e=>{let t=typeof e==`string`?e:e.scheme;t&&S.push(t)}),!e||e.replace(UNICODE_WHITESPACE_REGEX_GLOBAL,``).match(RegExp(`^(?:(?:${S.join(`|`)}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,`i`))}var Link=Mark.create({name:`link`,priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(e=>{if(typeof e==`string`){(0,import_linkify.registerCustomProtocol)(e);return}(0,import_linkify.registerCustomProtocol)(e.scheme,e.optionalSlashes)})},onDestroy(){(0,import_linkify.reset)()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer nofollow`,class:null},isAllowedUri:(e,t)=>!!isAllowedUri(e,t.protocols),validate:e=>!!e,shouldAutoLink:e=>{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e),S=/^[a-z][a-z0-9+.-]*:/i.test(e);if(t||S&&!e.includes(`@`))return!0;let w=(e.includes(`@`)?e.split(`@`).pop():e).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(w)||!/\./.test(w))}}},addAttributes(){return{href:{default:null,parseHTML(e){return e.getAttribute(`href`)}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:`a[href]`,getAttrs:e=>{let t=e.getAttribute(`href`);return!t||!this.options.isAllowedUri(t,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:e}){return this.options.isAllowedUri(e.href,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?[`a`,mergeAttributes(this.options.HTMLAttributes,e),0]:[`a`,mergeAttributes(this.options.HTMLAttributes,{...e,href:``}),0]},markdownTokenName:`link`,parseMarkdown:(e,t)=>t.applyMark(`link`,t.parseInline(e.tokens||[]),{href:e.href,title:e.title||null}),renderMarkdown:(e,t)=>{var S,w,E,D;let O=e.attrs?.href??``,k=e.attrs?.title??``,j=t.renderChildren(e);return k?`[${j}](${O} "${k}")`:`[${j}](${O})`},addCommands(){return{setLink:e=>({chain:t})=>{let{href:S}=e;return this.options.isAllowedUri(S,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,e).setMeta(`preventAutolink`,!0).run():!1},toggleLink:e=>({chain:t})=>{let{href:S}=e||{};return S&&!this.options.isAllowedUri(S,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:t().toggleMark(this.name,e,{extendEmptyMarkRange:!0}).setMeta(`preventAutolink`,!0).run()},unsetLink:()=>({chain:e})=>e().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta(`preventAutolink`,!0).run()}},addPasteRules(){return[markPasteRule({find:e=>{let t=[];if(e){let{protocols:S,defaultProtocol:w}=this.options,E=(0,import_linkify.find)(e).filter(e=>e.isLink&&this.options.isAllowedUri(e.value,{defaultValidate:e=>!!isAllowedUri(e,S),protocols:S,defaultProtocol:w}));E.length&&E.forEach(e=>{this.options.shouldAutoLink(e.value)&&t.push({text:e.value,data:{href:e.href},index:e.start})})}return t},type:this.type,getAttributes:e=>{var t;return{href:e.data?.href}}})]},addProseMirrorPlugins(){let e=[],{protocols:t,defaultProtocol:S}=this.options;return this.options.autolink&&e.push(autolink$1({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:e=>this.options.isAllowedUri(e,{defaultValidate:e=>!!isAllowedUri(e,t),protocols:t,defaultProtocol:S}),shouldAutoLink:this.options.shouldAutoLink})),e.push(clickHandler({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick===`whenNotEditable`?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&e.push(pasteHandler({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),e}}),index_default$5=Link,inputRegex$4=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,pasteRegex$2=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,Highlight=Mark.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||e.style.backgroundColor,renderHTML:e=>e.color?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){return[`mark`,mergeAttributes(this.options.HTMLAttributes,e),0]},renderMarkdown:(e,t)=>`==${t.renderChildren(e)}==`,parseMarkdown:(e,t)=>t.applyMark(`highlight`,t.parseInline(e.tokens||[])),markdownTokenizer:{name:`highlight`,level:`inline`,start:e=>e.indexOf(`==`),tokenize(e,t,S){let w=/^(==)([^=]+)(==)/.exec(e);if(w){let e=w[2].trim(),t=S.inlineTokens(e);return{type:`highlight`,raw:w[0],text:e,tokens:t}}}},addCommands(){return{setHighlight:e=>({commands:t})=>t.setMark(this.name,e),toggleHighlight:e=>({commands:t})=>t.toggleMark(this.name,e),unsetHighlight:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[markInputRule({find:inputRegex$4,type:this.type})]},addPasteRules(){return[markPasteRule({find:pasteRegex$2,type:this.type})]}}),index_default$4=Highlight;let readFromCache,addToCache;if(typeof WeakMap<`u`){let e=new WeakMap;readFromCache=t=>e.get(t),addToCache=(t,S)=>(e.set(t,S),S)}else{let e=[],t=10,S=0;readFromCache=t=>{for(let S=0;S<e.length;S+=2)if(e[S]==t)return e[S+1]},addToCache=(t,w)=>(S==10&&(S=0),e[S++]=t,e[S++]=w)}var TableMap=class{constructor(e,t,S,w){this.width=e,this.height=t,this.map=S,this.problems=w}findCell(e){for(let t=0;t<this.map.length;t++){let S=this.map[t];if(S!=e)continue;let w=t%this.width,E=t/this.width|0,D=w+1,O=E+1;for(let e=1;D<this.width&&this.map[t+e]==S;e++)D++;for(let e=1;O<this.height&&this.map[t+this.width*e]==S;e++)O++;return{left:w,top:E,right:D,bottom:O}}throw RangeError(`No cell with offset ${e} found`)}colCount(e){for(let t=0;t<this.map.length;t++)if(this.map[t]==e)return t%this.width;throw RangeError(`No cell with offset ${e} found`)}nextCell(e,t,S){let{left:w,right:E,top:D,bottom:O}=this.findCell(e);return t==`horiz`?(S<0?w==0:E==this.width)?null:this.map[D*this.width+(S<0?w-1:E)]:(S<0?D==0:O==this.height)?null:this.map[w+this.width*(S<0?D-1:O)]}rectBetween(e,t){let{left:S,right:w,top:E,bottom:D}=this.findCell(e),{left:O,right:k,top:j,bottom:F}=this.findCell(t);return{left:Math.min(S,O),top:Math.min(E,j),right:Math.max(w,k),bottom:Math.max(D,F)}}cellsInRect(e){let t=[],S={};for(let w=e.top;w<e.bottom;w++)for(let E=e.left;E<e.right;E++){let D=w*this.width+E,O=this.map[D];S[O]||(S[O]=!0,!(E==e.left&&E&&this.map[D-1]==O||w==e.top&&w&&this.map[D-this.width]==O)&&t.push(O))}return t}positionAt(e,t,S){for(let w=0,E=0;;w++){let D=E+S.child(w).nodeSize;if(w==e){let S=t+e*this.width,w=(e+1)*this.width;for(;S<w&&this.map[S]<E;)S++;return S==w?D-1:this.map[S]}E=D}}static get(e){return readFromCache(e)||addToCache(e,computeMap(e))}};function computeMap(e){if(e.type.spec.tableRole!=`table`)throw RangeError(`Not a table node: `+e.type.name);let t=findWidth(e),S=e.childCount,w=[],E=0,D=null,O=[];for(let e=0,E=t*S;e<E;e++)w[e]=0;for(let k=0,j=0;k<S;k++){let F=e.child(k);j++;for(let e=0;;e++){for(;E<w.length&&w[E]!=0;)E++;if(e==F.childCount)break;let L=F.child(e),{colspan:B,rowspan:H,colwidth:q}=L.attrs;for(let e=0;e<H;e++){if(e+k>=S){(D||=[]).push({type:`overlong_rowspan`,pos:j,n:H-e});break}let F=E+e*t;for(let e=0;e<B;e++){w[F+e]==0?w[F+e]=j:(D||=[]).push({type:`collision`,row:k,pos:j,n:B-e});let S=q&&q[e];if(S){let w=(F+e)%t*2,E=O[w];E==null||E!=S&&O[w+1]==1?(O[w]=S,O[w+1]=1):E==S&&O[w+1]++}}}E+=B,j+=L.nodeSize}let L=(k+1)*t,B=0;for(;E<L;)w[E++]==0&&B++;B&&(D||=[]).push({type:`missing`,row:k,n:B}),j++}(t===0||S===0)&&(D||=[]).push({type:`zero_sized`});let k=new TableMap(t,S,w,D),j=!1;for(let e=0;!j&&e<O.length;e+=2)O[e]!=null&&O[e+1]<S&&(j=!0);return j&&findBadColWidths(k,O,e),k}function findWidth(e){let t=-1,S=!1;for(let w=0;w<e.childCount;w++){let E=e.child(w),D=0;if(S)for(let t=0;t<w;t++){let S=e.child(t);for(let e=0;e<S.childCount;e++){let E=S.child(e);t+E.attrs.rowspan>w&&(D+=E.attrs.colspan)}}for(let e=0;e<E.childCount;e++){let t=E.child(e);D+=t.attrs.colspan,t.attrs.rowspan>1&&(S=!0)}t==-1?t=D:t!=D&&(t=Math.max(t,D))}return t}function findBadColWidths(e,t,S){e.problems||=[];let w={};for(let E=0;E<e.map.length;E++){let D=e.map[E];if(w[D])continue;w[D]=!0;let O=S.nodeAt(D);if(!O)throw RangeError(`No cell with offset ${D} found`);let k=null,j=O.attrs;for(let S=0;S<j.colspan;S++){let w=t[(E+S)%e.width*2];w!=null&&(!j.colwidth||j.colwidth[S]!=w)&&((k||=freshColWidth(j))[S]=w)}k&&e.problems.unshift({type:`colwidth mismatch`,pos:D,colwidth:k})}}function freshColWidth(e){if(e.colwidth)return e.colwidth.slice();let t=[];for(let S=0;S<e.colspan;S++)t.push(0);return t}function tableNodeTypes(e){let t=e.cached.tableNodeTypes;if(!t){t=e.cached.tableNodeTypes={};for(let S in e.nodes){let w=e.nodes[S],E=w.spec.tableRole;E&&(t[E]=w)}}return t}const tableEditingKey=new PluginKey(`selectingCells`);function cellAround(e){for(let t=e.depth-1;t>0;t--)if(e.node(t).type.spec.tableRole==`row`)return e.node(0).resolve(e.before(t+1));return null}function cellWrapping(e){for(let t=e.depth;t>0;t--){let S=e.node(t).type.spec.tableRole;if(S===`cell`||S===`header_cell`)return e.node(t)}return null}function isInTable(e){let t=e.selection.$head;for(let e=t.depth;e>0;e--)if(t.node(e).type.spec.tableRole==`row`)return!0;return!1}function selectionCell(e){let t=e.selection;if(`$anchorCell`in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if(`node`in t&&t.node&&t.node.type.spec.tableRole==`cell`)return t.$anchor;let S=cellAround(t.$head)||cellNear(t.$head);if(S)return S;throw RangeError(`No cell found around position ${t.head}`)}function cellNear(e){for(let t=e.nodeAfter,S=e.pos;t;t=t.firstChild,S++){let w=t.type.spec.tableRole;if(w==`cell`||w==`header_cell`)return e.doc.resolve(S)}for(let t=e.nodeBefore,S=e.pos;t;t=t.lastChild,S--){let w=t.type.spec.tableRole;if(w==`cell`||w==`header_cell`)return e.doc.resolve(S-t.nodeSize)}}function pointsAtCell(e){return e.parent.type.spec.tableRole==`row`&&!!e.nodeAfter}function moveCellForward(e){return e.node(0).resolve(e.pos+e.nodeAfter.nodeSize)}function inSameTable(e,t){return e.depth==t.depth&&e.pos>=t.start(-1)&&e.pos<=t.end(-1)}function nextCell(e,t,S){let w=e.node(-1),E=TableMap.get(w),D=e.start(-1),O=E.nextCell(e.pos-D,t,S);return O==null?null:e.node(0).resolve(D+O)}function removeColSpan(e,t,S=1){let w={...e,colspan:e.colspan-S};return w.colwidth&&(w.colwidth=w.colwidth.slice(),w.colwidth.splice(t,S),w.colwidth.some(e=>e>0)||(w.colwidth=null)),w}function addColSpan(e,t,S=1){let w={...e,colspan:e.colspan+S};if(w.colwidth){w.colwidth=w.colwidth.slice();for(let e=0;e<S;e++)w.colwidth.splice(t,0,0)}return w}function columnIsHeader(e,t,S){let w=tableNodeTypes(t.type.schema).header_cell;for(let E=0;E<e.height;E++)if(t.nodeAt(e.map[S+E*e.width]).type!=w)return!1;return!0}var CellSelection=class e extends Selection$1{constructor(e,t=e){let S=e.node(-1),w=TableMap.get(S),E=e.start(-1),D=w.rectBetween(e.pos-E,t.pos-E),O=e.node(0),k=w.cellsInRect(D).filter(e=>e!=t.pos-E);k.unshift(t.pos-E);let j=k.map(e=>{let t=S.nodeAt(e);if(!t)throw RangeError(`No cell with offset ${e} found`);let w=E+e+1;return new SelectionRange(O.resolve(w),O.resolve(w+t.content.size))});super(j[0].$from,j[0].$to,j),this.$anchorCell=e,this.$headCell=t}map(t,S){let w=t.resolve(S.map(this.$anchorCell.pos)),E=t.resolve(S.map(this.$headCell.pos));if(pointsAtCell(w)&&pointsAtCell(E)&&inSameTable(w,E)){let t=this.$anchorCell.node(-1)!=w.node(-1);return t&&this.isRowSelection()?e.rowSelection(w,E):t&&this.isColSelection()?e.colSelection(w,E):new e(w,E)}return TextSelection.between(w,E)}content(){let e=this.$anchorCell.node(-1),t=TableMap.get(e),S=this.$anchorCell.start(-1),w=t.rectBetween(this.$anchorCell.pos-S,this.$headCell.pos-S),E={},D=[];for(let S=w.top;S<w.bottom;S++){let O=[];for(let D=S*t.width+w.left,k=w.left;k<w.right;k++,D++){let S=t.map[D];if(E[S])continue;E[S]=!0;let k=t.findCell(S),j=e.nodeAt(S);if(!j)throw RangeError(`No cell with offset ${S} found`);let F=w.left-k.left,L=k.right-w.right;if(F>0||L>0){let e=j.attrs;if(F>0&&(e=removeColSpan(e,0,F)),L>0&&(e=removeColSpan(e,e.colspan-L,L)),k.left<w.left){if(j=j.type.createAndFill(e),!j)throw RangeError(`Could not create cell with attrs ${JSON.stringify(e)}`)}else j=j.type.create(e,j.content)}if(k.top<w.top||k.bottom>w.bottom){let e={...j.attrs,rowspan:Math.min(k.bottom,w.bottom)-Math.max(k.top,w.top)};j=k.top<w.top?j.type.createAndFill(e):j.type.create(e,j.content)}O.push(j)}D.push(e.child(S).copy(Fragment.from(O)))}let O=this.isColSelection()&&this.isRowSelection()?e:D;return new Slice(Fragment.from(O),1,1)}replace(e,t=Slice.empty){let S=e.steps.length,w=this.ranges;for(let E=0;E<w.length;E++){let{$from:D,$to:O}=w[E],k=e.mapping.slice(S);e.replace(k.map(D.pos),k.map(O.pos),E?Slice.empty:t)}let E=Selection$1.findFrom(e.doc.resolve(e.mapping.slice(S).map(this.to)),-1);E&&e.setSelection(E)}replaceWith(e,t){this.replace(e,new Slice(Fragment.from(t),0,0))}forEachCell(e){let t=this.$anchorCell.node(-1),S=TableMap.get(t),w=this.$anchorCell.start(-1),E=S.cellsInRect(S.rectBetween(this.$anchorCell.pos-w,this.$headCell.pos-w));for(let S=0;S<E.length;S++)e(t.nodeAt(E[S]),w+E[S])}isColSelection(){let e=this.$anchorCell.index(-1),t=this.$headCell.index(-1);if(Math.min(e,t)>0)return!1;let S=e+this.$anchorCell.nodeAfter.attrs.rowspan,w=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(S,w)==this.$headCell.node(-1).childCount}static colSelection(t,S=t){let w=t.node(-1),E=TableMap.get(w),D=t.start(-1),O=E.findCell(t.pos-D),k=E.findCell(S.pos-D),j=t.node(0);return O.top<=k.top?(O.top>0&&(t=j.resolve(D+E.map[O.left])),k.bottom<E.height&&(S=j.resolve(D+E.map[E.width*(E.height-1)+k.right-1]))):(k.top>0&&(S=j.resolve(D+E.map[k.left])),O.bottom<E.height&&(t=j.resolve(D+E.map[E.width*(E.height-1)+O.right-1]))),new e(t,S)}isRowSelection(){let e=this.$anchorCell.node(-1),t=TableMap.get(e),S=this.$anchorCell.start(-1),w=t.colCount(this.$anchorCell.pos-S),E=t.colCount(this.$headCell.pos-S);if(Math.min(w,E)>0)return!1;let D=w+this.$anchorCell.nodeAfter.attrs.colspan,O=E+this.$headCell.nodeAfter.attrs.colspan;return Math.max(D,O)==t.width}eq(t){return t instanceof e&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,S=t){let w=t.node(-1),E=TableMap.get(w),D=t.start(-1),O=E.findCell(t.pos-D),k=E.findCell(S.pos-D),j=t.node(0);return O.left<=k.left?(O.left>0&&(t=j.resolve(D+E.map[O.top*E.width])),k.right<E.width&&(S=j.resolve(D+E.map[E.width*(k.top+1)-1]))):(k.left>0&&(S=j.resolve(D+E.map[k.top*E.width])),O.right<E.width&&(t=j.resolve(D+E.map[E.width*(O.top+1)-1]))),new e(t,S)}toJSON(){return{type:`cell`,anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(t,S){return new e(t.resolve(S.anchor),t.resolve(S.head))}static create(t,S,w=S){return new e(t.resolve(S),t.resolve(w))}getBookmark(){return new CellBookmark(this.$anchorCell.pos,this.$headCell.pos)}};CellSelection.prototype.visible=!1,Selection$1.jsonID(`cell`,CellSelection);var CellBookmark=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){let t=e.resolve(this.anchor),S=e.resolve(this.head);return t.parent.type.spec.tableRole==`row`&&S.parent.type.spec.tableRole==`row`&&t.index()<t.parent.childCount&&S.index()<S.parent.childCount&&inSameTable(t,S)?new CellSelection(t,S):Selection$1.near(S,1)}};function drawCellSelection(e){if(!(e.selection instanceof CellSelection))return null;let t=[];return e.selection.forEachCell((e,S)=>{t.push(Decoration.node(S,S+e.nodeSize,{class:`selectedCell`}))}),DecorationSet.create(e.doc,t)}function isCellBoundarySelection({$from:e,$to:t}){if(e.pos==t.pos||e.pos<t.pos-6)return!1;let S=e.pos,w=t.pos,E=e.depth;for(;E>=0&&!(e.after(E+1)<e.end(E));E--,S++);for(let e=t.depth;e>=0&&!(t.before(e+1)>t.start(e));e--,w--);return S==w&&/row|table/.test(e.node(E).type.spec.tableRole)}function isTextSelectionAcrossCells({$from:e,$to:t}){let S,w;for(let t=e.depth;t>0;t--){let w=e.node(t);if(w.type.spec.tableRole===`cell`||w.type.spec.tableRole===`header_cell`){S=w;break}}for(let e=t.depth;e>0;e--){let S=t.node(e);if(S.type.spec.tableRole===`cell`||S.type.spec.tableRole===`header_cell`){w=S;break}}return S!==w&&t.parentOffset===0}function normalizeSelection(e,t,S){let w=(t||e).selection,E=(t||e).doc,D,O;if(w instanceof NodeSelection&&(O=w.node.type.spec.tableRole)){if(O==`cell`||O==`header_cell`)D=CellSelection.create(E,w.from);else if(O==`row`){let e=E.resolve(w.from+1);D=CellSelection.rowSelection(e,e)}else if(!S){let e=TableMap.get(w.node),t=w.from+1,S=t+e.map[e.width*e.height-1];D=CellSelection.create(E,t+1,S)}}else w instanceof TextSelection&&isCellBoundarySelection(w)?D=TextSelection.create(E,w.from):w instanceof TextSelection&&isTextSelectionAcrossCells(w)&&(D=TextSelection.create(E,w.$from.start(),w.$from.end()));return D&&(t||=e.tr).setSelection(D),t}const fixTablesKey=new PluginKey(`fix-tables`);function changedDescendants(e,t,S,w){let E=e.childCount,D=t.childCount;outer:for(let O=0,k=0;O<D;O++){let D=t.child(O);for(let t=k,w=Math.min(E,O+3);t<w;t++)if(e.child(t)==D){k=t+1,S+=D.nodeSize;continue outer}w(D,S),k<E&&e.child(k).sameMarkup(D)?changedDescendants(e.child(k),D,S+1,w):D.nodesBetween(0,D.content.size,w,S+1),S+=D.nodeSize}}function fixTables(e,t){let S,w=(t,w)=>{t.type.spec.tableRole==`table`&&(S=fixTable(e,t,w,S))};return t?t.doc!=e.doc&&changedDescendants(t.doc,e.doc,0,w):e.doc.descendants(w),S}function fixTable(e,t,S,w){let E=TableMap.get(t);if(!E.problems)return w;w||=e.tr;let D=[];for(let e=0;e<E.height;e++)D.push(0);for(let e=0;e<E.problems.length;e++){let O=E.problems[e];if(O.type==`collision`){let e=t.nodeAt(O.pos);if(!e)continue;let E=e.attrs;for(let e=0;e<E.rowspan;e++)D[O.row+e]+=O.n;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,removeColSpan(E,E.colspan-O.n,O.n))}else if(O.type==`missing`)D[O.row]+=O.n;else if(O.type==`overlong_rowspan`){let e=t.nodeAt(O.pos);if(!e)continue;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,{...e.attrs,rowspan:e.attrs.rowspan-O.n})}else if(O.type==`colwidth mismatch`){let e=t.nodeAt(O.pos);if(!e)continue;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,{...e.attrs,colwidth:O.colwidth})}else if(O.type==`zero_sized`){let e=w.mapping.map(S);w.delete(e,e+t.nodeSize)}}let O,k;for(let e=0;e<D.length;e++)D[e]&&(O??=e,k=e);for(let j=0,F=S+1;j<E.height;j++){let S=t.child(j),E=F+S.nodeSize,L=D[j];if(L>0){let t=`cell`;S.firstChild&&(t=S.firstChild.type.spec.tableRole);let D=[];for(let S=0;S<L;S++){let S=tableNodeTypes(e.schema)[t].createAndFill();S&&D.push(S)}let B=(j==0||O==j-1)&&k==j?F+1:E-1;w.insert(w.mapping.map(B),D)}F=E}return w.setMeta(fixTablesKey,{fixTables:!0})}function selectedRect(e){let t=e.selection,S=selectionCell(e),w=S.node(-1),E=S.start(-1),D=TableMap.get(w);return{...t instanceof CellSelection?D.rectBetween(t.$anchorCell.pos-E,t.$headCell.pos-E):D.findCell(S.pos-E),tableStart:E,map:D,table:w}}function addColumn(e,{map:t,tableStart:S,table:w},E){let D=E>0?-1:0;columnIsHeader(t,w,E+D)&&(D=E==0||E==t.width?null:0);for(let O=0;O<t.height;O++){let k=O*t.width+E;if(E>0&&E<t.width&&t.map[k-1]==t.map[k]){let D=t.map[k],j=w.nodeAt(D);e.setNodeMarkup(e.mapping.map(S+D),null,addColSpan(j.attrs,E-t.colCount(D))),O+=j.attrs.rowspan-1}else{let j=D==null?tableNodeTypes(w.type.schema).cell:w.nodeAt(t.map[k+D]).type,F=t.positionAt(O,E,w);e.insert(e.mapping.map(S+F),j.createAndFill())}}return e}function addColumnBefore(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addColumn(e.tr,S,S.left))}return!0}function addColumnAfter(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addColumn(e.tr,S,S.right))}return!0}function removeColumn(e,{map:t,table:S,tableStart:w},E){let D=e.mapping.maps.length;for(let O=0;O<t.height;){let k=O*t.width+E,j=t.map[k],F=S.nodeAt(j),L=F.attrs;if(E>0&&t.map[k-1]==j||E<t.width-1&&t.map[k+1]==j)e.setNodeMarkup(e.mapping.slice(D).map(w+j),null,removeColSpan(L,E-t.colCount(j)));else{let t=e.mapping.slice(D).map(w+j);e.delete(t,t+F.nodeSize)}O+=L.rowspan}}function deleteColumn(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e),w=e.tr;if(S.left==0&&S.right==S.map.width)return!1;for(let e=S.right-1;removeColumn(w,S,e),e!=S.left;e--){let e=S.tableStart?w.doc.nodeAt(S.tableStart-1):w.doc;if(!e)throw RangeError(`No table found`);S.table=e,S.map=TableMap.get(e)}t(w)}return!0}function rowIsHeader(e,t,S){var w;let E=tableNodeTypes(t.type.schema).header_cell;for(let w=0;w<e.width;w++)if(t.nodeAt(e.map[w+S*e.width])?.type!=E)return!1;return!0}function addRow(e,{map:t,tableStart:S,table:w},E){let D=S;for(let e=0;e<E;e++)D+=w.child(e).nodeSize;let O=[],k=E>0?-1:0;rowIsHeader(t,w,E+k)&&(k=E==0||E==t.height?null:0);for(let D=0,F=t.width*E;D<t.width;D++,F++)if(E>0&&E<t.height&&t.map[F]==t.map[F-t.width]){let E=t.map[F],O=w.nodeAt(E).attrs;e.setNodeMarkup(S+E,null,{...O,rowspan:O.rowspan+1}),D+=O.colspan-1}else{var j;let e=(k==null?tableNodeTypes(w.type.schema).cell:w.nodeAt(t.map[F+k*t.width])?.type)?.createAndFill();e&&O.push(e)}return e.insert(D,tableNodeTypes(w.type.schema).row.create(null,O)),e}function addRowBefore(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addRow(e.tr,S,S.top))}return!0}function addRowAfter(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addRow(e.tr,S,S.bottom))}return!0}function removeRow(e,{map:t,table:S,tableStart:w},E){let D=0;for(let e=0;e<E;e++)D+=S.child(e).nodeSize;let O=D+S.child(E).nodeSize,k=e.mapping.maps.length;e.delete(D+w,O+w);let j=new Set;for(let D=0,O=E*t.width;D<t.width;D++,O++){let F=t.map[O];if(!j.has(F)){if(j.add(F),E>0&&F==t.map[O-t.width]){let t=S.nodeAt(F).attrs;e.setNodeMarkup(e.mapping.slice(k).map(F+w),null,{...t,rowspan:t.rowspan-1}),D+=t.colspan-1}else if(E<t.height&&F==t.map[O+t.width]){let O=S.nodeAt(F),j=O.attrs,L=O.type.create({...j,rowspan:O.attrs.rowspan-1},O.content),B=t.positionAt(E+1,D,S);e.insert(e.mapping.slice(k).map(w+B),L),D+=j.colspan-1}}}}function deleteRow(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e),w=e.tr;if(S.top==0&&S.bottom==S.map.height)return!1;for(let e=S.bottom-1;removeRow(w,S,e),e!=S.top;e--){let e=S.tableStart?w.doc.nodeAt(S.tableStart-1):w.doc;if(!e)throw RangeError(`No table found`);S.table=e,S.map=TableMap.get(S.table)}t(w)}return!0}function isEmpty$3(e){let t=e.content;return t.childCount==1&&t.child(0).isTextblock&&t.child(0).childCount==0}function cellsOverlapRectangle({width:e,height:t,map:S},w){let E=w.top*e+w.left,D=E,O=(w.bottom-1)*e+w.left,k=E+(w.right-w.left-1);for(let t=w.top;t<w.bottom;t++){if(w.left>0&&S[D]==S[D-1]||w.right<e&&S[k]==S[k+1])return!0;D+=e,k+=e}for(let D=w.left;D<w.right;D++){if(w.top>0&&S[E]==S[E-e]||w.bottom<t&&S[O]==S[O+e])return!0;E++,O++}return!1}function mergeCells(e,t){let S=e.selection;if(!(S instanceof CellSelection)||S.$anchorCell.pos==S.$headCell.pos)return!1;let w=selectedRect(e),{map:E}=w;if(cellsOverlapRectangle(E,w))return!1;if(t){let S=e.tr,D={},O=Fragment.empty,k,j;for(let e=w.top;e<w.bottom;e++)for(let t=w.left;t<w.right;t++){let F=E.map[e*E.width+t],L=w.table.nodeAt(F);if(!(D[F]||!L))if(D[F]=!0,k==null)k=F,j=L;else{isEmpty$3(L)||(O=O.append(L.content));let e=S.mapping.map(F+w.tableStart);S.delete(e,e+L.nodeSize)}}if(k==null||j==null)return!0;if(S.setNodeMarkup(k+w.tableStart,null,{...addColSpan(j.attrs,j.attrs.colspan,w.right-w.left-j.attrs.colspan),rowspan:w.bottom-w.top}),O.size>0){let e=k+1+j.content.size,t=isEmpty$3(j)?k+1:e;S.replaceWith(t+w.tableStart,e+w.tableStart,O)}S.setSelection(new CellSelection(S.doc.resolve(k+w.tableStart))),t(S)}return!0}function splitCell(e,t){let S=tableNodeTypes(e.schema);return splitCellWithType(({node:e})=>S[e.type.spec.tableRole])(e,t)}function splitCellWithType(e){return(t,S)=>{let w=t.selection,E,D;if(w instanceof CellSelection){if(w.$anchorCell.pos!=w.$headCell.pos)return!1;E=w.$anchorCell.nodeAfter,D=w.$anchorCell.pos}else{var O;if(E=cellWrapping(w.$from),!E)return!1;D=cellAround(w.$from)?.pos}if(E==null||D==null||E.attrs.colspan==1&&E.attrs.rowspan==1)return!1;if(S){let O=E.attrs,k=[],j=O.colwidth;O.rowspan>1&&(O={...O,rowspan:1}),O.colspan>1&&(O={...O,colspan:1});let F=selectedRect(t),L=t.tr;for(let e=0;e<F.right-F.left;e++)k.push(j?{...O,colwidth:j&&j[e]?[j[e]]:null}:O);let B;for(let t=F.top;t<F.bottom;t++){let S=F.map.positionAt(t,F.left,F.table);t==F.top&&(S+=E.nodeSize);for(let w=F.left,D=0;w<F.right;w++,D++)w==F.left&&t==F.top||L.insert(B=L.mapping.map(S+F.tableStart,1),e({node:E,row:t,col:w}).createAndFill(k[D]))}L.setNodeMarkup(D,e({node:E,row:F.top,col:F.left}),k[0]),w instanceof CellSelection&&L.setSelection(new CellSelection(L.doc.resolve(w.$anchorCell.pos),B?L.doc.resolve(B):void 0)),S(L)}return!0}}function setCellAttr(e,t){return function(S,w){if(!isInTable(S))return!1;let E=selectionCell(S);if(E.nodeAfter.attrs[e]===t)return!1;if(w){let D=S.tr;S.selection instanceof CellSelection?S.selection.forEachCell((S,w)=>{S.attrs[e]!==t&&D.setNodeMarkup(w,null,{...S.attrs,[e]:t})}):D.setNodeMarkup(E.pos,null,{...E.nodeAfter.attrs,[e]:t}),w(D)}return!0}}function deprecated_toggleHeader(e){return function(t,S){if(!isInTable(t))return!1;if(S){let w=tableNodeTypes(t.schema),E=selectedRect(t),D=t.tr,O=E.map.cellsInRect(e==`column`?{left:E.left,top:0,right:E.right,bottom:E.map.height}:e==`row`?{left:0,top:E.top,right:E.map.width,bottom:E.bottom}:E),k=O.map(e=>E.table.nodeAt(e));for(let e=0;e<O.length;e++)k[e].type==w.header_cell&&D.setNodeMarkup(E.tableStart+O[e],w.cell,k[e].attrs);if(D.steps.length===0)for(let e=0;e<O.length;e++)D.setNodeMarkup(E.tableStart+O[e],w.header_cell,k[e].attrs);S(D)}return!0}}function isHeaderEnabledByType(e,t,S){let w=t.map.cellsInRect({left:0,top:0,right:e==`row`?t.map.width:1,bottom:e==`column`?t.map.height:1});for(let e=0;e<w.length;e++){let E=t.table.nodeAt(w[e]);if(E&&E.type!==S.header_cell)return!1}return!0}function toggleHeader(e,t){return t||={useDeprecatedLogic:!1},t.useDeprecatedLogic?deprecated_toggleHeader(e):function(t,S){if(!isInTable(t))return!1;if(S){let w=tableNodeTypes(t.schema),E=selectedRect(t),D=t.tr,O=isHeaderEnabledByType(`row`,E,w),k=isHeaderEnabledByType(`column`,E,w),j=(e===`column`?O:e===`row`&&k)?1:0,F=e==`column`?{left:0,top:j,right:1,bottom:E.map.height}:e==`row`?{left:j,top:0,right:E.map.width,bottom:1}:E,L=e==`column`?k?w.cell:w.header_cell:e==`row`?O?w.cell:w.header_cell:w.cell;E.map.cellsInRect(F).forEach(e=>{let t=e+E.tableStart,S=D.doc.nodeAt(t);S&&D.setNodeMarkup(t,L,S.attrs)}),S(D)}return!0}}const toggleHeaderRow=toggleHeader(`row`,{useDeprecatedLogic:!0}),toggleHeaderColumn=toggleHeader(`column`,{useDeprecatedLogic:!0}),toggleHeaderCell=toggleHeader(`cell`,{useDeprecatedLogic:!0});function findNextCell(e,t){if(t<0){let t=e.nodeBefore;if(t)return e.pos-t.nodeSize;for(let t=e.index(-1)-1,S=e.before();t>=0;t--){let w=e.node(-1).child(t),E=w.lastChild;if(E)return S-1-E.nodeSize;S-=w.nodeSize}}else{if(e.index()<e.parent.childCount-1)return e.pos+e.nodeAfter.nodeSize;let t=e.node(-1);for(let S=e.indexAfter(-1),w=e.after();S<t.childCount;S++){let e=t.child(S);if(e.childCount)return w+1;w+=e.nodeSize}}return null}function goToNextCell(e){return function(t,S){if(!isInTable(t))return!1;let w=findNextCell(selectionCell(t),e);if(w==null)return!1;if(S){let e=t.doc.resolve(w);S(t.tr.setSelection(TextSelection.between(e,moveCellForward(e))).scrollIntoView())}return!0}}function deleteTable(e,t){let S=e.selection.$anchor;for(let w=S.depth;w>0;w--)if(S.node(w).type.spec.tableRole==`table`)return t&&t(e.tr.delete(S.before(w),S.after(w)).scrollIntoView()),!0;return!1}function deleteCellSelection(e,t){let S=e.selection;if(!(S instanceof CellSelection))return!1;if(t){let w=e.tr,E=tableNodeTypes(e.schema).cell.createAndFill().content;S.forEachCell((e,t)=>{e.content.eq(E)||w.replace(w.mapping.map(t+1),w.mapping.map(t+e.nodeSize-1),new Slice(E,0,0))}),w.docChanged&&t(w)}return!0}function pastedCells(e){if(e.size===0)return null;let{content:t,openStart:S,openEnd:w}=e;for(;t.childCount==1&&(S>0&&w>0||t.child(0).type.spec.tableRole==`table`);)S--,w--,t=t.child(0).content;let E=t.child(0),D=E.type.spec.tableRole,O=E.type.schema,k=[];if(D==`row`)for(let e=0;e<t.childCount;e++){let E=t.child(e).content,D=e?0:Math.max(0,S-1),j=e<t.childCount-1?0:Math.max(0,w-1);(D||j)&&(E=fitSlice(tableNodeTypes(O).row,new Slice(E,D,j)).content),k.push(E)}else if(D==`cell`||D==`header_cell`)k.push(S||w?fitSlice(tableNodeTypes(O).row,new Slice(t,S,w)).content:t);else return null;return ensureRectangular(O,k)}function ensureRectangular(e,t){let S=[];for(let e=0;e<t.length;e++){let w=t[e];for(let t=w.childCount-1;t>=0;t--){let{rowspan:E,colspan:D}=w.child(t).attrs;for(let t=e;t<e+E;t++)S[t]=(S[t]||0)+D}}let w=0;for(let e=0;e<S.length;e++)w=Math.max(w,S[e]);for(let E=0;E<S.length;E++)if(E>=t.length&&t.push(Fragment.empty),S[E]<w){let D=tableNodeTypes(e).cell.createAndFill(),O=[];for(let e=S[E];e<w;e++)O.push(D);t[E]=t[E].append(Fragment.from(O))}return{height:t.length,width:w,rows:t}}function fitSlice(e,t){let S=e.createAndFill();return new Transform$4(S).replace(0,S.content.size,t).doc}function clipCells({width:e,height:t,rows:S},w,E){if(e!=w){let t=[],E=[];for(let e=0;e<S.length;e++){let D=S[e],O=[];for(let S=t[e]||0,E=0;S<w;E++){let k=D.child(E%D.childCount);S+k.attrs.colspan>w&&(k=k.type.createChecked(removeColSpan(k.attrs,k.attrs.colspan,S+k.attrs.colspan-w),k.content)),O.push(k),S+=k.attrs.colspan;for(let S=1;S<k.attrs.rowspan;S++)t[e+S]=(t[e+S]||0)+k.attrs.colspan}E.push(Fragment.from(O))}S=E,e=w}if(t!=E){let e=[];for(let w=0,D=0;w<E;w++,D++){let O=[],k=S[D%t];for(let e=0;e<k.childCount;e++){let t=k.child(e);w+t.attrs.rowspan>E&&(t=t.type.create({...t.attrs,rowspan:Math.max(1,E-t.attrs.rowspan)},t.content)),O.push(t)}e.push(Fragment.from(O))}S=e,t=E}return{width:e,height:t,rows:S}}function growTable(e,t,S,w,E,D,O){let k=e.doc.type.schema,j=tableNodeTypes(k),F,L;if(E>t.width)for(let D=0,k=0;D<t.height;D++){let B=S.child(D);k+=B.nodeSize;let H=[],q;q=B.lastChild==null||B.lastChild.type==j.cell?F||=j.cell.createAndFill():L||=j.header_cell.createAndFill();for(let e=t.width;e<E;e++)H.push(q);e.insert(e.mapping.slice(O).map(k-1+w),H)}if(D>t.height){let k=[];for(let e=0,w=(t.height-1)*t.width;e<Math.max(t.width,E);e++){let E=e>=t.width?!1:S.nodeAt(t.map[w+e]).type==j.header_cell;k.push(E?L||=j.header_cell.createAndFill():F||=j.cell.createAndFill())}let B=j.row.create(null,Fragment.from(k)),H=[];for(let e=t.height;e<D;e++)H.push(B);e.insert(e.mapping.slice(O).map(w+S.nodeSize-2),H)}return!!(F||L)}function isolateHorizontal(e,t,S,w,E,D,O,k){if(O==0||O==t.height)return!1;let j=!1;for(let F=E;F<D;F++){let E=O*t.width+F,D=t.map[E];if(t.map[E-t.width]==D){j=!0;let E=S.nodeAt(D),{top:L,left:B}=t.findCell(D);e.setNodeMarkup(e.mapping.slice(k).map(D+w),null,{...E.attrs,rowspan:O-L}),e.insert(e.mapping.slice(k).map(t.positionAt(O,B,S)),E.type.createAndFill({...E.attrs,rowspan:L+E.attrs.rowspan-O})),F+=E.attrs.colspan-1}}return j}function isolateVertical(e,t,S,w,E,D,O,k){if(O==0||O==t.width)return!1;let j=!1;for(let F=E;F<D;F++){let E=F*t.width+O,D=t.map[E];if(t.map[E-1]==D){j=!0;let E=S.nodeAt(D),L=t.colCount(D),B=e.mapping.slice(k).map(D+w);e.setNodeMarkup(B,null,removeColSpan(E.attrs,O-L,E.attrs.colspan-(O-L))),e.insert(B+E.nodeSize,E.type.createAndFill(removeColSpan(E.attrs,0,O-L))),F+=E.attrs.rowspan-1}}return j}function insertCells(e,t,S,w,E){let D=S?e.doc.nodeAt(S-1):e.doc;if(!D)throw Error(`No table found`);let O=TableMap.get(D),{top:k,left:j}=w,F=j+E.width,L=k+E.height,B=e.tr,H=0;function q(){if(D=S?B.doc.nodeAt(S-1):B.doc,!D)throw Error(`No table found`);O=TableMap.get(D),H=B.mapping.maps.length}growTable(B,O,D,S,F,L,H)&&q(),isolateHorizontal(B,O,D,S,j,F,k,H)&&q(),isolateHorizontal(B,O,D,S,j,F,L,H)&&q(),isolateVertical(B,O,D,S,k,L,j,H)&&q(),isolateVertical(B,O,D,S,k,L,F,H)&&q();for(let e=k;e<L;e++){let t=O.positionAt(e,j,D),w=O.positionAt(e,F,D);B.replace(B.mapping.slice(H).map(t+S),B.mapping.slice(H).map(w+S),new Slice(E.rows[e-k],0,0))}q(),B.setSelection(new CellSelection(B.doc.resolve(S+O.positionAt(k,j,D)),B.doc.resolve(S+O.positionAt(L-1,F-1,D)))),t(B)}const handleKeyDown$1=keydownHandler({ArrowLeft:arrow$1(`horiz`,-1),ArrowRight:arrow$1(`horiz`,1),ArrowUp:arrow$1(`vert`,-1),ArrowDown:arrow$1(`vert`,1),"Shift-ArrowLeft":shiftArrow(`horiz`,-1),"Shift-ArrowRight":shiftArrow(`horiz`,1),"Shift-ArrowUp":shiftArrow(`vert`,-1),"Shift-ArrowDown":shiftArrow(`vert`,1),Backspace:deleteCellSelection,"Mod-Backspace":deleteCellSelection,Delete:deleteCellSelection,"Mod-Delete":deleteCellSelection});function maybeSetSelection(e,t,S){return S.eq(e.selection)?!1:(t&&t(e.tr.setSelection(S).scrollIntoView()),!0)}function arrow$1(e,t){return(S,w,E)=>{if(!E)return!1;let D=S.selection;if(D instanceof CellSelection)return maybeSetSelection(S,w,Selection$1.near(D.$headCell,t));if(e!=`horiz`&&!D.empty)return!1;let O=atEndOfCell(E,e,t);if(O==null)return!1;if(e==`horiz`)return maybeSetSelection(S,w,Selection$1.near(S.doc.resolve(D.head+t),t));{let E=S.doc.resolve(O),D=nextCell(E,e,t),k;return k=D?Selection$1.near(D,1):t<0?Selection$1.near(S.doc.resolve(E.before(-1)),-1):Selection$1.near(S.doc.resolve(E.after(-1)),1),maybeSetSelection(S,w,k)}}}function shiftArrow(e,t){return(S,w,E)=>{if(!E)return!1;let D=S.selection,O;if(D instanceof CellSelection)O=D;else{let w=atEndOfCell(E,e,t);if(w==null)return!1;O=new CellSelection(S.doc.resolve(w))}let k=nextCell(O.$headCell,e,t);return k?maybeSetSelection(S,w,new CellSelection(O.$anchorCell,k)):!1}}function handleTripleClick(e,t){let S=e.state.doc,w=cellAround(S.resolve(t));return w?(e.dispatch(e.state.tr.setSelection(new CellSelection(w))),!0):!1}function handlePaste(e,t,S){if(!isInTable(e.state))return!1;let w=pastedCells(S),E=e.state.selection;if(E instanceof CellSelection){w||={width:1,height:1,rows:[Fragment.from(fitSlice(tableNodeTypes(e.state.schema).cell,S))]};let t=E.$anchorCell.node(-1),D=E.$anchorCell.start(-1),O=TableMap.get(t).rectBetween(E.$anchorCell.pos-D,E.$headCell.pos-D);return w=clipCells(w,O.right-O.left,O.bottom-O.top),insertCells(e.state,e.dispatch,D,O,w),!0}else if(w){let t=selectionCell(e.state),S=t.start(-1);return insertCells(e.state,e.dispatch,S,TableMap.get(t.node(-1)).findCell(t.pos-S),w),!0}else return!1}function handleMouseDown$1(e,t){var S;if(t.button!=0||t.ctrlKey||t.metaKey)return;let w=domInCell(e,t.target),E;if(t.shiftKey&&e.state.selection instanceof CellSelection)D(e.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&w&&(E=cellAround(e.state.selection.$anchor))!=null&&cellUnderMouse(e,t)?.pos!=E.pos)D(E,t),t.preventDefault();else if(!w)return;function D(t,S){let w=cellUnderMouse(e,S),E=tableEditingKey.getState(e.state)==null;if(!w||!inSameTable(t,w))if(E)w=t;else return;let D=new CellSelection(t,w);if(E||!e.state.selection.eq(D)){let S=e.state.tr.setSelection(D);E&&S.setMeta(tableEditingKey,t.pos),e.dispatch(S)}}function O(){e.root.removeEventListener(`mouseup`,O),e.root.removeEventListener(`dragstart`,O),e.root.removeEventListener(`mousemove`,k),tableEditingKey.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta(tableEditingKey,-1))}function k(S){let E=S,k=tableEditingKey.getState(e.state),j;if(k!=null)j=e.state.doc.resolve(k);else if(domInCell(e,E.target)!=w&&(j=cellUnderMouse(e,t),!j))return O();j&&D(j,E)}e.root.addEventListener(`mouseup`,O),e.root.addEventListener(`dragstart`,O),e.root.addEventListener(`mousemove`,k)}function atEndOfCell(e,t,S){if(!(e.state.selection instanceof TextSelection))return null;let{$head:w}=e.state.selection;for(let E=w.depth-1;E>=0;E--){let D=w.node(E);if((S<0?w.index(E):w.indexAfter(E))!=(S<0?0:D.childCount))return null;if(D.type.spec.tableRole==`cell`||D.type.spec.tableRole==`header_cell`){let D=w.before(E),O=t==`vert`?S>0?`down`:`up`:S>0?`right`:`left`;return e.endOfTextblock(O)?D:null}}return null}function domInCell(e,t){for(;t&&t!=e.dom;t=t.parentNode)if(t.nodeName==`TD`||t.nodeName==`TH`)return t;return null}function cellUnderMouse(e,t){let S=e.posAtCoords({left:t.clientX,top:t.clientY});if(!S)return null;let{inside:w,pos:E}=S;return w>=0&&cellAround(e.state.doc.resolve(w))||cellAround(e.state.doc.resolve(E))}var TableView$1=class{constructor(e,t){this.node=e,this.defaultCellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),this.table.style.setProperty(`--default-cell-min-width`,`${t}px`),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),updateColumnsOnResize(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type==this.node.type?(this.node=e,updateColumnsOnResize(e,this.colgroup,this.table,this.defaultCellMinWidth),!0):!1}ignoreMutation(e){return e.type==`attributes`&&(e.target==this.table||this.colgroup.contains(e.target))}};function updateColumnsOnResize(e,t,S,w,E,D){let O=0,k=!0,j=t.firstChild,F=e.firstChild;if(F){for(let e=0,S=0;e<F.childCount;e++){let{colspan:L,colwidth:B}=F.child(e).attrs;for(let e=0;e<L;e++,S++){let F=E==S?D:B&&B[e],L=F?F+`px`:``;if(O+=F||w,F||(k=!1),j)j.style.width!=L&&(j.style.width=L),j=j.nextSibling;else{let e=document.createElement(`col`);e.style.width=L,t.appendChild(e)}}}for(;j;){var L;let e=j.nextSibling;(L=j.parentNode)==null||L.removeChild(j),j=e}k?(S.style.width=O+`px`,S.style.minWidth=``):(S.style.width=``,S.style.minWidth=O+`px`)}}const columnResizingPluginKey=new PluginKey(`tableColumnResizing`);function columnResizing({handleWidth:e=5,cellMinWidth:t=25,defaultCellMinWidth:S=100,View:w=TableView$1,lastColumnResizable:E=!0}={}){let D=new Plugin({key:columnResizingPluginKey,state:{init(e,t){var E;let O=(E=D.spec)==null||(E=E.props)==null?void 0:E.nodeViews,k=tableNodeTypes(t.schema).table.name;return w&&O&&(O[k]=(e,t)=>new w(e,S,t)),new ResizeState(-1,!1)},apply(e,t){return t.apply(e)}},props:{attributes:e=>{let t=columnResizingPluginKey.getState(e);return t&&t.activeHandle>-1?{class:`resize-cursor`}:{}},handleDOMEvents:{mousemove:(t,S)=>{handleMouseMove(t,S,e,E)},mouseleave:e=>{handleMouseLeave(e)},mousedown:(e,w)=>{handleMouseDown(e,w,t,S)}},decorations:e=>{let t=columnResizingPluginKey.getState(e);if(t&&t.activeHandle>-1)return handleDecorations(e,t.activeHandle)},nodeViews:{}}});return D}var ResizeState=class e{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(t){let S=this,w=t.getMeta(columnResizingPluginKey);if(w&&w.setHandle!=null)return new e(w.setHandle,!1);if(w&&w.setDragging!==void 0)return new e(S.activeHandle,w.setDragging);if(S.activeHandle>-1&&t.docChanged){let w=t.mapping.map(S.activeHandle,-1);return pointsAtCell(t.doc.resolve(w))||(w=-1),new e(w,S.dragging)}return S}};function handleMouseMove(e,t,S,w){if(!e.editable)return;let E=columnResizingPluginKey.getState(e.state);if(E&&!E.dragging){let D=domCellAround(t.target),O=-1;if(D){let{left:w,right:E}=D.getBoundingClientRect();t.clientX-w<=S?O=edgeCell(e,t,`left`,S):E-t.clientX<=S&&(O=edgeCell(e,t,`right`,S))}if(O!=E.activeHandle){if(!w&&O!==-1){let t=e.state.doc.resolve(O),S=t.node(-1),w=TableMap.get(S),E=t.start(-1);if(w.colCount(t.pos-E)+t.nodeAfter.attrs.colspan-1==w.width-1)return}updateHandle(e,O)}}}function handleMouseLeave(e){if(!e.editable)return;let t=columnResizingPluginKey.getState(e.state);t&&t.activeHandle>-1&&!t.dragging&&updateHandle(e,-1)}function handleMouseDown(e,t,S,w){var E;if(!e.editable)return!1;let D=e.dom.ownerDocument.defaultView??window,O=columnResizingPluginKey.getState(e.state);if(!O||O.activeHandle==-1||O.dragging)return!1;let k=e.state.doc.nodeAt(O.activeHandle),j=currentColWidth(e,O.activeHandle,k.attrs);e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setDragging:{startX:t.clientX,startWidth:j}}));function F(t){D.removeEventListener(`mouseup`,F),D.removeEventListener(`mousemove`,L);let w=columnResizingPluginKey.getState(e.state);w?.dragging&&(updateColumnWidth(e,w.activeHandle,draggedWidth(w.dragging,t,S)),e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setDragging:null})))}function L(t){if(!t.which)return F(t);let E=columnResizingPluginKey.getState(e.state);if(E&&E.dragging){let D=draggedWidth(E.dragging,t,S);displayColumnWidth(e,E.activeHandle,D,w)}}return displayColumnWidth(e,O.activeHandle,j,w),D.addEventListener(`mouseup`,F),D.addEventListener(`mousemove`,L),t.preventDefault(),!0}function currentColWidth(e,t,{colspan:S,colwidth:w}){let E=w&&w[w.length-1];if(E)return E;let D=e.domAtPos(t),O=D.node.childNodes[D.offset].offsetWidth,k=S;if(w)for(let e=0;e<S;e++)w[e]&&(O-=w[e],k--);return O/k}function domCellAround(e){for(;e&&e.nodeName!=`TD`&&e.nodeName!=`TH`;)e=e.classList&&e.classList.contains(`ProseMirror`)?null:e.parentNode;return e}function edgeCell(e,t,S,w){let E=S==`right`?-w:w,D=e.posAtCoords({left:t.clientX+E,top:t.clientY});if(!D)return-1;let{pos:O}=D,k=cellAround(e.state.doc.resolve(O));if(!k)return-1;if(S==`right`)return k.pos;let j=TableMap.get(k.node(-1)),F=k.start(-1),L=j.map.indexOf(k.pos-F);return L%j.width==0?-1:F+j.map[L-1]}function draggedWidth(e,t,S){let w=t.clientX-e.startX;return Math.max(S,e.startWidth+w)}function updateHandle(e,t){e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setHandle:t}))}function updateColumnWidth(e,t,S){let w=e.state.doc.resolve(t),E=w.node(-1),D=TableMap.get(E),O=w.start(-1),k=D.colCount(w.pos-O)+w.nodeAfter.attrs.colspan-1,j=e.state.tr;for(let e=0;e<D.height;e++){let t=e*D.width+k;if(e&&D.map[t]==D.map[t-D.width])continue;let w=D.map[t],F=E.nodeAt(w).attrs,L=F.colspan==1?0:k-D.colCount(w);if(F.colwidth&&F.colwidth[L]==S)continue;let B=F.colwidth?F.colwidth.slice():zeroes(F.colspan);B[L]=S,j.setNodeMarkup(O+w,null,{...F,colwidth:B})}j.docChanged&&e.dispatch(j)}function displayColumnWidth(e,t,S,w){let E=e.state.doc.resolve(t),D=E.node(-1),O=E.start(-1),k=TableMap.get(D).colCount(E.pos-O)+E.nodeAfter.attrs.colspan-1,j=e.domAtPos(E.start(-1)).node;for(;j&&j.nodeName!=`TABLE`;)j=j.parentNode;j&&updateColumnsOnResize(D,j.firstChild,j,w,k,S)}function zeroes(e){return Array(e).fill(0)}function handleDecorations(e,t){let S=[],w=e.doc.resolve(t),E=w.node(-1);if(!E)return DecorationSet.empty;let D=TableMap.get(E),O=w.start(-1),k=D.colCount(w.pos-O)+w.nodeAfter.attrs.colspan-1;for(let t=0;t<D.height;t++){let w=k+t*D.width;if((k==D.width-1||D.map[w]!=D.map[w+1])&&(t==0||D.map[w]!=D.map[w-D.width])){var j;let t=D.map[w],k=O+t+E.nodeAt(t).nodeSize-1,F=document.createElement(`div`);F.className=`column-resize-handle`,columnResizingPluginKey.getState(e)?.dragging&&S.push(Decoration.node(O+t,O+t+E.nodeAt(t).nodeSize,{class:`column-resize-dragging`})),S.push(Decoration.widget(k,F))}}return DecorationSet.create(e.doc,S)}function tableEditing({allowTableNodeSelection:e=!1}={}){return new Plugin({key:tableEditingKey,state:{init(){return null},apply(e,t){let S=e.getMeta(tableEditingKey);if(S!=null)return S==-1?null:S;if(t==null||!e.docChanged)return t;let{deleted:w,pos:E}=e.mapping.mapResult(t);return w?null:E}},props:{decorations:drawCellSelection,handleDOMEvents:{mousedown:handleMouseDown$1},createSelectionBetween(e){return tableEditingKey.getState(e.state)==null?null:e.state.selection},handleTripleClick,handleKeyDown:handleKeyDown$1,handlePaste},appendTransaction(t,S,w){return normalizeSelection(w,fixTables(w,S),e)}})}function normalizeTableCellAlign(e){return e===`left`||e===`right`||e===`center`?e:null}function parseAlign(e){let t=(e.style.textAlign||``).trim().toLowerCase(),S=(e.getAttribute(`align`)||``).trim().toLowerCase();return normalizeTableCellAlign(t||S)}function normalizeTableCellAlignFromAttributes(e){return normalizeTableCellAlign(e?.align)}function createAlignAttribute(){return{default:null,parseHTML:e=>parseAlign(e),renderHTML:e=>e.align?{style:`text-align: ${e.align}`}:{}}}var TableCell=Node3.create({name:`tableCell`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{var t,S;let w=e.getAttribute(`colwidth`),E=w?w.split(`,`).map(e=>parseInt(e,10)):null;if(!E){let t=e.closest(`table`)?.querySelectorAll(`colgroup > col`),S=Array.from(e.parentElement?.children||[]).indexOf(e);if(S&&S>-1&&t&&t[S]){let e=t[S].getAttribute(`width`);return e?[parseInt(e,10)]:null}}return E}},align:createAlignAttribute()}},tableRole:`cell`,isolating:!0,parseHTML(){return[{tag:`td`}]},renderHTML({HTMLAttributes:e}){return[`td`,mergeAttributes(this.options.HTMLAttributes,e),0]}}),TableHeader=Node3.create({name:`tableHeader`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{let t=e.getAttribute(`colwidth`);return t?t.split(`,`).map(e=>parseInt(e,10)):null}},align:createAlignAttribute()}},tableRole:`header_cell`,isolating:!0,parseHTML(){return[{tag:`th`}]},renderHTML({HTMLAttributes:e}){return[`th`,mergeAttributes(this.options.HTMLAttributes,e),0]}}),TableRow=Node3.create({name:`tableRow`,addOptions(){return{HTMLAttributes:{}}},content:`(tableCell | tableHeader)*`,tableRole:`row`,parseHTML(){return[{tag:`tr`}]},renderHTML({HTMLAttributes:e}){return[`tr`,mergeAttributes(this.options.HTMLAttributes,e),0]}});function getColStyleDeclaration(e,t){return t?[`width`,`${Math.max(t,e)}px`]:[`min-width`,`${e}px`]}function updateColumns(e,t,S,w,E,D){var O;let k=0,j=!0,F=t.firstChild,L=e.firstChild;if(L!==null)for(let e=0,S=0;e<L.childCount;e+=1){let{colspan:O,colwidth:B}=L.child(e).attrs;for(let e=0;e<O;e+=1,S+=1){let O=E===S?D:B&&B[e],L=O?`${O}px`:``;if(k+=O||w,O||(j=!1),F){if(F.style.width!==L){let[e,t]=getColStyleDeclaration(w,O);F.style.setProperty(e,t)}F=F.nextSibling}else{let e=document.createElement(`col`),[S,E]=getColStyleDeclaration(w,O);e.style.setProperty(S,E),t.appendChild(e)}}}for(;F;){let e=F.nextSibling;(O=F.parentNode)==null||O.removeChild(F),F=e}let B=e.attrs.style&&typeof e.attrs.style==`string`&&/\bwidth\s*:/i.test(e.attrs.style);j&&!B?(S.style.width=`${k}px`,S.style.minWidth=``):(S.style.width=``,S.style.minWidth=`${k}px`)}var TableView=class{constructor(e,t){this.node=e,this.cellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),e.attrs.style&&(this.table.style.cssText=e.attrs.style),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),updateColumns(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type===this.node.type?(this.node=e,updateColumns(e,this.colgroup,this.table,this.cellMinWidth),!0):!1}ignoreMutation(e){let t=e.target,S=this.dom.contains(t),w=this.contentDOM.contains(t);return!!(S&&!w&&(e.type===`attributes`||e.type===`childList`||e.type===`characterData`))}};function createColGroup(e,t,S,w){let E=0,D=!0,O=[],k=e.firstChild;if(!k)return{};for(let e=0,j=0;e<k.childCount;e+=1){let{colspan:F,colwidth:L}=k.child(e).attrs;for(let e=0;e<F;e+=1,j+=1){let k=S===j?w:L&&L[e];E+=k||t,k||(D=!1);let[F,B]=getColStyleDeclaration(t,k);O.push([`col`,{style:`${F}: ${B}`}])}}let j=D?`${E}px`:``,F=D?``:`${E}px`;return{colgroup:[`colgroup`,{},...O],tableWidth:j,tableMinWidth:F}}function createCell(e,t){return t?e.createChecked(null,t):e.createAndFill()}function getTableNodeTypes(e){if(e.cached.tableNodeTypes)return e.cached.tableNodeTypes;let t={};return Object.keys(e.nodes).forEach(S=>{let w=e.nodes[S];w.spec.tableRole&&(t[w.spec.tableRole]=w)}),e.cached.tableNodeTypes=t,t}function createTable(e,t,S,w,E){let D=getTableNodeTypes(e),O=[],k=[];for(let e=0;e<S;e+=1){let e=createCell(D.cell,E);if(e&&k.push(e),w){let e=createCell(D.header_cell,E);e&&O.push(e)}}let j=[];for(let e=0;e<t;e+=1)j.push(D.row.createChecked(null,w&&e===0?O:k));return D.table.createChecked(null,j)}function isCellSelection(e){return e instanceof CellSelection}var deleteTableWhenAllCellsSelected=({editor:e})=>{let{selection:t}=e.state;if(!isCellSelection(t))return!1;let S=0;return findParentNodeClosestToPos(t.ranges[0].$from,e=>e.type.name===`table`)?.node.descendants(e=>{if(e.type.name===`table`)return!1;[`tableCell`,`tableHeader`].includes(e.type.name)&&(S+=1)}),S===t.ranges.length?(e.commands.deleteTable(),!0):!1},DEFAULT_CELL_LINE_SEPARATOR=``;function collapseWhitespace(e){return(e||``).replace(/\s+/g,` `).trim()}function renderTableToMarkdown(e,t,S={}){var w;let E=S.cellLineSeparator??``;if(!e||!e.content||e.content.length===0)return``;let D=[];e.content.forEach(e=>{let S=[];e.content&&e.content.forEach(e=>{let w=``;w=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>t.renderChildren(e)).join(E):e.content?t.renderChildren(e.content):``;let D=collapseWhitespace(w),O=e.type===`tableHeader`,k=normalizeTableCellAlignFromAttributes(e.attrs);S.push({text:D,isHeader:O,align:k})}),D.push(S)});let O=D.reduce((e,t)=>Math.max(e,t.length),0);if(O===0)return``;let k=Array(O).fill(0);D.forEach(e=>{var t;for(let t=0;t<O;t+=1){let S=(e[t]?.text||``).length;S>k[t]&&(k[t]=S),k[t]<3&&(k[t]=3)}});let j=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),F=D[0],L=F.some(e=>e.isHeader),B=Array(O).fill(null);D.forEach(e=>{var t;for(let t=0;t<O;t+=1)!B[t]&&e[t]?.align&&(B[t]=e[t].align)});let H=`
|
|
215
|
+
3. "-" cannot repeat`);Ns.customSchemes.push([e,t])}function Rs(){Ns.scanner=Xr(Ns.customSchemes);for(let e=0;e<Ns.tokenQueue.length;e++)Ns.tokenQueue[e][1]({scanner:Ns.scanner});Ns.parser=Ts(Ns.scanner.tokens);for(let e=0;e<Ns.pluginQueue.length;e++)Ns.pluginQueue[e][1]({scanner:Ns.scanner,parser:Ns.parser});return Ns.initialized=!0,Ns}function $s(e){return Ns.initialized||Rs(),Ds(Ns.parser.start,e,Zr(Ns.scanner.start,e))}$s.scan=Zr;function ec(e,t=null,S=null){if(t&&typeof t==`object`){if(S)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);S=t,t=null}let w=new Gi(S),E=$s(e),D=[];for(let e=0;e<E.length;e++){let S=E[e];S.isLink&&(!t||S.t===t)&&w.check(S)&&D.push(S.toFormattedObject(w))}return D}e.find=ec,e.registerCustomProtocol=Is,e.reset=Ps,e.tokenize=$s})),import_linkify=require_linkify(),UNICODE_WHITESPACE_PATTERN=`[\0- \xA0 -\u2029 ]`,UNICODE_WHITESPACE_REGEX=new RegExp(UNICODE_WHITESPACE_PATTERN),UNICODE_WHITESPACE_REGEX_END=RegExp(`${UNICODE_WHITESPACE_PATTERN}$`),UNICODE_WHITESPACE_REGEX_GLOBAL=new RegExp(UNICODE_WHITESPACE_PATTERN,`g`);function isValidLinkStructure(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function autolink$1(e){return new Plugin({key:new PluginKey(`autolink`),appendTransaction:(t,S,w)=>{let E=t.some(e=>e.docChanged)&&!S.doc.eq(w.doc),D=t.some(e=>e.getMeta(`preventAutolink`));if(!E||D)return;let{tr:O}=w;if(getChangedRanges(combineTransactionSteps(S.doc,[...t])).forEach(({newRange:t})=>{let S=findChildrenInRange(w.doc,t,e=>e.isTextblock),E,D;if(S.length>1)E=S[0],D=w.doc.textBetween(E.pos,E.pos+E.node.nodeSize,void 0,` `);else if(S.length){let e=w.doc.textBetween(t.from,t.to,` `,` `);if(!UNICODE_WHITESPACE_REGEX_END.test(e))return;E=S[0],D=w.doc.textBetween(E.pos,t.to,void 0,` `)}if(E&&D){let t=D.split(UNICODE_WHITESPACE_REGEX).filter(Boolean);if(t.length<=0)return!1;let S=t[t.length-1],k=E.pos+D.lastIndexOf(S);if(!S)return!1;let j=(0,import_linkify.tokenize)(S).map(t=>t.toObject(e.defaultProtocol));if(!isValidLinkStructure(j))return!1;j.filter(e=>e.isLink).map(e=>({...e,from:k+e.start+1,to:k+e.end+1})).filter(e=>w.schema.marks.code?!w.doc.rangeHasMark(e.from,e.to,w.schema.marks.code):!0).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{getMarksBetween(t.from,t.to,w.doc).some(t=>t.mark.type===e.type)||O.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),O.steps.length)return O}})}function clickHandler(e){return new Plugin({key:new PluginKey(`handleClickLink`),props:{handleClick:(t,S,w)=>{var E,D;if(w.button!==0||!t.editable)return!1;let O=null;if(w.target instanceof HTMLAnchorElement)O=w.target;else{let t=w.target;if(!t)return!1;let S=e.editor.view.dom;O=t.closest(`a`),O&&!S.contains(O)&&(O=null)}if(!O)return!1;let k=!1;if(e.enableClickSelection&&(k=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let S=getAttributes(t.state,e.type.name),w=O.href??S.href,E=O.target??S.target;w&&(window.open(w,E),k=!0)}return k}}})}function pasteHandler(e){return new Plugin({key:new PluginKey(`handlePasteLink`),props:{handlePaste:(t,S,w)=>{let{shouldAutoLink:E}=e,{state:D}=t,{selection:O}=D,{empty:k}=O;if(k)return!1;let j=``;w.content.forEach(e=>{j+=e.textContent});let F=(0,import_linkify.find)(j,{defaultProtocol:e.defaultProtocol}).find(e=>e.isLink&&e.value===j);return!j||!F||E!==void 0&&!E(F.value)?!1:e.editor.commands.setMark(e.type,{href:F.href})}}})}function isAllowedUri(e,t){let S=[`http`,`https`,`ftp`,`ftps`,`mailto`,`tel`,`callto`,`sms`,`cid`,`xmpp`];return t&&t.forEach(e=>{let t=typeof e==`string`?e:e.scheme;t&&S.push(t)}),!e||e.replace(UNICODE_WHITESPACE_REGEX_GLOBAL,``).match(RegExp(`^(?:(?:${S.join(`|`)}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,`i`))}var Link=Mark.create({name:`link`,priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(e=>{if(typeof e==`string`){(0,import_linkify.registerCustomProtocol)(e);return}(0,import_linkify.registerCustomProtocol)(e.scheme,e.optionalSlashes)})},onDestroy(){(0,import_linkify.reset)()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer nofollow`,class:null},isAllowedUri:(e,t)=>!!isAllowedUri(e,t.protocols),validate:e=>!!e,shouldAutoLink:e=>{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e),S=/^[a-z][a-z0-9+.-]*:/i.test(e);if(t||S&&!e.includes(`@`))return!0;let w=(e.includes(`@`)?e.split(`@`).pop():e).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(w)||!/\./.test(w))}}},addAttributes(){return{href:{default:null,parseHTML(e){return e.getAttribute(`href`)}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:`a[href]`,getAttrs:e=>{let t=e.getAttribute(`href`);return!t||!this.options.isAllowedUri(t,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:e}){return this.options.isAllowedUri(e.href,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?[`a`,mergeAttributes(this.options.HTMLAttributes,e),0]:[`a`,mergeAttributes(this.options.HTMLAttributes,{...e,href:``}),0]},markdownTokenName:`link`,parseMarkdown:(e,t)=>t.applyMark(`link`,t.parseInline(e.tokens||[]),{href:e.href,title:e.title||null}),renderMarkdown:(e,t)=>{var S,w,E,D;let O=e.attrs?.href??``,k=e.attrs?.title??``,j=t.renderChildren(e);return k?`[${j}](${O} "${k}")`:`[${j}](${O})`},addCommands(){return{setLink:e=>({chain:t})=>{let{href:S}=e;return this.options.isAllowedUri(S,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,e).setMeta(`preventAutolink`,!0).run():!1},toggleLink:e=>({chain:t})=>{let{href:S}=e||{};return S&&!this.options.isAllowedUri(S,{defaultValidate:e=>!!isAllowedUri(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:t().toggleMark(this.name,e,{extendEmptyMarkRange:!0}).setMeta(`preventAutolink`,!0).run()},unsetLink:()=>({chain:e})=>e().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta(`preventAutolink`,!0).run()}},addPasteRules(){return[markPasteRule({find:e=>{let t=[];if(e){let{protocols:S,defaultProtocol:w}=this.options,E=(0,import_linkify.find)(e).filter(e=>e.isLink&&this.options.isAllowedUri(e.value,{defaultValidate:e=>!!isAllowedUri(e,S),protocols:S,defaultProtocol:w}));E.length&&E.forEach(e=>{this.options.shouldAutoLink(e.value)&&t.push({text:e.value,data:{href:e.href},index:e.start})})}return t},type:this.type,getAttributes:e=>{var t;return{href:e.data?.href}}})]},addProseMirrorPlugins(){let e=[],{protocols:t,defaultProtocol:S}=this.options;return this.options.autolink&&e.push(autolink$1({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:e=>this.options.isAllowedUri(e,{defaultValidate:e=>!!isAllowedUri(e,t),protocols:t,defaultProtocol:S}),shouldAutoLink:this.options.shouldAutoLink})),e.push(clickHandler({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick===`whenNotEditable`?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&e.push(pasteHandler({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),e}}),index_default$5=Link,inputRegex$4=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,pasteRegex$2=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,Highlight=Mark.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||e.style.backgroundColor,renderHTML:e=>e.color?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){return[`mark`,mergeAttributes(this.options.HTMLAttributes,e),0]},renderMarkdown:(e,t)=>`==${t.renderChildren(e)}==`,parseMarkdown:(e,t)=>t.applyMark(`highlight`,t.parseInline(e.tokens||[])),markdownTokenizer:{name:`highlight`,level:`inline`,start:e=>e.indexOf(`==`),tokenize(e,t,S){let w=/^(==)([^=]+)(==)/.exec(e);if(w){let e=w[2].trim(),t=S.inlineTokens(e);return{type:`highlight`,raw:w[0],text:e,tokens:t}}}},addCommands(){return{setHighlight:e=>({commands:t})=>t.setMark(this.name,e),toggleHighlight:e=>({commands:t})=>t.toggleMark(this.name,e),unsetHighlight:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[markInputRule({find:inputRegex$4,type:this.type})]},addPasteRules(){return[markPasteRule({find:pasteRegex$2,type:this.type})]}}),index_default$4=Highlight;let readFromCache,addToCache;if(typeof WeakMap<`u`){let e=new WeakMap;readFromCache=t=>e.get(t),addToCache=(t,S)=>(e.set(t,S),S)}else{let e=[],t=10,S=0;readFromCache=t=>{for(let S=0;S<e.length;S+=2)if(e[S]==t)return e[S+1]},addToCache=(t,w)=>(S==10&&(S=0),e[S++]=t,e[S++]=w)}var TableMap=class{constructor(e,t,S,w){this.width=e,this.height=t,this.map=S,this.problems=w}findCell(e){for(let t=0;t<this.map.length;t++){let S=this.map[t];if(S!=e)continue;let w=t%this.width,E=t/this.width|0,D=w+1,O=E+1;for(let e=1;D<this.width&&this.map[t+e]==S;e++)D++;for(let e=1;O<this.height&&this.map[t+this.width*e]==S;e++)O++;return{left:w,top:E,right:D,bottom:O}}throw RangeError(`No cell with offset ${e} found`)}colCount(e){for(let t=0;t<this.map.length;t++)if(this.map[t]==e)return t%this.width;throw RangeError(`No cell with offset ${e} found`)}nextCell(e,t,S){let{left:w,right:E,top:D,bottom:O}=this.findCell(e);return t==`horiz`?(S<0?w==0:E==this.width)?null:this.map[D*this.width+(S<0?w-1:E)]:(S<0?D==0:O==this.height)?null:this.map[w+this.width*(S<0?D-1:O)]}rectBetween(e,t){let{left:S,right:w,top:E,bottom:D}=this.findCell(e),{left:O,right:k,top:j,bottom:F}=this.findCell(t);return{left:Math.min(S,O),top:Math.min(E,j),right:Math.max(w,k),bottom:Math.max(D,F)}}cellsInRect(e){let t=[],S={};for(let w=e.top;w<e.bottom;w++)for(let E=e.left;E<e.right;E++){let D=w*this.width+E,O=this.map[D];S[O]||(S[O]=!0,!(E==e.left&&E&&this.map[D-1]==O||w==e.top&&w&&this.map[D-this.width]==O)&&t.push(O))}return t}positionAt(e,t,S){for(let w=0,E=0;;w++){let D=E+S.child(w).nodeSize;if(w==e){let S=t+e*this.width,w=(e+1)*this.width;for(;S<w&&this.map[S]<E;)S++;return S==w?D-1:this.map[S]}E=D}}static get(e){return readFromCache(e)||addToCache(e,computeMap(e))}};function computeMap(e){if(e.type.spec.tableRole!=`table`)throw RangeError(`Not a table node: `+e.type.name);let t=findWidth(e),S=e.childCount,w=[],E=0,D=null,O=[];for(let e=0,E=t*S;e<E;e++)w[e]=0;for(let k=0,j=0;k<S;k++){let F=e.child(k);j++;for(let e=0;;e++){for(;E<w.length&&w[E]!=0;)E++;if(e==F.childCount)break;let L=F.child(e),{colspan:B,rowspan:H,colwidth:q}=L.attrs;for(let e=0;e<H;e++){if(e+k>=S){(D||=[]).push({type:`overlong_rowspan`,pos:j,n:H-e});break}let F=E+e*t;for(let e=0;e<B;e++){w[F+e]==0?w[F+e]=j:(D||=[]).push({type:`collision`,row:k,pos:j,n:B-e});let S=q&&q[e];if(S){let w=(F+e)%t*2,E=O[w];E==null||E!=S&&O[w+1]==1?(O[w]=S,O[w+1]=1):E==S&&O[w+1]++}}}E+=B,j+=L.nodeSize}let L=(k+1)*t,B=0;for(;E<L;)w[E++]==0&&B++;B&&(D||=[]).push({type:`missing`,row:k,n:B}),j++}(t===0||S===0)&&(D||=[]).push({type:`zero_sized`});let k=new TableMap(t,S,w,D),j=!1;for(let e=0;!j&&e<O.length;e+=2)O[e]!=null&&O[e+1]<S&&(j=!0);return j&&findBadColWidths(k,O,e),k}function findWidth(e){let t=-1,S=!1;for(let w=0;w<e.childCount;w++){let E=e.child(w),D=0;if(S)for(let t=0;t<w;t++){let S=e.child(t);for(let e=0;e<S.childCount;e++){let E=S.child(e);t+E.attrs.rowspan>w&&(D+=E.attrs.colspan)}}for(let e=0;e<E.childCount;e++){let t=E.child(e);D+=t.attrs.colspan,t.attrs.rowspan>1&&(S=!0)}t==-1?t=D:t!=D&&(t=Math.max(t,D))}return t}function findBadColWidths(e,t,S){e.problems||=[];let w={};for(let E=0;E<e.map.length;E++){let D=e.map[E];if(w[D])continue;w[D]=!0;let O=S.nodeAt(D);if(!O)throw RangeError(`No cell with offset ${D} found`);let k=null,j=O.attrs;for(let S=0;S<j.colspan;S++){let w=t[(E+S)%e.width*2];w!=null&&(!j.colwidth||j.colwidth[S]!=w)&&((k||=freshColWidth(j))[S]=w)}k&&e.problems.unshift({type:`colwidth mismatch`,pos:D,colwidth:k})}}function freshColWidth(e){if(e.colwidth)return e.colwidth.slice();let t=[];for(let S=0;S<e.colspan;S++)t.push(0);return t}function tableNodeTypes(e){let t=e.cached.tableNodeTypes;if(!t){t=e.cached.tableNodeTypes={};for(let S in e.nodes){let w=e.nodes[S],E=w.spec.tableRole;E&&(t[E]=w)}}return t}const tableEditingKey=new PluginKey(`selectingCells`);function cellAround(e){for(let t=e.depth-1;t>0;t--)if(e.node(t).type.spec.tableRole==`row`)return e.node(0).resolve(e.before(t+1));return null}function cellWrapping(e){for(let t=e.depth;t>0;t--){let S=e.node(t).type.spec.tableRole;if(S===`cell`||S===`header_cell`)return e.node(t)}return null}function isInTable(e){let t=e.selection.$head;for(let e=t.depth;e>0;e--)if(t.node(e).type.spec.tableRole==`row`)return!0;return!1}function selectionCell(e){let t=e.selection;if(`$anchorCell`in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if(`node`in t&&t.node&&t.node.type.spec.tableRole==`cell`)return t.$anchor;let S=cellAround(t.$head)||cellNear(t.$head);if(S)return S;throw RangeError(`No cell found around position ${t.head}`)}function cellNear(e){for(let t=e.nodeAfter,S=e.pos;t;t=t.firstChild,S++){let w=t.type.spec.tableRole;if(w==`cell`||w==`header_cell`)return e.doc.resolve(S)}for(let t=e.nodeBefore,S=e.pos;t;t=t.lastChild,S--){let w=t.type.spec.tableRole;if(w==`cell`||w==`header_cell`)return e.doc.resolve(S-t.nodeSize)}}function pointsAtCell(e){return e.parent.type.spec.tableRole==`row`&&!!e.nodeAfter}function moveCellForward(e){return e.node(0).resolve(e.pos+e.nodeAfter.nodeSize)}function inSameTable(e,t){return e.depth==t.depth&&e.pos>=t.start(-1)&&e.pos<=t.end(-1)}function nextCell(e,t,S){let w=e.node(-1),E=TableMap.get(w),D=e.start(-1),O=E.nextCell(e.pos-D,t,S);return O==null?null:e.node(0).resolve(D+O)}function removeColSpan(e,t,S=1){let w={...e,colspan:e.colspan-S};return w.colwidth&&(w.colwidth=w.colwidth.slice(),w.colwidth.splice(t,S),w.colwidth.some(e=>e>0)||(w.colwidth=null)),w}function addColSpan(e,t,S=1){let w={...e,colspan:e.colspan+S};if(w.colwidth){w.colwidth=w.colwidth.slice();for(let e=0;e<S;e++)w.colwidth.splice(t,0,0)}return w}function columnIsHeader(e,t,S){let w=tableNodeTypes(t.type.schema).header_cell;for(let E=0;E<e.height;E++)if(t.nodeAt(e.map[S+E*e.width]).type!=w)return!1;return!0}var CellSelection=class e extends Selection$1{constructor(e,t=e){let S=e.node(-1),w=TableMap.get(S),E=e.start(-1),D=w.rectBetween(e.pos-E,t.pos-E),O=e.node(0),k=w.cellsInRect(D).filter(e=>e!=t.pos-E);k.unshift(t.pos-E);let j=k.map(e=>{let t=S.nodeAt(e);if(!t)throw RangeError(`No cell with offset ${e} found`);let w=E+e+1;return new SelectionRange(O.resolve(w),O.resolve(w+t.content.size))});super(j[0].$from,j[0].$to,j),this.$anchorCell=e,this.$headCell=t}map(t,S){let w=t.resolve(S.map(this.$anchorCell.pos)),E=t.resolve(S.map(this.$headCell.pos));if(pointsAtCell(w)&&pointsAtCell(E)&&inSameTable(w,E)){let t=this.$anchorCell.node(-1)!=w.node(-1);return t&&this.isRowSelection()?e.rowSelection(w,E):t&&this.isColSelection()?e.colSelection(w,E):new e(w,E)}return TextSelection.between(w,E)}content(){let e=this.$anchorCell.node(-1),t=TableMap.get(e),S=this.$anchorCell.start(-1),w=t.rectBetween(this.$anchorCell.pos-S,this.$headCell.pos-S),E={},D=[];for(let S=w.top;S<w.bottom;S++){let O=[];for(let D=S*t.width+w.left,k=w.left;k<w.right;k++,D++){let S=t.map[D];if(E[S])continue;E[S]=!0;let k=t.findCell(S),j=e.nodeAt(S);if(!j)throw RangeError(`No cell with offset ${S} found`);let F=w.left-k.left,L=k.right-w.right;if(F>0||L>0){let e=j.attrs;if(F>0&&(e=removeColSpan(e,0,F)),L>0&&(e=removeColSpan(e,e.colspan-L,L)),k.left<w.left){if(j=j.type.createAndFill(e),!j)throw RangeError(`Could not create cell with attrs ${JSON.stringify(e)}`)}else j=j.type.create(e,j.content)}if(k.top<w.top||k.bottom>w.bottom){let e={...j.attrs,rowspan:Math.min(k.bottom,w.bottom)-Math.max(k.top,w.top)};j=k.top<w.top?j.type.createAndFill(e):j.type.create(e,j.content)}O.push(j)}D.push(e.child(S).copy(Fragment.from(O)))}let O=this.isColSelection()&&this.isRowSelection()?e:D;return new Slice(Fragment.from(O),1,1)}replace(e,t=Slice.empty){let S=e.steps.length,w=this.ranges;for(let E=0;E<w.length;E++){let{$from:D,$to:O}=w[E],k=e.mapping.slice(S);e.replace(k.map(D.pos),k.map(O.pos),E?Slice.empty:t)}let E=Selection$1.findFrom(e.doc.resolve(e.mapping.slice(S).map(this.to)),-1);E&&e.setSelection(E)}replaceWith(e,t){this.replace(e,new Slice(Fragment.from(t),0,0))}forEachCell(e){let t=this.$anchorCell.node(-1),S=TableMap.get(t),w=this.$anchorCell.start(-1),E=S.cellsInRect(S.rectBetween(this.$anchorCell.pos-w,this.$headCell.pos-w));for(let S=0;S<E.length;S++)e(t.nodeAt(E[S]),w+E[S])}isColSelection(){let e=this.$anchorCell.index(-1),t=this.$headCell.index(-1);if(Math.min(e,t)>0)return!1;let S=e+this.$anchorCell.nodeAfter.attrs.rowspan,w=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(S,w)==this.$headCell.node(-1).childCount}static colSelection(t,S=t){let w=t.node(-1),E=TableMap.get(w),D=t.start(-1),O=E.findCell(t.pos-D),k=E.findCell(S.pos-D),j=t.node(0);return O.top<=k.top?(O.top>0&&(t=j.resolve(D+E.map[O.left])),k.bottom<E.height&&(S=j.resolve(D+E.map[E.width*(E.height-1)+k.right-1]))):(k.top>0&&(S=j.resolve(D+E.map[k.left])),O.bottom<E.height&&(t=j.resolve(D+E.map[E.width*(E.height-1)+O.right-1]))),new e(t,S)}isRowSelection(){let e=this.$anchorCell.node(-1),t=TableMap.get(e),S=this.$anchorCell.start(-1),w=t.colCount(this.$anchorCell.pos-S),E=t.colCount(this.$headCell.pos-S);if(Math.min(w,E)>0)return!1;let D=w+this.$anchorCell.nodeAfter.attrs.colspan,O=E+this.$headCell.nodeAfter.attrs.colspan;return Math.max(D,O)==t.width}eq(t){return t instanceof e&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,S=t){let w=t.node(-1),E=TableMap.get(w),D=t.start(-1),O=E.findCell(t.pos-D),k=E.findCell(S.pos-D),j=t.node(0);return O.left<=k.left?(O.left>0&&(t=j.resolve(D+E.map[O.top*E.width])),k.right<E.width&&(S=j.resolve(D+E.map[E.width*(k.top+1)-1]))):(k.left>0&&(S=j.resolve(D+E.map[k.top*E.width])),O.right<E.width&&(t=j.resolve(D+E.map[E.width*(O.top+1)-1]))),new e(t,S)}toJSON(){return{type:`cell`,anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(t,S){return new e(t.resolve(S.anchor),t.resolve(S.head))}static create(t,S,w=S){return new e(t.resolve(S),t.resolve(w))}getBookmark(){return new CellBookmark(this.$anchorCell.pos,this.$headCell.pos)}};CellSelection.prototype.visible=!1,Selection$1.jsonID(`cell`,CellSelection);var CellBookmark=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){let t=e.resolve(this.anchor),S=e.resolve(this.head);return t.parent.type.spec.tableRole==`row`&&S.parent.type.spec.tableRole==`row`&&t.index()<t.parent.childCount&&S.index()<S.parent.childCount&&inSameTable(t,S)?new CellSelection(t,S):Selection$1.near(S,1)}};function drawCellSelection(e){if(!(e.selection instanceof CellSelection))return null;let t=[];return e.selection.forEachCell((e,S)=>{t.push(Decoration.node(S,S+e.nodeSize,{class:`selectedCell`}))}),DecorationSet.create(e.doc,t)}function isCellBoundarySelection({$from:e,$to:t}){if(e.pos==t.pos||e.pos<t.pos-6)return!1;let S=e.pos,w=t.pos,E=e.depth;for(;E>=0&&!(e.after(E+1)<e.end(E));E--,S++);for(let e=t.depth;e>=0&&!(t.before(e+1)>t.start(e));e--,w--);return S==w&&/row|table/.test(e.node(E).type.spec.tableRole)}function isTextSelectionAcrossCells({$from:e,$to:t}){let S,w;for(let t=e.depth;t>0;t--){let w=e.node(t);if(w.type.spec.tableRole===`cell`||w.type.spec.tableRole===`header_cell`){S=w;break}}for(let e=t.depth;e>0;e--){let S=t.node(e);if(S.type.spec.tableRole===`cell`||S.type.spec.tableRole===`header_cell`){w=S;break}}return S!==w&&t.parentOffset===0}function normalizeSelection(e,t,S){let w=(t||e).selection,E=(t||e).doc,D,O;if(w instanceof NodeSelection&&(O=w.node.type.spec.tableRole)){if(O==`cell`||O==`header_cell`)D=CellSelection.create(E,w.from);else if(O==`row`){let e=E.resolve(w.from+1);D=CellSelection.rowSelection(e,e)}else if(!S){let e=TableMap.get(w.node),t=w.from+1,S=t+e.map[e.width*e.height-1];D=CellSelection.create(E,t+1,S)}}else w instanceof TextSelection&&isCellBoundarySelection(w)?D=TextSelection.create(E,w.from):w instanceof TextSelection&&isTextSelectionAcrossCells(w)&&(D=TextSelection.create(E,w.$from.start(),w.$from.end()));return D&&(t||=e.tr).setSelection(D),t}const fixTablesKey=new PluginKey(`fix-tables`);function changedDescendants(e,t,S,w){let E=e.childCount,D=t.childCount;outer:for(let O=0,k=0;O<D;O++){let D=t.child(O);for(let t=k,w=Math.min(E,O+3);t<w;t++)if(e.child(t)==D){k=t+1,S+=D.nodeSize;continue outer}w(D,S),k<E&&e.child(k).sameMarkup(D)?changedDescendants(e.child(k),D,S+1,w):D.nodesBetween(0,D.content.size,w,S+1),S+=D.nodeSize}}function fixTables(e,t){let S,w=(t,w)=>{t.type.spec.tableRole==`table`&&(S=fixTable(e,t,w,S))};return t?t.doc!=e.doc&&changedDescendants(t.doc,e.doc,0,w):e.doc.descendants(w),S}function fixTable(e,t,S,w){let E=TableMap.get(t);if(!E.problems)return w;w||=e.tr;let D=[];for(let e=0;e<E.height;e++)D.push(0);for(let e=0;e<E.problems.length;e++){let O=E.problems[e];if(O.type==`collision`){let e=t.nodeAt(O.pos);if(!e)continue;let E=e.attrs;for(let e=0;e<E.rowspan;e++)D[O.row+e]+=O.n;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,removeColSpan(E,E.colspan-O.n,O.n))}else if(O.type==`missing`)D[O.row]+=O.n;else if(O.type==`overlong_rowspan`){let e=t.nodeAt(O.pos);if(!e)continue;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,{...e.attrs,rowspan:e.attrs.rowspan-O.n})}else if(O.type==`colwidth mismatch`){let e=t.nodeAt(O.pos);if(!e)continue;w.setNodeMarkup(w.mapping.map(S+1+O.pos),null,{...e.attrs,colwidth:O.colwidth})}else if(O.type==`zero_sized`){let e=w.mapping.map(S);w.delete(e,e+t.nodeSize)}}let O,k;for(let e=0;e<D.length;e++)D[e]&&(O??=e,k=e);for(let j=0,F=S+1;j<E.height;j++){let S=t.child(j),E=F+S.nodeSize,L=D[j];if(L>0){let t=`cell`;S.firstChild&&(t=S.firstChild.type.spec.tableRole);let D=[];for(let S=0;S<L;S++){let S=tableNodeTypes(e.schema)[t].createAndFill();S&&D.push(S)}let B=(j==0||O==j-1)&&k==j?F+1:E-1;w.insert(w.mapping.map(B),D)}F=E}return w.setMeta(fixTablesKey,{fixTables:!0})}function selectedRect(e){let t=e.selection,S=selectionCell(e),w=S.node(-1),E=S.start(-1),D=TableMap.get(w);return{...t instanceof CellSelection?D.rectBetween(t.$anchorCell.pos-E,t.$headCell.pos-E):D.findCell(S.pos-E),tableStart:E,map:D,table:w}}function addColumn(e,{map:t,tableStart:S,table:w},E){let D=E>0?-1:0;columnIsHeader(t,w,E+D)&&(D=E==0||E==t.width?null:0);for(let O=0;O<t.height;O++){let k=O*t.width+E;if(E>0&&E<t.width&&t.map[k-1]==t.map[k]){let D=t.map[k],j=w.nodeAt(D);e.setNodeMarkup(e.mapping.map(S+D),null,addColSpan(j.attrs,E-t.colCount(D))),O+=j.attrs.rowspan-1}else{let j=D==null?tableNodeTypes(w.type.schema).cell:w.nodeAt(t.map[k+D]).type,F=t.positionAt(O,E,w);e.insert(e.mapping.map(S+F),j.createAndFill())}}return e}function addColumnBefore(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addColumn(e.tr,S,S.left))}return!0}function addColumnAfter(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addColumn(e.tr,S,S.right))}return!0}function removeColumn(e,{map:t,table:S,tableStart:w},E){let D=e.mapping.maps.length;for(let O=0;O<t.height;){let k=O*t.width+E,j=t.map[k],F=S.nodeAt(j),L=F.attrs;if(E>0&&t.map[k-1]==j||E<t.width-1&&t.map[k+1]==j)e.setNodeMarkup(e.mapping.slice(D).map(w+j),null,removeColSpan(L,E-t.colCount(j)));else{let t=e.mapping.slice(D).map(w+j);e.delete(t,t+F.nodeSize)}O+=L.rowspan}}function deleteColumn(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e),w=e.tr;if(S.left==0&&S.right==S.map.width)return!1;for(let e=S.right-1;removeColumn(w,S,e),e!=S.left;e--){let e=S.tableStart?w.doc.nodeAt(S.tableStart-1):w.doc;if(!e)throw RangeError(`No table found`);S.table=e,S.map=TableMap.get(e)}t(w)}return!0}function rowIsHeader(e,t,S){var w;let E=tableNodeTypes(t.type.schema).header_cell;for(let w=0;w<e.width;w++)if(t.nodeAt(e.map[w+S*e.width])?.type!=E)return!1;return!0}function addRow(e,{map:t,tableStart:S,table:w},E){let D=S;for(let e=0;e<E;e++)D+=w.child(e).nodeSize;let O=[],k=E>0?-1:0;rowIsHeader(t,w,E+k)&&(k=E==0||E==t.height?null:0);for(let D=0,F=t.width*E;D<t.width;D++,F++)if(E>0&&E<t.height&&t.map[F]==t.map[F-t.width]){let E=t.map[F],O=w.nodeAt(E).attrs;e.setNodeMarkup(S+E,null,{...O,rowspan:O.rowspan+1}),D+=O.colspan-1}else{var j;let e=(k==null?tableNodeTypes(w.type.schema).cell:w.nodeAt(t.map[F+k*t.width])?.type)?.createAndFill();e&&O.push(e)}return e.insert(D,tableNodeTypes(w.type.schema).row.create(null,O)),e}function addRowBefore(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addRow(e.tr,S,S.top))}return!0}function addRowAfter(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e);t(addRow(e.tr,S,S.bottom))}return!0}function removeRow(e,{map:t,table:S,tableStart:w},E){let D=0;for(let e=0;e<E;e++)D+=S.child(e).nodeSize;let O=D+S.child(E).nodeSize,k=e.mapping.maps.length;e.delete(D+w,O+w);let j=new Set;for(let D=0,O=E*t.width;D<t.width;D++,O++){let F=t.map[O];if(!j.has(F)){if(j.add(F),E>0&&F==t.map[O-t.width]){let t=S.nodeAt(F).attrs;e.setNodeMarkup(e.mapping.slice(k).map(F+w),null,{...t,rowspan:t.rowspan-1}),D+=t.colspan-1}else if(E<t.height&&F==t.map[O+t.width]){let O=S.nodeAt(F),j=O.attrs,L=O.type.create({...j,rowspan:O.attrs.rowspan-1},O.content),B=t.positionAt(E+1,D,S);e.insert(e.mapping.slice(k).map(w+B),L),D+=j.colspan-1}}}}function deleteRow(e,t){if(!isInTable(e))return!1;if(t){let S=selectedRect(e),w=e.tr;if(S.top==0&&S.bottom==S.map.height)return!1;for(let e=S.bottom-1;removeRow(w,S,e),e!=S.top;e--){let e=S.tableStart?w.doc.nodeAt(S.tableStart-1):w.doc;if(!e)throw RangeError(`No table found`);S.table=e,S.map=TableMap.get(S.table)}t(w)}return!0}function isEmpty$3(e){let t=e.content;return t.childCount==1&&t.child(0).isTextblock&&t.child(0).childCount==0}function cellsOverlapRectangle({width:e,height:t,map:S},w){let E=w.top*e+w.left,D=E,O=(w.bottom-1)*e+w.left,k=E+(w.right-w.left-1);for(let t=w.top;t<w.bottom;t++){if(w.left>0&&S[D]==S[D-1]||w.right<e&&S[k]==S[k+1])return!0;D+=e,k+=e}for(let D=w.left;D<w.right;D++){if(w.top>0&&S[E]==S[E-e]||w.bottom<t&&S[O]==S[O+e])return!0;E++,O++}return!1}function mergeCells(e,t){let S=e.selection;if(!(S instanceof CellSelection)||S.$anchorCell.pos==S.$headCell.pos)return!1;let w=selectedRect(e),{map:E}=w;if(cellsOverlapRectangle(E,w))return!1;if(t){let S=e.tr,D={},O=Fragment.empty,k,j;for(let e=w.top;e<w.bottom;e++)for(let t=w.left;t<w.right;t++){let F=E.map[e*E.width+t],L=w.table.nodeAt(F);if(!(D[F]||!L))if(D[F]=!0,k==null)k=F,j=L;else{isEmpty$3(L)||(O=O.append(L.content));let e=S.mapping.map(F+w.tableStart);S.delete(e,e+L.nodeSize)}}if(k==null||j==null)return!0;if(S.setNodeMarkup(k+w.tableStart,null,{...addColSpan(j.attrs,j.attrs.colspan,w.right-w.left-j.attrs.colspan),rowspan:w.bottom-w.top}),O.size>0){let e=k+1+j.content.size,t=isEmpty$3(j)?k+1:e;S.replaceWith(t+w.tableStart,e+w.tableStart,O)}S.setSelection(new CellSelection(S.doc.resolve(k+w.tableStart))),t(S)}return!0}function splitCell(e,t){let S=tableNodeTypes(e.schema);return splitCellWithType(({node:e})=>S[e.type.spec.tableRole])(e,t)}function splitCellWithType(e){return(t,S)=>{let w=t.selection,E,D;if(w instanceof CellSelection){if(w.$anchorCell.pos!=w.$headCell.pos)return!1;E=w.$anchorCell.nodeAfter,D=w.$anchorCell.pos}else{var O;if(E=cellWrapping(w.$from),!E)return!1;D=cellAround(w.$from)?.pos}if(E==null||D==null||E.attrs.colspan==1&&E.attrs.rowspan==1)return!1;if(S){let O=E.attrs,k=[],j=O.colwidth;O.rowspan>1&&(O={...O,rowspan:1}),O.colspan>1&&(O={...O,colspan:1});let F=selectedRect(t),L=t.tr;for(let e=0;e<F.right-F.left;e++)k.push(j?{...O,colwidth:j&&j[e]?[j[e]]:null}:O);let B;for(let t=F.top;t<F.bottom;t++){let S=F.map.positionAt(t,F.left,F.table);t==F.top&&(S+=E.nodeSize);for(let w=F.left,D=0;w<F.right;w++,D++)w==F.left&&t==F.top||L.insert(B=L.mapping.map(S+F.tableStart,1),e({node:E,row:t,col:w}).createAndFill(k[D]))}L.setNodeMarkup(D,e({node:E,row:F.top,col:F.left}),k[0]),w instanceof CellSelection&&L.setSelection(new CellSelection(L.doc.resolve(w.$anchorCell.pos),B?L.doc.resolve(B):void 0)),S(L)}return!0}}function setCellAttr(e,t){return function(S,w){if(!isInTable(S))return!1;let E=selectionCell(S);if(E.nodeAfter.attrs[e]===t)return!1;if(w){let D=S.tr;S.selection instanceof CellSelection?S.selection.forEachCell((S,w)=>{S.attrs[e]!==t&&D.setNodeMarkup(w,null,{...S.attrs,[e]:t})}):D.setNodeMarkup(E.pos,null,{...E.nodeAfter.attrs,[e]:t}),w(D)}return!0}}function deprecated_toggleHeader(e){return function(t,S){if(!isInTable(t))return!1;if(S){let w=tableNodeTypes(t.schema),E=selectedRect(t),D=t.tr,O=E.map.cellsInRect(e==`column`?{left:E.left,top:0,right:E.right,bottom:E.map.height}:e==`row`?{left:0,top:E.top,right:E.map.width,bottom:E.bottom}:E),k=O.map(e=>E.table.nodeAt(e));for(let e=0;e<O.length;e++)k[e].type==w.header_cell&&D.setNodeMarkup(E.tableStart+O[e],w.cell,k[e].attrs);if(D.steps.length===0)for(let e=0;e<O.length;e++)D.setNodeMarkup(E.tableStart+O[e],w.header_cell,k[e].attrs);S(D)}return!0}}function isHeaderEnabledByType(e,t,S){let w=t.map.cellsInRect({left:0,top:0,right:e==`row`?t.map.width:1,bottom:e==`column`?t.map.height:1});for(let e=0;e<w.length;e++){let E=t.table.nodeAt(w[e]);if(E&&E.type!==S.header_cell)return!1}return!0}function toggleHeader(e,t){return t||={useDeprecatedLogic:!1},t.useDeprecatedLogic?deprecated_toggleHeader(e):function(t,S){if(!isInTable(t))return!1;if(S){let w=tableNodeTypes(t.schema),E=selectedRect(t),D=t.tr,O=isHeaderEnabledByType(`row`,E,w),k=isHeaderEnabledByType(`column`,E,w),j=(e===`column`?O:e===`row`&&k)?1:0,F=e==`column`?{left:0,top:j,right:1,bottom:E.map.height}:e==`row`?{left:j,top:0,right:E.map.width,bottom:1}:E,L=e==`column`?k?w.cell:w.header_cell:e==`row`?O?w.cell:w.header_cell:w.cell;E.map.cellsInRect(F).forEach(e=>{let t=e+E.tableStart,S=D.doc.nodeAt(t);S&&D.setNodeMarkup(t,L,S.attrs)}),S(D)}return!0}}const toggleHeaderRow=toggleHeader(`row`,{useDeprecatedLogic:!0}),toggleHeaderColumn=toggleHeader(`column`,{useDeprecatedLogic:!0}),toggleHeaderCell=toggleHeader(`cell`,{useDeprecatedLogic:!0});function findNextCell(e,t){if(t<0){let t=e.nodeBefore;if(t)return e.pos-t.nodeSize;for(let t=e.index(-1)-1,S=e.before();t>=0;t--){let w=e.node(-1).child(t),E=w.lastChild;if(E)return S-1-E.nodeSize;S-=w.nodeSize}}else{if(e.index()<e.parent.childCount-1)return e.pos+e.nodeAfter.nodeSize;let t=e.node(-1);for(let S=e.indexAfter(-1),w=e.after();S<t.childCount;S++){let e=t.child(S);if(e.childCount)return w+1;w+=e.nodeSize}}return null}function goToNextCell(e){return function(t,S){if(!isInTable(t))return!1;let w=findNextCell(selectionCell(t),e);if(w==null)return!1;if(S){let e=t.doc.resolve(w);S(t.tr.setSelection(TextSelection.between(e,moveCellForward(e))).scrollIntoView())}return!0}}function deleteTable(e,t){let S=e.selection.$anchor;for(let w=S.depth;w>0;w--)if(S.node(w).type.spec.tableRole==`table`)return t&&t(e.tr.delete(S.before(w),S.after(w)).scrollIntoView()),!0;return!1}function deleteCellSelection(e,t){let S=e.selection;if(!(S instanceof CellSelection))return!1;if(t){let w=e.tr,E=tableNodeTypes(e.schema).cell.createAndFill().content;S.forEachCell((e,t)=>{e.content.eq(E)||w.replace(w.mapping.map(t+1),w.mapping.map(t+e.nodeSize-1),new Slice(E,0,0))}),w.docChanged&&t(w)}return!0}function pastedCells(e){if(e.size===0)return null;let{content:t,openStart:S,openEnd:w}=e;for(;t.childCount==1&&(S>0&&w>0||t.child(0).type.spec.tableRole==`table`);)S--,w--,t=t.child(0).content;let E=t.child(0),D=E.type.spec.tableRole,O=E.type.schema,k=[];if(D==`row`)for(let e=0;e<t.childCount;e++){let E=t.child(e).content,D=e?0:Math.max(0,S-1),j=e<t.childCount-1?0:Math.max(0,w-1);(D||j)&&(E=fitSlice(tableNodeTypes(O).row,new Slice(E,D,j)).content),k.push(E)}else if(D==`cell`||D==`header_cell`)k.push(S||w?fitSlice(tableNodeTypes(O).row,new Slice(t,S,w)).content:t);else return null;return ensureRectangular(O,k)}function ensureRectangular(e,t){let S=[];for(let e=0;e<t.length;e++){let w=t[e];for(let t=w.childCount-1;t>=0;t--){let{rowspan:E,colspan:D}=w.child(t).attrs;for(let t=e;t<e+E;t++)S[t]=(S[t]||0)+D}}let w=0;for(let e=0;e<S.length;e++)w=Math.max(w,S[e]);for(let E=0;E<S.length;E++)if(E>=t.length&&t.push(Fragment.empty),S[E]<w){let D=tableNodeTypes(e).cell.createAndFill(),O=[];for(let e=S[E];e<w;e++)O.push(D);t[E]=t[E].append(Fragment.from(O))}return{height:t.length,width:w,rows:t}}function fitSlice(e,t){let S=e.createAndFill();return new Transform$3(S).replace(0,S.content.size,t).doc}function clipCells({width:e,height:t,rows:S},w,E){if(e!=w){let t=[],E=[];for(let e=0;e<S.length;e++){let D=S[e],O=[];for(let S=t[e]||0,E=0;S<w;E++){let k=D.child(E%D.childCount);S+k.attrs.colspan>w&&(k=k.type.createChecked(removeColSpan(k.attrs,k.attrs.colspan,S+k.attrs.colspan-w),k.content)),O.push(k),S+=k.attrs.colspan;for(let S=1;S<k.attrs.rowspan;S++)t[e+S]=(t[e+S]||0)+k.attrs.colspan}E.push(Fragment.from(O))}S=E,e=w}if(t!=E){let e=[];for(let w=0,D=0;w<E;w++,D++){let O=[],k=S[D%t];for(let e=0;e<k.childCount;e++){let t=k.child(e);w+t.attrs.rowspan>E&&(t=t.type.create({...t.attrs,rowspan:Math.max(1,E-t.attrs.rowspan)},t.content)),O.push(t)}e.push(Fragment.from(O))}S=e,t=E}return{width:e,height:t,rows:S}}function growTable(e,t,S,w,E,D,O){let k=e.doc.type.schema,j=tableNodeTypes(k),F,L;if(E>t.width)for(let D=0,k=0;D<t.height;D++){let B=S.child(D);k+=B.nodeSize;let H=[],q;q=B.lastChild==null||B.lastChild.type==j.cell?F||=j.cell.createAndFill():L||=j.header_cell.createAndFill();for(let e=t.width;e<E;e++)H.push(q);e.insert(e.mapping.slice(O).map(k-1+w),H)}if(D>t.height){let k=[];for(let e=0,w=(t.height-1)*t.width;e<Math.max(t.width,E);e++){let E=e>=t.width?!1:S.nodeAt(t.map[w+e]).type==j.header_cell;k.push(E?L||=j.header_cell.createAndFill():F||=j.cell.createAndFill())}let B=j.row.create(null,Fragment.from(k)),H=[];for(let e=t.height;e<D;e++)H.push(B);e.insert(e.mapping.slice(O).map(w+S.nodeSize-2),H)}return!!(F||L)}function isolateHorizontal(e,t,S,w,E,D,O,k){if(O==0||O==t.height)return!1;let j=!1;for(let F=E;F<D;F++){let E=O*t.width+F,D=t.map[E];if(t.map[E-t.width]==D){j=!0;let E=S.nodeAt(D),{top:L,left:B}=t.findCell(D);e.setNodeMarkup(e.mapping.slice(k).map(D+w),null,{...E.attrs,rowspan:O-L}),e.insert(e.mapping.slice(k).map(t.positionAt(O,B,S)),E.type.createAndFill({...E.attrs,rowspan:L+E.attrs.rowspan-O})),F+=E.attrs.colspan-1}}return j}function isolateVertical(e,t,S,w,E,D,O,k){if(O==0||O==t.width)return!1;let j=!1;for(let F=E;F<D;F++){let E=F*t.width+O,D=t.map[E];if(t.map[E-1]==D){j=!0;let E=S.nodeAt(D),L=t.colCount(D),B=e.mapping.slice(k).map(D+w);e.setNodeMarkup(B,null,removeColSpan(E.attrs,O-L,E.attrs.colspan-(O-L))),e.insert(B+E.nodeSize,E.type.createAndFill(removeColSpan(E.attrs,0,O-L))),F+=E.attrs.rowspan-1}}return j}function insertCells(e,t,S,w,E){let D=S?e.doc.nodeAt(S-1):e.doc;if(!D)throw Error(`No table found`);let O=TableMap.get(D),{top:k,left:j}=w,F=j+E.width,L=k+E.height,B=e.tr,H=0;function q(){if(D=S?B.doc.nodeAt(S-1):B.doc,!D)throw Error(`No table found`);O=TableMap.get(D),H=B.mapping.maps.length}growTable(B,O,D,S,F,L,H)&&q(),isolateHorizontal(B,O,D,S,j,F,k,H)&&q(),isolateHorizontal(B,O,D,S,j,F,L,H)&&q(),isolateVertical(B,O,D,S,k,L,j,H)&&q(),isolateVertical(B,O,D,S,k,L,F,H)&&q();for(let e=k;e<L;e++){let t=O.positionAt(e,j,D),w=O.positionAt(e,F,D);B.replace(B.mapping.slice(H).map(t+S),B.mapping.slice(H).map(w+S),new Slice(E.rows[e-k],0,0))}q(),B.setSelection(new CellSelection(B.doc.resolve(S+O.positionAt(k,j,D)),B.doc.resolve(S+O.positionAt(L-1,F-1,D)))),t(B)}const handleKeyDown$1=keydownHandler({ArrowLeft:arrow$1(`horiz`,-1),ArrowRight:arrow$1(`horiz`,1),ArrowUp:arrow$1(`vert`,-1),ArrowDown:arrow$1(`vert`,1),"Shift-ArrowLeft":shiftArrow(`horiz`,-1),"Shift-ArrowRight":shiftArrow(`horiz`,1),"Shift-ArrowUp":shiftArrow(`vert`,-1),"Shift-ArrowDown":shiftArrow(`vert`,1),Backspace:deleteCellSelection,"Mod-Backspace":deleteCellSelection,Delete:deleteCellSelection,"Mod-Delete":deleteCellSelection});function maybeSetSelection(e,t,S){return S.eq(e.selection)?!1:(t&&t(e.tr.setSelection(S).scrollIntoView()),!0)}function arrow$1(e,t){return(S,w,E)=>{if(!E)return!1;let D=S.selection;if(D instanceof CellSelection)return maybeSetSelection(S,w,Selection$1.near(D.$headCell,t));if(e!=`horiz`&&!D.empty)return!1;let O=atEndOfCell(E,e,t);if(O==null)return!1;if(e==`horiz`)return maybeSetSelection(S,w,Selection$1.near(S.doc.resolve(D.head+t),t));{let E=S.doc.resolve(O),D=nextCell(E,e,t),k;return k=D?Selection$1.near(D,1):t<0?Selection$1.near(S.doc.resolve(E.before(-1)),-1):Selection$1.near(S.doc.resolve(E.after(-1)),1),maybeSetSelection(S,w,k)}}}function shiftArrow(e,t){return(S,w,E)=>{if(!E)return!1;let D=S.selection,O;if(D instanceof CellSelection)O=D;else{let w=atEndOfCell(E,e,t);if(w==null)return!1;O=new CellSelection(S.doc.resolve(w))}let k=nextCell(O.$headCell,e,t);return k?maybeSetSelection(S,w,new CellSelection(O.$anchorCell,k)):!1}}function handleTripleClick(e,t){let S=e.state.doc,w=cellAround(S.resolve(t));return w?(e.dispatch(e.state.tr.setSelection(new CellSelection(w))),!0):!1}function handlePaste(e,t,S){if(!isInTable(e.state))return!1;let w=pastedCells(S),E=e.state.selection;if(E instanceof CellSelection){w||={width:1,height:1,rows:[Fragment.from(fitSlice(tableNodeTypes(e.state.schema).cell,S))]};let t=E.$anchorCell.node(-1),D=E.$anchorCell.start(-1),O=TableMap.get(t).rectBetween(E.$anchorCell.pos-D,E.$headCell.pos-D);return w=clipCells(w,O.right-O.left,O.bottom-O.top),insertCells(e.state,e.dispatch,D,O,w),!0}else if(w){let t=selectionCell(e.state),S=t.start(-1);return insertCells(e.state,e.dispatch,S,TableMap.get(t.node(-1)).findCell(t.pos-S),w),!0}else return!1}function handleMouseDown$1(e,t){var S;if(t.button!=0||t.ctrlKey||t.metaKey)return;let w=domInCell(e,t.target),E;if(t.shiftKey&&e.state.selection instanceof CellSelection)D(e.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&w&&(E=cellAround(e.state.selection.$anchor))!=null&&cellUnderMouse(e,t)?.pos!=E.pos)D(E,t),t.preventDefault();else if(!w)return;function D(t,S){let w=cellUnderMouse(e,S),E=tableEditingKey.getState(e.state)==null;if(!w||!inSameTable(t,w))if(E)w=t;else return;let D=new CellSelection(t,w);if(E||!e.state.selection.eq(D)){let S=e.state.tr.setSelection(D);E&&S.setMeta(tableEditingKey,t.pos),e.dispatch(S)}}function O(){e.root.removeEventListener(`mouseup`,O),e.root.removeEventListener(`dragstart`,O),e.root.removeEventListener(`mousemove`,k),tableEditingKey.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta(tableEditingKey,-1))}function k(S){let E=S,k=tableEditingKey.getState(e.state),j;if(k!=null)j=e.state.doc.resolve(k);else if(domInCell(e,E.target)!=w&&(j=cellUnderMouse(e,t),!j))return O();j&&D(j,E)}e.root.addEventListener(`mouseup`,O),e.root.addEventListener(`dragstart`,O),e.root.addEventListener(`mousemove`,k)}function atEndOfCell(e,t,S){if(!(e.state.selection instanceof TextSelection))return null;let{$head:w}=e.state.selection;for(let E=w.depth-1;E>=0;E--){let D=w.node(E);if((S<0?w.index(E):w.indexAfter(E))!=(S<0?0:D.childCount))return null;if(D.type.spec.tableRole==`cell`||D.type.spec.tableRole==`header_cell`){let D=w.before(E),O=t==`vert`?S>0?`down`:`up`:S>0?`right`:`left`;return e.endOfTextblock(O)?D:null}}return null}function domInCell(e,t){for(;t&&t!=e.dom;t=t.parentNode)if(t.nodeName==`TD`||t.nodeName==`TH`)return t;return null}function cellUnderMouse(e,t){let S=e.posAtCoords({left:t.clientX,top:t.clientY});if(!S)return null;let{inside:w,pos:E}=S;return w>=0&&cellAround(e.state.doc.resolve(w))||cellAround(e.state.doc.resolve(E))}var TableView$1=class{constructor(e,t){this.node=e,this.defaultCellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),this.table.style.setProperty(`--default-cell-min-width`,`${t}px`),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),updateColumnsOnResize(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type==this.node.type?(this.node=e,updateColumnsOnResize(e,this.colgroup,this.table,this.defaultCellMinWidth),!0):!1}ignoreMutation(e){return e.type==`attributes`&&(e.target==this.table||this.colgroup.contains(e.target))}};function updateColumnsOnResize(e,t,S,w,E,D){let O=0,k=!0,j=t.firstChild,F=e.firstChild;if(F){for(let e=0,S=0;e<F.childCount;e++){let{colspan:L,colwidth:B}=F.child(e).attrs;for(let e=0;e<L;e++,S++){let F=E==S?D:B&&B[e],L=F?F+`px`:``;if(O+=F||w,F||(k=!1),j)j.style.width!=L&&(j.style.width=L),j=j.nextSibling;else{let e=document.createElement(`col`);e.style.width=L,t.appendChild(e)}}}for(;j;){var L;let e=j.nextSibling;(L=j.parentNode)==null||L.removeChild(j),j=e}k?(S.style.width=O+`px`,S.style.minWidth=``):(S.style.width=``,S.style.minWidth=O+`px`)}}const columnResizingPluginKey=new PluginKey(`tableColumnResizing`);function columnResizing({handleWidth:e=5,cellMinWidth:t=25,defaultCellMinWidth:S=100,View:w=TableView$1,lastColumnResizable:E=!0}={}){let D=new Plugin({key:columnResizingPluginKey,state:{init(e,t){var E;let O=(E=D.spec)==null||(E=E.props)==null?void 0:E.nodeViews,k=tableNodeTypes(t.schema).table.name;return w&&O&&(O[k]=(e,t)=>new w(e,S,t)),new ResizeState(-1,!1)},apply(e,t){return t.apply(e)}},props:{attributes:e=>{let t=columnResizingPluginKey.getState(e);return t&&t.activeHandle>-1?{class:`resize-cursor`}:{}},handleDOMEvents:{mousemove:(t,S)=>{handleMouseMove(t,S,e,E)},mouseleave:e=>{handleMouseLeave(e)},mousedown:(e,w)=>{handleMouseDown(e,w,t,S)}},decorations:e=>{let t=columnResizingPluginKey.getState(e);if(t&&t.activeHandle>-1)return handleDecorations(e,t.activeHandle)},nodeViews:{}}});return D}var ResizeState=class e{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(t){let S=this,w=t.getMeta(columnResizingPluginKey);if(w&&w.setHandle!=null)return new e(w.setHandle,!1);if(w&&w.setDragging!==void 0)return new e(S.activeHandle,w.setDragging);if(S.activeHandle>-1&&t.docChanged){let w=t.mapping.map(S.activeHandle,-1);return pointsAtCell(t.doc.resolve(w))||(w=-1),new e(w,S.dragging)}return S}};function handleMouseMove(e,t,S,w){if(!e.editable)return;let E=columnResizingPluginKey.getState(e.state);if(E&&!E.dragging){let D=domCellAround(t.target),O=-1;if(D){let{left:w,right:E}=D.getBoundingClientRect();t.clientX-w<=S?O=edgeCell(e,t,`left`,S):E-t.clientX<=S&&(O=edgeCell(e,t,`right`,S))}if(O!=E.activeHandle){if(!w&&O!==-1){let t=e.state.doc.resolve(O),S=t.node(-1),w=TableMap.get(S),E=t.start(-1);if(w.colCount(t.pos-E)+t.nodeAfter.attrs.colspan-1==w.width-1)return}updateHandle(e,O)}}}function handleMouseLeave(e){if(!e.editable)return;let t=columnResizingPluginKey.getState(e.state);t&&t.activeHandle>-1&&!t.dragging&&updateHandle(e,-1)}function handleMouseDown(e,t,S,w){var E;if(!e.editable)return!1;let D=e.dom.ownerDocument.defaultView??window,O=columnResizingPluginKey.getState(e.state);if(!O||O.activeHandle==-1||O.dragging)return!1;let k=e.state.doc.nodeAt(O.activeHandle),j=currentColWidth(e,O.activeHandle,k.attrs);e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setDragging:{startX:t.clientX,startWidth:j}}));function F(t){D.removeEventListener(`mouseup`,F),D.removeEventListener(`mousemove`,L);let w=columnResizingPluginKey.getState(e.state);w?.dragging&&(updateColumnWidth(e,w.activeHandle,draggedWidth(w.dragging,t,S)),e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setDragging:null})))}function L(t){if(!t.which)return F(t);let E=columnResizingPluginKey.getState(e.state);if(E&&E.dragging){let D=draggedWidth(E.dragging,t,S);displayColumnWidth(e,E.activeHandle,D,w)}}return displayColumnWidth(e,O.activeHandle,j,w),D.addEventListener(`mouseup`,F),D.addEventListener(`mousemove`,L),t.preventDefault(),!0}function currentColWidth(e,t,{colspan:S,colwidth:w}){let E=w&&w[w.length-1];if(E)return E;let D=e.domAtPos(t),O=D.node.childNodes[D.offset].offsetWidth,k=S;if(w)for(let e=0;e<S;e++)w[e]&&(O-=w[e],k--);return O/k}function domCellAround(e){for(;e&&e.nodeName!=`TD`&&e.nodeName!=`TH`;)e=e.classList&&e.classList.contains(`ProseMirror`)?null:e.parentNode;return e}function edgeCell(e,t,S,w){let E=S==`right`?-w:w,D=e.posAtCoords({left:t.clientX+E,top:t.clientY});if(!D)return-1;let{pos:O}=D,k=cellAround(e.state.doc.resolve(O));if(!k)return-1;if(S==`right`)return k.pos;let j=TableMap.get(k.node(-1)),F=k.start(-1),L=j.map.indexOf(k.pos-F);return L%j.width==0?-1:F+j.map[L-1]}function draggedWidth(e,t,S){let w=t.clientX-e.startX;return Math.max(S,e.startWidth+w)}function updateHandle(e,t){e.dispatch(e.state.tr.setMeta(columnResizingPluginKey,{setHandle:t}))}function updateColumnWidth(e,t,S){let w=e.state.doc.resolve(t),E=w.node(-1),D=TableMap.get(E),O=w.start(-1),k=D.colCount(w.pos-O)+w.nodeAfter.attrs.colspan-1,j=e.state.tr;for(let e=0;e<D.height;e++){let t=e*D.width+k;if(e&&D.map[t]==D.map[t-D.width])continue;let w=D.map[t],F=E.nodeAt(w).attrs,L=F.colspan==1?0:k-D.colCount(w);if(F.colwidth&&F.colwidth[L]==S)continue;let B=F.colwidth?F.colwidth.slice():zeroes(F.colspan);B[L]=S,j.setNodeMarkup(O+w,null,{...F,colwidth:B})}j.docChanged&&e.dispatch(j)}function displayColumnWidth(e,t,S,w){let E=e.state.doc.resolve(t),D=E.node(-1),O=E.start(-1),k=TableMap.get(D).colCount(E.pos-O)+E.nodeAfter.attrs.colspan-1,j=e.domAtPos(E.start(-1)).node;for(;j&&j.nodeName!=`TABLE`;)j=j.parentNode;j&&updateColumnsOnResize(D,j.firstChild,j,w,k,S)}function zeroes(e){return Array(e).fill(0)}function handleDecorations(e,t){let S=[],w=e.doc.resolve(t),E=w.node(-1);if(!E)return DecorationSet.empty;let D=TableMap.get(E),O=w.start(-1),k=D.colCount(w.pos-O)+w.nodeAfter.attrs.colspan-1;for(let t=0;t<D.height;t++){let w=k+t*D.width;if((k==D.width-1||D.map[w]!=D.map[w+1])&&(t==0||D.map[w]!=D.map[w-D.width])){var j;let t=D.map[w],k=O+t+E.nodeAt(t).nodeSize-1,F=document.createElement(`div`);F.className=`column-resize-handle`,columnResizingPluginKey.getState(e)?.dragging&&S.push(Decoration.node(O+t,O+t+E.nodeAt(t).nodeSize,{class:`column-resize-dragging`})),S.push(Decoration.widget(k,F))}}return DecorationSet.create(e.doc,S)}function tableEditing({allowTableNodeSelection:e=!1}={}){return new Plugin({key:tableEditingKey,state:{init(){return null},apply(e,t){let S=e.getMeta(tableEditingKey);if(S!=null)return S==-1?null:S;if(t==null||!e.docChanged)return t;let{deleted:w,pos:E}=e.mapping.mapResult(t);return w?null:E}},props:{decorations:drawCellSelection,handleDOMEvents:{mousedown:handleMouseDown$1},createSelectionBetween(e){return tableEditingKey.getState(e.state)==null?null:e.state.selection},handleTripleClick,handleKeyDown:handleKeyDown$1,handlePaste},appendTransaction(t,S,w){return normalizeSelection(w,fixTables(w,S),e)}})}function normalizeTableCellAlign(e){return e===`left`||e===`right`||e===`center`?e:null}function parseAlign(e){let t=(e.style.textAlign||``).trim().toLowerCase(),S=(e.getAttribute(`align`)||``).trim().toLowerCase();return normalizeTableCellAlign(t||S)}function normalizeTableCellAlignFromAttributes(e){return normalizeTableCellAlign(e?.align)}function createAlignAttribute(){return{default:null,parseHTML:e=>parseAlign(e),renderHTML:e=>e.align?{style:`text-align: ${e.align}`}:{}}}var TableCell=Node3.create({name:`tableCell`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{var t,S;let w=e.getAttribute(`colwidth`),E=w?w.split(`,`).map(e=>parseInt(e,10)):null;if(!E){let t=e.closest(`table`)?.querySelectorAll(`colgroup > col`),S=Array.from(e.parentElement?.children||[]).indexOf(e);if(S&&S>-1&&t&&t[S]){let e=t[S].getAttribute(`width`);return e?[parseInt(e,10)]:null}}return E}},align:createAlignAttribute()}},tableRole:`cell`,isolating:!0,parseHTML(){return[{tag:`td`}]},renderHTML({HTMLAttributes:e}){return[`td`,mergeAttributes(this.options.HTMLAttributes,e),0]}}),TableHeader=Node3.create({name:`tableHeader`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{let t=e.getAttribute(`colwidth`);return t?t.split(`,`).map(e=>parseInt(e,10)):null}},align:createAlignAttribute()}},tableRole:`header_cell`,isolating:!0,parseHTML(){return[{tag:`th`}]},renderHTML({HTMLAttributes:e}){return[`th`,mergeAttributes(this.options.HTMLAttributes,e),0]}}),TableRow=Node3.create({name:`tableRow`,addOptions(){return{HTMLAttributes:{}}},content:`(tableCell | tableHeader)*`,tableRole:`row`,parseHTML(){return[{tag:`tr`}]},renderHTML({HTMLAttributes:e}){return[`tr`,mergeAttributes(this.options.HTMLAttributes,e),0]}});function getColStyleDeclaration(e,t){return t?[`width`,`${Math.max(t,e)}px`]:[`min-width`,`${e}px`]}function updateColumns(e,t,S,w,E,D){var O;let k=0,j=!0,F=t.firstChild,L=e.firstChild;if(L!==null)for(let e=0,S=0;e<L.childCount;e+=1){let{colspan:O,colwidth:B}=L.child(e).attrs;for(let e=0;e<O;e+=1,S+=1){let O=E===S?D:B&&B[e],L=O?`${O}px`:``;if(k+=O||w,O||(j=!1),F){if(F.style.width!==L){let[e,t]=getColStyleDeclaration(w,O);F.style.setProperty(e,t)}F=F.nextSibling}else{let e=document.createElement(`col`),[S,E]=getColStyleDeclaration(w,O);e.style.setProperty(S,E),t.appendChild(e)}}}for(;F;){let e=F.nextSibling;(O=F.parentNode)==null||O.removeChild(F),F=e}let B=e.attrs.style&&typeof e.attrs.style==`string`&&/\bwidth\s*:/i.test(e.attrs.style);j&&!B?(S.style.width=`${k}px`,S.style.minWidth=``):(S.style.width=``,S.style.minWidth=`${k}px`)}var TableView=class{constructor(e,t){this.node=e,this.cellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),e.attrs.style&&(this.table.style.cssText=e.attrs.style),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),updateColumns(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type===this.node.type?(this.node=e,updateColumns(e,this.colgroup,this.table,this.cellMinWidth),!0):!1}ignoreMutation(e){let t=e.target,S=this.dom.contains(t),w=this.contentDOM.contains(t);return!!(S&&!w&&(e.type===`attributes`||e.type===`childList`||e.type===`characterData`))}};function createColGroup(e,t,S,w){let E=0,D=!0,O=[],k=e.firstChild;if(!k)return{};for(let e=0,j=0;e<k.childCount;e+=1){let{colspan:F,colwidth:L}=k.child(e).attrs;for(let e=0;e<F;e+=1,j+=1){let k=S===j?w:L&&L[e];E+=k||t,k||(D=!1);let[F,B]=getColStyleDeclaration(t,k);O.push([`col`,{style:`${F}: ${B}`}])}}let j=D?`${E}px`:``,F=D?``:`${E}px`;return{colgroup:[`colgroup`,{},...O],tableWidth:j,tableMinWidth:F}}function createCell(e,t){return t?e.createChecked(null,t):e.createAndFill()}function getTableNodeTypes(e){if(e.cached.tableNodeTypes)return e.cached.tableNodeTypes;let t={};return Object.keys(e.nodes).forEach(S=>{let w=e.nodes[S];w.spec.tableRole&&(t[w.spec.tableRole]=w)}),e.cached.tableNodeTypes=t,t}function createTable(e,t,S,w,E){let D=getTableNodeTypes(e),O=[],k=[];for(let e=0;e<S;e+=1){let e=createCell(D.cell,E);if(e&&k.push(e),w){let e=createCell(D.header_cell,E);e&&O.push(e)}}let j=[];for(let e=0;e<t;e+=1)j.push(D.row.createChecked(null,w&&e===0?O:k));return D.table.createChecked(null,j)}function isCellSelection(e){return e instanceof CellSelection}var deleteTableWhenAllCellsSelected=({editor:e})=>{let{selection:t}=e.state;if(!isCellSelection(t))return!1;let S=0;return findParentNodeClosestToPos(t.ranges[0].$from,e=>e.type.name===`table`)?.node.descendants(e=>{if(e.type.name===`table`)return!1;[`tableCell`,`tableHeader`].includes(e.type.name)&&(S+=1)}),S===t.ranges.length?(e.commands.deleteTable(),!0):!1},DEFAULT_CELL_LINE_SEPARATOR=``;function collapseWhitespace(e){return(e||``).replace(/\s+/g,` `).trim()}function renderTableToMarkdown(e,t,S={}){var w;let E=S.cellLineSeparator??``;if(!e||!e.content||e.content.length===0)return``;let D=[];e.content.forEach(e=>{let S=[];e.content&&e.content.forEach(e=>{let w=``;w=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>t.renderChildren(e)).join(E):e.content?t.renderChildren(e.content):``;let D=collapseWhitespace(w),O=e.type===`tableHeader`,k=normalizeTableCellAlignFromAttributes(e.attrs);S.push({text:D,isHeader:O,align:k})}),D.push(S)});let O=D.reduce((e,t)=>Math.max(e,t.length),0);if(O===0)return``;let k=Array(O).fill(0);D.forEach(e=>{var t;for(let t=0;t<O;t+=1){let S=(e[t]?.text||``).length;S>k[t]&&(k[t]=S),k[t]<3&&(k[t]=3)}});let j=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),F=D[0],L=F.some(e=>e.isHeader),B=Array(O).fill(null);D.forEach(e=>{var t;for(let t=0;t<O;t+=1)!B[t]&&e[t]?.align&&(B[t]=e[t].align)});let H=`
|
|
216
216
|
`,q=Array(O).fill(0).map((e,t)=>L&&F[t]&&F[t].text||``);return H+=`| ${q.map((e,t)=>j(e,k[t])).join(` | `)} |
|
|
217
217
|
`,H+=`| ${k.map((e,t)=>{let S=Math.max(3,e),w=B[t];return w===`left`?`:${`-`.repeat(S)}`:w===`right`?`${`-`.repeat(S)}:`:w===`center`?`:${`-`.repeat(S)}:`:`-`.repeat(S)}).join(` | `)} |
|
|
218
218
|
`,(L?D.slice(1):D).forEach(e=>{H+=`| ${Array(O).fill(0).map((t,S)=>j(e[S]&&e[S].text||``,k[S])).join(` | `)} |
|
|
@@ -247,7 +247,7 @@ ${t.slice(F+2)}`,B+=1;else break}t.push({indent:F,number:parseInt(k,10),content:
|
|
|
247
247
|
`});return w(),t(),O+`
|
|
248
248
|
`+(E===1?`=`:`-`).repeat(O.length-(Math.max(O.lastIndexOf(`\r`),O.lastIndexOf(`
|
|
249
249
|
`))+1))}let O=`#`.repeat(E),k=S.enter(`headingAtx`),j=S.enter(`phrasing`);D.move(O+` `);let F=S.containerPhrasing(e,{before:`# `,after:`
|
|
250
|
-
`,...D.current()});return/^[\t ]/.test(F)&&(F=encodeCharacterReference(F.charCodeAt(0))+F.slice(1)),F=F?O+` `+F:O,S.options.closeAtx&&(F+=` `+O),j(),k(),F}html.peek=htmlPeek;function html(e){return e.value||``}function htmlPeek(){return`<`}image.peek=imagePeek;function image(e,t,S,w){let E=checkQuote(S),D=E===`"`?`Quote`:`Apostrophe`,O=S.enter(`image`),k=S.enter(`label`),j=S.createTracker(w),F=j.move(`![`);return F+=j.move(S.safe(e.alt,{before:F,after:`]`,...j.current()})),F+=j.move(`](`),k(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(k=S.enter(`destinationLiteral`),F+=j.move(`<`),F+=j.move(S.safe(e.url,{before:F,after:`>`,...j.current()})),F+=j.move(`>`)):(k=S.enter(`destinationRaw`),F+=j.move(S.safe(e.url,{before:F,after:e.title?` `:`)`,...j.current()}))),k(),e.title&&(k=S.enter(`title${D}`),F+=j.move(` `+E),F+=j.move(S.safe(e.title,{before:F,after:E,...j.current()})),F+=j.move(E),k()),F+=j.move(`)`),O(),F}function imagePeek(){return`!`}imageReference.peek=imageReferencePeek;function imageReference(e,t,S,w){let E=e.referenceType,D=S.enter(`imageReference`),O=S.enter(`label`),k=S.createTracker(w),j=k.move(`![`),F=S.safe(e.alt,{before:j,after:`]`,...k.current()});j+=k.move(F+`][`),O();let L=S.stack;S.stack=[],O=S.enter(`reference`);let B=S.safe(S.associationId(e),{before:j,after:`]`,...k.current()});return O(),S.stack=L,D(),E===`full`||!F||F!==B?j+=k.move(B+`]`):E===`shortcut`?j=j.slice(0,-1):j+=k.move(`]`),j}function imageReferencePeek(){return`!`}inlineCode.peek=inlineCodePeek;function inlineCode(e,t,S){let w=e.value||``,E="`",D=-1;for(;RegExp("(^|[^`])"+E+"([^`]|$)").test(w);)E+="`";for(/[^ \r\n]/.test(w)&&(/^[ \r\n]/.test(w)&&/[ \r\n]$/.test(w)||/^`|`$/.test(w))&&(w=` `+w+` `);++D<S.unsafe.length;){let e=S.unsafe[D],t=S.compilePattern(e),E;if(e.atBreak)for(;E=t.exec(w);){let e=E.index;w.charCodeAt(e)===10&&w.charCodeAt(e-1)===13&&e--,w=w.slice(0,e)+` `+w.slice(E.index+1)}}return E+w+E}function inlineCodePeek(){return"`"}function formatLinkAsAutolink(e,t){let S=toString(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type===`text`&&(S===e.url||`mailto:`+S===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}link.peek=linkPeek;function link(e,t,S,w){let E=checkQuote(S),D=E===`"`?`Quote`:`Apostrophe`,O=S.createTracker(w),k,j;if(formatLinkAsAutolink(e,S)){let t=S.stack;S.stack=[],k=S.enter(`autolink`);let w=O.move(`<`);return w+=O.move(S.containerPhrasing(e,{before:w,after:`>`,...O.current()})),w+=O.move(`>`),k(),S.stack=t,w}k=S.enter(`link`),j=S.enter(`label`);let F=O.move(`[`);return F+=O.move(S.containerPhrasing(e,{before:F,after:`](`,...O.current()})),F+=O.move(`](`),j(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(j=S.enter(`destinationLiteral`),F+=O.move(`<`),F+=O.move(S.safe(e.url,{before:F,after:`>`,...O.current()})),F+=O.move(`>`)):(j=S.enter(`destinationRaw`),F+=O.move(S.safe(e.url,{before:F,after:e.title?` `:`)`,...O.current()}))),j(),e.title&&(j=S.enter(`title${D}`),F+=O.move(` `+E),F+=O.move(S.safe(e.title,{before:F,after:E,...O.current()})),F+=O.move(E),j()),F+=O.move(`)`),k(),F}function linkPeek(e,t,S){return formatLinkAsAutolink(e,S)?`<`:`[`}linkReference.peek=linkReferencePeek;function linkReference(e,t,S,w){let E=e.referenceType,D=S.enter(`linkReference`),O=S.enter(`label`),k=S.createTracker(w),j=k.move(`[`),F=S.containerPhrasing(e,{before:j,after:`]`,...k.current()});j+=k.move(F+`][`),O();let L=S.stack;S.stack=[],O=S.enter(`reference`);let B=S.safe(S.associationId(e),{before:j,after:`]`,...k.current()});return O(),S.stack=L,D(),E===`full`||!F||F!==B?j+=k.move(B+`]`):E===`shortcut`?j=j.slice(0,-1):j+=k.move(`]`),j}function linkReferencePeek(){return`[`}function checkBullet(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function checkBulletOther(e){let t=checkBullet(e),S=e.options.bulletOther;if(!S)return t===`*`?`-`:`*`;if(S!==`*`&&S!==`+`&&S!==`-`)throw Error("Cannot serialize items with `"+S+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(S===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+S+"`) to be different");return S}function checkBulletOrdered(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function checkRule(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function list$1(e,t,S,w){let E=S.enter(`list`),D=S.bulletCurrent,O=e.ordered?checkBulletOrdered(S):checkBullet(S),k=e.ordered?O===`.`?`)`:`.`:checkBulletOther(S),j=t&&S.bulletLastUsed?O===S.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((O===`*`||O===`-`)&&t&&(!t.children||!t.children[0])&&S.stack[S.stack.length-1]===`list`&&S.stack[S.stack.length-2]===`listItem`&&S.stack[S.stack.length-3]===`list`&&S.stack[S.stack.length-4]===`listItem`&&S.indexStack[S.indexStack.length-1]===0&&S.indexStack[S.indexStack.length-2]===0&&S.indexStack[S.indexStack.length-3]===0&&(j=!0),checkRule(S)===O&&t){let t=-1;for(;++t<e.children.length;){let S=e.children[t];if(S&&S.type===`listItem`&&S.children&&S.children[0]&&S.children[0].type===`thematicBreak`){j=!0;break}}}}j&&(O=k),S.bulletCurrent=O;let F=S.containerFlow(e,w);return S.bulletLastUsed=O,S.bulletCurrent=D,E(),F}function checkListItemIndent(e){let t=e.options.listItemIndent||`one`;if(t!==`tab`&&t!==`one`&&t!==`mixed`)throw Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function listItem(e,t,S,w){let E=checkListItemIndent(S),D=S.bulletCurrent||checkBullet(S);t&&t.type===`list`&&t.ordered&&(D=(typeof t.start==`number`&&t.start>-1?t.start:1)+(S.options.incrementListMarker===!1?0:t.children.indexOf(e))+D);let O=D.length+1;(E===`tab`||E===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(O=Math.ceil(O/4)*4);let k=S.createTracker(w);k.move(D+` `.repeat(O-D.length)),k.shift(O);let j=S.enter(`listItem`),F=S.indentLines(S.containerFlow(e,k.current()),L);return j(),F;function L(e,t,S){return t?(S?``:` `.repeat(O))+e:(S?D:D+` `.repeat(O-D.length))+e}}function paragraph(e,t,S,w){let E=S.enter(`paragraph`),D=S.enter(`phrasing`),O=S.containerPhrasing(e,w);return D(),E(),O}function root(e,t,S,w){return(e.children.some(function(e){return phrasing(e)})?S.containerPhrasing:S.containerFlow).call(S,e,w)}function checkStrong(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}strong.peek=strongPeek;function strong(e,t,S,w){let E=checkStrong(S),D=S.enter(`strong`),O=S.createTracker(w),k=O.move(E+E),j=O.move(S.containerPhrasing(e,{after:E,before:k,...O.current()})),F=j.charCodeAt(0),L=encodeInfo(w.before.charCodeAt(w.before.length-1),F,E);L.inside&&(j=encodeCharacterReference(F)+j.slice(1));let B=j.charCodeAt(j.length-1),H=encodeInfo(w.after.charCodeAt(0),B,E);H.inside&&(j=j.slice(0,-1)+encodeCharacterReference(B));let q=O.move(E+E);return D(),S.attentionEncodeSurroundingInfo={after:H.outside,before:L.outside},k+j+q}function strongPeek(e,t,S){return S.options.strong||`*`}function text$3(e,t,S,w){return S.safe(e.value,w)}function checkRuleRepetition(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function thematicBreak$1(e,t,S){let w=(checkRule(S)+(S.options.ruleSpaces?` `:``)).repeat(checkRuleRepetition(S));return S.options.ruleSpaces?w.slice(0,-1):w}const handle$1={blockquote,break:hardBreak,code:code$1,definition:definition$1,emphasis,hardBreak,heading,html,image,imageReference,inlineCode,link,linkReference,list:list$1,listItem,paragraph,root,strong,text:text$3,thematicBreak:thematicBreak$1},join$
|
|
250
|
+
`,...D.current()});return/^[\t ]/.test(F)&&(F=encodeCharacterReference(F.charCodeAt(0))+F.slice(1)),F=F?O+` `+F:O,S.options.closeAtx&&(F+=` `+O),j(),k(),F}html.peek=htmlPeek;function html(e){return e.value||``}function htmlPeek(){return`<`}image.peek=imagePeek;function image(e,t,S,w){let E=checkQuote(S),D=E===`"`?`Quote`:`Apostrophe`,O=S.enter(`image`),k=S.enter(`label`),j=S.createTracker(w),F=j.move(`![`);return F+=j.move(S.safe(e.alt,{before:F,after:`]`,...j.current()})),F+=j.move(`](`),k(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(k=S.enter(`destinationLiteral`),F+=j.move(`<`),F+=j.move(S.safe(e.url,{before:F,after:`>`,...j.current()})),F+=j.move(`>`)):(k=S.enter(`destinationRaw`),F+=j.move(S.safe(e.url,{before:F,after:e.title?` `:`)`,...j.current()}))),k(),e.title&&(k=S.enter(`title${D}`),F+=j.move(` `+E),F+=j.move(S.safe(e.title,{before:F,after:E,...j.current()})),F+=j.move(E),k()),F+=j.move(`)`),O(),F}function imagePeek(){return`!`}imageReference.peek=imageReferencePeek;function imageReference(e,t,S,w){let E=e.referenceType,D=S.enter(`imageReference`),O=S.enter(`label`),k=S.createTracker(w),j=k.move(`![`),F=S.safe(e.alt,{before:j,after:`]`,...k.current()});j+=k.move(F+`][`),O();let L=S.stack;S.stack=[],O=S.enter(`reference`);let B=S.safe(S.associationId(e),{before:j,after:`]`,...k.current()});return O(),S.stack=L,D(),E===`full`||!F||F!==B?j+=k.move(B+`]`):E===`shortcut`?j=j.slice(0,-1):j+=k.move(`]`),j}function imageReferencePeek(){return`!`}inlineCode.peek=inlineCodePeek;function inlineCode(e,t,S){let w=e.value||``,E="`",D=-1;for(;RegExp("(^|[^`])"+E+"([^`]|$)").test(w);)E+="`";for(/[^ \r\n]/.test(w)&&(/^[ \r\n]/.test(w)&&/[ \r\n]$/.test(w)||/^`|`$/.test(w))&&(w=` `+w+` `);++D<S.unsafe.length;){let e=S.unsafe[D],t=S.compilePattern(e),E;if(e.atBreak)for(;E=t.exec(w);){let e=E.index;w.charCodeAt(e)===10&&w.charCodeAt(e-1)===13&&e--,w=w.slice(0,e)+` `+w.slice(E.index+1)}}return E+w+E}function inlineCodePeek(){return"`"}function formatLinkAsAutolink(e,t){let S=toString(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type===`text`&&(S===e.url||`mailto:`+S===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}link.peek=linkPeek;function link(e,t,S,w){let E=checkQuote(S),D=E===`"`?`Quote`:`Apostrophe`,O=S.createTracker(w),k,j;if(formatLinkAsAutolink(e,S)){let t=S.stack;S.stack=[],k=S.enter(`autolink`);let w=O.move(`<`);return w+=O.move(S.containerPhrasing(e,{before:w,after:`>`,...O.current()})),w+=O.move(`>`),k(),S.stack=t,w}k=S.enter(`link`),j=S.enter(`label`);let F=O.move(`[`);return F+=O.move(S.containerPhrasing(e,{before:F,after:`](`,...O.current()})),F+=O.move(`](`),j(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(j=S.enter(`destinationLiteral`),F+=O.move(`<`),F+=O.move(S.safe(e.url,{before:F,after:`>`,...O.current()})),F+=O.move(`>`)):(j=S.enter(`destinationRaw`),F+=O.move(S.safe(e.url,{before:F,after:e.title?` `:`)`,...O.current()}))),j(),e.title&&(j=S.enter(`title${D}`),F+=O.move(` `+E),F+=O.move(S.safe(e.title,{before:F,after:E,...O.current()})),F+=O.move(E),j()),F+=O.move(`)`),k(),F}function linkPeek(e,t,S){return formatLinkAsAutolink(e,S)?`<`:`[`}linkReference.peek=linkReferencePeek;function linkReference(e,t,S,w){let E=e.referenceType,D=S.enter(`linkReference`),O=S.enter(`label`),k=S.createTracker(w),j=k.move(`[`),F=S.containerPhrasing(e,{before:j,after:`]`,...k.current()});j+=k.move(F+`][`),O();let L=S.stack;S.stack=[],O=S.enter(`reference`);let B=S.safe(S.associationId(e),{before:j,after:`]`,...k.current()});return O(),S.stack=L,D(),E===`full`||!F||F!==B?j+=k.move(B+`]`):E===`shortcut`?j=j.slice(0,-1):j+=k.move(`]`),j}function linkReferencePeek(){return`[`}function checkBullet(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function checkBulletOther(e){let t=checkBullet(e),S=e.options.bulletOther;if(!S)return t===`*`?`-`:`*`;if(S!==`*`&&S!==`+`&&S!==`-`)throw Error("Cannot serialize items with `"+S+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(S===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+S+"`) to be different");return S}function checkBulletOrdered(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function checkRule(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function list$1(e,t,S,w){let E=S.enter(`list`),D=S.bulletCurrent,O=e.ordered?checkBulletOrdered(S):checkBullet(S),k=e.ordered?O===`.`?`)`:`.`:checkBulletOther(S),j=t&&S.bulletLastUsed?O===S.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((O===`*`||O===`-`)&&t&&(!t.children||!t.children[0])&&S.stack[S.stack.length-1]===`list`&&S.stack[S.stack.length-2]===`listItem`&&S.stack[S.stack.length-3]===`list`&&S.stack[S.stack.length-4]===`listItem`&&S.indexStack[S.indexStack.length-1]===0&&S.indexStack[S.indexStack.length-2]===0&&S.indexStack[S.indexStack.length-3]===0&&(j=!0),checkRule(S)===O&&t){let t=-1;for(;++t<e.children.length;){let S=e.children[t];if(S&&S.type===`listItem`&&S.children&&S.children[0]&&S.children[0].type===`thematicBreak`){j=!0;break}}}}j&&(O=k),S.bulletCurrent=O;let F=S.containerFlow(e,w);return S.bulletLastUsed=O,S.bulletCurrent=D,E(),F}function checkListItemIndent(e){let t=e.options.listItemIndent||`one`;if(t!==`tab`&&t!==`one`&&t!==`mixed`)throw Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function listItem(e,t,S,w){let E=checkListItemIndent(S),D=S.bulletCurrent||checkBullet(S);t&&t.type===`list`&&t.ordered&&(D=(typeof t.start==`number`&&t.start>-1?t.start:1)+(S.options.incrementListMarker===!1?0:t.children.indexOf(e))+D);let O=D.length+1;(E===`tab`||E===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(O=Math.ceil(O/4)*4);let k=S.createTracker(w);k.move(D+` `.repeat(O-D.length)),k.shift(O);let j=S.enter(`listItem`),F=S.indentLines(S.containerFlow(e,k.current()),L);return j(),F;function L(e,t,S){return t?(S?``:` `.repeat(O))+e:(S?D:D+` `.repeat(O-D.length))+e}}function paragraph(e,t,S,w){let E=S.enter(`paragraph`),D=S.enter(`phrasing`),O=S.containerPhrasing(e,w);return D(),E(),O}function root(e,t,S,w){return(e.children.some(function(e){return phrasing(e)})?S.containerPhrasing:S.containerFlow).call(S,e,w)}function checkStrong(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}strong.peek=strongPeek;function strong(e,t,S,w){let E=checkStrong(S),D=S.enter(`strong`),O=S.createTracker(w),k=O.move(E+E),j=O.move(S.containerPhrasing(e,{after:E,before:k,...O.current()})),F=j.charCodeAt(0),L=encodeInfo(w.before.charCodeAt(w.before.length-1),F,E);L.inside&&(j=encodeCharacterReference(F)+j.slice(1));let B=j.charCodeAt(j.length-1),H=encodeInfo(w.after.charCodeAt(0),B,E);H.inside&&(j=j.slice(0,-1)+encodeCharacterReference(B));let q=O.move(E+E);return D(),S.attentionEncodeSurroundingInfo={after:H.outside,before:L.outside},k+j+q}function strongPeek(e,t,S){return S.options.strong||`*`}function text$3(e,t,S,w){return S.safe(e.value,w)}function checkRuleRepetition(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function thematicBreak$1(e,t,S){let w=(checkRule(S)+(S.options.ruleSpaces?` `:``)).repeat(checkRuleRepetition(S));return S.options.ruleSpaces?w.slice(0,-1):w}const handle$1={blockquote,break:hardBreak,code:code$1,definition:definition$1,emphasis,hardBreak,heading,html,image,imageReference,inlineCode,link,linkReference,list:list$1,listItem,paragraph,root,strong,text:text$3,thematicBreak:thematicBreak$1},join$1=[joinDefaults];function joinDefaults(e,t,S,w){if(t.type===`code`&&formatCodeAsIndented(t,w)&&(e.type===`list`||e.type===t.type&&formatCodeAsIndented(e,w)))return!1;if(`spread`in S&&typeof S.spread==`boolean`)return e.type===`paragraph`&&(e.type===t.type||t.type===`definition`||t.type===`heading`&&formatHeadingAsSetext(t,w))?void 0:S.spread?1:0}const fullPhrasingSpans=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`],unsafe=[{character:` `,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,before:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`]},{character:`\r`,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`,`codeFencedMetaGraveAccent`,`codeFencedMetaTilde`,`destinationLiteral`,`headingAtx`]},{character:`
|
|
251
251
|
`,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`,`codeFencedMetaGraveAccent`,`codeFencedMetaTilde`,`destinationLiteral`,`headingAtx`]},{character:` `,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,before:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`]},{character:`!`,after:`\\[`,inConstruct:`phrasing`,notInConstruct:fullPhrasingSpans},{character:`"`,inConstruct:`titleQuote`},{atBreak:!0,character:`#`},{character:`#`,inConstruct:`headingAtx`,after:`(?:[\r
|
|
252
252
|
]|$)`},{character:`&`,after:`[#A-Za-z]`,inConstruct:`phrasing`},{character:`'`,inConstruct:`titleApostrophe`},{character:`(`,inConstruct:`destinationRaw`},{before:`\\]`,character:`(`,inConstruct:`phrasing`,notInConstruct:fullPhrasingSpans},{atBreak:!0,before:`\\d+`,character:`)`},{character:`)`,inConstruct:`destinationRaw`},{atBreak:!0,character:`*`,after:`(?:[ \r
|
|
253
253
|
*])`},{character:`*`,inConstruct:`phrasing`,notInConstruct:fullPhrasingSpans},{atBreak:!0,character:`+`,after:`(?:[ \r
|
|
@@ -264,7 +264,7 @@ ${t.slice(F+2)}`,B+=1;else break}t.push({indent:F,number:parseInt(k,10),content:
|
|
|
264
264
|
|
|
265
265
|
`}return`
|
|
266
266
|
|
|
267
|
-
`}const eol=/\r?\n|\r/g;function indentLines(e,t){let S=[],w=0,E=0,D;for(;D=eol.exec(e);)O(e.slice(w,D.index)),S.push(D[0]),w=D.index+D[0].length,E++;return O(e.slice(w)),S.join(``);function O(e){S.push(t(e,E,!e))}}function safe(e,t,S){let w=(S.before||``)+(t||``)+(S.after||``),E=[],D=[],O={},k=-1;for(;++k<e.unsafe.length;){let t=e.unsafe[k];if(!patternInScope(e.stack,t))continue;let S=e.compilePattern(t),D;for(;D=S.exec(w);){let e=`before`in t||!!t.atBreak,S=`after`in t,w=D.index+(e?D[1].length:0);E.includes(w)?(O[w].before&&!e&&(O[w].before=!1),O[w].after&&!S&&(O[w].after=!1)):(E.push(w),O[w]={before:e,after:S})}}E.sort(numerical);let j=S.before?S.before.length:0,F=w.length-(S.after?S.after.length:0);for(k=-1;++k<E.length;){let e=E[k];e<j||e>=F||e+1<F&&E[k+1]===e+1&&O[e].after&&!O[e+1].before&&!O[e+1].after||E[k-1]===e-1&&O[e].before&&!O[e-1].before&&!O[e-1].after||(j!==e&&D.push(escapeBackslashes(w.slice(j,e),`\\`)),j=e,/[!-/:-@[-`{-~]/.test(w.charAt(e))&&(!S.encode||!S.encode.includes(w.charAt(e)))?D.push(`\\`):(D.push(encodeCharacterReference(w.charCodeAt(e))),j++))}return D.push(escapeBackslashes(w.slice(j,F),S.after)),D.join(``)}function numerical(e,t){return e-t}function escapeBackslashes(e,t){let S=/\\(?=[!-/:-@[-`{-~])/g,w=[],E=[],D=e+t,O=-1,k=0,j;for(;j=S.exec(D);)w.push(j.index);for(;++O<w.length;)k!==w[O]&&E.push(e.slice(k,w[O])),E.push(`\\`),k=w[O];return E.push(e.slice(k)),E.join(``)}function track(e){let t=e||{},S=t.now||{},w=t.lineShift||0,E=S.line||1,D=S.column||1;return{move:j,current:O,shift:k};function O(){return{now:{line:E,column:D},lineShift:w}}function k(e){w+=e}function j(e){let t=e||``,S=t.split(/\r?\n|\r/g),O=S[S.length-1];return E+=S.length-1,D=S.length===1?D+O.length:1+O.length+w,t}}function toMarkdown(e,t){let S=t||{},w={associationId:association,containerPhrasing:containerPhrasingBound,containerFlow:containerFlowBound,createTracker:track,compilePattern,enter:D,handlers:{...handle$1},handle:void 0,indentLines,indexStack:[],join:[...join$
|
|
267
|
+
`}const eol=/\r?\n|\r/g;function indentLines(e,t){let S=[],w=0,E=0,D;for(;D=eol.exec(e);)O(e.slice(w,D.index)),S.push(D[0]),w=D.index+D[0].length,E++;return O(e.slice(w)),S.join(``);function O(e){S.push(t(e,E,!e))}}function safe(e,t,S){let w=(S.before||``)+(t||``)+(S.after||``),E=[],D=[],O={},k=-1;for(;++k<e.unsafe.length;){let t=e.unsafe[k];if(!patternInScope(e.stack,t))continue;let S=e.compilePattern(t),D;for(;D=S.exec(w);){let e=`before`in t||!!t.atBreak,S=`after`in t,w=D.index+(e?D[1].length:0);E.includes(w)?(O[w].before&&!e&&(O[w].before=!1),O[w].after&&!S&&(O[w].after=!1)):(E.push(w),O[w]={before:e,after:S})}}E.sort(numerical);let j=S.before?S.before.length:0,F=w.length-(S.after?S.after.length:0);for(k=-1;++k<E.length;){let e=E[k];e<j||e>=F||e+1<F&&E[k+1]===e+1&&O[e].after&&!O[e+1].before&&!O[e+1].after||E[k-1]===e-1&&O[e].before&&!O[e-1].before&&!O[e-1].after||(j!==e&&D.push(escapeBackslashes(w.slice(j,e),`\\`)),j=e,/[!-/:-@[-`{-~]/.test(w.charAt(e))&&(!S.encode||!S.encode.includes(w.charAt(e)))?D.push(`\\`):(D.push(encodeCharacterReference(w.charCodeAt(e))),j++))}return D.push(escapeBackslashes(w.slice(j,F),S.after)),D.join(``)}function numerical(e,t){return e-t}function escapeBackslashes(e,t){let S=/\\(?=[!-/:-@[-`{-~])/g,w=[],E=[],D=e+t,O=-1,k=0,j;for(;j=S.exec(D);)w.push(j.index);for(;++O<w.length;)k!==w[O]&&E.push(e.slice(k,w[O])),E.push(`\\`),k=w[O];return E.push(e.slice(k)),E.join(``)}function track(e){let t=e||{},S=t.now||{},w=t.lineShift||0,E=S.line||1,D=S.column||1;return{move:j,current:O,shift:k};function O(){return{now:{line:E,column:D},lineShift:w}}function k(e){w+=e}function j(e){let t=e||``,S=t.split(/\r?\n|\r/g),O=S[S.length-1];return E+=S.length-1,D=S.length===1?D+O.length:1+O.length+w,t}}function toMarkdown(e,t){let S=t||{},w={associationId:association,containerPhrasing:containerPhrasingBound,containerFlow:containerFlowBound,createTracker:track,compilePattern,enter:D,handlers:{...handle$1},handle:void 0,indentLines,indexStack:[],join:[...join$1],options:{},safe:safeBound,stack:[],unsafe:[...unsafe]};configure$1(w,S),w.options.tightDefinitions&&w.join.push(joinDefinition),w.handle=zwitch(`type`,{invalid:invalid$1,unknown:unknown$1,handlers:w.handlers});let E=w.handle(e,void 0,w,{before:`
|
|
268
268
|
`,after:`
|
|
269
269
|
`,now:{line:1,column:1},lineShift:0});return E&&E.charCodeAt(E.length-1)!==10&&E.charCodeAt(E.length-1)!==13&&(E+=`
|
|
270
270
|
`),E;function D(e){return w.stack.push(e),t;function t(){w.stack.pop()}}}function invalid$1(e){throw Error("Cannot handle value `"+e+"`, expected node")}function unknown$1(e){throw Error("Cannot handle unknown node `"+e.type+"`")}function joinDefinition(e,t){if(e.type===`definition`&&e.type===t.type)return 0}function containerPhrasingBound(e,t){return containerPhrasing(e,this,t)}function containerFlowBound(e,t){return containerFlow$1(e,this,t)}function safeBound(e,t){return safe(this,e,t)}function gfmTableFromMarkdown(){return{enter:{table:enterTable,tableData:enterCell,tableHeader:enterCell,tableRow:enterRow},exit:{codeText:exitCodeText,table:exitTable,tableData:exit$1,tableHeader:exit$1,tableRow:exit$1}}}function enterTable(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function exitTable(e){this.exit(e),this.data.inTable=void 0}function enterRow(e){this.enter({type:`tableRow`,children:[]},e)}function exit$1(e){this.exit(e)}function enterCell(e){this.enter({type:`tableCell`,children:[]},e)}function exitCodeText(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,replace));let S=this.stack[this.stack.length-1];S.type,S.value=t,this.exit(e)}function replace(e,t){return t===`|`?t:e}function gfmTableToMarkdown(e){let t=e||{},S=t.tableCellPadding,w=t.tablePipeAlign,E=t.stringLength,D=S?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:`
|
|
@@ -428,11 +428,7 @@ $2`).split(`
|
|
|
428
428
|
`)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),LifecycleStatusSchema=object$1({status:string$2().min(1),reason:string$2()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2(),lifecycle:LifecycleStatusSchema.nullable()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`,`audio`,`pdf`,`text`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({writers:array(SaveVersionWriterSchema).optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1)}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),DuplicatePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),DuplicatePathSuccessSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),duplicatedDocNames:array(string$2().min(1))}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1),icon:string$2().min(1).max(2048).optional()}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncRemoteSchema=object$1({label:string$2().min(1),webUrl:url().nullable()}).loose(),PushPermissionSchema=discriminatedUnion(`checkStatus`,[object$1({checkStatus:literal(`allowed`)}).loose(),object$1({checkStatus:literal(`denied`),deniedReason:_enum([`no-collaborator`,`private-no-access`,`repo-not-found`])}).loose(),object$1({checkStatus:literal(`unknown`),unknownError:_enum([`network`,`timeout`,`rate-limit`,`token-invalid`,`malformed-response`]).optional()}).loose()]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),remote:SyncRemoteSchema.nullable().optional(),error:string$2().optional(),errorCode:_enum([`auth-403`,`auth-401`,`auth-scope-mismatch`,`semantic-protected-branch`]).optional(),pausedReason:string$2().optional(),pushPermission:PushPermissionSchema.optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`,`delete`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0&&e.content!==``,{message:`content must be a non-empty string when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2(),kind:_enum([`both-modified`,`delete-modify`,`modify-delete`]),lifecycleStatus:string$2().nullable()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable(),frontmatter_sources:record(string$2(),string$2()).optional(),schema_declarations:record(string$2(),unknown$2()).optional(),schema_sources:record(string$2(),string$2()).optional(),schema_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional(),declarations:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema$1=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema$1,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema$1.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`,`cli-start`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]||(e.startsWith(`local-agent-mode-`)?`claude`:`bot`):`bot`}const BRAND_NAME={claude:`Claude`,cursor:`Cursor`,windsurf:`Windsurf`,openai:`Codex`,github:`Copilot`,cline:`Cline`};function displayNameFromClientName(e){let t=e?.trim();return t?BRAND_NAME[iconFromClientName(t)]??t:`Agent`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{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),w=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 w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${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 w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.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 w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}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 w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. 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(`
|
|
429
429
|
`)){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(`
|
|
430
430
|
`)){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 w=S,E=w.kind,D=w.metadata;if(typeof D!=`object`||!D)return null;let O=typeof w.docName==`string`?w.docName:null,k=typeof w.size==`number`&&Number.isFinite(w.size)?w.size:null;if(E===`bridge-merge-loss`){let e=D;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:O,size:k,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(E===`external-change-rescue`){let e=D;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:O,size:k,metadata:{incomingDiskSha:e.incomingDiskSha}}: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,...w}=e,E={...w};return t&&t.length>0&&(E.summaries=t),S&&S.length>0&&(E.previous_paths=S),`${OK_ACTOR_PREFIX}${JSON.stringify(E)}`}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,w;if(typeof e.writer_id==`string`&&e.writer_id.length>0)w=e.writer_id;else if(S)w=`agent-${S}`;else if(t)w=t;else switch(e.display_name){case`File System`:w=`file-system`;break;case`Git (upstream)`:w=`git-upstream`;break;default:w=`openknowledge-service`}let E=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,D=parsePreviousPaths(e);return{v:1,writer_id:w,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`),...E&&E.length>0?{summaries:E}:{},...D&&D.length>0?{previous_paths:D}:{}}}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 parseOkActors(e){if(!e)return[];let t=[];for(let S of e.split(`
|
|
431
|
-
`)){let e=S.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let w;try{w=JSON.parse(e.slice(10))}catch{continue}if(typeof w!=`object`||!w)continue;let E=parseOkActorObject(w);E&&t.push(E)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let S=stripLineBreaks(e);if(t.length===0)return S;if(t.length>=2)return`${S} (${t.length} edits)`;let[w]=t;if(w===void 0)return S;let E=stripLineBreaks(w),D=`${S} — ${E}`;if(D.length<=72)return D;let O=`${S} — `,k=72-O.length-1;return k<=0?D.slice(0,72):`${O}${E.slice(0,k)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_err_helpers=__commonJSMin$1(((e,t)=>{let S=e=>e&&typeof e.message==`string`,w=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return S(t)?t:void 0}else return S(t)?t:void 0},E=(e,t)=>{if(!S(e))return``;let D=e.stack||``;if(t.has(e))return D+`
|
|
432
|
-
causes have become circular...`;let O=w(e);return O?(t.add(e),D+`
|
|
433
|
-
caused by: `+E(O,t)):D},D=e=>E(e,new Set),O=(e,t,E)=>{if(!S(e))return``;let D=E?``:e.message||``;if(t.has(e))return D+`: ...`;let k=w(e);if(k){t.add(e);let S=typeof e.cause==`function`;return D+(S?``:`: `)+O(k,t,S)}else return D};t.exports={isErrorLike:S,getErrorCause:w,stackWithCauses:D,messageWithCauses:e=>O(e,new Set)}})),require_err_proto=__commonJSMin$1(((e,t)=>{let S=Symbol(`circular-ref-tag`),w=Symbol(`pino-raw-err-ref`),E=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[w]},set:function(e){this[w]=e}}});Object.defineProperty(E,w,{writable:!0,value:{}}),t.exports={pinoErrProto:E,pinoErrorSymbols:{seen:S,rawSymbol:w}}})),require_err=__commonJSMin$1(((e,t)=>{t.exports=F;let{messageWithCauses:S,stackWithCauses:w,isErrorLike:E}=require_err_helpers(),{pinoErrProto:D,pinoErrorSymbols:O}=require_err_proto(),{seen:k}=O,{toString:j}=Object.prototype;function F(e){if(!E(e))return e;e[k]=void 0;let t=Object.create(D);t.type=j.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=S(e),t.stack=w(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>F(e)));for(let S in e)if(t[S]===void 0){let w=e[S];E(w)?S!==`cause`&&!Object.prototype.hasOwnProperty.call(w,k)&&(t[S]=F(w)):t[S]=w}return delete e[k],t.raw=e,t}})),require_err_with_cause=__commonJSMin$1(((e,t)=>{t.exports=k;let{isErrorLike:S}=require_err_helpers(),{pinoErrProto:w,pinoErrorSymbols:E}=require_err_proto(),{seen:D}=E,{toString:O}=Object.prototype;function k(e){if(!S(e))return e;e[D]=void 0;let t=Object.create(w);t.type=O.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>k(e))),S(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,D)&&(t.cause=k(e.cause));for(let w in e)if(t[w]===void 0){let E=e[w];S(E)?Object.prototype.hasOwnProperty.call(E,D)||(t[w]=k(E)):t[w]=E}return delete e[D],t.raw=e,t}})),require_req=__commonJSMin$1(((e,t)=>{t.exports={mapHttpRequest:D,reqSerializer:E};let S=Symbol(`pino-raw-req-ref`),w=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[S]},set:function(e){this[S]=e}}});Object.defineProperty(w,S,{writable:!0,value:{}});function E(e){let t=e.info||e.socket,S=Object.create(w);if(S.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),S.method=e.method,e.originalUrl)S.url=e.originalUrl;else{let t=e.path;S.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(S.query=e.query),e.params&&(S.params=e.params),S.headers=e.headers,S.remoteAddress=t&&t.remoteAddress,S.remotePort=t&&t.remotePort,S.raw=e.raw||e,S}function D(e){return{req:E(e)}}})),require_res=__commonJSMin$1(((e,t)=>{t.exports={mapHttpResponse:D,resSerializer:E};let S=Symbol(`pino-raw-res-ref`),w=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[S]},set:function(e){this[S]=e}}});Object.defineProperty(w,S,{writable:!0,value:{}});function E(e){let t=Object.create(w);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function D(e){return{res:E(e)}}})),require_pino_std_serializers=__commonJSMin$1(((e,t)=>{let S=require_err(),w=require_err_with_cause(),E=require_req(),D=require_res();t.exports={err:S,errWithCause:w,mapHttpRequest:E.mapHttpRequest,mapHttpResponse:D.mapHttpResponse,req:E.reqSerializer,res:D.resSerializer,wrapErrorSerializer:function(e){return e===S?e:function(t){return e(S(t))}},wrapRequestSerializer:function(e){return e===E.reqSerializer?e:function(t){return e(E.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===D.resSerializer?e:function(t){return e(D.resSerializer(t))}}}})),require_caller=__commonJSMin$1(((e,t)=>{function S(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=S;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let w=t.slice(2),E=[];for(let e of w)e&&E.push(e.getFileName());return E}})),require_redact=__commonJSMin$1(((e,t)=>{function S(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let w=0;w<e.length;w++)t[w]=S(e[w]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let w in e)Object.prototype.hasOwnProperty.call(e,w)&&(t[w]=S(e[w]));return t}return e}function w(e){let t=[],S=``,w=!1,E=!1,D=``;for(let O=0;O<e.length;O++){let k=e[O];!w&&k===`.`?S&&=(t.push(S),``):k===`[`?(S&&=(t.push(S),``),w=!0):k===`]`&&w?(t.push(S),S=``,w=!1,E=!1):(k===`"`||k===`'`)&&w?E?k===D?(E=!1,D=``):S+=k:(E=!0,D=k):S+=k}return S&&t.push(S),t}function E(e,t,S){let w=e;for(let e=0;e<t.length-1;e++){let S=t[e];if(typeof w!=`object`||!w||!(S in w)||typeof w[S]!=`object`||w[S]===null)return!1;w=w[S]}let E=t[t.length-1];if(E===`*`){if(Array.isArray(w))for(let e=0;e<w.length;e++)w[e]=S;else if(typeof w==`object`&&w)for(let e in w)Object.prototype.hasOwnProperty.call(w,e)&&(w[e]=S)}else typeof w==`object`&&w&&E in w&&Object.prototype.hasOwnProperty.call(w,E)&&(w[E]=S);return!0}function D(e,t){let S=e;for(let e=0;e<t.length-1;e++){let w=t[e];if(typeof S!=`object`||!S||!(w in S)||typeof S[w]!=`object`||S[w]===null)return!1;S=S[w]}let w=t[t.length-1];if(w===`*`){if(Array.isArray(S))for(let e=0;e<S.length;e++)S[e]=void 0;else if(typeof S==`object`&&S)for(let e in S)Object.prototype.hasOwnProperty.call(S,e)&&delete S[e]}else typeof S==`object`&&S&&w in S&&Object.prototype.hasOwnProperty.call(S,w)&&delete S[w];return!0}let O=Symbol(`PATH_NOT_FOUND`);function k(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S||!S||!(e in S))return O;S=S[e]}return S}function j(e,t){let S=e;for(let e of t){if(typeof S!=`object`||!S||!S)return;S=S[e]}return S}function F(e,t,S,j=!1){for(let F of t){let t=w(F);if(t.includes(`*`))L(e,t,S,F,j);else if(j)D(e,t);else{let w=k(e,t);if(w===O)continue;E(e,t,typeof S==`function`?S(w,t):S)}}}function L(e,t,S,w,E=!1){let D=t.indexOf(`*`);if(D===t.length-1){let w=t.slice(0,-1),D=e;for(let e of w){if(typeof D!=`object`||!D||!D)return;D=D[e]}if(Array.isArray(D))if(E)for(let e=0;e<D.length;e++)D[e]=void 0;else for(let e=0;e<D.length;e++){let t=[...w,e.toString()],E=typeof S==`function`?S(D[e],t):S;D[e]=E}else if(typeof D==`object`&&D)if(E){let e=[];for(let t in D)Object.prototype.hasOwnProperty.call(D,t)&&e.push(t);for(let t of e)delete D[t]}else for(let e in D){let t=[...w,e],E=typeof S==`function`?S(D[e],t):S;D[e]=E}}else B(e,t,S,D,w,E)}function B(e,t,S,w,O,k=!1){let F=t.slice(0,w),B=t.slice(w+1),H=[];function q(e,t){if(t===F.length){if(Array.isArray(e))for(let S=0;S<e.length;S++)H[t]=S.toString(),q(e[S],t+1);else if(typeof e==`object`&&e)for(let S in e)H[t]=S,q(e[S],t+1)}else if(t<F.length){let S=F[t];e&&typeof e==`object`&&e&&S in e&&(H[t]=S,q(e[S],t+1))}else B.includes(`*`)?L(e,B,typeof S==`function`?(e,w)=>S(e,[...H.slice(0,t),...w]):S,O,k):k?D(e,B):E(e,B,typeof S==`function`?S(j(e,B),[...H.slice(0,t),...B]):S)}if(F.length===0)q(e,0);else{let t=e;for(let e=0;e<F.length;e++){let S=F[e];if(typeof t!=`object`||!t||!t)return;t=t[S],H[e]=S}t!=null&&q(t,F.length)}}function H(e){if(e.length===0)return null;let t=new Map;for(let S of e){let e=w(S),E=t;for(let t=0;t<e.length;t++){let S=e[t];E.has(S)||E.set(S,new Map),E=E.get(S)}}return t}function q(e,t){if(!t)return e;function S(e,t,w=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let w=[];for(let E=0;E<e.length;E++){let D=E.toString();t.has(D)||t.has(`*`)?w[E]=S(e[E],t.get(D)||t.get(`*`)):w[E]=e[E]}return w}let E=Object.create(Object.getPrototypeOf(e));for(let w in e)Object.prototype.hasOwnProperty.call(e,w)&&(t.has(w)||t.has(`*`)?E[w]=S(e[w],t.get(w)||t.get(`*`)):E[w]=e[w]);return E}return S(e,t)}function J(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,S=!1,w=``;for(let E=0;E<e.length;E++){let D=e[E];if((D===`"`||D===`'`)&&t>0)S?D===w&&(S=!1,w=``):(S=!0,w=D);else if(D===`[`&&!S)t++;else if(D===`]`&&!S&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function Y(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)J(t)}function ee(e={}){let{paths:t=[],censor:w=`[REDACTED]`,serialize:E=JSON.stringify,strict:D=!0,remove:O=!1}=e;Y(t);let k=H(t);return function(e){if(D&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return E?E(e):e;let j=q(e,k),L=e,B=w;return typeof w==`function`&&(B=w),F(j,t,B,O),E===!1?(j.restore=function(){return S(L)},j):typeof E==`function`?E(j):JSON.stringify(j)}}t.exports=ee})),require_symbols=__commonJSMin$1(((e,t)=>{let S=Symbol(`pino.setLevel`),w=Symbol(`pino.getLevel`),E=Symbol(`pino.levelVal`),D=Symbol(`pino.levelComp`),O=Symbol(`pino.useLevelLabels`),k=Symbol(`pino.useOnlyCustomLevels`),j=Symbol(`pino.mixin`),F=Symbol(`pino.lsCache`),L=Symbol(`pino.chindings`),B=Symbol(`pino.asJson`),H=Symbol(`pino.write`),q=Symbol(`pino.redactFmt`),J=Symbol(`pino.time`),Y=Symbol(`pino.timeSliceIndex`),ee=Symbol(`pino.stream`),te=Symbol(`pino.stringify`),ne=Symbol(`pino.stringifySafe`),ae=Symbol(`pino.stringifiers`),oe=Symbol(`pino.end`),se=Symbol(`pino.formatOpts`),ce=Symbol(`pino.messageKey`),ue=Symbol(`pino.errorKey`),de=Symbol(`pino.nestedKey`),fe=Symbol(`pino.nestedKeyStr`),me=Symbol(`pino.mixinMergeStrategy`),ge=Symbol(`pino.msgPrefix`),_e=Symbol(`pino.wildcardFirst`),ve=Symbol.for(`pino.serializers`),ye=Symbol.for(`pino.formatters`),Ce=Symbol.for(`pino.hooks`);t.exports={setLevelSym:S,getLevelSym:w,levelValSym:E,levelCompSym:D,useLevelLabelsSym:O,mixinSym:j,lsCacheSym:F,chindingsSym:L,asJsonSym:B,writeSym:H,serializersSym:ve,redactFmtSym:q,timeSym:J,timeSliceIndexSym:Y,streamSym:ee,stringifySym:te,stringifySafeSym:ne,stringifiersSym:ae,endSym:oe,formatOptsSym:se,messageKeySym:ce,errorKeySym:ue,nestedKeySym:de,wildcardFirstSym:_e,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:k,formattersSym:ye,hooksSym:Ce,nestedKeyStrSym:fe,mixinMergeStrategySym:me,msgPrefixSym:ge}})),require_redaction=__commonJSMin$1(((e,t)=>{let S=require_redact(),{redactFmtSym:w,wildcardFirstSym:E}=require_symbols(),D=/[^.[\]]+|\[([^[\]]*?)\]/g,O=`[Redacted]`,k=!1;function j(e,t){let{paths:O,censor:k,remove:j}=F(e),L=O.reduce((e,t)=>{D.lastIndex=0;let S=D.exec(t),w=D.exec(t),O=S[1]===void 0?S[0]:S[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(O===`*`&&(O=E),w===null)return e[O]=null,e;if(e[O]===null)return e;let{index:k}=w,j=`${t.substr(k,t.length-1)}`;return e[O]=e[O]||[],O!==E&&e[O].length===0&&e[O].push(...e[E]||[]),O===E&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(j)}),e[O].push(j),e},{}),B={[w]:S({paths:O,censor:k,serialize:t,strict:!1,remove:j})},H=(...e)=>t(typeof k==`function`?k(...e):k);return[...Object.keys(L),...Object.getOwnPropertySymbols(L)].reduce((e,w)=>{if(L[w]===null)e[w]=e=>H(e,[w]);else{let E=typeof k==`function`?(e,t)=>k(e,[w,...t]):k;e[w]=S({paths:L[w],censor:E,serialize:t,strict:!1,remove:j})}return e},B)}function F(e){if(Array.isArray(e))return e={paths:e,censor:O},e;let{paths:t,censor:S=O,remove:w}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return w===!0&&(S=void 0),{paths:t,censor:S,remove:w}}t.exports=j})),require_time$4=__commonJSMin$1(((e,t)=>{let S=()=>``,w=()=>`,"time":${Date.now()}`,E=()=>`,"time":${Math.round(Date.now()/1e3)}`,D=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,O=1000000n,k=1000000000n,j=BigInt(Date.now())*1000000n,F=process.hrtime.bigint();t.exports={nullTime:S,epochTime:w,unixTime:E,isoTime:D,isoTimeNano:()=>{let e=j+(process.hrtime.bigint()-F),t=e/k,S=e%k,w=Number(t*1000n+S/1000000n),E=new Date(w);return`,"time":"${E.getUTCFullYear()}-${(E.getUTCMonth()+1).toString().padStart(2,`0`)}-${E.getUTCDate().toString().padStart(2,`0`)}T${E.getUTCHours().toString().padStart(2,`0`)}:${E.getUTCMinutes().toString().padStart(2,`0`)}:${E.getUTCSeconds().toString().padStart(2,`0`)}.${S.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin$1(((e,t)=>{function S(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=w;function w(e,t,w){var E=w&&w.stringify||S,D=1;if(typeof e==`object`&&e){var O=t.length+D;if(O===1)return e;var k=Array(O);k[0]=E(e);for(var j=1;j<O;j++)k[j]=E(t[j]);return k.join(` `)}if(typeof e!=`string`)return e;var F=t.length;if(F===0)return e;for(var L=``,B=1-D,H=-1,q=e&&e.length||0,J=0;J<q;){if(e.charCodeAt(J)===37&&J+1<q){switch(H=H>-1?H:0,e.charCodeAt(J+1)){case 100:case 102:if(B>=F||t[B]==null)break;H<J&&(L+=e.slice(H,J)),L+=Number(t[B]),H=J+2,J++;break;case 105:if(B>=F||t[B]==null)break;H<J&&(L+=e.slice(H,J)),L+=Math.floor(Number(t[B])),H=J+2,J++;break;case 79:case 111:case 106:if(B>=F||t[B]===void 0)break;H<J&&(L+=e.slice(H,J));var Y=typeof t[B];if(Y===`string`){L+=`'`+t[B]+`'`,H=J+2,J++;break}if(Y===`function`){L+=t[B].name||`<anonymous>`,H=J+2,J++;break}L+=E(t[B]),H=J+2,J++;break;case 115:if(B>=F)break;H<J&&(L+=e.slice(H,J)),L+=String(t[B]),H=J+2,J++;break;case 37:H<J&&(L+=e.slice(H,J)),L+=`%`,H=J+2,J++,B--;break}++B}++J}return H===-1?e:(H<q&&(L+=e.slice(H)),L)}})),require_atomic_sleep=__commonJSMin$1(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function S(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=S}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin$1(((e,t)=>{let S=__require$1(`fs`),w=__require$1(`events`),E=__require$1(`util`).inherits,D=__require$1(`path`),O=require_atomic_sleep(),k=__require$1(`assert`),j=100,F=Buffer.allocUnsafe(0),L=16*1024,B=`buffer`,H=`utf8`,[q,J]=(process.versions.node||`0.0`).split(`.`).map(Number),Y=q>=22&&J>=7;function ee(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function w(S,w){if(S){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,S)}):t.emit(`error`,S);return}let E=t._reopening;t.fd=w,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():E&&process.nextTick(()=>t.emit(`drain`)))}let E=t.append?`a`:`w`,O=t.mode;if(t.sync)try{t.mkdir&&S.mkdirSync(D.dirname(e),{recursive:!0}),w(null,S.openSync(e,E,O))}catch(e){throw w(e),e}else t.mkdir?S.mkdir(D.dirname(e),{recursive:!0},t=>{if(t)return w(t);S.open(e,E,O,w)}):S.open(e,E,O,w)}function te(e){if(!(this instanceof te))return new te(e);let{fd:t,dest:w,minLength:E,maxLength:D,maxWrite:k,periodicFlush:j,sync:L,append:q=!0,mkdir:J,retryEAGAIN:Y,fsync:oe,contentMode:ue,mode:Ce}=e||{};t||=w,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(E||0,16387),this.file=null,this.destroyed=!1,this.minLength=E||0,this.maxLength=D||0,this.maxWrite=k||16384,this._periodicFlush=j||0,this._periodicFlushTimer=void 0,this.sync=L||!1,this.writable=!0,this._fsync=oe||!1,this.append=q||!1,this.mode=Ce,this.retryEAGAIN=Y||(()=>!0),this.mkdir=J||!1;let we,Te;if(ue===B)this._writingBuf=F,this.write=ce,this.flush=fe,this.flushSync=ge,this._actualWrite=ve,we=()=>S.writeSync(this.fd,this._writingBuf),Te=()=>S.write(this.fd,this._writingBuf,this.release);else if(ue===void 0||ue===H)this._writingBuf=``,this.write=se,this.flush=de,this.flushSync=me,this._actualWrite=_e,we=()=>Buffer.isBuffer(this._writingBuf)?S.writeSync(this.fd,this._writingBuf):S.writeSync(this.fd,this._writingBuf,`utf8`),Te=()=>Buffer.isBuffer(this._writingBuf)?S.write(this.fd,this._writingBuf,this.release):S.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${H}" and "${B}", but passed ${ue}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)ee(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{O(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(Te,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let w=ne(this._writingBuf,this._len,t);if(this._len=w.len,this._writingBuf=w.writingBuf,this._writingBuf.length){if(!this.sync){Te();return}try{do{let e=we(),t=ne(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&S.fsyncSync(this.fd);let E=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):E>this.minLength?this._actualWrite():this._ending?E>0?this._actualWrite():(this._writing=!1,ye(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(ae,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function ne(e,t,S){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-S,0),e=e.subarray(S),{writingBuf:e,len:t}}function ae(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}E(te,w);function oe(e,t){return e.length===0?F:e.length===1?e[0]:Buffer.concat(e,t)}function se(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),S=this._len+t,w=this._bufs;return this.maxLength&&S>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(w.length===0||Buffer.byteLength(w[w.length-1])+t>this.maxWrite?w.push(e):w[w.length-1]+=e,this._len=S,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function ce(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,S=this._bufs,w=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(S.length===0||w[w.length-1]+e.length>this.maxWrite?(S.push([e]),w.push(e.length)):(S[S.length-1].push(e),w[w.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function ue(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{S.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,w)},w=S=>{this._flushPending=!1,e(S),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,w)}function de(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&ue.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function fe(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&ue.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&S.close(t,e=>{if(e)return this.emit(`error`,e)})}),ee(this.file,this)},te.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():ye(this)))};function me(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?S.writeSync(this.fd,e):S.writeSync(this.fd,e,`utf8`),w=ne(e,this._len,t);e=w.writingBuf,this._len=w.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;O(100)}}try{S.fsyncSync(this.fd)}catch{}}function ge(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=F);let e=F;for(;this._bufs.length||e.length;){e.length<=0&&(e=oe(this._bufs[0],this._lens[0]));try{let t=S.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;O(100)}}}te.prototype.destroy=function(){this.destroyed||ye(this)};function _e(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?S.writeSync(this.fd,this._writingBuf):S.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else S.write(this.fd,this._writingBuf,e)}function ve(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:oe(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,S.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else Y&&(this._writingBuf=Buffer.from(this._writingBuf)),S.write(this.fd,this._writingBuf,e)}function ye(e){if(e.fd===-1){e.once(`ready`,ye.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],k(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{S.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?S.close(e.fd,w):w()}function w(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}te.SonicBoom=te,te.default=te,t.exports=te})),require_on_exit_leak_free=__commonJSMin$1(((e,t)=>{let S={exit:[],beforeExit:[]},w={exit:j,beforeExit:F},E;function D(){E===void 0&&(E=new FinalizationRegistry(B))}function O(e){S[e].length>0||process.on(e,w[e])}function k(e){S[e].length>0||(process.removeListener(e,w[e]),S.exit.length===0&&S.beforeExit.length===0&&(E=void 0))}function j(){L(`exit`)}function F(){L(`beforeExit`)}function L(e){for(let t of S[e]){let S=t.deref(),w=t.fn;S!==void 0&&w(S,e)}S[e]=[]}function B(e){for(let t of[`exit`,`beforeExit`]){let w=S[t].indexOf(e);S[t].splice(w,w+1),k(t)}}function H(e,t,w){if(t===void 0)throw Error(`the object can't be undefined`);O(e);let k=new WeakRef(t);k.fn=w,D(),E.register(t,k),S[e].push(k)}function q(e,t){H(`exit`,e,t)}function J(e,t){H(`beforeExit`,e,t)}function Y(e){if(E!==void 0){E.unregister(e);for(let t of[`exit`,`beforeExit`])S[t]=S[t].filter(t=>{let S=t.deref();return S&&S!==e}),k(t)}}t.exports={register:q,registerBeforeExit:J,unregister:Y}})),require_package=__commonJSMin$1(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin$1(((e,t)=>{let S=1e4;function w(e,t,w,E,D){let O=E===1/0?1/0:Date.now()+E,k=()=>{let E=Atomics.load(e,t);if(E===w){D(null,`ok`);return}if(O!==1/0&&Date.now()>O){D(null,`timed-out`);return}let j=O===1/0?S:Math.min(S,Math.max(1,O-Date.now())),F=Atomics.waitAsync(e,t,E,j);F.async?F.value.then(k):setImmediate(k)};k()}function E(e,t,w,E,D){let O=E===1/0?1/0:Date.now()+E,k=()=>{if(Atomics.load(e,t)!==w){D(null,`ok`);return}if(O!==1/0&&Date.now()>O){D(null,`timed-out`);return}let E=O===1/0?S:Math.min(S,Math.max(1,O-Date.now())),j=Atomics.waitAsync(e,t,w,E);j.async?j.value.then(k):setImmediate(k)};k()}t.exports={wait:w,waitDiff:E}})),require_indexes=__commonJSMin$1(((e,t)=>{let S=4,w=8;t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin$1(((e,t)=>{let{version:S}=require_package(),{EventEmitter:w}=__require$1(`events`),{Worker:E}=__require$1(`worker_threads`),{join:D}=__require$1(`path`),{pathToFileURL:O}=__require$1(`url`),{wait:k}=require_wait(),{WRITE_INDEX:j,READ_INDEX:F}=require_indexes(),L=__require$1(`buffer`),B=__require$1(`assert`),H=Symbol(`kImpl`),q=L.constants.MAX_STRING_LENGTH;var J=class{constructor(e){this._value=e}deref(){return this._value}},Y=class{register(){}unregister(){}};let ee=process.env.NODE_V8_COVERAGE?Y:global.FinalizationRegistry||Y,te=process.env.NODE_V8_COVERAGE?J:global.WeakRef||J,ne=new ee(e=>{e.exited||e.terminate()});function ae(e,t){let{filename:w,workerData:k}=t,j=new E((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||D(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:w.indexOf(`file://`)===0?w:O(w).href,dataBuf:e[H].dataBuf,stateBuf:e[H].stateBuf,workerData:{$context:{threadStreamVersion:S},...k}}});return j.stream=new J(e),j.on(`message`,ce),j.on(`exit`,ue),ne.register(e,j),j}function oe(e){B(!e[H].sync),e[H].needDrain&&(e[H].needDrain=!1,e.emit(`drain`))}function se(e){let t=Atomics.load(e[H].state,j),S=e[H].data.length-t;if(S>0){if(e[H].buf.length===0){e[H].flushing=!1,e[H].ending?_e(e):e[H].needDrain&&process.nextTick(oe,e);return}let t=e[H].buf.slice(0,S),w=Buffer.byteLength(t);w<=S?(e[H].buf=e[H].buf.slice(S),ge(e,t,se.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[H].state,F,0),Atomics.store(e[H].state,j,0),Atomics.notify(e[H].state,F);w>e[H].data.length;)S/=2,t=e[H].buf.slice(0,S),w=Buffer.byteLength(t);e[H].buf=e[H].buf.slice(S),ge(e,t,se.bind(null,e))}})}else if(S===0){if(t===0&&e[H].buf.length===0)return;e.flush(()=>{Atomics.store(e[H].state,F,0),Atomics.store(e[H].state,j,0),Atomics.notify(e[H].state,F),se(e)})}else me(e,Error(`overwritten`))}function ce(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new te(t),t.flush(()=>{t[H].ready=!0,t.emit(`ready`)});break;case`ERROR`:me(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:me(t,Error(`this should not happen: `+e.code))}}function ue(e){let t=this.stream.deref();t!==void 0&&(ne.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,ue),me(t,e===0?null:Error(`the worker thread exited`)))}var de=class extends w{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[H]={},this[H].stateBuf=new SharedArrayBuffer(128),this[H].state=new Int32Array(this[H].stateBuf),this[H].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[H].data=Buffer.from(this[H].dataBuf),this[H].sync=e.sync||!1,this[H].ending=!1,this[H].ended=!1,this[H].needDrain=!1,this[H].destroyed=!1,this[H].flushing=!1,this[H].ready=!1,this[H].finished=!1,this[H].errored=null,this[H].closed=!1,this[H].buf=``,this.worker=ae(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[H].destroyed)return fe(this,Error(`the worker has exited`)),!1;if(this[H].ending)return fe(this,Error(`the worker is ending`)),!1;if(this[H].flushing&&this[H].buf.length+e.length>=q)try{ve(this),this[H].flushing=!0}catch(e){return me(this,e),!1}if(this[H].buf+=e,this[H].sync)try{return ve(this),!0}catch(e){return me(this,e),!1}return this[H].flushing||(this[H].flushing=!0,setImmediate(se,this)),this[H].needDrain=this[H].data.length-this[H].buf.length-Atomics.load(this[H].state,j)<=0,!this[H].needDrain}end(){this[H].destroyed||(this[H].ending=!0,_e(this))}flush(e){if(this[H].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[H].state,j);k(this[H].state,F,t,1/0,(t,S)=>{if(t){me(this,t),process.nextTick(e,t);return}if(S===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[H].destroyed||(ve(this),ye(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[H].ready}get destroyed(){return this[H].destroyed}get closed(){return this[H].closed}get writable(){return!this[H].destroyed&&!this[H].ending}get writableEnded(){return this[H].ending}get writableFinished(){return this[H].finished}get writableNeedDrain(){return this[H].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[H].errored}};function fe(e,t){setImmediate(()=>{e.emit(`error`,t)})}function me(e,t){e[H].destroyed||(e[H].destroyed=!0,t&&(e[H].errored=t,fe(e,t)),e.worker.exited?setImmediate(()=>{e[H].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[H].closed=!0,e.emit(`close`)}))}function ge(e,t,S){let w=Atomics.load(e[H].state,j),E=Buffer.byteLength(t);return e[H].data.write(t,w),Atomics.store(e[H].state,j,w+E),Atomics.notify(e[H].state,j),S(),!0}function _e(e){if(!(e[H].ended||!e[H].ending||e[H].flushing)){e[H].ended=!0;try{e.flushSync();let t=Atomics.load(e[H].state,F);Atomics.store(e[H].state,j,-1),Atomics.notify(e[H].state,j);let S=0;for(;t!==-1;){if(Atomics.wait(e[H].state,F,t,1e3),t=Atomics.load(e[H].state,F),t===-2){me(e,Error(`end() failed`));return}if(++S===10){me(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[H].finished=!0,e.emit(`finish`)})}catch(t){me(e,t)}}}function ve(e){let t=()=>{e[H].ending?_e(e):e[H].needDrain&&process.nextTick(oe,e)};for(e[H].flushing=!1;e[H].buf.length!==0;){let S=Atomics.load(e[H].state,j),w=e[H].data.length-S;if(w===0){ye(e),Atomics.store(e[H].state,F,0),Atomics.store(e[H].state,j,0),Atomics.notify(e[H].state,F);continue}else if(w<0)throw Error(`overwritten`);let E=e[H].buf.slice(0,w),D=Buffer.byteLength(E);if(D<=w)e[H].buf=e[H].buf.slice(w),ge(e,E,t);else{for(ye(e),Atomics.store(e[H].state,F,0),Atomics.store(e[H].state,j,0),Atomics.notify(e[H].state,F);D>e[H].buf.length;)w/=2,E=e[H].buf.slice(0,w),D=Buffer.byteLength(E);e[H].buf=e[H].buf.slice(w),ge(e,E,t)}}}function ye(e){if(e[H].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[H].state,j),S=0;for(;;){let w=Atomics.load(e[H].state,F);if(w===-2)throw Error(`_flushSync failed`);if(w!==t)Atomics.wait(e[H].state,F,w,1e3);else break;if(++S===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=de})),require_transport=__commonJSMin$1(((e,t)=>{let{createRequire:S}=__require$1(`module`),{existsSync:w}=__require$1(`node:fs`),E=require_caller(),{join:D,isAbsolute:O,sep:k}=__require$1(`node:path`),{fileURLToPath:j}=__require$1(`node:url`),F=require_atomic_sleep(),L=require_on_exit_leak_free(),B=require_thread_stream();function H(e){L.register(e,ne),L.registerBeforeExit(e,ae),e.on(`close`,function(){L.unregister(e)})}function q(){let e=process.execArgv;for(let t=0;t<e.length;t++){let S=e[t];if(S===`--import`||S===`--require`||S===`-r`||S.startsWith(`--import=`)||S.startsWith(`--require=`)||S.startsWith(`-r=`))return!0}return!1}function J(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let S=[],w=!1;for(let e=0;e<t.length;e++){let E=t[e];if(E===`--require`||E===`-r`||E===`--import`){let D=t[e+1];if(D&&Y(D)){w=!0,e++;continue}S.push(E),D&&(S.push(D),e++);continue}if((E.startsWith(`--require=`)||E.startsWith(`-r=`)||E.startsWith(`--import=`))&&Y(E.slice(E.indexOf(`=`)+1))){w=!0;continue}S.push(E)}return w?S.join(` `):e}function Y(e){let t=ee(e);if(!t)return!1;let S=t;if(S.startsWith(`file://`))try{S=j(S)}catch{return!1}return O(S)&&!w(S)}function ee(e){let t=e[0],S=e[e.length-1];return t===`"`&&S===`"`||t===`'`&&S===`'`?e.slice(1,-1):e}function te(e,t,S,w,E){if(!S.execArgv&&q()&&__require$1.main===void 0&&(S={...S,execArgv:[]}),!S.env&&process.env.NODE_OPTIONS){let e=J(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(S={...S,env:{...process.env,NODE_OPTIONS:e}})}S={...S,name:E};let D=new B({filename:e,workerData:t,workerOpts:S,sync:w});D.on(`ready`,O),D.on(`close`,function(){process.removeListener(`exit`,k)}),process.on(`exit`,k);function O(){process.removeListener(`exit`,k),D.unref(),S.autoEnd!==!1&&H(D)}function k(){D.closed||(D.flushSync(),F(100),D.end())}return D}function ne(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function ae(e){e.flushSync()}function oe(e){let{pipeline:t,targets:w,levels:j,dedupe:F,worker:L={},caller:B=E(),sync:H=!1}=e,q={...e.options},J=typeof B==`string`?[B]:B,Y=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),ee=e.target;if(ee&&w)throw Error(`only one of target or targets can be specified`);w?(ee=Y[`pino-worker`]||D(__dirname,`worker.js`),q.targets=w.filter(e=>e.target).map(e=>({...e,target:ae(e.target)})),q.pipelines=w.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:ae(t.target)})))):t&&(ee=Y[`pino-worker`]||D(__dirname,`worker.js`),q.pipelines=[t.map(e=>({...e,target:ae(e.target)}))]),j&&(q.levels=j),F&&(q.dedupe=F),q.pinoWillSendConfig=!0;let ne=w||t?`pino.transport`:ee;return te(ae(ee),q,L,H,ne);function ae(e){if(e=Y[e]||e,O(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return D(__dirname,`..`,`file.js`);let t;for(let w of J)try{t=S(w===`node:repl`?process.cwd()+k:w).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=oe})),require_tools=__commonJSMin$1(((e,t)=>{let S=__require$1(`node:diagnostics_channel`),w=require_quick_format_unescaped(),{mapHttpRequest:E,mapHttpResponse:D}=require_pino_std_serializers(),O=require_sonic_boom(),k=require_on_exit_leak_free(),{lsCacheSym:j,chindingsSym:F,writeSym:L,serializersSym:B,formatOptsSym:H,endSym:q,stringifiersSym:J,stringifySym:Y,stringifySafeSym:ee,wildcardFirstSym:te,nestedKeySym:ne,formattersSym:ae,messageKeySym:oe,errorKeySym:se,nestedKeyStrSym:ce,msgPrefixSym:ue}=require_symbols(),{isMainThread:de}=__require$1(`worker_threads`),fe=require_transport(),[me]=process.versions.node.split(`.`).map(e=>Number(e)),ge=S.tracingChannel(`pino_asJson`),_e=me>=25?e=>JSON.stringify(e):Ce;function ve(){}function ye(e,t){if(!t)return S;return function(...w){t.call(this,w,S,e)};function S(t,...S){if(typeof t==`object`){let O=t;t!==null&&(t.method&&t.headers&&t.socket?t=E(t):typeof t.setHeader==`function`&&(t=D(t)));let k;O===null&&S.length===0?k=[null]:(O=S.shift(),k=S),typeof this[ue]==`string`&&O!=null&&(O=this[ue]+O),this[L](t,w(O,k,this[H]),e)}else{let E=t===void 0?S.shift():t;typeof this[ue]==`string`&&E!=null&&(E=this[ue]+E),this[L](null,w(E,S,this[H]),e)}}}function Ce(e){let t=``,S=0,w=!1,E=255,D=e.length;if(D>100)return JSON.stringify(e);for(var O=0;O<D&&E>=32;O++)E=e.charCodeAt(O),(E===34||E===92)&&(t+=e.slice(S,O)+`\\`,S=O,w=!0);return w?t+=e.slice(S):t=e,E<32?JSON.stringify(e):`"`+t+`"`}function we(e,t,S,w){if(ge.hasSubscribers===!1)return Te.call(this,e,t,S,w);let E={instance:this,arguments};return ge.traceSync(Te,E,this,e,t,S,w)}function Te(e,t,S,w){let E=this[Y],D=this[ee],O=this[J],k=this[q],L=this[F],H=this[B],ue=this[ae],de=this[oe],fe=this[se],me=this[j][S]+w;me+=L;let ge;ue.log&&(e=ue.log(e));let ve=O[te],ye=``;for(let t in e)if(ge=e[t],Object.prototype.hasOwnProperty.call(e,t)&&ge!==void 0){H[t]?ge=H[t](ge):t===fe&&H.err&&(ge=H.err(ge));let e=O[t]||ve;switch(typeof ge){case`undefined`:case`function`:continue;case`number`:Number.isFinite(ge)===!1&&(ge=null);case`boolean`:e&&(ge=e(ge));break;case`string`:ge=(e||_e)(ge);break;default:ge=(e||E)(ge,D)}if(ge===void 0)continue;let S=_e(t);ye+=`,`+S+`:`+ge}let Ce=``;if(t!==void 0){ge=H[de]?H[de](t):t;let e=O[de]||ve;switch(typeof ge){case`function`:break;case`number`:Number.isFinite(ge)===!1&&(ge=null);case`boolean`:e&&(ge=e(ge)),Ce=`,"`+de+`":`+ge;break;case`string`:ge=(e||_e)(ge),Ce=`,"`+de+`":`+ge;break;default:ge=(e||E)(ge,D),Ce=`,"`+de+`":`+ge}}return this[ne]&&ye?me+this[ce]+ye.slice(1)+`}`+Ce+k:me+ye+Ce+k}function De(e,t){let S,w=e[F],E=e[Y],D=e[ee],O=e[J],k=O[te],j=e[B],L=e[ae].bindings;t=L(t);for(let e in t)if(S=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&S!==void 0)===!0){if(S=j[e]?j[e](S):S,S=(O[e]||k||E)(S,D),S===void 0)continue;w+=`,"`+e+`":`+S}return w}function je(e){return e.write!==e.constructor.prototype.write}function Me(e){let t=new O(e);return t.on(`error`,S),!e.sync&&de&&(k.register(t,Pe),t.on(`close`,function(){k.unregister(t)})),t;function S(e){if(e.code===`EPIPE`){t.write=ve,t.end=ve,t.flushSync=ve,t.destroy=ve;return}t.removeListener(`error`,S),t.emit(`error`,e)}}function Pe(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function Ie(e){return function(t,S,w={},E){if(typeof w==`string`)E=Me({dest:w}),w={};else if(typeof E==`string`){if(w&&w.transport)throw Error(`only one of option.transport or stream can be specified`);E=Me({dest:E})}else if(w instanceof O||w.writable||w._writableState)E=w,w={};else if(w.transport){if(w.transport instanceof O||w.transport.writable||w.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(w.transport.targets&&w.transport.targets.length&&w.formatters&&typeof w.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;w.customLevels&&(e=w.useOnlyCustomLevels?w.customLevels:Object.assign({},w.levels,w.customLevels)),E=fe({caller:S,...w.transport,levels:e})}if(w=Object.assign({},e,w),w.serializers=Object.assign({},e.serializers,w.serializers),w.formatters=Object.assign({},e.formatters,w.formatters),w.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:D,onChild:k}=w;return D===!1&&(w.level=`silent`),k||(w.onChild=ve),E||=je(process.stdout)?process.stdout:Me({fd:process.stdout.fd||1}),{opts:w,stream:E}}}function Re(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[ee])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ze(e,t,S){return{level:e,bindings:t,log:S}}function Be(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:ve,buildSafeSonicBoom:Me,asChindings:De,asJson:we,genLog:ye,createArgsNormalizer:Ie,stringify:Re,buildFormatters:ze,normalizeDestFileDescriptor:Be}})),require_constants$7=__commonJSMin$1(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin$1(((e,t)=>{let{lsCacheSym:S,levelValSym:w,useOnlyCustomLevelsSym:E,streamSym:D,formattersSym:O,hooksSym:k,levelCompSym:j}=require_symbols(),{noop:F,genLog:L}=require_tools(),{DEFAULT_LEVELS:B,SORTING_ORDER:H}=require_constants$7(),q={fatal:e=>{let t=L(B.fatal,e);return function(...e){let S=this[D];if(t.call(this,...e),typeof S.flushSync==`function`)try{S.flushSync()}catch{}}},error:e=>L(B.error,e),warn:e=>L(B.warn,e),info:e=>L(B.info,e),debug:e=>L(B.debug,e),trace:e=>L(B.trace,e)},J=Object.keys(B).reduce((e,t)=>(e[B[t]]=t,e),{}),Y=Object.keys(J).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function ee(e){let t=e[O].level,{labels:w}=e.levels,E={};for(let e in w){let S=t(w[e],Number(e));E[e]=JSON.stringify(S).slice(0,-1)}return e[S]=E,e}function te(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function ne(e){let{labels:t,values:S}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(S[e]===void 0)throw Error(`unknown level `+e);let D=this[w],O=this[w]=S[e],B=this[E],H=this[j],J=this[k].logMethod;for(let e in S){if(H(S[e],O)===!1){this[e]=F;continue}this[e]=te(e,B)?q[e](J):L(S[e],J)}this.emit(`level-change`,e,O,t[D],D,this)}function ae(e){let{levels:t,levelVal:S}=this;return t&&t.labels?t.labels[S]:``}function oe(e){let{values:t}=this.levels,S=t[e];return S!==void 0&&this[j](S,this[w])}function se(e,t,S){return e===H.DESC?t<=S:t>=S}function ce(e){return typeof e==`string`?se.bind(null,e):e}function ue(e=null,t=!1){let S=e?Object.keys(e).reduce((t,S)=>(t[e[S]]=S,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:J,S),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:B,e)}}function de(e,t,S){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),S?[]:Object.keys(J).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),S?null:B,t)))throw Error(`default level:${e} must be included in custom levels`)}function fe(e,t){let{labels:S,values:w}=e;for(let e in t){if(e in w)throw Error(`levels cannot be overridden`);if(t[e]in S)throw Error(`pre-existing level values cannot be used for new levels`)}}function me(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(H).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:Y,genLsCache:ee,levelMethods:q,getLevel:ae,setLevel:ne,isLevelEnabled:oe,mappings:ue,assertNoLevelCollisions:fe,assertDefaultLevelFound:de,genLevelComparison:ce,assertLevelComparison:me}})),require_meta=__commonJSMin$1(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin$1(((e,t)=>{let{EventEmitter:S}=__require$1(`node:events`),{lsCacheSym:w,levelValSym:E,setLevelSym:D,getLevelSym:O,chindingsSym:k,mixinSym:j,asJsonSym:F,writeSym:L,mixinMergeStrategySym:B,timeSym:H,timeSliceIndexSym:q,streamSym:J,serializersSym:Y,formattersSym:ee,errorKeySym:te,messageKeySym:ne,useOnlyCustomLevelsSym:ae,needsMetadataGsym:oe,redactFmtSym:se,stringifySym:ce,formatOptsSym:ue,stringifiersSym:de,msgPrefixSym:fe,hooksSym:me}=require_symbols(),{getLevel:ge,setLevel:_e,isLevelEnabled:ve,mappings:ye,initialLsCache:Ce,genLsCache:we,assertNoLevelCollisions:Te}=require_levels(),{asChindings:De,asJson:je,buildFormatters:Me,stringify:Pe,noop:Ie}=require_tools(),{version:Re}=require_meta(),ze=require_redaction(),Be={constructor:class{},child:Ue,bindings:We,setBindings:Ge,flush:$e,isLevelEnabled:ve,version:Re,get level(){return this[O]()},set level(e){this[D](e)},get levelVal(){return this[E]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[fe]},get[Symbol.toStringTag](){return`Pino`},[w]:Ce,[L]:Xe,[F]:je,[O]:ge,[D]:_e};Object.setPrototypeOf(Be,S.prototype),t.exports=function(){return Object.create(Be)};let Ve=e=>e;function Ue(e,t){if(!e)throw Error(`missing bindings for child Pino`);let S=this[Y],w=this[ee],E=Object.create(this);if(t==null)return E[ee].bindings!==Ve&&(E[ee]=Me(w.level,Ve,w.log)),E[k]=De(E,e),this.onChild!==Ie&&this.onChild(E),E;if(t.hasOwnProperty(`serializers`)===!0){E[Y]=Object.create(null);for(let e in S)E[Y][e]=S[e];let e=Object.getOwnPropertySymbols(S);for(var O=0;O<e.length;O++){let t=e[O];E[Y][t]=S[t]}for(let e in t.serializers)E[Y][e]=t.serializers[e];let w=Object.getOwnPropertySymbols(t.serializers);for(var j=0;j<w.length;j++){let e=w[j];E[Y][e]=t.serializers[e]}}else E[Y]=S;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:S,log:D}=t.formatters;E[ee]=Me(e||w.level,S||Ve,D||w.log)}else E[ee]=Me(w.level,Ve,w.log);if(t.hasOwnProperty(`customLevels`)===!0&&(Te(this.levels,t.customLevels),E.levels=ye(t.customLevels,E[ae]),we(E)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){E.redact=t.redact;let e=ze(E.redact,Pe),S={stringify:e[se]};E[ce]=Pe,E[de]=e,E[ue]=S}if(typeof t.msgPrefix==`string`&&(E[fe]=(this[fe]||``)+t.msgPrefix),E[k]=De(E,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;E[D](e)}return this.onChild(E),E}function We(){let e=`{${this[k].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Ge(e){this[k]=De(this,e)}function Ke(e,t){return Object.assign(t,e)}function Xe(e,t,S){let w=this[H](),E=this[j],D=this[te],O=this[ne],k=this[B]||Ke,L,Y=this[me].streamWrite;e==null?L={}:e instanceof Error?(L={[D]:e},t===void 0&&(t=e.message)):(L=e,t===void 0&&e[O]===void 0&&e[D]&&(t=e[D].message)),E&&(L=k(L,E(L,S,this)));let ee=this[F](L,t,S,w),ae=this[J];ae[oe]===!0&&(ae.lastLevel=S,ae.lastObj=L,ae.lastMsg=t,ae.lastTime=w.slice(this[q]),ae.lastLogger=this),ae.write(Y?Y(ee):ee)}function $e(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[J];typeof t.flush==`function`?t.flush(e||Ie):e&&e()}})),require_safe_stable_stringify=__commonJSMin$1(((e,t)=>{let{hasOwnProperty:S}=Object.prototype,w=te();w.configure=te,w.stringify=w,w.default=w,e.stringify=w,e.configure=te,t.exports=w;let E=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function D(e){return e.length<5e3&&!E.test(e)?`"${e}"`:JSON.stringify(e)}function O(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let S=e[t],w=t;for(;w!==0&&e[w-1]>S;)e[w]=e[w-1],w--;e[w]=S}return e}let k=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function j(e){return k.call(e)!==void 0&&e.length!==0}function F(e,t,S){e.length<S&&(S=e.length);let w=t===`,`?``:` `,E=`"0":${w}${e[0]}`;for(let D=1;D<S;D++)E+=`${t}"${D}":${w}${e[D]}`;return E}function L(e){if(S.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function B(e){let t;if(S.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function H(e,t){let w;if(S.call(e,t)&&(w=e[t],typeof w!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return w===void 0?!0:w}function q(e,t){let w;if(S.call(e,t)){if(w=e[t],typeof w!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(w))throw TypeError(`The "${t}" argument must be an integer`);if(w<1)throw RangeError(`The "${t}" argument must be >= 1`)}return w===void 0?1/0:w}function J(e){return e===1?`1 item`:`${e} items`}function Y(e){let t=new Set;for(let S of e)(typeof S==`string`||typeof S==`number`)&&t.add(String(S));return t}function ee(e){if(S.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function te(e){e={...e};let t=ee(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let S=L(e),w=H(e,`bigint`),E=B(e),k=typeof E==`function`?E:void 0,te=q(e,`maximumDepth`),ne=q(e,`maximumBreadth`);function ae(e,F,L,B,H,q){let Y=F[e];switch(typeof Y==`object`&&Y&&typeof Y.toJSON==`function`&&(Y=Y.toJSON(e)),Y=B.call(F,e,Y),typeof Y){case`string`:return D(Y);case`object`:{if(Y===null)return`null`;if(L.indexOf(Y)!==-1)return S;let e=``,t=`,`,w=q;if(Array.isArray(Y)){if(Y.length===0)return`[]`;if(te<L.length+1)return`"[Array]"`;L.push(Y),H!==``&&(q+=H,e+=`\n${q}`,t=`,\n${q}`);let S=Math.min(Y.length,ne),E=0;for(;E<S-1;E++){let S=ae(String(E),Y,L,B,H,q);e+=S===void 0?`null`:S,e+=t}let D=ae(String(E),Y,L,B,H,q);if(e+=D===void 0?`null`:D,Y.length-1>ne){let S=Y.length-ne-1;e+=`${t}"... ${J(S)} not stringified"`}return H!==``&&(e+=`\n${w}`),L.pop(),`[${e}]`}let F=Object.keys(Y),ee=F.length;if(ee===0)return`{}`;if(te<L.length+1)return`"[Object]"`;let oe=``,se=``;H!==``&&(q+=H,t=`,\n${q}`,oe=` `);let ce=Math.min(ee,ne);E&&!j(Y)&&(F=O(F,k)),L.push(Y);for(let S=0;S<ce;S++){let w=F[S],E=ae(w,Y,L,B,H,q);E!==void 0&&(e+=`${se}${D(w)}:${oe}${E}`,se=t)}if(ee>ne){let S=ee-ne;e+=`${se}"...":${oe}"${J(S)} not stringified"`,se=t}return H!==``&&se.length>1&&(e=`\n${q}${e}\n${w}`),L.pop(),`{${e}}`}case`number`:return isFinite(Y)?String(Y):t?t(Y):`null`;case`boolean`:return Y===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(w)return String(Y);default:return t?t(Y):void 0}}function oe(e,E,O,k,j,F){switch(typeof E==`object`&&E&&typeof E.toJSON==`function`&&(E=E.toJSON(e)),typeof E){case`string`:return D(E);case`object`:{if(E===null)return`null`;if(O.indexOf(E)!==-1)return S;let e=F,t=``,w=`,`;if(Array.isArray(E)){if(E.length===0)return`[]`;if(te<O.length+1)return`"[Array]"`;O.push(E),j!==``&&(F+=j,t+=`\n${F}`,w=`,\n${F}`);let S=Math.min(E.length,ne),D=0;for(;D<S-1;D++){let e=oe(String(D),E[D],O,k,j,F);t+=e===void 0?`null`:e,t+=w}let L=oe(String(D),E[D],O,k,j,F);if(t+=L===void 0?`null`:L,E.length-1>ne){let e=E.length-ne-1;t+=`${w}"... ${J(e)} not stringified"`}return j!==``&&(t+=`\n${e}`),O.pop(),`[${t}]`}O.push(E);let L=``;j!==``&&(F+=j,w=`,\n${F}`,L=` `);let B=``;for(let e of k){let S=oe(e,E[e],O,k,j,F);S!==void 0&&(t+=`${B}${D(e)}:${L}${S}`,B=w)}return j!==``&&B.length>1&&(t=`\n${F}${t}\n${e}`),O.pop(),`{${t}}`}case`number`:return isFinite(E)?String(E):t?t(E):`null`;case`boolean`:return E===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(w)return String(E);default:return t?t(E):void 0}}function se(e,L,B,H,q){switch(typeof L){case`string`:return D(L);case`object`:{if(L===null)return`null`;if(typeof L.toJSON==`function`){if(L=L.toJSON(e),typeof L!=`object`)return se(e,L,B,H,q);if(L===null)return`null`}if(B.indexOf(L)!==-1)return S;let t=q;if(Array.isArray(L)){if(L.length===0)return`[]`;if(te<B.length+1)return`"[Array]"`;B.push(L),q+=H;let e=`\n${q}`,S=`,\n${q}`,w=Math.min(L.length,ne),E=0;for(;E<w-1;E++){let t=se(String(E),L[E],B,H,q);e+=t===void 0?`null`:t,e+=S}let D=se(String(E),L[E],B,H,q);if(e+=D===void 0?`null`:D,L.length-1>ne){let t=L.length-ne-1;e+=`${S}"... ${J(t)} not stringified"`}return e+=`\n${t}`,B.pop(),`[${e}]`}let w=Object.keys(L),Y=w.length;if(Y===0)return`{}`;if(te<B.length+1)return`"[Object]"`;q+=H;let ee=`,\n${q}`,ae=``,oe=``,ce=Math.min(Y,ne);j(L)&&(ae+=F(L,ee,ne),w=w.slice(L.length),ce-=L.length,oe=ee),E&&(w=O(w,k)),B.push(L);for(let e=0;e<ce;e++){let t=w[e],S=se(t,L[t],B,H,q);S!==void 0&&(ae+=`${oe}${D(t)}: ${S}`,oe=ee)}if(Y>ne){let e=Y-ne;ae+=`${oe}"...": "${J(e)} not stringified"`,oe=ee}return oe!==``&&(ae=`\n${q}${ae}\n${t}`),B.pop(),`{${ae}}`}case`number`:return isFinite(L)?String(L):t?t(L):`null`;case`boolean`:return L===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(w)return String(L);default:return t?t(L):void 0}}function ce(e,L,B){switch(typeof L){case`string`:return D(L);case`object`:{if(L===null)return`null`;if(typeof L.toJSON==`function`){if(L=L.toJSON(e),typeof L!=`object`)return ce(e,L,B);if(L===null)return`null`}if(B.indexOf(L)!==-1)return S;let t=``,w=L.length!==void 0;if(w&&Array.isArray(L)){if(L.length===0)return`[]`;if(te<B.length+1)return`"[Array]"`;B.push(L);let e=Math.min(L.length,ne),S=0;for(;S<e-1;S++){let e=ce(String(S),L[S],B);t+=e===void 0?`null`:e,t+=`,`}let w=ce(String(S),L[S],B);if(t+=w===void 0?`null`:w,L.length-1>ne){let e=L.length-ne-1;t+=`,"... ${J(e)} not stringified"`}return B.pop(),`[${t}]`}let H=Object.keys(L),q=H.length;if(q===0)return`{}`;if(te<B.length+1)return`"[Object]"`;let Y=``,ee=Math.min(q,ne);w&&j(L)&&(t+=F(L,`,`,ne),H=H.slice(L.length),ee-=L.length,Y=`,`),E&&(H=O(H,k)),B.push(L);for(let e=0;e<ee;e++){let S=H[e],w=ce(S,L[S],B);w!==void 0&&(t+=`${Y}${D(S)}:${w}`,Y=`,`)}if(q>ne){let e=q-ne;t+=`${Y}"...":"${J(e)} not stringified"`}return B.pop(),`{${t}}`}case`number`:return isFinite(L)?String(L):t?t(L):`null`;case`boolean`:return L===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(w)return String(L);default:return t?t(L):void 0}}function ue(e,t,S){if(arguments.length>1){let w=``;if(typeof S==`number`?w=` `.repeat(Math.min(S,10)):typeof S==`string`&&(w=S.slice(0,10)),t!=null){if(typeof t==`function`)return ae(``,{"":e},[],t,w,``);if(Array.isArray(t))return oe(``,e,[],Y(t),w,``)}if(w.length!==0)return se(``,e,[],w,``)}return ce(``,e,[])}return ue}})),require_multistream=__commonJSMin$1(((e,t)=>{let S=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:w}=require_constants$7(),E=w.info;function D(e,t){e||=[],t||={dedupe:!1};let D=Object.create(w);D.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{D[e]=t.levels[e]});let L={write:B,add:J,remove:Y,emit:H,flushSync:q,end:ee,minLevel:0,lastId:0,streams:[],clone:te,[S]:!0,streamLevels:D};return Array.isArray(e)?e.forEach(J,L):J.call(L,e),e=null,L;function B(e){let w,E=this.lastLevel,{streams:D}=this,O=0,L;for(let B=k(D.length,t.dedupe);F(B,D.length,t.dedupe);B=j(B,t.dedupe))if(w=D[B],w.level<=E){if(O!==0&&O!==w.level)break;if(L=w.stream,L[S]){let{lastTime:e,lastMsg:t,lastObj:S,lastLogger:w}=this;L.lastLevel=E,L.lastTime=e,L.lastMsg=t,L.lastObj=S,L.lastLogger=w}L.write(e),t.dedupe&&(O=w.level)}else if(!t.dedupe)break}function H(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function q(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function J(e){if(!e)return L;let t=typeof e.write==`function`||e.stream,S=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:w,streamLevels:D}=this,k;k=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?D[e.level]:typeof e.level==`number`?e.level:E;let j={stream:S,level:k,levelVal:void 0,id:++L.lastId};return w.unshift(j),w.sort(O),this.minLevel=w[0].level,L}function Y(e){let{streams:t}=this,S=t.findIndex(t=>t.id===e);return S>=0&&(t.splice(S,1),t.sort(O),this.minLevel=t.length>0?t[0].level:-1),L}function ee(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function te(e){let t=Array(this.streams.length);for(let S=0;S<t.length;S++)t[S]={level:e,stream:this.streams[S].stream};return{write:B,add:J,remove:Y,minLevel:e,streams:t,clone:te,emit:H,flushSync:q,[S]:!0}}}function O(e,t){return e.level-t.level}function k(e,t){return t?e-1:0}function j(e,t){return t?e-1:e+1}function F(e,t,S){return S?e>=0:e<t}t.exports=D})),require_pino=__commonJSMin$1(((e,t)=>{let S=__require$1(`node:os`),w=require_pino_std_serializers(),E=require_caller(),D=require_redaction(),O=require_time$4(),k=require_proto(),j=require_symbols(),{configure:F}=require_safe_stable_stringify(),{assertDefaultLevelFound:L,mappings:B,genLsCache:H,genLevelComparison:q,assertLevelComparison:J}=require_levels(),{DEFAULT_LEVELS:Y,SORTING_ORDER:ee}=require_constants$7(),{createArgsNormalizer:te,asChindings:ne,buildSafeSonicBoom:ae,buildFormatters:oe,stringify:se,normalizeDestFileDescriptor:ce,noop:ue}=require_tools(),{version:de}=require_meta(),{chindingsSym:fe,redactFmtSym:me,serializersSym:ge,timeSym:_e,timeSliceIndexSym:ve,streamSym:ye,stringifySym:Ce,stringifySafeSym:we,stringifiersSym:Te,setLevelSym:De,endSym:je,formatOptsSym:Me,messageKeySym:Pe,errorKeySym:Ie,nestedKeySym:Re,mixinSym:ze,levelCompSym:Be,useOnlyCustomLevelsSym:Ve,formattersSym:Ue,hooksSym:We,nestedKeyStrSym:Ge,mixinMergeStrategySym:Ke,msgPrefixSym:Xe}=j,{epochTime:$e,nullTime:nt}=O,{pid:rt}=process,it=S.hostname(),at=w.err,st=te({level:`info`,levelComparison:ee.ASC,levels:Y,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:rt,hostname:it},serializers:Object.assign(Object.create(null),{err:at}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:$e,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),vt=Object.assign(Object.create(null),w);function Tt(...e){let t={},{opts:S,stream:w}=st(t,E(),...e);S.level&&typeof S.level==`string`&&Y[S.level.toLowerCase()]!==void 0&&(S.level=S.level.toLowerCase());let{redact:O,crlf:j,serializers:ee,timestamp:te,messageKey:ae,errorKey:ce,nestedKey:de,base:rt,name:it,level:at,customLevels:vt,levelComparison:Tt,mixin:Et,mixinMergeStrategy:Dt,useOnlyCustomLevels:jt,formatters:Mt,hooks:Ft,depthLimit:It,edgeLimit:Lt,onChild:Rt,msgPrefix:zt}=S,Bt=F({maximumDepth:It,maximumBreadth:Lt}),Vt=oe(Mt.level,Mt.bindings,Mt.log),Ht=se.bind({[we]:Bt}),Ut=O?D(O,Ht):{},Wt=O?{stringify:Ut[me]}:{stringify:Ht},Kt=`}`+(j?`\r
|
|
434
|
-
`:`
|
|
435
|
-
`),$t=ne.bind(null,{[fe]:``,[ge]:ee,[Te]:Ut,[Ce]:se,[we]:Bt,[Ue]:Vt}),en=``;rt!==null&&(en=$t(it===void 0?rt:Object.assign({},rt,{name:it})));let jr=te instanceof Function?te:te?$e:nt,Mr=jr().indexOf(`:`)+1;if(jt&&!vt)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(Et&&typeof Et!=`function`)throw Error(`Unknown mixin type "${typeof Et}" - expected "function"`);if(zt&&typeof zt!=`string`)throw Error(`Unknown msgPrefix type "${typeof zt}" - expected "string"`);L(at,vt,jt);let Fr=B(vt,jt);typeof w.emit==`function`&&w.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Fr,messageKey:ae,errorKey:ce}}),J(Tt);let Ir=q(Tt);return Object.assign(t,{levels:Fr,[Be]:Ir,[Ve]:jt,[ye]:w,[_e]:jr,[ve]:Mr,[Ce]:se,[we]:Bt,[Te]:Ut,[je]:Kt,[Me]:Wt,[Pe]:ae,[Ie]:ce,[Re]:de,[Ge]:de?`,${JSON.stringify(de)}:{`:``,[ge]:ee,[ze]:Et,[Ke]:Dt,[fe]:en,[Ue]:Vt,[We]:Ft,silent:ue,onChild:Rt,[Xe]:zt}),Object.setPrototypeOf(t,k()),H(t),t[De](at),t}t.exports=Tt,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=ce(e.dest||process.stdout.fd),ae(e)):ae({dest:ce(e),minLength:0}),t.exports.transport=require_transport(),t.exports.multistream=require_multistream(),t.exports.levels=B(),t.exports.stdSerializers=vt,t.exports.stdTimeFunctions=Object.assign({},O),t.exports.symbols=j,t.exports.version=de,t.exports.default=Tt,t.exports.pino=Tt})),require_colorette=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=__require$1(`tty`);function S(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(S){if(S!==`default`){var w=Object.getOwnPropertyDescriptor(e,S);Object.defineProperty(t,S,w.get?w:{enumerable:!0,get:function(){return e[S]}})}}),t.default=e,Object.freeze(t)}var w=S(t);let{env:E={},argv:D=[],platform:O=``}=typeof process>`u`?{}:process,k=`NO_COLOR`in E||D.includes(`--no-color`),j=`FORCE_COLOR`in E||D.includes(`--color`),F=O===`win32`,L=E.TERM===`dumb`,B=w&&w.isatty&&w.isatty(1)&&E.TERM&&!L,H=`CI`in E&&(`GITHUB_ACTIONS`in E||`GITLAB_CI`in E||`CIRCLECI`in E),q=!k&&(j||F&&!L||B||H),J=(e,t,S,w,E=t.substring(0,e)+w,D=t.substring(e+S.length),O=D.indexOf(S))=>E+(O<0?D:J(O,D,S,w)),Y=(e,t,S,w,E)=>e<0?S+t+w:S+J(e,t,w,E)+w,ee=(e,t,S=e,w=e.length+1)=>E=>E||!(E===``||E===void 0)?Y((``+E).indexOf(t,w),E,e,t,S):``,te=(e,t,S)=>ee(`\x1b[${e}m`,`\x1b[${t}m`,S),ne={reset:te(0,0),bold:te(1,22,`\x1B[22m\x1B[1m`),dim:te(2,22,`\x1B[22m\x1B[2m`),italic:te(3,23),underline:te(4,24),inverse:te(7,27),hidden:te(8,28),strikethrough:te(9,29),black:te(30,39),red:te(31,39),green:te(32,39),yellow:te(33,39),blue:te(34,39),magenta:te(35,39),cyan:te(36,39),white:te(37,39),gray:te(90,39),bgBlack:te(40,49),bgRed:te(41,49),bgGreen:te(42,49),bgYellow:te(43,49),bgBlue:te(44,49),bgMagenta:te(45,49),bgCyan:te(46,49),bgWhite:te(47,49),blackBright:te(90,39),redBright:te(91,39),greenBright:te(92,39),yellowBright:te(93,39),blueBright:te(94,39),magentaBright:te(95,39),cyanBright:te(96,39),whiteBright:te(97,39),bgBlackBright:te(100,49),bgRedBright:te(101,49),bgGreenBright:te(102,49),bgYellowBright:te(103,49),bgBlueBright:te(104,49),bgMagentaBright:te(105,49),bgCyanBright:te(106,49),bgWhiteBright:te(107,49)},ae=({useColor:e=q}={})=>e?ne:Object.keys(ne).reduce((e,t)=>({...e,[t]:String}),{}),{reset:oe,bold:se,dim:ce,italic:ue,underline:de,inverse:fe,hidden:me,strikethrough:ge,black:_e,red:ve,green:ye,yellow:Ce,blue:we,magenta:Te,cyan:De,white:je,gray:Me,bgBlack:Pe,bgRed:Ie,bgGreen:Re,bgYellow:ze,bgBlue:Be,bgMagenta:Ve,bgCyan:Ue,bgWhite:We,blackBright:Ge,redBright:Ke,greenBright:Xe,yellowBright:$e,blueBright:nt,magentaBright:rt,cyanBright:it,whiteBright:at,bgBlackBright:st,bgRedBright:vt,bgGreenBright:Tt,bgYellowBright:Et,bgBlueBright:Dt,bgMagentaBright:jt,bgCyanBright:Mt,bgWhiteBright:Ft}=ae();e.bgBlack=Pe,e.bgBlackBright=st,e.bgBlue=Be,e.bgBlueBright=Dt,e.bgCyan=Ue,e.bgCyanBright=Mt,e.bgGreen=Re,e.bgGreenBright=Tt,e.bgMagenta=Ve,e.bgMagentaBright=jt,e.bgRed=Ie,e.bgRedBright=vt,e.bgWhite=We,e.bgWhiteBright=Ft,e.bgYellow=ze,e.bgYellowBright=Et,e.black=_e,e.blackBright=Ge,e.blue=we,e.blueBright=nt,e.bold=se,e.createColors=ae,e.cyan=De,e.cyanBright=it,e.dim=ce,e.gray=Me,e.green=ye,e.greenBright=Xe,e.hidden=me,e.inverse=fe,e.isColorSupported=q,e.italic=ue,e.magenta=Te,e.magentaBright=rt,e.red=ve,e.redBright=Ke,e.reset=oe,e.strikethrough=ge,e.underline=de,e.white=je,e.whiteBright=at,e.yellow=Ce,e.yellowBright=$e})),require_wrappy=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e,t){if(e&&t)return S(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){w[t]=e[t]}),w;function w(){for(var t=Array(arguments.length),S=0;S<t.length;S++)t[S]=arguments[S];var w=e.apply(this,t),E=t[t.length-1];return typeof w==`function`&&w!==E&&Object.keys(E).forEach(function(e){w[e]=E[e]}),w}}})),require_once=__commonJSMin$1(((e,t)=>{var S=require_wrappy();t.exports=S(w),t.exports.strict=S(E),w.proto=w(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return w(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return E(this)},configurable:!0})});function w(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function E(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),require_end_of_stream=__commonJSMin$1(((e,t)=>{var S=require_once(),w=function(){},E=global.Bare?queueMicrotask:process.nextTick.bind(process),D=function(e){return e.setHeader&&typeof e.abort==`function`},O=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},k=function(e,t,j){if(typeof t==`function`)return k(e,null,t);t||={},j=S(j||w);var F=e._writableState,L=e._readableState,B=t.readable||t.readable!==!1&&e.readable,H=t.writable||t.writable!==!1&&e.writable,q=!1,J=function(){e.writable||Y()},Y=function(){H=!1,B||j.call(e)},ee=function(){B=!1,H||j.call(e)},te=function(t){j.call(e,t?Error(`exited with error code: `+t):null)},ne=function(t){j.call(e,t)},ae=function(){E(oe)},oe=function(){if(!q&&(B&&!(L&&L.ended&&!L.destroyed)||H&&!(F&&F.ended&&!F.destroyed)))return j.call(e,Error(`premature close`))},se=function(){e.req.on(`finish`,Y)};return D(e)?(e.on(`complete`,Y),e.on(`abort`,ae),e.req?se():e.on(`request`,se)):H&&!F&&(e.on(`end`,J),e.on(`close`,J)),O(e)&&e.on(`exit`,te),e.on(`end`,ee),e.on(`finish`,Y),t.error!==!1&&e.on(`error`,ne),e.on(`close`,ae),function(){q=!0,e.removeListener(`complete`,Y),e.removeListener(`abort`,ae),e.removeListener(`request`,se),e.req&&e.req.removeListener(`finish`,Y),e.removeListener(`end`,J),e.removeListener(`close`,J),e.removeListener(`finish`,Y),e.removeListener(`exit`,te),e.removeListener(`end`,ee),e.removeListener(`error`,ne),e.removeListener(`close`,ae)}};t.exports=k})),require_pump=__commonJSMin$1(((e,t)=>{var S=require_once(),w=require_end_of_stream(),E;try{E=__require$1(`fs`)}catch{}var D=function(){},O=typeof process>`u`?!1:/^v?\.0/.test(process.version),k=function(e){return typeof e==`function`},j=function(e){return!O||!E?!1:(e instanceof(E.ReadStream||D)||e instanceof(E.WriteStream||D))&&k(e.close)},F=function(e){return e.setHeader&&k(e.abort)},L=function(e,t,E,O){O=S(O);var L=!1;e.on(`close`,function(){L=!0}),w(e,{readable:t,writable:E},function(e){if(e)return O(e);L=!0,O()});var B=!1;return function(t){if(!L&&!B){if(B=!0,j(e))return e.close(D);if(F(e))return e.abort();if(k(e.destroy))return e.destroy();O(t||Error(`stream was destroyed`))}}},B=function(e){e()},H=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=k(e[e.length-1]||D)&&e.pop()||D;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var S,w=e.map(function(E,D){var O=D<e.length-1;return L(E,O,D>0,function(e){S||=e,e&&w.forEach(B),!O&&(w.forEach(B),t(S))})});return e.reduce(H)}})),require_split2=__commonJSMin$1(((e,t)=>{let{Transform:S}=__require$1(`stream`),{StringDecoder:w}=__require$1(`string_decoder`),E=Symbol(`last`),D=Symbol(`decoder`);function O(e,t,S){let w;if(this.overflow){if(w=this[D].write(e).split(this.matcher),w.length===1)return S();w.shift(),this.overflow=!1}else this[E]+=this[D].write(e),w=this[E].split(this.matcher);this[E]=w.pop();for(let e=0;e<w.length;e++)try{j(this,this.mapper(w[e]))}catch(e){return S(e)}if(this.overflow=this[E].length>this.maxLength,this.overflow&&!this.skipOverflow){S(Error(`maximum buffer reached`));return}S()}function k(e){if(this[E]+=this[D].end(),this[E])try{j(this,this.mapper(this[E]))}catch(t){return e(t)}e()}function j(e,t){t!==void 0&&e.push(t)}function F(e){return e}function L(e,t,j){switch(e||=/\r?\n/,t||=F,j||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(j=e,e=/\r?\n/);break;case 2:typeof e==`function`?(j=t,t=e,e=/\r?\n/):typeof t==`object`&&(j=t,t=F)}j=Object.assign({},j),j.autoDestroy=!0,j.transform=O,j.flush=k,j.readableObjectMode=!0;let L=new S(j);return L[E]=``,L[D]=new w(`utf8`),L.matcher=e,L.mapper=t,L.maxLength=j.maxLength,L.skipOverflow=j.skipOverflow||!1,L.overflow=!1,L._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},L}t.exports=L})),require_pino_abstract_transport=__commonJSMin$1(((e,t)=>{let S=Symbol.for(`pino.metadata`),w=require_split2(),{Duplex:E}=__require$1(`stream`),{parentPort:D,workerData:O}=__require$1(`worker_threads`);function k(){let e,t,S=new Promise((S,w)=>{e=S,t=w});return S.resolve=e,S.reject=t,S}t.exports=function(e,t={}){let F=t.expectPinoConfig===!0&&O?.workerData?.pinoWillSendConfig===!0,L=t.parse===`lines`,B=typeof t.parseLine==`function`?t.parseLine:JSON.parse,H=t.close||j,q=w(function(e){let t;try{t=B(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),q[S]&&(q.lastTime=t.time,q.lastLevel=t.level,q.lastObj=t),L?e:t},{autoDestroy:!0});if(q._destroy=function(e,t){let S=H(e,t);S&&typeof S.then==`function`&&S.then(t,t)},t.expectPinoConfig===!0&&O?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{q.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(q[S]=!0,q.lastTime=0,q.lastLevel=0,q.lastObj=null),F){let e={},t=k();return D.on(`message`,function S(w){w.code===`PINO_CONFIG`&&(e=w.config,t.resolve(),D.off(`message`,S))}),Object.defineProperties(q,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(J)}return J();function J(){let S=e(q);if(S&&typeof S.catch==`function`)S.catch(e=>{q.destroy(e)}),S=null;else if(t.enablePipelining&&S)return E.from({writable:q,readable:S});return q}};function j(e,t){process.nextTick(t,e)}})),require_constants$6=__commonJSMin$1(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),require_get_level_label_data=__commonJSMin$1(((e,t)=>{t.exports=E;let{LEVELS:S,LEVEL_NAMES:w}=require_constants$6();function E(e,t,E){let D=e?t||S:Object.assign({},S,t),O=e?E||w:Object.assign({},w,E);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(D,e)?e:t:Object.prototype.hasOwnProperty.call(O,e.toLowerCase())?O[e.toLowerCase()]:t,[D[t],t]}}})),require_colors=__commonJSMin$1(((e,t)=>{let S=e=>e,w={default:S,60:S,50:S,40:S,30:S,20:S,10:S,message:S,greyMessage:S,property:S},{createColors:E}=require_colorette(),D=require_get_level_label_data(),O=E({useColor:!0}),{white:k,bgRed:j,red:F,yellow:L,green:B,blue:H,gray:q,cyan:J,magenta:Y}=O,ee={default:k,60:j,50:F,40:L,30:B,20:H,10:q,message:J,greyMessage:q,property:Y};function te(e){return e.reduce(function(e,[t,S]){return e[t]=typeof O[S]==`function`?O[S]:k,e},{default:k,message:J,greyMessage:q,property:Y})}function ne(e){return function(t,S,{customLevels:w,customLevelNames:E}={}){let[O,k]=D(e,w,E)(t);return Object.prototype.hasOwnProperty.call(S,k)?S[k](O):S.default(O)}}function ae(e){let t=ne(e),S=function(e,S){return t(e,w,S)};return S.message=w.message,S.greyMessage=w.greyMessage,S.property=w.property,S.colors=E({useColor:!1}),S}function oe(e){let t=ne(e),S=function(e,S){return t(e,ee,S)};return S.message=ee.message,S.property=ee.property,S.greyMessage=ee.greyMessage,S.colors=O,S}function se(e,t){let S=te(e),w=t?S:Object.assign({},ee,S),E=ne(t),D=function(e,t){return E(e,w,t)};return D.colors=O,D.message=D.message||w.message,D.property=D.property||w.property,D.greyMessage=D.greyMessage||w.greyMessage,D}t.exports=function(e=!1,t,S){return e&&t!==void 0?se(t,S):e?oe(S):ae(S)}})),require_noop=__commonJSMin$1(((e,t)=>{t.exports=function(){}})),require_build_safe_sonic_boom=__commonJSMin$1(((e,t)=>{t.exports=D;let{isMainThread:S}=__require$1(`node:worker_threads`),w=require_sonic_boom(),E=require_noop();function D(e){let t=new w(e);return t.on(`error`,D),!e.sync&&S&&O(t),t;function D(e){if(e.code===`EPIPE`){t.write=E,t.end=E,t.flushSync=E,t.destroy=E;return}t.removeListener(`error`,D)}}function O(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=require_on_exit_leak_free();t.register(e,k),e.on(`close`,function(){t.unregister(e)})}}function k(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),require_is_valid_date=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),require_create_date=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_is_valid_date();function w(e){let t=new Date(e);return S(t)||(t=new Date(+e)),t}})),require_split_property_key=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){let t=[],S=!1,w=``;for(let E=0;E<e.length;E++){let D=e.charAt(E);if(D===`\\`){S=!0;continue}if(S){S=!1,w+=D;continue}if(D===`.`){t.push(w),w=``;continue}w+=D}return w.length&&t.push(w),t}})),require_get_property_value=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_split_property_key();function w(e,t){let w=Array.isArray(t)?t:S(t);for(let t of w){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),require_delete_log_property=__commonJSMin$1(((e,t)=>{t.exports=E;let S=require_get_property_value(),w=require_split_property_key();function E(e,t){let E=w(t),D=E.pop();e=S(e,E),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,D)&&delete e[D]}})),require_cjs=__commonJSMin$1((e=>{let t=Function.prototype.toString,S=Object.prototype.toString;function w(e){if(!e)return Object.create(null);let S=e.constructor;if(S===Object)return e===Object.prototype?{}:Object.create(e);if(S&&~t.call(S).indexOf(`[native code]`))try{return new S}catch{}return Object.create(e)}function E(e){let t=e[Symbol.toStringTag];if(t)return t;let w=S.call(e);return w.substring(8,w.length-1)}let{hasOwnProperty:D,propertyIsEnumerable:O}=Object.prototype;function k(e,t,S,w){let E=Object.getOwnPropertyDescriptor(e,S)||{configurable:!0,enumerable:!0,value:e[S],writable:!0},D=E.get||E.set?E:{configurable:E.configurable,enumerable:E.enumerable,value:w.copier(E.value,w),writable:E.writable};try{Object.defineProperty(t,S,D)}catch{t[S]=D.get?D.get():D.value}}function j(e,t,S){let w=Object.getOwnPropertyNames(e);for(let E=0;E<w.length;++E)k(e,t,w[E],S);let E=Object.getOwnPropertySymbols(e);for(let w=0;w<E.length;++w)k(e,t,E[w],S);return t}function F(e,t){let S=new t.Constructor;t.cache.set(e,S);for(let w=0;w<e.length;++w)S[w]=t.copier(e[w],t);return S}function L(e,t){let S=new t.Constructor;return t.cache.set(e,S),j(e,S,t)}function B(e,t){return e.slice(0)}function H(e,t){return e.slice(0,e.size,e.type)}function q(e,t){return new t.Constructor(B(e.buffer))}function J(e,t){return new t.Constructor(e.getTime())}function Y(e,t){let S=new t.Constructor;return t.cache.set(e,S),e.forEach((e,w)=>{S.set(w,t.copier(e,t))}),S}function ee(e,t){return j(e,Y(e,t),t)}function te(e,t){let S=w(t.prototype);t.cache.set(e,S);for(let w in e)D.call(e,w)&&(S[w]=t.copier(e[w],t));let E=Object.getOwnPropertySymbols(e);for(let w=0;w<E.length;++w){let D=E[w];O.call(e,D)&&(S[D]=t.copier(e[D],t))}return S}function ne(e,t){let S=w(t.prototype);return t.cache.set(e,S),j(e,S,t)}function ae(e,t){return new t.Constructor(e.valueOf())}function oe(e,t){let S=new t.Constructor(e.source,e.flags);return S.lastIndex=e.lastIndex,S}function se(e,t){return e}function ce(e,t){let S=new t.Constructor;return t.cache.set(e,S),e.forEach(e=>{S.add(t.copier(e,t))}),S}function ue(e,t){return j(e,ce(e,t),t)}function de(){return new WeakMap}function fe({createCache:e,methods:t,strict:S}){let w={array:S?L:F,arrayBuffer:B,asyncGenerator:se,blob:H,dataView:q,date:J,error:se,generator:se,map:S?ee:Y,object:S?ne:te,regExp:oe,set:S?ue:ce},E=t?Object.assign(w,t):w,D=me(E),O=e||de;if(!D.Object||!D.Array)throw Error(`An object and array copier must be provided.`);return{createCache:O,copiers:D,methods:E,strict:!!S}}function me(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:ae,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:ae,Object:e.object,Promise:se,RegExp:e.regExp,Set:e.set,String:ae,WeakMap:se,WeakSet:se,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function ge(e={}){let{createCache:t,copiers:S}=fe(e),{Array:w,Object:D}=S;function O(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return D(e,t);if(Array.isArray(e))return w(e,t);let O=S[E(e)];return O?O(e,t):typeof e.then==`function`?e:D(e,t)}return function(e){return O(e,{Constructor:void 0,cache:t(),copier:O,prototype:void 0})}}let _e=ge({strict:!0});e.copy=ge(),e.copyStrict=_e,e.createCopier=ge})),require_filter_log=__commonJSMin$1(((e,t)=>{t.exports=D;let{createCopier:S}=require_cjs(),w=S({}),E=require_delete_log_property();function D({log:e,context:t}){let{ignoreKeys:S,includeKeys:D}=t,O=w(e);if(D){let e={};return D.forEach(t=>{e[t]=O[t]}),e}return S.forEach(e=>{E(O,e)}),O}})),require_dateformat=__commonJSMin$1(((e,t)=>{function S(e){"@babel/helpers - typeof";return S=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},S(e)}(function(w){var E=arguments,D=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,S=/[^-+\dA-Z]/g;return function(w,B,H,q){if(E.length===1&&L(w)===`string`&&!/\d/.test(w)&&(B=w,w=void 0),w=w||w===0?w:new Date,w instanceof Date||(w=new Date(w)),isNaN(w))throw TypeError(`Invalid date`);B=String(D.masks[B]||B||D.masks.default);var J=B.slice(0,4);(J===`UTC:`||J===`GMT:`)&&(B=B.slice(4),H=!0,J===`GMT:`&&(q=!0));var Y=function(){return H?`getUTC`:`get`},ee=function(){return w[Y()+`Date`]()},te=function(){return w[Y()+`Day`]()},ne=function(){return w[Y()+`Month`]()},ae=function(){return w[Y()+`FullYear`]()},oe=function(){return w[Y()+`Hours`]()},se=function(){return w[Y()+`Minutes`]()},ce=function(){return w[Y()+`Seconds`]()},ue=function(){return w[Y()+`Milliseconds`]()},de=function(){return H?0:w.getTimezoneOffset()},fe=function(){return j(w)},me=function(){return F(w)},ge={d:function(){return ee()},dd:function(){return O(ee())},ddd:function(){return D.i18n.dayNames[te()]},DDD:function(){return k({y:ae(),m:ne(),d:ee(),_:Y(),dayName:D.i18n.dayNames[te()],short:!0})},dddd:function(){return D.i18n.dayNames[te()+7]},DDDD:function(){return k({y:ae(),m:ne(),d:ee(),_:Y(),dayName:D.i18n.dayNames[te()+7]})},m:function(){return ne()+1},mm:function(){return O(ne()+1)},mmm:function(){return D.i18n.monthNames[ne()]},mmmm:function(){return D.i18n.monthNames[ne()+12]},yy:function(){return String(ae()).slice(2)},yyyy:function(){return O(ae(),4)},h:function(){return oe()%12||12},hh:function(){return O(oe()%12||12)},H:function(){return oe()},HH:function(){return O(oe())},M:function(){return se()},MM:function(){return O(se())},s:function(){return ce()},ss:function(){return O(ce())},l:function(){return O(ue(),3)},L:function(){return O(Math.floor(ue()/10))},t:function(){return oe()<12?D.i18n.timeNames[0]:D.i18n.timeNames[1]},tt:function(){return oe()<12?D.i18n.timeNames[2]:D.i18n.timeNames[3]},T:function(){return oe()<12?D.i18n.timeNames[4]:D.i18n.timeNames[5]},TT:function(){return oe()<12?D.i18n.timeNames[6]:D.i18n.timeNames[7]},Z:function(){return q?`GMT`:H?`UTC`:(String(w).match(t)||[``]).pop().replace(S,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(de()>0?`-`:`+`)+O(Math.floor(Math.abs(de())/60)*100+Math.abs(de())%60,4)},p:function(){return(de()>0?`-`:`+`)+O(Math.floor(Math.abs(de())/60),2)+`:`+O(Math.floor(Math.abs(de())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][ee()%10>3?0:(ee()%100-ee()%10!=10)*ee()%10]},W:function(){return fe()},WW:function(){return O(fe())},N:function(){return me()}};return B.replace(e,function(e){return e in ge?ge[e]():e.slice(1,e.length-1)})}}();D.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},D.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var O=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},k=function(e){var t=e.y,S=e.m,w=e.d,E=e._,D=e.dayName,O=e.short,k=O===void 0?!1:O,j=new Date,F=new Date;F.setDate(F[E+`Date`]()-1);var L=new Date;return L.setDate(L[E+`Date`]()+1),function(){return j[E+`FullYear`]()}()===t&&function(){return j[E+`Month`]()}()===S&&function(){return j[E+`Date`]()}()===w?k?`Tdy`:`Today`:function(){return F[E+`FullYear`]()}()===t&&function(){return F[E+`Month`]()}()===S&&function(){return F[E+`Date`]()}()===w?k?`Ysd`:`Yesterday`:function(){return L[E+`FullYear`]()}()===t&&function(){return L[E+`Month`]()}()===S&&function(){return L[E+`Date`]()}()===w?k?`Tmw`:`Tomorrow`:D},j=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var S=new Date(t.getFullYear(),0,4);S.setDate(S.getDate()-(S.getDay()+6)%7+3);var w=t.getTimezoneOffset()-S.getTimezoneOffset();t.setHours(t.getHours()-w);var E=(t-S)/(864e5*7);return 1+Math.floor(E)},F=function(e){var t=e.getDay();return t===0&&(t=7),t},L=function(e){return e===null?`null`:e===void 0?`undefined`:S(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():S(e)};typeof define==`function`&&define.amd?define(function(){return D}):(e===void 0?`undefined`:S(e))===`object`?t.exports=D:w.dateFormat=D})(void 0)})),require_format_time=__commonJSMin$1(((e,t)=>{t.exports=k;let{DATE_FORMAT:S,DATE_FORMAT_SIMPLE:w}=require_constants$6(),E=require_dateformat(),D=require_create_date(),O=require_is_valid_date();function k(e,t=!1){if(t===!1)return e;let k=D(e);if(!O(k))return e;if(t===!0)return E(k,w);let j=t.toUpperCase();if(j===`SYS:STANDARD`)return E(k,S);let F=j.substr(0,4);return F===`SYS:`||F===`UTC:`?F===`UTC:`?E(k,t):E(k,t.slice(4)):E(k,`UTC:${t}`)}})),require_handle_custom_levels_names_opts=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,S)=>{let[w,E=S]=t.split(`:`);return e[w.toLowerCase()]=E,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,S)=>(t[S.toLowerCase()]=e[S],t),{}):{}:{}}})),require_handle_custom_levels_opts=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,S)=>{let[w,E=S]=t.split(`:`);return e[E]=w.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,S)=>(t[e[S]]=S.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),require_interpret_conditionals=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_get_property_value();function w(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,w),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function w(e,w,E){let D=S(t,w);return D&&E.includes(w)?E.replace(RegExp(`{`+w+`}`,`g`),D):``}}})),require_is_object=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),require_join_lines_with_indentation=__commonJSMin$1(((e,t)=>{t.exports=S;function S({input:e,ident:t=` `,eol:S=`
|
|
431
|
+
`)){let e=S.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let w;try{w=JSON.parse(e.slice(10))}catch{continue}if(typeof w!=`object`||!w)continue;let E=parseOkActorObject(w);E&&t.push(E)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let S=stripLineBreaks(e);if(t.length===0)return S;if(t.length>=2)return`${S} (${t.length} edits)`;let[w]=t;if(w===void 0)return S;let E=stripLineBreaks(w),D=`${S} — ${E}`;if(D.length<=72)return D;let O=`${S} — `,k=72-O.length-1;return k<=0?D.slice(0,72):`${O}${E.slice(0,k)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_colorette=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=__require$1(`tty`);function S(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(S){if(S!==`default`){var w=Object.getOwnPropertyDescriptor(e,S);Object.defineProperty(t,S,w.get?w:{enumerable:!0,get:function(){return e[S]}})}}),t.default=e,Object.freeze(t)}var w=S(t);let{env:E={},argv:D=[],platform:O=``}=typeof process>`u`?{}:process,k=`NO_COLOR`in E||D.includes(`--no-color`),j=`FORCE_COLOR`in E||D.includes(`--color`),F=O===`win32`,L=E.TERM===`dumb`,B=w&&w.isatty&&w.isatty(1)&&E.TERM&&!L,H=`CI`in E&&(`GITHUB_ACTIONS`in E||`GITLAB_CI`in E||`CIRCLECI`in E),q=!k&&(j||F&&!L||B||H),J=(e,t,S,w,E=t.substring(0,e)+w,D=t.substring(e+S.length),O=D.indexOf(S))=>E+(O<0?D:J(O,D,S,w)),Y=(e,t,S,w,E)=>e<0?S+t+w:S+J(e,t,w,E)+w,ee=(e,t,S=e,w=e.length+1)=>E=>E||!(E===``||E===void 0)?Y((``+E).indexOf(t,w),E,e,t,S):``,te=(e,t,S)=>ee(`\x1b[${e}m`,`\x1b[${t}m`,S),ne={reset:te(0,0),bold:te(1,22,`\x1B[22m\x1B[1m`),dim:te(2,22,`\x1B[22m\x1B[2m`),italic:te(3,23),underline:te(4,24),inverse:te(7,27),hidden:te(8,28),strikethrough:te(9,29),black:te(30,39),red:te(31,39),green:te(32,39),yellow:te(33,39),blue:te(34,39),magenta:te(35,39),cyan:te(36,39),white:te(37,39),gray:te(90,39),bgBlack:te(40,49),bgRed:te(41,49),bgGreen:te(42,49),bgYellow:te(43,49),bgBlue:te(44,49),bgMagenta:te(45,49),bgCyan:te(46,49),bgWhite:te(47,49),blackBright:te(90,39),redBright:te(91,39),greenBright:te(92,39),yellowBright:te(93,39),blueBright:te(94,39),magentaBright:te(95,39),cyanBright:te(96,39),whiteBright:te(97,39),bgBlackBright:te(100,49),bgRedBright:te(101,49),bgGreenBright:te(102,49),bgYellowBright:te(103,49),bgBlueBright:te(104,49),bgMagentaBright:te(105,49),bgCyanBright:te(106,49),bgWhiteBright:te(107,49)},ae=({useColor:e=q}={})=>e?ne:Object.keys(ne).reduce((e,t)=>({...e,[t]:String}),{}),{reset:oe,bold:se,dim:ce,italic:ue,underline:de,inverse:fe,hidden:me,strikethrough:ge,black:_e,red:ve,green:ye,yellow:Ce,blue:we,magenta:Te,cyan:De,white:je,gray:Me,bgBlack:Pe,bgRed:Ie,bgGreen:Re,bgYellow:ze,bgBlue:Be,bgMagenta:Ve,bgCyan:Ue,bgWhite:We,blackBright:Ge,redBright:Ke,greenBright:Xe,yellowBright:$e,blueBright:nt,magentaBright:rt,cyanBright:it,whiteBright:at,bgBlackBright:st,bgRedBright:vt,bgGreenBright:Tt,bgYellowBright:Et,bgBlueBright:Dt,bgMagentaBright:jt,bgCyanBright:Mt,bgWhiteBright:Ft}=ae();e.bgBlack=Pe,e.bgBlackBright=st,e.bgBlue=Be,e.bgBlueBright=Dt,e.bgCyan=Ue,e.bgCyanBright=Mt,e.bgGreen=Re,e.bgGreenBright=Tt,e.bgMagenta=Ve,e.bgMagentaBright=jt,e.bgRed=Ie,e.bgRedBright=vt,e.bgWhite=We,e.bgWhiteBright=Ft,e.bgYellow=ze,e.bgYellowBright=Et,e.black=_e,e.blackBright=Ge,e.blue=we,e.blueBright=nt,e.bold=se,e.createColors=ae,e.cyan=De,e.cyanBright=it,e.dim=ce,e.gray=Me,e.green=ye,e.greenBright=Xe,e.hidden=me,e.inverse=fe,e.isColorSupported=q,e.italic=ue,e.magenta=Te,e.magentaBright=rt,e.red=ve,e.redBright=Ke,e.reset=oe,e.strikethrough=ge,e.underline=de,e.white=je,e.whiteBright=at,e.yellow=Ce,e.yellowBright=$e})),require_wrappy=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e,t){if(e&&t)return S(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){w[t]=e[t]}),w;function w(){for(var t=Array(arguments.length),S=0;S<t.length;S++)t[S]=arguments[S];var w=e.apply(this,t),E=t[t.length-1];return typeof w==`function`&&w!==E&&Object.keys(E).forEach(function(e){w[e]=E[e]}),w}}})),require_once=__commonJSMin$1(((e,t)=>{var S=require_wrappy();t.exports=S(w),t.exports.strict=S(E),w.proto=w(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return w(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return E(this)},configurable:!0})});function w(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function E(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),require_end_of_stream=__commonJSMin$1(((e,t)=>{var S=require_once(),w=function(){},E=global.Bare?queueMicrotask:process.nextTick.bind(process),D=function(e){return e.setHeader&&typeof e.abort==`function`},O=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},k=function(e,t,j){if(typeof t==`function`)return k(e,null,t);t||={},j=S(j||w);var F=e._writableState,L=e._readableState,B=t.readable||t.readable!==!1&&e.readable,H=t.writable||t.writable!==!1&&e.writable,q=!1,J=function(){e.writable||Y()},Y=function(){H=!1,B||j.call(e)},ee=function(){B=!1,H||j.call(e)},te=function(t){j.call(e,t?Error(`exited with error code: `+t):null)},ne=function(t){j.call(e,t)},ae=function(){E(oe)},oe=function(){if(!q&&(B&&!(L&&L.ended&&!L.destroyed)||H&&!(F&&F.ended&&!F.destroyed)))return j.call(e,Error(`premature close`))},se=function(){e.req.on(`finish`,Y)};return D(e)?(e.on(`complete`,Y),e.on(`abort`,ae),e.req?se():e.on(`request`,se)):H&&!F&&(e.on(`end`,J),e.on(`close`,J)),O(e)&&e.on(`exit`,te),e.on(`end`,ee),e.on(`finish`,Y),t.error!==!1&&e.on(`error`,ne),e.on(`close`,ae),function(){q=!0,e.removeListener(`complete`,Y),e.removeListener(`abort`,ae),e.removeListener(`request`,se),e.req&&e.req.removeListener(`finish`,Y),e.removeListener(`end`,J),e.removeListener(`close`,J),e.removeListener(`finish`,Y),e.removeListener(`exit`,te),e.removeListener(`end`,ee),e.removeListener(`error`,ne),e.removeListener(`close`,ae)}};t.exports=k})),require_pump=__commonJSMin$1(((e,t)=>{var S=require_once(),w=require_end_of_stream(),E;try{E=__require$1(`fs`)}catch{}var D=function(){},O=typeof process>`u`?!1:/^v?\.0/.test(process.version),k=function(e){return typeof e==`function`},j=function(e){return!O||!E?!1:(e instanceof(E.ReadStream||D)||e instanceof(E.WriteStream||D))&&k(e.close)},F=function(e){return e.setHeader&&k(e.abort)},L=function(e,t,E,O){O=S(O);var L=!1;e.on(`close`,function(){L=!0}),w(e,{readable:t,writable:E},function(e){if(e)return O(e);L=!0,O()});var B=!1;return function(t){if(!L&&!B){if(B=!0,j(e))return e.close(D);if(F(e))return e.abort();if(k(e.destroy))return e.destroy();O(t||Error(`stream was destroyed`))}}},B=function(e){e()},H=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=k(e[e.length-1]||D)&&e.pop()||D;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var S,w=e.map(function(E,D){var O=D<e.length-1;return L(E,O,D>0,function(e){S||=e,e&&w.forEach(B),!O&&(w.forEach(B),t(S))})});return e.reduce(H)}})),require_split2=__commonJSMin$1(((e,t)=>{let{Transform:S}=__require$1(`stream`),{StringDecoder:w}=__require$1(`string_decoder`),E=Symbol(`last`),D=Symbol(`decoder`);function O(e,t,S){let w;if(this.overflow){if(w=this[D].write(e).split(this.matcher),w.length===1)return S();w.shift(),this.overflow=!1}else this[E]+=this[D].write(e),w=this[E].split(this.matcher);this[E]=w.pop();for(let e=0;e<w.length;e++)try{j(this,this.mapper(w[e]))}catch(e){return S(e)}if(this.overflow=this[E].length>this.maxLength,this.overflow&&!this.skipOverflow){S(Error(`maximum buffer reached`));return}S()}function k(e){if(this[E]+=this[D].end(),this[E])try{j(this,this.mapper(this[E]))}catch(t){return e(t)}e()}function j(e,t){t!==void 0&&e.push(t)}function F(e){return e}function L(e,t,j){switch(e||=/\r?\n/,t||=F,j||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(j=e,e=/\r?\n/);break;case 2:typeof e==`function`?(j=t,t=e,e=/\r?\n/):typeof t==`object`&&(j=t,t=F)}j=Object.assign({},j),j.autoDestroy=!0,j.transform=O,j.flush=k,j.readableObjectMode=!0;let L=new S(j);return L[E]=``,L[D]=new w(`utf8`),L.matcher=e,L.mapper=t,L.maxLength=j.maxLength,L.skipOverflow=j.skipOverflow||!1,L.overflow=!1,L._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},L}t.exports=L})),require_pino_abstract_transport=__commonJSMin$1(((e,t)=>{let S=Symbol.for(`pino.metadata`),w=require_split2(),{Duplex:E}=__require$1(`stream`),{parentPort:D,workerData:O}=__require$1(`worker_threads`);function k(){let e,t,S=new Promise((S,w)=>{e=S,t=w});return S.resolve=e,S.reject=t,S}t.exports=function(e,t={}){let F=t.expectPinoConfig===!0&&O?.workerData?.pinoWillSendConfig===!0,L=t.parse===`lines`,B=typeof t.parseLine==`function`?t.parseLine:JSON.parse,H=t.close||j,q=w(function(e){let t;try{t=B(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),q[S]&&(q.lastTime=t.time,q.lastLevel=t.level,q.lastObj=t),L?e:t},{autoDestroy:!0});if(q._destroy=function(e,t){let S=H(e,t);S&&typeof S.then==`function`&&S.then(t,t)},t.expectPinoConfig===!0&&O?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{q.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(q[S]=!0,q.lastTime=0,q.lastLevel=0,q.lastObj=null),F){let e={},t=k();return D.on(`message`,function S(w){w.code===`PINO_CONFIG`&&(e=w.config,t.resolve(),D.off(`message`,S))}),Object.defineProperties(q,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(J)}return J();function J(){let S=e(q);if(S&&typeof S.catch==`function`)S.catch(e=>{q.destroy(e)}),S=null;else if(t.enablePipelining&&S)return E.from({writable:q,readable:S});return q}};function j(e,t){process.nextTick(t,e)}})),require_constants$6=__commonJSMin$1(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),require_get_level_label_data=__commonJSMin$1(((e,t)=>{t.exports=E;let{LEVELS:S,LEVEL_NAMES:w}=require_constants$6();function E(e,t,E){let D=e?t||S:Object.assign({},S,t),O=e?E||w:Object.assign({},w,E);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(D,e)?e:t:Object.prototype.hasOwnProperty.call(O,e.toLowerCase())?O[e.toLowerCase()]:t,[D[t],t]}}})),require_colors=__commonJSMin$1(((e,t)=>{let S=e=>e,w={default:S,60:S,50:S,40:S,30:S,20:S,10:S,message:S,greyMessage:S,property:S},{createColors:E}=require_colorette(),D=require_get_level_label_data(),O=E({useColor:!0}),{white:k,bgRed:j,red:F,yellow:L,green:B,blue:H,gray:q,cyan:J,magenta:Y}=O,ee={default:k,60:j,50:F,40:L,30:B,20:H,10:q,message:J,greyMessage:q,property:Y};function te(e){return e.reduce(function(e,[t,S]){return e[t]=typeof O[S]==`function`?O[S]:k,e},{default:k,message:J,greyMessage:q,property:Y})}function ne(e){return function(t,S,{customLevels:w,customLevelNames:E}={}){let[O,k]=D(e,w,E)(t);return Object.prototype.hasOwnProperty.call(S,k)?S[k](O):S.default(O)}}function ae(e){let t=ne(e),S=function(e,S){return t(e,w,S)};return S.message=w.message,S.greyMessage=w.greyMessage,S.property=w.property,S.colors=E({useColor:!1}),S}function oe(e){let t=ne(e),S=function(e,S){return t(e,ee,S)};return S.message=ee.message,S.property=ee.property,S.greyMessage=ee.greyMessage,S.colors=O,S}function se(e,t){let S=te(e),w=t?S:Object.assign({},ee,S),E=ne(t),D=function(e,t){return E(e,w,t)};return D.colors=O,D.message=D.message||w.message,D.property=D.property||w.property,D.greyMessage=D.greyMessage||w.greyMessage,D}t.exports=function(e=!1,t,S){return e&&t!==void 0?se(t,S):e?oe(S):ae(S)}})),require_atomic_sleep=__commonJSMin$1(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function S(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=S}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin$1(((e,t)=>{let S=__require$1(`fs`),w=__require$1(`events`),E=__require$1(`util`).inherits,D=__require$1(`path`),O=require_atomic_sleep(),k=__require$1(`assert`),j=100,F=Buffer.allocUnsafe(0),L=16*1024,B=`buffer`,H=`utf8`,[q,J]=(process.versions.node||`0.0`).split(`.`).map(Number),Y=q>=22&&J>=7;function ee(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function w(S,w){if(S){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,S)}):t.emit(`error`,S);return}let E=t._reopening;t.fd=w,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():E&&process.nextTick(()=>t.emit(`drain`)))}let E=t.append?`a`:`w`,O=t.mode;if(t.sync)try{t.mkdir&&S.mkdirSync(D.dirname(e),{recursive:!0}),w(null,S.openSync(e,E,O))}catch(e){throw w(e),e}else t.mkdir?S.mkdir(D.dirname(e),{recursive:!0},t=>{if(t)return w(t);S.open(e,E,O,w)}):S.open(e,E,O,w)}function te(e){if(!(this instanceof te))return new te(e);let{fd:t,dest:w,minLength:E,maxLength:D,maxWrite:k,periodicFlush:j,sync:L,append:q=!0,mkdir:J,retryEAGAIN:Y,fsync:oe,contentMode:ue,mode:Ce}=e||{};t||=w,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(E||0,16387),this.file=null,this.destroyed=!1,this.minLength=E||0,this.maxLength=D||0,this.maxWrite=k||16384,this._periodicFlush=j||0,this._periodicFlushTimer=void 0,this.sync=L||!1,this.writable=!0,this._fsync=oe||!1,this.append=q||!1,this.mode=Ce,this.retryEAGAIN=Y||(()=>!0),this.mkdir=J||!1;let we,Te;if(ue===B)this._writingBuf=F,this.write=ce,this.flush=fe,this.flushSync=ge,this._actualWrite=ve,we=()=>S.writeSync(this.fd,this._writingBuf),Te=()=>S.write(this.fd,this._writingBuf,this.release);else if(ue===void 0||ue===H)this._writingBuf=``,this.write=se,this.flush=de,this.flushSync=me,this._actualWrite=_e,we=()=>Buffer.isBuffer(this._writingBuf)?S.writeSync(this.fd,this._writingBuf):S.writeSync(this.fd,this._writingBuf,`utf8`),Te=()=>Buffer.isBuffer(this._writingBuf)?S.write(this.fd,this._writingBuf,this.release):S.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${H}" and "${B}", but passed ${ue}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)ee(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{O(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(Te,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let w=ne(this._writingBuf,this._len,t);if(this._len=w.len,this._writingBuf=w.writingBuf,this._writingBuf.length){if(!this.sync){Te();return}try{do{let e=we(),t=ne(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&S.fsyncSync(this.fd);let E=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):E>this.minLength?this._actualWrite():this._ending?E>0?this._actualWrite():(this._writing=!1,ye(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(ae,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function ne(e,t,S){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-S,0),e=e.subarray(S),{writingBuf:e,len:t}}function ae(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}E(te,w);function oe(e,t){return e.length===0?F:e.length===1?e[0]:Buffer.concat(e,t)}function se(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),S=this._len+t,w=this._bufs;return this.maxLength&&S>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(w.length===0||Buffer.byteLength(w[w.length-1])+t>this.maxWrite?w.push(e):w[w.length-1]+=e,this._len=S,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function ce(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,S=this._bufs,w=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(S.length===0||w[w.length-1]+e.length>this.maxWrite?(S.push([e]),w.push(e.length)):(S[S.length-1].push(e),w[w.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function ue(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{S.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,w)},w=S=>{this._flushPending=!1,e(S),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,w)}function de(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&ue.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function fe(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&ue.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&S.close(t,e=>{if(e)return this.emit(`error`,e)})}),ee(this.file,this)},te.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():ye(this)))};function me(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?S.writeSync(this.fd,e):S.writeSync(this.fd,e,`utf8`),w=ne(e,this._len,t);e=w.writingBuf,this._len=w.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;O(100)}}try{S.fsyncSync(this.fd)}catch{}}function ge(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=F);let e=F;for(;this._bufs.length||e.length;){e.length<=0&&(e=oe(this._bufs[0],this._lens[0]));try{let t=S.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;O(100)}}}te.prototype.destroy=function(){this.destroyed||ye(this)};function _e(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?S.writeSync(this.fd,this._writingBuf):S.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else S.write(this.fd,this._writingBuf,e)}function ve(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:oe(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,S.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else Y&&(this._writingBuf=Buffer.from(this._writingBuf)),S.write(this.fd,this._writingBuf,e)}function ye(e){if(e.fd===-1){e.once(`ready`,ye.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],k(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{S.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?S.close(e.fd,w):w()}function w(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}te.SonicBoom=te,te.default=te,t.exports=te})),require_noop=__commonJSMin$1(((e,t)=>{t.exports=function(){}})),require_on_exit_leak_free=__commonJSMin$1(((e,t)=>{let S={exit:[],beforeExit:[]},w={exit:j,beforeExit:F},E;function D(){E===void 0&&(E=new FinalizationRegistry(B))}function O(e){S[e].length>0||process.on(e,w[e])}function k(e){S[e].length>0||(process.removeListener(e,w[e]),S.exit.length===0&&S.beforeExit.length===0&&(E=void 0))}function j(){L(`exit`)}function F(){L(`beforeExit`)}function L(e){for(let t of S[e]){let S=t.deref(),w=t.fn;S!==void 0&&w(S,e)}S[e]=[]}function B(e){for(let t of[`exit`,`beforeExit`]){let w=S[t].indexOf(e);S[t].splice(w,w+1),k(t)}}function H(e,t,w){if(t===void 0)throw Error(`the object can't be undefined`);O(e);let k=new WeakRef(t);k.fn=w,D(),E.register(t,k),S[e].push(k)}function q(e,t){H(`exit`,e,t)}function J(e,t){H(`beforeExit`,e,t)}function Y(e){if(E!==void 0){E.unregister(e);for(let t of[`exit`,`beforeExit`])S[t]=S[t].filter(t=>{let S=t.deref();return S&&S!==e}),k(t)}}t.exports={register:q,registerBeforeExit:J,unregister:Y}})),require_build_safe_sonic_boom=__commonJSMin$1(((e,t)=>{t.exports=D;let{isMainThread:S}=__require$1(`node:worker_threads`),w=require_sonic_boom(),E=require_noop();function D(e){let t=new w(e);return t.on(`error`,D),!e.sync&&S&&O(t),t;function D(e){if(e.code===`EPIPE`){t.write=E,t.end=E,t.flushSync=E,t.destroy=E;return}t.removeListener(`error`,D)}}function O(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=require_on_exit_leak_free();t.register(e,k),e.on(`close`,function(){t.unregister(e)})}}function k(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),require_is_valid_date=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),require_create_date=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_is_valid_date();function w(e){let t=new Date(e);return S(t)||(t=new Date(+e)),t}})),require_split_property_key=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){let t=[],S=!1,w=``;for(let E=0;E<e.length;E++){let D=e.charAt(E);if(D===`\\`){S=!0;continue}if(S){S=!1,w+=D;continue}if(D===`.`){t.push(w),w=``;continue}w+=D}return w.length&&t.push(w),t}})),require_get_property_value=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_split_property_key();function w(e,t){let w=Array.isArray(t)?t:S(t);for(let t of w){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),require_delete_log_property=__commonJSMin$1(((e,t)=>{t.exports=E;let S=require_get_property_value(),w=require_split_property_key();function E(e,t){let E=w(t),D=E.pop();e=S(e,E),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,D)&&delete e[D]}})),require_cjs=__commonJSMin$1((e=>{let t=Function.prototype.toString,S=Object.prototype.toString;function w(e){if(!e)return Object.create(null);let S=e.constructor;if(S===Object)return e===Object.prototype?{}:Object.create(e);if(S&&~t.call(S).indexOf(`[native code]`))try{return new S}catch{}return Object.create(e)}function E(e){let t=e[Symbol.toStringTag];if(t)return t;let w=S.call(e);return w.substring(8,w.length-1)}let{hasOwnProperty:D,propertyIsEnumerable:O}=Object.prototype;function k(e,t,S,w){let E=Object.getOwnPropertyDescriptor(e,S)||{configurable:!0,enumerable:!0,value:e[S],writable:!0},D=E.get||E.set?E:{configurable:E.configurable,enumerable:E.enumerable,value:w.copier(E.value,w),writable:E.writable};try{Object.defineProperty(t,S,D)}catch{t[S]=D.get?D.get():D.value}}function j(e,t,S){let w=Object.getOwnPropertyNames(e);for(let E=0;E<w.length;++E)k(e,t,w[E],S);let E=Object.getOwnPropertySymbols(e);for(let w=0;w<E.length;++w)k(e,t,E[w],S);return t}function F(e,t){let S=new t.Constructor;t.cache.set(e,S);for(let w=0;w<e.length;++w)S[w]=t.copier(e[w],t);return S}function L(e,t){let S=new t.Constructor;return t.cache.set(e,S),j(e,S,t)}function B(e,t){return e.slice(0)}function H(e,t){return e.slice(0,e.size,e.type)}function q(e,t){return new t.Constructor(B(e.buffer))}function J(e,t){return new t.Constructor(e.getTime())}function Y(e,t){let S=new t.Constructor;return t.cache.set(e,S),e.forEach((e,w)=>{S.set(w,t.copier(e,t))}),S}function ee(e,t){return j(e,Y(e,t),t)}function te(e,t){let S=w(t.prototype);t.cache.set(e,S);for(let w in e)D.call(e,w)&&(S[w]=t.copier(e[w],t));let E=Object.getOwnPropertySymbols(e);for(let w=0;w<E.length;++w){let D=E[w];O.call(e,D)&&(S[D]=t.copier(e[D],t))}return S}function ne(e,t){let S=w(t.prototype);return t.cache.set(e,S),j(e,S,t)}function ae(e,t){return new t.Constructor(e.valueOf())}function oe(e,t){let S=new t.Constructor(e.source,e.flags);return S.lastIndex=e.lastIndex,S}function se(e,t){return e}function ce(e,t){let S=new t.Constructor;return t.cache.set(e,S),e.forEach(e=>{S.add(t.copier(e,t))}),S}function ue(e,t){return j(e,ce(e,t),t)}function de(){return new WeakMap}function fe({createCache:e,methods:t,strict:S}){let w={array:S?L:F,arrayBuffer:B,asyncGenerator:se,blob:H,dataView:q,date:J,error:se,generator:se,map:S?ee:Y,object:S?ne:te,regExp:oe,set:S?ue:ce},E=t?Object.assign(w,t):w,D=me(E),O=e||de;if(!D.Object||!D.Array)throw Error(`An object and array copier must be provided.`);return{createCache:O,copiers:D,methods:E,strict:!!S}}function me(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:ae,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:ae,Object:e.object,Promise:se,RegExp:e.regExp,Set:e.set,String:ae,WeakMap:se,WeakSet:se,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function ge(e={}){let{createCache:t,copiers:S}=fe(e),{Array:w,Object:D}=S;function O(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return D(e,t);if(Array.isArray(e))return w(e,t);let O=S[E(e)];return O?O(e,t):typeof e.then==`function`?e:D(e,t)}return function(e){return O(e,{Constructor:void 0,cache:t(),copier:O,prototype:void 0})}}let _e=ge({strict:!0});e.copy=ge(),e.copyStrict=_e,e.createCopier=ge})),require_filter_log=__commonJSMin$1(((e,t)=>{t.exports=D;let{createCopier:S}=require_cjs(),w=S({}),E=require_delete_log_property();function D({log:e,context:t}){let{ignoreKeys:S,includeKeys:D}=t,O=w(e);if(D){let e={};return D.forEach(t=>{e[t]=O[t]}),e}return S.forEach(e=>{E(O,e)}),O}})),require_dateformat=__commonJSMin$1(((e,t)=>{function S(e){"@babel/helpers - typeof";return S=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},S(e)}(function(w){var E=arguments,D=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,S=/[^-+\dA-Z]/g;return function(w,B,H,q){if(E.length===1&&L(w)===`string`&&!/\d/.test(w)&&(B=w,w=void 0),w=w||w===0?w:new Date,w instanceof Date||(w=new Date(w)),isNaN(w))throw TypeError(`Invalid date`);B=String(D.masks[B]||B||D.masks.default);var J=B.slice(0,4);(J===`UTC:`||J===`GMT:`)&&(B=B.slice(4),H=!0,J===`GMT:`&&(q=!0));var Y=function(){return H?`getUTC`:`get`},ee=function(){return w[Y()+`Date`]()},te=function(){return w[Y()+`Day`]()},ne=function(){return w[Y()+`Month`]()},ae=function(){return w[Y()+`FullYear`]()},oe=function(){return w[Y()+`Hours`]()},se=function(){return w[Y()+`Minutes`]()},ce=function(){return w[Y()+`Seconds`]()},ue=function(){return w[Y()+`Milliseconds`]()},de=function(){return H?0:w.getTimezoneOffset()},fe=function(){return j(w)},me=function(){return F(w)},ge={d:function(){return ee()},dd:function(){return O(ee())},ddd:function(){return D.i18n.dayNames[te()]},DDD:function(){return k({y:ae(),m:ne(),d:ee(),_:Y(),dayName:D.i18n.dayNames[te()],short:!0})},dddd:function(){return D.i18n.dayNames[te()+7]},DDDD:function(){return k({y:ae(),m:ne(),d:ee(),_:Y(),dayName:D.i18n.dayNames[te()+7]})},m:function(){return ne()+1},mm:function(){return O(ne()+1)},mmm:function(){return D.i18n.monthNames[ne()]},mmmm:function(){return D.i18n.monthNames[ne()+12]},yy:function(){return String(ae()).slice(2)},yyyy:function(){return O(ae(),4)},h:function(){return oe()%12||12},hh:function(){return O(oe()%12||12)},H:function(){return oe()},HH:function(){return O(oe())},M:function(){return se()},MM:function(){return O(se())},s:function(){return ce()},ss:function(){return O(ce())},l:function(){return O(ue(),3)},L:function(){return O(Math.floor(ue()/10))},t:function(){return oe()<12?D.i18n.timeNames[0]:D.i18n.timeNames[1]},tt:function(){return oe()<12?D.i18n.timeNames[2]:D.i18n.timeNames[3]},T:function(){return oe()<12?D.i18n.timeNames[4]:D.i18n.timeNames[5]},TT:function(){return oe()<12?D.i18n.timeNames[6]:D.i18n.timeNames[7]},Z:function(){return q?`GMT`:H?`UTC`:(String(w).match(t)||[``]).pop().replace(S,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(de()>0?`-`:`+`)+O(Math.floor(Math.abs(de())/60)*100+Math.abs(de())%60,4)},p:function(){return(de()>0?`-`:`+`)+O(Math.floor(Math.abs(de())/60),2)+`:`+O(Math.floor(Math.abs(de())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][ee()%10>3?0:(ee()%100-ee()%10!=10)*ee()%10]},W:function(){return fe()},WW:function(){return O(fe())},N:function(){return me()}};return B.replace(e,function(e){return e in ge?ge[e]():e.slice(1,e.length-1)})}}();D.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},D.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var O=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},k=function(e){var t=e.y,S=e.m,w=e.d,E=e._,D=e.dayName,O=e.short,k=O===void 0?!1:O,j=new Date,F=new Date;F.setDate(F[E+`Date`]()-1);var L=new Date;return L.setDate(L[E+`Date`]()+1),function(){return j[E+`FullYear`]()}()===t&&function(){return j[E+`Month`]()}()===S&&function(){return j[E+`Date`]()}()===w?k?`Tdy`:`Today`:function(){return F[E+`FullYear`]()}()===t&&function(){return F[E+`Month`]()}()===S&&function(){return F[E+`Date`]()}()===w?k?`Ysd`:`Yesterday`:function(){return L[E+`FullYear`]()}()===t&&function(){return L[E+`Month`]()}()===S&&function(){return L[E+`Date`]()}()===w?k?`Tmw`:`Tomorrow`:D},j=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var S=new Date(t.getFullYear(),0,4);S.setDate(S.getDate()-(S.getDay()+6)%7+3);var w=t.getTimezoneOffset()-S.getTimezoneOffset();t.setHours(t.getHours()-w);var E=(t-S)/(864e5*7);return 1+Math.floor(E)},F=function(e){var t=e.getDay();return t===0&&(t=7),t},L=function(e){return e===null?`null`:e===void 0?`undefined`:S(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():S(e)};typeof define==`function`&&define.amd?define(function(){return D}):(e===void 0?`undefined`:S(e))===`object`?t.exports=D:w.dateFormat=D})(void 0)})),require_format_time=__commonJSMin$1(((e,t)=>{t.exports=k;let{DATE_FORMAT:S,DATE_FORMAT_SIMPLE:w}=require_constants$6(),E=require_dateformat(),D=require_create_date(),O=require_is_valid_date();function k(e,t=!1){if(t===!1)return e;let k=D(e);if(!O(k))return e;if(t===!0)return E(k,w);let j=t.toUpperCase();if(j===`SYS:STANDARD`)return E(k,S);let F=j.substr(0,4);return F===`SYS:`||F===`UTC:`?F===`UTC:`?E(k,t):E(k,t.slice(4)):E(k,`UTC:${t}`)}})),require_handle_custom_levels_names_opts=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,S)=>{let[w,E=S]=t.split(`:`);return e[w.toLowerCase()]=E,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,S)=>(t[S.toLowerCase()]=e[S],t),{}):{}:{}}})),require_handle_custom_levels_opts=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,S)=>{let[w,E=S]=t.split(`:`);return e[E]=w.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,S)=>(t[e[S]]=S.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),require_interpret_conditionals=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_get_property_value();function w(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,w),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function w(e,w,E){let D=S(t,w);return D&&E.includes(w)?E.replace(RegExp(`{`+w+`}`,`g`),D):``}}})),require_is_object=__commonJSMin$1(((e,t)=>{t.exports=S;function S(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),require_join_lines_with_indentation=__commonJSMin$1(((e,t)=>{t.exports=S;function S({input:e,ident:t=` `,eol:S=`
|
|
436
432
|
`}){let w=e.split(/\r?\n/);for(let e=1;e<w.length;e+=1)w[e]=t+w[e];return w.join(S)}})),require_parse_factory_options=__commonJSMin$1(((e,t)=>{t.exports=k;let{LEVEL_NAMES:S}=require_constants$6(),w=require_colors(),E=require_handle_custom_levels_opts(),D=require_handle_custom_levels_names_opts(),O=require_get_level_label_data();function k(e){let t=e.crlf?`\r
|
|
437
433
|
`:`
|
|
438
434
|
`,k=` `,{customPrettifiers:j,errorLikeObjectKeys:F,hideObject:L,levelFirst:B,levelKey:H,levelLabel:q,messageFormat:J,messageKey:Y,minimumLevel:ee,singleLine:te,timestampKey:ne,translateTime:ae}=e,oe=e.errorProps.split(`,`),se=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,ce=E(e.customLevels),ue=D(e.customLevels),de=O(se,ce,ue),fe;if(e.customColors)if(typeof e.customColors==`string`)fe=e.customColors.split(`,`).reduce((t,w)=>{let[E,D]=w.split(`:`),O=(se?e.customLevels:ue[E]!==void 0)?ue[E]:S[E],k=O===void 0?E:O;return t.push([k,D]),t},[]);else if(typeof e.customColors==`object`)fe=Object.keys(e.customColors).reduce((t,w)=>{let[E,D]=[w,e.customColors[w]],O=(se?e.customLevels:ue[E]!==void 0)?ue[E]:S[E],k=O===void 0?E:O;return t.push([k,D]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let me={customLevels:ce,customLevelNames:ue};se===!0&&!e.customLevels&&(me.customLevels=void 0,me.customLevelNames=void 0);let ge=e.include===void 0?void 0:new Set(e.include.split(`,`)),_e=!ge&&e.ignore?new Set(e.ignore.split(`,`)):void 0,ve=w(e.colorize,fe,se),ye=e.colorizeObjects?ve:w(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:ve,customColors:fe,customLevelNames:ue,customLevels:ce,customPrettifiers:j,customProperties:me,errorLikeObjectKeys:F,errorProps:oe,getLevelLabelData:de,hideObject:L,ignoreKeys:_e,includeKeys:ge,levelFirst:B,levelKey:H,levelLabel:q,messageFormat:J,messageKey:Y,minimumLevel:ee,objectColorizer:ye,singleLine:te,timestampKey:ne,translateTime:ae,useOnlyCustomProps:se}}})),require_fast_safe_stringify=__commonJSMin$1(((e,t)=>{t.exports=k,k.default=k,k.stable=B,k.stableStringify=B;var S=`[...]`,w=`[Circular]`,E=[],D=[];function O(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function k(e,t,S,w){w===void 0&&(w=O()),F(e,``,0,[],void 0,0,w);var k;try{k=D.length===0?JSON.stringify(e,t,S):JSON.stringify(e,q(t),S)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;E.length!==0;){var j=E.pop();j.length===4?Object.defineProperty(j[0],j[1],j[3]):j[0][j[1]]=j[2]}}return k}function j(e,t,S,w){var O=Object.getOwnPropertyDescriptor(w,S);O.get===void 0?(w[S]=e,E.push([w,S,t])):O.configurable?(Object.defineProperty(w,S,{value:e}),E.push([w,S,t,O])):D.push([t,S,e])}function F(e,t,E,D,O,k,L){k+=1;var B;if(typeof e==`object`&&e){for(B=0;B<D.length;B++)if(D[B]===e){j(w,e,t,O);return}if(L.depthLimit!==void 0&&k>L.depthLimit){j(S,e,t,O);return}if(L.edgesLimit!==void 0&&E+1>L.edgesLimit){j(S,e,t,O);return}if(D.push(e),Array.isArray(e))for(B=0;B<e.length;B++)F(e[B],B,B,D,e,k,L);else{var H=Object.keys(e);for(B=0;B<H.length;B++){var q=H[B];F(e[q],q,B,D,e,k,L)}}D.pop()}}function L(e,t){return e<t?-1:e>t?1:0}function B(e,t,S,w){w===void 0&&(w=O());var k=H(e,``,0,[],void 0,0,w)||e,j;try{j=D.length===0?JSON.stringify(k,t,S):JSON.stringify(k,q(t),S)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;E.length!==0;){var F=E.pop();F.length===4?Object.defineProperty(F[0],F[1],F[3]):F[0][F[1]]=F[2]}}return j}function H(e,t,D,O,k,F,B){F+=1;var q;if(typeof e==`object`&&e){for(q=0;q<O.length;q++)if(O[q]===e){j(w,e,t,k);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(B.depthLimit!==void 0&&F>B.depthLimit){j(S,e,t,k);return}if(B.edgesLimit!==void 0&&D+1>B.edgesLimit){j(S,e,t,k);return}if(O.push(e),Array.isArray(e))for(q=0;q<e.length;q++)H(e[q],q,q,O,e,F,B);else{var J={},Y=Object.keys(e).sort(L);for(q=0;q<Y.length;q++){var ee=Y[q];H(e[ee],ee,q,O,e,F,B),J[ee]=e[ee]}if(k!==void 0)E.push([k,t,e]),k[t]=J;else return J}O.pop()}}function q(e){return e=e===void 0?function(e,t){return t}:e,function(t,S){if(D.length>0)for(var w=0;w<D.length;w++){var E=D[w];if(E[1]===t&&E[0]===S){S=E[2],D.splice(w,1);break}}return e.call(this,t,S)}}})),require_prettify_error=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_join_lines_with_indentation();function w({keyName:e,lines:t,eol:w,ident:E}){let D=``,O=`${E}${e}: ${S({input:t,ident:E,eol:w})}${w}`.split(w);for(let e=0;e<O.length;e+=1){e!==0&&(D+=w);let t=O[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let S=/^\s*/.exec(t)[0].length+4,E=` `.repeat(S),O=e[2];D+=e[1]+w+E+JSON.parse(O).replace(/\n/g,w+E)}else D+=t}else D+=t}return D}})),require_prettify_object=__commonJSMin$1(((e,t)=>{t.exports=O;let{LOGGER_KEYS:S}=require_constants$6(),w=require_fast_safe_stringify(),E=require_join_lines_with_indentation(),D=require_prettify_error();function O({log:e,excludeLoggerKeys:t=!0,skipKeys:O=[],context:k}){let{EOL:j,IDENT:F,customPrettifiers:L,errorLikeObjectKeys:B,objectColorizer:H,singleLine:q,colorizer:J}=k,Y=[].concat(O);t===!0&&Array.prototype.push.apply(Y,S);let ee=``,{plain:te,errors:ne}=Object.entries(e).reduce(({plain:t,errors:S},[w,E])=>{if(Y.includes(w)===!1){let D=typeof L[w]==`function`?L[w](E,w,e,{colors:J.colors}):E;B.includes(w)?S[w]=D:t[w]=D}return{plain:t,errors:S}},{plain:{},errors:{}});return q?(Object.keys(te).length>0&&(ee+=H.greyMessage(w(te))),ee+=j,ee=ee.replace(/\\\\/gi,`\\`)):Object.entries(te).forEach(([e,t])=>{let S=typeof L[e]==`function`?t:w(t,null,2);if(S===void 0)return;S=S.replace(/\\\\/gi,`\\`);let D=E({input:S,ident:F,eol:j});ee+=`${F}${H.property(e)}:${D.startsWith(j)?``:` `}${D}${j}`}),Object.entries(ne).forEach(([e,t])=>{let S=typeof L[e]==`function`?t:w(t,null,2);S!==void 0&&(ee+=D({keyName:e,lines:S,eol:j,ident:F}))}),ee}})),require_prettify_error_log=__commonJSMin$1(((e,t)=>{t.exports=O;let{LOGGER_KEYS:S}=require_constants$6(),w=require_is_object(),E=require_join_lines_with_indentation(),D=require_prettify_object();function O({log:e,context:t}){let{EOL:O,IDENT:k,errorProps:j,messageKey:F}=t,L=e.stack,B=`${k}${E({input:L,ident:k,eol:O})}${O}`;if(j.length>0){let E=S.concat(F,`type`,`stack`),L;L=j[0]===`*`?Object.keys(e).filter(e=>E.includes(e)===!1):j.filter(e=>E.includes(e)===!1);for(let S=0;S<L.length;S+=1){let E=L[S];if(E in e){if(w(e[E])){let S=D({log:e[E],excludeLoggerKeys:!1,context:{...t,IDENT:k+k}});B=`${B}${k}${E}: {${O}${S}${k}}${O}`;continue}B=`${B}${k}${E}: ${e[E]}${O}`}}}return B}})),require_prettify_level=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_get_property_value();function w({log:e,context:t}){let{colorizer:w,customLevels:E,customLevelNames:D,levelKey:O,getLevelLabelData:k}=t,j=t.customPrettifiers?.level,F=S(e,O);if(F===void 0)return;let L=w(F,{customLevels:E,customLevelNames:D});if(j){let[t]=k(F);return j(F,O,e,{label:t,labelColorized:L,colors:w.colors})}return L}})),require_prettify_message=__commonJSMin$1(((e,t)=>{t.exports=D;let{LEVELS:S}=require_constants$6(),w=require_get_property_value(),E=require_interpret_conditionals();function D({log:e,context:t}){let{colorizer:D,customLevels:O,levelKey:k,levelLabel:j,messageFormat:F,messageKey:L,useOnlyCustomProps:B}=t;if(F&&typeof F==`string`){let t=E(F,e),L=String(t).replace(/{([^{}]+)}/g,function(t,E){let D;if(E===j&&(D=w(e,k))!==void 0)return(B?O===void 0:O[D]===void 0)?S[D]:O[D];let F=w(e,E);return F===void 0?``:F});return D.message(L)}if(F&&typeof F==`function`){let t=F(e,L,j,{colors:D.colors});return D.message(t)}if(L in e&&!(typeof e[L]!=`string`&&typeof e[L]!=`number`&&typeof e[L]!=`boolean`))return D.message(e[L])}})),require_prettify_metadata=__commonJSMin$1(((e,t)=>{t.exports=S;function S({log:e,context:t}){let{customPrettifiers:S,colorizer:w}=t,E=``;if(e.name||e.pid||e.hostname){if(E+=`(`,e.name&&(E+=S.name?S.name(e.name,`name`,e,{colors:w.colors}):e.name),e.pid){let t=S.pid?S.pid(e.pid,`pid`,e,{colors:w.colors}):e.pid;e.name&&e.pid?E+=`/`+t:E+=t}if(e.hostname){let t=S.hostname?S.hostname(e.hostname,`hostname`,e,{colors:w.colors}):e.hostname;E+=`${E===`(`?`on`:` on`} ${t}`}E+=`)`}if(e.caller){let t=S.caller?S.caller(e.caller,`caller`,e,{colors:w.colors}):e.caller;E+=`${E===``?``:` `}<${t}>`}if(E!==``)return E}})),require_prettify_time=__commonJSMin$1(((e,t)=>{t.exports=w;let S=require_format_time();function w({log:e,context:t}){let{timestampKey:w,translateTime:E}=t,D=t.customPrettifiers?.time,O=null;if(w in e?O=e[w]:`timestamp`in e&&(O=e.timestamp),O===null)return;let k=E?S(O,E):O;return D?D(k):`[${k}]`}})),require_utils$16=__commonJSMin$1(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin$1(((e,t)=>{let S=typeof Buffer<`u`,w=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,E=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function D(e,t,D){D==null&&typeof t==`object`&&t&&(D=t,t=void 0),S&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let k=JSON.parse(e,t);if(typeof k!=`object`||!k)return k;let j=D&&D.protoAction||`error`,F=D&&D.constructorAction||`error`;if(j===`ignore`&&F===`ignore`)return k;if(j!==`ignore`&&F!==`ignore`){if(w.test(e)===!1&&E.test(e)===!1)return k}else if(j!==`ignore`&&F===`ignore`){if(w.test(e)===!1)return k}else if(E.test(e)===!1)return k;return O(k,{protoAction:j,constructorAction:F,safe:D&&D.safe})}function O(e,{protoAction:t=`error`,constructorAction:S=`error`,safe:w}={}){let E=[e];for(;E.length;){let e=E;E=[];for(let D of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(D,`__proto__`)){if(w===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete D.__proto__}if(S!==`ignore`&&Object.prototype.hasOwnProperty.call(D,`constructor`)&&D.constructor!==null&&typeof D.constructor==`object`&&Object.prototype.hasOwnProperty.call(D.constructor,`prototype`)){if(w===!0)return null;if(S===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete D.constructor}for(let e in D){let t=D[e];t&&typeof t==`object`&&E.push(t)}}}return e}function k(e,t,S){let{stackTraceLimit:w}=Error;Error.stackTraceLimit=0;try{return D(e,t,S)}finally{Error.stackTraceLimit=w}}function j(e,t){let{stackTraceLimit:S}=Error;Error.stackTraceLimit=0;try{return D(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=S}}t.exports=k,t.exports.default=k,t.exports.parse=k,t.exports.safeParse=j,t.exports.scan=O})),require_pretty=__commonJSMin$1(((e,t)=>{t.exports=Y;let S=require_secure_json_parse(),w=require_is_object(),E=require_prettify_error_log(),D=require_prettify_level(),O=require_prettify_message(),k=require_prettify_metadata(),j=require_prettify_object(),F=require_prettify_time(),L=require_filter_log(),{LEVELS:B,LEVEL_KEY:H,LEVEL_NAMES:q}=require_constants$6(),J=e=>{try{return{value:S.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function Y(e){let t;if(w(e))t=e;else{let S=J(e);if(S.err||!w(S.value))return e+this.EOL;t=S.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let S;if(S=e?this.customLevelNames[this.minimumLevel]:q[this.minimumLevel],S||=typeof this.minimumLevel==`string`?q[this.minimumLevel]:q[B[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?H:this.levelKey]<S)return}let S=O({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=L({log:t,context:this.context}));let Y=D({log:t,context:{...this.context,...this.context.customProperties}}),ee=k({log:t,context:this.context}),te=F({log:t,context:this.context}),ne=``;if(this.levelFirst&&Y&&(ne=`${Y}`),te&&ne===``?ne=`${te}`:te&&(ne=`${ne} ${te}`),!this.levelFirst&&Y&&(ne=ne.length>0?`${ne} ${Y}`:Y),ee&&(ne=ne.length>0?`${ne} ${ee}:`:ee),ne.endsWith(`:`)===!1&&ne!==``&&(ne+=`:`),S!==void 0&&(ne=ne.length>0?`${ne} ${S}`:S),ne.length>0&&!this.singleLine&&(ne+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=E({log:t,context:this.context});this.singleLine&&(ne+=this.EOL),ne+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),S=j({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(S)&&(ne+=` `),ne+=S}return ne}})),require_pino_pretty=__commonJSMin$1(((e,t)=>{let{isColorSupported:S}=require_colorette(),w=require_pump(),{Transform:E}=__require$1(`node:stream`),D=require_pino_abstract_transport(),O=require_colors(),{ERROR_LIKE_KEYS:k,LEVEL_KEY:j,LEVEL_LABEL:F,MESSAGE_KEY:L,TIMESTAMP_KEY:B}=require_constants$6(),{buildSafeSonicBoom:H,parseFactoryOptions:q}=require_utils$16(),J=require_pretty(),Y={colorize:S,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:k,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:j,levelLabel:F,messageFormat:null,messageKey:L,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:B,translateTime:!0,useOnlyCustomProps:!0};function ee(e){let t=q(Object.assign({},Y,e));return J.bind({...t,context:t})}function te(e={}){let t=ee(e),S;return D(function(D){D.on(`message`,function S(w){!w||w.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:w.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||k,w.config.errorKey])),customLevels:w.config.levels.values}),t=ee(e),D.off(`message`,S))});let O=new E({objectMode:!0,autoDestroy:!0,transform(e,S,w){w(null,t(e))}});return S=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:H({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),D.on(`unknown`,function(e){S.write(e+`
|
|
@@ -456,7 +452,7 @@ To resolve the conflict:`,(0,w.getConflictResolutionRecipe)(E,e))),D=O):S.diag.w
|
|
|
456
452
|
To resolve the conflict:`,(0,w.getConflictResolutionRecipe)(E,e))),D=O):S.diag.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
|
|
457
453
|
`,`Details:
|
|
458
454
|
`,(0,w.getIncompatibilityDetails)(E,e),`To resolve the conflict:
|
|
459
|
-
`,(0,w.getConflictResolutionRecipe)(E,e))}return D}}})),require_MultiWritableMetricStorage$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,S,w){this._backingStorages.forEach(E=>{E.record(e,t,S,w)})}}})),require_ObservableResult$1=__commonJSMin$1((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$1(),w=require_Instruments$1();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new S.AttributeHashMap;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,E,D={}){if(!(0,w.isObservableInstrument)(e))return;let O=this._buffer.get(e);if(O??(O=new S.AttributeHashMap,this._buffer.set(e,O)),typeof E!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${E}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(E)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),E=Math.trunc(E),!Number.isInteger(E))||O.set(D,E)}}})),require_ObservableRegistry$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_Instruments$1(),w=require_ObservableResult$1(),E=require_utils$7();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,w){let E=new Set(w.filter(S.isObservableInstrument));if(E.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,w);return}this._findBatchCallback(e,E)>=0||this._batchCallbacks.push({callback:e,instruments:E})}removeBatchCallback(e,t){let w=new Set(t.filter(S.isObservableInstrument)),E=this._findBatchCallback(e,w);E<0||this._batchCallbacks.splice(E,1)}async observe(e,t){let S=this._observeCallbacks(e,t),w=this._observeBatchCallbacks(e,t);return(await(0,E.PromiseAllSettled)([...S,...w])).filter(E.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:S,instrument:D})=>{let O=new w.ObservableResultImpl(D._descriptor.name,D._descriptor.valueType),k=Promise.resolve(S(O));t!=null&&(k=(0,E.callWithTimeout)(k,t)),await k,D._metricStorages.forEach(t=>{t.record(O._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:S,instruments:D})=>{let O=new w.BatchObservableResultImpl,k=Promise.resolve(S(O));t!=null&&(k=(0,E.callWithTimeout)(k,t)),await k,D.forEach(t=>{let S=O._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,E.setEquals)(S.instruments,t))}}})),require_SyncMetricStorage$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage$1(),S=require_DeltaMetricProcessor$1(),w=require_TemporalMetricProcessor$1();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,E,D,O){super(e),this._attributesProcessor=E,this._aggregationCardinalityLimit=O,this._deltaMetricStorage=new S.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new w.TemporalMetricProcessor(t,D)}record(e,t,S,w){t=this._attributesProcessor.process(t,S),this._deltaMetricStorage.record(e,t,S,w)}collect(e,t){let S=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,S,t)}}})),require_AttributesProcessor$1=__commonJSMin$1((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}},w=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let S={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>S[t]=e[t]),S}},E=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let S={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>S[t]=e[t]),S}};function D(){return F}e.createNoopAttributesProcessor=D;function O(e){return new S(e)}e.createMultiAttributesProcessor=O;function k(e){return new w(e)}e.createAllowListAttributesProcessor=k;function j(e){return new E(e)}e.createDenyListAttributesProcessor=j;let F=new t})),require_MeterSharedState$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor$1(),S=require_Meter$1(),w=require_utils$7(),E=require_AsyncMetricStorage$1(),D=require_MetricStorageRegistry$1(),O=require_MultiWritableMetricStorage$1(),k=require_ObservableRegistry$1(),j=require_SyncMetricStorage$1(),F=require_AttributesProcessor$1();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new D.MetricStorageRegistry;observableRegistry=new k.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new S.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,j.SyncMetricStorage);return t.length===1?t[0]:new O.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,E.AsyncMetricStorage)}async collect(e,t,S){let E=await this.observableRegistry.observe(t,S?.timeoutMillis),D=this.metricStorageRegistry.getStorages(e);if(D.length===0)return null;let O=D.map(S=>S.collect(e,t)).filter(w.isNotNullish);return O.length===0?{errors:E}:{scopeMetrics:{scope:this._instrumentationScope,metrics:O},errors:E}}_registerMetricStorage(e,S){let w=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(w=>{let E=(0,t.createInstrumentDescriptorWithView)(w,e),D=this.metricStorageRegistry.findOrUpdateCompatibleStorage(E);if(D!=null)return D;let O=new S(E,w.aggregation.createAggregator(E),w.attributesProcessor,this._meterProviderSharedState.metricCollectors,w.aggregationCardinalityLimit);return this.metricStorageRegistry.register(O),O});if(w.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,w])=>{let E=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(E!=null)return E;let D=w.createAggregator(e),O=t.selectCardinalityLimit(e.type),k=new S(e,D,(0,F.createNoopAttributesProcessor)(),[t],O);return this.metricStorageRegistry.registerForCollector(t,k),k});w=w.concat(t)}return w}}})),require_MeterProviderSharedState$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$7(),S=require_ViewRegistry$1(),w=require_MeterSharedState$1(),E=require_AggregationOption$1();e.MeterProviderSharedState=class{resource;viewRegistry=new S.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let S=(0,t.instrumentationScopeId)(e),E=this.meterSharedStates.get(S);return E??(E=new w.MeterSharedState(this,e),this.meterSharedStates.set(S,E)),E}selectAggregations(e){let t=[];for(let S of this.metricCollectors)t.push([S,(0,E.toAggregation)(S.selectAggregation(e))]);return t}}})),require_MetricCollector$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$8();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let S=(0,t.millisToHrTime)(Date.now()),w=[],E=[],D=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let D=await t.collect(this,S,e);D?.scopeMetrics!=null&&w.push(D.scopeMetrics),D?.errors!=null&&E.push(...D.errors)});return await Promise.all(D),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:w},errors:E}}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$1=__commonJSMin$1((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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate$1();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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate$1();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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate$1(),S=require_AttributesProcessor$1(),w=require_InstrumentSelector$1(),E=require_MeterSelector$1(),D=require_AggregationOption$1();function O(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function k(e){if(O(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){k(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,D.toAggregation)(e.aggregation??{type:D.AggregationType.DEFAULT}),this.instrumentSelector=new w.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new E.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$7(),w=require_MeterProviderSharedState$1(),E=require_MetricCollector$1(),D=require_View$1();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new w.MeterProviderSharedState(e?.resource??(0,S.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new D.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new E.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,S=``,w={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:S,schemaUrl:w.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$6=__commonJSMin$1((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$1();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var S=require_MetricData$1();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return S.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return S.InstrumentType}});var w=require_MetricReader$1();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return w.MetricReader}});var E=require_PeriodicExportingMetricReader$1();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return E.PeriodicExportingMetricReader}});var D=require_InMemoryMetricExporter$1();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return D.InMemoryMetricExporter}});var O=require_ConsoleMetricExporter$1();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return O.ConsoleMetricExporter}});var k=require_MeterProvider$1();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return k.MeterProvider}});var j=require_AggregationOption$1();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return j.AggregationType}});var F=require_AttributesProcessor$1();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return F.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return F.createDenyListAttributesProcessor}});var L=require_utils$7();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return L.TimeoutError}})})),require_internal_types=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.EAggregationTemporality=void 0,(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(e.EAggregationTemporality||={})})),require_internal$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportMetricsServiceRequest=e.toMetric=e.toScopeMetrics=e.toResourceMetrics=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$6(),w=require_internal_types(),E=require_utils$8(),D=require_internal$3();function O(e,t){let S=(0,E.getOtlpEncoder)(t),w=(0,D.createResource)(e.resource);return{resource:w,schemaUrl:w.schemaUrl,scopeMetrics:k(e.scopeMetrics,S)}}e.toResourceMetrics=O;function k(e,t){return Array.from(e.map(e=>({scope:(0,D.createInstrumentationScope)(e.scope),metrics:e.metrics.map(e=>j(e,t)),schemaUrl:e.scope.schemaUrl})))}e.toScopeMetrics=k;function j(e,t){let w={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},E=q(e.aggregationTemporality);switch(e.dataPointType){case S.DataPointType.SUM:w.sum={aggregationTemporality:E,isMonotonic:e.isMonotonic,dataPoints:L(e,t)};break;case S.DataPointType.GAUGE:w.gauge={dataPoints:L(e,t)};break;case S.DataPointType.HISTOGRAM:w.histogram={aggregationTemporality:E,dataPoints:B(e,t)};break;case S.DataPointType.EXPONENTIAL_HISTOGRAM:w.exponentialHistogram={aggregationTemporality:E,dataPoints:H(e,t)};break}return w}e.toMetric=j;function F(e,S,w){let E={attributes:(0,D.toAttributes)(e.attributes),startTimeUnixNano:w.encodeHrTime(e.startTime),timeUnixNano:w.encodeHrTime(e.endTime)};switch(S){case t.ValueType.INT:E.asInt=e.value;break;case t.ValueType.DOUBLE:E.asDouble=e.value;break}return E}function L(e,t){return e.dataPoints.map(S=>F(S,e.descriptor.valueType,t))}function B(e,t){return e.dataPoints.map(e=>{let S=e.value;return{attributes:(0,D.toAttributes)(e.attributes),bucketCounts:S.buckets.counts,explicitBounds:S.buckets.boundaries,count:S.count,sum:S.sum,min:S.min,max:S.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function H(e,t){return e.dataPoints.map(e=>{let S=e.value;return{attributes:(0,D.toAttributes)(e.attributes),count:S.count,min:S.min,max:S.max,sum:S.sum,positive:{offset:S.positive.offset,bucketCounts:S.positive.bucketCounts},negative:{offset:S.negative.offset,bucketCounts:S.negative.bucketCounts},scale:S.scale,zeroCount:S.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function q(e){switch(e){case S.AggregationTemporality.DELTA:return w.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;case S.AggregationTemporality.CUMULATIVE:return w.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE}}function J(e,t){return{resourceMetrics:e.map(e=>O(e,t))}}e.createExportMetricsServiceRequest=J})),require_metrics$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;let t=require_root(),S=require_internal$1(),w=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,E=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.ProtobufMetricsSerializer={serializeRequest:e=>{let t=(0,S.createExportMetricsServiceRequest)([e]);return E.encode(t).finish()},deserializeResponse:e=>w.decode(e)}})),require_protobuf$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;var t=require_metrics$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return t.ProtobufMetricsSerializer}})})),require_internal=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportTraceServiceRequest=e.toOtlpSpanEvent=e.toOtlpLink=e.sdkSpanToOtlpSpan=void 0;let t=require_internal$3(),S=require_utils$8();function w(e,S){let w=e.spanContext(),O=e.status,k=e.parentSpanContext?.spanId?S.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:S.encodeSpanContext(w.traceId),spanId:S.encodeSpanContext(w.spanId),parentSpanId:k,traceState:w.traceState?.serialize(),name:e.name,kind:e.kind==null?0:e.kind+1,startTimeUnixNano:S.encodeHrTime(e.startTime),endTimeUnixNano:S.encodeHrTime(e.endTime),attributes:(0,t.toAttributes)(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>D(e,S)),droppedEventsCount:e.droppedEventsCount,status:{code:O.code,message:O.message},links:e.links.map(e=>E(e,S)),droppedLinksCount:e.droppedLinksCount}}e.sdkSpanToOtlpSpan=w;function E(e,S){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],spanId:S.encodeSpanContext(e.context.spanId),traceId:S.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpLink=E;function D(e,S){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],name:e.name,timeUnixNano:S.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpSpanEvent=D;function O(e,t){return{resourceSpans:j(e,(0,S.getOtlpEncoder)(t))}}e.createExportTraceServiceRequest=O;function k(e){let t=new Map;for(let S of e){let e=t.get(S.resource);e||(e=new Map,t.set(S.resource,e));let w=`${S.instrumentationScope.name}@${S.instrumentationScope.version||``}:${S.instrumentationScope.schemaUrl||``}`,E=e.get(w);E||(E=[],e.set(w,E)),E.push(S)}return t}function j(e,S){let E=k(e),D=[],O=E.entries(),j=O.next();for(;!j.done;){let[e,E]=j.value,k=[],F=E.values(),L=F.next();for(;!L.done;){let e=L.value;if(e.length>0){let E=e.map(e=>w(e,S));k.push({scope:(0,t.createInstrumentationScope)(e[0].instrumentationScope),spans:E,schemaUrl:e[0].instrumentationScope.schemaUrl})}L=F.next()}let B=(0,t.createResource)(e),H={resource:B,scopeSpans:k,schemaUrl:B.schemaUrl};D.push(H),j=O.next()}return D}})),require_trace$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;let t=require_root(),S=require_internal(),w=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,E=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.ProtobufTraceSerializer={serializeRequest:e=>{let t=(0,S.createExportTraceServiceRequest)(e);return E.encode(t).finish()},deserializeResponse:e=>w.decode(e)}})),require_protobuf=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;var t=require_trace$1();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return t.ProtobufTraceSerializer}})})),require_logs=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;let t=require_internal$2();e.JsonLogsSerializer={serializeRequest:e=>{let S=(0,t.createExportLogsServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;var t=require_logs();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return t.JsonLogsSerializer}})})),require_metrics=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;let t=require_internal$1();e.JsonMetricsSerializer={serializeRequest:e=>{let S=(0,t.createExportMetricsServiceRequest)([e],{useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;var t=require_metrics();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return t.JsonMetricsSerializer}})})),require_trace=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;let t=require_internal();e.JsonTraceSerializer={serializeRequest:e=>{let S=(0,t.createExportTraceServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;var t=require_trace();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return t.JsonTraceSerializer}})})),require_src$5=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=e.JsonMetricsSerializer=e.JsonLogsSerializer=e.ProtobufTraceSerializer=e.ProtobufMetricsSerializer=e.ProtobufLogsSerializer=void 0;var t=require_protobuf$2();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}});var S=require_protobuf$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return S.ProtobufMetricsSerializer}});var w=require_protobuf();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return w.ProtobufTraceSerializer}});var E=require_json$2();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return E.JsonLogsSerializer}});var D=require_json$1();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return D.JsonMetricsSerializer}});var O=require_json();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return O.JsonTraceSerializer}})})),require_version$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`0.204.0`}));function validateAndNormalizeHeaders(e){return()=>{let t={};return Object.entries(e?.()??{}).forEach(([e,S])=>{S===void 0?diag.warn(`Header "${e}" has invalid value (${S}) and will be ignored`):t[e]=String(S)}),t}}var init_util=__esmMin((()=>{init_esm$2()}));function mergeHeaders(e,t,S){let w={...S()},E={};return()=>(t!=null&&Object.assign(E,t()),e!=null&&Object.assign(E,e()),Object.assign(E,w))}function validateUserProvidedUrl(e){if(e!=null)try{let t=globalThis.location?.href;return new URL(e,t).href}catch{throw Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function httpAgentFactoryFromOptions(e){return async t=>{let{Agent:S}=await(t===`http:`?import(`http`):import(`https`));return new S(e)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,S){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,S),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,S.headers),url:validateUserProvidedUrl(e.url)??t.url??S.url,agentFactory:e.agentFactory??t.agentFactory??S.agentFactory}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:`http://localhost:4318/`+t,agentFactory:httpAgentFactoryFromOptions({keepAlive:!0})}}var init_otlp_http_configuration=__esmMin((()=>{init_shared_configuration(),init_util()}));function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(e==null)return;let t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?t*1e3:-1;let S=new Date(e).getTime()-Date.now();return S>=0?S:0}var init_is_export_retryable=__esmMin((()=>{}));function sendWithHttp(e,t,S,w,E,D){let O=new URL(t.url),k=e({hostname:O.hostname,port:O.port,path:O.pathname,method:`POST`,headers:{...t.headers()},agent:S},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>{e.statusCode&&e.statusCode<299?E({status:`success`,data:Buffer.concat(t)}):e.statusCode&&isExportRetryable(e.statusCode)?E({status:`retryable`,retryInMillis:parseRetryAfterToMills(e.headers[`retry-after`])}):E({status:`failure`,error:new OTLPExporterError(e.statusMessage,e.statusCode,Buffer.concat(t).toString())})})});k.setTimeout(D,()=>{k.destroy(),E({status:`failure`,error:Error(`Request Timeout`)})}),k.on(`error`,e=>{E({status:`failure`,error:e})}),compressAndSend(k,t.compression,w,e=>{E({status:`failure`,error:e})})}function compressAndSend(e,t,S,w){let E=readableFromUint8Array(S);t===`gzip`&&(e.setHeader(`Content-Encoding`,`gzip`),E=E.on(`error`,w).pipe(zlib$2.createGzip()).on(`error`,w)),E.pipe(e).on(`error`,w)}function readableFromUint8Array(e){let t=new Readable;return t.push(e),t.push(null),t}var init_http_transport_utils=__esmMin((()=>{init_is_export_retryable(),init_types()}));async function requestFunctionFactory(e){let{request:t}=await(e===`http:`?import(`http`):import(`https`));return t}function createHttpExporterTransport(e){return new HttpExporterTransport(e)}var HttpExporterTransport,init_http_exporter_transport=__esmMin((()=>{init_http_transport_utils(),HttpExporterTransport=class{_parameters;_utils=null;constructor(e){this._parameters=e}async send(e,t){let{agent:S,request:w}=await this._loadUtils();return new Promise(E=>{sendWithHttp(w,this._parameters,S,e,e=>{E(e)},t)})}shutdown(){}async _loadUtils(){let e=this._utils;if(e===null){let t=new URL(this._parameters.url).protocol,[S,w]=await Promise.all([this._parameters.agentFactory(t),requestFunctionFactory(t)]);e=this._utils={agent:S,request:w}}return e}}}));function getJitter(){return 2*JITTER*Math.random()-JITTER}function createRetryingTransport(e){return new RetryingTransport(e.transport)}var MAX_ATTEMPTS,INITIAL_BACKOFF,MAX_BACKOFF,BACKOFF_MULTIPLIER,JITTER,RetryingTransport,init_retrying_transport=__esmMin((()=>{MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2,RetryingTransport=class{_transport;constructor(e){this._transport=e}retry(e,t,S){return new Promise((w,E)=>{setTimeout(()=>{this._transport.send(e,t).then(w,E)},S)})}async send(e,t){let S=Date.now()+t,w=await this._transport.send(e,t),E=MAX_ATTEMPTS,D=INITIAL_BACKOFF;for(;w.status===`retryable`&&E>0;){E--;let t=Math.max(Math.min(D,MAX_BACKOFF)+getJitter(),0);D*=BACKOFF_MULTIPLIER;let O=w.retryInMillis??t,k=S-Date.now();if(O>k)return w;w=await this.retry(e,k,O)}return w}shutdown(){return this._transport.shutdown()}}}));function createOtlpHttpExportDelegate(e,t){return createOtlpExportDelegate({transport:createRetryingTransport({transport:createHttpExporterTransport(e)}),serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}var init_otlp_http_export_delegate=__esmMin((()=>{init_otlp_export_delegate(),init_http_exporter_transport(),init_bounded_queue_export_promise_handler(),init_retrying_transport()}));function parseAndValidateTimeoutFromEnv(e){let t=process.env[e]?.trim();if(t!=null&&t!==``){let S=Number(t);if(Number.isFinite(S)&&S>0)return S;diag.warn(`Configuration: ${e} is invalid, expected number greater than 0 (actual: ${t})`)}}function getTimeoutFromEnv(e){let t=parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${e}_TIMEOUT`),S=parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_TIMEOUT`);return t??S}function parseAndValidateCompressionFromEnv(e){let t=process.env[e]?.trim();if(t!==``){if(t==null||t===`none`||t===`gzip`)return t;diag.warn(`Configuration: ${e} is invalid, expected 'none' or 'gzip' (actual: '${t}')`)}}function getCompressionFromEnv(e){let t=parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${e}_COMPRESSION`),S=parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_COMPRESSION`);return t??S}function getSharedConfigurationFromEnvironment(e){return{timeoutMillis:getTimeoutFromEnv(e),compression:getCompressionFromEnv(e)}}var init_shared_env_configuration=__esmMin((()=>{init_esm$2()}));function getStaticHeadersFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${e}_HEADERS`),S=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_HEADERS`),w=(0,import_src$8.parseKeyPairsIntoRecord)(t),E=(0,import_src$8.parseKeyPairsIntoRecord)(S);if(!(Object.keys(w).length===0&&Object.keys(E).length===0))return Object.assign({},(0,import_src$8.parseKeyPairsIntoRecord)(S),(0,import_src$8.parseKeyPairsIntoRecord)(t))}function appendRootPathToUrlIfNeeded(e){try{return new URL(e).toString()}catch{diag.warn(`Configuration: Could not parse environment-provided export URL: '${e}', falling back to undefined`);return}}function appendResourcePathToUrl(e,t){try{new URL(e)}catch{diag.warn(`Configuration: Could not parse environment-provided export URL: '${e}', falling back to undefined`);return}e.endsWith(`/`)||(e+=`/`),e+=t;try{new URL(e)}catch{diag.warn(`Configuration: Provided URL appended with '${t}' is not a valid URL, using 'undefined' instead of '${e}'`);return}return e}function getNonSpecificUrlFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_ENDPOINT`);if(t!==void 0)return appendResourcePathToUrl(t,e)}function getSpecificUrlFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${e}_ENDPOINT`);if(t!==void 0)return appendRootPathToUrlIfNeeded(t)}function getHttpConfigurationFromEnvironment(e,t){return{...getSharedConfigurationFromEnvironment(e),url:getSpecificUrlFromEnv(e)??getNonSpecificUrlFromEnv(t),headers:wrapStaticHeadersInFunction(getStaticHeadersFromEnv(e))}}var import_src$8,init_otlp_http_env_configuration=__esmMin((()=>{import_src$8=require_src$9(),init_esm$2(),init_shared_env_configuration(),init_shared_configuration()}));function convertLegacyAgentOptions(e){if(typeof e.httpAgentOptions==`function`)return e.httpAgentOptions;let t=e.httpAgentOptions;if(e.keepAlive!=null&&(t={keepAlive:e.keepAlive,...t}),t!=null)return httpAgentFactoryFromOptions(t)}function convertLegacyHttpOptions(e,t,S,w){return e.metadata&&diag.warn(`Metadata cannot be set when using http`),mergeOtlpHttpConfigurationWithDefaults({url:e.url,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit,timeoutMillis:e.timeoutMillis,compression:e.compression,agentFactory:convertLegacyAgentOptions(e)},getHttpConfigurationFromEnvironment(t,S),getHttpConfigurationDefaults(w,S))}var init_convert_legacy_node_http_options=__esmMin((()=>{init_otlp_http_configuration(),init_otlp_http_env_configuration(),init_esm$2(),init_shared_configuration()})),index_node_http_exports=__exportAll({convertLegacyHttpOptions:()=>convertLegacyHttpOptions,createOtlpHttpExportDelegate:()=>createOtlpHttpExportDelegate,getSharedConfigurationFromEnvironment:()=>getSharedConfigurationFromEnvironment,httpAgentFactoryFromOptions:()=>httpAgentFactoryFromOptions}),init_index_node_http=__esmMin((()=>{init_otlp_http_configuration(),init_otlp_http_export_delegate(),init_shared_env_configuration(),init_convert_legacy_node_http_options()})),require_OTLPMetricExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;let t=require_OTLPMetricExporterBase(),S=require_src$5(),w=require_version$2(),E=(init_index_node_http(),__toCommonJS(index_node_http_exports)),D={"User-Agent":`OTel-OTLP-Exporter-JavaScript/${w.VERSION}`};e.OTLPMetricExporter=class extends t.OTLPMetricExporterBase{constructor(e){super((0,E.createOtlpHttpExportDelegate)((0,E.convertLegacyHttpOptions)(e??{},`METRICS`,`v1/metrics`,{...D,"Content-Type":`application/json`}),S.JsonMetricsSerializer),e)}}})),require_node$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;var t=require_OTLPMetricExporter();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}})})),require_platform$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;var t=require_node$3();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}})})),require_src$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporterBase=e.LowMemoryTemporalitySelector=e.DeltaTemporalitySelector=e.CumulativeTemporalitySelector=e.AggregationTemporalityPreference=e.OTLPMetricExporter=void 0;var t=require_platform$3();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}});var S=require_OTLPMetricExporterOptions();Object.defineProperty(e,`AggregationTemporalityPreference`,{enumerable:!0,get:function(){return S.AggregationTemporalityPreference}});var w=require_OTLPMetricExporterBase();Object.defineProperty(e,`CumulativeTemporalitySelector`,{enumerable:!0,get:function(){return w.CumulativeTemporalitySelector}}),Object.defineProperty(e,`DeltaTemporalitySelector`,{enumerable:!0,get:function(){return w.DeltaTemporalitySelector}}),Object.defineProperty(e,`LowMemoryTemporalitySelector`,{enumerable:!0,get:function(){return w.LowMemoryTemporalitySelector}}),Object.defineProperty(e,`OTLPMetricExporterBase`,{enumerable:!0,get:function(){return w.OTLPMetricExporterBase}})})),require_version$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`0.204.0`})),require_OTLPTraceExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;let t=(init_esm(),__toCommonJS(esm_exports)),S=require_version$1(),w=require_src$5(),E=(init_index_node_http(),__toCommonJS(index_node_http_exports));e.OTLPTraceExporter=class extends t.OTLPExporterBase{constructor(e={}){super((0,E.createOtlpHttpExportDelegate)((0,E.convertLegacyHttpOptions)(e,`TRACES`,`v1/traces`,{"User-Agent":`OTel-OTLP-Exporter-JavaScript/${S.VERSION}`,"Content-Type":`application/json`}),w.JsonTraceSerializer))}}})),require_node$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_OTLPTraceExporter();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_platform$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_node$2();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_src$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_platform$2();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_default_service_name=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._clearDefaultServiceNameCache=e.defaultServiceName=void 0;let t;function S(){if(t===void 0)try{let e=globalThis.process.argv0;t=e?`unknown_service:${e}`:`unknown_service`}catch{t=`unknown_service`}return t}e.defaultServiceName=S;function w(){t=void 0}e._clearDefaultServiceNameCache=w})),require_utils$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPromiseLike=void 0,e.isPromiseLike=e=>typeof e==`object`&&!!e&&typeof e.then==`function`})),require_ResourceImpl=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$13(),w=(init_esm$1(),__toCommonJS(esm_exports$1)),E=require_default_service_name(),D=require_utils$4();var O=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,S){let w=new e({},S);return w._rawAttributes=B(t),w._asyncAttributesPending=t.filter(([e,t])=>(0,D.isPromiseLike)(t)).length>0,w}constructor(e,t){let S=e.attributes??{};this._rawAttributes=Object.entries(S).map(([e,t])=>((0,D.isPromiseLike)(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=B(this._rawAttributes),this._schemaUrl=H(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[t,S]=this._rawAttributes[e];this._rawAttributes[e]=[t,(0,D.isPromiseLike)(S)?await S:S]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&t.diag.error(`Accessing resource attributes before async attributes settled`),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[S,w]of this._rawAttributes){if((0,D.isPromiseLike)(w)){t.diag.debug(`Unsettled resource attribute ${S} skipped`);continue}w!=null&&(e[S]??=w)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;let S=q(this,t),w=S?{schemaUrl:S}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],w)}};function k(e,t){return O.FromAttributeList(Object.entries(e),t)}e.resourceFromAttributes=k;function j(e,t){return new O(e,t)}e.resourceFromDetectedResource=j;function F(){return k({})}e.emptyResource=F;function L(){return k({[w.ATTR_SERVICE_NAME]:(0,E.defaultServiceName)(),[w.ATTR_TELEMETRY_SDK_LANGUAGE]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_LANGUAGE],[w.ATTR_TELEMETRY_SDK_NAME]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_NAME],[w.ATTR_TELEMETRY_SDK_VERSION]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_VERSION]})}e.defaultResource=L;function B(e){return e.map(([e,S])=>(0,D.isPromiseLike)(S)?[e,S.catch(S=>{t.diag.debug(`promise rejection for resource attribute: %s - %s`,e,S)})]:[e,S])}function H(e){if(typeof e==`string`||e===void 0)return e;t.diag.warn(`Schema URL must be string or undefined, got %s. Schema URL will be ignored.`,e)}function q(e,S){let w=e?.schemaUrl,E=S?.schemaUrl,D=w===void 0||w===``,O=E===void 0||E===``;if(D)return E;if(O||w===E)return w;t.diag.warn(`Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.`,w,E)}})),require_detect_resources=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_ResourceImpl();e.detectResources=(e={})=>(e.detectors||[]).map(w=>{try{let E=(0,S.resourceFromDetectedResource)(w.detect(e));return t.diag.debug(`${w.constructor.name} found resource.`,E),E}catch(e){return t.diag.debug(`${w.constructor.name} failed: ${e.message}`),(0,S.emptyResource)()}}).reduce((e,t)=>e.merge(t),(0,S.emptyResource)())})),require_EnvDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=(init_esm$1(),__toCommonJS(esm_exports$1)),w=require_src$13();e.envDetector=new class{_MAX_LENGTH=255;_COMMA_SEPARATOR=`,`;_LABEL_KEY_VALUE_SPLITTER=`=`;detect(e){let E={},D=(0,w.getStringFromEnv)(`OTEL_RESOURCE_ATTRIBUTES`),O=(0,w.getStringFromEnv)(`OTEL_SERVICE_NAME`);if(D)try{let e=this._parseResourceAttributes(D);Object.assign(E,e)}catch(e){t.diag.debug(`EnvDetector failed: ${e instanceof Error?e.message:e}`)}return O&&(E[S.ATTR_SERVICE_NAME]=O),{attributes:E}}_parseResourceAttributes(e){if(!e)return{};let t={},S=e.split(this._COMMA_SEPARATOR).filter(e=>e.trim()!==``);for(let e of S){let S=e.split(this._LABEL_KEY_VALUE_SPLITTER);if(S.length!==2)throw Error(`Invalid format for OTEL_RESOURCE_ATTRIBUTES: "${e}". Expected format: key=value. The ',' and '=' characters must be percent-encoded in keys and values.`);let[w,E]=S,D=w.trim(),O=E.trim();if(D.length===0)throw Error(`Invalid OTEL_RESOURCE_ATTRIBUTES: empty attribute key in "${e}".`);let k,j;try{k=decodeURIComponent(D),j=decodeURIComponent(O)}catch(t){throw Error(`Failed to percent-decode OTEL_RESOURCE_ATTRIBUTES entry "${e}": ${t instanceof Error?t.message:t}`)}if(k.length>this._MAX_LENGTH)throw Error(`Attribute key exceeds the maximum length of ${this._MAX_LENGTH} characters: "${k}".`);if(j.length>this._MAX_LENGTH)throw Error(`Attribute value exceeds the maximum length of ${this._MAX_LENGTH} characters for key "${k}".`);t[k]=j}return t}}})),require_semconv$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_WEBENGINE_VERSION=e.ATTR_WEBENGINE_NAME=e.ATTR_WEBENGINE_DESCRIPTION=e.ATTR_SERVICE_NAMESPACE=e.ATTR_SERVICE_INSTANCE_ID=e.ATTR_PROCESS_RUNTIME_VERSION=e.ATTR_PROCESS_RUNTIME_NAME=e.ATTR_PROCESS_RUNTIME_DESCRIPTION=e.ATTR_PROCESS_PID=e.ATTR_PROCESS_OWNER=e.ATTR_PROCESS_EXECUTABLE_PATH=e.ATTR_PROCESS_EXECUTABLE_NAME=e.ATTR_PROCESS_COMMAND_ARGS=e.ATTR_PROCESS_COMMAND=e.ATTR_OS_VERSION=e.ATTR_OS_TYPE=e.ATTR_K8S_POD_NAME=e.ATTR_K8S_NAMESPACE_NAME=e.ATTR_K8S_DEPLOYMENT_NAME=e.ATTR_K8S_CLUSTER_NAME=e.ATTR_HOST_TYPE=e.ATTR_HOST_NAME=e.ATTR_HOST_IMAGE_VERSION=e.ATTR_HOST_IMAGE_NAME=e.ATTR_HOST_IMAGE_ID=e.ATTR_HOST_ID=e.ATTR_HOST_ARCH=e.ATTR_CONTAINER_NAME=e.ATTR_CONTAINER_IMAGE_TAGS=e.ATTR_CONTAINER_IMAGE_NAME=e.ATTR_CONTAINER_ID=e.ATTR_CLOUD_REGION=e.ATTR_CLOUD_PROVIDER=e.ATTR_CLOUD_AVAILABILITY_ZONE=e.ATTR_CLOUD_ACCOUNT_ID=void 0,e.ATTR_CLOUD_ACCOUNT_ID=`cloud.account.id`,e.ATTR_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,e.ATTR_CLOUD_PROVIDER=`cloud.provider`,e.ATTR_CLOUD_REGION=`cloud.region`,e.ATTR_CONTAINER_ID=`container.id`,e.ATTR_CONTAINER_IMAGE_NAME=`container.image.name`,e.ATTR_CONTAINER_IMAGE_TAGS=`container.image.tags`,e.ATTR_CONTAINER_NAME=`container.name`,e.ATTR_HOST_ARCH=`host.arch`,e.ATTR_HOST_ID=`host.id`,e.ATTR_HOST_IMAGE_ID=`host.image.id`,e.ATTR_HOST_IMAGE_NAME=`host.image.name`,e.ATTR_HOST_IMAGE_VERSION=`host.image.version`,e.ATTR_HOST_NAME=`host.name`,e.ATTR_HOST_TYPE=`host.type`,e.ATTR_K8S_CLUSTER_NAME=`k8s.cluster.name`,e.ATTR_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,e.ATTR_K8S_NAMESPACE_NAME=`k8s.namespace.name`,e.ATTR_K8S_POD_NAME=`k8s.pod.name`,e.ATTR_OS_TYPE=`os.type`,e.ATTR_OS_VERSION=`os.version`,e.ATTR_PROCESS_COMMAND=`process.command`,e.ATTR_PROCESS_COMMAND_ARGS=`process.command_args`,e.ATTR_PROCESS_EXECUTABLE_NAME=`process.executable.name`,e.ATTR_PROCESS_EXECUTABLE_PATH=`process.executable.path`,e.ATTR_PROCESS_OWNER=`process.owner`,e.ATTR_PROCESS_PID=`process.pid`,e.ATTR_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`,e.ATTR_PROCESS_RUNTIME_VERSION=`process.runtime.version`,e.ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,e.ATTR_SERVICE_NAMESPACE=`service.namespace`,e.ATTR_WEBENGINE_DESCRIPTION=`webengine.description`,e.ATTR_WEBENGINE_NAME=`webengine.name`,e.ATTR_WEBENGINE_VERSION=`webengine.version`})),require_getMachineId=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMachineId=void 0;let t=__require$1(`process`),S;async function w(){if(!S)switch(t.platform){case`darwin`:S=(await import(`./getMachineId-darwin-C9wsuHP1.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`linux`:S=(await import(`./getMachineId-linux-Bt9mk0EE.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`freebsd`:S=(await import(`./getMachineId-bsd-D7C80Q-x.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`win32`:S=(await import(`./getMachineId-win-1MPHaim9.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;default:S=(await import(`./getMachineId-unsupported-DAbsbHrs.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break}return S()}e.getMachineId=w})),require_utils$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.normalizeType=e.normalizeArch=void 0,e.normalizeArch=e=>{switch(e){case`arm`:return`arm32`;case`ppc`:return`ppc32`;case`x64`:return`amd64`;default:return e}},e.normalizeType=e=>{switch(e){case`sunos`:return`solaris`;case`win32`:return`windows`;default:return e}}})),require_HostDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=require_semconv$1(),S=__require$1(`os`),w=require_getMachineId(),E=require_utils$3();e.hostDetector=new class{detect(e){return{attributes:{[t.ATTR_HOST_NAME]:(0,S.hostname)(),[t.ATTR_HOST_ARCH]:(0,E.normalizeArch)((0,S.arch)()),[t.ATTR_HOST_ID]:(0,w.getMachineId)()}}}}})),require_OSDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=require_semconv$1(),S=__require$1(`os`),w=require_utils$3();e.osDetector=new class{detect(e){return{attributes:{[t.ATTR_OS_TYPE]:(0,w.normalizeType)((0,S.platform)()),[t.ATTR_OS_VERSION]:(0,S.release)()}}}}})),require_ProcessDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_semconv$1(),w=__require$1(`os`);e.processDetector=new class{detect(e){let E={[S.ATTR_PROCESS_PID]:process.pid,[S.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[S.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[S.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[S.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[S.ATTR_PROCESS_RUNTIME_NAME]:`nodejs`,[S.ATTR_PROCESS_RUNTIME_DESCRIPTION]:`Node.js`};process.argv.length>1&&(E[S.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let e=w.userInfo();E[S.ATTR_PROCESS_OWNER]=e.username}catch(e){t.diag.debug(`error obtaining process owner: ${e}`)}return{attributes:E}}}})),require_ServiceInstanceIdDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=require_semconv$1(),S=__require$1(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,S.randomUUID)()}}}}})),require_node$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_HostDetector();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var S=require_OSDetector();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}});var w=require_ProcessDetector();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return w.processDetector}});var E=require_ServiceInstanceIdDetector();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return E.serviceInstanceIdDetector}})})),require_platform$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_node$1();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return t.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return t.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return t.serviceInstanceIdDetector}})})),require_NoopDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.NoopDetector=void 0;var t=class{detect(){return{attributes:{}}}};e.NoopDetector=t,e.noopDetector=new t})),require_detectors=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=require_EnvDetector();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var S=require_platform$1();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return S.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return S.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return S.serviceInstanceIdDetector}});var w=require_NoopDetector();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return w.noopDetector}})})),require_src$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=e.emptyResource=e.defaultResource=e.resourceFromAttributes=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=e.detectResources=void 0;var t=require_detect_resources();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var S=require_detectors();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return S.envDetector}}),Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return S.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return S.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return S.serviceInstanceIdDetector}});var w=require_ResourceImpl();Object.defineProperty(e,`resourceFromAttributes`,{enumerable:!0,get:function(){return w.resourceFromAttributes}}),Object.defineProperty(e,`defaultResource`,{enumerable:!0,get:function(){return w.defaultResource}}),Object.defineProperty(e,`emptyResource`,{enumerable:!0,get:function(){return w.emptyResource}});var E=require_default_service_name();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return E.defaultServiceName}})})),require_AggregationTemporality=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregationTemporality=void 0,(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(e.AggregationTemporality||={})})),require_MetricData=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DataPointType=e.InstrumentType=void 0,(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(e.InstrumentType||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(e.DataPointType||={})})),require_utils$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.equalsCaseInsensitive=e.binarySearchUB=e.setEquals=e.callWithTimeout=e.TimeoutError=e.instrumentationScopeId=e.hashAttributes=void 0;function t(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}e.hashAttributes=t;function S(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}e.instrumentationScopeId=S;var w=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=w;function E(e,t){let S,E=new Promise(function(e,E){S=setTimeout(function(){E(new w(`Operation timed out.`))},t)});return Promise.race([e,E]).then(e=>(clearTimeout(S),e),e=>{throw clearTimeout(S),e})}e.callWithTimeout=E;function D(e,t){if(e.size!==t.size)return!1;for(let S of e)if(!t.has(S))return!1;return!0}e.setEquals=D;function O(e,t){let S=0,w=e.length-1,E=e.length;for(;w>=S;){let D=S+Math.trunc((w-S)/2);e[D]<t?S=D+1:(E=D,w=D-1)}return E}e.binarySearchUB=O;function k(e,t){return e.toLowerCase()===t.toLowerCase()}e.equalsCaseInsensitive=k})),require_types$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregatorKind=void 0,(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(e.AggregatorKind||={})})),require_Drop=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DropAggregator=void 0;let t=require_types$2();e.DropAggregator=class{kind=t.AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,S,w){}}})),require_Histogram=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HistogramAggregator=e.HistogramAccumulation=void 0;let t=require_types$2(),S=require_MetricData(),w=require_utils$2();function E(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var D=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,S=!0,w=E(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=S,this._current=w}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=(0,w.binarySearchUB)(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.HistogramAccumulation=D,e.HistogramAggregator=class{kind=t.AggregatorKind.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new D(e,this._boundaries,this._recordMinMax)}merge(e,t){let S=e.toPointValue(),w=t.toPointValue(),E=S.buckets.counts,O=w.buckets.counts,k=Array(E.length);for(let e=0;e<E.length;e++)k[e]=E[e]+O[e];let j=1/0,F=-1/0;return this._recordMinMax&&(S.hasMinMax&&w.hasMinMax?(j=Math.min(S.min,w.min),F=Math.max(S.max,w.max)):S.hasMinMax?(j=S.min,F=S.max):w.hasMinMax&&(j=w.min,F=w.max)),new D(e.startTime,S.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:S.buckets.boundaries,counts:k},count:S.count+w.count,sum:S.sum+w.sum,hasMinMax:this._recordMinMax&&(S.hasMinMax||w.hasMinMax),min:j,max:F})}diff(e,t){let S=e.toPointValue(),w=t.toPointValue(),E=S.buckets.counts,O=w.buckets.counts,k=Array(E.length);for(let e=0;e<E.length;e++)k[e]=O[e]-E[e];return new D(t.startTime,S.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:S.buckets.boundaries,counts:k},count:w.count-S.count,sum:w.sum-S.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,w,E){return{descriptor:e,aggregationTemporality:t,dataPointType:S.DataPointType.HISTOGRAM,dataPoints:w.map(([t,w])=>{let D=w.toPointValue(),O=e.type===S.InstrumentType.GAUGE||e.type===S.InstrumentType.UP_DOWN_COUNTER||e.type===S.InstrumentType.OBSERVABLE_GAUGE||e.type===S.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:w.startTime,endTime:E,value:{min:D.hasMinMax?D.min:void 0,max:D.hasMinMax?D.max:void 0,sum:O?void 0:D.sum,buckets:D.buckets,count:D.count}}})}}}})),require_Buckets=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Buckets=void 0,e.Buckets=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new t,S=0,w=0,E=0){this.backing=e,this.indexBase=S,this.indexStart=w,this.indexEnd=E}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,S=1<<e,w=0,E=0;for(let e=this.indexStart;e<=this.indexEnd;){let D=e%S;D<0&&(D+=S);for(let O=D;O<S&&w<t;O++)this._relocateBucket(E,w),w++,e++;E++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}};var t=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,S){let w=Array(e).fill(0);w.splice(S,this._counts.length-t,...this._counts.slice(t)),w.splice(0,t,...this._counts.slice(0,t)),this._counts=w}reverse(e,t){let S=Math.floor((e+t)/2)-e;for(let w=0;w<S;w++){let S=this._counts[e+w];this._counts[e+w]=this._counts[t-w-1],this._counts[t-w-1]=S}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}})),require_ieee754=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSignificand=e.getNormalBase2=e.MIN_VALUE=e.MAX_NORMAL_EXPONENT=e.MIN_NORMAL_EXPONENT=e.SIGNIFICAND_WIDTH=void 0,e.SIGNIFICAND_WIDTH=52;let t=2146435072,S=1048575,w=1023;e.MIN_NORMAL_EXPONENT=-w+1,e.MAX_NORMAL_EXPONENT=w,e.MIN_VALUE=2**-1022;function E(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&2146435072)>>20)-w}e.getNormalBase2=E;function D(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let S=t.getUint32(0),w=t.getUint32(4);return(S&1048575)*2**32+w}e.getSignificand=D})),require_util$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.nextGreaterSquare=e.ldexp=void 0;function t(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}e.ldexp=t;function S(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}e.nextGreaterSquare=S})),require_types$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MappingError=void 0,e.MappingError=class extends Error{}})),require_ExponentMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentMapping=void 0;let t=require_ieee754(),S=require_util$1(),w=require_types$1();e.ExponentMapping=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<t.MIN_VALUE?this._minNormalLowerBoundaryIndex():t.getNormalBase2(e)+this._rightShift(t.getSignificand(e)-1,t.SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new w.MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);let E=this._maxNormalLowerBoundaryIndex();if(e>E)throw new w.MappingError(`overflow: ${e} is > maximum lower boundary: ${E}`);return S.ldexp(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=t.MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return t.MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),require_LogarithmMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogarithmMapping=void 0;let t=require_ieee754(),S=require_util$1(),w=require_types$1();e.LogarithmMapping=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=S.ldexp(Math.LOG2E,e),this._inverseFactor=S.ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=t.MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(t.getSignificand(e)===0)return(t.getNormalBase2(e)<<this._scale)-1;let S=Math.floor(Math.log(e)*this._scaleFactor),w=this._maxNormalLowerBoundaryIndex();return S>=w?w:S}lowerBoundary(e){let S=this._maxNormalLowerBoundaryIndex();if(e>=S){if(e===S)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new w.MappingError(`overflow: ${e} is > maximum lower boundary: ${S}`)}let E=this._minNormalLowerBoundaryIndex();if(e<=E){if(e===E)return t.MIN_VALUE;if(e===E-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new w.MappingError(`overflow: ${e} is < minimum lower boundary: ${E}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return t.MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(t.MAX_NORMAL_EXPONENT+1<<this._scale)-1}}})),require_getMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMapping=void 0;let t=require_ExponentMapping(),S=require_LogarithmMapping(),w=require_types$1(),E=-10,D=20,O=Array.from({length:31},(e,w)=>w>10?new S.LogarithmMapping(w-10):new t.ExponentMapping(w-10));function k(e){if(e>20||e<-10)throw new w.MappingError(`expected scale >= -10 && <= 20, got: ${e}`);return O[e+10]}e.getMapping=k})),require_ExponentialHistogram=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=void 0;let t=require_types$2(),S=require_MetricData(),w=(init_esm$2(),__toCommonJS(esm_exports$2)),E=require_Buckets(),D=require_getMapping(),O=require_util$1();var k=class e{static combine(t,S){return new e(Math.min(t.low,S.low),Math.max(t.high,S.high))}low;high;constructor(e,t){this.low=e,this.high=t}};let j=20,F=160,L=2;var B=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=160,S=!0,O=0,k=0,j=0,F=1/0,L=-1/0,B=new E.Buckets,H=new E.Buckets,q=(0,D.getMapping)(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=S,this._sum=O,this._count=k,this._zeroCount=j,this._min=F,this._max=L,this._positive=B,this._negative=H,this._mapping=q,this._maxSize<2&&(w.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
455
|
+
`,(0,w.getConflictResolutionRecipe)(E,e))}return D}}})),require_MultiWritableMetricStorage$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,S,w){this._backingStorages.forEach(E=>{E.record(e,t,S,w)})}}})),require_ObservableResult$1=__commonJSMin$1((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$1(),w=require_Instruments$1();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new S.AttributeHashMap;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,E,D={}){if(!(0,w.isObservableInstrument)(e))return;let O=this._buffer.get(e);if(O??(O=new S.AttributeHashMap,this._buffer.set(e,O)),typeof E!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${E}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(E)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),E=Math.trunc(E),!Number.isInteger(E))||O.set(D,E)}}})),require_ObservableRegistry$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_Instruments$1(),w=require_ObservableResult$1(),E=require_utils$7();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,w){let E=new Set(w.filter(S.isObservableInstrument));if(E.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,w);return}this._findBatchCallback(e,E)>=0||this._batchCallbacks.push({callback:e,instruments:E})}removeBatchCallback(e,t){let w=new Set(t.filter(S.isObservableInstrument)),E=this._findBatchCallback(e,w);E<0||this._batchCallbacks.splice(E,1)}async observe(e,t){let S=this._observeCallbacks(e,t),w=this._observeBatchCallbacks(e,t);return(await(0,E.PromiseAllSettled)([...S,...w])).filter(E.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:S,instrument:D})=>{let O=new w.ObservableResultImpl(D._descriptor.name,D._descriptor.valueType),k=Promise.resolve(S(O));t!=null&&(k=(0,E.callWithTimeout)(k,t)),await k,D._metricStorages.forEach(t=>{t.record(O._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:S,instruments:D})=>{let O=new w.BatchObservableResultImpl,k=Promise.resolve(S(O));t!=null&&(k=(0,E.callWithTimeout)(k,t)),await k,D.forEach(t=>{let S=O._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,E.setEquals)(S.instruments,t))}}})),require_SyncMetricStorage$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage$1(),S=require_DeltaMetricProcessor$1(),w=require_TemporalMetricProcessor$1();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,E,D,O){super(e),this._attributesProcessor=E,this._aggregationCardinalityLimit=O,this._deltaMetricStorage=new S.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new w.TemporalMetricProcessor(t,D)}record(e,t,S,w){t=this._attributesProcessor.process(t,S),this._deltaMetricStorage.record(e,t,S,w)}collect(e,t){let S=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,S,t)}}})),require_AttributesProcessor$1=__commonJSMin$1((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}},w=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let S={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>S[t]=e[t]),S}},E=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let S={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>S[t]=e[t]),S}};function D(){return F}e.createNoopAttributesProcessor=D;function O(e){return new S(e)}e.createMultiAttributesProcessor=O;function k(e){return new w(e)}e.createAllowListAttributesProcessor=k;function j(e){return new E(e)}e.createDenyListAttributesProcessor=j;let F=new t})),require_MeterSharedState$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor$1(),S=require_Meter$1(),w=require_utils$7(),E=require_AsyncMetricStorage$1(),D=require_MetricStorageRegistry$1(),O=require_MultiWritableMetricStorage$1(),k=require_ObservableRegistry$1(),j=require_SyncMetricStorage$1(),F=require_AttributesProcessor$1();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new D.MetricStorageRegistry;observableRegistry=new k.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new S.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,j.SyncMetricStorage);return t.length===1?t[0]:new O.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,E.AsyncMetricStorage)}async collect(e,t,S){let E=await this.observableRegistry.observe(t,S?.timeoutMillis),D=this.metricStorageRegistry.getStorages(e);if(D.length===0)return null;let O=D.map(S=>S.collect(e,t)).filter(w.isNotNullish);return O.length===0?{errors:E}:{scopeMetrics:{scope:this._instrumentationScope,metrics:O},errors:E}}_registerMetricStorage(e,S){let w=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(w=>{let E=(0,t.createInstrumentDescriptorWithView)(w,e),D=this.metricStorageRegistry.findOrUpdateCompatibleStorage(E);if(D!=null)return D;let O=new S(E,w.aggregation.createAggregator(E),w.attributesProcessor,this._meterProviderSharedState.metricCollectors,w.aggregationCardinalityLimit);return this.metricStorageRegistry.register(O),O});if(w.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,w])=>{let E=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(E!=null)return E;let D=w.createAggregator(e),O=t.selectCardinalityLimit(e.type),k=new S(e,D,(0,F.createNoopAttributesProcessor)(),[t],O);return this.metricStorageRegistry.registerForCollector(t,k),k});w=w.concat(t)}return w}}})),require_MeterProviderSharedState$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$7(),S=require_ViewRegistry$1(),w=require_MeterSharedState$1(),E=require_AggregationOption$1();e.MeterProviderSharedState=class{resource;viewRegistry=new S.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let S=(0,t.instrumentationScopeId)(e),E=this.meterSharedStates.get(S);return E??(E=new w.MeterSharedState(this,e),this.meterSharedStates.set(S,E)),E}selectAggregations(e){let t=[];for(let S of this.metricCollectors)t.push([S,(0,E.toAggregation)(S.selectAggregation(e))]);return t}}})),require_MetricCollector$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$8();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let S=(0,t.millisToHrTime)(Date.now()),w=[],E=[],D=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let D=await t.collect(this,S,e);D?.scopeMetrics!=null&&w.push(D.scopeMetrics),D?.errors!=null&&E.push(...D.errors)});return await Promise.all(D),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:w},errors:E}}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$1=__commonJSMin$1((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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate$1();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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate$1();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$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate$1(),S=require_AttributesProcessor$1(),w=require_InstrumentSelector$1(),E=require_MeterSelector$1(),D=require_AggregationOption$1();function O(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function k(e){if(O(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){k(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,D.toAggregation)(e.aggregation??{type:D.AggregationType.DEFAULT}),this.instrumentSelector=new w.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new E.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$7(),w=require_MeterProviderSharedState$1(),E=require_MetricCollector$1(),D=require_View$1();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new w.MeterProviderSharedState(e?.resource??(0,S.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new D.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new E.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,S=``,w={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:S,schemaUrl:w.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$6=__commonJSMin$1((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$1();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var S=require_MetricData$1();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return S.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return S.InstrumentType}});var w=require_MetricReader$1();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return w.MetricReader}});var E=require_PeriodicExportingMetricReader$1();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return E.PeriodicExportingMetricReader}});var D=require_InMemoryMetricExporter$1();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return D.InMemoryMetricExporter}});var O=require_ConsoleMetricExporter$1();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return O.ConsoleMetricExporter}});var k=require_MeterProvider$1();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return k.MeterProvider}});var j=require_AggregationOption$1();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return j.AggregationType}});var F=require_AttributesProcessor$1();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return F.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return F.createDenyListAttributesProcessor}});var L=require_utils$7();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return L.TimeoutError}})})),require_internal_types=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.EAggregationTemporality=void 0,(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(e.EAggregationTemporality||={})})),require_internal$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportMetricsServiceRequest=e.toMetric=e.toScopeMetrics=e.toResourceMetrics=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$6(),w=require_internal_types(),E=require_utils$8(),D=require_internal$3();function O(e,t){let S=(0,E.getOtlpEncoder)(t),w=(0,D.createResource)(e.resource);return{resource:w,schemaUrl:w.schemaUrl,scopeMetrics:k(e.scopeMetrics,S)}}e.toResourceMetrics=O;function k(e,t){return Array.from(e.map(e=>({scope:(0,D.createInstrumentationScope)(e.scope),metrics:e.metrics.map(e=>j(e,t)),schemaUrl:e.scope.schemaUrl})))}e.toScopeMetrics=k;function j(e,t){let w={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},E=q(e.aggregationTemporality);switch(e.dataPointType){case S.DataPointType.SUM:w.sum={aggregationTemporality:E,isMonotonic:e.isMonotonic,dataPoints:L(e,t)};break;case S.DataPointType.GAUGE:w.gauge={dataPoints:L(e,t)};break;case S.DataPointType.HISTOGRAM:w.histogram={aggregationTemporality:E,dataPoints:B(e,t)};break;case S.DataPointType.EXPONENTIAL_HISTOGRAM:w.exponentialHistogram={aggregationTemporality:E,dataPoints:H(e,t)};break}return w}e.toMetric=j;function F(e,S,w){let E={attributes:(0,D.toAttributes)(e.attributes),startTimeUnixNano:w.encodeHrTime(e.startTime),timeUnixNano:w.encodeHrTime(e.endTime)};switch(S){case t.ValueType.INT:E.asInt=e.value;break;case t.ValueType.DOUBLE:E.asDouble=e.value;break}return E}function L(e,t){return e.dataPoints.map(S=>F(S,e.descriptor.valueType,t))}function B(e,t){return e.dataPoints.map(e=>{let S=e.value;return{attributes:(0,D.toAttributes)(e.attributes),bucketCounts:S.buckets.counts,explicitBounds:S.buckets.boundaries,count:S.count,sum:S.sum,min:S.min,max:S.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function H(e,t){return e.dataPoints.map(e=>{let S=e.value;return{attributes:(0,D.toAttributes)(e.attributes),count:S.count,min:S.min,max:S.max,sum:S.sum,positive:{offset:S.positive.offset,bucketCounts:S.positive.bucketCounts},negative:{offset:S.negative.offset,bucketCounts:S.negative.bucketCounts},scale:S.scale,zeroCount:S.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function q(e){switch(e){case S.AggregationTemporality.DELTA:return w.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA;case S.AggregationTemporality.CUMULATIVE:return w.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE}}function J(e,t){return{resourceMetrics:e.map(e=>O(e,t))}}e.createExportMetricsServiceRequest=J})),require_metrics$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;let t=require_root(),S=require_internal$1(),w=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,E=t.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.ProtobufMetricsSerializer={serializeRequest:e=>{let t=(0,S.createExportMetricsServiceRequest)([e]);return E.encode(t).finish()},deserializeResponse:e=>w.decode(e)}})),require_protobuf$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufMetricsSerializer=void 0;var t=require_metrics$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return t.ProtobufMetricsSerializer}})})),require_internal=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createExportTraceServiceRequest=e.toOtlpSpanEvent=e.toOtlpLink=e.sdkSpanToOtlpSpan=void 0;let t=require_internal$3(),S=require_utils$8();function w(e,S){let w=e.spanContext(),O=e.status,k=e.parentSpanContext?.spanId?S.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:S.encodeSpanContext(w.traceId),spanId:S.encodeSpanContext(w.spanId),parentSpanId:k,traceState:w.traceState?.serialize(),name:e.name,kind:e.kind==null?0:e.kind+1,startTimeUnixNano:S.encodeHrTime(e.startTime),endTimeUnixNano:S.encodeHrTime(e.endTime),attributes:(0,t.toAttributes)(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>D(e,S)),droppedEventsCount:e.droppedEventsCount,status:{code:O.code,message:O.message},links:e.links.map(e=>E(e,S)),droppedLinksCount:e.droppedLinksCount}}e.sdkSpanToOtlpSpan=w;function E(e,S){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],spanId:S.encodeSpanContext(e.context.spanId),traceId:S.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpLink=E;function D(e,S){return{attributes:e.attributes?(0,t.toAttributes)(e.attributes):[],name:e.name,timeUnixNano:S.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}e.toOtlpSpanEvent=D;function O(e,t){return{resourceSpans:j(e,(0,S.getOtlpEncoder)(t))}}e.createExportTraceServiceRequest=O;function k(e){let t=new Map;for(let S of e){let e=t.get(S.resource);e||(e=new Map,t.set(S.resource,e));let w=`${S.instrumentationScope.name}@${S.instrumentationScope.version||``}:${S.instrumentationScope.schemaUrl||``}`,E=e.get(w);E||(E=[],e.set(w,E)),E.push(S)}return t}function j(e,S){let E=k(e),D=[],O=E.entries(),j=O.next();for(;!j.done;){let[e,E]=j.value,k=[],F=E.values(),L=F.next();for(;!L.done;){let e=L.value;if(e.length>0){let E=e.map(e=>w(e,S));k.push({scope:(0,t.createInstrumentationScope)(e[0].instrumentationScope),spans:E,schemaUrl:e[0].instrumentationScope.schemaUrl})}L=F.next()}let B=(0,t.createResource)(e),H={resource:B,scopeSpans:k,schemaUrl:B.schemaUrl};D.push(H),j=O.next()}return D}})),require_trace$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;let t=require_root(),S=require_internal(),w=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,E=t.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.ProtobufTraceSerializer={serializeRequest:e=>{let t=(0,S.createExportTraceServiceRequest)(e);return E.encode(t).finish()},deserializeResponse:e=>w.decode(e)}})),require_protobuf=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufTraceSerializer=void 0;var t=require_trace$1();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return t.ProtobufTraceSerializer}})})),require_logs=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;let t=require_internal$2();e.JsonLogsSerializer={serializeRequest:e=>{let S=(0,t.createExportLogsServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonLogsSerializer=void 0;var t=require_logs();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return t.JsonLogsSerializer}})})),require_metrics=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;let t=require_internal$1();e.JsonMetricsSerializer={serializeRequest:e=>{let S=(0,t.createExportMetricsServiceRequest)([e],{useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonMetricsSerializer=void 0;var t=require_metrics();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return t.JsonMetricsSerializer}})})),require_trace=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;let t=require_internal();e.JsonTraceSerializer={serializeRequest:e=>{let S=(0,t.createExportTraceServiceRequest)(e,{useHex:!0,useLongBits:!1});return new TextEncoder().encode(JSON.stringify(S))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;return JSON.parse(t.decode(e))}}})),require_json=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=void 0;var t=require_trace();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return t.JsonTraceSerializer}})})),require_src$5=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.JsonTraceSerializer=e.JsonMetricsSerializer=e.JsonLogsSerializer=e.ProtobufTraceSerializer=e.ProtobufMetricsSerializer=e.ProtobufLogsSerializer=void 0;var t=require_protobuf$2();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}});var S=require_protobuf$1();Object.defineProperty(e,`ProtobufMetricsSerializer`,{enumerable:!0,get:function(){return S.ProtobufMetricsSerializer}});var w=require_protobuf();Object.defineProperty(e,`ProtobufTraceSerializer`,{enumerable:!0,get:function(){return w.ProtobufTraceSerializer}});var E=require_json$2();Object.defineProperty(e,`JsonLogsSerializer`,{enumerable:!0,get:function(){return E.JsonLogsSerializer}});var D=require_json$1();Object.defineProperty(e,`JsonMetricsSerializer`,{enumerable:!0,get:function(){return D.JsonMetricsSerializer}});var O=require_json();Object.defineProperty(e,`JsonTraceSerializer`,{enumerable:!0,get:function(){return O.JsonTraceSerializer}})})),require_version$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`0.204.0`}));function validateAndNormalizeHeaders(e){return()=>{let t={};return Object.entries(e?.()??{}).forEach(([e,S])=>{S===void 0?diag.warn(`Header "${e}" has invalid value (${S}) and will be ignored`):t[e]=String(S)}),t}}var init_util=__esmMin((()=>{init_esm$2()}));function mergeHeaders(e,t,S){let w={...S()},E={};return()=>(t!=null&&Object.assign(E,t()),e!=null&&Object.assign(E,e()),Object.assign(E,w))}function validateUserProvidedUrl(e){if(e!=null)try{let t=globalThis.location?.href;return new URL(e,t).href}catch{throw Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function httpAgentFactoryFromOptions(e){return async t=>{let{Agent:S}=await(t===`http:`?import(`http`):import(`https`));return new S(e)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,S){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,S),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,S.headers),url:validateUserProvidedUrl(e.url)??t.url??S.url,agentFactory:e.agentFactory??t.agentFactory??S.agentFactory}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:`http://localhost:4318/`+t,agentFactory:httpAgentFactoryFromOptions({keepAlive:!0})}}var init_otlp_http_configuration=__esmMin((()=>{init_shared_configuration(),init_util()}));function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(e==null)return;let t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?t*1e3:-1;let S=new Date(e).getTime()-Date.now();return S>=0?S:0}var init_is_export_retryable=__esmMin((()=>{}));function sendWithHttp(e,t,S,w,E,D){let O=new URL(t.url),k=e({hostname:O.hostname,port:O.port,path:O.pathname,method:`POST`,headers:{...t.headers()},agent:S},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>{e.statusCode&&e.statusCode<299?E({status:`success`,data:Buffer.concat(t)}):e.statusCode&&isExportRetryable(e.statusCode)?E({status:`retryable`,retryInMillis:parseRetryAfterToMills(e.headers[`retry-after`])}):E({status:`failure`,error:new OTLPExporterError(e.statusMessage,e.statusCode,Buffer.concat(t).toString())})})});k.setTimeout(D,()=>{k.destroy(),E({status:`failure`,error:Error(`Request Timeout`)})}),k.on(`error`,e=>{E({status:`failure`,error:e})}),compressAndSend(k,t.compression,w,e=>{E({status:`failure`,error:e})})}function compressAndSend(e,t,S,w){let E=readableFromUint8Array(S);t===`gzip`&&(e.setHeader(`Content-Encoding`,`gzip`),E=E.on(`error`,w).pipe(zlib$1.createGzip()).on(`error`,w)),E.pipe(e).on(`error`,w)}function readableFromUint8Array(e){let t=new Readable;return t.push(e),t.push(null),t}var init_http_transport_utils=__esmMin((()=>{init_is_export_retryable(),init_types()}));async function requestFunctionFactory(e){let{request:t}=await(e===`http:`?import(`http`):import(`https`));return t}function createHttpExporterTransport(e){return new HttpExporterTransport(e)}var HttpExporterTransport,init_http_exporter_transport=__esmMin((()=>{init_http_transport_utils(),HttpExporterTransport=class{_parameters;_utils=null;constructor(e){this._parameters=e}async send(e,t){let{agent:S,request:w}=await this._loadUtils();return new Promise(E=>{sendWithHttp(w,this._parameters,S,e,e=>{E(e)},t)})}shutdown(){}async _loadUtils(){let e=this._utils;if(e===null){let t=new URL(this._parameters.url).protocol,[S,w]=await Promise.all([this._parameters.agentFactory(t),requestFunctionFactory(t)]);e=this._utils={agent:S,request:w}}return e}}}));function getJitter(){return 2*JITTER*Math.random()-JITTER}function createRetryingTransport(e){return new RetryingTransport(e.transport)}var MAX_ATTEMPTS,INITIAL_BACKOFF,MAX_BACKOFF,BACKOFF_MULTIPLIER,JITTER,RetryingTransport,init_retrying_transport=__esmMin((()=>{MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2,RetryingTransport=class{_transport;constructor(e){this._transport=e}retry(e,t,S){return new Promise((w,E)=>{setTimeout(()=>{this._transport.send(e,t).then(w,E)},S)})}async send(e,t){let S=Date.now()+t,w=await this._transport.send(e,t),E=MAX_ATTEMPTS,D=INITIAL_BACKOFF;for(;w.status===`retryable`&&E>0;){E--;let t=Math.max(Math.min(D,MAX_BACKOFF)+getJitter(),0);D*=BACKOFF_MULTIPLIER;let O=w.retryInMillis??t,k=S-Date.now();if(O>k)return w;w=await this.retry(e,k,O)}return w}shutdown(){return this._transport.shutdown()}}}));function createOtlpHttpExportDelegate(e,t){return createOtlpExportDelegate({transport:createRetryingTransport({transport:createHttpExporterTransport(e)}),serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}var init_otlp_http_export_delegate=__esmMin((()=>{init_otlp_export_delegate(),init_http_exporter_transport(),init_bounded_queue_export_promise_handler(),init_retrying_transport()}));function parseAndValidateTimeoutFromEnv(e){let t=process.env[e]?.trim();if(t!=null&&t!==``){let S=Number(t);if(Number.isFinite(S)&&S>0)return S;diag.warn(`Configuration: ${e} is invalid, expected number greater than 0 (actual: ${t})`)}}function getTimeoutFromEnv(e){let t=parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${e}_TIMEOUT`),S=parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_TIMEOUT`);return t??S}function parseAndValidateCompressionFromEnv(e){let t=process.env[e]?.trim();if(t!==``){if(t==null||t===`none`||t===`gzip`)return t;diag.warn(`Configuration: ${e} is invalid, expected 'none' or 'gzip' (actual: '${t}')`)}}function getCompressionFromEnv(e){let t=parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${e}_COMPRESSION`),S=parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_COMPRESSION`);return t??S}function getSharedConfigurationFromEnvironment(e){return{timeoutMillis:getTimeoutFromEnv(e),compression:getCompressionFromEnv(e)}}var init_shared_env_configuration=__esmMin((()=>{init_esm$2()}));function getStaticHeadersFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${e}_HEADERS`),S=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_HEADERS`),w=(0,import_src$8.parseKeyPairsIntoRecord)(t),E=(0,import_src$8.parseKeyPairsIntoRecord)(S);if(!(Object.keys(w).length===0&&Object.keys(E).length===0))return Object.assign({},(0,import_src$8.parseKeyPairsIntoRecord)(S),(0,import_src$8.parseKeyPairsIntoRecord)(t))}function appendRootPathToUrlIfNeeded(e){try{return new URL(e).toString()}catch{diag.warn(`Configuration: Could not parse environment-provided export URL: '${e}', falling back to undefined`);return}}function appendResourcePathToUrl(e,t){try{new URL(e)}catch{diag.warn(`Configuration: Could not parse environment-provided export URL: '${e}', falling back to undefined`);return}e.endsWith(`/`)||(e+=`/`),e+=t;try{new URL(e)}catch{diag.warn(`Configuration: Provided URL appended with '${t}' is not a valid URL, using 'undefined' instead of '${e}'`);return}return e}function getNonSpecificUrlFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_ENDPOINT`);if(t!==void 0)return appendResourcePathToUrl(t,e)}function getSpecificUrlFromEnv(e){let t=(0,import_src$8.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${e}_ENDPOINT`);if(t!==void 0)return appendRootPathToUrlIfNeeded(t)}function getHttpConfigurationFromEnvironment(e,t){return{...getSharedConfigurationFromEnvironment(e),url:getSpecificUrlFromEnv(e)??getNonSpecificUrlFromEnv(t),headers:wrapStaticHeadersInFunction(getStaticHeadersFromEnv(e))}}var import_src$8,init_otlp_http_env_configuration=__esmMin((()=>{import_src$8=require_src$9(),init_esm$2(),init_shared_env_configuration(),init_shared_configuration()}));function convertLegacyAgentOptions(e){if(typeof e.httpAgentOptions==`function`)return e.httpAgentOptions;let t=e.httpAgentOptions;if(e.keepAlive!=null&&(t={keepAlive:e.keepAlive,...t}),t!=null)return httpAgentFactoryFromOptions(t)}function convertLegacyHttpOptions(e,t,S,w){return e.metadata&&diag.warn(`Metadata cannot be set when using http`),mergeOtlpHttpConfigurationWithDefaults({url:e.url,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit,timeoutMillis:e.timeoutMillis,compression:e.compression,agentFactory:convertLegacyAgentOptions(e)},getHttpConfigurationFromEnvironment(t,S),getHttpConfigurationDefaults(w,S))}var init_convert_legacy_node_http_options=__esmMin((()=>{init_otlp_http_configuration(),init_otlp_http_env_configuration(),init_esm$2(),init_shared_configuration()})),index_node_http_exports=__exportAll({convertLegacyHttpOptions:()=>convertLegacyHttpOptions,createOtlpHttpExportDelegate:()=>createOtlpHttpExportDelegate,getSharedConfigurationFromEnvironment:()=>getSharedConfigurationFromEnvironment,httpAgentFactoryFromOptions:()=>httpAgentFactoryFromOptions}),init_index_node_http=__esmMin((()=>{init_otlp_http_configuration(),init_otlp_http_export_delegate(),init_shared_env_configuration(),init_convert_legacy_node_http_options()})),require_OTLPMetricExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;let t=require_OTLPMetricExporterBase(),S=require_src$5(),w=require_version$2(),E=(init_index_node_http(),__toCommonJS(index_node_http_exports)),D={"User-Agent":`OTel-OTLP-Exporter-JavaScript/${w.VERSION}`};e.OTLPMetricExporter=class extends t.OTLPMetricExporterBase{constructor(e){super((0,E.createOtlpHttpExportDelegate)((0,E.convertLegacyHttpOptions)(e??{},`METRICS`,`v1/metrics`,{...D,"Content-Type":`application/json`}),S.JsonMetricsSerializer),e)}}})),require_node$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;var t=require_OTLPMetricExporter();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}})})),require_platform$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporter=void 0;var t=require_node$3();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}})})),require_src$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPMetricExporterBase=e.LowMemoryTemporalitySelector=e.DeltaTemporalitySelector=e.CumulativeTemporalitySelector=e.AggregationTemporalityPreference=e.OTLPMetricExporter=void 0;var t=require_platform$3();Object.defineProperty(e,`OTLPMetricExporter`,{enumerable:!0,get:function(){return t.OTLPMetricExporter}});var S=require_OTLPMetricExporterOptions();Object.defineProperty(e,`AggregationTemporalityPreference`,{enumerable:!0,get:function(){return S.AggregationTemporalityPreference}});var w=require_OTLPMetricExporterBase();Object.defineProperty(e,`CumulativeTemporalitySelector`,{enumerable:!0,get:function(){return w.CumulativeTemporalitySelector}}),Object.defineProperty(e,`DeltaTemporalitySelector`,{enumerable:!0,get:function(){return w.DeltaTemporalitySelector}}),Object.defineProperty(e,`LowMemoryTemporalitySelector`,{enumerable:!0,get:function(){return w.LowMemoryTemporalitySelector}}),Object.defineProperty(e,`OTLPMetricExporterBase`,{enumerable:!0,get:function(){return w.OTLPMetricExporterBase}})})),require_version$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`0.204.0`})),require_OTLPTraceExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;let t=(init_esm(),__toCommonJS(esm_exports)),S=require_version$1(),w=require_src$5(),E=(init_index_node_http(),__toCommonJS(index_node_http_exports));e.OTLPTraceExporter=class extends t.OTLPExporterBase{constructor(e={}){super((0,E.createOtlpHttpExportDelegate)((0,E.convertLegacyHttpOptions)(e,`TRACES`,`v1/traces`,{"User-Agent":`OTel-OTLP-Exporter-JavaScript/${S.VERSION}`,"Content-Type":`application/json`}),w.JsonTraceSerializer))}}})),require_node$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_OTLPTraceExporter();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_platform$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_node$2();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_src$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.OTLPTraceExporter=void 0;var t=require_platform$2();Object.defineProperty(e,`OTLPTraceExporter`,{enumerable:!0,get:function(){return t.OTLPTraceExporter}})})),require_default_service_name=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._clearDefaultServiceNameCache=e.defaultServiceName=void 0;let t;function S(){if(t===void 0)try{let e=globalThis.process.argv0;t=e?`unknown_service:${e}`:`unknown_service`}catch{t=`unknown_service`}return t}e.defaultServiceName=S;function w(){t=void 0}e._clearDefaultServiceNameCache=w})),require_utils$4=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPromiseLike=void 0,e.isPromiseLike=e=>typeof e==`object`&&!!e&&typeof e.then==`function`})),require_ResourceImpl=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$13(),w=(init_esm$1(),__toCommonJS(esm_exports$1)),E=require_default_service_name(),D=require_utils$4();var O=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,S){let w=new e({},S);return w._rawAttributes=B(t),w._asyncAttributesPending=t.filter(([e,t])=>(0,D.isPromiseLike)(t)).length>0,w}constructor(e,t){let S=e.attributes??{};this._rawAttributes=Object.entries(S).map(([e,t])=>((0,D.isPromiseLike)(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=B(this._rawAttributes),this._schemaUrl=H(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[t,S]=this._rawAttributes[e];this._rawAttributes[e]=[t,(0,D.isPromiseLike)(S)?await S:S]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&t.diag.error(`Accessing resource attributes before async attributes settled`),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[S,w]of this._rawAttributes){if((0,D.isPromiseLike)(w)){t.diag.debug(`Unsettled resource attribute ${S} skipped`);continue}w!=null&&(e[S]??=w)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;let S=q(this,t),w=S?{schemaUrl:S}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],w)}};function k(e,t){return O.FromAttributeList(Object.entries(e),t)}e.resourceFromAttributes=k;function j(e,t){return new O(e,t)}e.resourceFromDetectedResource=j;function F(){return k({})}e.emptyResource=F;function L(){return k({[w.ATTR_SERVICE_NAME]:(0,E.defaultServiceName)(),[w.ATTR_TELEMETRY_SDK_LANGUAGE]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_LANGUAGE],[w.ATTR_TELEMETRY_SDK_NAME]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_NAME],[w.ATTR_TELEMETRY_SDK_VERSION]:S.SDK_INFO[w.ATTR_TELEMETRY_SDK_VERSION]})}e.defaultResource=L;function B(e){return e.map(([e,S])=>(0,D.isPromiseLike)(S)?[e,S.catch(S=>{t.diag.debug(`promise rejection for resource attribute: %s - %s`,e,S)})]:[e,S])}function H(e){if(typeof e==`string`||e===void 0)return e;t.diag.warn(`Schema URL must be string or undefined, got %s. Schema URL will be ignored.`,e)}function q(e,S){let w=e?.schemaUrl,E=S?.schemaUrl,D=w===void 0||w===``,O=E===void 0||E===``;if(D)return E;if(O||w===E)return w;t.diag.warn(`Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.`,w,E)}})),require_detect_resources=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_ResourceImpl();e.detectResources=(e={})=>(e.detectors||[]).map(w=>{try{let E=(0,S.resourceFromDetectedResource)(w.detect(e));return t.diag.debug(`${w.constructor.name} found resource.`,E),E}catch(e){return t.diag.debug(`${w.constructor.name} failed: ${e.message}`),(0,S.emptyResource)()}}).reduce((e,t)=>e.merge(t),(0,S.emptyResource)())})),require_EnvDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=(init_esm$1(),__toCommonJS(esm_exports$1)),w=require_src$13();e.envDetector=new class{_MAX_LENGTH=255;_COMMA_SEPARATOR=`,`;_LABEL_KEY_VALUE_SPLITTER=`=`;detect(e){let E={},D=(0,w.getStringFromEnv)(`OTEL_RESOURCE_ATTRIBUTES`),O=(0,w.getStringFromEnv)(`OTEL_SERVICE_NAME`);if(D)try{let e=this._parseResourceAttributes(D);Object.assign(E,e)}catch(e){t.diag.debug(`EnvDetector failed: ${e instanceof Error?e.message:e}`)}return O&&(E[S.ATTR_SERVICE_NAME]=O),{attributes:E}}_parseResourceAttributes(e){if(!e)return{};let t={},S=e.split(this._COMMA_SEPARATOR).filter(e=>e.trim()!==``);for(let e of S){let S=e.split(this._LABEL_KEY_VALUE_SPLITTER);if(S.length!==2)throw Error(`Invalid format for OTEL_RESOURCE_ATTRIBUTES: "${e}". Expected format: key=value. The ',' and '=' characters must be percent-encoded in keys and values.`);let[w,E]=S,D=w.trim(),O=E.trim();if(D.length===0)throw Error(`Invalid OTEL_RESOURCE_ATTRIBUTES: empty attribute key in "${e}".`);let k,j;try{k=decodeURIComponent(D),j=decodeURIComponent(O)}catch(t){throw Error(`Failed to percent-decode OTEL_RESOURCE_ATTRIBUTES entry "${e}": ${t instanceof Error?t.message:t}`)}if(k.length>this._MAX_LENGTH)throw Error(`Attribute key exceeds the maximum length of ${this._MAX_LENGTH} characters: "${k}".`);if(j.length>this._MAX_LENGTH)throw Error(`Attribute value exceeds the maximum length of ${this._MAX_LENGTH} characters for key "${k}".`);t[k]=j}return t}}})),require_semconv$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_WEBENGINE_VERSION=e.ATTR_WEBENGINE_NAME=e.ATTR_WEBENGINE_DESCRIPTION=e.ATTR_SERVICE_NAMESPACE=e.ATTR_SERVICE_INSTANCE_ID=e.ATTR_PROCESS_RUNTIME_VERSION=e.ATTR_PROCESS_RUNTIME_NAME=e.ATTR_PROCESS_RUNTIME_DESCRIPTION=e.ATTR_PROCESS_PID=e.ATTR_PROCESS_OWNER=e.ATTR_PROCESS_EXECUTABLE_PATH=e.ATTR_PROCESS_EXECUTABLE_NAME=e.ATTR_PROCESS_COMMAND_ARGS=e.ATTR_PROCESS_COMMAND=e.ATTR_OS_VERSION=e.ATTR_OS_TYPE=e.ATTR_K8S_POD_NAME=e.ATTR_K8S_NAMESPACE_NAME=e.ATTR_K8S_DEPLOYMENT_NAME=e.ATTR_K8S_CLUSTER_NAME=e.ATTR_HOST_TYPE=e.ATTR_HOST_NAME=e.ATTR_HOST_IMAGE_VERSION=e.ATTR_HOST_IMAGE_NAME=e.ATTR_HOST_IMAGE_ID=e.ATTR_HOST_ID=e.ATTR_HOST_ARCH=e.ATTR_CONTAINER_NAME=e.ATTR_CONTAINER_IMAGE_TAGS=e.ATTR_CONTAINER_IMAGE_NAME=e.ATTR_CONTAINER_ID=e.ATTR_CLOUD_REGION=e.ATTR_CLOUD_PROVIDER=e.ATTR_CLOUD_AVAILABILITY_ZONE=e.ATTR_CLOUD_ACCOUNT_ID=void 0,e.ATTR_CLOUD_ACCOUNT_ID=`cloud.account.id`,e.ATTR_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,e.ATTR_CLOUD_PROVIDER=`cloud.provider`,e.ATTR_CLOUD_REGION=`cloud.region`,e.ATTR_CONTAINER_ID=`container.id`,e.ATTR_CONTAINER_IMAGE_NAME=`container.image.name`,e.ATTR_CONTAINER_IMAGE_TAGS=`container.image.tags`,e.ATTR_CONTAINER_NAME=`container.name`,e.ATTR_HOST_ARCH=`host.arch`,e.ATTR_HOST_ID=`host.id`,e.ATTR_HOST_IMAGE_ID=`host.image.id`,e.ATTR_HOST_IMAGE_NAME=`host.image.name`,e.ATTR_HOST_IMAGE_VERSION=`host.image.version`,e.ATTR_HOST_NAME=`host.name`,e.ATTR_HOST_TYPE=`host.type`,e.ATTR_K8S_CLUSTER_NAME=`k8s.cluster.name`,e.ATTR_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,e.ATTR_K8S_NAMESPACE_NAME=`k8s.namespace.name`,e.ATTR_K8S_POD_NAME=`k8s.pod.name`,e.ATTR_OS_TYPE=`os.type`,e.ATTR_OS_VERSION=`os.version`,e.ATTR_PROCESS_COMMAND=`process.command`,e.ATTR_PROCESS_COMMAND_ARGS=`process.command_args`,e.ATTR_PROCESS_EXECUTABLE_NAME=`process.executable.name`,e.ATTR_PROCESS_EXECUTABLE_PATH=`process.executable.path`,e.ATTR_PROCESS_OWNER=`process.owner`,e.ATTR_PROCESS_PID=`process.pid`,e.ATTR_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`,e.ATTR_PROCESS_RUNTIME_VERSION=`process.runtime.version`,e.ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,e.ATTR_SERVICE_NAMESPACE=`service.namespace`,e.ATTR_WEBENGINE_DESCRIPTION=`webengine.description`,e.ATTR_WEBENGINE_NAME=`webengine.name`,e.ATTR_WEBENGINE_VERSION=`webengine.version`})),require_getMachineId=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMachineId=void 0;let t=__require$1(`process`),S;async function w(){if(!S)switch(t.platform){case`darwin`:S=(await import(`./getMachineId-darwin-C9wsuHP1.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`linux`:S=(await import(`./getMachineId-linux-Bt9mk0EE.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`freebsd`:S=(await import(`./getMachineId-bsd-D7C80Q-x.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;case`win32`:S=(await import(`./getMachineId-win-1MPHaim9.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break;default:S=(await import(`./getMachineId-unsupported-DAbsbHrs.mjs`).then(e=>__toESM$1(e.default))).getMachineId;break}return S()}e.getMachineId=w})),require_utils$3=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.normalizeType=e.normalizeArch=void 0,e.normalizeArch=e=>{switch(e){case`arm`:return`arm32`;case`ppc`:return`ppc32`;case`x64`:return`amd64`;default:return e}},e.normalizeType=e=>{switch(e){case`sunos`:return`solaris`;case`win32`:return`windows`;default:return e}}})),require_HostDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=require_semconv$1(),S=__require$1(`os`),w=require_getMachineId(),E=require_utils$3();e.hostDetector=new class{detect(e){return{attributes:{[t.ATTR_HOST_NAME]:(0,S.hostname)(),[t.ATTR_HOST_ARCH]:(0,E.normalizeArch)((0,S.arch)()),[t.ATTR_HOST_ID]:(0,w.getMachineId)()}}}}})),require_OSDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=require_semconv$1(),S=__require$1(`os`),w=require_utils$3();e.osDetector=new class{detect(e){return{attributes:{[t.ATTR_OS_TYPE]:(0,w.normalizeType)((0,S.platform)()),[t.ATTR_OS_VERSION]:(0,S.release)()}}}}})),require_ProcessDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_semconv$1(),w=__require$1(`os`);e.processDetector=new class{detect(e){let E={[S.ATTR_PROCESS_PID]:process.pid,[S.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[S.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[S.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[S.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[S.ATTR_PROCESS_RUNTIME_NAME]:`nodejs`,[S.ATTR_PROCESS_RUNTIME_DESCRIPTION]:`Node.js`};process.argv.length>1&&(E[S.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let e=w.userInfo();E[S.ATTR_PROCESS_OWNER]=e.username}catch(e){t.diag.debug(`error obtaining process owner: ${e}`)}return{attributes:E}}}})),require_ServiceInstanceIdDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=require_semconv$1(),S=__require$1(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,S.randomUUID)()}}}}})),require_node$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_HostDetector();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var S=require_OSDetector();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}});var w=require_ProcessDetector();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return w.processDetector}});var E=require_ServiceInstanceIdDetector();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return E.serviceInstanceIdDetector}})})),require_platform$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=require_node$1();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return t.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return t.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return t.serviceInstanceIdDetector}})})),require_NoopDetector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.NoopDetector=void 0;var t=class{detect(){return{attributes:{}}}};e.NoopDetector=t,e.noopDetector=new t})),require_detectors=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=require_EnvDetector();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var S=require_platform$1();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return S.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return S.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return S.serviceInstanceIdDetector}});var w=require_NoopDetector();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return w.noopDetector}})})),require_src$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=e.emptyResource=e.defaultResource=e.resourceFromAttributes=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=e.detectResources=void 0;var t=require_detect_resources();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var S=require_detectors();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return S.envDetector}}),Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return S.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return S.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return S.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return S.serviceInstanceIdDetector}});var w=require_ResourceImpl();Object.defineProperty(e,`resourceFromAttributes`,{enumerable:!0,get:function(){return w.resourceFromAttributes}}),Object.defineProperty(e,`defaultResource`,{enumerable:!0,get:function(){return w.defaultResource}}),Object.defineProperty(e,`emptyResource`,{enumerable:!0,get:function(){return w.emptyResource}});var E=require_default_service_name();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return E.defaultServiceName}})})),require_AggregationTemporality=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregationTemporality=void 0,(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(e.AggregationTemporality||={})})),require_MetricData=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DataPointType=e.InstrumentType=void 0,(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(e.InstrumentType||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(e.DataPointType||={})})),require_utils$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.equalsCaseInsensitive=e.binarySearchUB=e.setEquals=e.callWithTimeout=e.TimeoutError=e.instrumentationScopeId=e.hashAttributes=void 0;function t(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}e.hashAttributes=t;function S(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}e.instrumentationScopeId=S;var w=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=w;function E(e,t){let S,E=new Promise(function(e,E){S=setTimeout(function(){E(new w(`Operation timed out.`))},t)});return Promise.race([e,E]).then(e=>(clearTimeout(S),e),e=>{throw clearTimeout(S),e})}e.callWithTimeout=E;function D(e,t){if(e.size!==t.size)return!1;for(let S of e)if(!t.has(S))return!1;return!0}e.setEquals=D;function O(e,t){let S=0,w=e.length-1,E=e.length;for(;w>=S;){let D=S+Math.trunc((w-S)/2);e[D]<t?S=D+1:(E=D,w=D-1)}return E}e.binarySearchUB=O;function k(e,t){return e.toLowerCase()===t.toLowerCase()}e.equalsCaseInsensitive=k})),require_types$2=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregatorKind=void 0,(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(e.AggregatorKind||={})})),require_Drop=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DropAggregator=void 0;let t=require_types$2();e.DropAggregator=class{kind=t.AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,S,w){}}})),require_Histogram=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HistogramAggregator=e.HistogramAccumulation=void 0;let t=require_types$2(),S=require_MetricData(),w=require_utils$2();function E(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var D=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,S=!0,w=E(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=S,this._current=w}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=(0,w.binarySearchUB)(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.HistogramAccumulation=D,e.HistogramAggregator=class{kind=t.AggregatorKind.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new D(e,this._boundaries,this._recordMinMax)}merge(e,t){let S=e.toPointValue(),w=t.toPointValue(),E=S.buckets.counts,O=w.buckets.counts,k=Array(E.length);for(let e=0;e<E.length;e++)k[e]=E[e]+O[e];let j=1/0,F=-1/0;return this._recordMinMax&&(S.hasMinMax&&w.hasMinMax?(j=Math.min(S.min,w.min),F=Math.max(S.max,w.max)):S.hasMinMax?(j=S.min,F=S.max):w.hasMinMax&&(j=w.min,F=w.max)),new D(e.startTime,S.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:S.buckets.boundaries,counts:k},count:S.count+w.count,sum:S.sum+w.sum,hasMinMax:this._recordMinMax&&(S.hasMinMax||w.hasMinMax),min:j,max:F})}diff(e,t){let S=e.toPointValue(),w=t.toPointValue(),E=S.buckets.counts,O=w.buckets.counts,k=Array(E.length);for(let e=0;e<E.length;e++)k[e]=O[e]-E[e];return new D(t.startTime,S.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:S.buckets.boundaries,counts:k},count:w.count-S.count,sum:w.sum-S.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,w,E){return{descriptor:e,aggregationTemporality:t,dataPointType:S.DataPointType.HISTOGRAM,dataPoints:w.map(([t,w])=>{let D=w.toPointValue(),O=e.type===S.InstrumentType.GAUGE||e.type===S.InstrumentType.UP_DOWN_COUNTER||e.type===S.InstrumentType.OBSERVABLE_GAUGE||e.type===S.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:w.startTime,endTime:E,value:{min:D.hasMinMax?D.min:void 0,max:D.hasMinMax?D.max:void 0,sum:O?void 0:D.sum,buckets:D.buckets,count:D.count}}})}}}})),require_Buckets=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Buckets=void 0,e.Buckets=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new t,S=0,w=0,E=0){this.backing=e,this.indexBase=S,this.indexStart=w,this.indexEnd=E}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,S=1<<e,w=0,E=0;for(let e=this.indexStart;e<=this.indexEnd;){let D=e%S;D<0&&(D+=S);for(let O=D;O<S&&w<t;O++)this._relocateBucket(E,w),w++,e++;E++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}};var t=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,S){let w=Array(e).fill(0);w.splice(S,this._counts.length-t,...this._counts.slice(t)),w.splice(0,t,...this._counts.slice(0,t)),this._counts=w}reverse(e,t){let S=Math.floor((e+t)/2)-e;for(let w=0;w<S;w++){let S=this._counts[e+w];this._counts[e+w]=this._counts[t-w-1],this._counts[t-w-1]=S}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}})),require_ieee754=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSignificand=e.getNormalBase2=e.MIN_VALUE=e.MAX_NORMAL_EXPONENT=e.MIN_NORMAL_EXPONENT=e.SIGNIFICAND_WIDTH=void 0,e.SIGNIFICAND_WIDTH=52;let t=2146435072,S=1048575,w=1023;e.MIN_NORMAL_EXPONENT=-w+1,e.MAX_NORMAL_EXPONENT=w,e.MIN_VALUE=2**-1022;function E(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&2146435072)>>20)-w}e.getNormalBase2=E;function D(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let S=t.getUint32(0),w=t.getUint32(4);return(S&1048575)*2**32+w}e.getSignificand=D})),require_util$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.nextGreaterSquare=e.ldexp=void 0;function t(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}e.ldexp=t;function S(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}e.nextGreaterSquare=S})),require_types$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MappingError=void 0,e.MappingError=class extends Error{}})),require_ExponentMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentMapping=void 0;let t=require_ieee754(),S=require_util$1(),w=require_types$1();e.ExponentMapping=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<t.MIN_VALUE?this._minNormalLowerBoundaryIndex():t.getNormalBase2(e)+this._rightShift(t.getSignificand(e)-1,t.SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new w.MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);let E=this._maxNormalLowerBoundaryIndex();if(e>E)throw new w.MappingError(`overflow: ${e} is > maximum lower boundary: ${E}`);return S.ldexp(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=t.MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return t.MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),require_LogarithmMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogarithmMapping=void 0;let t=require_ieee754(),S=require_util$1(),w=require_types$1();e.LogarithmMapping=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=S.ldexp(Math.LOG2E,e),this._inverseFactor=S.ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=t.MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(t.getSignificand(e)===0)return(t.getNormalBase2(e)<<this._scale)-1;let S=Math.floor(Math.log(e)*this._scaleFactor),w=this._maxNormalLowerBoundaryIndex();return S>=w?w:S}lowerBoundary(e){let S=this._maxNormalLowerBoundaryIndex();if(e>=S){if(e===S)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new w.MappingError(`overflow: ${e} is > maximum lower boundary: ${S}`)}let E=this._minNormalLowerBoundaryIndex();if(e<=E){if(e===E)return t.MIN_VALUE;if(e===E-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new w.MappingError(`overflow: ${e} is < minimum lower boundary: ${E}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return t.MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(t.MAX_NORMAL_EXPONENT+1<<this._scale)-1}}})),require_getMapping=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMapping=void 0;let t=require_ExponentMapping(),S=require_LogarithmMapping(),w=require_types$1(),E=-10,D=20,O=Array.from({length:31},(e,w)=>w>10?new S.LogarithmMapping(w-10):new t.ExponentMapping(w-10));function k(e){if(e>20||e<-10)throw new w.MappingError(`expected scale >= -10 && <= 20, got: ${e}`);return O[e+10]}e.getMapping=k})),require_ExponentialHistogram=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=void 0;let t=require_types$2(),S=require_MetricData(),w=(init_esm$2(),__toCommonJS(esm_exports$2)),E=require_Buckets(),D=require_getMapping(),O=require_util$1();var k=class e{static combine(t,S){return new e(Math.min(t.low,S.low),Math.max(t.high,S.high))}low;high;constructor(e,t){this.low=e,this.high=t}};let j=20,F=160,L=2;var B=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=160,S=!0,O=0,k=0,j=0,F=1/0,L=-1/0,B=new E.Buckets,H=new E.Buckets,q=(0,D.getMapping)(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=S,this._sum=O,this._count=k,this._zeroCount=j,this._min=F,this._max=L,this._positive=B,this._negative=H,this._mapping=q,this._maxSize<2&&(w.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
460
456
|
changing to the minimum size of: 2`),this._maxSize=2)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new e(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,S){let w=this._mapping.mapToIndex(t),E=!1,D=0,O=0;if(e.length===0?(e.indexStart=w,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):w<e.indexStart&&e.indexEnd-w>=this._maxSize?(E=!0,O=w,D=e.indexEnd):w>e.indexEnd&&w-e.indexStart>=this._maxSize&&(E=!0,O=e.indexStart,D=w),E){let e=this._changeScale(D,O);this._downscale(e),w=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,w,S)}_incrementIndexBy(e,t,S){if(S===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){let S=e.indexEnd-t;S>=e.backing.length&&this._grow(e,S+1),e.indexStart=t}else if(t>e.indexEnd){let S=t-e.indexStart;S>=e.backing.length&&this._grow(e,S+1),e.indexEnd=t}let w=t-e.indexBase;w<0&&(w+=e.backing.length),e.incrementBucket(w,S)}_grow(e,t){let S=e.backing.length,w=e.indexBase-e.indexStart,E=S-w,D=(0,O.nextGreaterSquare)(t);D>this._maxSize&&(D=this._maxSize);let k=D-w;e.backing.growTo(D,E,k)}_changeScale(e,t){let S=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,S++;return S}_downscale(e){if(e===0)return;if(e<0)throw Error(`impossible change of scale: ${this.scale}`);let t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=(0,D.getMapping)(t)}_minScale(e){let t=Math.min(this.scale,e.scale),S=k.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),w=k.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(S.high,S.low),t-this._changeScale(w.high,w.low))}_highLowAtScale(e,t,S){if(e.length===0)return new k(0,-1);let w=t-S;return new k(e.indexStart>>w,e.indexEnd>>w)}_mergeBuckets(e,t,S,w){let E=S.offset,D=t.scale-w;for(let t=0;t<S.length;t++)this._incrementIndexBy(e,E+t>>D,S.at(t))}_diffBuckets(e,t,S,w){let E=S.offset,D=t.scale-w;for(let t=0;t<S.length;t++){let w=(E+t>>D)-e.indexBase;w<0&&(w+=e.backing.length),e.decrementBucket(w,S.at(t))}e.trim()}};e.ExponentialHistogramAccumulation=B,e.ExponentialHistogramAggregator=class{kind=t.AggregatorKind.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new B(e,this._maxSize,this._recordMinMax)}merge(e,t){let S=t.clone();return S.merge(e),S}diff(e,t){let S=t.clone();return S.diff(e),S}toMetricData(e,t,w,E){return{descriptor:e,aggregationTemporality:t,dataPointType:S.DataPointType.EXPONENTIAL_HISTOGRAM,dataPoints:w.map(([t,w])=>{let D=w.toPointValue(),O=e.type===S.InstrumentType.GAUGE||e.type===S.InstrumentType.UP_DOWN_COUNTER||e.type===S.InstrumentType.OBSERVABLE_GAUGE||e.type===S.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:w.startTime,endTime:E,value:{min:D.hasMinMax?D.min:void 0,max:D.hasMinMax?D.max:void 0,sum:O?void 0:D.sum,positive:{offset:D.positive.offset,bucketCounts:D.positive.bucketCounts},negative:{offset:D.negative.offset,bucketCounts:D.negative.bucketCounts},count:D.count,scale:D.scale,zeroCount:D.zeroCount}}})}}}})),require_LastValue=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LastValueAggregator=e.LastValueAccumulation=void 0;let t=require_types$2(),S=require_src$13(),w=require_MetricData();var E=class{startTime;_current;sampleTime;constructor(e,t=0,S=[0,0]){this.startTime=e,this._current=t,this.sampleTime=S}record(e){this._current=e,this.sampleTime=(0,S.millisToHrTime)(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.LastValueAccumulation=E,e.LastValueAggregator=class{kind=t.AggregatorKind.LAST_VALUE;createAccumulation(e){return new E(e)}merge(e,t){let w=(0,S.hrTimeToMicroseconds)(t.sampleTime)>=(0,S.hrTimeToMicroseconds)(e.sampleTime)?t:e;return new E(e.startTime,w.toPointValue(),w.sampleTime)}diff(e,t){let w=(0,S.hrTimeToMicroseconds)(t.sampleTime)>=(0,S.hrTimeToMicroseconds)(e.sampleTime)?t:e;return new E(t.startTime,w.toPointValue(),w.sampleTime)}toMetricData(e,t,S,E){return{descriptor:e,aggregationTemporality:t,dataPointType:w.DataPointType.GAUGE,dataPoints:S.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:E,value:t.toPointValue()}))}}}})),require_Sum=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SumAggregator=e.SumAccumulation=void 0;let t=require_types$2(),S=require_MetricData();var w=class{startTime;monotonic;_current;reset;constructor(e,t,S=0,w=!1){this.startTime=e,this.monotonic=t,this._current=S,this.reset=w}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.SumAccumulation=w,e.SumAggregator=class{kind=t.AggregatorKind.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new w(e,this.monotonic)}merge(e,t){let S=e.toPointValue(),E=t.toPointValue();return t.reset?new w(t.startTime,this.monotonic,E,t.reset):new w(e.startTime,this.monotonic,S+E)}diff(e,t){let S=e.toPointValue(),E=t.toPointValue();return this.monotonic&&S>E?new w(t.startTime,this.monotonic,E,!0):new w(t.startTime,this.monotonic,E-S)}toMetricData(e,t,w,E){return{descriptor:e,aggregationTemporality:t,dataPointType:S.DataPointType.SUM,dataPoints:w.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:E,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),require_aggregator=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SumAggregator=e.SumAccumulation=e.LastValueAggregator=e.LastValueAccumulation=e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=e.HistogramAggregator=e.HistogramAccumulation=e.DropAggregator=void 0;var t=require_Drop();Object.defineProperty(e,`DropAggregator`,{enumerable:!0,get:function(){return t.DropAggregator}});var S=require_Histogram();Object.defineProperty(e,`HistogramAccumulation`,{enumerable:!0,get:function(){return S.HistogramAccumulation}}),Object.defineProperty(e,`HistogramAggregator`,{enumerable:!0,get:function(){return S.HistogramAggregator}});var w=require_ExponentialHistogram();Object.defineProperty(e,`ExponentialHistogramAccumulation`,{enumerable:!0,get:function(){return w.ExponentialHistogramAccumulation}}),Object.defineProperty(e,`ExponentialHistogramAggregator`,{enumerable:!0,get:function(){return w.ExponentialHistogramAggregator}});var E=require_LastValue();Object.defineProperty(e,`LastValueAccumulation`,{enumerable:!0,get:function(){return E.LastValueAccumulation}}),Object.defineProperty(e,`LastValueAggregator`,{enumerable:!0,get:function(){return E.LastValueAggregator}});var D=require_Sum();Object.defineProperty(e,`SumAccumulation`,{enumerable:!0,get:function(){return D.SumAccumulation}}),Object.defineProperty(e,`SumAggregator`,{enumerable:!0,get:function(){return D.SumAggregator}})})),require_Aggregation=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_AGGREGATION=e.EXPONENTIAL_HISTOGRAM_AGGREGATION=e.HISTOGRAM_AGGREGATION=e.LAST_VALUE_AGGREGATION=e.SUM_AGGREGATION=e.DROP_AGGREGATION=e.DefaultAggregation=e.ExponentialHistogramAggregation=e.ExplicitBucketHistogramAggregation=e.HistogramAggregation=e.LastValueAggregation=e.SumAggregation=e.DropAggregation=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_aggregator(),w=require_MetricData();var E=class e{static DEFAULT_INSTANCE=new S.DropAggregator;createAggregator(t){return e.DEFAULT_INSTANCE}};e.DropAggregation=E;var D=class e{static MONOTONIC_INSTANCE=new S.SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new S.SumAggregator(!1);createAggregator(t){switch(t.type){case w.InstrumentType.COUNTER:case w.InstrumentType.OBSERVABLE_COUNTER:case w.InstrumentType.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}};e.SumAggregation=D;var O=class e{static DEFAULT_INSTANCE=new S.LastValueAggregator;createAggregator(t){return e.DEFAULT_INSTANCE}};e.LastValueAggregation=O;var k=class e{static DEFAULT_INSTANCE=new S.HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}};e.HistogramAggregation=k;var j=class{_boundaries;_recordMinMax;constructor(e,t=!0){if(e==null)throw Error(`ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array`);e=e.concat(),e=e.sort((e,t)=>e-t);let S=e.lastIndexOf(-1/0),w=e.indexOf(1/0);w===-1&&(w=void 0),this._boundaries=e.slice(S+1,w),this._recordMinMax=t}createAggregator(e){return new S.HistogramAggregator(this._boundaries,this._recordMinMax)}};e.ExplicitBucketHistogramAggregation=j;var F=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new S.ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}};e.ExponentialHistogramAggregation=F;var L=class{_resolve(S){switch(S.type){case w.InstrumentType.COUNTER:case w.InstrumentType.UP_DOWN_COUNTER:case w.InstrumentType.OBSERVABLE_COUNTER:case w.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:return e.SUM_AGGREGATION;case w.InstrumentType.GAUGE:case w.InstrumentType.OBSERVABLE_GAUGE:return e.LAST_VALUE_AGGREGATION;case w.InstrumentType.HISTOGRAM:return S.advice.explicitBucketBoundaries?new j(S.advice.explicitBucketBoundaries):e.HISTOGRAM_AGGREGATION}return t.diag.warn(`Unable to recognize instrument type: ${S.type}`),e.DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}};e.DefaultAggregation=L,e.DROP_AGGREGATION=new E,e.SUM_AGGREGATION=new D,e.LAST_VALUE_AGGREGATION=new O,e.HISTOGRAM_AGGREGATION=new k,e.EXPONENTIAL_HISTOGRAM_AGGREGATION=new F,e.DEFAULT_AGGREGATION=new L})),require_AggregationOption=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toAggregation=e.AggregationType=void 0;let t=require_Aggregation();var S;(function(e){e[e.DEFAULT=0]=`DEFAULT`,e[e.DROP=1]=`DROP`,e[e.SUM=2]=`SUM`,e[e.LAST_VALUE=3]=`LAST_VALUE`,e[e.EXPLICIT_BUCKET_HISTOGRAM=4]=`EXPLICIT_BUCKET_HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=5]=`EXPONENTIAL_HISTOGRAM`})(S=e.AggregationType||={});function w(e){switch(e.type){case S.DEFAULT:return t.DEFAULT_AGGREGATION;case S.DROP:return t.DROP_AGGREGATION;case S.SUM:return t.SUM_AGGREGATION;case S.LAST_VALUE:return t.LAST_VALUE_AGGREGATION;case S.EXPONENTIAL_HISTOGRAM:{let S=e;return new t.ExponentialHistogramAggregation(S.options?.maxSize,S.options?.recordMinMax)}case S.EXPLICIT_BUCKET_HISTOGRAM:{let S=e;return S.options==null?t.HISTOGRAM_AGGREGATION:new t.ExplicitBucketHistogramAggregation(S.options?.boundaries,S.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}e.toAggregation=w})),require_AggregationSelector=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e.DEFAULT_AGGREGATION_SELECTOR=void 0;let t=require_AggregationTemporality(),S=require_AggregationOption();e.DEFAULT_AGGREGATION_SELECTOR=e=>({type:S.AggregationType.DEFAULT}),e.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>t.AggregationTemporality.CUMULATIVE})),require_MetricReader=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricReader=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_utils$2(),w=require_AggregationSelector();e.MetricReader=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??w.DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??w.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw Error(`MetricReader is not bound to a MetricProducer`);if(this._shutdown)throw Error(`MetricReader is shutdown`);let[t,...S]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),w=t.errors.concat(S.flatMap(e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(S.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:w}}async shutdown(e){if(this._shutdown){t.diag.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await(0,S.callWithTimeout)(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){t.diag.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await(0,S.callWithTimeout)(this.onForceFlush(),e.timeoutMillis)}}})),require_PeriodicExportingMetricReader=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.PeriodicExportingMetricReader=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$13(),w=require_MetricReader(),E=require_utils$2(),D=require_MetricData();e.PeriodicExportingMetricReader=class extends w.MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){let{exporter:S,exportIntervalMillis:w=6e4,metricProducers:E,cardinalityLimits:O}=e,{exportTimeoutMillis:k=3e4}=e;if(super({aggregationSelector:S.selectAggregation?.bind(S),aggregationTemporalitySelector:S.selectAggregationTemporality?.bind(S),metricProducers:E,cardinalitySelector:e=>{let t={default:2e3,...O};switch(e){case D.InstrumentType.COUNTER:return t.counter??t.default;case D.InstrumentType.GAUGE:return t.gauge??t.default;case D.InstrumentType.HISTOGRAM:return t.histogram??t.default;case D.InstrumentType.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case D.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case D.InstrumentType.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case D.InstrumentType.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),w<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(k<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(w<k){if(`exportIntervalMillis`in e&&`exportTimeoutMillis`in e)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);t.diag.info(`Timeout of ${k} exceeds the interval of ${w}. Clamping timeout to interval duration.`),k=w}this._exportInterval=w,this._exportTimeout=k,this._exporter=S}async _runOnce(){try{await(0,E.callWithTimeout)(this._doRun(),this._exportTimeout)}catch(e){if(e instanceof E.TimeoutError){t.diag.error(`Export took longer than %s milliseconds and timed out.`,this._exportTimeout);return}(0,S.globalErrorHandler)(e)}}async _doRun(){let{resourceMetrics:e,errors:w}=await this.collect({timeoutMillis:this._exportTimeout});if(w.length>0&&t.diag.error(`PeriodicExportingMetricReader: metrics collection errors`,...w),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){t.diag.debug(`Error while resolving async portion of resource: `,e),(0,S.globalErrorHandler)(e)}if(e.scopeMetrics.length===0)return;let E=await S.internal._export(this._exporter,e);if(E.code!==S.ExportResultCode.SUCCESS)throw Error(`PeriodicExportingMetricReader: metrics export failed (error ${E.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!=`number`&&this._interval.unref()}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}})),require_InMemoryMetricExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryMetricExporter=void 0;let t=require_src$13();e.InMemoryMetricExporter=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,S){if(this._shutdown){setTimeout(()=>S({code:t.ExportResultCode.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>S({code:t.ExportResultCode.SUCCESS}),0)}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}})),require_ConsoleMetricExporter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleMetricExporter=void 0;let t=require_src$13(),S=require_AggregationSelector();e.ConsoleMetricExporter=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??S.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(S,w){if(this._shutdown){w({code:t.ExportResultCode.FAILED});return}return e._sendMetrics(S,w)}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,S){for(let t of e.scopeMetrics)for(let e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});S({code:t.ExportResultCode.SUCCESS})}}})),require_ViewRegistry=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ViewRegistry=void 0,e.ViewRegistry=class{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(S=>this._matchInstrument(S.instrumentSelector,e)&&this._matchMeter(S.meterSelector,t))}_matchInstrument(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))}}})),require_InstrumentDescriptor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isValidName=e.isDescriptorCompatibleWith=e.createInstrumentDescriptorWithView=e.createInstrumentDescriptor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_utils$2();function w(e,S,w){return k(e)||t.diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:S,description:w?.description??``,unit:w?.unit??``,valueType:w?.valueType??t.ValueType.DOUBLE,advice:w?.advice??{}}}e.createInstrumentDescriptor=w;function E(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}e.createInstrumentDescriptorWithView=E;function D(e,t){return(0,S.equalsCaseInsensitive)(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}e.isDescriptorCompatibleWith=D;let O=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function k(e){return O.test(e)}e.isValidName=k})),require_Instruments=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isObservableInstrument=e.ObservableUpDownCounterInstrument=e.ObservableGaugeInstrument=e.ObservableCounterInstrument=e.ObservableInstrument=e.HistogramInstrument=e.GaugeInstrument=e.CounterInstrument=e.UpDownCounterInstrument=e.SyncInstrument=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_src$13();var w=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,w={},E=t.context.active()){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,w,E,(0,S.millisToHrTime)(Date.now()))}};e.SyncInstrument=w,e.UpDownCounterInstrument=class extends w{add(e,t,S){this._record(e,t,S)}},e.CounterInstrument=class extends w{add(e,S,w){if(e<0){t.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,S,w)}},e.GaugeInstrument=class extends w{record(e,t,S){this._record(e,t,S)}},e.HistogramInstrument=class extends w{record(e,S,w){if(e<0){t.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,S,w)}};var E=class{_metricStorages;_descriptor;_observableRegistry;constructor(e,t,S){this._descriptor=e,this._metricStorages=t,this._observableRegistry=S}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}};e.ObservableInstrument=E,e.ObservableCounterInstrument=class extends E{},e.ObservableGaugeInstrument=class extends E{},e.ObservableUpDownCounterInstrument=class extends E{};function D(e){return e instanceof E}e.isObservableInstrument=D})),require_Meter=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Meter=void 0;let t=require_InstrumentDescriptor(),S=require_Instruments(),w=require_MetricData();e.Meter=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.GAUGE,E),O=this._meterSharedState.registerMetricStorage(D);return new S.GaugeInstrument(O,D)}createHistogram(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.HISTOGRAM,E),O=this._meterSharedState.registerMetricStorage(D);return new S.HistogramInstrument(O,D)}createCounter(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.COUNTER,E),O=this._meterSharedState.registerMetricStorage(D);return new S.CounterInstrument(O,D)}createUpDownCounter(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.UP_DOWN_COUNTER,E),O=this._meterSharedState.registerMetricStorage(D);return new S.UpDownCounterInstrument(O,D)}createObservableGauge(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.OBSERVABLE_GAUGE,E),O=this._meterSharedState.registerAsyncMetricStorage(D);return new S.ObservableGaugeInstrument(D,O,this._meterSharedState.observableRegistry)}createObservableCounter(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.OBSERVABLE_COUNTER,E),O=this._meterSharedState.registerAsyncMetricStorage(D);return new S.ObservableCounterInstrument(D,O,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,E){let D=(0,t.createInstrumentDescriptor)(e,w.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER,E),O=this._meterSharedState.registerAsyncMetricStorage(D);return new S.ObservableUpDownCounterInstrument(D,O,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),require_MetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricStorage=void 0;let t=require_InstrumentDescriptor();e.MetricStorage=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=(0,t.createInstrumentDescriptor)(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),require_HashMap=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AttributeHashMap=e.HashMap=void 0;let t=require_utils$2();var S=class{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){let S=this._hash(e);if(this._valueMap.has(S))return this._valueMap.get(S);let w=t();return this._keyMap.has(S)||this._keyMap.set(S,e),this._valueMap.set(S,w),w}set(e,t,S){S??=this._hash(e),this._keyMap.has(S)||this._keyMap.set(S,e),this._valueMap.set(S,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){let e=this._keyMap.entries(),t=e.next();for(;t.done!==!0;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){let e=this._valueMap.entries(),t=e.next();for(;t.done!==!0;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}};e.HashMap=S,e.AttributeHashMap=class extends S{constructor(){super(t.hashAttributes)}}})),require_DeltaMetricProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DeltaMetricProcessor=void 0;let t=require_utils$2(),S=require_HashMap();e.DeltaMetricProcessor=class{_activeCollectionStorage=new S.AttributeHashMap;_cumulativeMemoStorage=new S.AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,S){this._aggregator=e,this._cardinalityLimit=(S??2e3)-1,this._overflowHashCode=(0,t.hashAttributes)(this._overflowAttributes)}record(e,t,S,w){let E=this._activeCollectionStorage.get(t);if(!E){if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(w))?.record(e);return}E=this._aggregator.createAccumulation(w),this._activeCollectionStorage.set(t,E)}E?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,S,w])=>{let E=this._aggregator.createAccumulation(t);E?.record(S);let D=E;if(this._cumulativeMemoStorage.has(e,w)){let t=this._cumulativeMemoStorage.get(e,w);D=this._aggregator.diff(t,E)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,w=this._overflowHashCode,this._cumulativeMemoStorage.has(e,w))){let t=this._cumulativeMemoStorage.get(e,w);D=this._aggregator.diff(t,E)}if(this._activeCollectionStorage.has(e,w)){let t=this._activeCollectionStorage.get(e,w);D=this._aggregator.merge(t,D)}this._cumulativeMemoStorage.set(e,E,w),this._activeCollectionStorage.set(e,D,w)})}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new S.AttributeHashMap,e}}})),require_TemporalMetricProcessor=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TemporalMetricProcessor=void 0;let t=require_AggregationTemporality(),S=require_HashMap();e.TemporalMetricProcessor=class e{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(S,E,D,O){this._stashAccumulations(D);let k=this._getMergedUnreportedAccumulations(S),j=k,F;if(this._reportHistory.has(S)){let w=this._reportHistory.get(S),E=w.collectionTime;F=w.aggregationTemporality,j=F===t.AggregationTemporality.CUMULATIVE?e.merge(w.accumulations,k,this._aggregator):e.calibrateStartTime(w.accumulations,k,E)}else F=S.selectAggregationTemporality(E.type);this._reportHistory.set(S,{accumulations:j,collectionTime:O,aggregationTemporality:F});let L=w(j);if(L.length!==0)return this._aggregator.toMetricData(E,F,L,O)}_stashAccumulations(e){let t=this._unreportedAccumulations.keys();for(let S of t){let t=this._unreportedAccumulations.get(S);t===void 0&&(t=[],this._unreportedAccumulations.set(S,t)),t.push(e)}}_getMergedUnreportedAccumulations(t){let w=new S.AttributeHashMap,E=this._unreportedAccumulations.get(t);if(this._unreportedAccumulations.set(t,[]),E===void 0)return w;for(let t of E)w=e.merge(w,t,this._aggregator);return w}static merge(e,t,S){let w=e,E=t.entries(),D=E.next();for(;D.done!==!0;){let[t,O,k]=D.value;if(e.has(t,k)){let E=e.get(t,k),D=S.merge(E,O);w.set(t,D,k)}else w.set(t,O,k);D=E.next()}return w}static calibrateStartTime(e,t,S){for(let[w,E]of e.keys())t.get(w,E)?.setStartTime(S);return t}};function w(e){return Array.from(e.entries())}})),require_AsyncMetricStorage=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AsyncMetricStorage=void 0;let t=require_MetricStorage(),S=require_DeltaMetricProcessor(),w=require_TemporalMetricProcessor(),E=require_HashMap();e.AsyncMetricStorage=class extends t.MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,E,D,O){super(e),this._aggregationCardinalityLimit=O,this._deltaMetricStorage=new S.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new w.TemporalMetricProcessor(t,D),this._attributesProcessor=E}record(e,t){let S=new E.AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{S.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(S,t)}collect(e,t){let S=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,S,t)}}})),require_RegistrationConflicts=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getConflictResolutionRecipe=e.getDescriptionResolutionRecipe=e.getTypeConflictResolutionRecipe=e.getUnitConflictResolutionRecipe=e.getValueTypeConflictResolutionRecipe=e.getIncompatibilityDetails=void 0;function t(e,t){let S=``;return e.unit!==t.unit&&(S+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(S+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(S+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(S+=`\t- Description '${e.description}' does not match '${t.description}'\n`),S}e.getIncompatibilityDetails=t;function S(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}e.getValueTypeConflictResolutionRecipe=S;function w(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}e.getUnitConflictResolutionRecipe=w;function E(e,t){let S={name:t.name,type:t.type,unit:t.unit},w=JSON.stringify(S);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${w}'`}e.getTypeConflictResolutionRecipe=E;function D(e,t){let S={name:t.name,type:t.type,unit:t.unit},w=JSON.stringify(S);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${w}'
|
|
461
457
|
\t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${w}
|
|
462
458
|
\t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${w}`}e.getDescriptionResolutionRecipe=D;function O(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:D(e,t):E(e,t):w(e,t):S(e,t)}e.getConflictResolutionRecipe=O})),require_MetricStorageRegistry=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricStorageRegistry=void 0;let t=require_InstrumentDescriptor(),S=(init_esm$2(),__toCommonJS(esm_exports$2)),w=require_RegistrationConflicts();e.MetricStorageRegistry=class e{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new e}getStorages(e){let t=[];for(let e of this._sharedRegistry.values())t=t.concat(e);let S=this._perCollectorRegistry.get(e);if(S!=null)for(let e of S.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let S=this._perCollectorRegistry.get(e);S??(S=new Map,this._perCollectorRegistry.set(e,S)),this._registerStorage(t,S)}findOrUpdateCompatibleStorage(e){let t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){let S=this._perCollectorRegistry.get(e);if(S===void 0)return null;let w=S.get(t.name);return w===void 0?null:this._findOrUpdateCompatibleStorage(t,w)}_registerStorage(e,t){let S=e.getInstrumentDescriptor(),w=t.get(S.name);if(w===void 0){t.set(S.name,[e]);return}w.push(e)}_findOrUpdateCompatibleStorage(e,E){let D=null;for(let O of E){let E=O.getInstrumentDescriptor();(0,t.isDescriptorCompatibleWith)(E,e)?(E.description!==e.description&&(e.description.length>E.description.length&&O.updateDescription(e.description),S.diag.warn(`A view or instrument with the name `,e.name,` has already been registered, but has a different description and is incompatible with another registered view.
|
|
@@ -470,7 +466,7 @@ To resolve the conflict:`,(0,w.getConflictResolutionRecipe)(E,e))),D=O):S.diag.w
|
|
|
470
466
|
`,`\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
|
|
471
467
|
`))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
|
|
472
468
|
`,{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),w=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(S===42){if(w>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(w>=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)&&w>maximumTiffStreamIfdOffsetInBytes)return t;let S=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,w,{maximumLength:S,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let E;try{E=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return E??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)}const STALE_TMP_AGE_MS=3e4,DEFAULT_FS={writeFile:(e,t,S)=>writeFile(e,t,S),rename:(e,t)=>rename(e,t)};async function sweepStaleTmps(e){try{let t=dirname(e),S=`${basename(e)}.tmp.`,w=Date.now()-STALE_TMP_AGE_MS,E=await readdir(t);await Promise.all(E.map(async e=>{if(!e.startsWith(S))return;let E=join(t,e);try{(await stat$1(E)).mtimeMs<w&&await unlink(E)}catch{}}))}catch{}}function sweepStaleTmpsSync(e){try{let t=dirname(e),S=`${basename(e)}.tmp.`,w=Date.now()-STALE_TMP_AGE_MS;for(let e of readdirSync(t)){if(!e.startsWith(S))continue;let E=join(t,e);try{statSync(E).mtimeMs<w&&unlinkSync(E)}catch{}}}catch{}}async function atomicWriteFile(e,t,S={}){await sweepStaleTmps(e);let w=S.fs??DEFAULT_FS,E=`${e}.tmp.${crypto.randomUUID()}`;try{await w.writeFile(E,t,{encoding:`utf-8`,mode:S.mode??420}),await w.rename(E,e)}catch(e){try{unlinkSync(E)}catch{}throw e}}function atomicWriteFileSync(e,t,S={}){sweepStaleTmpsSync(e);let w=`${e}.tmp.${crypto.randomUUID()}`;try{writeFileSync(w,t,{encoding:`utf-8`,mode:S.mode??420}),renameSync(w,e)}catch(e){try{unlinkSync(w)}catch{}throw e}}var FileLockTimeoutError=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};const sleep=e=>new Promise(t=>{setTimeout(t,e)});async function withFileLock(e,t,S={}){let w=S.timeoutMs??5e3,E=S.retryIntervalMs??25,D=w*2,O=Date.now()+w;for(;;){let k;try{k=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let k;try{let t=statSync(e);k=Date.now()-t.mtimeMs}catch{continue}let j=!1;if(k>D){S.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:k,staleThresholdMs:D});try{unlinkSync(e),j=!0}catch{}}if(j)continue;if(Date.now()>=O)throw new FileLockTimeoutError(e,w);await sleep(E);continue}try{return await t()}finally{try{closeSync(k)}catch{}try{unlinkSync(e)}catch{}}}}function sleepSyncBusy(e){let t=Date.now()+e;for(;Date.now()<t;);}function withFileLockSync(e,t,S={}){let w=S.timeoutMs??5e3,E=S.retryIntervalMs??25,D=w*2,O=Date.now()+w;for(;;){let k;try{k=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let k;try{let t=statSync(e);k=Date.now()-t.mtimeMs}catch{continue}let j=!1;if(k>D){S.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:k,staleThresholdMs:D});try{unlinkSync(e),j=!0}catch{}}if(j)continue;if(Date.now()>=O)throw new FileLockTimeoutError(e,w);sleepSyncBusy(E);continue}try{return t()}finally{try{closeSync(k)}catch{}try{unlinkSync(e)}catch{}}}}const CONFIG_FILENAME=`config.yml`,USER_CONFIG_FILENAME=`global.yml`;function schemaUrl(e){return`https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/${e===`user`?`config.user.schema.json`:e===`project-local`?`config.project-local.schema.json`:`config.project.schema.json`}`}function defaultFirstWriteHeader(e){return`# yaml-language-server: $schema=${schemaUrl(e)}\n`}function resolveConfigPath(e,t,S){if(e===`user`)return resolve(S??homedir(),`.ok`,USER_CONFIG_FILENAME);let w=isAbsolute(t)?t:resolve(t);return e===`project-local`?resolve(w,`.ok`,LOCAL_DIR,CONFIG_FILENAME):resolve(w,`.ok`,CONFIG_FILENAME)}function err(e){return{ok:!1,error:e}}function ok(e){return{ok:!0,...e}}async function writeConfigPatch(e){return withConfigSpan(`config.patch`,{"config.scope":e.scope,"config.transport":`fs`},async t=>{let S=await writeConfigPatchInner(e);return t.setAttribute(`config.outcome`,S.ok?`success`:`rejected`),S.ok||t.setAttribute(`config.error.code`,S.error.code),S})}async function writeConfigPatchInner(e){let{cwd:t,scope:S,patch:w,homedirOverride:E}=e,D=resolveConfigPath(S,t,E),O=validatePatchScopes(w,S);if(O!==null)return err(O);try{await mkdir(dirname(D),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${D}: ${e instanceof Error?e.message:String(e)}`})}try{return await withFileLock(`${D}.lock`,()=>writeConfigPatchLocked(e,D))}catch(e){if(e instanceof FileLockTimeoutError)return err({code:`WRITE_ERROR`,detail:e.message});throw e}}async function writeConfigPatchLocked(e,t){let{patch:S,scope:w,firstWriteHeader:E}=e,D=``,O=!1;if(existsSync(t)){O=!0;try{D=readFileSync(t,`utf-8`)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not read existing config: ${e instanceof Error?e.message:String(e)}`})}}let k=(0,import_dist$1.parseDocument)(D);if(k.errors.length>0)return err({code:`YAML_PARSE`,detail:k.errors.map(e=>e.message).join(`; `)});if(k.contents===null)k.contents=k.createNode({});else if(!(0,import_dist$1.isMap)(k.contents))return err({code:`YAML_PARSE`,detail:`Top-level YAML value must be a mapping (object), got ${(0,import_dist$1.isSeq)(k.contents)?`sequence`:`scalar`}`});let j=applyPatchToDocument(k,S),F=k.toJSON(),L=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L2`},e=>{let t=ConfigSchema$1.safeParse(F);if(e.setAttribute(`config.outcome`,t.success?`success`:`rejected`),!t.success)for(let e of t.error.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":e.path.map(e=>String(e)).join(`.`),"issue.message":e.message});return t});if(!L.success)return err({code:`SCHEMA_INVALID`,issues:L.error.issues.map(toConfigIssue)});let B=k.toString();if(!O){let e=E===void 0?defaultFirstWriteHeader(w):E??``;e.length>0&&(B=`${e.endsWith(`
|
|
473
|
-
`)?e:`${e}\n`}${B}`)}try{await mkdir(dirname(t),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${t}: ${e instanceof Error?e.message:String(e)}`})}try{await atomicWriteFile(t,B)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not write ${t}: ${e instanceof Error?e.message:String(e)}`})}return ok({effective:L.data,appliedPaths:j,path:t,created:!O})}function buildSchemaInvalidError(e,t,S,w){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let E=e.path.map(e=>typeof e==`symbol`?String(e):e),D=locateIssue({file:w,source:S,doc:t,path:E});return{path:E,message:e.message,issueCode:e.code,...D===void 0?{}:{source:D}}})}}function attemptSideline(e,t,S){let w=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return renameSync(e,w),w}catch(t){S(`[config] Could not sideline invalid config file ${e} → ${w}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function readConfigSafely(e){let{absPath:t,sideline:S=!0,timestamp:w=new Date().toISOString()}=e,E=e.warn??(e=>console.warn(e)),D=ConfigSchema$1.parse({});if(!existsSync(t))return{valid:!0,value:D,source:void 0};let O;try{O=readFileSync(t,`utf-8`)}catch(e){let S=e instanceof Error?e.message:String(e);return E(`[config] Could not read ${t}: ${S}. Using schema defaults.`),{valid:!1,value:D,error:{code:`UNKNOWN`,message:`Read failed: ${S}`}}}let k=(0,import_dist$1.parseDocument)(O);if(k.errors.length>0){let e=k.errors.map(e=>e.message).join(`; `);E(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let O=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:{code:`YAML_PARSE`,detail:e},...O===void 0?{}:{sidelinedTo:O}}}let j=k.toJSON()??{},F=ConfigSchema$1.safeParse(j);if(!F.success){let e=buildSchemaInvalidError(F,k,O,t);E(`[config] ${t} fails schema validation (${F.error.issues.length} issue(s)). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let j=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:e,...j===void 0?{}:{sidelinedTo:j}}}return{valid:!0,value:F.data,source:t}}var require_dist$1=__commonJSMin$1(((e,t)=>{function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}let w=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function E(e){if(Buffer.isBuffer(e))return e;if(typeof e==`number`)return Buffer.alloc(e);if(typeof e==`string`)return Buffer.from(e);throw Error(`input must be buffer, number, or string, received `+typeof e)}function D(e){let t=E(4);return t.writeInt32BE(e,0),t}function O(e,t){e=E(e),Buffer.isBuffer(t)&&(t=t.readUInt32BE(0));let S=~~t^-1;for(var D=0;D<e.length;D++)S=w[(S^e[D])&255]^S>>>8;return S^-1}function k(){return D(O.apply(null,arguments))}k.signed=function(){return O.apply(null,arguments)},k.unsigned=function(){return O.apply(null,arguments)>>>0},t.exports=S(k)})),require_yazl=__commonJSMin$1((e=>{var t=__require$1(`fs`),S=__require$1(`stream`).Transform,w=__require$1(`stream`).PassThrough,E=__require$1(`zlib`),D=__require$1(`util`),O=__require$1(`events`).EventEmitter,k=__require$1(`events`).errorMonitor,j=require_dist$1();e.ZipFile=F,D.inherits(F,O);function F(){this.outputStream=new w,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1,this.errored=!1,this.on(k,function(){this.errored=!0})}F.prototype.addFile=function(e,S,w){var E=this;if(S=se(S,!1),w??={},!ee(E)){var D=new ue(S,!1,w);E.entries.push(D),t.stat(e,function(S,O){if(S)return E.emit(`error`,S);if(!O.isFile())return E.emit(`error`,Error(`not a file: `+e));D.uncompressedSize=O.size,w.mtime??D.setLastModDate(O.mtime),w.mode??D.setFileAttributesMode(O.mode),D.setFileDataPumpFunction(function(){var S=t.createReadStream(e);D.state=ue.FILE_DATA_IN_PROGRESS,S.on(`error`,function(e){E.emit(`error`,e)}),H(E,D,S)}),J(E)})}},F.prototype.addReadStream=function(e,t,S){this.addReadStreamLazy(t,S,function(t){t(null,e)})},F.prototype.addReadStreamLazy=function(e,t,S){var w=this;if(typeof t==`function`&&(S=t,t=null),t??={},e=se(e,!1),!ee(w)){var E=new ue(e,!1,t);w.entries.push(E),E.setFileDataPumpFunction(function(){E.state=ue.FILE_DATA_IN_PROGRESS,S(function(e,t){if(e)return w.emit(`error`,e);H(w,E,t)})}),J(w)}},F.prototype.addBuffer=function(e,t,S){var w=this;if(t=se(t,!1),e.length>1073741823)throw Error(`buffer too large: `+e.length+` > 1073741823`);if(S??={},S.size!=null)throw Error(`options.size not allowed`);if(ee(w))return;var D=new ue(t,!1,S);D.uncompressedSize=e.length,D.crc32=j.unsigned(e),D.crcAndFileSizeKnown=!0,w.entries.push(D),D.compressionLevel===0?O(e):E.deflateRaw(e,{level:D.compressionLevel},function(e,t){O(t)});function O(e){D.compressedSize=e.length,D.setFileDataPumpFunction(function(){B(w,e),B(w,D.getDataDescriptor()),D.state=ue.FILE_DATA_DONE,setImmediate(function(){J(w)})}),J(w)}},F.prototype.addEmptyDirectory=function(e,t){var S=this;if(e=se(e,!0),t??={},t.size!=null)throw Error(`options.size not allowed`);if(t.compress!=null)throw Error(`options.compress not allowed`);if(t.compressionLevel!=null)throw Error(`options.compressionLevel not allowed`);if(!ee(S)){var w=new ue(e,!0,t);S.entries.push(w),w.setFileDataPumpFunction(function(){B(S,w.getDataDescriptor()),w.state=ue.FILE_DATA_DONE,J(S)}),J(S)}};var L=Ge([80,75,5,6]);F.prototype.end=function(e,t){if(typeof e==`function`&&(t=e,e=null),e??={},!this.ended&&(this.ended=!0,!this.errored)){if(this.calculatedTotalSizeCallback=t,this.forceZip64Eocd=!!e.forceZip64Format,e.comment){if(typeof e.comment==`string`?this.comment=Ue(e.comment):this.comment=e.comment,this.comment.length>65535)throw Error(`comment is too large`);if(Ke(this.comment,L))throw Error(`comment contains end of central directory record signature`)}else this.comment=ce;J(this)}};function B(e,t){e.outputStream.write(t),e.outputStreamCursor+=t.length}function H(e,t,S){var D=new ze,O=new Re,k=t.compressionLevel===0?new w:new E.DeflateRaw({level:t.compressionLevel}),j=new Re;S.pipe(D).pipe(O).pipe(k).pipe(j).pipe(e.outputStream,{end:!1}),j.on(`end`,function(){if(t.crc32=D.crc32,t.uncompressedSize==null)t.uncompressedSize=O.byteCount;else if(t.uncompressedSize!==O.byteCount)return e.emit(`error`,Error(`file data stream has unexpected number of bytes`));t.compressedSize=j.byteCount,e.outputStreamCursor+=t.compressedSize,B(e,t.getDataDescriptor()),t.state=ue.FILE_DATA_DONE,J(e)})}function q(e){if(e.compress!=null&&e.compressionLevel!=null&&!!e.compress!=!!e.compressionLevel)throw Error(`conflicting settings for compress and compressionLevel`);return e.compressionLevel==null?e.compress===!1?0:6:e.compressionLevel}function J(e){if(e.allDone||e.errored)return;if(e.ended&&e.calculatedTotalSizeCallback!=null){var t=Y(e);t!=null&&(e.calculatedTotalSizeCallback(t),e.calculatedTotalSizeCallback=null)}var S=w();function w(){for(var t=0;t<e.entries.length;t++){var S=e.entries[t];if(S.state<ue.FILE_DATA_DONE)return S}return null}if(S!=null){if(S.state<ue.READY_TO_PUMP_FILE_DATA||S.state===ue.FILE_DATA_IN_PROGRESS)return;S.relativeOffsetOfLocalHeader=e.outputStreamCursor,B(e,S.getLocalFileHeader()),S.doFileDataPump()}else e.ended&&(e.offsetOfStartOfCentralDirectory=e.outputStreamCursor,e.entries.forEach(function(t){B(e,t.getCentralDirectoryRecord())}),B(e,oe(e)),e.outputStream.end(),e.allDone=!0)}function Y(e){for(var t=0,S=0,w=0;w<e.entries.length;w++){var E=e.entries[w];if(E.compressionLevel!==0)return-1;if(E.state>=ue.READY_TO_PUMP_FILE_DATA){if(E.uncompressedSize==null)return-1}else if(E.uncompressedSize==null)return null;E.relativeOffsetOfLocalHeader=t;var D=E.useZip64Format();t+=de+E.utf8FileName.length,t+=E.uncompressedSize,E.crcAndFileSizeKnown||(D?t+=Ce:t+=ye),S+=we+E.utf8FileName.length+E.fileComment.length,E.forceDosTimestamp||(S+=Te),D&&(S+=De)}var O=0;return(e.forceZip64Eocd||e.entries.length>=65535||S>=65535||t>=4294967295)&&(O+=te+ne),O+=ae+e.comment.length,t+S+O}function ee(e){if(e.ended)throw Error(`cannot add entries after calling end()`);return!!e.errored}var te=56,ne=20,ae=22;function oe(e,t){var S=!1,w=e.entries.length;(e.forceZip64Eocd||e.entries.length>=65535)&&(w=65535,S=!0);var E=e.outputStreamCursor-e.offsetOfStartOfCentralDirectory,D=E;(e.forceZip64Eocd||E>=4294967295)&&(D=4294967295,S=!0);var O=e.offsetOfStartOfCentralDirectory;if((e.forceZip64Eocd||e.offsetOfStartOfCentralDirectory>=4294967295)&&(O=4294967295,S=!0),t)return S?te+ne+ae:ae;var k=We(ae+e.comment.length);if(k.writeUInt32LE(101010256,0),k.writeUInt16LE(0,4),k.writeUInt16LE(0,6),k.writeUInt16LE(w,8),k.writeUInt16LE(w,10),k.writeUInt32LE(D,12),k.writeUInt32LE(O,16),k.writeUInt16LE(e.comment.length,20),e.comment.copy(k,22),!S)return k;var j=We(te);j.writeUInt32LE(101075792,0),Ie(j,te-12,4),j.writeUInt16LE(ge,12),j.writeUInt16LE(me,14),j.writeUInt32LE(0,16),j.writeUInt32LE(0,20),Ie(j,e.entries.length,24),Ie(j,e.entries.length,32),Ie(j,E,40),Ie(j,e.offsetOfStartOfCentralDirectory,48);var F=We(ne);return F.writeUInt32LE(117853008,0),F.writeUInt32LE(0,4),Ie(F,e.outputStreamCursor,8),F.writeUInt32LE(1,16),Buffer.concat([j,F,k])}function se(e,t){if(e===``)throw Error(`empty metadataPath`);if(e=e.replace(/\\/g,`/`),/^[a-zA-Z]:/.test(e)||/^\//.test(e))throw Error(`absolute path: `+e);if(e.split(`/`).indexOf(`..`)!==-1)throw Error(`invalid relative path: `+e);var S=/\/$/.test(e);if(t)S||(e+=`/`);else if(S)throw Error(`file path cannot end with '/': `+e);return e}var ce=We(0);function ue(e,t,S){if(this.utf8FileName=Ge(e),this.utf8FileName.length>65535)throw Error(`utf8 file name too long. `+utf8FileName.length+` > 65535`);if(this.isDirectory=t,this.state=ue.WAITING_FOR_METADATA,this.setLastModDate(S.mtime==null?new Date:S.mtime),this.forceDosTimestamp=!!S.forceDosTimestamp,S.mode==null?this.setFileAttributesMode(t?16893:33204):this.setFileAttributesMode(S.mode),t?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,S.size!=null&&(this.uncompressedSize=S.size)),t?this.compressionLevel=0:this.compressionLevel=q(S),this.forceZip64Format=!!S.forceZip64Format,S.fileComment){if(typeof S.fileComment==`string`?this.fileComment=Ge(S.fileComment,`utf-8`):this.fileComment=S.fileComment,this.fileComment.length>65535)throw Error(`fileComment is too large`)}else this.fileComment=ce}ue.WAITING_FOR_METADATA=0,ue.READY_TO_PUMP_FILE_DATA=1,ue.FILE_DATA_IN_PROGRESS=2,ue.FILE_DATA_DONE=3,ue.prototype.setLastModDate=function(e){this.mtime=e;var t=Pe(e);this.lastModFileTime=t.time,this.lastModFileDate=t.date},ue.prototype.setFileAttributesMode=function(e){if((e&65535)!==e)throw Error(`invalid mode. expected: 0 <= `+e+` <= 65535`);this.externalFileAttributes=e<<16>>>0},ue.prototype.setFileDataPumpFunction=function(e){this.doFileDataPump=e,this.state=ue.READY_TO_PUMP_FILE_DATA},ue.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var de=30,fe=20,me=45,ge=831,_e=2048,ve=8;ue.prototype.getLocalFileHeader=function(){var e=0,t=0,S=0;this.crcAndFileSizeKnown&&(e=this.crc32,t=this.compressedSize,S=this.uncompressedSize);var w=We(de),E=_e;return this.crcAndFileSizeKnown||(E|=ve),w.writeUInt32LE(67324752,0),w.writeUInt16LE(fe,4),w.writeUInt16LE(E,6),w.writeUInt16LE(this.getCompressionMethod(),8),w.writeUInt16LE(this.lastModFileTime,10),w.writeUInt16LE(this.lastModFileDate,12),w.writeUInt32LE(e,14),w.writeUInt32LE(t,18),w.writeUInt32LE(S,22),w.writeUInt16LE(this.utf8FileName.length,26),w.writeUInt16LE(0,28),Buffer.concat([w,this.utf8FileName])};var ye=16,Ce=24;ue.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return ce;if(this.useZip64Format()){var e=We(Ce);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),Ie(e,this.compressedSize,8),Ie(e,this.uncompressedSize,16),e}else{var e=We(ye);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),e.writeUInt32LE(this.compressedSize,8),e.writeUInt32LE(this.uncompressedSize,12),e}};var we=46,Te=9,De=28;ue.prototype.getCentralDirectoryRecord=function(){var e=We(we),t=_e;this.crcAndFileSizeKnown||(t|=ve);var S=ce;if(!this.forceDosTimestamp){S=We(Te),S.writeUInt16LE(21589,0),S.writeUInt16LE(Te-4,2),S.writeUInt8(3,4);var w=Math.floor(this.mtime.getTime()/1e3);w<-2147483648&&(w=-2147483648),w>2147483647&&(w=2147483647),S.writeUInt32LE(w,5)}var E=this.compressedSize,D=this.uncompressedSize,O=this.relativeOffsetOfLocalHeader,k=fe,j=ce;return this.useZip64Format()&&(E=4294967295,D=4294967295,O=4294967295,k=me,j=We(De),j.writeUInt16LE(1,0),j.writeUInt16LE(De-4,2),Ie(j,this.uncompressedSize,4),Ie(j,this.compressedSize,12),Ie(j,this.relativeOffsetOfLocalHeader,20)),e.writeUInt32LE(33639248,0),e.writeUInt16LE(ge,4),e.writeUInt16LE(k,6),e.writeUInt16LE(t,8),e.writeUInt16LE(this.getCompressionMethod(),10),e.writeUInt16LE(this.lastModFileTime,12),e.writeUInt16LE(this.lastModFileDate,14),e.writeUInt32LE(this.crc32,16),e.writeUInt32LE(E,20),e.writeUInt32LE(D,24),e.writeUInt16LE(this.utf8FileName.length,28),e.writeUInt16LE(S.length+j.length,30),e.writeUInt16LE(this.fileComment.length,32),e.writeUInt16LE(0,34),e.writeUInt16LE(0,36),e.writeUInt32LE(this.externalFileAttributes,38),e.writeUInt32LE(O,42),Buffer.concat([e,this.utf8FileName,S,j,this.fileComment])},ue.prototype.getCompressionMethod=function(){return this.compressionLevel===0?0:8};var je=new Date(1980,0,1),Me=new Date(2107,11,31,23,59,58);function Pe(e){e<je?e=je:e>Me&&(e=Me);var t=0;t|=e.getDate()&31,t|=(e.getMonth()+1&15)<<5,t|=(e.getFullYear()-1980&127)<<9;var S=0;return S|=Math.floor(e.getSeconds()/2),S|=(e.getMinutes()&63)<<5,S|=(e.getHours()&31)<<11,{date:t,time:S}}function Ie(e,t,S){var w=Math.floor(t/4294967296),E=t%4294967296;e.writeUInt32LE(E,S),e.writeUInt32LE(w,S+4)}D.inherits(Re,S);function Re(e){S.call(this,e),this.byteCount=0}Re.prototype._transform=function(e,t,S){this.byteCount+=e.length,S(null,e)},D.inherits(ze,S);function ze(e){S.call(this,e),this.crc32=0}ze.prototype._transform=function(e,t,S){this.crc32=j.unsigned(e,this.crc32),S(null,e)};var Be=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;if(Be.length!==256)throw Error(`assertion failure`);var Ve=null;function Ue(e){if(/^[\x20-\x7e]*$/.test(e))return Ge(e,`utf-8`);if(Ve==null){Ve={};for(var t=0;t<Be.length;t++)Ve[Be[t]]=t}for(var S=We(e.length),t=0;t<e.length;t++){var w=Ve[e[t]];if(w==null)throw Error(`character not encodable in CP437: `+JSON.stringify(e[t]));S[t]=w}return S}function We(e){We=t;try{return We(e)}catch{return We=S,We(e)}function t(e){return Buffer.allocUnsafe(e)}function S(e){return new Buffer(e)}}function Ge(e,t){Ge=S;try{return Ge(e,t)}catch{return Ge=w,Ge(e,t)}function S(e,t){return Buffer.from(e,t)}function w(e,t){return new Buffer(e,t)}}function Ke(e,t){Ke=S;try{return Ke(e,t)}catch{return Ke=w,Ke(e,t)}function S(e,t){return e.includes(t)}function w(e,t){for(var S=0;S<=e.length-t.length;S++)for(var w=0;;w++){if(w===t.length)return!0;if(e[S+w]!==t[w])break}return!1}}})),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`),w={};for(let e of S)w[e]=t[e];return e.objectValues(w)},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 w(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=w,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:[]},w=e=>{for(let E of e.issues)if(E.code===`invalid_union`)E.unionErrors.map(w);else if(E.code===`invalid_return_type`)w(E.returnTypeError);else if(E.code===`invalid_arguments`)w(E.argumentsError);else if(E.path.length===0)S._errors.push(t(E));else{let e=S,w=0;for(;w<E.path.length;){let S=E.path[w];w===E.path.length-1?(e[S]=e[S]||{_errors:[]},e[S]._errors.push(t(E))):e[S]=e[S]||{_errors:[]},e=e[S],w++}}};return w(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 w of this.issues)if(w.path.length>0){let S=w.path[0];t[S]=t[S]||[],t[S].push(e(w))}else S.push(e(w));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:w,issueData:E}=e,D=[...S,...E.path||[]],O={...E,path:D};if(E.message!==void 0)return{...E,path:D,message:E.message};let k=``,j=w.filter(e=>!!e).slice().reverse();for(let e of j)k=e(O,{data:t,defaultError:k}).message;return{...E,path:D,message:k}};function addIssueToContext(e,t){let S=getErrorMap(),w=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(w)}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 w of t){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&e.dirty(),S.push(w.value)}return{status:e.value,value:S}}static async mergeObjectAsync(t,S){let w=[];for(let e of S){let t=await e.key,S=await e.value;w.push({key:t,value:S})}return e.mergeObjectSync(t,w)}static mergeObjectSync(e,t){let S={};for(let w of t){let{key:t,value:E}=w;if(t.status===`aborted`||E.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),E.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(E.value!==void 0||w.alwaysSet)&&(S[t.value]=E.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,w){this._cachedPath=[],this.parent=e,this.data=t,this._path=S,this._key=w}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:w,description:E}=e;if(t&&(S||w))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:E}:{errorMap:(t,E)=>{let{message:D}=e;return t.code===`invalid_enum_value`?{message:D??E.defaultError}:E.data===void 0?{message:D??w??E.defaultError}:t.code===`invalid_type`?{message:D??S??E.defaultError}:{message:E.defaultError}},description:E}}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)},w=this._parse({data:e,path:S.path,parent:S});return handleResult(S,await(isAsync(w)?w:Promise.resolve(w)))}refine(e,t){let S=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,w)=>{let E=e(t),D=()=>w.addIssue({code:ZodIssueCode.custom,...S(t)});return typeof Promise<`u`&&E instanceof Promise?E.then(e=>e?!0:(D(),!1)):E?!0:(D(),!1)})}refinement(e,t){return this._refinement((S,w)=>e(S)?!0:(w.addIssue(typeof t==`function`?t(S,w):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 w=S.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(S.length+(4-S.length%4)%4,`=`),E=JSON.parse(atob(w));return!(typeof E!=`object`||!E||`typ`in E&&E?.typ!==`JWT`||!E.alg||t&&E.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 w of this._def.checks)if(w.kind===`min`)e.data.length<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`max`)e.data.length>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`length`){let E=e.data.length>w.value,D=e.data.length<w.value;(E||D)&&(S=this._getOrReturnCtx(e,S),E?addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}):D&&addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}),t.dirty())}else if(w.kind===`email`)emailRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`email`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.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:w.message}),t.dirty());else if(w.kind===`uuid`)uuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`nanoid`)nanoidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid`)cuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid2`)cuid2Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`ulid`)ulidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`url`)try{new URL(e.data)}catch{S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()}else w.kind===`regex`?(w.regex.lastIndex=0,w.regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`regex`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty())):w.kind===`trim`?e.data=e.data.trim():w.kind===`includes`?e.data.includes(w.value,w.position)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{includes:w.value,position:w.position},message:w.message}),t.dirty()):w.kind===`toLowerCase`?e.data=e.data.toLowerCase():w.kind===`toUpperCase`?e.data=e.data.toUpperCase():w.kind===`startsWith`?e.data.startsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{startsWith:w.value},message:w.message}),t.dirty()):w.kind===`endsWith`?e.data.endsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{endsWith:w.value},message:w.message}),t.dirty()):w.kind===`datetime`?datetimeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:w.message}),t.dirty()):w.kind===`date`?dateRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`date`,message:w.message}),t.dirty()):w.kind===`time`?timeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`time`,message:w.message}),t.dirty()):w.kind===`duration`?durationRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`duration`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`ip`?isValidIP(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ip`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`jwt`?isValidJWT(e.data,w.alg)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`cidr`?isValidCidr(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64`?base64Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64url`?base64urlRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):util.assertNever(w);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,w=(t.toString().split(`.`)[1]||``).length,E=S>w?S:w;return Number.parseInt(e.toFixed(E).replace(`.`,``))%Number.parseInt(t.toFixed(E).replace(`.`,``))/10**E}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 w of this._def.checks)w.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:w.message}),S.dirty()):w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`multipleOf`?floatSafeRemainder(e.data,w.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):w.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:w.message}),S.dirty()):util.assertNever(w);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,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_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 w of this._def.checks)w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`multipleOf`?e.data%w.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):util.assertNever(w);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,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_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 w of this._def.checks)w.kind===`min`?e.data.getTime()<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,message:w.message,inclusive:!0,exact:!1,minimum:w.value,type:`date`}),t.dirty()):w.kind===`max`?e.data.getTime()>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,message:w.message,inclusive:!0,exact:!1,maximum:w.value,type:`date`}),t.dirty()):util.assertNever(w);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),w=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(w.exactLength!==null){let e=t.data.length>w.exactLength.value,E=t.data.length<w.exactLength.value;(e||E)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:E?w.exactLength.value:void 0,maximum:e?w.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:w.exactLength.message}),S.dirty())}if(w.minLength!==null&&t.data.length<w.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.minLength.value,type:`array`,inclusive:!0,exact:!1,message:w.minLength.message}),S.dirty()),w.maxLength!==null&&t.data.length>w.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:w.maxLength.message}),S.dirty()),t.common.async)return Promise.all([...t.data].map((e,S)=>w.type._parseAsync(new ParseInputLazyPath(t,e,t.path,S)))).then(e=>ParseStatus.mergeArray(S,e));let E=[...t.data].map((e,S)=>w.type._parseSync(new ParseInputLazyPath(t,e,t.path,S)));return ParseStatus.mergeArray(S,E)}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 w=e.shape[S];t[S]=ZodOptional.create(deepPartialify(w))}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:w,keys:E}=this._getCached(),D=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in S.data)E.includes(e)||D.push(e);let O=[];for(let e of E){let t=w[e],E=S.data[e];O.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(S,E,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 D)O.push({key:{status:`valid`,value:e},value:{status:`valid`,value:S.data[e]}});else if(e===`strict`)D.length>0&&(addIssueToContext(S,{code:ZodIssueCode.unrecognized_keys,keys:D}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of D){let w=S.data[t];O.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(S,w,S.path,t)),alwaysSet:t in S.data})}}return S.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of O){let S=await t.key,w=await t.value;e.push({key:S,value:w,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,O)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,S)=>{let w=this._def.errorMap?.(e,S).message??S.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??w}:{message:w}}}})}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 w=this.shape[e];t&&!t[e]?S[e]=w:S[e]=w.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 w(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(w);{let e,w=[];for(let E of S){let S={...t,common:{...t.common,issues:[]},parent:null},D=E._parseSync({data:t.data,path:t.path,parent:S});if(D.status===`valid`)return D;D.status===`dirty`&&!e&&(e={result:D,ctx:S}),S.common.issues.length&&w.push(S.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let E=w.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:E}),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,w=t.data[S],E=this.optionsMap.get(w);return E?t.common.async?E._parseAsync({data:t.data,path:t.path,parent:t}):E._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,w){let E=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 w of S){if(E.has(w))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(w)}`);E.set(w,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:S,optionsMap:E,...processCreateParams(w)})}};function mergeValues(e,t){let S=getParsedType(e),w=getParsedType(t);if(e===t)return{valid:!0,data:e};if(S===ZodParsedType.object&&w===ZodParsedType.object){let S=util.objectKeys(t),w=util.objectKeys(e).filter(e=>S.indexOf(e)!==-1),E={...e,...t};for(let S of w){let w=mergeValues(e[S],t[S]);if(!w.valid)return{valid:!1};E[S]=w.data}return{valid:!0,data:E}}else if(S===ZodParsedType.array&&w===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let S=[];for(let w=0;w<e.length;w++){let E=e[w],D=t[w],O=mergeValues(E,D);if(!O.valid)return{valid:!1};S.push(O.data)}return{valid:!0,data:S}}else if(S===ZodParsedType.date&&w===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),w=(e,w)=>{if(isAborted(e)||isAborted(w))return INVALID;let E=mergeValues(e.value,w.value);return E.valid?((isDirty(e)||isDirty(w))&&t.dirty(),{status:t.value,value:E.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])=>w(e,t)):w(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 w=[...S.data].map((e,t)=>{let w=this._def.items[t]||this._def.rest;return w?w._parse(new ParseInputLazyPath(S,e,S.path,t)):null}).filter(e=>!!e);return S.common.async?Promise.all(w).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,w)}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 w=[],E=this._def.keyType,D=this._def.valueType;for(let e in S.data)w.push({key:E._parse(new ParseInputLazyPath(S,e,S.path,e)),value:D._parse(new ParseInputLazyPath(S,S.data[e],S.path,e)),alwaysSet:e in S.data});return S.common.async?ParseStatus.mergeObjectAsync(t,w):ParseStatus.mergeObjectSync(t,w)}get element(){return this._def.valueType}static create(t,S,w){return S instanceof ZodType?new e({keyType:t,valueType:S,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(w)}):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 w=this._def.keyType,E=this._def.valueType,D=[...S.data.entries()].map(([e,t],D)=>({key:w._parse(new ParseInputLazyPath(S,e,S.path,[D,`key`])),value:E._parse(new ParseInputLazyPath(S,t,S.path,[D,`value`]))}));if(S.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let S of D){let w=await S.key,E=await S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let S of D){let w=S.key,E=S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.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 w=this._def;w.minSize!==null&&S.data.size<w.minSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.minSize.value,type:`set`,inclusive:!0,exact:!1,message:w.minSize.message}),t.dirty()),w.maxSize!==null&&S.data.size>w.maxSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:w.maxSize.message}),t.dirty());let E=this._def.valueType;function D(e){let S=new Set;for(let w of e){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&t.dirty(),S.add(w.value)}return{status:t.value,value:S}}let O=[...S.data.values()].map((e,t)=>E._parse(new ParseInputLazyPath(S,e,S.path,t)));return S.common.async?Promise.all(O).then(e=>D(e)):D(O)}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 w(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 E={errorMap:t.common.contextualErrorMap},D=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let O=new ZodError([]),k=await e._def.args.parseAsync(t,E).catch(e=>{throw O.addIssue(S(t,e)),O}),j=await Reflect.apply(D,this,k);return await e._def.returns._def.type.parseAsync(j,E).catch(e=>{throw O.addIssue(w(j,e)),O})})}else{let e=this;return OK(function(...t){let O=e._def.args.safeParse(t,E);if(!O.success)throw new ZodError([S(t,O.error)]);let k=Reflect.apply(D,this,O.data),j=e._def.returns.safeParse(k,E);if(!j.success)throw new ZodError([w(k,j.error)]);return j.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,w){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:S||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(w)})}},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),w=this._def.effect||null,E={addIssue:e=>{addIssueToContext(S,e),e.fatal?t.abort():t.dirty()},get path(){return S.path}};if(E.addIssue=E.addIssue.bind(E),w.type===`preprocess`){let e=w.transform(S.data,E);if(S.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let w=await this._def.schema._parseAsync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w});{if(t.value===`aborted`)return INVALID;let w=this._def.schema._parseSync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w}}if(w.type===`refinement`){let e=e=>{let t=w.refinement(e,E);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 w=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});return w.status===`aborted`?INVALID:(w.status===`dirty`&&t.dirty(),e(w.value),{status:t.value,value:w.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(w.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 D=w.transform(e.value,E);if(D instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:D}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(e=>isValid(e)?Promise.resolve(w.transform(e.value,E)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(w)}};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:[]}},w=this._def.innerType._parse({data:S.data,path:S.path,parent:{...S}});return isAsync(w)?w.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:w.status===`valid`?w.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$6(e,t,S,{callee:e.parse}),e.safeParse=(t,S)=>safeParse$2(e,t,S),e.parseAsync=async(t,S)=>parseAsync$1(e,t,S,{callee:e.parseAsync}),e.safeParseAsync=async(t,S)=>safeParseAsync$2(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$2,meta=meta$2;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),w=t.every(e=>!isZ4Schema(e));if(S)return object(e);if(w)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$2(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$2(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$2(),number$1().int()]),CursorSchema=string$2(),TaskCreationParamsSchema=looseObject({ttl:number$1().optional(),pollInterval:number$1().optional()}),TaskMetadataSchema=object$1({ttl:number$1().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string$2()}),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$2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string$2(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string$2(),number$1().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$1().int(),message:string$2(),data:unknown$2().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$2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string$2(),mimeType:string$2().optional(),sizes:array(string$2()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string$2(),title:string$2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string$2(),websiteUrl:string$2().optional(),description:string$2().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean$1().optional()}),record(string$2(),unknown$2())),ElicitationCapabilitySchema=preprocess$1(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$2(),unknown$2()).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$2(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string$2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string$2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean$1().optional()}).optional(),resources:object$1({subscribe:boolean$1().optional(),listChanged:boolean$1().optional()}).optional(),tools:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string$2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string$2().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$1(),total:optional(number$1()),message:optional(string$2())}),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$2(),status:TaskStatusSchema,ttl:union([number$1(),_null()]),createdAt:string$2(),lastUpdatedAt:string$2(),pollInterval:optional(number$1()),statusMessage:optional(string$2())}),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$2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string$2()})}),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$2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string$2(),mimeType:optional(string$2()),_meta:record(string$2(),unknown$2()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string$2()}),Base64Schema=string$2().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$1().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string$2(),description:optional(string$2()),mimeType:optional(string$2()),size:optional(number$1()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string$2(),description:optional(string$2()),mimeType:optional(string$2()),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$2()}),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$2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string$2(),description:optional(string$2()),required:optional(boolean$1())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string$2()),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$2(),arguments:record(string$2(),string$2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string$2(),id:string$2(),input:record(string$2(),unknown$2()),_meta:record(string$2(),unknown$2()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).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$2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string$2().optional(),readOnlyHint:boolean$1().optional(),destructiveHint:boolean$1().optional(),idempotentHint:boolean$1().optional(),openWorldHint:boolean$1().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string$2().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()),outputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string$2(),unknown$2()).optional(),isError:boolean$1().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown$2()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string$2(),arguments:record(string$2(),unknown$2()).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$1().default(!0),debounceMs:number$1().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$2().optional(),data:unknown$2()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string$2().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number$1().min(0).max(1).optional(),speedPriority:number$1().min(0).max(1).optional(),intelligencePriority:number$1().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string$2().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean$1().optional(),_meta:record(string$2(),unknown$2()).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$2(),unknown$2()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string$2().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number$1().optional(),maxTokens:number$1().int(),stopSequences:array(string$2()).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$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string$2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string$2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string$2().optional(),description:string$2().optional(),default:boolean$1().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),minLength:number$1().optional(),maxLength:number$1().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string$2().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string$2().optional(),description:string$2().optional(),minimum:number$1().optional(),maximum:number$1().optional(),default:number$1().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),default:string$2().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),oneOf:array(object$1({const:string$2(),title:string$2()})),default:string$2().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),enumNames:array(string$2()).optional(),default:string$2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({type:literal(`string`),enum:array(string$2())}),default:array(string$2()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({anyOf:array(object$1({const:string$2(),title:string$2()}))}),default:array(string$2()).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$2(),requestedSchema:object$1({type:literal(`object`),properties:record(string$2(),PrimitiveSchemaDefinitionSchema),required:array(string$2()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string$2(),elicitationId:string$2(),url:string$2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string$2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess$1(e=>e===null?void 0:e,record(string$2(),union([string$2(),number$1(),boolean$1(),array(string$2())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string$2()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string$2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string$2(),value:string$2()}),context:object$1({arguments:record(string$2(),string$2()).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$2()).max(100),total:optional(number$1().int()),hasMore:optional(boolean$1())})}),RootSchema=object$1({uri:string$2().startsWith(`file://`),name:string$2().optional(),_meta:record(string$2(),unknown$2()).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,w){if(t===ErrorCode.UrlElicitationRequired&&w){let e=w;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,S)}return new e(t,S,w)}},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,w){w?.errorMessages&&S&&(e.errorMessage={...e.errorMessage,[t]:S})}function setResponseValueAndErrors(e,t,S,w,E){e[t]=S,addErrorMessage(e,t,w,E)}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 w of e.checks)switch(w.kind){case`min`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`minimum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMinimum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMinimum=!0),setResponseValueAndErrors(S,`minimum`,w.value,w.message,t));break;case`max`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`maximum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMaximum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMaximum=!0),setResponseValueAndErrors(S,`maximum`,w.value,w.message,t));break;case`multipleOf`:setResponseValueAndErrors(S,`multipleOf`,w.value,w.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 w=S??t.dateStrategy;if(Array.isArray(w))return{anyOf:w.map((S,w)=>parseDateDef(e,t,S))};switch(w){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 w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minimum`,w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maximum`,w.value,w.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),w=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,E=[];return S.forEach(e=>{if(isJsonSchema7AllOfType(e))E.push(...e.allOf),e.unevaluatedProperties===void 0&&(w=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:S,...w}=e;t=w}else w=void 0;E.push(t)}}),E.length?{allOf:E,...w}: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 w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(S,`email`,w.message,t);break;case`format:idn-email`:addFormat(S,`idn-email`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.email,w.message,t);break}break;case`url`:addFormat(S,`uri`,w.message,t);break;case`uuid`:addFormat(S,`uuid`,w.message,t);break;case`regex`:addPattern(S,w.regex,w.message,t);break;case`cuid`:addPattern(S,zodPatterns.cuid,w.message,t);break;case`cuid2`:addPattern(S,zodPatterns.cuid2,w.message,t);break;case`startsWith`:addPattern(S,RegExp(`^${escapeLiteralCheckValue(w.value,t)}`),w.message,t);break;case`endsWith`:addPattern(S,RegExp(`${escapeLiteralCheckValue(w.value,t)}$`),w.message,t);break;case`datetime`:addFormat(S,`date-time`,w.message,t);break;case`date`:addFormat(S,`date`,w.message,t);break;case`time`:addFormat(S,`time`,w.message,t);break;case`duration`:addFormat(S,`duration`,w.message,t);break;case`length`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t),setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`includes`:addPattern(S,RegExp(escapeLiteralCheckValue(w.value,t)),w.message,t);break;case`ip`:w.version!==`v6`&&addFormat(S,`ipv4`,w.message,t),w.version!==`v4`&&addFormat(S,`ipv6`,w.message,t);break;case`base64url`:addPattern(S,zodPatterns.base64url,w.message,t);break;case`jwt`:addPattern(S,zodPatterns.jwt,w.message,t);break;case`cidr`:w.version!==`v6`&&addPattern(S,zodPatterns.ipv4Cidr,w.message,t),w.version!==`v4`&&addPattern(S,zodPatterns.ipv6Cidr,w.message,t);break;case`emoji`:addPattern(S,zodPatterns.emoji(),w.message,t);break;case`ulid`:addPattern(S,zodPatterns.ulid,w.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(S,`binary`,w.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(S,`contentEncoding`,`base64`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.base64,w.message,t);break}break;case`nanoid`:addPattern(S,zodPatterns.nanoid,w.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(w)}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,w){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&w.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&&w.errorMessages&&{errorMessage:{format:S}}})):setResponseValueAndErrors(e,`format`,t,S,w)}function addPattern(e,t,S,w){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&w.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,w),...S&&w.errorMessages&&{errorMessage:{pattern:S}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,w),S,w)}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`)},w=S.i?e.source.toLowerCase():e.source,E=``,D=!1,O=!1,k=!1;for(let e=0;e<w.length;e++){if(D){E+=w[e],D=!1;continue}if(S.i){if(O){if(w[e].match(/[a-z]/)){k?(E+=w[e],E+=`${w[e-2]}-${w[e]}`.toUpperCase(),k=!1):w[e+1]===`-`&&w[e+2]?.match(/[a-z]/)?(E+=w[e],k=!0):E+=`${w[e]}${w[e].toUpperCase()}`;continue}}else if(w[e].match(/[a-z]/)){E+=`[${w[e]}${w[e].toUpperCase()}]`;continue}}if(S.m){if(w[e]===`^`){E+=`(^|(?<=[\r
|
|
469
|
+
`)?e:`${e}\n`}${B}`)}try{await mkdir(dirname(t),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${t}: ${e instanceof Error?e.message:String(e)}`})}try{await atomicWriteFile(t,B)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not write ${t}: ${e instanceof Error?e.message:String(e)}`})}return ok({effective:L.data,appliedPaths:j,path:t,created:!O})}function buildSchemaInvalidError(e,t,S,w){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let E=e.path.map(e=>typeof e==`symbol`?String(e):e),D=locateIssue({file:w,source:S,doc:t,path:E});return{path:E,message:e.message,issueCode:e.code,...D===void 0?{}:{source:D}}})}}function attemptSideline(e,t,S){let w=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return renameSync(e,w),w}catch(t){S(`[config] Could not sideline invalid config file ${e} → ${w}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function readConfigSafely(e){let{absPath:t,sideline:S=!0,timestamp:w=new Date().toISOString()}=e,E=e.warn??(e=>console.warn(e)),D=ConfigSchema$1.parse({});if(!existsSync(t))return{valid:!0,value:D,source:void 0};let O;try{O=readFileSync(t,`utf-8`)}catch(e){let S=e instanceof Error?e.message:String(e);return E(`[config] Could not read ${t}: ${S}. Using schema defaults.`),{valid:!1,value:D,error:{code:`UNKNOWN`,message:`Read failed: ${S}`}}}let k=(0,import_dist$1.parseDocument)(O);if(k.errors.length>0){let e=k.errors.map(e=>e.message).join(`; `);E(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let O=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:{code:`YAML_PARSE`,detail:e},...O===void 0?{}:{sidelinedTo:O}}}let j=k.toJSON()??{},F=ConfigSchema$1.safeParse(j);if(!F.success){let e=buildSchemaInvalidError(F,k,O,t);E(`[config] ${t} fails schema validation (${F.error.issues.length} issue(s)). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let j=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:e,...j===void 0?{}:{sidelinedTo:j}}}return{valid:!0,value:F.data,source:t}}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`),w={};for(let e of S)w[e]=t[e];return e.objectValues(w)},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 w(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=w,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:[]},w=e=>{for(let E of e.issues)if(E.code===`invalid_union`)E.unionErrors.map(w);else if(E.code===`invalid_return_type`)w(E.returnTypeError);else if(E.code===`invalid_arguments`)w(E.argumentsError);else if(E.path.length===0)S._errors.push(t(E));else{let e=S,w=0;for(;w<E.path.length;){let S=E.path[w];w===E.path.length-1?(e[S]=e[S]||{_errors:[]},e[S]._errors.push(t(E))):e[S]=e[S]||{_errors:[]},e=e[S],w++}}};return w(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 w of this.issues)if(w.path.length>0){let S=w.path[0];t[S]=t[S]||[],t[S].push(e(w))}else S.push(e(w));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:w,issueData:E}=e,D=[...S,...E.path||[]],O={...E,path:D};if(E.message!==void 0)return{...E,path:D,message:E.message};let k=``,j=w.filter(e=>!!e).slice().reverse();for(let e of j)k=e(O,{data:t,defaultError:k}).message;return{...E,path:D,message:k}};function addIssueToContext(e,t){let S=getErrorMap(),w=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(w)}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 w of t){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&e.dirty(),S.push(w.value)}return{status:e.value,value:S}}static async mergeObjectAsync(t,S){let w=[];for(let e of S){let t=await e.key,S=await e.value;w.push({key:t,value:S})}return e.mergeObjectSync(t,w)}static mergeObjectSync(e,t){let S={};for(let w of t){let{key:t,value:E}=w;if(t.status===`aborted`||E.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),E.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(E.value!==void 0||w.alwaysSet)&&(S[t.value]=E.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,w){this._cachedPath=[],this.parent=e,this.data=t,this._path=S,this._key=w}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:w,description:E}=e;if(t&&(S||w))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:E}:{errorMap:(t,E)=>{let{message:D}=e;return t.code===`invalid_enum_value`?{message:D??E.defaultError}:E.data===void 0?{message:D??w??E.defaultError}:t.code===`invalid_type`?{message:D??S??E.defaultError}:{message:E.defaultError}},description:E}}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)},w=this._parse({data:e,path:S.path,parent:S});return handleResult(S,await(isAsync(w)?w:Promise.resolve(w)))}refine(e,t){let S=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,w)=>{let E=e(t),D=()=>w.addIssue({code:ZodIssueCode.custom,...S(t)});return typeof Promise<`u`&&E instanceof Promise?E.then(e=>e?!0:(D(),!1)):E?!0:(D(),!1)})}refinement(e,t){return this._refinement((S,w)=>e(S)?!0:(w.addIssue(typeof t==`function`?t(S,w):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 w=S.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(S.length+(4-S.length%4)%4,`=`),E=JSON.parse(atob(w));return!(typeof E!=`object`||!E||`typ`in E&&E?.typ!==`JWT`||!E.alg||t&&E.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 w of this._def.checks)if(w.kind===`min`)e.data.length<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`max`)e.data.length>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`length`){let E=e.data.length>w.value,D=e.data.length<w.value;(E||D)&&(S=this._getOrReturnCtx(e,S),E?addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}):D&&addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}),t.dirty())}else if(w.kind===`email`)emailRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`email`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.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:w.message}),t.dirty());else if(w.kind===`uuid`)uuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`nanoid`)nanoidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid`)cuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid2`)cuid2Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`ulid`)ulidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`url`)try{new URL(e.data)}catch{S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()}else w.kind===`regex`?(w.regex.lastIndex=0,w.regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`regex`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty())):w.kind===`trim`?e.data=e.data.trim():w.kind===`includes`?e.data.includes(w.value,w.position)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{includes:w.value,position:w.position},message:w.message}),t.dirty()):w.kind===`toLowerCase`?e.data=e.data.toLowerCase():w.kind===`toUpperCase`?e.data=e.data.toUpperCase():w.kind===`startsWith`?e.data.startsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{startsWith:w.value},message:w.message}),t.dirty()):w.kind===`endsWith`?e.data.endsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{endsWith:w.value},message:w.message}),t.dirty()):w.kind===`datetime`?datetimeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:w.message}),t.dirty()):w.kind===`date`?dateRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`date`,message:w.message}),t.dirty()):w.kind===`time`?timeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`time`,message:w.message}),t.dirty()):w.kind===`duration`?durationRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`duration`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`ip`?isValidIP(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ip`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`jwt`?isValidJWT(e.data,w.alg)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`cidr`?isValidCidr(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64`?base64Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64url`?base64urlRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):util.assertNever(w);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,w=(t.toString().split(`.`)[1]||``).length,E=S>w?S:w;return Number.parseInt(e.toFixed(E).replace(`.`,``))%Number.parseInt(t.toFixed(E).replace(`.`,``))/10**E}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 w of this._def.checks)w.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:w.message}),S.dirty()):w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`multipleOf`?floatSafeRemainder(e.data,w.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):w.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:w.message}),S.dirty()):util.assertNever(w);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,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_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 w of this._def.checks)w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`multipleOf`?e.data%w.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):util.assertNever(w);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,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_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 w of this._def.checks)w.kind===`min`?e.data.getTime()<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,message:w.message,inclusive:!0,exact:!1,minimum:w.value,type:`date`}),t.dirty()):w.kind===`max`?e.data.getTime()>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,message:w.message,inclusive:!0,exact:!1,maximum:w.value,type:`date`}),t.dirty()):util.assertNever(w);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),w=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(w.exactLength!==null){let e=t.data.length>w.exactLength.value,E=t.data.length<w.exactLength.value;(e||E)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:E?w.exactLength.value:void 0,maximum:e?w.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:w.exactLength.message}),S.dirty())}if(w.minLength!==null&&t.data.length<w.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.minLength.value,type:`array`,inclusive:!0,exact:!1,message:w.minLength.message}),S.dirty()),w.maxLength!==null&&t.data.length>w.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:w.maxLength.message}),S.dirty()),t.common.async)return Promise.all([...t.data].map((e,S)=>w.type._parseAsync(new ParseInputLazyPath(t,e,t.path,S)))).then(e=>ParseStatus.mergeArray(S,e));let E=[...t.data].map((e,S)=>w.type._parseSync(new ParseInputLazyPath(t,e,t.path,S)));return ParseStatus.mergeArray(S,E)}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 w=e.shape[S];t[S]=ZodOptional.create(deepPartialify(w))}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:w,keys:E}=this._getCached(),D=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in S.data)E.includes(e)||D.push(e);let O=[];for(let e of E){let t=w[e],E=S.data[e];O.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(S,E,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 D)O.push({key:{status:`valid`,value:e},value:{status:`valid`,value:S.data[e]}});else if(e===`strict`)D.length>0&&(addIssueToContext(S,{code:ZodIssueCode.unrecognized_keys,keys:D}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of D){let w=S.data[t];O.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(S,w,S.path,t)),alwaysSet:t in S.data})}}return S.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of O){let S=await t.key,w=await t.value;e.push({key:S,value:w,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,O)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,S)=>{let w=this._def.errorMap?.(e,S).message??S.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??w}:{message:w}}}})}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 w=this.shape[e];t&&!t[e]?S[e]=w:S[e]=w.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 w(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(w);{let e,w=[];for(let E of S){let S={...t,common:{...t.common,issues:[]},parent:null},D=E._parseSync({data:t.data,path:t.path,parent:S});if(D.status===`valid`)return D;D.status===`dirty`&&!e&&(e={result:D,ctx:S}),S.common.issues.length&&w.push(S.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let E=w.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:E}),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,w=t.data[S],E=this.optionsMap.get(w);return E?t.common.async?E._parseAsync({data:t.data,path:t.path,parent:t}):E._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,w){let E=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 w of S){if(E.has(w))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(w)}`);E.set(w,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:S,optionsMap:E,...processCreateParams(w)})}};function mergeValues(e,t){let S=getParsedType(e),w=getParsedType(t);if(e===t)return{valid:!0,data:e};if(S===ZodParsedType.object&&w===ZodParsedType.object){let S=util.objectKeys(t),w=util.objectKeys(e).filter(e=>S.indexOf(e)!==-1),E={...e,...t};for(let S of w){let w=mergeValues(e[S],t[S]);if(!w.valid)return{valid:!1};E[S]=w.data}return{valid:!0,data:E}}else if(S===ZodParsedType.array&&w===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let S=[];for(let w=0;w<e.length;w++){let E=e[w],D=t[w],O=mergeValues(E,D);if(!O.valid)return{valid:!1};S.push(O.data)}return{valid:!0,data:S}}else if(S===ZodParsedType.date&&w===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),w=(e,w)=>{if(isAborted(e)||isAborted(w))return INVALID;let E=mergeValues(e.value,w.value);return E.valid?((isDirty(e)||isDirty(w))&&t.dirty(),{status:t.value,value:E.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])=>w(e,t)):w(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 w=[...S.data].map((e,t)=>{let w=this._def.items[t]||this._def.rest;return w?w._parse(new ParseInputLazyPath(S,e,S.path,t)):null}).filter(e=>!!e);return S.common.async?Promise.all(w).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,w)}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 w=[],E=this._def.keyType,D=this._def.valueType;for(let e in S.data)w.push({key:E._parse(new ParseInputLazyPath(S,e,S.path,e)),value:D._parse(new ParseInputLazyPath(S,S.data[e],S.path,e)),alwaysSet:e in S.data});return S.common.async?ParseStatus.mergeObjectAsync(t,w):ParseStatus.mergeObjectSync(t,w)}get element(){return this._def.valueType}static create(t,S,w){return S instanceof ZodType?new e({keyType:t,valueType:S,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(w)}):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 w=this._def.keyType,E=this._def.valueType,D=[...S.data.entries()].map(([e,t],D)=>({key:w._parse(new ParseInputLazyPath(S,e,S.path,[D,`key`])),value:E._parse(new ParseInputLazyPath(S,t,S.path,[D,`value`]))}));if(S.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let S of D){let w=await S.key,E=await S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let S of D){let w=S.key,E=S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.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 w=this._def;w.minSize!==null&&S.data.size<w.minSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.minSize.value,type:`set`,inclusive:!0,exact:!1,message:w.minSize.message}),t.dirty()),w.maxSize!==null&&S.data.size>w.maxSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:w.maxSize.message}),t.dirty());let E=this._def.valueType;function D(e){let S=new Set;for(let w of e){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&t.dirty(),S.add(w.value)}return{status:t.value,value:S}}let O=[...S.data.values()].map((e,t)=>E._parse(new ParseInputLazyPath(S,e,S.path,t)));return S.common.async?Promise.all(O).then(e=>D(e)):D(O)}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 w(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 E={errorMap:t.common.contextualErrorMap},D=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let O=new ZodError([]),k=await e._def.args.parseAsync(t,E).catch(e=>{throw O.addIssue(S(t,e)),O}),j=await Reflect.apply(D,this,k);return await e._def.returns._def.type.parseAsync(j,E).catch(e=>{throw O.addIssue(w(j,e)),O})})}else{let e=this;return OK(function(...t){let O=e._def.args.safeParse(t,E);if(!O.success)throw new ZodError([S(t,O.error)]);let k=Reflect.apply(D,this,O.data),j=e._def.returns.safeParse(k,E);if(!j.success)throw new ZodError([w(k,j.error)]);return j.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,w){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:S||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(w)})}},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),w=this._def.effect||null,E={addIssue:e=>{addIssueToContext(S,e),e.fatal?t.abort():t.dirty()},get path(){return S.path}};if(E.addIssue=E.addIssue.bind(E),w.type===`preprocess`){let e=w.transform(S.data,E);if(S.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let w=await this._def.schema._parseAsync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w});{if(t.value===`aborted`)return INVALID;let w=this._def.schema._parseSync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w}}if(w.type===`refinement`){let e=e=>{let t=w.refinement(e,E);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 w=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});return w.status===`aborted`?INVALID:(w.status===`dirty`&&t.dirty(),e(w.value),{status:t.value,value:w.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(w.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 D=w.transform(e.value,E);if(D instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:D}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(e=>isValid(e)?Promise.resolve(w.transform(e.value,E)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(w)}};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:[]}},w=this._def.innerType._parse({data:S.data,path:S.path,parent:{...S}});return isAsync(w)?w.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:w.status===`valid`?w.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$6(e,t,S,{callee:e.parse}),e.safeParse=(t,S)=>safeParse$2(e,t,S),e.parseAsync=async(t,S)=>parseAsync$1(e,t,S,{callee:e.parseAsync}),e.safeParseAsync=async(t,S)=>safeParseAsync$2(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$2,meta=meta$2;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),w=t.every(e=>!isZ4Schema(e));if(S)return object(e);if(w)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$2(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$2(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$2(),number$1().int()]),CursorSchema=string$2(),TaskCreationParamsSchema=looseObject({ttl:number$1().optional(),pollInterval:number$1().optional()}),TaskMetadataSchema=object$1({ttl:number$1().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string$2()}),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$2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string$2(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string$2(),number$1().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$1().int(),message:string$2(),data:unknown$2().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$2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string$2(),mimeType:string$2().optional(),sizes:array(string$2()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string$2(),title:string$2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string$2(),websiteUrl:string$2().optional(),description:string$2().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean$1().optional()}),record(string$2(),unknown$2())),ElicitationCapabilitySchema=preprocess$1(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$2(),unknown$2()).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$2(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string$2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string$2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean$1().optional()}).optional(),resources:object$1({subscribe:boolean$1().optional(),listChanged:boolean$1().optional()}).optional(),tools:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string$2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string$2().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$1(),total:optional(number$1()),message:optional(string$2())}),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$2(),status:TaskStatusSchema,ttl:union([number$1(),_null()]),createdAt:string$2(),lastUpdatedAt:string$2(),pollInterval:optional(number$1()),statusMessage:optional(string$2())}),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$2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string$2()})}),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$2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string$2(),mimeType:optional(string$2()),_meta:record(string$2(),unknown$2()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string$2()}),Base64Schema=string$2().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$1().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string$2(),description:optional(string$2()),mimeType:optional(string$2()),size:optional(number$1()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string$2(),description:optional(string$2()),mimeType:optional(string$2()),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$2()}),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$2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string$2(),description:optional(string$2()),required:optional(boolean$1())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string$2()),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$2(),arguments:record(string$2(),string$2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string$2(),id:string$2(),input:record(string$2(),unknown$2()),_meta:record(string$2(),unknown$2()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).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$2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string$2().optional(),readOnlyHint:boolean$1().optional(),destructiveHint:boolean$1().optional(),idempotentHint:boolean$1().optional(),openWorldHint:boolean$1().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string$2().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()),outputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string$2(),unknown$2()).optional(),isError:boolean$1().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown$2()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string$2(),arguments:record(string$2(),unknown$2()).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$1().default(!0),debounceMs:number$1().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$2().optional(),data:unknown$2()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string$2().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number$1().min(0).max(1).optional(),speedPriority:number$1().min(0).max(1).optional(),intelligencePriority:number$1().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string$2().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean$1().optional(),_meta:record(string$2(),unknown$2()).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$2(),unknown$2()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string$2().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number$1().optional(),maxTokens:number$1().int(),stopSequences:array(string$2()).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$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string$2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string$2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string$2().optional(),description:string$2().optional(),default:boolean$1().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),minLength:number$1().optional(),maxLength:number$1().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string$2().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string$2().optional(),description:string$2().optional(),minimum:number$1().optional(),maximum:number$1().optional(),default:number$1().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),default:string$2().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),oneOf:array(object$1({const:string$2(),title:string$2()})),default:string$2().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),enumNames:array(string$2()).optional(),default:string$2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({type:literal(`string`),enum:array(string$2())}),default:array(string$2()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({anyOf:array(object$1({const:string$2(),title:string$2()}))}),default:array(string$2()).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$2(),requestedSchema:object$1({type:literal(`object`),properties:record(string$2(),PrimitiveSchemaDefinitionSchema),required:array(string$2()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string$2(),elicitationId:string$2(),url:string$2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string$2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess$1(e=>e===null?void 0:e,record(string$2(),union([string$2(),number$1(),boolean$1(),array(string$2())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string$2()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string$2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string$2(),value:string$2()}),context:object$1({arguments:record(string$2(),string$2()).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$2()).max(100),total:optional(number$1().int()),hasMore:optional(boolean$1())})}),RootSchema=object$1({uri:string$2().startsWith(`file://`),name:string$2().optional(),_meta:record(string$2(),unknown$2()).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,w){if(t===ErrorCode.UrlElicitationRequired&&w){let e=w;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,S)}return new e(t,S,w)}},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,w){w?.errorMessages&&S&&(e.errorMessage={...e.errorMessage,[t]:S})}function setResponseValueAndErrors(e,t,S,w,E){e[t]=S,addErrorMessage(e,t,w,E)}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 w of e.checks)switch(w.kind){case`min`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`minimum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMinimum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMinimum=!0),setResponseValueAndErrors(S,`minimum`,w.value,w.message,t));break;case`max`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`maximum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMaximum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMaximum=!0),setResponseValueAndErrors(S,`maximum`,w.value,w.message,t));break;case`multipleOf`:setResponseValueAndErrors(S,`multipleOf`,w.value,w.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 w=S??t.dateStrategy;if(Array.isArray(w))return{anyOf:w.map((S,w)=>parseDateDef(e,t,S))};switch(w){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 w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minimum`,w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maximum`,w.value,w.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),w=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,E=[];return S.forEach(e=>{if(isJsonSchema7AllOfType(e))E.push(...e.allOf),e.unevaluatedProperties===void 0&&(w=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:S,...w}=e;t=w}else w=void 0;E.push(t)}}),E.length?{allOf:E,...w}: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 w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(S,`email`,w.message,t);break;case`format:idn-email`:addFormat(S,`idn-email`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.email,w.message,t);break}break;case`url`:addFormat(S,`uri`,w.message,t);break;case`uuid`:addFormat(S,`uuid`,w.message,t);break;case`regex`:addPattern(S,w.regex,w.message,t);break;case`cuid`:addPattern(S,zodPatterns.cuid,w.message,t);break;case`cuid2`:addPattern(S,zodPatterns.cuid2,w.message,t);break;case`startsWith`:addPattern(S,RegExp(`^${escapeLiteralCheckValue(w.value,t)}`),w.message,t);break;case`endsWith`:addPattern(S,RegExp(`${escapeLiteralCheckValue(w.value,t)}$`),w.message,t);break;case`datetime`:addFormat(S,`date-time`,w.message,t);break;case`date`:addFormat(S,`date`,w.message,t);break;case`time`:addFormat(S,`time`,w.message,t);break;case`duration`:addFormat(S,`duration`,w.message,t);break;case`length`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t),setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`includes`:addPattern(S,RegExp(escapeLiteralCheckValue(w.value,t)),w.message,t);break;case`ip`:w.version!==`v6`&&addFormat(S,`ipv4`,w.message,t),w.version!==`v4`&&addFormat(S,`ipv6`,w.message,t);break;case`base64url`:addPattern(S,zodPatterns.base64url,w.message,t);break;case`jwt`:addPattern(S,zodPatterns.jwt,w.message,t);break;case`cidr`:w.version!==`v6`&&addPattern(S,zodPatterns.ipv4Cidr,w.message,t),w.version!==`v4`&&addPattern(S,zodPatterns.ipv6Cidr,w.message,t);break;case`emoji`:addPattern(S,zodPatterns.emoji(),w.message,t);break;case`ulid`:addPattern(S,zodPatterns.ulid,w.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(S,`binary`,w.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(S,`contentEncoding`,`base64`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.base64,w.message,t);break}break;case`nanoid`:addPattern(S,zodPatterns.nanoid,w.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(w)}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,w){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&w.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&&w.errorMessages&&{errorMessage:{format:S}}})):setResponseValueAndErrors(e,`format`,t,S,w)}function addPattern(e,t,S,w){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&w.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,w),...S&&w.errorMessages&&{errorMessage:{pattern:S}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,w),S,w)}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`)},w=S.i?e.source.toLowerCase():e.source,E=``,D=!1,O=!1,k=!1;for(let e=0;e<w.length;e++){if(D){E+=w[e],D=!1;continue}if(S.i){if(O){if(w[e].match(/[a-z]/)){k?(E+=w[e],E+=`${w[e-2]}-${w[e]}`.toUpperCase(),k=!1):w[e+1]===`-`&&w[e+2]?.match(/[a-z]/)?(E+=w[e],k=!0):E+=`${w[e]}${w[e].toUpperCase()}`;continue}}else if(w[e].match(/[a-z]/)){E+=`[${w[e]}${w[e].toUpperCase()}]`;continue}}if(S.m){if(w[e]===`^`){E+=`(^|(?<=[\r
|
|
474
470
|
]))`;continue}else if(w[e]===`$`){E+=`($|(?=[\r
|
|
475
471
|
]))`;continue}}if(S.s&&w[e]===`.`){E+=O?`${w[e]}\r\n`:`[${w[e]}\r\n]`;continue}E+=w[e],w[e]===`\\`?D=!0:O&&w[e]===`]`?O=!1:!O&&w[e]===`[`&&(O=!0)}try{new RegExp(E)}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 E}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,w)=>({...S,[w]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,w]})??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:w,...E}=parseStringDef(e.keyType._def,t);return{...S,propertyNames:E}}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:w,...E}=parseBrandedDef(e.keyType._def,t);return{...S,propertyNames:E}}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]),w=Array.from(new Set(S.map(e=>typeof e)));return{type:w.length===1?w[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 w of e.checks)switch(w.kind){case`int`:S.type=`integer`,addErrorMessage(S,`type`,w.message,t);break;case`min`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`minimum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMinimum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMinimum=!0),setResponseValueAndErrors(S,`minimum`,w.value,w.message,t));break;case`max`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`maximum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMaximum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMaximum=!0),setResponseValueAndErrors(S,`maximum`,w.value,w.message,t));break;case`multipleOf`:setResponseValueAndErrors(S,`multipleOf`,w.value,w.message,t);break}return S}function parseObjectDef(e,t){let S=t.target===`openAi`,w={type:`object`,properties:{}},E=[],D=e.shape();for(let e in D){let O=D[e];if(O===void 0||O._def===void 0)continue;let k=safeIsOptional(O);k&&S&&(O._def.typeName===`ZodOptional`&&(O=O._def.innerType),O.isNullable()||(O=O.nullable()),k=!1);let j=parseDef(O._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});j!==void 0&&(w.properties[e]=j,k||E.push(e))}E.length&&(w.required=E);let O=decideAdditionalProperties(e,t);return O!==void 0&&(w.additionalProperties=O),w}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 w=t.seen.get(e);if(t.override){let E=t.override?.(e,t,w,S);if(E!==ignoreOverride)return E}if(w&&!S){let e=get$ref(w,t);if(e!==void 0)return e}let E={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,E);let D=selectParser(e,e.typeName,t),O=typeof D==`function`?parseDef(D(),t):D;if(O&&addMeta(e,t,O),t.postProcess){let S=t.postProcess(O,e,t);return E.jsonSchema=O,S}return E.jsonSchema=O,O}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),w=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,w])=>({...e,[t]:parseDef(w._def,{...S,currentPath:[...S.basePath,S.definitionPath,t]},!0)??parseAnyDef(S)}),{}):void 0,E=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,D=parseDef(e._def,E===void 0?S:{...S,currentPath:[...S.basePath,S.definitionPath,E]},!1)??parseAnyDef(S),O=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;O!==void 0&&(D.title=O),S.flags.hasReferencedOpenAiAnyType&&(w||={},w[S.openAiAnyTypeName]||(w[S.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:S.$refStrategy===`relative`?`1`:[...S.basePath,S.definitionPath,S.openAiAnyTypeName].join(`/`)}}));let k=E===void 0?w?{...D,[S.definitionPath]:w}:D:{$ref:[...S.$refStrategy===`relative`?[]:S.basePath,S.definitionPath,E].join(`/`),[S.definitionPath]:{...w,[E]:D}};return S.target===`jsonSchema7`?k.$schema=`http://json-schema.org/draft-07/schema#`:(S.target===`jsonSchema2019-09`||S.target===`openAi`)&&(k.$schema=`https://json-schema.org/draft/2019-09/schema#`),S.target===`openAi`&&(`anyOf`in k||`oneOf`in k||`allOf`in k||`type`in k&&Array.isArray(k.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),k};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 w=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(w,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,S=t.id,w=this._requestResolvers.get(S);if(w)if(this._requestResolvers.delete(S),e.type===`response`)w(t);else{let e=t;w(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 E=await this._taskStore.getTask(w,t.sessionId);if(!E)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${w}`);if(!isTerminal(E.status))return await this._waitForTaskUpdate(w,t.signal),await S();if(isTerminal(E.status)){let e=await this._taskStore.getTaskResult(w,t.sessionId);return this._clearTaskQueue(w),{...e,_meta:{...e._meta,[RELATED_TASK_META_KEY]:{taskId:w}}}}return await S()};return await S()}),this.setRequestHandler(ListTasksRequestSchema,async(e,t)=>{try{let{tasks:S,nextCursor:w}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:S,nextCursor:w,_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 w=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!w)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...w}}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,w,E=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(w,t),startTime:Date.now(),timeout:t,maxTotalTimeout:S,resetTimeoutOnProgress:E,onTimeout:w})}_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 w=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{w?.(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,w=this._transport,E=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`}};E&&this._taskMessageQueue?this._enqueueTaskMessage(E,{type:`error`,message:t,timestamp:Date.now()},w?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):w?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let D=new AbortController;this._requestHandlerAbortControllers.set(e.id,D);let O=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,k=this._taskStore?this.requestTaskStore(e,w?.sessionId):void 0,j={signal:D.signal,sessionId:w?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(D.signal.aborted)return;let S={relatedRequestId:e.id};E&&(S.relatedTask={taskId:E}),await this.notification(t,S)},sendRequest:async(t,S,w)=>{if(D.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,`Request was cancelled`);let O={...w,relatedRequestId:e.id};E&&!O.relatedTask&&(O.relatedTask={taskId:E});let j=O.relatedTask?.taskId??E;return j&&k&&await k.updateTaskStatus(j,`input_required`),await this.request(t,S,O)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:E,taskStore:k,taskRequestedTtl:O?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{O&&this.assertTaskHandlerCapability(e.method)}).then(()=>S(e,j)).then(async t=>{if(D.signal.aborted)return;let S={result:t,jsonrpc:`2.0`,id:e.id};E&&this._taskMessageQueue?await this._enqueueTaskMessage(E,{type:`response`,message:S,timestamp:Date.now()},w?.sessionId):await w?.send(S)},async t=>{if(D.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}}};E&&this._taskMessageQueue?await this._enqueueTaskMessage(E,{type:`error`,message:S,timestamp:Date.now()},w?.sessionId):await w?.send(S)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===D&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...S}=e.params,w=Number(t),E=this._progressHandlers.get(w);if(!E){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let D=this._responseHandlers.get(w),O=this._timeoutInfo.get(w);if(O&&D&&O.resetTimeoutOnProgress)try{this._resetTimeout(w)}catch(e){this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),D(e);return}E(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 w=this._responseHandlers.get(t);if(w===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 E=!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`&&(E=!0,this._taskProgressTokens.set(e.taskId,t))}}E||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?w(e):w(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:w}=S??{};if(!w){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 E;try{let w=await this.request(e,CreateTaskResultSchema,S);if(w.task)E=w.task.taskId,yield{type:`taskCreated`,task:w.task};else throw new McpError(ErrorCode.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:E},S);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:E},t,S)}:e.status===`failed`?yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${E} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${E} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:E},t,S)};return}let w=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,w)),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:w,resumptionToken:E,onresumptiontoken:D,task:O,relatedTask:k}=S??{};return new Promise((j,F)=>{let L=e=>{F(e)};if(!this._transport){L(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),O&&this.assertTaskCapability(e.method)}catch(e){L(e);return}S?.signal?.throwIfAborted();let B=this._requestMessageId++,H={...e,jsonrpc:`2.0`,id:B};S?.onprogress&&(this._progressHandlers.set(B,S.onprogress),H.params={...e.params,_meta:{...e.params?._meta||{},progressToken:B}}),O&&(H.params={...H.params,task:O}),k&&(H.params={...H.params,_meta:{...H.params?._meta||{},[RELATED_TASK_META_KEY]:k}});let q=e=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:B,reason:String(e)}},{relatedRequestId:w,resumptionToken:E,onresumptiontoken:D}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),F(e instanceof McpError?e:new McpError(ErrorCode.RequestTimeout,String(e)))};this._responseHandlers.set(B,e=>{if(!S?.signal?.aborted){if(e instanceof Error)return F(e);try{let S=safeParse(t,e.result);S.success?j(S.data):F(S.error)}catch(e){F(e)}}}),S?.signal?.addEventListener(`abort`,()=>{q(S?.signal?.reason)});let J=S?.timeout??6e4;this._setupTimeout(B,J,S?.maxTotalTimeout,()=>q(McpError.fromError(ErrorCode.RequestTimeout,`Request timed out`,{timeout:J})),S?.resetTimeoutOnProgress??!1);let Y=k?.taskId;Y?(this._requestResolvers.set(B,e=>{let t=this._responseHandlers.get(B);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${B}`))}),this._enqueueTaskMessage(Y,{type:`request`,message:H,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(B),F(e)})):this._transport.send(H,{relatedRequestId:w,resumptionToken:E,onresumptiontoken:D}).catch(e=>{this._cleanupTimeout(B),F(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 w={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}};await this._enqueueTaskMessage(S,{type:`notification`,message:w,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 w={...e,jsonrpc:`2.0`};t?.relatedTask&&(w={...w,params:{...w.params,_meta:{...w.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),await this._transport.send(w,t)}setRequestHandler(e,t){let S=getMethodLiteral(e);this.assertRequestHandlerCapability(S),this._requestHandlers.set(S,(S,w)=>{let E=parseWithCompat(e,S);return Promise.resolve(t(E,w))})}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 w=parseWithCompat(e,S);return Promise.resolve(t(w))})}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 w=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,S,w)}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,w=this._requestResolvers.get(S);w?(w(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,w)=>{if(t.aborted){w(new McpError(ErrorCode.InvalidRequest,`Request cancelled`));return}let E=setTimeout(e,S);t.addEventListener(`abort`,()=>{clearTimeout(E),w(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 w=>{if(!e)throw Error(`No request provided`);return await S.createTask(w,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let w=await S.getTask(e,t);if(!w)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return w},storeTaskResult:async(e,w,E)=>{await S.storeTaskResult(e,w,E,t);let D=await S.getTask(e,t);if(D){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:D});await this.notification(t),isTerminal(D.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>S.getTaskResult(e,t),updateTaskStatus:async(e,w,E)=>{let D=await S.getTask(e,t);if(!D)throw new McpError(ErrorCode.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(D.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${e}" from terminal status "${D.status}" to "${w}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await S.updateTaskStatus(e,w,E,t);let O=await S.getTask(e,t);if(O){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:O});await this.notification(t),isTerminal(O.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 w=e,E=t[w];if(E===void 0)continue;let D=S[w];isPlainObject$1(D)&&isPlainObject$1(E)?S[w]={...D,...E}:S[w]=E}return S}var require_code$1=__commonJSMin$1((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 w=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=w,e.nil=new w(``);function E(e,...t){let S=[e[0]],E=0;for(;E<t.length;)k(S,t[E]),S.push(e[++E]);return new w(S)}e._=E;let D=new w(`+`);function O(e,...t){let S=[q(e[0])],E=0;for(;E<t.length;)S.push(D),k(S,t[E]),S.push(D,q(e[++E]));return j(S),new w(S)}e.str=O;function k(e,t){t instanceof w?e.push(...t._items):t instanceof S?e.push(t):e.push(B(t))}e.addCodeArg=k;function j(e){let t=1;for(;t<e.length-1;){if(e[t]===D){let S=F(e[t-1],e[t+1]);if(S!==void 0){e.splice(t-1,3,S);continue}e[t++]=`+`}t++}}function F(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 L(e,t){return t.emptyStr()?e:e.emptyStr()?t:O`${e}${t}`}e.strConcat=L;function B(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:q(Array.isArray(e)?e.join(`,`):e)}function H(e){return new w(q(e))}e.stringify=H;function q(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=q;function J(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new w(`.${t}`):E`[${t}]`}e.getProperty=J;function Y(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new w(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=Y;function ee(e){return new w(e.toString())}e.regexpCode=ee})),require_scope=__commonJSMin$1((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}},w;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(w||(e.UsedValueState=w={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var E=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=E;var D=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:S,itemIndex:w}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(S)}[${w}]`}};e.ValueScopeName=D;let O=(0,t._)`\n`;e.ValueScope=class extends E{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?O:t.nil}}get(){return this._scope}name(e){return new D(e,this._newName(e))}value(e,t){var S;if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let w=this.toName(e),{prefix:E}=w,D=t.key??t.ref,O=this._values[E];if(O){let e=O.get(D);if(e)return e}else O=this._values[E]=new Map;O.set(D,w);let k=this._scope[E]||(this._scope[E]=[]),j=k.length;return k[j]=t.ref,w.setValue(t,{property:E,itemIndex:j}),w}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(E,D,O={},k){let j=t.nil;for(let F in E){let L=E[F];if(!L)continue;let B=O[F]=O[F]||new Map;L.forEach(E=>{if(B.has(E))return;B.set(E,w.Started);let O=D(E);if(O){let S=this.opts.es5?e.varKinds.var:e.varKinds.const;j=(0,t._)`${j}${S} ${E} = ${O};${this.opts._n}`}else if(O=k?.(E))j=(0,t._)`${j}${O}${this.opts._n}`;else throw new S(E);B.set(E,w.Completed)})}return j}}})),require_codegen=__commonJSMin$1((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 w=require_code$1();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return w._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return w.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return w.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return w.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return w.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return w.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return w.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return w.Name}});var E=require_scope();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return E.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return E.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return E.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return E.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 D=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},O=class extends D{constructor(e,t,S){super(),this.varKind=e,this.name=t,this.rhs=S}render({es5:e,_n:t}){let w=e?S.varKinds.var:this.varKind,E=this.rhs===void 0?``:` = ${this.rhs}`;return`${w} ${this.name}${E};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ve(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},k=class extends D{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=ve(this.rhs,e,S),this}get names(){return _e(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},j=class extends k{constructor(e,t,S,w){super(e,S,w),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},F=class extends D{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},L=class extends D{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},B=class extends D{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},H=class extends D{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=ve(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},q=class extends D{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,w=S.length;for(;w--;){let E=S[w];E.optimizeNames(e,t)||(ye(e,E.names),S.splice(w,1))}return S.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ge(e,t.names),{})}},J=class extends q{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},Y=class extends q{},ee=class extends J{};ee.kind=`else`;var te=class e extends J{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(Ce(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=ve(this.condition,e,t),this}get names(){let e=super.names;return _e(e,this.condition),this.else&&ge(e,this.else.names),e}};te.kind=`if`;var ne=class extends J{};ne.kind=`for`;var ae=class extends ne{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=ve(this.iteration,e,t),this}get names(){return ge(super.names,this.iteration.names)}},oe=class extends ne{constructor(e,t,S,w){super(),this.varKind=e,this.name=t,this.from=S,this.to=w}render(e){let t=e.es5?S.varKinds.var:this.varKind,{name:w,from:E,to:D}=this;return`for(${t} ${w}=${E}; ${w}<${D}; ${w}++)`+super.render(e)}get names(){return _e(_e(super.names,this.from),this.to)}},se=class extends ne{constructor(e,t,S,w){super(),this.loop=e,this.varKind=t,this.name=S,this.iterable=w}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=ve(this.iterable,e,t),this}get names(){return ge(super.names,this.iterable.names)}},ce=class extends J{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)}};ce.kind=`func`;var ue=class extends q{render(e){return`return `+super.render(e)}};ue.kind=`return`;var de=class extends J{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,w;return super.optimizeNames(e,t),(S=this.catch)==null||S.optimizeNames(e,t),(w=this.finally)==null||w.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ge(e,this.catch.names),this.finally&&ge(e,this.finally.names),e}},fe=class extends J{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fe.kind=`catch`;var me=class extends J{render(e){return`finally`+super.render(e)}};me.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
476
472
|
`:``},this._extScope=e,this._scope=new S.Scope({parent:e}),this._nodes=[new Y]}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,w){let E=this._scope.toName(t);return S!==void 0&&w&&(this._constants[E.str]=S),this._leafNode(new O(e,E,S)),E}const(e,t,w){return this._def(S.varKinds.const,e,t,w)}let(e,t,w){return this._def(S.varKinds.let,e,t,w)}var(e,t,w){return this._def(S.varKinds.var,e,t,w)}assign(e,t,S){return this._leafNode(new k(e,t,S))}add(t,S){return this._leafNode(new j(t,e.operators.ADD,S))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new H(e)),this}object(...e){let S=[`{`];for(let[w,E]of e)S.length>1&&S.push(`,`),S.push(w),(w!==E||this.opts.es5)&&(S.push(`:`),(0,t.addCodeArg)(S,E));return S.push(`}`),new t._Code(S)}if(e,t,S){if(this._blockNode(new te(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 te(e))}else(){return this._elseNode(new ee)}endIf(){return this._endBlockNode(te,ee)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new ae(e),t)}forRange(e,t,w,E,D=this.opts.es5?S.varKinds.var:S.varKinds.let){let O=this._scope.toName(e);return this._for(new oe(D,O,t,w),()=>E(O))}forOf(e,w,E,D=S.varKinds.const){let O=this._scope.toName(e);if(this.opts.es5){let e=w instanceof t.Name?w:this.var(`_arr`,w);return this.forRange(`_i`,0,(0,t._)`${e}.length`,S=>{this.var(O,(0,t._)`${e}[${S}]`),E(O)})}return this._for(new se(`of`,D,O,w),()=>E(O))}forIn(e,w,E,D=this.opts.es5?S.varKinds.var:S.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${w})`,E);let O=this._scope.toName(e);return this._for(new se(`in`,D,O,w),()=>E(O))}endFor(){return this._endBlockNode(ne)}label(e){return this._leafNode(new F(e))}break(e){return this._leafNode(new L(e))}return(e){let t=new ue;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(ue)}try(e,t,S){if(!t&&!S)throw Error(`CodeGen: "try" without "catch" and "finally"`);let w=new de;if(this._blockNode(w),this.code(e),t){let e=this.name(`e`);this._currNode=w.catch=new fe(e),t(e)}return S&&(this._currNode=w.finally=new me,this.code(S)),this._endBlockNode(fe,me)}throw(e){return this._leafNode(new B(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,w,E){return this._blockNode(new ce(e,S,w)),E&&this.code(E).endFunc(),this}endFunc(){return this._endBlockNode(ce)}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 te))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 ge(e,t){for(let S in t)e[S]=(e[S]||0)+(t[S]||0);return e}function _e(e,S){return S instanceof t._CodeOrName?ge(e,S.names):e}function ve(e,S,w){if(e instanceof t.Name)return E(e);if(!D(e))return e;return new t._Code(e._items.reduce((e,S)=>(S instanceof t.Name&&(S=E(S)),S instanceof t._Code?e.push(...S._items):e.push(S),e),[]));function E(e){let t=w[e.str];return t===void 0||S[e.str]!==1?e:(delete S[e.str],t)}function D(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&S[e.str]===1&&w[e.str]!==void 0)}}function ye(e,t){for(let S in t)e[S]=(e[S]||0)-(t[S]||0)}function Ce(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${Pe(e)}`}e.not=Ce;let we=Me(e.operators.AND);function Te(...e){return e.reduce(we)}e.and=Te;let De=Me(e.operators.OR);function je(...e){return e.reduce(De)}e.or=je;function Me(e){return(S,w)=>S===t.nil?w:w===t.nil?S:(0,t._)`${Pe(S)} ${e} ${Pe(w)}`}function Pe(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),require_util=__commonJSMin$1((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 w(e){let t={};for(let S of e)t[S]=!0;return t}e.toHash=w;function E(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(D(e,t),!O(t,e.self.RULES.all))}e.alwaysValidSchema=E;function D(e,t=e.schema){let{opts:S,self:w}=e;if(!S.strictSchema||typeof t==`boolean`)return;let E=w.RULES.keywords;for(let S in t)E[S]||se(e,`unknown keyword: "${S}"`)}e.checkUnknownRules=D;function O(e,t){if(typeof e==`boolean`)return!e;for(let S in e)if(t[S])return!0;return!1}e.schemaHasRules=O;function k(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=k;function j({topSchemaRef:e,schemaPath:S},w,E,D){if(!D){if(typeof w==`number`||typeof w==`boolean`)return w;if(typeof w==`string`)return(0,t._)`${w}`}return(0,t._)`${e}${S}${(0,t.getProperty)(E)}`}e.schemaRefOrVal=j;function F(e){return H(decodeURIComponent(e))}e.unescapeFragment=F;function L(e){return encodeURIComponent(B(e))}e.escapeFragment=L;function B(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=B;function H(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=H;function q(e,t){if(Array.isArray(e))for(let S of e)t(S);else t(e)}e.eachItem=q;function J({mergeNames:e,mergeToName:S,mergeValues:w,resultToName:E}){return(D,O,k,j)=>{let F=k===void 0?O:k instanceof t.Name?(O instanceof t.Name?e(D,O,k):S(D,O,k),k):O instanceof t.Name?(S(D,k,O),O):w(O,k);return j===t.Name&&!(F instanceof t.Name)?E(D,F):F}}e.mergeEvaluated={props:J({mergeNames:(e,S,w)=>e.if((0,t._)`${w} !== true && ${S} !== undefined`,()=>{e.if((0,t._)`${S} === true`,()=>e.assign(w,!0),()=>e.assign(w,(0,t._)`${w} || {}`).code((0,t._)`Object.assign(${w}, ${S})`))}),mergeToName:(e,S,w)=>e.if((0,t._)`${w} !== true`,()=>{S===!0?e.assign(w,!0):(e.assign(w,(0,t._)`${w} || {}`),ee(e,w,S))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Y}),items:J({mergeNames:(e,S,w)=>e.if((0,t._)`${w} !== true && ${S} !== undefined`,()=>e.assign(w,(0,t._)`${S} === true ? true : ${w} > ${S} ? ${w} : ${S}`)),mergeToName:(e,S,w)=>e.if((0,t._)`${w} !== true`,()=>e.assign(w,S===!0?!0:(0,t._)`${w} > ${S} ? ${w} : ${S}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function Y(e,S){if(S===!0)return e.var(`props`,!0);let w=e.var(`props`,(0,t._)`{}`);return S!==void 0&&ee(e,w,S),w}e.evaluatedPropsToName=Y;function ee(e,S,w){Object.keys(w).forEach(w=>e.assign((0,t._)`${S}${(0,t.getProperty)(w)}`,!0))}e.setEvaluated=ee;let te={};function ne(e,t){return e.scopeValue(`func`,{ref:t,code:te[t.code]||(te[t.code]=new S._Code(t.code))})}e.useFunc=ne;var ae;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(ae||(e.Type=ae={}));function oe(e,S,w){if(e instanceof t.Name){let E=S===ae.Num;return w?E?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:E?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return w?(0,t.getProperty)(e).toString():`/`+B(e)}e.getErrorPath=oe;function se(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=se})),require_names=__commonJSMin$1((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$1((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(),w=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 E(S,w=e.keywordError,E,D){let{it:O}=S,{gen:k,compositeRule:L,allErrors:H}=O,q=B(S,w,E);D??(L||H)?j(k,q):F(O,(0,t._)`[${q}]`)}e.reportError=E;function D(t,S=e.keywordError,E){let{it:D}=t,{gen:O,compositeRule:k,allErrors:L}=D;j(O,B(t,S,E)),k||L||F(D,w.default.vErrors)}e.reportExtraError=D;function O(e,S){e.assign(w.default.errors,S),e.if((0,t._)`${w.default.vErrors} !== null`,()=>e.if(S,()=>e.assign((0,t._)`${w.default.vErrors}.length`,S),()=>e.assign(w.default.vErrors,null)))}e.resetErrorsCount=O;function k({gen:e,keyword:S,schemaValue:E,data:D,errsCount:O,it:k}){if(O===void 0)throw Error(`ajv implementation error`);let j=e.name(`err`);e.forRange(`i`,O,w.default.errors,O=>{e.const(j,(0,t._)`${w.default.vErrors}[${O}]`),e.if((0,t._)`${j}.instancePath === undefined`,()=>e.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(w.default.instancePath,k.errorPath))),e.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${S}`),k.opts.verbose&&(e.assign((0,t._)`${j}.schema`,E),e.assign((0,t._)`${j}.data`,D))})}e.extendErrors=k;function j(e,S){let E=e.const(`err`,S);e.if((0,t._)`${w.default.vErrors} === null`,()=>e.assign(w.default.vErrors,(0,t._)`[${E}]`),(0,t._)`${w.default.vErrors}.push(${E})`),e.code((0,t._)`${w.default.errors}++`)}function F(e,S){let{gen:w,validateName:E,schemaEnv:D}=e;D.$async?w.throw((0,t._)`new ${e.ValidationError}(${S})`):(w.assign((0,t._)`${E}.errors`,S),w.return(!1))}let L={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 B(e,S,w){let{createErrors:E}=e.it;return E===!1?(0,t._)`{}`:H(e,S,w)}function H(e,t,S={}){let{gen:w,it:E}=e,D=[q(E,S),J(e,S)];return Y(e,t,D),w.object(...D)}function q({errorPath:e},{instancePath:E}){let D=E?(0,t.str)`${e}${(0,S.getErrorPath)(E,S.Type.Str)}`:e;return[w.default.instancePath,(0,t.strConcat)(w.default.instancePath,D)]}function J({keyword:e,it:{errSchemaPath:w}},{schemaPath:E,parentSchema:D}){let O=D?w:(0,t.str)`${w}/${e}`;return E&&(O=(0,t.str)`${O}${(0,S.getErrorPath)(E,S.Type.Str)}`),[L.schemaPath,O]}function Y(e,{params:S,message:E},D){let{keyword:O,data:k,schemaValue:j,it:F}=e,{opts:B,propertyName:H,topSchemaRef:q,schemaPath:J}=F;D.push([L.keyword,O],[L.params,typeof S==`function`?S(e):S||(0,t._)`{}`]),B.messages&&D.push([L.message,typeof E==`function`?E(e):E]),B.verbose&&D.push([L.schema,j],[L.parentSchema,(0,t._)`${q}${J}`],[w.default.data,k]),H&&D.push([L.propertyName,H])}})),require_boolSchema=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=require_errors(),S=require_codegen(),w=require_names(),E={message:`boolean schema is false`};function D(e){let{gen:t,schema:E,validateName:D}=e;E===!1?k(e,!1):typeof E==`object`&&E.$async===!0?t.return(w.default.data):(t.assign((0,S._)`${D}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=D;function O(e,t){let{gen:S,schema:w}=e;w===!1?(S.var(t,!1),k(e)):S.var(t,!0)}e.boolOrEmptySchema=O;function k(e,S){let{gen:w,data:D}=e,O={gen:w,keyword:`false schema`,data:D,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(O,E,void 0,S)}})),require_rules=__commonJSMin$1((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 w(){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=w})),require_applicability=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},w){let E=t.RULES.types[w];return E&&E!==!0&&S(e,E)}e.schemaHasRulesForType=t;function S(e,t){return t.rules.some(t=>w(e,t))}e.shouldUseGroup=S;function w(e,t){var S;return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=w})),require_dataType=__commonJSMin$1((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(),w=require_errors(),E=require_codegen(),D=require_util();var O;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(O||(e.DataType=O={}));function k(e){let t=j(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=k;function j(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=j;function F(e,t){let{gen:w,data:E,opts:D}=e,k=B(t,D.coerceTypes),j=t.length>0&&!(k.length===0&&t.length===1&&(0,S.schemaHasRulesForType)(e,t[0]));if(j){let S=Y(t,E,D.strictNumbers,O.Wrong);w.if(S,()=>{k.length?H(e,t,k):te(e)})}return j}e.coerceAndCheckDataType=F;let L=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function B(e,t){return t?e.filter(e=>L.has(e)||t===`array`&&e===`array`):[]}function H(e,t,S){let{gen:w,data:D,opts:O}=e,k=w.let(`dataType`,(0,E._)`typeof ${D}`),j=w.let(`coerced`,(0,E._)`undefined`);O.coerceTypes===`array`&&w.if((0,E._)`${k} == 'object' && Array.isArray(${D}) && ${D}.length == 1`,()=>w.assign(D,(0,E._)`${D}[0]`).assign(k,(0,E._)`typeof ${D}`).if(Y(t,D,O.strictNumbers),()=>w.assign(j,D))),w.if((0,E._)`${j} !== undefined`);for(let e of S)(L.has(e)||e===`array`&&O.coerceTypes===`array`)&&F(e);w.else(),te(e),w.endIf(),w.if((0,E._)`${j} !== undefined`,()=>{w.assign(D,j),q(e,j)});function F(e){switch(e){case`string`:w.elseIf((0,E._)`${k} == "number" || ${k} == "boolean"`).assign(j,(0,E._)`"" + ${D}`).elseIf((0,E._)`${D} === null`).assign(j,(0,E._)`""`);return;case`number`:w.elseIf((0,E._)`${k} == "boolean" || ${D} === null
|
|
@@ -480,7 +476,7 @@ To resolve the conflict:`,(0,w.getConflictResolutionRecipe)(E,e))),D=O):S.diag.w
|
|
|
480
476
|
missingProperty: ${E},
|
|
481
477
|
depsCount: ${S},
|
|
482
478
|
deps: ${w}}`};let E={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,S]=D(e);O(e,t),k(e,S)}};function D({schema:e}){let t={},S={};for(let w in e){if(w===`__proto__`)continue;let E=Array.isArray(e[w])?t:S;E[w]=e[w]}return[t,S]}function O(e,S=e.schema){let{gen:E,data:D,it:O}=e;if(Object.keys(S).length===0)return;let k=E.let(`missing`);for(let j in S){let F=S[j];if(F.length===0)continue;let L=(0,w.propertyInData)(E,D,j,O.opts.ownProperties);e.setParams({property:j,depsCount:F.length,deps:F.join(`, `)}),O.allErrors?E.if(L,()=>{for(let t of F)(0,w.checkReportMissingProp)(e,t)}):(E.if((0,t._)`${L} && (${(0,w.checkMissingProp)(e,F,k)})`),(0,w.reportMissingProp)(e,k),E.else())}}e.validatePropertyDeps=O;function k(e,t=e.schema){let{gen:E,data:D,keyword:O,it:k}=e,j=E.name(`valid`);for(let F in t)(0,S.alwaysValidSchema)(k,t[F])||(E.if((0,w.propertyInData)(E,D,F,k.opts.ownProperties),()=>{let t=e.subschema({keyword:O,schemaProp:F},j);e.mergeValidEvaluated(t,j)},()=>E.var(j,!0)),e.ok(j))}e.validateSchemaDeps=k,e.default=E})),require_propertyNames=__commonJSMin$1((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:w,schema:E,data:D,it:O}=e;if((0,S.alwaysValidSchema)(O,E))return;let k=w.name(`valid`);w.forIn(`key`,D,S=>{e.setParams({propertyName:S}),e.subschema({keyword:`propertyNames`,data:S,dataTypes:[`string`],propertyName:S,compositeRule:!0},k),w.if((0,t.not)(k),()=>{e.error(!0),O.allErrors||w.break()})}),e.ok(k)}}})),require_additionalProperties=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),S=require_codegen(),w=require_names(),E=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:D,schema:O,parentSchema:k,data:j,errsCount:F,it:L}=e;if(!F)throw Error(`ajv implementation error`);let{allErrors:B,opts:H}=L;if(L.props=!0,H.removeAdditional!==`all`&&(0,E.alwaysValidSchema)(L,O))return;let q=(0,t.allSchemaProperties)(k.properties),J=(0,t.allSchemaProperties)(k.patternProperties);Y(),e.ok((0,S._)`${F} === ${w.default.errors}`);function Y(){D.forIn(`key`,j,e=>{!q.length&&!J.length?ne(e):D.if(ee(e),()=>ne(e))})}function ee(w){let O;if(q.length>8){let e=(0,E.schemaRefOrVal)(L,k.properties,`properties`);O=(0,t.isOwnProperty)(D,e,w)}else O=q.length?(0,S.or)(...q.map(e=>(0,S._)`${w} === ${e}`)):S.nil;return J.length&&(O=(0,S.or)(O,...J.map(E=>(0,S._)`${(0,t.usePattern)(e,E)}.test(${w})`))),(0,S.not)(O)}function te(e){D.code((0,S._)`delete ${j}[${e}]`)}function ne(t){if(H.removeAdditional===`all`||H.removeAdditional&&O===!1){te(t);return}if(O===!1){e.setParams({additionalProperty:t}),e.error(),B||D.break();return}if(typeof O==`object`&&!(0,E.alwaysValidSchema)(L,O)){let w=D.name(`valid`);H.removeAdditional===`failing`?(ae(t,w,!1),D.if((0,S.not)(w),()=>{e.reset(),te(t)})):(ae(t,w),B||D.if((0,S.not)(w),()=>D.break()))}}function ae(t,S,w){let D={keyword:`additionalProperties`,dataProp:t,dataPropType:E.Type.Str};w===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(D,S)}}}})),require_properties=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),S=require_code(),w=require_util(),E=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:D,schema:O,parentSchema:k,data:j,it:F}=e;F.opts.removeAdditional===`all`&&k.additionalProperties===void 0&&E.default.code(new t.KeywordCxt(F,E.default,`additionalProperties`));let L=(0,S.allSchemaProperties)(O);for(let e of L)F.definedProperties.add(e);F.opts.unevaluated&&L.length&&F.props!==!0&&(F.props=w.mergeEvaluated.props(D,(0,w.toHash)(L),F.props));let B=L.filter(e=>!(0,w.alwaysValidSchema)(F,O[e]));if(B.length===0)return;let H=D.name(`valid`);for(let t of B)q(t)?J(t):(D.if((0,S.propertyInData)(D,j,t,F.opts.ownProperties)),J(t),F.allErrors||D.else().var(H,!0),D.endIf()),e.it.definedProperties.add(t),e.ok(H);function q(e){return F.opts.useDefaults&&!F.compositeRule&&O[e].default!==void 0}function J(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},H)}}}})),require_patternProperties=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),S=require_codegen(),w=require_util(),E=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:D,schema:O,data:k,parentSchema:j,it:F}=e,{opts:L}=F,B=(0,t.allSchemaProperties)(O),H=B.filter(e=>(0,w.alwaysValidSchema)(F,O[e]));if(B.length===0||H.length===B.length&&(!F.opts.unevaluated||F.props===!0))return;let q=L.strictSchema&&!L.allowMatchingProperties&&j.properties,J=D.name(`valid`);F.props!==!0&&!(F.props instanceof S.Name)&&(F.props=(0,E.evaluatedPropsToName)(D,F.props));let{props:Y}=F;ee();function ee(){for(let e of B)q&&te(e),F.allErrors?ne(e):(D.var(J,!0),ne(e),D.if(J))}function te(e){for(let t in q)new RegExp(e).test(t)&&(0,w.checkStrictMode)(F,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function ne(w){D.forIn(`key`,k,O=>{D.if((0,S._)`${(0,t.usePattern)(e,w)}.test(${O})`,()=>{let t=H.includes(w);t||e.subschema({keyword:`patternProperties`,schemaProp:w,dataProp:O,dataPropType:E.Type.Str},J),F.opts.unevaluated&&Y!==!0?D.assign((0,S._)`${Y}[${O}]`,!0):!t&&!F.allErrors&&D.if((0,S.not)(J),()=>D.break())})})}}}})),require_not=__commonJSMin$1((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:w,it:E}=e;if((0,t.alwaysValidSchema)(E,w)){e.fail();return}let D=S.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},D),e.failResult(D,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$1((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$1((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:w,schema:E,parentSchema:D,it:O}=e;if(!Array.isArray(E))throw Error(`ajv implementation error`);if(O.opts.discriminator&&D.discriminator)return;let k=E,j=w.let(`valid`,!1),F=w.let(`passing`,null),L=w.name(`_valid`);e.setParams({passing:F}),w.block(B),e.result(j,()=>e.reset(),()=>e.error(!0));function B(){k.forEach((E,D)=>{let k;(0,S.alwaysValidSchema)(O,E)?w.var(L,!0):k=e.subschema({keyword:`oneOf`,schemaProp:D,compositeRule:!0},L),D>0&&w.if((0,t._)`${L} && ${j}`).assign(j,!1).assign(F,(0,t._)`[${F}, ${D}]`).else(),w.if(L,()=>{w.assign(j,!0),w.assign(F,D),k&&e.mergeEvaluated(k,t.Name)})})}}}})),require_allOf=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:S,schema:w,it:E}=e;if(!Array.isArray(w))throw Error(`ajv implementation error`);let D=S.name(`valid`);w.forEach((S,w)=>{if((0,t.alwaysValidSchema)(E,S))return;let O=e.subschema({keyword:`allOf`,schemaProp:w},D);e.ok(D),e.mergeEvaluated(O)})}}})),require_if=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),S=require_util(),w={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:w,parentSchema:D,it:O}=e;D.then===void 0&&D.else===void 0&&(0,S.checkStrictMode)(O,`"if" without "then" and "else" is ignored`);let k=E(O,`then`),j=E(O,`else`);if(!k&&!j)return;let F=w.let(`valid`,!0),L=w.name(`_valid`);if(B(),e.reset(),k&&j){let t=w.let(`ifClause`);e.setParams({ifClause:t}),w.if(L,H(`then`,t),H(`else`,t))}else k?w.if(L,H(`then`)):w.if((0,t.not)(L),H(`else`));e.pass(F,()=>e.error(!0));function B(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},L);e.mergeEvaluated(t)}function H(S,E){return()=>{let D=e.subschema({keyword:S},L);w.assign(F,L),e.mergeValidEvaluated(D,F),E?w.assign(E,(0,t._)`${S}`):e.setParams({ifClause:S})}}}};function E(e,t){let w=e.schema[t];return w!==void 0&&!(0,S.alwaysValidSchema)(e,w)}e.default=w})),require_thenElse=__commonJSMin$1((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:w}){S.if===void 0&&(0,t.checkStrictMode)(w,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),S=require_prefixItems(),w=require_items(),E=require_items2020(),D=require_contains(),O=require_dependencies(),k=require_propertyNames(),j=require_additionalProperties(),F=require_properties(),L=require_patternProperties(),B=require_not(),H=require_anyOf(),q=require_oneOf(),J=require_allOf(),Y=require_if(),ee=require_thenElse();function te(e=!1){let te=[B.default,H.default,q.default,J.default,Y.default,ee.default,k.default,j.default,O.default,F.default,L.default];return e?te.push(S.default,E.default):te.push(t.default,w.default),te.push(D.default),te}e.default=te})),require_format$1=__commonJSMin$1((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:w,data:E,$data:D,schema:O,schemaCode:k,it:j}=e,{opts:F,errSchemaPath:L,schemaEnv:B,self:H}=j;if(!F.validateFormats)return;D?q():J();function q(){let D=w.scopeValue(`formats`,{ref:H.formats,code:F.code.formats}),O=w.const(`fDef`,(0,t._)`${D}[${k}]`),j=w.let(`fType`),L=w.let(`format`);w.if((0,t._)`typeof ${O} == "object" && !(${O} instanceof RegExp)`,()=>w.assign(j,(0,t._)`${O}.type || "string"`).assign(L,(0,t._)`${O}.validate`),()=>w.assign(j,(0,t._)`"string"`).assign(L,O)),e.fail$data((0,t.or)(q(),J()));function q(){return F.strictSchema===!1?t.nil:(0,t._)`${k} && !${L}`}function J(){let e=B.$async?(0,t._)`(${O}.async ? await ${L}(${E}) : ${L}(${E}))`:(0,t._)`${L}(${E})`,w=(0,t._)`(typeof ${L} == "function" ? ${e} : ${L}.test(${E}))`;return(0,t._)`${L} && ${L} !== true && ${j} === ${S} && !${w}`}}function J(){let D=H.formats[O];if(!D){J();return}if(D===!0)return;let[k,j,q]=Y(D);k===S&&e.pass(ee());function J(){if(F.strictSchema===!1){H.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${O}" ignored in schema at path "${L}"`}}function Y(e){let S=e instanceof RegExp?(0,t.regexpCode)(e):F.code.formats?(0,t._)`${F.code.formats}${(0,t.getProperty)(O)}`:void 0,E=w.scopeValue(`formats`,{key:O,ref:e,code:S});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${E}.validate`]:[`string`,e,E]}function ee(){if(typeof D==`object`&&!(D instanceof RegExp)&&D.async){if(!B.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${q}(${E})`}return typeof j==`function`?(0,t._)`${q}(${E})`:(0,t._)`${q}.test(${E})`}}}}})),require_format=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$1((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$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),S=require_validation$2(),w=require_applicator(),E=require_format(),D=require_metadata();e.default=[t.default,S.default,(0,w.default)(),E.default,D.metadataVocabulary,D.contentVocabulary]})),require_types=__commonJSMin$1((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$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),S=require_types(),w=require_compile(),E=require_ref_error(),D=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:w}})=>(0,t._)`{error: ${e}, tag: ${w}, tagValue: ${S}}`},code(e){let{gen:O,data:k,schema:j,parentSchema:F,it:L}=e,{oneOf:B}=F;if(!L.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let H=j.propertyName;if(typeof H!=`string`)throw Error(`discriminator: requires propertyName`);if(j.mapping)throw Error(`discriminator: mapping is not supported`);if(!B)throw Error(`discriminator: requires oneOf keyword`);let q=O.let(`valid`,!1),J=O.const(`tag`,(0,t._)`${k}${(0,t.getProperty)(H)}`);O.if((0,t._)`typeof ${J} == "string"`,()=>Y(),()=>e.error(!1,{discrError:S.DiscrError.Tag,tag:J,tagName:H})),e.ok(q);function Y(){let w=te();O.if(!1);for(let e in w)O.elseIf((0,t._)`${J} === ${e}`),O.assign(q,ee(w[e]));O.else(),e.error(!1,{discrError:S.DiscrError.Mapping,tag:J,tagName:H}),O.endIf()}function ee(S){let w=O.name(`valid`),E=e.subschema({keyword:`oneOf`,schemaProp:S},w);return e.mergeEvaluated(E,t.Name),w}function te(){var e;let t={},S=k(F),O=!0;for(let e=0;e<B.length;e++){let t=B[e];if(t?.$ref&&!(0,D.schemaHasRulesButRef)(t,L.self.RULES)){let e=t.$ref;if(t=w.resolveRef.call(L.self,L.schemaEnv.root,L.baseId,e),t instanceof w.SchemaEnv&&(t=t.schema),t===void 0)throw new E.default(L.opts.uriResolver,L.baseId,e)}let F=t?.properties?.[H];if(typeof F!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${H}"`);O&&=S||k(t),j(F,e)}if(!O)throw Error(`discriminator: "${H}" must be required`);return t;function k({required:e}){return Array.isArray(e)&&e.includes(H)}function j(e,t){if(e.const)q(e.const,t);else if(e.enum)for(let S of e.enum)q(S,t);else throw Error(`discriminator: "properties/${H}" must have "const" or "enum"`)}function q(e,S){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${H}" values must be unique strings`);t[e]=S}}}}})),require_json_schema_draft_07=__commonJSMin$1(((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$1(((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(),w=require_draft7(),E=require_discriminator(),D=require_json_schema_draft_07(),O=[`/properties`],k=`http://json-schema.org/draft-07/schema`;var j=class extends S.default{_addVocabularies(){super._addVocabularies(),w.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(E.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(D,O):D;this.addMetaSchema(e,k,!1),this.refs[`http://json-schema.org/schema`]=k}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(k)?k:void 0)}};e.Ajv=j,t.exports=e=j,t.exports.Ajv=j,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=j;var F=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return F.KeywordCxt}});var L=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return L._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return L.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return L.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return L.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return L.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return L.CodeGen}});var B=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return B.default}});var H=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return H.default}})})),require_formats=__commonJSMin$1((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(D,O),time:t(j(!0),F),"date-time":t(H(!0),q),"iso-time":t(j(),L),"iso-date-time":t(H(),J),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:te,"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:me,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:ae,int32:{type:`number`,validate:ce},int64:{type:`number`,validate:ue},float:{type:`number`,validate:de},double:{type:`number`,validate:de},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,O),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,F),"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,q),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,L),"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,J),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 w=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,E=[0,31,28,31,30,31,30,31,31,30,31,30,31];function D(e){let t=w.exec(e);if(!t)return!1;let D=+t[1],O=+t[2],k=+t[3];return O>=1&&O<=12&&k>=1&&k<=(O===2&&S(D)?29:E[O])}function O(e,t){if(e&&t)return e>t?1:e<t?-1:0}let k=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function j(e){return function(t){let S=k.exec(t);if(!S)return!1;let w=+S[1],E=+S[2],D=+S[3],O=S[4],j=S[5]===`-`?-1:1,F=+(S[6]||0),L=+(S[7]||0);if(F>23||L>59||e&&!O)return!1;if(w<=23&&E<=59&&D<60)return!0;let B=E-L*j,H=w-F*j-(B<0?1:0);return(H===23||H===-1)&&(B===59||B===-1)&&D<61}}function F(e,t){if(!(e&&t))return;let S=new Date(`2020-01-01T`+e).valueOf(),w=new Date(`2020-01-01T`+t).valueOf();if(S&&w)return S-w}function L(e,t){if(!(e&&t))return;let S=k.exec(e),w=k.exec(t);if(S&&w)return e=S[1]+S[2]+S[3],t=w[1]+w[2]+w[3],e>t?1:e<t?-1:0}let B=/t|\s/i;function H(e){let t=j(e);return function(e){let S=e.split(B);return S.length===2&&D(S[0])&&t(S[1])}}function q(e,t){if(!(e&&t))return;let S=new Date(e).valueOf(),w=new Date(t).valueOf();if(S&&w)return S-w}function J(e,t){if(!(e&&t))return;let[S,w]=e.split(B),[E,D]=t.split(B),k=O(S,E);if(k!==void 0)return k||F(w,D)}let Y=/\/|:/,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 te(e){return Y.test(e)&&ee.test(e)}let ne=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function ae(e){return ne.lastIndex=0,ne.test(e)}let oe=-(2**31),se=2**31-1;function ce(e){return Number.isInteger(e)&&e<=se&&e>=oe}function ue(e){return Number.isInteger(e)}function de(){return!0}let fe=/[^\\]\\Z/;function me(e){if(fe.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),S=require_codegen(),w=S.operators,E={formatMaximum:{okStr:`<=`,ok:w.LTE,fail:w.GT},formatMinimum:{okStr:`>=`,ok:w.GTE,fail:w.LT},formatExclusiveMaximum:{okStr:`<`,ok:w.LT,fail:w.GTE},formatExclusiveMinimum:{okStr:`>`,ok:w.GT,fail:w.LTE}};e.formatLimitDefinition={keyword:Object.keys(E),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,S.str)`should be ${E[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,S._)`{comparison: ${E[e].okStr}, limit: ${t}}`},code(e){let{gen:w,data:D,schemaCode:O,keyword:k,it:j}=e,{opts:F,self:L}=j;if(!F.validateFormats)return;let B=new t.KeywordCxt(j,L.RULES.all.format.definition,`format`);B.$data?H():q();function H(){let t=w.scopeValue(`formats`,{ref:L.formats,code:F.code.formats}),E=w.const(`fmt`,(0,S._)`${t}[${B.schemaCode}]`);e.fail$data((0,S.or)((0,S._)`typeof ${E} != "object"`,(0,S._)`${E} instanceof RegExp`,(0,S._)`typeof ${E}.compare != "function"`,J(E)))}function q(){let t=B.schema,E=L.formats[t];if(!E||E===!0)return;if(typeof E!=`object`||E instanceof RegExp||typeof E.compare!=`function`)throw Error(`"${k}": format "${t}" does not define "compare" function`);let D=w.scopeValue(`formats`,{key:t,ref:E,code:F.code.formats?(0,S._)`${F.code.formats}${(0,S.getProperty)(t)}`:void 0});e.fail$data(J(D))}function J(e){return(0,S._)`${e}.compare(${D}, ${O}) ${E[k].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$1(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let S=require_formats(),w=require_limit(),E=require_codegen(),D=new E.Name(`fullFormats`),O=new E.Name(`fastFormats`),k=(e,t={keywords:!0})=>{if(Array.isArray(t))return j(e,t,S.fullFormats,D),e;let[E,k]=t.mode===`fast`?[S.fastFormats,O]:[S.fullFormats,D];return j(e,t.formats||S.formatNames,E,k),t.keywords&&(0,w.default)(e),e};k.get=(e,t=`full`)=>{let w=(t===`fast`?S.fastFormats:S.fullFormats)[e];if(!w)throw Error(`Unknown format "${e}"`);return w};function j(e,t,S,w){var D,O;(O=e.opts.code).formats??(O.formats=(0,E._)`require("ajv-formats/dist/formats").${w}`);for(let w of t)e.addFormat(w,S[w])}t.exports=e=k,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=k})),import_ajv=__toESM$1(require_ajv(),1),import_dist=__toESM$1(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],w=S.some(e=>e.type===`tool_result`),E=e.messages.length>1?e.messages[e.messages.length-2]:void 0,D=E?Array.isArray(E.content)?E.content:[E.content]:[],O=D.some(e=>e.type===`tool_use`);if(w){if(S.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!O)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(O){let e=new Set(D.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(),w=e.mode??`form`;switch(w){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 E=w===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:E},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:w}=e.params,E=LoggingLevelSchema.safeParse(w);return E.success&&this._loggingLevels.set(S,E.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 w;if(isZ4Schema(S)){let e=S;w=e._zod?.def?.value??e.value}else{let e=S;w=e._def?.value??e.value}if(typeof w!=`string`)throw Error(`Schema method literal must be a string`);return w===`tools/call`?super.setRequestHandler(e,async(e,S)=>{let w=safeParse(CallToolRequestSchema,e);if(!w.success){let e=w.error instanceof Error?w.error.message:String(w.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:E}=w.data,D=await Promise.resolve(t(e,S));if(E.task){let e=safeParse(CreateTaskResultSchema,D);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 O=safeParse(CallToolResultSchema,D);if(!O.success){let e=O.error instanceof Error?O.error.message:String(O.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return O.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],w=S.some(e=>e.type===`tool_result`),E=e.messages.length>1?e.messages[e.messages.length-2]:void 0,D=E?Array.isArray(E.content)?E.content:[E.content]:[],O=D.some(e=>e.type===`tool_use`);if(w){if(S.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!O)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(O){let e=new Set(D.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`},w=await this.request({method:`elicitation/create`,params:S},ElicitResultSchema,t);if(w.action===`accept`&&w.content&&S.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(S.requestedSchema)(w.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 w}}}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 w={taskSupport:`required`,...t.execution};if(w.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,w,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 w=!!e.params.task,E=S.execution?.taskSupport,D=`createTask`in S.handler;if((E===`required`||E===`optional`)&&!D)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${E}' but was not registered with registerToolTask`);if(E===`required`&&!w)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(E===`optional`&&!w&&D)return await this.handleAutomaticTaskPolling(S,e,t);let O=await this.validateToolInput(S,e.params.arguments,e.params.name),k=await this.executeToolHandler(S,O,t);return w||await this.validateToolOutput(S,k,e.params.name),k}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 w=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!w.success){let e=getParseErrorMessage(`error`in w?w.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${S}: ${e}`)}return w.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 w=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!w.success){let e=getParseErrorMessage(`error`in w?w.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${S}: ${e}`)}}async executeToolHandler(e,t,S){let w=e.handler;if(`createTask`in w){if(!S.taskStore)throw Error(`No task store provided.`);let E={...S,taskStore:S.taskStore};if(e.inputSchema){let e=w;return await Promise.resolve(e.createTask(t,E))}else{let e=w;return await Promise.resolve(e.createTask(E))}}if(e.inputSchema){let e=w;return await Promise.resolve(e(t,S))}else{let e=w;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 w=await this.validateToolInput(e,t.params.arguments,t.params.name),E=e.handler,D={...S,taskStore:S.taskStore},O=w?await Promise.resolve(E.createTask(w,D)):await Promise.resolve(E.createTask(D)),k=O.task.taskId,j=O.task,F=j.pollInterval??5e3;for(;j.status!==`completed`&&j.status!==`failed`&&j.status!==`cancelled`;){await new Promise(e=>setTimeout(e,F));let e=await S.taskStore.getTask(k);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${k} not found during polling`);j=e}return await S.taskStore.getTaskResult(k)}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 w=getObjectShape(S.argsSchema)?.[e.params.argument.name];if(!isCompletable(w))return EMPTY_COMPLETION_RESULT;let E=getCompleter(w);return E?createCompletionResult(await E(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 w=S.resourceTemplate.completeCallback(e.params.argument.name);return w?createCompletionResult(await w(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})),w=[];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)w.push({...e.metadata,...t})}return{resources:[...S,...w]}}),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),w=this._registeredResources[S.toString()];if(w){if(!w.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${S} disabled`);return w.readCallback(S,t)}for(let e of Object.values(this._registeredResourceTemplates)){let w=e.resourceTemplate.uriTemplate.match(S.toString());if(w)return e.readCallback(S,w,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 w=await safeParseAsync(normalizeObjectSchema(S.argsSchema),e.params.arguments);if(!w.success){let t=getParseErrorMessage(`error`in w?w.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let E=w.data,D=S.callback;return await Promise.resolve(D(E,t))}else{let e=S.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...S){let w;typeof S[0]==`object`&&(w=S.shift());let E=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,w,E);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,w,E);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}registerResource(e,t,S,w){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let E=this._createRegisteredResource(e,S.title,t,S,w);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),E}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let E=this._createRegisteredResourceTemplate(e,S.title,t,S,w);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),E}}_createRegisteredResource(e,t,S,w,E){let D={name:e,title:t,metadata:w,readCallback:E,enabled:!0,disable:()=>D.update({enabled:!1}),enable:()=>D.update({enabled:!0}),remove:()=>D.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==S&&(delete this._registeredResources[S],e.uri&&(this._registeredResources[e.uri]=D)),e.name!==void 0&&(D.name=e.name),e.title!==void 0&&(D.title=e.title),e.metadata!==void 0&&(D.metadata=e.metadata),e.callback!==void 0&&(D.readCallback=e.callback),e.enabled!==void 0&&(D.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[S]=D,D}_createRegisteredResourceTemplate(e,t,S,w,E){let D={resourceTemplate:S,title:t,metadata:w,readCallback:E,enabled:!0,disable:()=>D.update({enabled:!1}),enable:()=>D.update({enabled:!0}),remove:()=>D.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=D)),t.title!==void 0&&(D.title=t.title),t.template!==void 0&&(D.resourceTemplate=t.template),t.metadata!==void 0&&(D.metadata=t.metadata),t.callback!==void 0&&(D.readCallback=t.callback),t.enabled!==void 0&&(D.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=D;let O=S.uriTemplate.variableNames;return Array.isArray(O)&&O.some(e=>!!S.completeCallback(e))&&this.setCompletionRequestHandler(),D}_createRegisteredPrompt(e,t,S,w,E){let D={title:t,description:S,argsSchema:w===void 0?void 0:objectFromShape(w),callback:E,enabled:!0,disable:()=>D.update({enabled:!1}),enable:()=>D.update({enabled:!0}),remove:()=>D.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=D)),t.title!==void 0&&(D.title=t.title),t.description!==void 0&&(D.description=t.description),t.argsSchema!==void 0&&(D.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(D.callback=t.callback),t.enabled!==void 0&&(D.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=D,w&&Object.values(w).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),D}_createRegisteredTool(e,t,S,w,E,D,O,k,j){validateAndWarnToolName(e);let F={title:t,description:S,inputSchema:getZodSchemaObject(w),outputSchema:getZodSchemaObject(E),annotations:D,execution:O,_meta:k,handler:j,enabled:!0,disable:()=>F.update({enabled:!1}),enable:()=>F.update({enabled:!0}),remove:()=>F.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]=F)),t.title!==void 0&&(F.title=t.title),t.description!==void 0&&(F.description=t.description),t.paramsSchema!==void 0&&(F.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(F.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(F.handler=t.callback),t.annotations!==void 0&&(F.annotations=t.annotations),t._meta!==void 0&&(F._meta=t._meta),t.enabled!==void 0&&(F.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=F,this.setToolRequestHandlers(),this.sendToolListChanged(),F}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let S,w,E,D;if(typeof t[0]==`string`&&(S=t.shift()),t.length>1){let S=t[0];if(isZodRawShapeCompat(S))w=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(D=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`);D=t.shift()}}let O=t[0];return this._createRegisteredTool(e,void 0,S,w,void 0,D,{taskSupport:`forbidden`},void 0,O)}registerTool(e,t,S){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:w,description:E,inputSchema:D,outputSchema:O,annotations:k,_meta:j}=t;return this._createRegisteredTool(e,w,E,D,O,k,{taskSupport:`forbidden`},j,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 w;t.length>1&&(w=t.shift());let E=t[0],D=this._createRegisteredPrompt(e,void 0,S,w,E);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),D}registerPrompt(e,t,S){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:w,description:E,argsSchema:D}=t,O=this._createRegisteredPrompt(e,w,E,D,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),O}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]:w,[e+1]:E}=S;w.charCodeAt(0)!==58&&t.push([w,E])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,S,w,E)=>{let D={method:e,headers:S,signal:E.signal};if(e===`TRACE`){D.method=`GET`;let e=new Request$1(t,D);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in w&&w.rawBody instanceof Buffer)D.body=new ReadableStream({start(e){e.enqueue(w.rawBody),e.close()}});else if(w[wrapBodyStream]){let e;D.body=new ReadableStream({async pull(t){try{e||=Readable.toWeb(w).getReader();let{done:S,value:E}=await e.read();S?t.close():t.enqueue(E)}catch(e){t.error(e)}}})}else D.body=Readable.toWeb(w);return new Request$1(t,D)},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 w=e.url||``;if(w[0]!==`/`&&(w.startsWith(`http://`)||w.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{S[urlKey]=new URL(w).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return S}let E=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!E)throw new RequestError(`Missing host header`);let D;if(e instanceof Http2ServerRequest){if(D=e.scheme,!(D===`http`||D===`https`))throw new RequestError(`Unsupported scheme`)}else D=e.socket&&e.socket.encrypted?`https`:`http`;let O=new URL(`${D}://${E}${w}`);if(O.hostname.length!==E.length&&O.hostname!==E.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return S[urlKey]=O.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 w;if(this.#e=t,S instanceof e){let e=S[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=S.#t,w=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,w||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 w=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,w),t.on(`error`,w),(S??e.read()).then(O,E),e.closed.finally(()=>{t.off(`close`,w),t.off(`error`,w)});function E(e){e&&t.destroy(e)}function D(){e.read().then(O,E)}function O({done:S,value:w}){try{if(S)t.end();else if(!t.write(w))t.once(`drain`,D);else return e.read().then(O,E)}catch(e){E(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[w,E]of e)w===`set-cookie`?S.push(E):t[w]=E;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$2);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$1.NGHTTP2_NO_ERROR)}catch{}return}let S=0,w=()=>{clearTimeout(D),e.off(`data`,O),e.off(`end`,w),e.off(`error`,w)},E=()=>{w();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},D=setTimeout(E,DRAIN_TIMEOUT_MS);D.unref?.();let O=e=>{S+=e.length,S>MAX_DRAIN_BYTES&&E()};e.on(`data`,O),e.on(`end`,w),e.on(`error`,w),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,w,E]=e[cacheKey],D=!1;if(!E)E={"content-type":`text/plain; charset=UTF-8`};else if(E instanceof Headers)D=E.has(`content-length`),E=buildOutgoingHttpHeaders(E);else if(Array.isArray(E)){let e=new Headers(E);D=e.has(`content-length`),E=buildOutgoingHttpHeaders(e)}else for(let e in E)if(e.length===14&&e.toLowerCase()===`content-length`){D=!0;break}D||(typeof w==`string`?E[`Content-Length`]=Buffer.byteLength(w):w instanceof Uint8Array?E[`Content-Length`]=w.byteLength:w instanceof Blob&&(E[`Content-Length`]=w.size)),t.writeHead(S,E),typeof w==`string`||w instanceof Uint8Array?t.end(w):w instanceof Blob?t.end(new Uint8Array(await w.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(w,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 w=await S.errorHandler(t);if(!w)return;e=w}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let w=buildOutgoingHttpHeaders(e.headers);if(e.body){let S=e.body.getReader(),E=[],D=!1,O;if(w[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){O||=S.read();let w=await readWithoutBlocking(O).catch(e=>{console.error(e),D=!0});if(!w){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(O=void 0,w.value&&E.push(w.value),w.done){D=!0;break}}D&&!(`content-length`in w)&&(w[`content-length`]=E.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,w),E.forEach(e=>{t.write(e)}),D?t.end():(E.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(S,t,O))}else w[X_ALREADY_SENT]||(t.writeHead(e.status,w),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(w,E)=>{let D,O;try{O=newRequest(w,t.hostname);let k=!S||w.method===`GET`||w.method===`HEAD`;if(k||(w[wrapBodyStream]=!0,w.on(`end`,()=>{k=!0}),w instanceof Http2ServerRequest&&(E[outgoingEnded]=()=>{k||setTimeout(()=>{k||setTimeout(()=>{drainIncoming(w)})})}),E.on(`finish`,()=>{k||drainIncoming(w)})),E.on(`close`,()=>{O[abortControllerKey]&&(w.errored?O[abortControllerKey].abort(w.errored.toString()):E.writableFinished||O[abortControllerKey].abort(`Client connection prematurely closed.`)),k||setTimeout(()=>{k||setTimeout(()=>{drainIncoming(w)})})}),D=e(O,{incoming:w,outgoing:E}),cacheKey in D)return responseViaCache(D,E)}catch(e){if(D)return handleResponseError(e,E);if(t.errorHandler){if(D=await t.errorHandler(O?e:toRequestError(e)),!D)return}else D=O?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(D,E,t)}catch(e){return handleResponseError(e,E)}}},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,w){let E={code:t,message:S};return w?.data!==void 0&&(E.data=w.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:E,id:null}),{status:e,headers:{"Content-Type":`application/json`,...w?.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,w){if(!this._eventStore||w<`2025-11-25`)return;let E=await this._eventStore.storeEvent(S,{}),D=`id: ${E}\ndata: \n\n`;this._retryInterval!==void 0&&(D=`id: ${E}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(D))}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 w=new TextEncoder,E,D=new ReadableStream({start:e=>{E=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),O={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(O[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:E,encoder:w,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{E.close()}catch{}}}),new Response(D,{headers:O})}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 w=new TextEncoder,E,D=new ReadableStream({start:e=>{E=e},cancel:()=>{}}),O=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(E,w,t,e)){this.onerror?.(Error(`Failed replay events`));try{E.close()}catch{}}}});return this._streamMapping.set(O,{controller:E,encoder:w,cleanup:()=>{this._streamMapping.delete(O);try{E.close()}catch{}}}),new Response(D,{headers:S})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,S,w){try{let E=`event: message
|
|
483
|
-
`;return w&&(E+=`id: ${w}\n`),E+=`data: ${JSON.stringify(S)}\n\n`,e.enqueue(t.encode(E)),!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 w=e.headers.get(`content-type`);if(!w||!w.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 E={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},D;if(t?.parsedBody!==void 0)D=t.parsedBody;else try{D=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let O;try{O=Array.isArray(D)?D.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(D)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let k=O.some(isInitializeRequest);if(k){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(O.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(!k){let t=this.validateSession(e);if(t)return t;let S=this.validateProtocolVersion(e);if(S)return S}if(!O.some(isJSONRPCRequest)){for(let e of O)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E});return new Response(null,{status:202})}let j=crypto.randomUUID(),F=O.find(e=>isInitializeRequest(e)),L=F?F.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(j,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(j)}});for(let e of O)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,j);for(let e of O)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E})});let B=new TextEncoder,H,q=new ReadableStream({start:e=>{H=e},cancel:()=>{this._streamMapping.delete(j)}}),J={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(J[`mcp-session-id`]=this.sessionId);for(let e of O)isJSONRPCRequest(e)&&(this._streamMapping.set(j,{controller:H,encoder:B,cleanup:()=>{this._streamMapping.delete(j);try{H.close()}catch{}}}),this._requestToStreamMapping.set(e.id,j));await this.writePrimingEvent(H,B,j,L);for(let e of O){let S,w;isJSONRPCRequest(e)&&this._eventStore&&L>=`2025-11-25`&&(S=()=>{this.closeSSEStream(e.id)},w=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E,closeSSEStream:S,closeStandaloneSSEStream:w})}return new Response(q,{status:200,headers:J})}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 w=this._requestToStreamMapping.get(S);if(!w)throw Error(`No connection established for request ID: ${String(S)}`);let E=this._streamMapping.get(w);if(!this._enableJsonResponse&&E?.controller&&E?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(w,e)),this.writeSSEEvent(E.controller,E.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(S,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===w).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!E)throw Error(`No connection established for request ID: ${String(S)}`);if(this._enableJsonResponse&&E.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?E.resolveJson(new Response(JSON.stringify(S[0]),{status:200,headers:e})):E.resolveJson(new Response(JSON.stringify(S),{status:200,headers:e}))}else E.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 w=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:w,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-D_LDH8mS.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-CI2IrKwx.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-DjH-DHsP.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BWWIeWvm.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-DbpQ_xq6.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-BRaqkv9Z.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-BdSZnvQi.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-_UcxChNg.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-Fs-BUNPK.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CH8FstC-.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-oG2zzF3W.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-D31pO-B4.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-VQ3RwUo8.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-L50-Upms.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-C2sNM7Dv.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-CG1c0Pxf.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-D1U1S7L6.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-NmZL1hMB.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-BrvjgaMQ.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-CZsNmySp.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-DeuggFRh.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BePJiuxU.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CiH7i9-p.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-Dbe_0JM-.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-QytesYLS.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C1AAbgf8.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-QjngBhOg.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-CwKU0j6Z.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-VxSz_iJ4.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CnErgTj9.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-CHt1YsOk.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-gIXCkWyw.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-CUJSASTo.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-COiAX9LF.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-OtgXQJPP.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-Bc_GxS8t.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-D_NgfJcm.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-BE_RhPSK.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DSRxx5mc.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-BU2v6Jk9.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CsfD1mRM.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-BcC6aUKa.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-C4ozdy42.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-C4ozdy42.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-CjsckksZ.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-CjsckksZ.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-rwbd7U40.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CqFBjjSK.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-DJUeGOw7.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-DJUeGOw7.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CwAD0ujG.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DFBZjU3V.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DFBZjU3V.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-B5VN-dXM.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-Cj7j5Pz8.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DRmjT8LD.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-Cg5stPCO.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-D3Ph1Gn6.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-LxpBVg0M.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DdyaxseS.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-Cg0b6SeB.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-BL4xVSIz.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-lBp2yvEW.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-CAg7QQIj.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-CFFtkep9.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-CT98h277.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-Db230ZWS.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-CZumUR0P.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CRVfCXCP.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-B-fSXHB1.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-BQG1bQvh.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-COB3yQf8.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BniMheOA.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-DH18Zmoc.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-B5nTz8YA.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-iFQjU_f2.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-B0OUvEvJ.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-BSuL_Nsg.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-BSuL_Nsg.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-BssUQ3SC.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-BssUQ3SC.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-Dq2QRfS5.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,S){let w=tn.get(e.name);if(w||(w=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,w)),S.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:w}=await import(`./flag-coverage-QT4N2Z44-CQ2g5NLf.mjs`);w(S.coverage,e.name,t)}return w.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,w){return t||=await e.load(),t.execute(S,w)}}}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,w){h$3(e,`write`);let E=c$2(e);this.ensureParentDirs(E);let D=o(t,l$1(S));this.data.set(E,{type:`file`,content:D,mode:w?.mode??420,mtime:w?.mtime??new Date})}writeFileLazy(e,t,S){h$3(e,`write`);let w=c$2(e);this.ensureParentDirs(w),this.data.set(w,{type:`file`,lazy:t,mode:S?.mode??420,mtime:S?.mtime??new Date})}async materializeLazy(e,t){let S=await t.lazy(),w={type:`file`,content:typeof S==`string`?ot.encode(S):S,mode:t.mode,mtime:t.mtime};return this.data.set(e,w),w}async readFile(e,t){return h$4(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$3(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$3(e,`append`);let w=c$2(e),E=this.data.get(w);if(E&&E.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let D=o(t,l$1(S));if(E?.type===`file`){let e=E;`lazy`in e&&(e=await this.materializeLazy(w,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),S=new Uint8Array(t.length+D.length);S.set(t),S.set(D,t.length),this.data.set(w,{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$3(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 w=0;return S.type===`file`&&`content`in S&&S.content&&(w=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:w,mtime:S.mtime||new Date}}async lstat(e){h$3(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 w=0;return S.type===`file`&&`content`in S&&S.content&&(w=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:w,mtime:S.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$2(e);if(t===`/`)return`/`;let S=t.slice(1).split(`/`);if(S.length<=1)return t;let w=``,E=new Set;for(let t=0;t<S.length-1;t++){let D=S[t];w=`${w}/${D}`;let O=this.data.get(w),k=0,j=40;for(;O&&O.type===`symlink`&&k<40;){if(E.has(w))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);E.add(w),w=v$2(w,O.target),O=this.data.get(w),k++}if(k>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${w}/${S[S.length-1]}`}resolvePathWithSymlinks(e){let t=c$2(e);if(t===`/`)return`/`;let S=t.slice(1).split(`/`),w=``,E=new Set;for(let t of S){w=`${w}/${t}`;let S=this.data.get(w),D=0,O=40;for(;S&&S.type===`symlink`&&D<40;){if(E.has(w))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);E.add(w),w=v$2(w,S.target),S=this.data.get(w),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return w}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$3(e,`mkdir`);let S=c$2(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 w=m$1(S);if(w!==`/`&&!this.data.has(w))if(t?.recursive)this.mkdirSync(w,{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$3(e,`scandir`);let t=c$2(e),S=this.data.get(t);if(!S)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let w=new Set;for(;S&&S.type===`symlink`;){if(w.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);w.add(t),t=v$2(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 E=t===`/`?`/`:`${t}/`,D=new Map;for(let[e,S]of this.data.entries())if(e!==t&&e.startsWith(E)){let t=e.slice(E.length),w=t.split(`/`)[0];w&&!t.includes(`/`,w.length)&&!D.has(w)&&D.set(w,{name:w,isFile:S.type===`file`,isDirectory:S.type===`directory`,isSymbolicLink:S.type===`symlink`})}return Array.from(D.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$3(e,`rm`);let S=c$2(e),w=this.data.get(S);if(!w){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(w.type===`directory`){let w=await this.readdir(S);if(w.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of w){let w=p$1(S,e);await this.rm(w,t)}}}this.data.delete(S)}async cp(e,t,S){h$3(e,`cp`),h$3(t,`cp`);let w=c$2(e),E=c$2(t),D=this.data.get(w);if(!D)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(D.type===`file`)if(this.ensureParentDirs(E),`content`in D){let e=D.content instanceof Uint8Array?new Uint8Array(D.content):D.content;this.data.set(E,{...D,content:e})}else this.data.set(E,{...D});else if(D.type===`symlink`)this.ensureParentDirs(E),this.data.set(E,{...D});else if(D.type===`directory`){if(!S?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(E,{recursive:!0});let t=await this.readdir(w);for(let e of t){let t=p$1(w,e),D=p$1(E,e);await this.cp(t,D,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$3(e,`chmod`);let S=c$2(e),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);w.mode=t}async symlink(e,t){h$3(t,`symlink`);let S=c$2(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$3(e,`link`),h$3(t,`link`);let S=c$2(e),w=c$2(t),E=this.data.get(S);if(!E)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(E.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(w))throw Error(`EEXIST: file already exists, link '${t}'`);let D=E;`lazy`in D&&(D=await this.materializeLazy(S,D)),this.ensureParentDirs(w),this.data.set(w,{type:`file`,content:D.content,mode:D.mode,mtime:D.mtime})}async readlink(e){h$3(e,`readlink`);let t=c$2(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$3(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$3(e,`utimes`);let w=c$2(e),E=this.resolvePathWithSymlinks(w),D=this.data.get(E);if(!D)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);D.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}
|
|
479
|
+
`;return w&&(E+=`id: ${w}\n`),E+=`data: ${JSON.stringify(S)}\n\n`,e.enqueue(t.encode(E)),!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 w=e.headers.get(`content-type`);if(!w||!w.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 E={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},D;if(t?.parsedBody!==void 0)D=t.parsedBody;else try{D=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let O;try{O=Array.isArray(D)?D.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(D)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let k=O.some(isInitializeRequest);if(k){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(O.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(!k){let t=this.validateSession(e);if(t)return t;let S=this.validateProtocolVersion(e);if(S)return S}if(!O.some(isJSONRPCRequest)){for(let e of O)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E});return new Response(null,{status:202})}let j=crypto.randomUUID(),F=O.find(e=>isInitializeRequest(e)),L=F?F.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(j,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(j)}});for(let e of O)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,j);for(let e of O)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E})});let B=new TextEncoder,H,q=new ReadableStream({start:e=>{H=e},cancel:()=>{this._streamMapping.delete(j)}}),J={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(J[`mcp-session-id`]=this.sessionId);for(let e of O)isJSONRPCRequest(e)&&(this._streamMapping.set(j,{controller:H,encoder:B,cleanup:()=>{this._streamMapping.delete(j);try{H.close()}catch{}}}),this._requestToStreamMapping.set(e.id,j));await this.writePrimingEvent(H,B,j,L);for(let e of O){let S,w;isJSONRPCRequest(e)&&this._eventStore&&L>=`2025-11-25`&&(S=()=>{this.closeSSEStream(e.id)},w=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:E,closeSSEStream:S,closeStandaloneSSEStream:w})}return new Response(q,{status:200,headers:J})}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 w=this._requestToStreamMapping.get(S);if(!w)throw Error(`No connection established for request ID: ${String(S)}`);let E=this._streamMapping.get(w);if(!this._enableJsonResponse&&E?.controller&&E?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(w,e)),this.writeSSEEvent(E.controller,E.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(S,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===w).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!E)throw Error(`No connection established for request ID: ${String(S)}`);if(this._enableJsonResponse&&E.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?E.resolveJson(new Response(JSON.stringify(S[0]),{status:200,headers:e})):E.resolveJson(new Response(JSON.stringify(S),{status:200,headers:e}))}else E.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 w=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:w,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-D_LDH8mS.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-CI2IrKwx.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-DjH-DHsP.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BWWIeWvm.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-DbpQ_xq6.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-BRaqkv9Z.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-BdSZnvQi.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-_UcxChNg.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-Fs-BUNPK.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CH8FstC-.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-oG2zzF3W.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-D31pO-B4.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-VQ3RwUo8.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-L50-Upms.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-C2sNM7Dv.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-CG1c0Pxf.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-D1U1S7L6.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-NmZL1hMB.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-02E3dSfi.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-BrvjgaMQ.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-CZsNmySp.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-DeuggFRh.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BePJiuxU.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CiH7i9-p.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-Dbe_0JM-.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-QytesYLS.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C1AAbgf8.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-QjngBhOg.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-CwKU0j6Z.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-VxSz_iJ4.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CnErgTj9.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-CHt1YsOk.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-gIXCkWyw.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-CUJSASTo.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-COiAX9LF.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-OtgXQJPP.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-Bc_GxS8t.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-D_NgfJcm.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-BE_RhPSK.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-DSRxx5mc.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-BU2v6Jk9.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CsfD1mRM.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-BcC6aUKa.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-C4ozdy42.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-C4ozdy42.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-CjsckksZ.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-CjsckksZ.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-rwbd7U40.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CqFBjjSK.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-DJUeGOw7.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-DJUeGOw7.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CwAD0ujG.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DFBZjU3V.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DFBZjU3V.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-B5VN-dXM.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-Cj7j5Pz8.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DRmjT8LD.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-Cg5stPCO.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-D3Ph1Gn6.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-LxpBVg0M.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DdyaxseS.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-Cg0b6SeB.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-BL4xVSIz.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-lBp2yvEW.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-CAg7QQIj.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-CFFtkep9.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-CT98h277.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-Db230ZWS.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-CZumUR0P.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-CRVfCXCP.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-B-fSXHB1.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-BQG1bQvh.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-COB3yQf8.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BniMheOA.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-UkVql__3.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-DH18Zmoc.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-B5nTz8YA.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-iFQjU_f2.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-DN8JOqf2.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-CcfVkAVy.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-CcfVkAVy.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-D6BVeQcA.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-D6BVeQcA.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-Dq2QRfS5.mjs`)).curlCommand}],tn=new Map;function Gt(e){return{name:e.name,async execute(t,S){let w=tn.get(e.name);if(w||(w=await _$1.runTrustedAsync(()=>e.load()),tn.set(e.name,w)),S.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:w}=await import(`./flag-coverage-QT4N2Z44-g6MqLsWy.mjs`);w(S.coverage,e.name,t)}return w.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,w){return t||=await e.load(),t.execute(S,w)}}}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,w){h$3(e,`write`);let E=c$2(e);this.ensureParentDirs(E);let D=o(t,l$1(S));this.data.set(E,{type:`file`,content:D,mode:w?.mode??420,mtime:w?.mtime??new Date})}writeFileLazy(e,t,S){h$3(e,`write`);let w=c$2(e);this.ensureParentDirs(w),this.data.set(w,{type:`file`,lazy:t,mode:S?.mode??420,mtime:S?.mtime??new Date})}async materializeLazy(e,t){let S=await t.lazy(),w={type:`file`,content:typeof S==`string`?ot.encode(S):S,mode:t.mode,mtime:t.mtime};return this.data.set(e,w),w}async readFile(e,t){return h$4(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$3(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$3(e,`append`);let w=c$2(e),E=this.data.get(w);if(E&&E.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let D=o(t,l$1(S));if(E?.type===`file`){let e=E;`lazy`in e&&(e=await this.materializeLazy(w,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),S=new Uint8Array(t.length+D.length);S.set(t),S.set(D,t.length),this.data.set(w,{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$3(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 w=0;return S.type===`file`&&`content`in S&&S.content&&(w=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:w,mtime:S.mtime||new Date}}async lstat(e){h$3(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 w=0;return S.type===`file`&&`content`in S&&S.content&&(w=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:w,mtime:S.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$2(e);if(t===`/`)return`/`;let S=t.slice(1).split(`/`);if(S.length<=1)return t;let w=``,E=new Set;for(let t=0;t<S.length-1;t++){let D=S[t];w=`${w}/${D}`;let O=this.data.get(w),k=0,j=40;for(;O&&O.type===`symlink`&&k<40;){if(E.has(w))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);E.add(w),w=v$2(w,O.target),O=this.data.get(w),k++}if(k>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${w}/${S[S.length-1]}`}resolvePathWithSymlinks(e){let t=c$2(e);if(t===`/`)return`/`;let S=t.slice(1).split(`/`),w=``,E=new Set;for(let t of S){w=`${w}/${t}`;let S=this.data.get(w),D=0,O=40;for(;S&&S.type===`symlink`&&D<40;){if(E.has(w))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);E.add(w),w=v$2(w,S.target),S=this.data.get(w),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return w}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$3(e,`mkdir`);let S=c$2(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 w=m$1(S);if(w!==`/`&&!this.data.has(w))if(t?.recursive)this.mkdirSync(w,{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$3(e,`scandir`);let t=c$2(e),S=this.data.get(t);if(!S)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let w=new Set;for(;S&&S.type===`symlink`;){if(w.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);w.add(t),t=v$2(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 E=t===`/`?`/`:`${t}/`,D=new Map;for(let[e,S]of this.data.entries())if(e!==t&&e.startsWith(E)){let t=e.slice(E.length),w=t.split(`/`)[0];w&&!t.includes(`/`,w.length)&&!D.has(w)&&D.set(w,{name:w,isFile:S.type===`file`,isDirectory:S.type===`directory`,isSymbolicLink:S.type===`symlink`})}return Array.from(D.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$3(e,`rm`);let S=c$2(e),w=this.data.get(S);if(!w){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(w.type===`directory`){let w=await this.readdir(S);if(w.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of w){let w=p$1(S,e);await this.rm(w,t)}}}this.data.delete(S)}async cp(e,t,S){h$3(e,`cp`),h$3(t,`cp`);let w=c$2(e),E=c$2(t),D=this.data.get(w);if(!D)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(D.type===`file`)if(this.ensureParentDirs(E),`content`in D){let e=D.content instanceof Uint8Array?new Uint8Array(D.content):D.content;this.data.set(E,{...D,content:e})}else this.data.set(E,{...D});else if(D.type===`symlink`)this.ensureParentDirs(E),this.data.set(E,{...D});else if(D.type===`directory`){if(!S?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(E,{recursive:!0});let t=await this.readdir(w);for(let e of t){let t=p$1(w,e),D=p$1(E,e);await this.cp(t,D,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$3(e,`chmod`);let S=c$2(e),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);w.mode=t}async symlink(e,t){h$3(t,`symlink`);let S=c$2(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$3(e,`link`),h$3(t,`link`);let S=c$2(e),w=c$2(t),E=this.data.get(S);if(!E)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(E.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(w))throw Error(`EEXIST: file already exists, link '${t}'`);let D=E;`lazy`in D&&(D=await this.materializeLazy(S,D)),this.ensureParentDirs(w),this.data.set(w,{type:`file`,content:D.content,mode:D.mode,mtime:D.mtime})}async readlink(e){h$3(e,`readlink`);let t=c$2(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$3(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$3(e,`utimes`);let w=c$2(e),E=this.resolvePathWithSymlinks(w),D=this.data.get(E);if(!D)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);D.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}
|
|
484
480
|
`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
|
|
485
481
|
`),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 w=dn(t.name);if(!w)return t;let E=hn(e,w);if(!E||S.has(w))return t;try{S.add(w);let D=new V,O=E,k=E.endsWith(` `);if(!k)for(let e of t.args){let t=mn(e);O+=` ${t}`}let j;try{j=D.parse(O)}catch(e){if(e instanceof G$1)throw e;return t}if(j.statements.length!==1||j.statements[0].pipelines.length!==1||j.statements[0].pipelines[0].commands.length!==1)return pn(t,E);let F=j.statements[0].pipelines[0].commands[0];if(F.type!==`SimpleCommand`)return pn(t,E);let L={...F,assignments:[...t.assignments,...F.assignments],redirections:[...F.redirections,...t.redirections],line:t.line};if(k&&t.args.length>0&&(L={...L,args:[...L.args,...t.args]},L.args.length>0)){let t=L.args[0];if(fn(t)){let w=dn(t);if(w&&hn(e,w)){let w={type:`SimpleCommand`,name:t,args:L.args.slice(1),assignments:[],redirections:[]},E=Ws(e,w,S);E!==w&&(L={...L,name:E.name,args:[...E.args]})}}}return L}catch(e){throw S.delete(w),e}}function pn(e,t){let S=t;for(let t of e.args){let e=mn(t);S+=` ${e}`}let w=new V;return{type:`SimpleCommand`,name:w.parseWordFromString(`eval`,!1,!1),args:[w.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(``),w=S.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!w||!S.endsWith(`)`))return null;let E=w[1],D=[],O=!1,k=``,j=!1;for(let S of t.parts)if(S.type===`Literal`){let e=S.value;if(!O){let t=e.indexOf(`=(`);t!==-1&&(O=!0,e=e.slice(t+2))}if(O){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(k||j)&&(D.push(k),k=``,j=!1):e&&(k+=e)}}else if(O)if(S.type===`BraceExpansion`)if(/^\[.+\]=/.test(k))k+=En$1({type:`Word`,parts:[S]});else{(k||j)&&(D.push(k),k=``,j=!1);let t=await wl(e,{type:`Word`,parts:[S]});D.push(...t.values)}else{(S.type===`SingleQuoted`||S.type===`DoubleQuoted`||S.type===`Escaped`)&&(j=!0);let t=await Pt$1(e,{type:`Word`,parts:[S]});k+=t}return(k||j)&&D.push(k),`${E}=(${D.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,w=-1,E=!1;for(let e=0;e<t.parts.length;e++){let D=t.parts[e];if(D.type===`Literal`){let t=D.value.indexOf(`+=`);if(t!==-1){let O=D.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(O)){S=e,w=t,E=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(O)){S=e,w=t,E=!0;break}}let O=D.value.indexOf(`=`);if(O!==-1&&(O===0||D.value[O-1]!==`+`)){let t=D.value.slice(0,O);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){S=e,w=O;break}}}}if(S===-1)return null;let D=t.parts.slice(0,S),O=t.parts[S];if(O.type!==`Literal`)return null;let k=E?2:1,j=O.value.slice(0,w),F=O.value.slice(w+k),L=t.parts.slice(S+1),B=``;for(let t of D)B+=await Pt$1(e,{type:`Word`,parts:[t]});B+=j;let H={type:`Word`,parts:F===``?L:[{type:`Literal`,value:F},...L]},q=H.parts.length>0?await Pt$1(e,H):``;return`${B}${E?`+=`:`=`}${q}`}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=``,w=``){throw new b(e,t,S,w)}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
|
|
486
482
|
`);let S=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new d(128,``,`bash: break: ${t[0]}: numeric argument required
|
|
@@ -1196,7 +1192,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
|
|
|
1196
1192
|
`)),E.removeListener(`error`,ae),q.setSocket(E,j,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(q),q.on(`close`,()=>{this.clients.delete(q),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ne,this)})),F(q,w)}};function te(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 ne(e){e._state=2,e.emit(`close`)}function ae(){this.destroy()}function oe(e,t,S,E){S||=w.STATUS_CODES[t],E={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(S),...E},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${w.STATUS_CODES[t]}\r\n`+Object.keys(E).map(e=>`${e}: ${E[e]}`).join(`\r
|
|
1197
1193
|
`)+`\r
|
|
1198
1194
|
\r
|
|
1199
|
-
`+S)}function se(e,t,S,w,E,D){if(e.listenerCount(`wsClientError`)){let w=Error(E);Error.captureStackTrace(w,se),e.emit(`wsClientError`,w,S,t)}else oe(S,w,E,D)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM(require_websocket_server(),1),require_ignore=__commonJSMin$1(((e,t)=>{function S(e){return Array.isArray(e)?e:[e]}let w=``,E=` `,D=`\\`,O=/^\s+$/,k=/(?:[^\\]|^)\\$/,j=/^\\!/,F=/^\\#/,L=/\r?\n/g,B=/^\.*\/|^\.+$/,H=`/`,q=`node-ignore`;typeof Symbol<`u`&&(q=Symbol.for(`node-ignore`));let J=q,Y=(e,t,S)=>Object.defineProperty(e,t,{value:S}),ee=/([0-z])-([0-z])/g,te=()=>!1,ne=e=>e.replace(ee,(e,t,S)=>t.charCodeAt(0)<=S.charCodeAt(0)?e:``),ae=e=>{let{length:t}=e;return e.slice(0,t-t%2)},oe=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,S)=>t+(S.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:S}=t;return t.slice(0,S-S%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,S)=>t+6<S.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,S)=>t+S.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,S,w,E)=>t===`\\`?`\\[${S}${ae(w)}${E}`:E===`]`&&w.length%2==0?`[${ne(S)}${w}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],se=Object.create(null),ce=(e,t)=>{let S=se[e];return S||(S=oe.reduce((t,[S,w])=>t.replace(S,w.bind(e)),e),se[e]=S),t?new RegExp(S,`i`):new RegExp(S)},ue=e=>typeof e==`string`,de=e=>e&&ue(e)&&!O.test(e)&&!k.test(e)&&e.indexOf(`#`)!==0,fe=e=>e.split(L);var me=class{constructor(e,t,S,w){this.origin=e,this.pattern=t,this.negative=S,this.regex=w}};let ge=(e,t)=>{let S=e,w=!1;e.indexOf(`!`)===0&&(w=!0,e=e.substr(1)),e=e.replace(j,`!`).replace(F,`#`);let E=ce(e,t);return new me(S,e,w,E)},_e=(e,t)=>{throw new t(e)},ve=(e,t,S)=>ue(e)?e?ve.isNotRelative(e)?S(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:S(`path must not be empty`,TypeError):S(`path must be a string, but got \`${t}\``,TypeError),ye=e=>B.test(e);ve.isNotRelative=ye,ve.convert=e=>e;var Ce=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:S=!1}={}){Y(this,J,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=S,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[J]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(de(e)){let t=ge(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,S(ue(e)?fe(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let S=!1,w=!1;return this._rules.forEach(E=>{let{negative:D}=E;w===D&&S!==w||D&&!S&&!w&&!t||E.regex.test(e)&&(S=!D,w=D)}),{ignored:S,unignored:w}}_test(e,t,S,w){let E=e&&ve.convert(e);return ve(E,e,this._allowRelativePaths?te:_e),this._t(E,t,S,w)}_t(e,t,S,w){if(e in t)return t[e];if(w||=e.split(`/`),w.pop(),!w.length)return t[e]=this._testOne(e,S);let E=this._t(w.join(`/`)+`/`,t,S,w);return t[e]=E.ignored?E:this._testOne(e,S)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return S(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let we=e=>new Ce(e);if(we.isPathValid=e=>ve(e&&ve.convert(e),e,te),we.default=we,t.exports=we,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){ve.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;ve.isNotRelative=t=>e.test(t)||ye(t)}}));init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1),import_src=require_src$14(),import_src$1=require_src$13(),import_src$2=require_src$4(),import_src$3=require_src$3(),import_src$4=require_src$2(),import_src$5=require_src$1(),import_src$6=require_src();init_esm$1();var import_lib=__toESM$1(require_lib(),1),import_yazl=__toESM$1(require_yazl(),1),import_shell_quote=__toESM$1(require_shell_quote(),1),import_ignore=__toESM$1(require_ignore(),1);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let S;return S=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,S),S}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(S=>({...S,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:S,...w}=t;return w})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let S=t.getLocalState()??{},w=e(S.agentFocus??{});t.setLocalState({...S,agentFocus:w})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let S=0;this.mutateAgentPresence(w=>{let E=Date.now(),D={};for(let[t,O]of Object.entries(w)){if(E-O.ts>=2e4&&t!==e){S++;continue}D[t]=O}return D[e]=t,D})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),S>0&&this.log.info({evictedCount:S,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(S=>{if(!S[e])return S;t=!0;let{[e]:w,...E}=S;return E})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let S=[],w=!1,E=this.mutateAgentPresence(E=>{let D=E[e];if(!D)return E;w=!0;let O=Date.now();return S.push({currentDoc:D.currentDoc,ts:O}),{...E,[e]:{...D,mode:t,ts:O}}}),D=S[0];E&&D?this.log.debug({agentId:e,action:`touchMode`,currentDoc:D.currentDoc,ts:D.ts,mode:t},`[agent-presence] touchMode`):w||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;let E=Date.now();return t=E,{...S,[e]:{...w,ts:E}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let S=t.getLocalState()??{},w=e(S.agentPresence??{});return t.setLocalState({...S,agentPresence:w}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics$1.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$4.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let S=new import_src$6.BasicTracerProvider({resource:e,spanProcessors:[new import_src$6.BatchSpanProcessor(new import_src$3.OTLPTraceExporter)]});trace.setGlobalTracerProvider(S),propagation.setGlobalPropagator(new import_src$1.W3CTraceContextPropagator);let w=new import_src$5.MeterProvider({resource:e,readers:[new import_src$5.PeriodicExportingMetricReader({exporter:new import_src$2.OTLPMetricExporter})]});metrics$1.setGlobalMeterProvider(w),tracerProvider=S,meterProvider=w,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics$1.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics$1.getMeter(TRACER_NAME)}async function withSpan(e,t,S){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await S(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,S){return getTracer().startActiveSpan(e,t??{},e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,S,w){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:S,"body.bytes":t.length,"doc.name":e.guid}},()=>{let S=e.getXmlFragment(`default`),E=e.getText(`source`),D=E.toString(),{body:O}=stripFrontmatter(t),k=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":O.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(O,buildParseOpts(w))),j=schema.nodeFromJSON(k);D!==t&&applyFastDiff(E,D,t),updateYFragment(e,S,j,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,S){let w=e.getXmlFragment(`default`),E=e.getText(`source`),{body:D}=stripFrontmatter(t),O=mdManager.parseWithFallback(D,buildParseOpts(S)),k=schema.nodeFromJSON(O),j=E.toString();j!==t&&(E.delete(0,j.length),E.insert(0,t)),updateYFragment(e,w,k,{mapping:new Map,isOMark:new Map})}function deriveFragmentFromYtext(e,t){let S=e.getXmlFragment(`default`),{body:w}=stripFrontmatter(e.getText(`source`).toString()),E=mdManager.parseWithFallback(w,buildParseOpts(t));updateYFragment(e,S,schema.nodeFromJSON(E),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(e)??0)+1;this.seqs.set(e,S);let w=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:S});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(e,S),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let w=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});S.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,S);let w=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:S,branch:e});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,S)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,w);let E=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:w,docName:e,sv:Buffer.from(t).toString(`base64`)});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,S]of this.latestDiskAckSVs)e[t]=Buffer.from(S).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w);let E=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:w,docName:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w);let E=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:w,path:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let S=extname(e).slice(1).toLowerCase();return S.length>0&&t.has(S)}function stripDocExtension(e){let t=e.toLowerCase();for(let S of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(S))return e.slice(0,-S.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let S=canonicalize(t);if(!S)throw Error(`registerDocExtension: unsupported extension "${t}"`);let w=docExtensionByName.get(e);if(!w)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let E=canonicalize(w);return E?E===S?{effective:w,changed:!1,shadowed:null}:rank(S)<rank(E)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w}):{effective:w,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$9=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,S,w,E={}){let D=E.instance??`urn:uuid:${randomUUID()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$9().error({event:`api.error.double-write`,instance:D,type:S,status:t,handler:E.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}});return}let O={type:S,title:w,status:t,instance:D,detail:E.detail??void 0},k=ProblemDetailsSchema.safeParse(O);if(!k.success){log$9().error({event:`api.error.malformed-envelope`,issues:k.error.issues,body:O,handler:E.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let S=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:D}));return}let j=E.extensions?{...E.extensions,...O}:O;apiErrorCounter().add(1,{type:S,...E.handler?{handler:E.handler}:{}});let F=t>=500?`error`:`warn`;log$9()[F]({event:`api.error`,instance:D,type:S,status:t,handler:E.handler,detail:E.detail,err:E.cause},w);let L;try{L=JSON.stringify(j)}catch(S){log$9().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(j),handler:E.handler,originalStatus:t,instance:D,err:S},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:D}));return}e.writeHead(t,{...E.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(L)}function streamingProblemEvent(e,t,S,w={}){let E=w.instance??`urn:uuid:${randomUUID()}`,D={type:`error`,problem:{type:t,title:S,status:e,instance:E,detail:w.detail??void 0}},O=StreamingProblemEventSchema.safeParse(D);if(!O.success){log$9().error({event:`api.streaming.malformed-envelope`,issues:O.error.issues,body:D,handler:w.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...w.handler?{handler:w.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:E}}}apiErrorCounter().add(1,{type:t,...w.handler?{handler:w.handler}:{}});let k=e>=500?`error`:`warn`;return log$9()[k]({event:`api.streaming.error`,instance:E,type:t,status:e,handler:w.handler,detail:w.detail,err:w.cause},S),D}function createStreamingErrorWriter(e,t){return(S,w,E,D={})=>{if(e.writableEnded||e.destroyed){log$9().error({event:`api.streaming.error.suppressed`,type:w,status:S,handler:t,detail:D.detail,err:D.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let O=streamingProblemEvent(S,w,E,{handler:t,...D});try{e.write(`${JSON.stringify(O)}\n`)}catch(e){log$9().error({event:`api.streaming.error.write-failed`,type:w,status:S,handler:t,err:D.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,S){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:S,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:S,detail:`The document is in a merge-conflict state. Call get_conflict_content + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const FIX_HINT='Frontmatter must be a flat mapping where each value is a string, number, boolean, or array of scalars. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function respondFrontmatterMalformed(e,t,S){console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:S,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:S,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$8=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,S,w){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":S,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,S,w))}function applyAgentMarkdownWriteInner(e,t,S,w){try{let{frontmatter:E,body:D}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:O,body:k}=stripFrontmatter(t),j,F;switch(S){case`replace`:j=O||E,F=k;break;case`prepend`:j=E,F=D.length>0?`${k}\n\n${D}`:k;break;case`append`:j=E,F=D.length>0?`${D}\n\n${k}`:k;break}if(j!==E){let t=parseFrontmatterYaml(unwrapFrontmatterFences(j));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}composeAndWriteRawBody(e,prependFrontmatter(j,F),`agent`,w)}catch(w){throw w instanceof FrontmatterMalformedError||log$8.error({err:w,docName:e.name,position:S,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),w}}function applyAgentUndo(e,t,S){let w=e.dc.document;if(isDocInConflict(w))throw new DocInConflictError({file:docNameToFile(w.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let w=applyAgentUndoInner(e,t,S);return setActiveSpanAttributes({"agent.undo_effective":w}),w})}function applyAgentUndoInner(e,t,S){let{dc:w,um:E,undoOrigin:D}=e,O=w.document,k=!1;return O.transact(()=>{if(t===`last`){if(E.undoStack.length===0)return;E.undo(),k=!0}else for(;E.undoStack.length>0;)E.undo(),k=!0;deriveFragmentFromYtext(O,S)},D),k}function createSessionOrigin(e,t,S,w,E){let D={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(D.agent_type=t),S!==void 0&&(D.principal=S),w!==void 0&&(D.display_name=w),E!==void 0&&(D.color_seed=E),Object.freeze(D);let O={source:`local`,skipStoreHooks:!1,context:D};return Object.freeze(O),O}function createUndoOrigin(e,t){let S={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(S.agent_type=t),Object.freeze(S);let w={source:`local`,skipStoreHooks:!1,context:S};return Object.freeze(w),w}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,S]of this.sessions)e.endsWith(t)&&(yield S)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,S){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let w=this.sessionKey(e,t),E=this.sessions.get(w);if(E)return E;let D=this.pendingSessions.get(w);if(D)return D;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let O=this._createSession(e,t,S);this.pendingSessions.set(w,O);try{let e=await O;return this.sessions.set(w,e),e}finally{this.pendingSessions.delete(w)}}async _createSession(e,t,S){let w=S?.clientName,E=t.startsWith(`agent-`)?t.slice(6):t,D=createSessionOrigin(E,w,S?.principalId,S?.displayName,S?.colorSeed),O=createUndoOrigin(E,w),k={session_id:E,...w===void 0?{}:{agent_type:w},...S?.clientName===void 0?{}:{client_name:S.clientName},...S?.principalId===void 0?{}:{principalId:S.principalId}},j=await this.hocuspocus.openDirectConnection(e,k),F=new UndoManager([j.document.getText(`source`),j.document.getMap(`agent-flash`)],{trackedOrigins:new Set([D]),captureTimeout:500,captureTransaction:e=>e.origin!==O,ignoreRemoteMapChanges:!0}),L=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return F.on(`stack-item-added`,L),F.on(`stack-item-updated`,L),log$8.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:j,origin:D,undoOrigin:O,um:F,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,S){try{try{t.um.destroy()}catch(e){log$8.error({err:e,...S},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$8.error({err:e,...S},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let S=this.sessionKey(e,t),w=this.sessions.get(S);w&&(await this.cleanupSession(S,w,{docName:e,agentId:t}),log$8.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,S=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));S.length>0&&await Promise.allSettled(S.map(e=>this.pendingSessions.get(e)));let w=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of w){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,S=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of S){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,S,w){let E=e.doc;if(!E)return;let D=++_effectCounter,O=E.getMap(`agent-effects`),k=F=>{e.unobserve(k),E.off(`destroy`,j);let L=`${t}:${D}`,B={sessionId:t,timestamp:Date.now(),delta:F.delta,agent_type:w??`agent`,color_seed:S??t};try{E.transact(()=>{if(O.set(L,B),O.size>RING_BUFFER_LIMIT){let e=[...O.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,O.size-RING_BUFFER_LIMIT))O.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let S=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:S})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},j=()=>{e.unobserve(k)};e.observe(k),E.once(`destroy`,j)}function collectItemsInDeleteSet(e,t,S){iterateDeletedStructs(e,t,e=>{e instanceof Item&&S.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let S=[],w=[],E=t.doc,D=new Set,O=new Set;E&&E.transact(t=>{collectItemsInDeleteSet(t,e.insertions,D),collectItemsInDeleteSet(t,e.deletions,O)});let k=``,j=``,F=0,L=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,E=t.length,B=D.has(e),H=O.has(e);e.deleted?H&&(w.push({position:F,content:t,length:E}),k+=t,F+=E):(j+=t,B?S.push({position:L,content:t,length:E}):(k+=t,F+=E),L+=E)}return{insertions:S,deletions:w,before:k,after:j}}function synthesizeStackItemDiffText(e,t,S){let{before:w,after:E}=synthesizeStackItemDiff(e,t);return w===E?``:createPatch(S,w,E,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=0,O=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&w.has(e)&&(D+=t),E.has(e)&&(O+=t)}return{additions:D,deletions:O}}function listAgentActivity(e,t){let S=[],w=null,E=!1;for(let D of e.sessionsForConnection(t)){if(E=!0,!w){let e=D.origin.context,S=typeof e?.agent_type==`string`?e.agent_type:void 0,E=typeof e?.color_seed==`string`?e.color_seed:t,O=iconFromClientName(S),k=AGENT_ICON_COLORS[O]??colorFromSeed(E);w={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:k,icon:O,connectionId:t}}let e=D.docName,O=D.um,k=D.dc.document.getText(`source`),j=[];for(let e=0;e<O.undoStack.length;e++){let t=O.undoStack[e],S=getBurstTs(t),{additions:w,deletions:E}=countStackItemChanges(t,k);j.push({stackIndex:e,ts:S,additions:w,deletions:E})}if(j.length===0)continue;j.sort((e,t)=>t.stackIndex-e.stackIndex);let F=j.reduce((e,t)=>e+t.additions,0),L=j.reduce((e,t)=>e+t.deletions,0),B=Math.max(...j.map(e=>e.ts));S.push({docName:e,additionsTotal:F,deletionsTotal:L,lastTs:B,bursts:j})}return E?(S.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:w,files:S}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let S=getCounters(e);S.lastUserTxGen=++globalCounter,S.lastUserTxAtMs=Date.now()},S=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,S),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,S)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let S=counters.get(e);return S?S.settledGen>S.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let S=counters.get(e);return!S||S.lastUserTxAtMs===null?null:Math.max(0,t-S.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,S=Date.now()){let w=rateKey(e,t),E=lastEmitMs.get(w),D=readDebounceMs();if(E!==void 0&&S-E<D)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)S-t>=D&&lastEmitMs.delete(e);return lastEmitMs.set(w,S),!0}function shouldEmitBridgeToleranceApplied(e,t,S=Date.now()){let w=toleranceRateKey(e,t),E=lastToleranceEmitMs.get(w),D=readDebounceMs();return E!==void 0&&S-E<D?!1:(lastToleranceEmitMs.set(w,S),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let S=e??`__nodoc__`,w=lastPathBEmitMs.get(S),E=readDebounceMs();if(w!==void 0&&t-w<E)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,S]of lastPathBEmitMs)t-S>=E&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(S,t),!0}function emitObserverAPathBFired(e,t){let S=shouldEmitObserverAPathBFired(e,t);return S||incrementObserverAPathBFiresSuppressed(),S}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,S){let w=normalizeBridge(e),E=normalizeBridge(t);if(w===E){if(e!==t){let w=detectAppliedToleranceClasses(e,t);for(let e of w)shouldEmitBridgeToleranceApplied(S.site,e,S.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:S.site,class:e})))}return!0}let D={site:S.site,origin:S.origin,docName:S.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${w.slice(0,300)}\n frag: ${E.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!S.suppressDevThrow)throw new BridgeInvariantViolationError(D);if(!shouldEmitBridgeInvariantViolation(S.site,S.docName,S.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let O=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(D,{verbose:O}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,S){let w={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return S&&Object.assign(w,S),w}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,S){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,S)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,S){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,S)})}function tracedAppendFileSync(e,t,S){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,S)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,S){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,S)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
1195
|
+
`+S)}function se(e,t,S,w,E,D){if(e.listenerCount(`wsClientError`)){let w=Error(E);Error.captureStackTrace(w,se),e.emit(`wsClientError`,w,S,t)}else oe(S,w,E,D)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM(require_websocket_server(),1),require_ignore=__commonJSMin$1(((e,t)=>{function S(e){return Array.isArray(e)?e:[e]}let w=``,E=` `,D=`\\`,O=/^\s+$/,k=/(?:[^\\]|^)\\$/,j=/^\\!/,F=/^\\#/,L=/\r?\n/g,B=/^\.*\/|^\.+$/,H=`/`,q=`node-ignore`;typeof Symbol<`u`&&(q=Symbol.for(`node-ignore`));let J=q,Y=(e,t,S)=>Object.defineProperty(e,t,{value:S}),ee=/([0-z])-([0-z])/g,te=()=>!1,ne=e=>e.replace(ee,(e,t,S)=>t.charCodeAt(0)<=S.charCodeAt(0)?e:``),ae=e=>{let{length:t}=e;return e.slice(0,t-t%2)},oe=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,S)=>t+(S.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:S}=t;return t.slice(0,S-S%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,S)=>t+6<S.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,S)=>t+S.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,S,w,E)=>t===`\\`?`\\[${S}${ae(w)}${E}`:E===`]`&&w.length%2==0?`[${ne(S)}${w}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],se=Object.create(null),ce=(e,t)=>{let S=se[e];return S||(S=oe.reduce((t,[S,w])=>t.replace(S,w.bind(e)),e),se[e]=S),t?new RegExp(S,`i`):new RegExp(S)},ue=e=>typeof e==`string`,de=e=>e&&ue(e)&&!O.test(e)&&!k.test(e)&&e.indexOf(`#`)!==0,fe=e=>e.split(L);var me=class{constructor(e,t,S,w){this.origin=e,this.pattern=t,this.negative=S,this.regex=w}};let ge=(e,t)=>{let S=e,w=!1;e.indexOf(`!`)===0&&(w=!0,e=e.substr(1)),e=e.replace(j,`!`).replace(F,`#`);let E=ce(e,t);return new me(S,e,w,E)},_e=(e,t)=>{throw new t(e)},ve=(e,t,S)=>ue(e)?e?ve.isNotRelative(e)?S(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:S(`path must not be empty`,TypeError):S(`path must be a string, but got \`${t}\``,TypeError),ye=e=>B.test(e);ve.isNotRelative=ye,ve.convert=e=>e;var Ce=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:S=!1}={}){Y(this,J,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=S,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[J]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(de(e)){let t=ge(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,S(ue(e)?fe(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let S=!1,w=!1;return this._rules.forEach(E=>{let{negative:D}=E;w===D&&S!==w||D&&!S&&!w&&!t||E.regex.test(e)&&(S=!D,w=D)}),{ignored:S,unignored:w}}_test(e,t,S,w){let E=e&&ve.convert(e);return ve(E,e,this._allowRelativePaths?te:_e),this._t(E,t,S,w)}_t(e,t,S,w){if(e in t)return t[e];if(w||=e.split(`/`),w.pop(),!w.length)return t[e]=this._testOne(e,S);let E=this._t(w.join(`/`)+`/`,t,S,w);return t[e]=E.ignored?E:this._testOne(e,S)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return S(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let we=e=>new Ce(e);if(we.isPathValid=e=>ve(e&&ve.convert(e),e,te),we.default=we,t.exports=we,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){ve.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;ve.isNotRelative=t=>e.test(t)||ye(t)}}));init_esm$2();var import_pino_pretty=__toESM$1(require_pino_pretty(),1),import_src=require_src$14(),import_src$1=require_src$13(),import_src$2=require_src$4(),import_src$3=require_src$3(),import_src$4=require_src$2(),import_src$5=require_src$1(),import_src$6=require_src();init_esm$1();var import_lib=__toESM$1(require_lib(),1),import_shell_quote=__toESM$1(require_shell_quote(),1),import_ignore=__toESM$1(require_ignore(),1);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var PinoLogger=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:pino.stdSerializers.err,error:pino.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return pino(this.options,pino.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return pino(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),pino(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let S;return S=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,S),S}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(S=>({...S,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:S,...w}=t;return w})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let S=t.getLocalState()??{},w=e(S.agentFocus??{});t.setLocalState({...S,agentFocus:w})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let S=0;this.mutateAgentPresence(w=>{let E=Date.now(),D={};for(let[t,O]of Object.entries(w)){if(E-O.ts>=2e4&&t!==e){S++;continue}D[t]=O}return D[e]=t,D})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),S>0&&this.log.info({evictedCount:S,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(S=>{if(!S[e])return S;t=!0;let{[e]:w,...E}=S;return E})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let S=[],w=!1,E=this.mutateAgentPresence(E=>{let D=E[e];if(!D)return E;w=!0;let O=Date.now();return S.push({currentDoc:D.currentDoc,ts:O}),{...E,[e]:{...D,mode:t,ts:O}}}),D=S[0];E&&D?this.log.debug({agentId:e,action:`touchMode`,currentDoc:D.currentDoc,ts:D.ts,mode:t},`[agent-presence] touchMode`):w||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;let E=Date.now();return t=E,{...S,[e]:{...w,ts:E}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let S=t.getLocalState()??{},w=e(S.agentPresence??{});return t.setLocalState({...S,agentPresence:w}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics$1.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$4.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let S=new import_src$6.BasicTracerProvider({resource:e,spanProcessors:[new import_src$6.BatchSpanProcessor(new import_src$3.OTLPTraceExporter)]});trace.setGlobalTracerProvider(S),propagation.setGlobalPropagator(new import_src$1.W3CTraceContextPropagator);let w=new import_src$5.MeterProvider({resource:e,readers:[new import_src$5.PeriodicExportingMetricReader({exporter:new import_src$2.OTLPMetricExporter})]});metrics$1.setGlobalMeterProvider(w),tracerProvider=S,meterProvider=w,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,trace.disable(),metrics$1.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics$1.getMeter(TRACER_NAME)}async function withSpan(e,t,S){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await S(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,S){return getTracer().startActiveSpan(e,t??{},e=>{try{return S(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,S,w){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:S,"body.bytes":t.length,"doc.name":e.guid}},()=>{let S=e.getXmlFragment(`default`),E=e.getText(`source`),D=E.toString(),{body:O}=stripFrontmatter(t),k=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":O.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(O,buildParseOpts(w))),j=schema.nodeFromJSON(k);D!==t&&applyFastDiff(E,D,t),updateYFragment(e,S,j,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,S){let w=e.getXmlFragment(`default`),E=e.getText(`source`),{body:D}=stripFrontmatter(t),O=mdManager.parseWithFallback(D,buildParseOpts(S)),k=schema.nodeFromJSON(O),j=E.toString();j!==t&&(E.delete(0,j.length),E.insert(0,t)),updateYFragment(e,w,k,{mapping:new Map,isOMark:new Map})}function deriveFragmentFromYtext(e,t){let S=e.getXmlFragment(`default`),{body:w}=stripFrontmatter(e.getText(`source`).toString()),E=mdManager.parseWithFallback(w,buildParseOpts(t));updateYFragment(e,S,schema.nodeFromJSON(E),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(e)??0)+1;this.seqs.set(e,S);let w=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:S});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(e,S),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let w=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});S.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let S=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,S);let w=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:S,branch:e});t.broadcastStateless(JSON.stringify(w)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,S)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,w);let E=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:w,docName:e,sv:Buffer.from(t).toString(`base64`)});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,S]of this.latestDiskAckSVs)e[t]=Buffer.from(S).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w);let E=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:w,docName:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let S=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!S){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let w=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w);let E=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:w,path:e,error:t});S.broadcastStateless(JSON.stringify(E)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,w)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let S=extname(e).slice(1).toLowerCase();return S.length>0&&t.has(S)}function stripDocExtension(e){let t=e.toLowerCase();for(let S of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(S))return e.slice(0,-S.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let S=canonicalize(t);if(!S)throw Error(`registerDocExtension: unsupported extension "${t}"`);let w=docExtensionByName.get(e);if(!w)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let E=canonicalize(w);return E?E===S?{effective:w,changed:!1,shadowed:null}:rank(S)<rank(E)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w}):{effective:w,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:w})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$9=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,S,w,E={}){let D=E.instance??`urn:uuid:${randomUUID()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$9().error({event:`api.error.double-write`,instance:D,type:S,status:t,handler:E.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}});return}let O={type:S,title:w,status:t,instance:D,detail:E.detail??void 0},k=ProblemDetailsSchema.safeParse(O);if(!k.success){log$9().error({event:`api.error.malformed-envelope`,issues:k.error.issues,body:O,handler:E.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let S=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:D}));return}let j=E.extensions?{...E.extensions,...O}:O;apiErrorCounter().add(1,{type:S,...E.handler?{handler:E.handler}:{}});let F=t>=500?`error`:`warn`;log$9()[F]({event:`api.error`,instance:D,type:S,status:t,handler:E.handler,detail:E.detail,err:E.cause},w);let L;try{L=JSON.stringify(j)}catch(S){log$9().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(j),handler:E.handler,originalStatus:t,instance:D,err:S},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:D}));return}e.writeHead(t,{...E.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(L)}function streamingProblemEvent(e,t,S,w={}){let E=w.instance??`urn:uuid:${randomUUID()}`,D={type:`error`,problem:{type:t,title:S,status:e,instance:E,detail:w.detail??void 0}},O=StreamingProblemEventSchema.safeParse(D);if(!O.success){log$9().error({event:`api.streaming.malformed-envelope`,issues:O.error.issues,body:D,handler:w.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...w.handler?{handler:w.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:E}}}apiErrorCounter().add(1,{type:t,...w.handler?{handler:w.handler}:{}});let k=e>=500?`error`:`warn`;return log$9()[k]({event:`api.streaming.error`,instance:E,type:t,status:e,handler:w.handler,detail:w.detail,err:w.cause},S),D}function createStreamingErrorWriter(e,t){return(S,w,E,D={})=>{if(e.writableEnded||e.destroyed){log$9().error({event:`api.streaming.error.suppressed`,type:w,status:S,handler:t,detail:D.detail,err:D.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let O=streamingProblemEvent(S,w,E,{handler:t,...D});try{e.write(`${JSON.stringify(O)}\n`)}catch(e){log$9().error({event:`api.streaming.error.write-failed`,type:w,status:S,handler:t,err:D.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,S){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:S,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:S,detail:`The document is in a merge-conflict state. Call get_conflict_content + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const FIX_HINT='Frontmatter must be a flat mapping where each value is a string, number, boolean, or array of scalars. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function respondFrontmatterMalformed(e,t,S){console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:S,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:S,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$8=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,S,w){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":S,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,S,w))}function applyAgentMarkdownWriteInner(e,t,S,w){try{let{frontmatter:E,body:D}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:O,body:k}=stripFrontmatter(t),j,F;switch(S){case`replace`:j=O||E,F=k;break;case`prepend`:j=E,F=D.length>0?`${k}\n\n${D}`:k;break;case`append`:j=E,F=D.length>0?`${D}\n\n${k}`:k;break}if(j!==E){let t=parseFrontmatterYaml(unwrapFrontmatterFences(j));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}composeAndWriteRawBody(e,prependFrontmatter(j,F),`agent`,w)}catch(w){throw w instanceof FrontmatterMalformedError||log$8.error({err:w,docName:e.name,position:S,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),w}}function applyAgentUndo(e,t,S){let w=e.dc.document;if(isDocInConflict(w))throw new DocInConflictError({file:docNameToFile(w.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let w=applyAgentUndoInner(e,t,S);return setActiveSpanAttributes({"agent.undo_effective":w}),w})}function applyAgentUndoInner(e,t,S){let{dc:w,um:E,undoOrigin:D}=e,O=w.document,k=!1;return O.transact(()=>{if(t===`last`){if(E.undoStack.length===0)return;E.undo(),k=!0}else for(;E.undoStack.length>0;)E.undo(),k=!0;deriveFragmentFromYtext(O,S)},D),k}function createSessionOrigin(e,t,S,w,E){let D={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(D.agent_type=t),S!==void 0&&(D.principal=S),w!==void 0&&(D.display_name=w),E!==void 0&&(D.color_seed=E),Object.freeze(D);let O={source:`local`,skipStoreHooks:!1,context:D};return Object.freeze(O),O}function createUndoOrigin(e,t){let S={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(S.agent_type=t),Object.freeze(S);let w={source:`local`,skipStoreHooks:!1,context:S};return Object.freeze(w),w}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,S]of this.sessions)e.endsWith(t)&&(yield S)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,S){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let w=this.sessionKey(e,t),E=this.sessions.get(w);if(E)return E;let D=this.pendingSessions.get(w);if(D)return D;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let O=this._createSession(e,t,S);this.pendingSessions.set(w,O);try{let e=await O;return this.sessions.set(w,e),e}finally{this.pendingSessions.delete(w)}}async _createSession(e,t,S){let w=S?.clientName,E=t.startsWith(`agent-`)?t.slice(6):t,D=createSessionOrigin(E,w,S?.principalId,S?.displayName,S?.colorSeed),O=createUndoOrigin(E,w),k={session_id:E,...w===void 0?{}:{agent_type:w},...S?.clientName===void 0?{}:{client_name:S.clientName},...S?.principalId===void 0?{}:{principalId:S.principalId}},j=await this.hocuspocus.openDirectConnection(e,k),F=new UndoManager([j.document.getText(`source`),j.document.getMap(`agent-flash`)],{trackedOrigins:new Set([D]),captureTimeout:500,captureTransaction:e=>e.origin!==O,ignoreRemoteMapChanges:!0}),L=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return F.on(`stack-item-added`,L),F.on(`stack-item-updated`,L),log$8.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:j,origin:D,undoOrigin:O,um:F,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,S){try{try{t.um.destroy()}catch(e){log$8.error({err:e,...S},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$8.error({err:e,...S},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let S=this.sessionKey(e,t),w=this.sessions.get(S);w&&(await this.cleanupSession(S,w,{docName:e,agentId:t}),log$8.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,S=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));S.length>0&&await Promise.allSettled(S.map(e=>this.pendingSessions.get(e)));let w=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of w){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,S=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of S){let S=this.sessions.get(t);S&&await this.cleanupSession(t,S,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,S,w){let E=e.doc;if(!E)return;let D=++_effectCounter,O=E.getMap(`agent-effects`),k=F=>{e.unobserve(k),E.off(`destroy`,j);let L=`${t}:${D}`,B={sessionId:t,timestamp:Date.now(),delta:F.delta,agent_type:w??`agent`,color_seed:S??t};try{E.transact(()=>{if(O.set(L,B),O.size>RING_BUFFER_LIMIT){let e=[...O.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,O.size-RING_BUFFER_LIMIT))O.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let S=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:S})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},j=()=>{e.unobserve(k)};e.observe(k),E.once(`destroy`,j)}function collectItemsInDeleteSet(e,t,S){iterateDeletedStructs(e,t,e=>{e instanceof Item&&S.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let S=[],w=[],E=t.doc,D=new Set,O=new Set;E&&E.transact(t=>{collectItemsInDeleteSet(t,e.insertions,D),collectItemsInDeleteSet(t,e.deletions,O)});let k=``,j=``,F=0,L=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,E=t.length,B=D.has(e),H=O.has(e);e.deleted?H&&(w.push({position:F,content:t,length:E}),k+=t,F+=E):(j+=t,B?S.push({position:L,content:t,length:E}):(k+=t,F+=E),L+=E)}return{insertions:S,deletions:w,before:k,after:j}}function synthesizeStackItemDiffText(e,t,S){let{before:w,after:E}=synthesizeStackItemDiff(e,t);return w===E?``:createPatch(S,w,E,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=0,O=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&w.has(e)&&(D+=t),E.has(e)&&(O+=t)}return{additions:D,deletions:O}}function listAgentActivity(e,t){let S=[],w=null,E=!1;for(let D of e.sessionsForConnection(t)){if(E=!0,!w){let e=D.origin.context,S=typeof e?.agent_type==`string`?e.agent_type:void 0,E=typeof e?.color_seed==`string`?e.color_seed:t,O=iconFromClientName(S),k=AGENT_ICON_COLORS[O]??colorFromSeed(E);w={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:k,icon:O,connectionId:t}}let e=D.docName,O=D.um,k=D.dc.document.getText(`source`),j=[];for(let e=0;e<O.undoStack.length;e++){let t=O.undoStack[e],S=getBurstTs(t),{additions:w,deletions:E}=countStackItemChanges(t,k);j.push({stackIndex:e,ts:S,additions:w,deletions:E})}if(j.length===0)continue;j.sort((e,t)=>t.stackIndex-e.stackIndex);let F=j.reduce((e,t)=>e+t.additions,0),L=j.reduce((e,t)=>e+t.deletions,0),B=Math.max(...j.map(e=>e.ts));S.push({docName:e,additionsTotal:F,deletionsTotal:L,lastTs:B,bursts:j})}return E?(S.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:w,files:S}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let S=getCounters(e);S.lastUserTxGen=++globalCounter,S.lastUserTxAtMs=Date.now()},S=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,S),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,S)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let S=counters.get(e);return S?S.settledGen>S.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let S=counters.get(e);return!S||S.lastUserTxAtMs===null?null:Math.max(0,t-S.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,S=Date.now()){let w=rateKey(e,t),E=lastEmitMs.get(w),D=readDebounceMs();if(E!==void 0&&S-E<D)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)S-t>=D&&lastEmitMs.delete(e);return lastEmitMs.set(w,S),!0}function shouldEmitBridgeToleranceApplied(e,t,S=Date.now()){let w=toleranceRateKey(e,t),E=lastToleranceEmitMs.get(w),D=readDebounceMs();return E!==void 0&&S-E<D?!1:(lastToleranceEmitMs.set(w,S),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let S=e??`__nodoc__`,w=lastPathBEmitMs.get(S),E=readDebounceMs();if(w!==void 0&&t-w<E)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,S]of lastPathBEmitMs)t-S>=E&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(S,t),!0}function emitObserverAPathBFired(e,t){let S=shouldEmitObserverAPathBFired(e,t);return S||incrementObserverAPathBFiresSuppressed(),S}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,S){let w=normalizeBridge(e),E=normalizeBridge(t);if(w===E){if(e!==t){let w=detectAppliedToleranceClasses(e,t);for(let e of w)shouldEmitBridgeToleranceApplied(S.site,e,S.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:S.site,class:e})))}return!0}let D={site:S.site,origin:S.origin,docName:S.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${w.slice(0,300)}\n frag: ${E.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!S.suppressDevThrow)throw new BridgeInvariantViolationError(D);if(!shouldEmitBridgeInvariantViolation(S.site,S.docName,S.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let O=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(D,{verbose:O}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,S){let w={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return S&&Object.assign(w,S),w}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,S){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,S)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,S){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,S)})}function tracedAppendFileSync(e,t,S){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,S)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,S){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,S)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
1200
1196
|
`);for(let e=0;e<t.length;e++){let S=t[e]??``;if(S.length!==0&&/^\s+$/.test(S))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function validateConfigContent(e,t){return e===`__config__/okignore`?validateOkignore(t):validateConfigYaml(t)}function defaultLkgFor(e){return e===`__config__/okignore`?``:serializedDefaults()}function validateConfigYaml(e){let t=(0,import_dist$1.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let S=t.toJSON()??{},w=ConfigSchema$1.safeParse(S);return w.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:w.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function loadConfigDoc(e,t,S){let w=e.getText(`source`);if(w.length>0)return;let E=configDocAbsPath(t,S),D=``;if(existsSync(E))try{D=readFileSync(E,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[config] Could not read ${E}: ${t}. Seeding with empty content.`),D=``}let O=validateConfigContent(t,D);!O.ok&&D.length>0&&getLogger(`config-persistence`).warn({docName:t,path:E},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{D.length>0&&w.insert(0,D)},CONFIG_VALIDATION_REVERT_ORIGIN),O.ok&&D.length>0?S.lkgCache.set(t,D):S.lkgCache.set(t,defaultLkgFor(t))}async function atomicWriteConfig(e,t){await tracedMkdir(dirname(e),{recursive:!0});let S=`${e}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(S,t,`utf-8`),await tracedRename(S,e)}catch(e){try{tracedUnlinkSync(S)}catch{}throw e}}async function storeConfigDoc(e,t,S,w){return withConfigSpan(`config.persist`,{"config.scope":configScopeAttr(t),"config.transport":`fs`},async E=>{let D=await storeConfigDocInner(e,t,S,w);return E.setAttribute(`config.outcome`,persistOutcomeAttr(D)),D})}function persistOutcomeAttr(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function storeConfigDocInner(e,t,S,w){if(S===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let E=e.getText(`source`),D=E.toString(),O=w.lkgCache.get(t);if(D.length===0&&(t!==`__config__/okignore`||O===void 0||O===``)||O!==void 0&&D===O)return`no-op`;let k=configScopeAttr(t),j=withConfigSpanSync(`config.validate`,{"config.scope":k,"config.validation.layer":`L3`},e=>{let S=validateConfigContent(t,D);return e.setAttribute(`config.outcome`,S.ok?`success`:`rejected`),S.ok||emitSchemaInvalidIssueEvents(S.error),S});if(!j.ok)return await withConfigSpan(`config.revert`,{"config.scope":k,"config.outcome":`reverted`},async()=>{let S=O??defaultLkgFor(t);e.transact(()=>{E.length>0&&E.delete(0,E.length),E.insert(0,S)},CONFIG_VALIDATION_REVERT_ORIGIN),O===void 0&&w.lkgCache.set(t,S),t===`__config__/okignore`&&isKnownConfigError(j.error)&&okignoreRejectionCounter().add(1,{"error.code":j.error.code}),w.onConfigRejected?.(t,j.error)}),`reverted`;let F=configDocAbsPath(t,w);try{await tracedMkdir(dirname(F),{recursive:!0})}catch(e){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] could not create parent dir for ${F}: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${F}: ${S}`}),`write-failed`}try{return await withFileLock(`${F}.lock`,async()=>{let S=null;try{S=readFileSync(F,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] could not read config for reconciliation: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${F}: ${S}`}),`write-failed`}}if(S!==null&&O!==void 0&&S!==O){if(validateConfigContent(t,S).ok)return e.transact(()=>{E.length>0&&E.delete(0,E.length),E.insert(0,S)},CONFIG_FILE_WATCHER_ORIGIN),w.lkgCache.set(t,S),getLogger(`config-persistence`).info({docName:t,path:F},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:F},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(F,D)}catch(e){let S=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] write-failed at ${F}: ${S}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${F}: ${S}`}),`write-failed`}return w.lkgCache.set(t,D),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:F,err:e},`[config-persistence] lock timeout at ${F}: ${e.message}`),w.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,S,w){if(!e)return`no-op`;let E=w.lkgCache.get(t);if(E!==void 0&&E===S)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let w=validateConfigContent(t,S);return e.setAttribute(`config.outcome`,w.ok?`success`:`rejected`),w.ok||emitSchemaInvalidIssueEvents(w.error),w});if(!O.ok)return t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),w.onConfigRejected?.(t,O.error),`rejected`;let k=e.getText(`source`);return e.transact(()=>{k.length>0&&k.delete(0,k.length),k.insert(0,S)},CONFIG_FILE_WATCHER_ORIGIN),w.lkgCache.set(t,S),`applied`}let pendingContributors=new Map;function recordContributor(e,t,S,w,E,D,O,k){let j=pendingContributors.get(t);if(j||(j={writerId:t,displayName:S,colorSeed:w??S,docs:new Set,subjectOverride:E,actor:D,summaries:[],previousPaths:[]},pendingContributors.set(t,j)),j.docs.add(e),E!==void 0&&(j.subjectOverride=E),D!==void 0){let e=j.actor??{};D.principalId!==void 0&&(e.principalId=D.principalId),D.agentType!==void 0&&(e.agentType=D.agentType),D.clientName!==void 0&&(e.clientName=D.clientName),D.clientVersion!==void 0&&(e.clientVersion=D.clientVersion),D.label!==void 0&&(e.label=D.label),j.actor=e}if(typeof O==`string`&&O.length>0&&j.summaries.push(O),k&&k.length>0)for(let e of k)j.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,S]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:S.displayName,colorSeed:S.colorSeed,docs:new Set,actor:S.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of S.docs)e.docs.add(t);S.summaries.length>0&&(e.summaries=[...S.summaries,...e.summaries]),S.previousPaths.length>0&&(e.previousPaths=[...S.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let S of e.values()){let e={v:1,id:S.writerId,name:S.displayName,colorSeed:S.colorSeed,docs:[...S.docs]};S.summaries.length>0&&(e.summaries=[...S.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
1201
1197
|
`)}function formatContributors(){return formatContributorsFrom(pendingContributors)}function restoreContributorEntry(e,t){let S=pendingContributors.get(e);S||(S={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},pendingContributors.set(e,S));for(let e of t.docs)S.docs.add(e);t.summaries.length>0&&(S.summaries=[...t.summaries,...S.summaries]),t.previousPaths.length>0&&(S.previousPaths=[...t.previousPaths,...S.previousPaths])}function clearContributors(){pendingContributors.clear()}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}function acquireLock(e,t){let S=resolve(e,`lock`);if(existsSync(S)){let t=null;try{t=JSON.parse(readFileSync(S,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${S} — replacing`)}if(t&&!isValidLockPid(t.pid)&&(console.warn(`[shadow-lock] Invalid lock pid (${String(t.pid)}) at ${S} — replacing`),t=null),t){let S=t.hostname===hostname();if(!(S&&t.pid===process.pid)){if(S&&isProcessAlive(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let w={pid:process.pid,hostname:hostname(),startedAt:new Date().toISOString(),worktreeRoot:t};return writeFileSync(S,JSON.stringify(w,null,2),`utf-8`),S}function releaseLock(e){let t=resolve(e,`lock`);try{unlinkSync(t)}catch{}}const GIT_TIMEOUT_MS$3=(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})();function shadowGit(e){return esm_default({baseDir:e.workTree,timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function initShadowRepo(e){let t=resolveShadowDir(e),S=resolve(e,`.git/openknowledge`),w=existsSync(S),E=existsSync(t);if(w&&!E?tracedRenameSync(S,t):w&&E&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!existsSync(resolve(t,`HEAD`))){tracedMkdirSync(t,{recursive:!0}),await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$3}}).raw(`init`,`--bare`,t);let S=esm_default({timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:t});await S.raw(`config`,`--unset`,`core.bare`),await S.raw(`config`,`core.worktree`,e),await S.raw(`config`,`user.name`,`openknowledge`),await S.raw(`config`,`user.email`,`noreply@openknowledge.local`)}let D={gitDir:t,workTree:e};return await sweepLegacyShadowRefs(D),sweepOrphanedTmpIndexFiles(D),acquireLock(t,e),D}function destroyShadowRepo(e){releaseLock(e.gitDir)}async function sweepLegacyShadowRefs(e){let t=shadowGit(e),S;try{S=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
|
|
1202
1198
|
`).filter(e=>e.length>0)}catch{return 0}let w=[],E={server:0,"human-":0,upstream:0};for(let e of S){let t=e.split(`/`);if(t.length<4)continue;let S=t.slice(3).join(`/`);parseWriterId(S).classification===`unknown`&&(S===`server`?(w.push(e),E.server++):S.startsWith(`human-`)?(w.push(e),E[`human-`]++):S===`upstream`&&(w.push(e),E.upstream++))}if(w.length===0)return 0;for(let e of w)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let D=w.length;return incrementShadowMigrationLegacyRefsDeleted(D),console.warn(`[shadow-migration] deleted ${D} legacy refs: server=${E.server} human-=${E[`human-`]} upstream=${E.upstream}`),D}async function commitWip(e,t,S,w,E=`main`){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":E}},async()=>commitWipInner(e,t,S,w,E))}async function commitWipInner(e,t,S,w,E=`main`){let D=resolve(e.gitDir,`index-wip-${t.id}`),O=`refs/wip/${E}/${t.id}`,k=shadowGit(e),j=S||`.`;try{try{let t=(await k.raw(`rev-parse`,`${O}^{tree}`)).trim();await k.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:D}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${O}:`,e),e}await k.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:D}).raw(`add`,j);let S=(await k.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:D}).raw(`write-tree`)).trim(),E=null;try{E=(await k.raw(`rev-parse`,O)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${O}:`,e),e}let F=[`commit-tree`,S,`-m`,w];E&&F.push(`-p`,E);let L=(await k.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await k.raw(`update-ref`,O,L),L}finally{try{rmSync(D)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let S of readdirSync(e.gitDir))if(S.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,S)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let S=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),w=shadowGit(e),E=t||`.`;try{return await w.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:S}).raw(`add`,E),(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:S}).raw(`write-tree`)).trim()}finally{try{rmSync(S)}catch{}}}async function commitWipFromTree(e,t,S,w,E=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":E,"shadow.tree":S.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,S,w,E))}async function commitWipFromTreeInner(e,t,S,w,E=`main`){let D=`refs/wip/${E}/${t.id}`,O=shadowGit(e),k=null;try{k=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,S,`-m`,w];k&&j.push(`-p`,k);let F=(await O.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...j)).trim();return await O.raw(`update-ref`,D,F),F}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,S,w,E=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":E,"shadow.new_head":w.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,S,w,E))}async function commitUpstreamImportInner(e,t,S,w,E=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(S,w)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,E)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,S,w=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${S.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,w)}async function saveInMemoryCheckpoint(e,t,S){let w=S.branch??`main`,E=shadowGit(e),D=randomUUID(),O=resolve(e.gitDir,`index-checkpoint-${D}`),k=resolve(e.gitDir,`tmp-checkpoint-blob-${D}`),j=t?`${t.replace(/\/$/,``)}/${S.docName}`:S.docName,F=Buffer.byteLength(S.contents,`utf-8`),L=formatCheckpointBodyLine(S.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:S.docName,size:F,metadata:S.metadata}:{kind:`external-change-rescue`,docName:S.docName,size:F,metadata:S.metadata}),B=`checkpoint: ${S.label}\n\n${L}`;try{tracedWriteFileSync(k,S.contents,`utf-8`);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`hash-object`,`-w`,k)).trim();await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${j}`);let D=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),F=(await E.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,D,`-m`,B)).trim();return await E.raw(`update-ref`,`refs/checkpoints/${w}/${F}`,F),F}finally{try{rmSync(O)}catch{}try{rmSync(k)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let S=shadowGit(e),w;try{w=await S.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let E=w.trim().split(`
|
|
@@ -1246,7 +1242,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
1246
1242
|
`}function buildWorkflowHandler(e,t,S,w){return async E=>{let D=typeof E.cwd==`string`?E.cwd:void 0,O=await resolveProjectConfigContext(t.resolveCwd,t.config,D);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let k=E[S],j=typeof k==`string`?k:``;return textPlusStructured(`${buildWorkflowFrame(e)}${w(j,O.config.content.dir)}`,{previewUrl:null})}}async function resolveServerUrl(e,t){return typeof e==`function`?await e(t):e}async function resolveConfig(e,t){return typeof e==`function`?await e(t):e}async function resolveProjectConfigContext(e,t,S){let w;try{w=await e(S)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await resolveConfig(t,w);return{ok:!0,cwd:w,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,S,w){let E=await resolveProjectConfigContext(e,t,w);if(!E.ok)return E;let{cwd:D,config:O}=E;try{return{ok:!0,cwd:D,config:O,url:await resolveServerUrl(S,D)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function normalizeDocName(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}function normalizeResponse(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...S}=t;return{ok:!0,...S}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let S=t;if(typeof S.type==`string`&&typeof S.title==`string`){let{type:e,title:t,status:w,instance:E,detail:D,...O}=S;return{...O,ok:!1,error:t,type:e,...typeof w==`number`?{status:w}:{},...typeof E==`string`?{instance:E}:{},...typeof D==`string`?{detail:D}:{}}}let{ok:w,error:E,...D}=S,O=typeof E==`string`?E:typeof S.message==`string`?S.message:`Server returned HTTP ${e.status}`;return{...D,ok:!1,error:O}}async function httpGet(e,t){let S;try{S=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let w;try{w=await S.json()}catch(e){let t=e instanceof Error?e.message:String(e);return S.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${S.status} with non-JSON body: ${t}`}}return normalizeResponse(S,w)}async function httpPost(e,t,S){let w;if(S!==void 0)try{w=JSON.stringify(S)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let E;try{E=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:w,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let D;try{D=await E.json()}catch(e){let t=e instanceof Error?e.message:String(e);return E.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${E.status} with non-JSON body: ${t}`}}return normalizeResponse(E,D)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:S,to:w}=e;return typeof t==`string`&&typeof S==`string`&&typeof w==`string`?[{existing:t,incoming:S,to:w}]:[]}):[]}function mergeCascade(e,t){let S={...e},w=new Map;for(let[e,E]of Object.entries(t))if(E!==void 0)if(Array.isArray(E)){let t=Array.isArray(S[e])?[...S[e]]:[],D=w.get(e)??new Set(t.map(toDedupKey));w.set(e,D);for(let e of E){let S=toDedupKey(e);D.has(S)||(D.add(S),t.push(e))}S[e]=t}else S[e]=E;return S}function mergePatch(e,t){let S={...e};for(let[e,w]of Object.entries(t))if(w!==void 0){if(isEmpty$1(w)){delete S[e];continue}S[e]=w}return S}function mergeDeclarations(e,t){return{...e,...t}}function isEmpty$1(e){return isFrontmatterValueEmpty(e)}function toDedupKey(e){return typeof e==`string`?`s:${e}`:typeof e==`number`?`n:${e}`:typeof e==`boolean`?`b:${e}`:e===null?`null`:e===void 0?`undefined`:`j:${JSON.stringify(e)}`}function resolveNestedFrontmatterWithSources(e,t){let S=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),w=S===``||S===`.`?[]:S.split(`/`).filter(e=>e.length>0),E={},D={},O={},k={},j=!1;for(let t=0;t<=w.length;t++){let S=t===0?``:w.slice(0,t).join(`/`),F=t===0?resolve(e,`.ok`):resolve(e,S,`.ok`),L=resolve(F,`frontmatter.yml`);if(existsSync(L)){let e=readFrontmatterYaml(L);if(e!=null){E=mergeCascade(E,e);for(let t of Object.keys(e))e[t]!==void 0&&(D[t]=S);j=!0}}let B=resolve(F,`schema.yml`);if(existsSync(B)){let e=readFolderSchemaYaml(B);if(e!=null&&Object.keys(e).length>0){O=mergeDeclarations(O,e);for(let t of Object.keys(e))k[t]=S;j=!0}}}return j?{merged:coerceWellKnown(E),sources:D,declarations:O,declarationSources:k}:{merged:{},sources:{},declarations:{},declarationSources:{}}}function coerceWellKnown(e){let t={};for(let[S,w]of Object.entries(e))t[S]=w;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const warnedPaths=new Set;function readFolderSchemaYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let S;try{S=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-schema] malformed YAML at ${e} — folder declarations skipped. Fix the file or delete it. Reason: ${S}`)}return null}if(S==null)return warnedPaths.delete(e),{};let w=FolderSchemaSchema.safeParse(S);return w.success?(warnedPaths.delete(e),w.data.declarations):(warnedPaths.has(e)||(warnedPaths.add(e),console.warn(`[ok-folder-schema] invalid shape at ${e} — folder declarations skipped. ${w.error.message}`)),null)}function readFrontmatterYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let S;try{S=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-frontmatter] malformed YAML at ${e} — folder defaults skipped. Fix the file or delete it. Reason: ${S}`)}return null}return typeof S!=`object`||!S||Array.isArray(S)?null:(warnedPaths.delete(e),S)}function parentFolderOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}const GIT_TIMEOUT_MS$2=5e3;function projectHasGitDir(e){try{return statSync(resolve(e,`.git`)).isDirectory()}catch{return!1}}function openProjectGit(e){return esm_default({baseDir:resolve(e),timeout:{block:GIT_TIMEOUT_MS$2}})}async function readProjectGitLog(e,t,S=5){if(!projectHasGitDir(e))return{commits:[],source:`git-absent`};let w=openProjectGit(e),E=``;try{E=await w.raw(`log`,`-${Math.max(1,S)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let D=[];for(let e of E.split(`
|
|
1247
1243
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let S=e.indexOf(`|`,t+1);if(S<0)continue;let w=e.indexOf(`|`,S+1);w<0||D.push({hash:e.slice(0,t),date:e.slice(t+1,S),authorName:e.slice(S+1,w),subject:e.slice(w+1)})}return{commits:D,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let S=getWipRefPattern(t);return e.startsWith(S)?e.slice(S.length):e}async function logOnRef(e,t,S,w,E){let D=``;try{D=await e.raw(`log`,t,`-${Math.max(1,E*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,S)}catch{return[]}let O=writerIdFromRef(t,w),k=parseWriterId(O),j=[];for(let e of D.split(``)){let t=e.trimStart();if(!t)continue;let[S=``,E=``,D=``,F=``,L=``]=t.split(`\0`),B=S.trim();B.length===40&&j.push({hash:B,date:E,writerName:D,message:F,contributors:readContributors(L),writerId:O,isAgent:k.isAgent,writerClassification:k.classification,branch:w})}return j}async function readShadowLog(e,t,S=5){let w=getShadowRepoPath(e);if(!w)return{commits:[],source:`shadow-repo-absent`};let E=await currentProjectBranch(e);if(!E)return{commits:[],source:`shadow-repo`};let D=openShadowGit(w,resolve(e)),O=``;try{O=await D.raw(`for-each-ref`,getWipRefPattern(E),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let k=O.split(`
|
|
1248
1244
|
`).map(e=>e.trim()).filter(Boolean);return k.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(k.map(e=>logOnRef(D,e,t,E,S)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,S),source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,S={}){let w=normalizeFolderPath(t),E=w===``?[]:w.split(`/`),D=new Set,O=[];collectFromFolder(e,w,`local`,D,O);for(let t=E.length-1;t>=1;t--)collectFromFolder(e,E.slice(0,t).join(`/`),`inherited`,D,O);return E.length>0&&collectFromFolder(e,``,`inherited`,D,O),O}function collectFromFolder(e,t,S,w,E){let D=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(D))return;let O;try{O=readdirSync(D)}catch{return}for(let e of O){if(!e.endsWith(`.md`))continue;let O=e.slice(0,-3);if(w.has(O))continue;let k=join(D,e),j;try{j=statSync(k)}catch{continue}if(!j.isFile())continue;let F=readTemplateMeta(k),L={name:O,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:S};F.title!==void 0&&(L.title=F.title),F.description!==void 0&&(L.description=F.description),w.add(O),E.push(L)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${S}`)}return{}}let S=extractFrontmatterYaml(t);if(S===null)return{};let w;try{w=(0,import_dist$1.parse)(S)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${S}`)}return{}}if(typeof w!=`object`||!w)return{};let E=w,D={};return typeof E.title==`string`&&(D.title=E.title),typeof E.description==`string`&&(D.description=E.description),D}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),S=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return S?S[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${S}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.backlinks??S.results??S.links;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e,S=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;S&&E.push({source:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let S=[...new Set(t)],w=[];for(let e=0;e<S.length;e+=BACKLINK_COUNT_CHUNK)w.push(S.slice(e,e+BACKLINK_COUNT_CHUNK));let E=await Promise.all(w.map(async t=>{let S=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return S.ok?S.counts??{}:null})),D=new Map,O=!1;for(let e of E)if(e){O=!0;for(let[t,S]of Object.entries(e))typeof S==`number`&&Number.isFinite(S)&&D.set(t,S)}return O?D:null}async function fetchForwardLinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.forwardLinks??S.links??S.results;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){E.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let S=typeof t.docName==`string`?t.docName:void 0;S&&E.push({kind:`doc`,docName:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}function mergeFileAndFolder(e,t,S){let w=S?resolveNestedFrontmatterWithSources(S,parentFolderOf(t)):{merged:{},sources:{},declarations:{},declarationSources:{}},E=w.merged,D=mergeCascade(E,e??{});return{title:typeof D.title==`string`?D.title:void 0,description:typeof D.description==`string`?D.description:void 0,tags:Array.isArray(D.tags)?D.tags.filter(e=>typeof e==`string`):[],frontmatter:D,schemaDeclarations:w.declarations}}async function enrichPath(e,t,S={}){let w=resolveWithinRoot(t.projectDir,e);if(!w.ok)throw Error(`enrichPath: ${w.reason}`);let E=w.rel,D=w.abs,O=t.historyDepth??5,k=S.includeRichFields===!0,j=readFrontmatter(D);if(!k){let e=mergeFileAndFolder(await j,E,t.projectDir);return{path:E,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,schema_declarations:Object.keys(e.schemaDeclarations).length>0?e.schemaDeclarations:void 0,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[F,L,B,H,q]=await Promise.all([j,fetchBacklinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),readShadowLog(t.projectDir,E,O).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,E,O).catch(()=>({commits:[],source:`git`}))]),J=mergeFileAndFolder(F,E,t.projectDir);return{path:E,title:J.title,description:J.description,tags:J.tags,frontmatter:J.frontmatter,schema_declarations:Object.keys(J.schemaDeclarations).length>0?J.schemaDeclarations:void 0,backlinkCount:L?.length??null,backlinks:L,forwardLinkCount:B?.length??null,forwardLinks:B,history:H.commits,historySource:H.source,projectHistory:q.commits,projectHistorySource:q.source}}async function scanDirectory(e,t){let S={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},w=0,E=[{path:e,depth:0}];for(;E.length>0;){let e=E.shift();if(!e)break;if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}let D;try{D=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let O of D){if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}w++;let D=O.name;if(O.isDirectory()){if(DIR_SKIP.has(D)||D.startsWith(`.`))continue;e.depth===0&&S.childDirCount++,E.push({path:`${e.path}/${D}`,depth:e.depth+1})}else if(O.isFile()&&WIKI_EXT_RE.test(D)){S.recursiveMdCount++,e.depth===0&&S.directMdCount++;let w=`${e.path}/${D}`;try{let e=await stat$1(w);(!S.mostRecent||e.mtimeMs>S.mostRecent.mtimeMs)&&(S.mostRecent={absPath:w,relPath:relative(t,w).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return S}async function enrichDirectory(e,t){let S=resolveWithinRoot(t.projectDir,e);if(!S.ok)throw Error(`enrichDirectory: ${S.reason}`);let w=S.rel,E=S.abs,D=await scanDirectory(E,t.projectDir),O;if(D.mostRecent){let e=await readFrontmatter(D.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;O={path:D.mostRecent.relPath,title:t??basename(D.mostRecent.relPath),updatedAt:new Date(D.mostRecent.mtimeMs).toISOString()}}let k={path:w,type:`directory`,directMdCount:D.directMdCount,recursiveMdCount:D.recursiveMdCount,childDirCount:D.childDirCount,mostRecentMd:O,truncated:D.truncated},j=resolveNestedFrontmatterWithSources(t.projectDir,w),F=j.merged,L=F.title,B=F.description,H=F.tags??[];L!==void 0&&(k.title=L),B!==void 0&&(k.description=B),H.length>0&&(k.tags=H),Object.keys(F).length>0&&(k.frontmatter_defaults=F),Object.keys(j.declarations).length>0&&(k.schema_declarations=j.declarations);let q=resolveTemplatesAvailable(t.projectDir,w);return q.length>0&&(k.templates_available=q),k}async function enrichDirectoryRecursive(e,t,S){let w=await enrichDirectory(e,S);if(t<=1)return w;let E=w.path,D=resolve(S.projectDir,E),O;try{O=await readdir(D,{withFileTypes:!0})}catch{return w}let k=[];for(let e of O){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let w=await enrichDirectoryRecursive(E?`${E}/${e.name}`:e.name,t-1,S);k.push(w)}return k.length>0&&(w.subfolders=k),w}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function applyNestedFolderRulesUpsert(e){if(!isAbsolute(e.projectDir))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};let t=[];for(let S of e.rules){let w=resolveTargetFolderFromMatch(S.new_match??S.match);if(!w.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:w.message,rule:S.match}};let E=w.folder?resolve(e.projectDir,w.folder):e.projectDir,D=resolve(e.projectDir);if(!E.startsWith(D+sep)&&E!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${E}`,rule:S.match}};let O=null,k=null;if(S.new_match!==void 0&&S.new_match!==S.match){let t=resolveTargetFolderFromMatch(S.match);if(!t.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:t.message,rule:S.match}};if(O=t.folder,k=t.folder?resolve(e.projectDir,t.folder):e.projectDir,!k.startsWith(D+sep)&&k!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved source folder escapes projectDir: ${k}`,rule:S.match}}}t.push({targetFolder:w.folder,targetAbs:E,sourceFolder:O,sourceAbs:k,rule:S})}let S=[];for(let w of t)try{if(w.sourceAbs&&w.sourceAbs!==w.targetAbs){let t=join(w.sourceAbs,`.ok`,`frontmatter.yml`);existsSync(t)&&(unlinkSync(t),autoCleanOkDir(join(w.sourceAbs,`.ok`)),S.push({match:w.rule.match,path:relPathOf$1(e.projectDir,t),action:`deleted`}))}let t=join(w.targetAbs,`.ok`),E=join(t,`frontmatter.yml`),D=readExistingFrontmatter(E),O=Object.keys(w.rule.frontmatter).length===0?{}:mergePatch(D,w.rule.frontmatter);if(Object.keys(O).length===0){existsSync(E)&&(unlinkSync(E),autoCleanOkDir(t),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let k=(0,import_dist$1.stringify)(O),j=`${E}.tmp.${process.pid}.${Date.now()}`;writeFileSync(j,k,`utf-8`),renameSync(j,E),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested frontmatter for ${w.rule.match}: ${e.message}`,rule:w.rule.match},...S.length>0?{partiallyApplied:S}:{}}}return{ok:!0,applied:S}}function resolveTargetFolderFromMatch(e){let t=e.split(`/`).filter(e=>e.length>0),S=[],w=!1;for(let E of t){let t=/[*?[\]{}]/.test(E);if(w&&!t)return{ok:!1,message:`Glob "${e}" matches multiple folders (literal segment "${E}" appears after a glob). Split it into one rule per folder, e.g. folder_config({ action: "set-rule", rules: [{ match: "specs/foo/${E}/**", ... }, ...] }).`};if(t){if(w=!0,E!==`**`&&E!==`*`)return{ok:!1,message:`Glob "${e}" uses an unsupported pattern segment "${E}". Only "*" and "**" are supported in nested folder rules.`};continue}S.push(E)}return{ok:!0,folder:S.join(`/`)}}function applyNestedFolderSchemaUpsert(e){if(!isAbsolute(e.projectDir))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};let t=[];for(let S of e.rules){let w=resolveTargetFolderFromMatch(S.match);if(!w.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:w.message,rule:S.match}};let E=w.folder?resolve(e.projectDir,w.folder):e.projectDir,D=resolve(e.projectDir);if(!E.startsWith(D+sep)&&E!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${E}`,rule:S.match}};t.push({targetFolder:w.folder,targetAbs:E,rule:S})}let S=[];for(let w of t)try{let t=join(w.targetAbs,`.ok`),E=join(t,`schema.yml`),D={...readExistingSchema(E)};for(let[e,t]of Object.entries(w.rule.declarations))t===null?delete D[e]:D[e]=t;if(Object.keys(D).length===0){existsSync(E)&&(unlinkSync(E),autoCleanOkDir(t),S.push({match:w.rule.match,path:relPathOf$1(e.projectDir,E),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let O=(0,import_dist$1.stringify)({declarations:D}),k=`${E}.tmp.${process.pid}.${Date.now()}`;writeFileSync(k,O,`utf-8`),renameSync(k,E),S.push({match:w.rule.match,path:relPathOf$1(e.projectDir,E),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested schema for ${w.rule.match}: ${e.message}`,rule:w.rule.match},...S.length>0?{partiallyApplied:S}:{}}}return{ok:!0,applied:S}}function readExistingSchema(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));if(t==null)return{};let S=FolderSchemaSchema.safeParse(t);if(!S.success)throw Error(`Malformed schema.yml at ${e}: ${S.error.issues.map(e=>e.message).join(`, `)}`);return S.data.declarations}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$1(e,t){let S=resolve(e);return t.startsWith(S+sep)?t.slice(S.length+1).split(sep).join(`/`):t}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let S of e.matchAll(TOKEN_PATTERN)){let e=(S[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:S.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,S)=>{let w=S.trim();return isAllowedToken(w)?t[w]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let S=validateTitle(e.frontmatter.title);if(!S.ok)return{ok:!1,error:S.error};let w=validateSubstitutionAllowlist(e.body);if(!w.ok)return{ok:!1,error:w.error};let{templatesDir:E,filePath:D}=templatePaths(e.projectDir,t.folderRel,e.name),O=serializeFrontmatter(e.frontmatter),k=O?`---\n${O}---\n${e.body}`:e.body;try{mkdirSync(E,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let j=!existsSync(D),F=`${D}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(F,k,`utf-8`),renameSync(F,D)}catch(t){try{unlinkSync(F)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,D)}: ${t.message}`}}}let L=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&L.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,D),created:j,warnings:L}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:S,okDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name),D=existsSync(E);if(D)try{unlinkSync(E)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let O=!1,k=!1;if(existsSync(S)&&isEmpty(S))try{rmdirSync(S),O=!0}catch{}if(existsSync(w)&&isEmpty(w))try{rmdirSync(w),k=!0}catch{}return{ok:!0,path:relPathOf(e.projectDir,E),existed:D,cleanedEmpty:{templatesDir:O,okDir:k}}}function validateInputs(e,t,S){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(S))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(S)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let w=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(w.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let E=w?resolve(e,w):e,D=resolve(e);return!E.startsWith(D+sep)&&E!==D?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${E}`}}:{ok:!0,folderRel:w}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,S){let w=t?join(e,t,`.ok`):join(e,`.ok`),E=join(w,`templates`);return{okDir:w,templatesDir:E,filePath:join(E,`${S}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}const log$6=()=>getLogger(`http`);function successResponse(e,t,S,w,E={}){if(e.headersSent||e.writableEnded||e.destroyed){log$6().error({event:`api.success.double-write`,status:t,handler:E.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}});return}let D=S.safeParse(w);if(!D.success){log$6().error({event:`api.success.malformed-body`,issues:D.error.issues,bodyKeys:typeof w==`object`&&w?Object.keys(w):null,handler:E.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}let O;try{O=JSON.stringify(D.data)}catch(S){log$6().error({event:`api.success.unserializable-body`,bodyKeys:typeof D.data==`object`&&D.data!==null?Object.keys(D.data):null,handler:E.handler,originalStatus:t,err:S},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}e.writeHead(t,{...E.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(O)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,S=e.now??Date.now,w=e.ttlMs??6e4;async function E(E){let D=t.get(E);if(D?.status===`resolved`&&D.expiresAt>S())return D.installed;if(D?.status===`inflight`)return D.promise;let O=(async()=>{try{let D=await e.probe(E);return t.set(E,{status:`resolved`,installed:D,expiresAt:S()+w}),D}catch{return t.set(E,{status:`resolved`,installed:!1,expiresAt:S()+w}),!1}})();return t.set(E,{status:`inflight`,promise:O}),O}async function D(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await E(e)]));return Object.fromEntries(e)}return{probeAll:D,probeWithCache:E}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let S=e.headers.origin;if(typeof S==`string`&&S.length>0)try{return isLoopbackHostname(new URL(S).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await S():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return S=>e===`darwin`?probeMacOs(S,t):e===`win32`?probeWindows(S,t):probeLinux(S,t)}function probeMacOs(e,t){let S=MACOS_APP_NAMES[e];function w(e){return new Promise(S=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}return(async()=>{for(let e of S)if(await w(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(S=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{S(!e)})})}function probeLinux(e,t){return new Promise(S=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let S=[],w=0,E=AbortSignal.timeout(t.timeoutMs),D=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));E.addEventListener(`abort`,D,{once:!0});try{for await(let E of e){if(w+=E.length,w>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);S.push(E)}return Buffer.concat(S)}finally{E.removeEventListener(`abort`,D)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,S,w={}){let E=e.safeParse(t);if(E.success)return{ok:!0,value:E.data};let D=E.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:w.handler,detail:D}),{ok:!1}}function withValidation(e,t,S={}){return async(w,E)=>{if(S.method!==void 0&&w.method!==S.method){errorResponse(E,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:S.handler,extraHeaders:{Allow:S.method}});return}if(S.preBodyGate!==void 0&&!S.preBodyGate(w,E)){!E.headersSent&&!E.writableEnded&&!E.destroyed&&errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(S.skipBodyParse){let D=validateBody(e,{},E,S);if(!D.ok)return;await t(w,E,D.value);return}let D;try{D=await readRequestBody(w)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(E,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:S.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(E,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:S.handler,cause:e});return}errorResponse(E,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:S.handler,cause:e});return}let O;try{O=D.length===0?{}:JSON.parse(D.toString(`utf8`))}catch(e){errorResponse(E,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:S.handler,cause:e});return}let k=validateBody(e,O,E,S);k.ok&&await t(w,E,k.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,S){return new Promise(w=>{let E=!1,D=e=>{E||(E=!0,w(e))},O=setTimeout(()=>D({ok:!1,reason:`timeout`}),S);try{let S=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});S.once(`error`,e=>{clearTimeout(O),D(classifySpawnError(e))}),S.once(`spawn`,()=>{if(!E){try{S.unref()}catch{}clearTimeout(O),D({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(O),D(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let D=typeof E.path==`string`?E.path:``;if(!D){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(D,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let O=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!O){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let k=resolveCursorSpawnInvocation(O,D,S.platform),j=await(S.spawnDetached??spawnDetached)(k.exec,k.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(j.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(j.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(j.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let S of t){let t=S(e);try{return await access(t,constants.X_OK),t}catch(e){let S=e?.code;S!==`ENOENT`&&S!==`EACCES`&&S!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,S,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,S)=>{if(e){t(null);return}let w=S.split(/\r?\n/)[0]?.trim();t(w&&w.length>0?w:null)})})}function resolveCursorSpawnInvocation(e,t,S){return S===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,S){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(S===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let w=S===`win32`?win32:posix;try{let E=w.resolve(e),D=w.resolve(t);if(S===`win32`){let e=w.parse(E).root.toLowerCase(),t=w.parse(D).root.toLowerCase();if(!e||!t||e!==t)return!1}if(E===D)return!0;let O=w.relative(D,E);return O===``||O===`.`?!0:!(O===`..`||O.startsWith(`..${w.sep}`)||S===`win32`&&(/^[a-zA-Z]:[\\/]/.test(O)||O.startsWith(`\\\\`))||S!==`win32`&&O.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string$2().min(1).max(4096),workspacePath:string$2().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}if(S.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let D=HandoffRequestSchema.safeParse(E);if(!D.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:O,url:k,workspacePath:j}=D.data,F=RECIPES[O];if(!k.startsWith(F.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${F.urlScheme} for target ${O}.`,{handler:HANDLER});return}let L=S.sleep??defaultSleep,B=S.spawnDetached??spawnDetached;if(F.type===`app-bundle`){F.quitFirst&&(await B(`/usr/bin/osascript`,[`-e`,`tell application "${F.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await L(QUIT_SETTLE_MS));let e=await B(`/usr/bin/open`,[`-a`,F.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,O,e.reason);return}await L(APP_BUNDLE_SETTLE_MS);let S=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!S.ok){emitSpawnFailure(t,O,S.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!j){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(j,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let H=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!H){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let q=resolveCursorSpawnInvocation(H,j,S.platform),J=await B(q.exec,q.args,SPAWN_TIMEOUT_MS);if(!J.ok){emitSpawnFailure(t,O,J.reason);return}await L(CURSOR_SETTLE_MS);let Y=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!Y.ok){emitSpawnFailure(t,O,Y.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function emitSpawnFailure(e,t,S){switch(S){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(S)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let S=[],w=new Set,E=t=>{!t||w.has(t)||t!==e&&(w.add(t),S.push(t))},D=buildLowerDocNameIndex(t),O=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES)return S;let e=O===``?null:basename$1(O);if(e&&(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES))return S;if(O===``)break;O=parentFolder(O)}return S}function lookup$1(e,t,S){return e.has(S)?S:t.get(S.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let S of e.keys()){let e=S.toLowerCase();t.has(e)||t.set(e,S)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let S=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(S))return normalizeFrontmatterScalar(t.slice(S.length))||null;return null}function parseInlineAliases(e){let t=[],S=``,w=null;for(let E of e){if(w){S+=E,E===w&&(w=null);continue}if(E===`"`||E===`'`){w=E,S+=E;continue}if(E===`,`){let e=normalizeFrontmatterScalar(S);e&&t.push(e),S=``;continue}S+=E}let E=normalizeFrontmatterScalar(S);return E&&t.push(E),t}function dedupeExact(e){let t=[],S=new Set;for(let w of e)!w||S.has(w)||(S.add(w),t.push(w));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let S=splitFrontmatterLines(t);for(let e=0;e<S.length;e+=1){let t=S[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let w=t[1]?.trim()??``;if(w){if(w.startsWith(`[`)&&w.endsWith(`]`))return dedupeExact(parseInlineAliases(w.slice(1,-1)));let e=normalizeFrontmatterScalar(w);return e?[e]:[]}let E=[];for(let t=e+1;t<S.length;t+=1){let e=S[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&E.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(E)}return[]}function extractPageTitle(e,t){let{frontmatter:S,body:w}=stripFrontmatter(e),E=extractFrontmatterScalar(S,`title`);if(E)return E;let D=w.match(/^# (.+)$/m);return D?D[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),S=extractFrontmatterScalar(t,`icon`);if(!(!S||S.length>ICON_VALUE_LENGTH_CAP))return S}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let S=`${t}:`,w=splitFrontmatterLines(e);for(let e=0;e<w.length;e+=1){let t=w[e];if(!t?.startsWith(S))continue;let E=t.slice(S.length).trim();if(E){if(E.startsWith(`[`)&&E.endsWith(`]`)){let e=parseInlineAliases(E.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(E);return e?[e]:void 0}let D=[];for(let t=e+1;t<w.length;t+=1){let e=w[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&D.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return D.length>0?D:void 0}}function extractPageIdentity(e,t){let S=extractPageTitle(e,t),w=extractPageAliases(e),E=dedupeExact([S,...w]),D=[],O=new Set;for(let e of E){let t=toWikiLinkSlug(e);!t||O.has(t)||(O.add(t),D.push(t))}return{docName:t,title:S,aliases:w,matchLabels:E,normalizedMatchLabels:D}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidShareDocPath(e){if(e.length===0||e.startsWith(`/`)||e.startsWith(`\\`))return!1;for(let t of e.split(/[/\\]/))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,S,w){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(S)}/${w.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let S=t===void 0?``:` branch_exists=${t}`;console.log(`[share] action=construct-url result=${e}${S}`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let S;try{S=statSync(t)}catch{return null}if(S.isDirectory())return t;if(S.isFile()){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}let w=/^gitdir:\s*(.+)$/m.exec(S.trim());if(!w)return null;let E=w[1].trim(),D=isAbsolute(E)?E:resolve(e,E);return existsSync(D)?D:null}return null}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`HEAD`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=/^ref:\s*refs\/heads\/(.+)$/.exec(w.trim());return E?E[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),S=e.indexOf(`;`),w=-1;return t>=0&&S>=0?w=Math.min(t,S):t>=0?w=t:S>=0&&(w=S),(w===-1?e:e.slice(0,w)).trim()}function extractOriginUrl(e){let t=!1;for(let S of e.split(/\r?\n/)){let e=stripCommentAndTrim(S);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let w=/^url\s*=\s*(.+)$/.exec(e);if(!w)continue;let E=w[1].trim();if((E.startsWith(`"`)&&E.endsWith(`"`)||E.startsWith(`'`)&&E.endsWith(`'`))&&(E=E.slice(1,-1)),E.length>0)return E}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let S=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return S||(S=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)||(S=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),S)||(S=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)?{owner:S[1],repo:S[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`config`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=extractOriginUrl(w);return E?{originUrl:E,github:parseGitHubOriginUrl(E)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),S=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(S)return`${S[1]}/${S[2]}`;let w=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return w?w[1]:t}function branchExistsOnOrigin(e,t){let S=resolveGitDir$1(e);if(!S)return!1;if(existsSync(join(S,`refs`,`remotes`,`origin`,t)))return!0;let w=join(S,`packed-refs`);if(!existsSync(w))return!1;let E;try{E=readFileSync(w,`utf-8`)}catch{return!1}let D=`refs/remotes/origin/${t}`;for(let e of E.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let S=t.split(/\s+/);if(S.length===2&&S[1]===D)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
1249
|
-
`).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let S=JSON.parse(t[e]);if(S&&typeof S==`object`&&!Array.isArray(S))return S}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let S of e.owners){if(!S||typeof S!=`object`)continue;let e=S,w=typeof e.login==`string`?e.login:null,E=e.kind===`user`||e.kind===`org`?e.kind:null;if(w===null||E===null)continue;let D=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:w,kind:E,...D?{avatarUrl:D}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,S=typeof e.repoName==`string`?e.repoName:null,w=typeof e.cloneUrl==`string`?e.cloneUrl:null,E=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&S!==null&&w!==null&&E!==null?{ok:!0,ownerLogin:t,repoName:S,cloneUrl:w,defaultBranch:E}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,S){let w=[`action=${e}`,`result=${t}`];S?.count!==void 0&&w.push(`count=${S.count}`),S?.available!==void 0&&w.push(`available=${S.available}`),console.log(`[share] ${w.join(` `)}`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const MAX_ZIP_BYTES=102400,BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`},DESKTOP_SKILLS_REL=`Open Knowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let S=t.platform??process.platform,w=t.checkDesktop??!1,E=t.home??homedir(),D=[];w&&S===`darwin`&&(D.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),D.push(join(E,`Applications`,DESKTOP_SKILLS_REL,e))),D.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of D)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${D.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let S=await readdir(e,{withFileTypes:!0});for(let w of S){let S=join(e,w.name);w.isDirectory()?yield*walkFiles(S,t):w.isFile()&&(yield relative(t,S))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,S=computeWrapperFolderName(e)){let w=new
|
|
1245
|
+
`).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let S=JSON.parse(t[e]);if(S&&typeof S==`object`&&!Array.isArray(S))return S}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let S of e.owners){if(!S||typeof S!=`object`)continue;let e=S,w=typeof e.login==`string`?e.login:null,E=e.kind===`user`||e.kind===`org`?e.kind:null;if(w===null||E===null)continue;let D=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:w,kind:E,...D?{avatarUrl:D}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,S=typeof e.repoName==`string`?e.repoName:null,w=typeof e.cloneUrl==`string`?e.cloneUrl:null,E=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&S!==null&&w!==null&&E!==null?{ok:!0,ownerLogin:t,repoName:S,cloneUrl:w,defaultBranch:E}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,S){let w=[`action=${e}`,`result=${t}`];S?.count!==void 0&&w.push(`count=${S.count}`),S?.available!==void 0&&w.push(`available=${S.available}`),console.log(`[share] ${w.join(` `)}`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const MAX_ZIP_BYTES=102400,BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`},DESKTOP_SKILLS_REL=`Open Knowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let S=t.platform??process.platform,w=t.checkDesktop??!1,E=t.home??homedir(),D=[];w&&S===`darwin`&&(D.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),D.push(join(E,`Applications`,DESKTOP_SKILLS_REL,e))),D.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of D)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${D.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let S=await readdir(e,{withFileTypes:!0});for(let w of S){let S=join(e,w.name);w.isDirectory()?yield*walkFiles(S,t):w.isFile()&&(yield relative(t,S))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,S=computeWrapperFolderName(e)){let w=new yazl.ZipFile;w.addEmptyDirectory(`${S}/`);let E=[];for await(let t of walkFiles(e))E.push(t);E.sort();for(let t of E){let E=join(e,t),D=`${S}/${toPosixZipPath(t)}`;w.addFile(E,D)}w.end(),await new Promise((e,S)=>{let E=createWriteStream(t);w.outputStream.pipe(E),E.on(`close`,()=>e()),E.on(`error`,S),w.outputStream.on(`error`,S)})}async function sha256OfFile(e){return new Promise((t,S)=>{let w=createHash(`sha256`),E=createReadStream(e);E.on(`data`,e=>w.update(e)),E.on(`end`,()=>t(w.digest(`hex`))),E.on(`error`,S)})}function extractMetadataVersion(e){let t=e.indexOf(`
|
|
1250
1246
|
---`,4);if(!e.startsWith(`---
|
|
1251
1247
|
`)||t<0)return;let S=e.slice(4,t),w=S.search(/^metadata:/m);if(w<0)return;let E=S.slice(w).split(`
|
|
1252
1248
|
`).slice(1);for(let e of E){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,S={}){let w=S.bundle??`project`,E=statSync(e).size;if(E>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${E} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let D=await sha256OfFile(e),O=await readFile$1(join(S.sourceDir??resolveBundledSkillDir(w,{checkDesktop:!1}),`SKILL.md`),`utf-8`),k=BUNDLE_SKILL_NAME[w];if(!RegExp(`^name:\\s+${k}$`,`m`).test(O.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${k}'. Check packages/server/assets/skills/${w}/SKILL.md frontmatter.`);let j=extractMetadataVersion(O);if(t!==void 0){if(!j)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${w}/SKILL.md.`);if(j!==t)throw Error(`SKILL.md metadata.version (${j}) does not match expected version (${t}).`)}return{size:E,sha256:D,skillVersion:j}}async function buildSkillZip(e={}){let t=e.bundle??`project`,S=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),w=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(S,w,BUNDLE_SKILL_NAME[t]);let{size:E,sha256:D,skillVersion:O}=await validateSkillZip(w,e.expectedSkillVersion,{bundle:t,sourceDir:S});return{outputPath:w,size:E,sha256:D,skillVersion:O}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let S=t?.homedir??(()=>process.env.HOME??``),w=t?.warn??((e,t)=>{console.warn(t,e)}),E=S();if(!E){w({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let D=join(E,...SKILL_INSTALL_EVENTS_FILE_REL),O=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(D),{recursive:!0})}catch(e){w({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(D,O,{flag:`a`,encoding:`utf-8`})}catch(e){w({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,S)=>tracedWriteFile(e,t,S),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let S=skillStateYamlPath(e),w;try{w=await readFileAsync(S,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let E=(0,import_dist$1.parseDocument)(w);if(E.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:S,errors:E.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let D=SkillStateSchema.safeParse(E.toJSON());if(!D.success){let e=D.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:S,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:S,issues:D.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return D.data}async function writeSkillStateFile(e,t){let S=SkillStateSchema.safeParse(t);if(!S.success)throw Error(`Refusing to write invalid skill-state: ${S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let w=skillStateYamlPath(e);await tracedMkdir(dirname(w),{recursive:!0});let E=(0,import_dist$1.parseDocument)(``);E.contents=E.createNode(S.data),await atomicWriteFile(w,E.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.version??null}async function readTargetRecordedAt(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,S,w,E){if(!SKILL_STATE_VERSION_RE.test(S))throw Error(`Refusing to write invalid version string: ${S}`);let D=await readSkillStateFile(e,E)??emptySkillState(),O=new Date().toISOString(),k=D.targets[t],j=w===void 0?k?.surface??void 0:w,F=j===void 0?{version:S,recordedAt:O}:{version:S,recordedAt:O,surface:j};await writeSkillStateFile(e,{...D,targets:{...D.targets,[t]:F}})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[S,w]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:S,targets:w}}async function readAllTargets(e,t=DEFAULT_LOGGER){let S=null;try{S=await readSkillStateFile(e,t)}catch(w){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(w)},`non-ENOENT error reading skill-state.yml; treating as absent`),S=null}let w=SKILL_STATE_TARGETS.map(e=>{let t=S?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(w)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,S,w,E){return new Promise(D=>{let O;try{O=e(t,S,{env:w,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){D({kind:`spawn-error`,stderr:``,error:e});return}let k=``,j=!1,F=e=>{j||(j=!0,clearTimeout(L),D(e))};O.stderr?.on(`data`,e=>{k+=typeof e==`string`?e:e.toString(`utf-8`)}),O.on(`error`,e=>{F({kind:`spawn-error`,stderr:k,error:e})}),O.on(`exit`,e=>{F(e===0?{kind:`ok`,exitCode:e,stderr:k}:{kind:`nonzero`,exitCode:e,stderr:k})});let L=setTimeout(()=>{try{O.kill(`SIGTERM`)}catch{}F({kind:`timeout`,stderr:k})},E)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,S,w,E){if(!await anyLegacyUserSkillExists(e))return;let D=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],S,w);D.kind!==`ok`&&E.warn({event:`skill-install.legacy-remove-failed`,reason:D.kind,exitCode:D.exitCode,stderr:D.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),S=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},w=e.spawn??spawn,E=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,D=e.surface??`cli-npx-skills-add`,O=async(e,w,E)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:D,target:`cli-hosts`,bundle:`discovery`,outcome:e,...w===void 0?{}:{version:w},...E===void 0?{}:{reason:E}},{homedir:()=>t,warn:S.warn})},k;try{k=await readServerPackageVersion()}catch(e){return S.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await O(`failed`,void 0,`version-read-failed`),`failed`}let j=await readTargetVersion(t,`cli-hosts`,S).catch(e=>(S.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(j!==null&&j===k){if(await centralSkillExists(t))return S.info?.({event:`skill-install.skip-current`,version:k},`Open Knowledge skill already installed at current version; skipping.`),await O(`skip-current`,k),`skip-current`;S.info?.({event:`skill-install.reinstall-missing`,version:k,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let F;try{F=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return S.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await O(`failed`,k,`bundled-asset-missing`),`failed`}let L={...process.env,HOME:t};await removeLegacyUserSkill(t,w,L,E,S);let B=await runSpawn(w,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,F,`--agent`,`*`,`-g`,`-y`,`--copy`],L,E);if(B.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,k,D,S)}catch(e){return S.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await O(`failed`,k,`sidecar-write-failed`),`failed`}return S.info?.({event:`skill-install.installed`,version:k},`Open Knowledge skill installed to detected agent hosts.`),await O(`installed`,k),`installed`}return B.kind===`timeout`?(S.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:E,stderr:B.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`timeout`),`failed`):B.kind===`spawn-error`?(S.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(B.error),stderr:B.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`spawn-error`),`failed`):(S.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:B.exitCode,stderr:B.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`nonzero-exit:${B.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,S){let w={detached:!0,stdio:`ignore`};try{return t===`darwin`?(S(`open`,[e],w).unref(),{ok:!0}):t===`win32`?(S(`cmd`,[`/c`,`start`,`""`,e],w).unref(),{ok:!0}):t===`linux`?(S(`xdg-open`,[e],w).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),S=resolve(e.out??defaultDownloadsPath(t)),w=e.platformName??platform(),E=e.spawnFn??spawn,D=e.logger,O=async(e,S,w)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...S===void 0?{}:{version:S},...w===void 0?{}:{reason:w}},{homedir:()=>t,warn:D?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){D?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let S=null,w=null;try{[S,w]=await Promise.all([readTargetVersion(t,`claude-cowork`,D),readTargetRecordedAt(t,`claude-cowork`,D)])}catch(e){D?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(S!==null&&S===e)return D?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await O(`skip-current`,e),{status:`skip-current`,skillVersion:e,...w===null?{}:{recordedAt:w}}}}try{await tracedMkdir(dirname(S),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let k;try{k=await buildSkillZip({outputPath:S,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let j={status:`built`,outputPath:k.outputPath,size:k.size,sha256:k.sha256,skillVersion:k.skillVersion};if(k.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,k.skillVersion,`server-build-and-open`,D)}catch(e){D?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:k.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await O(`built`,k.skillVersion),j;let F=invokeFileAssociation(k.outputPath,w,E);return F.ok?(await O(`installed`,k.skillVersion),{...j,status:`installed`}):(await O(`built`,k.skillVersion,`handoff-${F.reason}`),{...j,handoffError:{reason:F.reason,message:F.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$5=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,S){this.hash.update(e),this.bytes+=e.length,S(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,S){let w=extname(S),E=S.slice(0,S.length-w.length),D=[S,...Array.from({length:99},(e,t)=>`${E}-${t+1}${w}`)];for(let S of D){let w=resolve(t,S);try{tracedLinkSync(e,w);try{tracedUnlinkSync(e)}catch{}return S}catch(t){let S=t.code;if(S===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw S===`ENOSPC`||S===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):S===`EROFS`||S===`EACCES`||S===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let S=tmpUploadDir(e),w={scanned:0,deleted:0,errors:0};if(!existsSync(S))return w;let E;try{E=readdirSync(S)}catch(e){return log$5.warn({err:e,dir:S},`[upload-tempfile-sweep] readdir failed`),w.errors++,w}let D=Date.now()-t;for(let e of E){if(!e.startsWith(`upload-`))continue;w.scanned++;let t=resolve(S,e);try{if(statSync(t).mtimeMs>=D)continue;tracedUnlinkSync(t),w.deleted++}catch(e){log$5.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),w.errors++}}return(w.deleted>0||w.errors>0)&&log$5.info({dir:S,scanned:w.scanned,deleted:w.deleted,errors:w.errors},`[upload-tempfile-sweep] swept ${w.deleted}/${w.scanned} (errors: ${w.errors})`),w}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{nextIndex:E+S};E+=t}return{nextIndex:w}}function readWikiLink$2(e,t){let S=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function readMarkdownLink$2(e,t){let S=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{text:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function readImageRef(e,t){let S=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{alt:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),S=[];for(let e=0;e<t.length;e+=2)S.push({line:t[e]??``,ending:t[e+1]??``});return S}function rewriteWikiLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let O=readWikiLink$2(e,D);if(O){O.target===t?(w+=`[[${S}${O.anchor?`#${O.anchor}`:``}${O.alias?`|${O.alias}`:``}]]`,E++):w+=e.slice(D,O.nextIndex),D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function recomputeRelativeImageHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D;if(j.startsWith(`/`)||j.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(j))return null;let F=posix.dirname(t),L=posix.dirname(S);if(F===L)return null;let B=F===`.`?`/`:`/${F}/`,H=posix.resolve(B,j).slice(1),q=posix.relative(L===`.`?``:L,H);return q||=posix.basename(H),j.startsWith(`./`)&&!q.startsWith(`./`)&&!q.startsWith(`../`)&&(q=`./${q}`),`${q}${k}${E}`}function recomputeRelativeMarkdownHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D,F=posix.dirname(t),L=posix.relative(F===`.`?``:F,S);return L||=posix.basename(S),j.endsWith(`.mdx`)?L+=`.mdx`:j.endsWith(`.md`)&&(L+=`.md`),j.startsWith(`./`)&&!L.startsWith(`./`)&&!L.startsWith(`../`)&&(L=`./${L}`),`${L}${k}${E}`}function rewriteMarkdownLinksInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`[`&&e[O+1]===`[`){let t=readWikiLink$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=t===S&&S!==w?recomputeRelativeImageHref(k.href,S,w):null;if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=``,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){if(resolveInternalHref(k.href,t)?.docName===S){let e=recomputeRelativeMarkdownHref(k.href,t,w),S=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${e}>`:e;E+=`[${k.text}](${S}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,S){let w=``,E=0,D=0;for(;D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`<`){let O=new RegExp(MIRROR_TAG_RE.source),k=e.slice(D),j=O.exec(k);if(j&&j.index===0){let[e,O]=j,k=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),F=O.replace(k,(e,w,D,O)=>O===t?(E++,`${w}${D}${S}${D}`):e);w+=`<Mirror${F}/>`,D+=e.length;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteMirrorSrcForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteMirrorSrcInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteWikiLinksForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteWikiLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteMarkdownLinksForDocumentRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteMarkdownLinksInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteOutboundMarkdownLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let t=readWikiLink$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`!`&&e[D+1]===`[`){let t=readImageRef(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`){let O=readMarkdownLink$2(e,D);if(O){let k=resolveInternalHref(O.href,t);if(k!==null){let t=recomputeRelativeMarkdownHref(O.href,S,k.docName);if(t!==O.href){let e=O.hrefRaw.startsWith(`<`)&&O.hrefRaw.endsWith(`>`)?`<${t}>`:t;w+=`[${O.text}](${e}${O.titleSuffix})`,E++}else w+=e.slice(D,O.nextIndex)}else w+=e.slice(D,O.nextIndex);D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,S){if(posix.dirname(t)===posix.dirname(S))return{markdown:e,rewrites:0};let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteOutboundMarkdownLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,S=[];for(let{from:w,to:E}of e){for(let[e,D]of t)e!==w&&D===E&&S.push({existing:e,incoming:w,to:E});t.set(w,E)}if(S.length>0)throw new ManagedRenameCollisionError(S);return t}function rewriteSupportedLinksForRename(e,t,S,w){let{frontmatter:E,body:D}=stripFrontmatter(e),O=rewriteWikiLinksForDocumentRename(D,S,w),k=rewriteMarkdownLinksForDocumentRename(O.markdown,t,S,w),j=rewriteMirrorSrcForDocumentRename(k.markdown,S,w);return{markdown:prependFrontmatter(E,j.markdown),rewrites:O.rewrites+k.rewrites+j.rewrites}}function applyRenameMap(e,t,S){let w=e,E=0,D,O=[];for(let[e,w]of S)e!==w&&(e===t?D=w:O.push([e,w]));if(D!==void 0){let e=rewriteSupportedLinksForRename(w,t,t,D);w=e.markdown,E+=e.rewrites;let{frontmatter:S,body:O}=stripFrontmatter(w),k=rewriteOutboundMarkdownLinksForSourceMove(O,t,D);w=prependFrontmatter(S,k.markdown),E+=k.rewrites}let k=D??t,j=new Map;for(let[e,t]of O){let S=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,D=rewriteSupportedLinksForRename(w,k,e,S);D.rewrites>0&&(w=D.markdown,E+=D.rewrites,j.set(S,t))}for(let[e,t]of j)w=rewriteSupportedLinksForRename(w,k,e,t).markdown;return{markdown:w,rewrites:E}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,S){if(!normalizeSnippet$1(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
@@ -3365,5 +3361,5 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3365
3361
|
`).split(`
|
|
3366
3362
|
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Rt),S=e+t;S>0?getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We,serializeDoc:at});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Bt,projectDir:S,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let w=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let e of CONFIG_DOC_NAMES){let t=w.get(e);if(t)try{ee.info({docName:e,path:t},`[config-file-watcher] starting`);let S=await startConfigFileWatcher(t,t=>{let S=_e.documents.get(e);ee.info({docName:e,hasDocument:S!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,e,t,ge.configPersistenceCtx);if(ee.info({docName:e,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:e,cleanup:S}),ee.info({docName:e,path:t},`[config-file-watcher] started`)}catch(S){ee.warn({err:S,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Wt.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:S,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(S,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(E=t)}}catch{}let D=E?[e,w,E]:[e,w],O=ee;O.info({okignorePath:e,gitignorePath:w,gitInfoExcludePath:E},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let k=await startMultiPathConfigFileWatcher(D,(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);O.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){O.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let E=await ue.rebuildIgnorePatterns();if(E.ok)O.info({changedPath:relative(S,t),patternCount:E.patternCount,nestedFileCount:E.nestedFileCount,durationMs:E.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;O.warn({changedPath:e,error:E.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,E.error.message)}})().catch(e=>{O.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:k}),O.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let E=resolveGitDir(S),D=E?readBranchFromHead(E)??`main`:`main`;switchReconciledBaseScope(D),de.switchBranch(D);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3367
3363
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.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){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}function O(e){for(let w of e)try{let e=relative(t,join(S,w));if(e.startsWith(`..`))continue;let E=stripDocExtension(e),D=_e.documents.get(E);if(!D)continue;let O=at(E);O===null?ee.warn({docName:E,file:w},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(E,O);let k=D.getMap(`lifecycle`);k.set(`status`,`conflict`),k.set(`reason`,`sync-merge-conflict`),ee.info({docName:E,file:w},`[sync] marked loaded content conflict`)}catch(e){ee.warn({err:e,file:w},`[sync] failed to mark loaded content conflict`)}}let k=J?.[0]??`open-knowledge`,j=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):k} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:j,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{ee.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||ee.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 Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}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 w=resolve(e,t);try{existsSync(w)&&statSync(w).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;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};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,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-BniQ3qki-D-qFWWUB.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.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 H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=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:O,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,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=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.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(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ne},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;w!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(e){if(ge)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,j(ne,Te),ge&&updateUiLockPort(ne,Te),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,S)=>{try{await je(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),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`,()=>Y()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(ne)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:ne,contentDir:e.contentDir,port:Te,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
|
|
3368
|
-
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[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,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}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 w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`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(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{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),w=0;w<32;w+=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 w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,GitDirAccessError as $r,initShadowRepo as $t,MissingOkConfigError as A,looseObject as Ai,readSkillInstallStateSnapshot as An,tracedWriteFile as Ar,createTestLogger as At,STARTER_PACK_IDS as B,releaseUiLock as Bn,writeTargetVersion as Br,formatContributors as Bt,LOG_MD_TEMPLATE as C,OK_PROJECT_MARKER as Ci,parseHocuspocusAuthToken as Cn,tracedMkdir as Cr,createLiveDerivedIndexExtension as Ct,MCP_SERVER_NAME as D,array as Di,readAllTargets as Dn,tracedRmSync as Dr,createServer$1 as Dt,MCP_CONNECTION_ID_HEADER as E,any$1 as Ei,planSeed as En,tracedRenameSync as Er,createPersistenceExtension as Et,SERVICE_WRITER as F,_coercedNumber as Fi,reconcile as Fn,validateCloneInputs as Fr,evictStaleTrackerEntries as Ft,StateManifestError as G,resolveCursorBinaryDefault as Gn,isInitializedNotification as Gr,getLogger as Gt,STATE_MANIFEST_FILENAME as H,resetMetrics as Hn,McpServer as Hr,gcCheckpointRefs as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,NEVER as Ii,recordContributor as In,validateSkillZip as Ir,extractWikiLinksFromMarkdown as It,acquireUiLock as J,resolvePack as Jn,atomicWriteFileSync as Jr,getTracer as Jt,TagIndex as K,resolveCursorSpawnInvocation as Kn,isJSONRPCRequest as Kr,getMeter as Kt,STARTER_FOLDERS as L,require_dist$2 as Li,recordSkillInstallEvent as Ln,withSpan as Lr,findEnclosingGitRoot as Lt,PinoLogger as M,object$1 as Mi,readTargetRecordedAt as Mn,updateLastKnownHash as Mr,detectProjectShape as Mt,ProjectGitInitError as N,string$2 as Ni,readTargetVersion as Nn,updateUiLockPort as Nr,ensureProjectGit as Nt,MISSING_OK_CONFIG_MESSAGE as O,boolean$1 as Oi,readBranchFromHead as On,tracedRmdirSync as Or,createServerObserverExtension as Ot,ROLLBACK_ORIGIN as P,url as Pi,readUiLock as Pn,validateAgentId as Pr,errorResponse as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,writeConfigPatch as Qr,incrementServerObserverFire as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,registerAllTools as Rn,withSpanSync as Rr,findEnclosingProjectRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,LOCAL_DIR as Si,parseAuthRejectionWire as Sn,tracedLinkSync as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,ZodNumber$1 as Ti,pathToDocName as Tn,tracedRename as Tr,createOsProbe as Tt,SeedPrerequisiteError as U,resolveBundledSkillDir as Un,JSONRPCMessageSchema as Ur,getCurrentMcpLogger as Ut,STARTER_TEMPLATES as V,removeLastKnownHash as Vn,writeTracker as Vr,formatContributorsFrom as Vt,SeedRootDirError as W,resolveContentDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getLocalDir as Wt,applyExternalChange as X,restoreContributors as Xn,resolveConfigPath as Xr,handleSpawnCursor as Xt,applyAgentMarkdownWrite as Y,resolvePackageVersion as Yn,readConfigSafely as Yr,handleCollabSocketError as Yt,applySeed as Z,restoreLifecycleFromConflictsJson as Zn,withFileLockSync as Zr,incrementCollabSocketFilteredError as Zt,GIT_UPSTREAM_WRITER as _,humanFormat as _i,listStarterPacks as _n,startWatcher as _r,contributorCount as _t,AgentPresenceBroadcaster as a,DEFAULT_SERVER_HOST as ai,isAllowedWorkspaceHostHeader as an,safeContentPath as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,isOrphanMode as bi,mountMcpAndApi as bn,toBroadcasterKey as br,createContentFilter as bt,BacklinkIndex as c,EXECUTABLE_BLOCKLIST_EXTENSIONS as ci,isKnownPackId as cn,sanitizeClientName as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,ProblemDetailsSchema as di,isPathWithinDir as dn,seedBasenameIndex as dr,coercePackId as dt,MalformedGitPointerError as ei,initTelemetry as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,SKILL_STATE_TARGETS as fi,isProjectRoot as fn,setActiveSpanAttributes as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,defaultScheduler as gi,listRescueCheckpoints as gn,splitMarkdownBlocks as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,colorFromSeed as hi,lastKnownHash as hn,spawnDetached as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ii,isAllowedApiOrigin as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,number$1 as ji,readStateManifest as jn,tracedWriteFileSync as jr,detectClaudeDesktopPresence as jt,McpLogger as k,literal as ki,readServerPackageVersion as kn,tracedUnlinkSync as kr,createStreamingErrorWriter as kt,CC1Broadcaster as l,INLINE_RENDERABLE_EXTENSIONS as li,isLoopbackAddress as ln,saveInMemoryCheckpoint as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,SYSTEM_DOC_NAME as mi,isSystemDoc as mn,shutdownTelemetry as mr,commitWipFromTree as mt,AGENT_ID_RE as n,ASSET_EXTENSIONS as ni,installTestLoggers as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,DEFAULT_SIGTERM_GRACE_MS as oi,isConfigDoc as on,safeSubdir as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,SPAWN_ERROR_LOG as pi,isSelfWrite as pn,shadowGit as pr,commitWip as pt,UiLockCollisionError as q,resolveLockDir as qn,isJSONRPCResultResponse as qr,getMetrics as qt,AGENT_WRITE_ORIGIN as r,CC1_CONTRACT_VERSION as ri,installUserSkill as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,EDITOR_LABELS as si,isHocuspocusAuthRejectionReason as sn,safetyCheckpoint as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,ALL_EDITOR_IDS as ti,installPrettyZodErrors as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,ORPHAN_MODES as ui,isPairedWriteOrigin as un,saveVersion as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,iconFromClientName as vi,loadPrincipal as vn,streamingProblemEvent as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,locateIssue as wi,parseKeepaliveConnectionId as wn,tracedMkdirSync as wr,createMcpHttpHandler as wt,INSTALLED_AGENTS_SCHEMES as x,CONFIG_SCHEMA_MAJOR_PATH as xi,normalizeFsPath as xn,tracedAppendFileSync as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,isBranchNotFoundGitError as yi,loggerFactory as yn,swapContributors as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,registerWrite as zn,writeStateManifest as zr,formatAuthRejectionWire as zt};
|
|
3369
|
-
//# sourceMappingURL=dist-
|
|
3364
|
+
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[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,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.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}`,w=`${e}.${t}`;try{renameSync(S,w)}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,w=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 E of w)if(t-E.mtime>S)try{unlinkSync(join(e,E.name))}catch{}let E=w.filter(e=>t-e.mtime<=S).sort((e,t)=>e.mtime-t.mtime),D=E.reduce((e,t)=>e+t.size,0);for(let t of E){if(D<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),D-=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),setTimeout(()=>pruneLogsDir(OK_LOGS_DIR),5e3);let w=pino.destination({dest:S,append:!0,sync:!1});return pino({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:pino.stdTimeFunctions.isoTime,...e.additionalOptions},w)}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 w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`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(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{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),w=0;w<32;w+=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 w=dirname(t);if(w===t)return;t=w}}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 w=e;return{name:String(w.name??`ObjectError`),message:scrubPaths(String(w.message??``))??``,stack:scrubPaths(w.stack),code:w.code,cause:w.cause===void 0?void 0:serializeError(w.cause,t+1,S)}}return{name:`UnknownError`,message:String(e)}}export{assertNeverDiskEvent as $,restoreContributors as $n,readConfigSafely as $r,handleSpawnCursor as $t,MissingOkConfigError as A,any$1 as Ai,readAllTargets as An,tracedRenameSync as Ar,createStreamingErrorWriter as At,STARTER_PACK_IDS as B,NEVER as Bi,recordSkillInstallEvent as Bn,validateSkillZip as Br,formatAuthRejectionWire as Bt,LOG_MD_TEMPLATE as C,isBranchNotFoundGitError as Ci,mountMcpAndApi as Cn,swapContributors as Cr,createFileLogger as Ct,MCP_SERVER_NAME as D,OK_PROJECT_MARKER as Di,parseKeepaliveConnectionId as Dn,tracedMkdir as Dr,createPersistenceExtension as Dt,MCP_CONNECTION_ID_HEADER as E,LOCAL_DIR as Ei,parseHocuspocusAuthToken as En,tracedLinkSync as Er,createOsProbe as Et,SERVICE_WRITER as F,number$1 as Fi,readTargetRecordedAt as Fn,tracedWriteFileSync as Fr,errorResponse as Ft,StateManifestError as G,resetMetrics as Gn,writeTracker as Gr,getLocalDir as Gt,STATE_MANIFEST_FILENAME as H,registerWrite as Hn,withSpanSync as Hr,formatContributorsFrom as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,object$1 as Ii,readTargetVersion as In,updateLastKnownHash as Ir,evictStaleTrackerEntries as It,acquireUiLock as J,resolveCursorBinaryDefault as Jn,LATEST_PROTOCOL_VERSION as Jr,getLogsDir as Jt,TagIndex as K,resolveBundledSkillDir as Kn,McpServer as Kr,getLogFilePath as Kt,STARTER_FOLDERS as L,string$2 as Li,readUiLock as Ln,updateUiLockPort as Lr,extractWikiLinksFromMarkdown as Lt,PinoLogger as M,boolean$1 as Mi,readServerPackageVersion as Mn,tracedRmdirSync as Mr,detectClaudeDesktopPresence as Mt,ProjectGitInitError as N,literal as Ni,readSkillInstallStateSnapshot as Nn,tracedUnlinkSync as Nr,detectProjectShape as Nt,MISSING_OK_CONFIG_MESSAGE as O,locateIssue as Oi,pathToDocName as On,tracedMkdirSync as Or,createServer$1 as Ot,ROLLBACK_ORIGIN as P,looseObject as Pi,readStateManifest as Pn,tracedWriteFile as Pr,ensureProjectGit as Pt,assertCompatibleStateManifest as Q,resolvePackageVersion as Qn,atomicWriteFileSync as Qr,handleCollabSocketError as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,url as Ri,reconcile as Rn,validateAgentId as Rr,findEnclosingGitRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,iconFromClientName as Si,loggerFactory as Sn,streamingProblemEvent as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,CONFIG_SCHEMA_MAJOR_PATH as Ti,parseAuthRejectionWire as Tn,tracedAppendFileSync as Tr,createMcpHttpHandler as Tt,SeedPrerequisiteError as U,releaseUiLock as Un,writeStateManifest as Ur,gcCheckpointRefs as Ut,STARTER_TEMPLATES as V,require_dist$1 as Vi,registerAllTools as Vn,withSpan as Vr,formatContributors as Vt,SeedRootDirError as W,removeLastKnownHash as Wn,writeTargetVersion as Wr,getCurrentMcpLogger as Wt,applyExternalChange as X,resolveLockDir as Xn,isJSONRPCRequest as Xr,getMetrics as Xt,applyAgentMarkdownWrite as Y,resolveCursorSpawnInvocation as Yn,isInitializedNotification as Yr,getMeter as Yt,applySeed as Z,resolvePack as Zn,isJSONRPCResultResponse as Zr,getTracer as Zt,GIT_UPSTREAM_WRITER as _,SPAWN_ERROR_LOG as _i,isSystemDoc as _n,shadowGit as _r,contributorCount as _t,AgentPresenceBroadcaster as a,ALL_EDITOR_IDS as ai,installTestLoggers as an,runCloneSubprocess as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,defaultScheduler as bi,listStarterPacks as bn,splitMarkdownBlocks as br,createContentFilter as bt,BacklinkIndex as c,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ci,isAllowedWorkspaceHostHeader as cn,safeContentPath as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,EDITOR_LABELS as di,isKnownPackId as dn,sanitizeClientName as dr,coercePackId as dt,resolveConfigPath as ei,incrementCollabSocketFilteredError as en,restoreLifecycleFromConflictsJson as er,attachIdleShutdown as et,ConfigSchema as f,EXECUTABLE_BLOCKLIST_EXTENSIONS as fi,isLoopbackAddress as fn,saveInMemoryCheckpoint as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,SKILL_STATE_TARGETS as gi,isSelfWrite as gn,setActiveSpanAttributes as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,ProblemDetailsSchema as hi,isProjectRoot as hn,serializeError as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,MalformedGitPointerError as ii,installPrettyZodErrors as in,runAuthStatusSubprocess as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,array as ji,readBranchFromHead as jn,tracedRmSync as jr,createTestLogger as jt,McpLogger as k,ZodNumber$1 as ki,planSeed as kn,tracedRename as kr,createServerObserverExtension as kt,CC1Broadcaster as l,DEFAULT_SERVER_HOST as li,isConfigDoc as ln,safeSubdir as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,ORPHAN_MODES as mi,isPathWithinDir as mn,seedBasenameIndex as mr,commitWipFromTree as mt,AGENT_ID_RE as n,writeConfigPatch as ni,initShadowRepo as nn,rewriteWikiLinksForDocumentRename as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,ASSET_EXTENSIONS as oi,installUserSkill as on,runDeviceFlowSubprocess as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,INLINE_RENDERABLE_EXTENSIONS as pi,isPairedWriteOrigin as pn,saveVersion as pr,commitWip as pt,UiLockCollisionError as q,resolveContentDir as qn,JSONRPCMessageSchema as qr,getLogger as qt,AGENT_WRITE_ORIGIN as r,GitDirAccessError as ri,initTelemetry as rn,runAuthReposSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,CC1_CONTRACT_VERSION as si,isAllowedApiOrigin as sn,runWithMcpLogger as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,withFileLockSync as ti,incrementServerObserverFire as tn,rewriteMarkdownLinksForDocumentRename as tr,bootServer as tt,CONFLICT_MARKER_RE as u,DEFAULT_SIGTERM_GRACE_MS as ui,isHocuspocusAuthRejectionReason as un,safetyCheckpoint as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,SYSTEM_DOC_NAME as vi,lastKnownHash as vn,shutdownTelemetry as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,isOrphanMode as wi,normalizeFsPath as wn,toBroadcasterKey as wr,createLiveDerivedIndexExtension as wt,INSTALLED_AGENTS_SCHEMES as x,humanFormat as xi,loadPrincipal as xn,startWatcher as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,colorFromSeed as yi,listRescueCheckpoints as yn,spawnDetached as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,_coercedNumber as zi,recordContributor as zn,validateCloneInputs as zr,findEnclosingProjectRoot as zt};
|
|
3365
|
+
//# sourceMappingURL=dist-D4zoOvWC.mjs.map
|