likec4 1.59.3 → 1.59.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/__app__/src/chunks/AIChat.mjs +108 -108
  2. package/__app__/src/chunks/LikeC4Styles.mjs +752 -604
  3. package/__app__/src/chunks/ProjectsOverview.mjs +72 -72
  4. package/__app__/src/chunks/es.mjs +1 -1
  5. package/__app__/src/chunks/hooks.mjs +94 -91
  6. package/__app__/src/chunks/libs/@floating-ui.mjs +3 -3
  7. package/__app__/src/chunks/libs/@mantine.mjs +1609 -892
  8. package/__app__/src/chunks/libs/@tanstack-ai.mjs +2 -2
  9. package/__app__/src/chunks/libs/@tanstack.mjs +4 -10
  10. package/__app__/src/chunks/libs/@xyflow/react.mjs +4 -4
  11. package/__app__/src/chunks/libs/d3.mjs +4 -9
  12. package/__app__/src/chunks/libs/fast-equals.mjs +61 -49
  13. package/__app__/src/chunks/libs/framer.mjs +6 -6
  14. package/__app__/src/chunks/styled-system.mjs +2578 -124
  15. package/__app__/src/main.mjs +21537 -20155
  16. package/__app__/src/style.css +1 -1
  17. package/config/schema.json +14 -0
  18. package/dist/app/render-view-client.css +1 -1
  19. package/dist/app/render-view-client.js +99 -105
  20. package/dist/chunks/filenames.mjs +6 -6
  21. package/dist/chunks/index.d.mts +7 -1
  22. package/dist/chunks/index2.d.mts +38 -21
  23. package/dist/chunks/libs/@chevrotain/gast.mjs +1 -1
  24. package/dist/chunks/libs/@chevrotain/types.d.mts +108 -0
  25. package/dist/chunks/libs/@logtape/logtape.mjs +4 -4
  26. package/dist/chunks/libs/langium.d.mts +1777 -16
  27. package/dist/chunks/libs/langium.mjs +4 -4
  28. package/dist/chunks/libs/p-queue.mjs +1 -1
  29. package/dist/chunks/libs/package-manager-detector.mjs +1 -1
  30. package/dist/chunks/libs/pako.mjs +2 -2
  31. package/dist/chunks/libs/picomatch.mjs +1 -1
  32. package/dist/chunks/libs/pretty-ms.mjs +1 -1
  33. package/dist/chunks/libs/remeda.mjs +1 -1
  34. package/dist/chunks/libs/ufo.mjs +1 -1
  35. package/dist/chunks/libs/unstorage.mjs +1 -1
  36. package/dist/chunks/libs/zod.d.mts +1717 -17
  37. package/dist/chunks/node.mjs +58 -59
  38. package/dist/chunks/vite-plugin.mjs +15 -12
  39. package/dist/cli/index.d.mts +1 -1
  40. package/dist/cli/index.mjs +104 -88
  41. package/dist/index.d.mts +3 -3
  42. package/dist/model/index.d.mts +4 -4
  43. package/dist/vite-plugin/index.d.mts +2 -2
  44. package/dist/vite-plugin/internal/index.d.mts +15 -15
  45. package/dist/vite-plugin/internal/index.mjs +72 -27
  46. package/package.json +28 -28
  47. package/react/index.d.mts +22720 -1460
  48. package/react/index.mjs +30391 -25072
  49. package/vite-plugin-modules.d.ts +4 -2
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{c as e,i as t,o as n,t as r}from"../chunks/rolldown-runtime.mjs";import{C as i,E as a,S as s,T as c,_ as l,a as u,b as f,c as p,d as m,f as h,g,h as v,l as y,m as b,n as ee,o as te,p as ne,r as x,s as re,u as ie,v as ae,w as oe,y as S}from"../chunks/node.mjs";import{n as se}from"../chunks/sequence-view.mjs";import{H as ce,V as le,b as ue,f as de,g as fe,h as pe,s as me}from"../chunks/libs/langium.mjs";import{c as he,l as ge,o as _e,r as ve,s as ye}from"../chunks/libs/ufo.mjs";import{t as be}from"../chunks/libs/json5.mjs";import{B as xe,C,D as w,F as Se,H as Ce,I as we,L as Te,M as Ee,N as De,O as Oe,P as ke,R as Ae,S as je,T,U as Me,V as Ne,W as Pe,_ as Fe,a as Ie,b as E,c as Le,d as Re,f as ze,g as D,i as Be,j as Ve,k as He,l as O,m as Ue,n as We,o as Ge,r as Ke,s as qe,u as k,v as Je,x as Ye,y as A}from"../chunks/libs/zod.mjs";import{$ as Xe,J as Ze,N as Qe,P as $e,S as et,T as tt,X as nt,Z as rt,b as it,d as at,h as ot,o as st,r as ct,rt as ut,t as dt,tt as ft,u as pt,w as mt}from"../chunks/libs/remeda.mjs";import{t as ht}from"../chunks/libs/which.mjs";import{t as _t}from"../chunks/libs/pretty-ms.mjs";import{t as vt}from"../chunks/libs/picomatch.mjs";import{a as yt,c as bt,i as xt,l as St,n as Ct,o as wt,r as Tt,s as Et,t as Dt}from"../chunks/vite-plugin.mjs";import{n as Ot,t as kt}from"../chunks/libs/package-manager-detector.mjs";import{LikeC4Model as At}from"../model/index.mjs";import jt from"node:module";import{isDeepStrictEqual as Mt,promisify as Nt}from"node:util";import{copyFile as Pt,cp as Ft,mkdir as It,mkdtemp as Lt,readFile as Rt,readdir as zt,realpath as Bt,rm as Vt,stat as Ht,writeFile as Ut}from"node:fs/promises";import j,{basename as Wt,dirname as Gt,extname as Kt,isAbsolute as qt,join as Jt,relative as Yt,resolve as M,sep as Xt}from"node:path";import{hasProp as Zt,invariant as Qt,nonexhaustive as $t}from"@likec4/core";import{compareNatural as en,ifilter as tn,invariant as nn,isSameHierarchy as rn,sortNaturalByFqn as an}from"@likec4/core/utils";import{isDeploymentElementModel as on,isDeploymentNodeModel as sn,isDeploymentRelationModel as cn,isElementModel as ln,isLikeC4ViewModel as un,isRelationModel as dn,modelConnection as fn}from"@likec4/core/model";import pn from"nano-spawn";import mn,{tmpdir as hn}from"node:os";import N,{copyFileSync as gn,existsSync as _n,readFileSync as vn,readdirSync as yn,realpathSync as bn,rmSync as xn,statSync as Sn,writeFileSync as Cn}from"node:fs";import wn,{createHash as Tn,randomUUID as En}from"node:crypto";import Dn from"node:net";import{fileURLToPath as On,pathToFileURL as kn}from"node:url";import{env as An,isCI as jn,isDevelopment as Mn,isTest as Nn,nodeENV as Pn}from"std-env";import P,{argv as Fn,cwd as In,exit as Ln,hrtime as Rn,stdout as zn}from"node:process";import Bn from"yargs";import{hideBin as Vn}from"yargs/helpers";import Hn from"node:tty";import{build as Un,createServer as Wn,preview as Gn}from"vite";import{viteSingleFile as Kn}from"vite-plugin-singlefile";import qn from"node:assert";import Jn from"@vitejs/plugin-react";import{setTimeout as Yn}from"node:timers/promises";import{STATUS_CODES as Xn,createServer as Zn}from"node:http";import{Http2ServerRequest as Qn,constants as $n}from"node:http2";import{Readable as er}from"node:stream";import{gzipSync as tr}from"node:zlib";var nr=e(vt(),1),rr=e(ht(),1);function graphvizBinPath(){try{return rr.default.sync(`dot`)}catch(e){return h.error(`Error checking for native Graphviz:`,{error:e}),null}}const ir={likec4:{Layouter(e){h.debug(`Creating ConfigurableLayouter`);let t=e.likec4.Graphviz,n=new b({graphviz:t});return e.shared.workspace.ConfigurationProvider.onConfigurationSectionUpdate(t=>{if(h.debug(`Configuration update: {update}`,{update:t}),t.section!==e.LanguageMetaData.languageId){h.debug(`Ignoring configuration update as it is not for ${e.LanguageMetaData.languageId}`);return}try{let{mode:r,path:i}=t.configuration.graphviz??{mode:`wasm`,path:``};if(r!==`wasm`){let t=$e(i)?graphvizBinPath():i;if(!$e(t)){n.changePort(new ne(t)),h.info`use graphviz binary: ${t}`;return}h.warn(`No Graphviz binaries found on PATH, use graphviz wasm`),e.shared.lsp.Connection?.window.showWarningMessage(`No Graphviz binaries found on PATH, set path to binaries in settings.`)}n.changePort(new v),h.info(`use graphviz wasm`)}catch(e){h.error(`Failed to update configuration`,{error:e})}}),n}}};function startLanguageServer(e){let t=e?.connection,n=se(e,{enableWatcher:!0,enableManualLayouts:!0,graphviz:`wasm`,configureLogger:!1});n.configureLogger!==!1&&(n.configureLogger===`stderr`?m({lspConnection:t,enableTelemetry:!1,useStdErr:!0}):n.configureLogger===`console`&&m({lspConnection:t})),t?h.info(`Starting LikeC4 language server`):h.warn(`Starting LikeC4 language server (headless - no LSP connection)`);let r=u({...t&&{connection:t},...re(n.enableWatcher),...n.enableManualLayouts&&p,...te(n.graphviz===`binary`?new ne:new v)},t?{likec4:{...ir.likec4}}:void 0);return me(r.shared),r}function appendView(e,t){e.append(`### `,t.titleOrId,g,g),t.description.nonEmpty&&e.append(t.description.md,g,g),e.append("```mermaid",g,Tt(t).trimEnd(),g,"```",g,g)}function generateMarkdown(e,t={}){let n=new fe;n.append(`# `,e.project.title??e.projectId,g,g),t.description&&n.append(t.description,g,g);for(let t of e.views())t.$view.sourcePath!==void 0&&appendView(n,t);return l(n)}function toUnion(e){return Qe(e)?`never`:(typeof e==`object`&&!Array.isArray(e)&&(e=et(e)),ft(e,ct(),st(en),it(e=>` | ${JSON.stringify(e)}`)).join(`
3
- `).trimStart())}function elementIdToUnion(e){let t=ft(e,dt(),rt(e=>!!e&&mt(e.id)),an,it(e=>` | ${JSON.stringify(e.id)}`));return t.length===0?`never`:t.join(`
2
+ import{c as e,i as t,o as n,t as r}from"../chunks/rolldown-runtime.mjs";import{C as i,E as a,S as s,T as c,_ as l,a as u,b as f,c as p,d as m,f as h,g,h as v,l as y,m as b,n as ee,o as te,p as ne,r as x,s as re,u as ie,v as ae,w as oe,y as S}from"../chunks/node.mjs";import{n as se}from"../chunks/sequence-view.mjs";import{H as ce,V as le,b as ue,f as de,g as fe,h as pe,s as me}from"../chunks/libs/langium.mjs";import{c as he,l as ge,o as _e,r as ve,s as ye}from"../chunks/libs/ufo.mjs";import{t as be}from"../chunks/libs/json5.mjs";import{B as xe,C,D as w,F as Se,H as Ce,I as we,L as Te,M as Ee,N as De,O as T,P as Oe,R as ke,S as Ae,T as E,U as je,V as Me,W as Ne,_ as Pe,a as D,b as O,c as Fe,d as Ie,f as Le,g as k,i as Re,j as ze,k as Be,l as A,m as Ve,n as He,o as Ue,r as We,s as Ge,u as j,v as Ke,x as qe,y as M}from"../chunks/libs/zod.mjs";import{$ as Je,J as Ye,N as Xe,P as Ze,S as Qe,T as $e,X as et,Z as tt,b as nt,d as rt,h as it,o as at,r as ot,rt as st,t as ct,tt as ut,u as dt,w as ft}from"../chunks/libs/remeda.mjs";import{t as pt}from"../chunks/libs/which.mjs";import{t as mt}from"../chunks/libs/pretty-ms.mjs";import{t as ht}from"../chunks/libs/picomatch.mjs";import{a as _t,c as vt,i as yt,l as bt,n as xt,o as St,r as Ct,s as wt,t as Tt}from"../chunks/vite-plugin.mjs";import{n as Et,t as Dt}from"../chunks/libs/package-manager-detector.mjs";import{LikeC4Model as Ot}from"../model/index.mjs";import kt from"node:module";import{isDeepStrictEqual as At,promisify as jt}from"node:util";import{copyFile as Mt,cp as Nt,mkdir as Pt,mkdtemp as Ft,readFile as It,readdir as Lt,realpath as Rt,rm as zt,stat as Bt,writeFile as Vt}from"node:fs/promises";import N,{basename as Ht,dirname as Ut,extname as Wt,isAbsolute as Gt,join as Kt,relative as qt,resolve as P,sep as Jt}from"node:path";import{ProjectId as Yt}from"@likec4/core/types";import{FqnRef as Xt,GlobalFqn as Zt,hasProp as Qt,invariant as $t,nonexhaustive as en}from"@likec4/core";import{compareNatural as tn,ifilter as nn,invariant as rn,isSameHierarchy as an,sortNaturalByFqn as on}from"@likec4/core/utils";import{isDeploymentElementModel as sn,isDeploymentNodeModel as cn,isDeploymentRelationModel as ln,isElementModel as un,isLikeC4ViewModel as dn,isRelationModel as fn,modelConnection as pn}from"@likec4/core/model";import mn from"nano-spawn";import hn,{tmpdir as gn}from"node:os";import F,{copyFileSync as _n,existsSync as vn,readFileSync as yn,readdirSync as bn,realpathSync as xn,rmSync as Sn,statSync as Cn,writeFileSync as wn}from"node:fs";import Tn,{createHash as En,randomUUID as Dn}from"node:crypto";import On from"node:net";import{fileURLToPath as kn,pathToFileURL as An}from"node:url";import{env as jn,isCI as Mn,isDevelopment as Nn,isTest as Pn,nodeENV as Fn}from"std-env";import I,{argv as In,cwd as Ln,exit as Rn,hrtime as zn,stdout as Bn}from"node:process";import Vn from"yargs";import{hideBin as Hn}from"yargs/helpers";import Un from"node:tty";import{build as Wn,createServer as Gn,preview as Kn}from"vite";import{viteSingleFile as qn}from"vite-plugin-singlefile";import Jn from"node:assert";import Yn from"@vitejs/plugin-react";import{setTimeout as Xn}from"node:timers/promises";import{STATUS_CODES as Zn,createServer as Qn}from"node:http";import{Http2ServerRequest as $n,constants as er}from"node:http2";import{Readable as tr}from"node:stream";import{gzipSync as nr}from"node:zlib";var rr=e(ht(),1),ir=e(pt(),1);function graphvizBinPath(){try{return ir.default.sync(`dot`)}catch(e){return h.error(`Error checking for native Graphviz:`,{error:e}),null}}const ar={likec4:{Layouter(e){h.debug(`Creating ConfigurableLayouter`);let t=e.likec4.Graphviz,n=new b({graphviz:t});return e.shared.workspace.ConfigurationProvider.onConfigurationSectionUpdate(t=>{if(h.debug(`Configuration update: {update}`,{update:t}),t.section!==e.LanguageMetaData.languageId){h.debug(`Ignoring configuration update as it is not for ${e.LanguageMetaData.languageId}`);return}try{let{mode:r,path:i}=t.configuration.graphviz??{mode:`wasm`,path:``};if(r!==`wasm`){let t=Ze(i)?graphvizBinPath():i;if(!Ze(t)){n.changePort(new ne(t)),h.info`use graphviz binary: ${t}`;return}h.warn(`No Graphviz binaries found on PATH, use graphviz wasm`),e.shared.lsp.Connection?.window.showWarningMessage(`No Graphviz binaries found on PATH, set path to binaries in settings.`)}n.changePort(new v),h.info(`use graphviz wasm`)}catch(e){h.error(`Failed to update configuration`,{error:e})}}),n}}};function startLanguageServer(e){let t=e?.connection,n=se(e,{enableWatcher:!0,enableManualLayouts:!0,graphviz:`wasm`,configureLogger:!1});n.configureLogger!==!1&&(n.configureLogger===`stderr`?m({lspConnection:t,enableTelemetry:!1,useStdErr:!0}):n.configureLogger===`console`&&m({lspConnection:t})),t?h.info(`Starting LikeC4 language server`):h.warn(`Starting LikeC4 language server (headless - no LSP connection)`);let r=u({...t&&{connection:t},...re(n.enableWatcher),...n.enableManualLayouts&&p,...te(n.graphviz===`binary`?new ne:new v)},t?{likec4:{...ar.likec4}}:void 0);return me(r.shared),r}function appendView(e,t){e.append(`### `,t.titleOrId,g,g),t.description.nonEmpty&&e.append(t.description.md,g,g),e.append("```mermaid",g,Ct(t).trimEnd(),g,"```",g,g)}function generateMarkdown(e,t={}){let n=new fe;n.append(`# `,e.project.title??e.projectId,g,g),t.description&&n.append(t.description,g,g);for(let t of e.views())t.$view.sourcePath!==void 0&&appendView(n,t);return l(n)}function toUnion(e){return Xe(e)?`never`:(typeof e==`object`&&!Array.isArray(e)&&(e=Qe(e)),ut(e,ot(),at(tn),nt(e=>` | ${JSON.stringify(e)}`)).join(`
3
+ `).trimStart())}function elementIdToUnion(e){let t=ut(e,ct(),tt(e=>!!e&&ft(e.id)),on,nt(e=>` | ${JSON.stringify(e.id)}`));return t.length===0?`never`:t.join(`
4
4
  `).trimStart()}function generateAux(e,t={}){let{useCorePackage:n=!1}=t;return`
5
5
  import type { Aux, SpecAux } from '${n?`@likec4/core/types`:`likec4/model`}';
6
6
 
@@ -81,7 +81,7 @@ export const likec4model: LikeC4Model<$Aux> = new LikeC4Model(${be.stringify(e.$
81
81
  }
82
82
 
83
83
  /* prettier-ignore-end */
84
- `.append(g),l(n))}function generateReactTypes(e,t={}){let{useCorePackage:n=!1}=t;nn(!e.isParsed(),`can not generate react types for parsed model`);let r=generateAux(e,t);return`
84
+ `.append(g),l(n))}function generateReactTypes(e,t={}){let{useCorePackage:n=!1}=t;rn(!e.isParsed(),`can not generate react types for parsed model`);let r=generateAux(e,t);return`
85
85
  /* prettier-ignore-start */
86
86
  /* eslint-disable */
87
87
 
@@ -137,20 +137,20 @@ export {
137
137
  ReactLikeC4
138
138
  }
139
139
  /* prettier-ignore-end */
140
- `.trimStart()}var ar=`likec4`,sr=`1.59.3`;function ansiRegex({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const cr=ansiRegex();function stripAnsi(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(cr,``)}function isAmbiguous(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}function isFullWidth(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}function isWide(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101631&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}function validate(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function eastAsianWidth(e,{ambiguousAsWide:t=!1}={}){return validate(e),isFullWidth(e)||isWide(e)||t&&isAmbiguous(e)?2:1}var lr=t(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,`default`);const ur=new Intl.Segmenter,dr=/^\p{Default_Ignorable_Code_Point}$/u;function stringWidth(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=stripAnsi(e)),e.length===0)return 0;let i=0,a={ambiguousAsWide:!n};for(let{segment:t}of ur.segment(e)){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159)&&!(e>=8203&&e<=8207||e===65279)&&!(e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071)&&!(e>=55296&&e<=57343)&&!(e>=65024&&e<=65039)&&!dr.test(t)){if(lr().test(t)){i+=2;continue}i+=eastAsianWidth(e,a)}}return i}const fr=t((e=0)=>t=>`\u001B[${t+e}m`,`wrapAnsi16`),pr=t((e=0)=>t=>`\u001B[${38+e};5;${t}m`,`wrapAnsi256`),mr=t((e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,`wrapAnsi16m`),F={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(F.modifier);const hr=Object.keys(F.color),gr=Object.keys(F.bgColor);[...hr,...gr];function assembleStyles$1(){let e=new Map;for(let[t,n]of Object.entries(F)){for(let[t,r]of Object.entries(n))F[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=F[t],e.set(r[0],r[1]);Object.defineProperty(F,t,{value:n,enumerable:!1})}return Object.defineProperty(F,"codes",{value:e,enumerable:!1}),F.color.close=`\x1B[39m`,F.bgColor.close=`\x1B[49m`,F.color.ansi=fr(),F.color.ansi256=pr(),F.color.ansi16m=mr(),F.bgColor.ansi=fr(10),F.bgColor.ansi256=pr(10),F.bgColor.ansi16m=mr(10),Object.defineProperties(F,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>F.rgbToAnsi256(...F.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>F.ansi256ToAnsi(F.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>F.ansi256ToAnsi(F.hexToAnsi256(e)),enumerable:!1}}),F}t(assembleStyles$1,`assembleStyles`);const _r=assembleStyles$1();function hasFlag(e,t=globalThis.Deno?globalThis.Deno.args:P.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:vr}=P;let yr;hasFlag(`no-color`)||hasFlag(`no-colors`)||hasFlag(`color=false`)||hasFlag(`color=never`)?yr=0:(hasFlag(`color`)||hasFlag(`colors`)||hasFlag(`color=true`)||hasFlag(`color=always`))&&(yr=1);function envForceColor(){if(`FORCE_COLOR`in vr)return vr.FORCE_COLOR===`true`?1:vr.FORCE_COLOR===`false`?0:vr.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(vr.FORCE_COLOR,10),3)}function translateLevel(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function _supportsColor(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=envForceColor();r!==void 0&&(yr=r);let i=n?yr:r;if(i===0)return 0;if(n){if(hasFlag(`color=16m`)||hasFlag(`color=full`)||hasFlag(`color=truecolor`))return 3;if(hasFlag(`color=256`))return 2}if(`TF_BUILD`in vr&&`AGENT_NAME`in vr)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(vr.TERM===`dumb`)return a;if(P.platform===`win32`){let e=mn.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in vr)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in vr)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in vr)||vr.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in vr)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(vr.TEAMCITY_VERSION);if(vr.COLORTERM===`truecolor`||vr.TERM===`xterm-kitty`)return 3;if(`TERM_PROGRAM`in vr){let e=Number.parseInt((vr.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(vr.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(vr.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(vr.TERM)||`COLORTERM`in vr?1:a}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}const br={stdout:createSupportsColor({isTTY:Hn.isatty(1)}),stderr:createSupportsColor({isTTY:Hn.isatty(2)})};function stringReplaceAll(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,s=``;do s+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return s+=e.slice(a),s}function stringEncaseCRLFWithFirstIndex(e,t,n,r){let i=0,a=``;do{let s=e[r-1]===`\r`;a+=e.slice(i,s?r-1:r)+t+(s?`\r
140
+ `.trimStart()}var sr=`likec4`,cr=`1.59.4`;function ansiRegex({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const lr=ansiRegex();function stripAnsi(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(lr,``)}function isAmbiguous(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}function isFullWidth(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}function isWide(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101631&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}function validate(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function eastAsianWidth(e,{ambiguousAsWide:t=!1}={}){return validate(e),isFullWidth(e)||isWide(e)||t&&isAmbiguous(e)?2:1}var ur=t(()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,`default`);const dr=new Intl.Segmenter,fr=/^\p{Default_Ignorable_Code_Point}$/u;function stringWidth(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=stripAnsi(e)),e.length===0)return 0;let i=0,a={ambiguousAsWide:!n};for(let{segment:t}of dr.segment(e)){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159)&&!(e>=8203&&e<=8207||e===65279)&&!(e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071)&&!(e>=55296&&e<=57343)&&!(e>=65024&&e<=65039)&&!fr.test(t)){if(ur().test(t)){i+=2;continue}i+=eastAsianWidth(e,a)}}return i}const pr=t((e=0)=>t=>`\u001B[${t+e}m`,`wrapAnsi16`),mr=t((e=0)=>t=>`\u001B[${38+e};5;${t}m`,`wrapAnsi256`),hr=t((e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,`wrapAnsi16m`),L={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(L.modifier);const gr=Object.keys(L.color),_r=Object.keys(L.bgColor);[...gr,..._r];function assembleStyles$1(){let e=new Map;for(let[t,n]of Object.entries(L)){for(let[t,r]of Object.entries(n))L[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=L[t],e.set(r[0],r[1]);Object.defineProperty(L,t,{value:n,enumerable:!1})}return Object.defineProperty(L,"codes",{value:e,enumerable:!1}),L.color.close=`\x1B[39m`,L.bgColor.close=`\x1B[49m`,L.color.ansi=pr(),L.color.ansi256=mr(),L.color.ansi16m=hr(),L.bgColor.ansi=pr(10),L.bgColor.ansi256=mr(10),L.bgColor.ansi16m=hr(10),Object.defineProperties(L,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>L.rgbToAnsi256(...L.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>L.ansi256ToAnsi(L.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>L.ansi256ToAnsi(L.hexToAnsi256(e)),enumerable:!1}}),L}t(assembleStyles$1,`assembleStyles`);const vr=assembleStyles$1();function hasFlag(e,t=globalThis.Deno?globalThis.Deno.args:I.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:R}=I;let yr;hasFlag(`no-color`)||hasFlag(`no-colors`)||hasFlag(`color=false`)||hasFlag(`color=never`)?yr=0:(hasFlag(`color`)||hasFlag(`colors`)||hasFlag(`color=true`)||hasFlag(`color=always`))&&(yr=1);function envForceColor(){if(`FORCE_COLOR`in R)return R.FORCE_COLOR===`true`?1:R.FORCE_COLOR===`false`?0:R.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(R.FORCE_COLOR,10),3)}function translateLevel(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function _supportsColor(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=envForceColor();r!==void 0&&(yr=r);let i=n?yr:r;if(i===0)return 0;if(n){if(hasFlag(`color=16m`)||hasFlag(`color=full`)||hasFlag(`color=truecolor`))return 3;if(hasFlag(`color=256`))return 2}if(`TF_BUILD`in R&&`AGENT_NAME`in R)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(R.TERM===`dumb`)return a;if(I.platform===`win32`){let e=hn.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in R)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in R)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in R)||R.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in R)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(R.TEAMCITY_VERSION);if(R.COLORTERM===`truecolor`||R.TERM===`xterm-kitty`)return 3;if(`TERM_PROGRAM`in R){let e=Number.parseInt((R.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(R.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(R.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(R.TERM)||`COLORTERM`in R?1:a}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}const br={stdout:createSupportsColor({isTTY:Un.isatty(1)}),stderr:createSupportsColor({isTTY:Un.isatty(2)})};function stringReplaceAll(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,s=``;do s+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return s+=e.slice(a),s}function stringEncaseCRLFWithFirstIndex(e,t,n,r){let i=0,a=``;do{let s=e[r-1]===`\r`;a+=e.slice(i,s?r-1:r)+t+(s?`\r
141
141
  `:`
142
142
  `)+n,i=r+1,r=e.indexOf(`
143
- `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:xr,stderr:Sr}=br,Cr=Symbol(`GENERATOR`),wr=Symbol(`STYLER`),Tr=Symbol(`IS_EMPTY`),Er=[`ansi`,`ansi`,`ansi256`,`ansi16m`],Dr=Object.create(null),applyOptions=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=xr?xr.level:0;e.level=t.level===void 0?n:t.level},chalkFactory=e=>{let chalk=(...e)=>e.join(` `);return applyOptions(chalk,e),Object.setPrototypeOf(chalk,createChalk.prototype),chalk};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(_r))Dr[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[wr]),this[Tr]);return Object.defineProperty(this,e,{value:n}),n}};Dr.visible={get(){let e=createBuilder(this,this[wr],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const getModelAnsi=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?_r[n].ansi16m(...r):t===`ansi256`?_r[n].ansi256(_r.rgbToAnsi256(...r)):_r[n].ansi(_r.rgbToAnsi(...r)):e===`hex`?getModelAnsi(`rgb`,t,n,..._r.hexToRgb(...r)):_r[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){Dr[e]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,Er[t],`color`,...n),_r.color.close,this[wr]);return createBuilder(this,r,this[Tr])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);Dr[t]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,Er[t],`bgColor`,...n),_r.bgColor.close,this[wr]);return createBuilder(this,r,this[Tr])}}}}const Or=Object.defineProperties(()=>{},{...Dr,level:{enumerable:!0,get(){return this[Cr].level},set(e){this[Cr].level=e}}}),createStyler=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},createBuilder=(e,t,n)=>{let builder=(...e)=>applyStyle(builder,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(builder,Or),builder[Cr]=e,builder[wr]=t,builder[Tr]=n,builder},applyStyle=(e,t)=>{if(e.level<=0||!t)return e[Tr]?``:t;let n=e[wr];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=stringReplaceAll(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
143
+ `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:xr,stderr:Sr}=br,Cr=Symbol(`GENERATOR`),wr=Symbol(`STYLER`),Tr=Symbol(`IS_EMPTY`),Er=[`ansi`,`ansi`,`ansi256`,`ansi16m`],Dr=Object.create(null),applyOptions=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=xr?xr.level:0;e.level=t.level===void 0?n:t.level},chalkFactory=e=>{let chalk=(...e)=>e.join(` `);return applyOptions(chalk,e),Object.setPrototypeOf(chalk,createChalk.prototype),chalk};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(vr))Dr[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[wr]),this[Tr]);return Object.defineProperty(this,e,{value:n}),n}};Dr.visible={get(){let e=createBuilder(this,this[wr],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const getModelAnsi=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?vr[n].ansi16m(...r):t===`ansi256`?vr[n].ansi256(vr.rgbToAnsi256(...r)):vr[n].ansi(vr.rgbToAnsi(...r)):e===`hex`?getModelAnsi(`rgb`,t,n,...vr.hexToRgb(...r)):vr[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){Dr[e]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,Er[t],`color`,...n),vr.color.close,this[wr]);return createBuilder(this,r,this[Tr])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);Dr[t]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,Er[t],`bgColor`,...n),vr.bgColor.close,this[wr]);return createBuilder(this,r,this[Tr])}}}}const Or=Object.defineProperties(()=>{},{...Dr,level:{enumerable:!0,get(){return this[Cr].level},set(e){this[Cr].level=e}}}),createStyler=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},createBuilder=(e,t,n)=>{let builder=(...e)=>applyStyle(builder,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(builder,Or),builder[Cr]=e,builder[wr]=t,builder[Tr]=n,builder},applyStyle=(e,t)=>{if(e.level<=0||!t)return e[Tr]?``:t;let n=e[wr];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=stringReplaceAll(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
144
144
  `);return a!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,i,r,a)),r+t+i};Object.defineProperties(createChalk.prototype,Dr);const kr=createChalk();createChalk({level:Sr?Sr.level:0});function widestLine(e){let t=0;for(let n of e.split(`
145
145
  `))t=Math.max(t,stringWidth(n));return t}var Ar=r(((e,t)=>{t.exports={single:{topLeft:`┌`,top:`─`,topRight:`┐`,right:`│`,bottomRight:`┘`,bottom:`─`,bottomLeft:`└`,left:`│`},double:{topLeft:`╔`,top:`═`,topRight:`╗`,right:`║`,bottomRight:`╝`,bottom:`═`,bottomLeft:`╚`,left:`║`},round:{topLeft:`╭`,top:`─`,topRight:`╮`,right:`│`,bottomRight:`╯`,bottom:`─`,bottomLeft:`╰`,left:`│`},bold:{topLeft:`┏`,top:`━`,topRight:`┓`,right:`┃`,bottomRight:`┛`,bottom:`━`,bottomLeft:`┗`,left:`┃`},singleDouble:{topLeft:`╓`,top:`─`,topRight:`╖`,right:`║`,bottomRight:`╜`,bottom:`─`,bottomLeft:`╙`,left:`║`},doubleSingle:{topLeft:`╒`,top:`═`,topRight:`╕`,right:`│`,bottomRight:`╛`,bottom:`═`,bottomLeft:`╘`,left:`│`},classic:{topLeft:`+`,top:`-`,topRight:`+`,right:`|`,bottomRight:`+`,bottom:`-`,bottomLeft:`+`,left:`|`},arrow:{topLeft:`↘`,top:`↓`,topRight:`↙`,right:`←`,bottomRight:`↖`,bottom:`↑`,bottomLeft:`↗`,left:`→`}}})),jr=e(r(((e,t)=>{let n=Ar();t.exports=n,t.exports.default=n}))(),1);const Mr=/[\p{Lu}]/u,Nr=/[\p{Ll}]/u,Pr=/^[\p{Lu}](?![\p{Lu}])/gu,Fr=/([\p{Alpha}\p{N}_]|$)/u,Ir=/[_.\- ]+/,Lr=RegExp(`^`+Ir.source),Rr=new RegExp(Ir.source+Fr.source,`gu`),zr=RegExp(`\\d+`+Fr.source,`gu`),preserveCamelCase=(e,t,n,r)=>{let i=!1,a=!1,s=!1,c=!1;for(let l=0;l<e.length;l++){let u=e[l];c=l>2?e[l-3]===`-`:!0,i&&Mr.test(u)?(e=e.slice(0,l)+`-`+e.slice(l),i=!1,s=a,a=!0,l++):a&&s&&Nr.test(u)&&(!c||r)?(e=e.slice(0,l-1)+`-`+e.slice(l-1),s=a,a=!1,i=!0):(i=t(u)===u&&n(u)!==u,s=a,a=n(u)===u&&t(u)!==u)}return e},preserveConsecutiveUppercase=(e,t)=>(Pr.lastIndex=0,e.replaceAll(Pr,e=>t(e))),postProcess=(e,t)=>(Rr.lastIndex=0,zr.lastIndex=0,e.replaceAll(zr,(n,r,i)=>[`_`,`-`].includes(e.charAt(i+n.length))?n:t(n)).replaceAll(Rr,(e,n)=>t(n)));function camelCase(e,t){if(!(typeof e==`string`||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join(`-`):e.trim(),e.length===0)return``;let n=t.locale===!1?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),r=t.locale===!1?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return e.length===1?Ir.test(e)?``:t.pascalCase?r(e):n(e):(e!==n(e)&&(e=preserveCamelCase(e,n,r,t.preserveConsecutiveUppercase)),e=e.replace(Lr,``),e=t.preserveConsecutiveUppercase?preserveConsecutiveUppercase(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),postProcess(e,r))}var Br=r(((e,t)=>{t.exports=({onlyFirst:e=!1}={})=>{let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}})),Vr=r(((e,t)=>{let n=Br();t.exports=e=>typeof e==`string`?e.replace(n(),``):e})),Hr=r(((e,t)=>{let isFullwidthCodePoint=e=>!Number.isNaN(e)&&e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);t.exports=isFullwidthCodePoint,t.exports.default=isFullwidthCodePoint})),Ur=r(((e,t)=>{t.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}})),Wr=r(((e,t)=>{let n=Vr(),r=Hr(),i=Ur(),stringWidth=e=>{if(typeof e!=`string`||e.length===0||(e=n(e),e.length===0))return 0;e=e.replace(i(),` `);let t=0;for(let n=0;n<e.length;n++){let i=e.codePointAt(n);i<=31||i>=127&&i<=159||i>=768&&i<=879||(i>65535&&n++,t+=r(i)?2:1)}return t};t.exports=stringWidth,t.exports.default=stringWidth})),Gr=e(r(((e,t)=>{let n=Wr();function ansiAlign(e,t){if(!e)return e;t||={};let r=t.align||`center`;if(r===`left`)return e;let i=t.split||`
146
- `,a=t.pad||` `,s=r===`right`?fullDiff:halfDiff,c=!1;Array.isArray(e)||(c=!0,e=String(e).split(i));let l,u=0;return e=e.map(function(e){return e=String(e),l=n(e),u=Math.max(l,u),{str:e,width:l}}).map(function(e){return Array(s(u,e.width)+1).join(a)+e.str}),c?e.join(i):e}ansiAlign.left=function left(e){return ansiAlign(e,{align:`left`})},ansiAlign.center=function center(e){return ansiAlign(e,{align:`center`})},ansiAlign.right=function right(e){return ansiAlign(e,{align:`right`})},t.exports=ansiAlign;function halfDiff(e,t){return Math.floor((e-t)/2)}function fullDiff(e,t){return e-t}}))(),1);const wrapAnsi16=(e=0)=>t=>`\u001B[${t+e}m`,wrapAnsi256=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,I={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(I.modifier);const Kr=Object.keys(I.color),qr=Object.keys(I.bgColor);[...Kr,...qr];function assembleStyles(){let e=new Map;for(let[t,n]of Object.entries(I)){for(let[t,r]of Object.entries(n))I[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=I[t],e.set(r[0],r[1]);Object.defineProperty(I,t,{value:n,enumerable:!1})}return Object.defineProperty(I,"codes",{value:e,enumerable:!1}),I.color.close=`\x1B[39m`,I.bgColor.close=`\x1B[49m`,I.color.ansi=wrapAnsi16(),I.color.ansi256=wrapAnsi256(),I.color.ansi16m=wrapAnsi16m(),I.bgColor.ansi=wrapAnsi16(10),I.bgColor.ansi256=wrapAnsi256(10),I.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(I,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>I.rgbToAnsi256(...I.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>I.ansi256ToAnsi(I.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>I.ansi256ToAnsi(I.hexToAnsi256(e)),enumerable:!1}}),I}const Jr=assembleStyles(),Yr=new Set([`\x1B`,`›`]),Xr=`]8;;`,wrapAnsiCode=e=>`${Yr.values().next().value}[${e}m`,wrapAnsiHyperlink=e=>`${Yr.values().next().value}${Xr}${e}`,wordLengths=e=>e.split(` `).map(e=>stringWidth(e)),wrapWord=(e,t,n)=>{let r=[...t],i=!1,a=!1,s=stringWidth(stripAnsi(e.at(-1)));for(let[t,c]of r.entries()){let l=stringWidth(c);if(s+l<=n?e[e.length-1]+=c:(e.push(c),s=0),Yr.has(c)&&(i=!0,a=r.slice(t+1,t+1+4).join(``)===Xr),i){a?c===`\x07`&&(i=!1,a=!1):c===`m`&&(i=!1);continue}s+=l,s===n&&t<r.length-1&&(e.push(``),s=0)}!s&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},stringVisibleTrimSpacesRight=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(stringWidth(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},exec=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,s=wordLengths(e),c=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(c[c.length-1]=c.at(-1).trimStart());let e=stringWidth(c.at(-1));if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(c.push(``),e=0),(e>0||n.trim===!1)&&(c[c.length-1]+=` `,e++)),n.hard&&s[r]>t){let n=t-e,a=1+Math.floor((s[r]-n-1)/t);Math.floor((s[r]-1)/t)<a&&c.push(``),wrapWord(c,i,t);continue}if(e+s[r]>t&&e>0&&s[r]>0){if(n.wordWrap===!1&&e<t){wrapWord(c,i,t);continue}c.push(``)}if(e+s[r]>t&&n.wordWrap===!1){wrapWord(c,i,t);continue}c[c.length-1]+=i}n.trim!==!1&&(c=c.map(e=>stringVisibleTrimSpacesRight(e)));let l=c.join(`
146
+ `,a=t.pad||` `,s=r===`right`?fullDiff:halfDiff,c=!1;Array.isArray(e)||(c=!0,e=String(e).split(i));let l,u=0;return e=e.map(function(e){return e=String(e),l=n(e),u=Math.max(l,u),{str:e,width:l}}).map(function(e){return Array(s(u,e.width)+1).join(a)+e.str}),c?e.join(i):e}ansiAlign.left=function left(e){return ansiAlign(e,{align:`left`})},ansiAlign.center=function center(e){return ansiAlign(e,{align:`center`})},ansiAlign.right=function right(e){return ansiAlign(e,{align:`right`})},t.exports=ansiAlign;function halfDiff(e,t){return Math.floor((e-t)/2)}function fullDiff(e,t){return e-t}}))(),1);const wrapAnsi16=(e=0)=>t=>`\u001B[${t+e}m`,wrapAnsi256=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,z={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(z.modifier);const Kr=Object.keys(z.color),qr=Object.keys(z.bgColor);[...Kr,...qr];function assembleStyles(){let e=new Map;for(let[t,n]of Object.entries(z)){for(let[t,r]of Object.entries(n))z[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=z[t],e.set(r[0],r[1]);Object.defineProperty(z,t,{value:n,enumerable:!1})}return Object.defineProperty(z,"codes",{value:e,enumerable:!1}),z.color.close=`\x1B[39m`,z.bgColor.close=`\x1B[49m`,z.color.ansi=wrapAnsi16(),z.color.ansi256=wrapAnsi256(),z.color.ansi16m=wrapAnsi16m(),z.bgColor.ansi=wrapAnsi16(10),z.bgColor.ansi256=wrapAnsi256(10),z.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(z,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>z.rgbToAnsi256(...z.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>z.ansi256ToAnsi(z.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>z.ansi256ToAnsi(z.hexToAnsi256(e)),enumerable:!1}}),z}const Jr=assembleStyles(),Yr=new Set([`\x1B`,`›`]),Xr=`]8;;`,wrapAnsiCode=e=>`${Yr.values().next().value}[${e}m`,wrapAnsiHyperlink=e=>`${Yr.values().next().value}${Xr}${e}`,wordLengths=e=>e.split(` `).map(e=>stringWidth(e)),wrapWord=(e,t,n)=>{let r=[...t],i=!1,a=!1,s=stringWidth(stripAnsi(e.at(-1)));for(let[t,c]of r.entries()){let l=stringWidth(c);if(s+l<=n?e[e.length-1]+=c:(e.push(c),s=0),Yr.has(c)&&(i=!0,a=r.slice(t+1,t+1+4).join(``)===Xr),i){a?c===`\x07`&&(i=!1,a=!1):c===`m`&&(i=!1);continue}s+=l,s===n&&t<r.length-1&&(e.push(``),s=0)}!s&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop())},stringVisibleTrimSpacesRight=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(stringWidth(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},exec=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,s=wordLengths(e),c=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(c[c.length-1]=c.at(-1).trimStart());let e=stringWidth(c.at(-1));if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(c.push(``),e=0),(e>0||n.trim===!1)&&(c[c.length-1]+=` `,e++)),n.hard&&s[r]>t){let n=t-e,a=1+Math.floor((s[r]-n-1)/t);Math.floor((s[r]-1)/t)<a&&c.push(``),wrapWord(c,i,t);continue}if(e+s[r]>t&&e>0&&s[r]>0){if(n.wordWrap===!1&&e<t){wrapWord(c,i,t);continue}c.push(``)}if(e+s[r]>t&&n.wordWrap===!1){wrapWord(c,i,t);continue}c[c.length-1]+=i}n.trim!==!1&&(c=c.map(e=>stringVisibleTrimSpacesRight(e)));let l=c.join(`
147
147
  `),u=[...l],f=0;for(let[e,t]of u.entries()){if(r+=t,Yr.has(t)){let{groups:e}=RegExp(`(?:\\[(?<code>\\d+)m|\\${Xr}(?<uri>.*))`).exec(l.slice(f))||{groups:{}};if(e.code!==void 0){let t=Number.parseFloat(e.code);i=t===39?void 0:t}else e.uri!==void 0&&(a=e.uri.length===0?void 0:e.uri)}let n=Jr.codes.get(Number(i));u[e+1]===`
148
148
  `?(a&&(r+=wrapAnsiHyperlink(``)),i&&n&&(r+=wrapAnsiCode(n))):t===`
149
149
  `&&(i&&n&&(r+=wrapAnsiCode(i)),a&&(r+=wrapAnsiHyperlink(a))),f+=t.length}return r};function wrapAnsi(e,t,n){return String(e).normalize().replaceAll(`\r
150
150
  `,`
151
151
  `).split(`
152
152
  `).map(e=>exec(e,t,n)).join(`
153
- `)}const Zr=`none`,terminalColumns=()=>{let{env:e,stdout:t,stderr:n}=P;return t?.columns?t.columns:n?.columns?n.columns:e.COLUMNS?Number.parseInt(e.COLUMNS,10):80},getObject=e=>typeof e==`number`?{top:e,right:e*3,bottom:e,left:e*3}:{top:0,right:0,bottom:0,left:0,...e},getBorderWidth=e=>e===Zr?0:2,getBorderChars=e=>{let t=[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`,`left`,`right`,`top`,`bottom`],n;if(e===Zr){e={};for(let n of t)e[n]=``}if(typeof e==`string`){if(n=jr.default[e],!n)throw TypeError(`Invalid border style: ${e}`)}else{typeof e?.vertical==`string`&&(e.left=e.vertical,e.right=e.vertical),typeof e?.horizontal==`string`&&(e.top=e.horizontal,e.bottom=e.horizontal);for(let n of t)if(e[n]===null||typeof e[n]!=`string`)throw TypeError(`Invalid border style: ${n}`);n=e}return n},makeTitle=(e,t,n)=>{let r=``,i=stringWidth(e);switch(n){case`left`:r=e+t.slice(i);break;case`right`:r=t.slice(i)+e;break;default:t=t.slice(i),t.length%2==1?(t=t.slice(Math.floor(t.length/2)),r=t.slice(1)+e+t):(t=t.slice(t.length/2),r=t+e+t)}return r},makeContentText=(e,{padding:t,width:n,textAlignment:r,height:i})=>{e=(0,Gr.default)(e,{align:r});let a=e.split(`
153
+ `)}const Zr=`none`,terminalColumns=()=>{let{env:e,stdout:t,stderr:n}=I;return t?.columns?t.columns:n?.columns?n.columns:e.COLUMNS?Number.parseInt(e.COLUMNS,10):80},getObject=e=>typeof e==`number`?{top:e,right:e*3,bottom:e,left:e*3}:{top:0,right:0,bottom:0,left:0,...e},getBorderWidth=e=>e===Zr?0:2,getBorderChars=e=>{let t=[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`,`left`,`right`,`top`,`bottom`],n;if(e===Zr){e={};for(let n of t)e[n]=``}if(typeof e==`string`){if(n=jr.default[e],!n)throw TypeError(`Invalid border style: ${e}`)}else{typeof e?.vertical==`string`&&(e.left=e.vertical,e.right=e.vertical),typeof e?.horizontal==`string`&&(e.top=e.horizontal,e.bottom=e.horizontal);for(let n of t)if(e[n]===null||typeof e[n]!=`string`)throw TypeError(`Invalid border style: ${n}`);n=e}return n},makeTitle=(e,t,n)=>{let r=``,i=stringWidth(e);switch(n){case`left`:r=e+t.slice(i);break;case`right`:r=t.slice(i)+e;break;default:t=t.slice(i),t.length%2==1?(t=t.slice(Math.floor(t.length/2)),r=t.slice(1)+e+t):(t=t.slice(t.length/2),r=t+e+t)}return r},makeContentText=(e,{padding:t,width:n,textAlignment:r,height:i})=>{e=(0,Gr.default)(e,{align:r});let a=e.split(`
154
154
  `),s=widestLine(e),c=n-t.left-t.right;if(s>c){let e=[];for(let t of a){let n=wrapAnsi(t,c,{hard:!0}),i=(0,Gr.default)(n,{align:r}).split(`
155
155
  `),a=Math.max(...i.map(e=>stringWidth(e)));for(let t of i){let n;switch(r){case`center`:n=` `.repeat((c-a)/2)+t;break;case`right`:n=` `.repeat(c-a)+t;break;default:n=t}e.push(n)}}a=e}r===`center`&&s<c?a=a.map(e=>` `.repeat((c-s)/2)+e):r===`right`&&s<c&&(a=a.map(e=>` `.repeat(c-s)+e));let l=` `.repeat(t.left),u=` `.repeat(t.right);return a=a.map(e=>{let t=l+e+u;return t+` `.repeat(n-stringWidth(t))}),t.top>0&&(a=[...Array.from({length:t.top}).fill(` `.repeat(n)),...a]),t.bottom>0&&(a=[...a,...Array.from({length:t.bottom}).fill(` `.repeat(n))]),i&&a.length>i?a=a.slice(0,i):i&&a.length<i&&(a=[...a,...Array.from({length:i-a.length}).fill(` `.repeat(n))]),a.join(`
156
156
  `)},boxContent=(e,t,n)=>{let colorizeBorder=e=>{let t=n.borderColor?getColorFunction(n.borderColor)(e):e;return n.dimBorder?kr.dim(t):t},colorizeContent=e=>n.backgroundColor?getBGColorFunction(n.backgroundColor)(e):e,r=getBorderChars(n.borderStyle),i=terminalColumns(),a=` `.repeat(n.margin.left);if(n.float===`center`){let e=Math.max((i-t-getBorderWidth(n.borderStyle))/2,0);a=` `.repeat(e)}else if(n.float===`right`){let e=Math.max(i-t-n.margin.right-getBorderWidth(n.borderStyle),0);a=` `.repeat(e)}let s=``;n.margin.top&&(s+=`
@@ -159,19 +159,19 @@ export {
159
159
  `);return s+=c.map(e=>a+colorizeBorder(r.left)+colorizeContent(e)+colorizeBorder(r.right)).join(`
160
160
  `),n.borderStyle!==Zr&&(s+=`
161
161
  `+colorizeBorder(a+r.bottomLeft+r.bottom.repeat(t)+r.bottomRight)),n.margin.bottom&&(s+=`
162
- `.repeat(n.margin.bottom)),s},sanitizeOptions=e=>{if(e.fullscreen&&P?.stdout){let t=[P.stdout.columns,P.stdout.rows];typeof e.fullscreen==`function`&&(t=e.fullscreen(...t)),e.width||=t[0],e.height||=t[1]}return e.width&&=Math.max(1,e.width-getBorderWidth(e.borderStyle)),e.height&&=Math.max(1,e.height-getBorderWidth(e.borderStyle)),e},formatTitle=(e,t)=>t===Zr?e:` ${e} `,determineDimensions=(e,t)=>{t=sanitizeOptions(t);let n=t.width!==void 0,r=terminalColumns(),i=getBorderWidth(t.borderStyle),a=r-t.margin.left-t.margin.right-i,s=widestLine(wrapAnsi(e,r-i,{hard:!0,trim:!1}))+t.padding.left+t.padding.right;if(t.title&&n?(t.title=t.title.slice(0,Math.max(0,t.width-2)),t.title&&=formatTitle(t.title,t.borderStyle)):t.title&&(t.title=t.title.slice(0,Math.max(0,a-2)),t.title&&(t.title=formatTitle(t.title,t.borderStyle),stringWidth(t.title)>s&&(t.width=stringWidth(t.title)))),t.width||=s,!n){if(t.margin.left&&t.margin.right&&t.width>a){let e=(r-t.width-i)/(t.margin.left+t.margin.right);t.margin.left=Math.max(0,Math.floor(t.margin.left*e)),t.margin.right=Math.max(0,Math.floor(t.margin.right*e))}t.width=Math.min(t.width,r-i-t.margin.left-t.margin.right)}return t.width-(t.padding.left+t.padding.right)<=0&&(t.padding.left=0,t.padding.right=0),t.height&&t.height-(t.padding.top+t.padding.bottom)<=0&&(t.padding.top=0,t.padding.bottom=0),t},isHex=e=>e.match(/^#(?:[0-f]{3}){1,2}$/i),isColorValid=e=>typeof e==`string`&&(kr[e]??isHex(e)),getColorFunction=e=>isHex(e)?kr.hex(e):kr[e],getBGColorFunction=e=>isHex(e)?kr.bgHex(e):kr[camelCase([`bg`,e])];function boxen$1(e,t){if(t={padding:0,borderStyle:`single`,dimBorder:!1,textAlignment:`left`,float:`left`,titleAlignment:`left`,...t},t.align&&(t.textAlignment=t.align),t.borderColor&&!isColorValid(t.borderColor))throw Error(`${t.borderColor} is not a valid borderColor`);if(t.backgroundColor&&!isColorValid(t.backgroundColor))throw Error(`${t.backgroundColor} is not a valid backgroundColor`);return t.padding=getObject(t.padding),t.margin=getObject(t.margin),t=determineDimensions(e,t),e=makeContentText(e,t),boxContent(e,t.width,t)}t(boxen$1,`boxen`);const Qr=s.getChild(`cli`);function createLikeC4Logger(e){let t=s.getChild(e);return{info(e){t.info(e)},debug(e,...n){n.length===0?t.debug(e):t.debug(e,{args:n})},warn(e){if(e instanceof Error){t.warn(`${S.red(e.name+` `+e.message)}`,{msg:e});return}if(typeof e==`string`){t.warn(e);return}t.warn`${e}`},warnOnce(e){t.warn(e)},error(e,n){let r=n?.error??e;if(r instanceof Error){if(e===r){t.error(`${S.red(r.name+` `+r.message)}`,{error:r});return}t.error(S.red(e),{error:r});return}if(typeof e==`string`){t.error(S.red(e));return}t.error`${e}`},clearScreen:function(e){},hasErrorLogged:function(e){return!1},hasWarned:!1}}function inMillis(e){let[t,n]=Rn(e),r=t*1e3+n/1e6;return{ms:r,pretty:_t(r)}}function startTimer(e){let t=Rn();return{stopAndLog(n=`done in `){n=S.green(`${n}${inMillis(t).pretty}`),(e||Qr).info(n)}}}function boxen(e,t){console.log(boxen$1(e,{padding:1,margin:1,dimBorder:!0,...t}))}const toPath=e=>e instanceof URL?On(e):e;function findUpSync(e,{cwd:t=P.cwd(),type:n=`file`,stopAt:r}={}){let i=j.resolve(toPath(t)??``),{root:a}=j.parse(i);for(r=j.resolve(i,toPath(r)??a);i&&i!==r&&i!==a;){let t=j.isAbsolute(e)?e:j.join(i,e);try{let e=N.statSync(t,{throwIfNoEntry:!1});if(n===`file`&&e?.isFile()||n===`directory`&&e?.isDirectory())return t}catch{}i=j.dirname(i)}}function packageUpSync({cwd:e=P.cwd()}={}){return findUpSync(`package.json`,{cwd:e})}const $r=createLikeC4Logger(`vite`),ei=Gt(On(import.meta.url));function findPkgRoot(){let e=packageUpSync({cwd:ei});if(!e)throw Error(`likec4 package folder not found`);return Gt(e)}function viteAppRoot(){let e=findPkgRoot(),t=[M(e,`__app__`),M(ei,`../__app__`),M(ei,`../../__app__`),M(ei,`../../dist/__app__`)],n=nt(t,_n);if(!n)throw s.error(`likec4 app root does not exist, tried:\n${t.join(`
163
- `)}`),Error(`likec4 app root does not exist`);return n}async function mkTempPublicDir(){let e=await Lt(Jt(hn(),`.likec4-public-`));return await Ut(Jt(e,`likec4-views.js`),`// generated by likec4
164
- `),e}function relativeToCwd(e){return Yt(In(),e)}async function copyUserPublicDir(e,t){if(!_n(e))throw Error(`--public directory does not exist: ${e}`);if(!Sn(e).isDirectory())throw Error(`--public path is not a directory: ${e}`);let n=await zt(e);return await Ft(e,t,{recursive:!0,errorOnExist:!1}),n}function viteAliases(){let e=findPkgRoot();return{"likec4/react":M(e,`react/index.mjs`),"likec4/model":M(e,`dist/model/index.mjs`),"likec4/vite-plugin/internal":M(e,`dist/vite-plugin/internal/index.mjs`)}}const viteConfig=async({languageServices:e,likec4AssetsDir:t,...n})=>{let r=n.customLogger??$r,i=viteAppRoot();r.info(`${S.cyan(`likec4 app root`)} ${S.dim(relativeToCwd(i))}`);let a=n.outputDir??M(e.workspace,`dist`);r.info(S.cyan(`outDir`)+` `+S.dim(relativeToCwd(a)));let s=`/`;n.base&&(s=ge(n.base),!ve(s)&&s!==`./`&&(s=ye(s))),s!==`/`&&r.info(`${S.green(`app base url`)} ${S.dim(s)}`);let c=n.webcomponentPrefix??`likec4`,l=n.title??`LikeC4`,u=n.outputSingleFile??!1;return{isDev:Mn,likec4AssetsDir:t,webcomponentPrefix:c,title:l,root:i,languageServices:e,clearScreen:!1,base:s,resolve:{alias:{...viteAliases(),"likec4/previews":t}},configFile:!1,mode:`production`,define:{"process.env.NODE_ENV":`"production"`},build:{outDir:a,emptyOutDir:!1,sourcemap:!1,minify:!0,copyPublicDir:!0,chunkSizeWarningLimit:2048,...!u&&{rolldownOptions:{input:[M(i,`index.html`),M(i,`src`,`main.mjs`),M(i,`src`,`fonts.css`),M(i,`src`,`style.css`)]}}},customLogger:r,plugins:[Dt({languageServices:e.languageServices,appConfig:{webcomponentPrefix:c,pageTitle:l,useHashHistory:n.useHashHistory,theme:n.theme}}),u?Kn():void 0]}};function viteWebcomponentConfig({languageServices:e,outDir:t,base:n,webcomponentPrefix:r=`likec4`,filename:i=`likec4-views.js`}){let a=createLikeC4Logger([`vite`,`webcomponent`]),s=viteAppRoot();return a.info(S.cyan(`outDir`)+` `+S.dim(t)),{root:s,clearScreen:!1,base:n,configFile:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases()},define:{"process.env.NODE_ENV":`"production"`},build:{outDir:t,emptyOutDir:!1,sourcemap:!1,minify:!0,assetsInlineLimit:512e3,chunkSizeWarningLimit:3072,lib:{entry:`codegen/webcomponent.mjs`,fileName(e,t){return i},formats:[`iife`],name:`LikeC4Views`}},customLogger:a,plugins:[Dt({ai:`disabled`,languageServices:e.languageServices,appConfig:{webcomponentPrefix:r}})]}}const ti=[`favicon.ico`,`robots.txt`];function removeAllButPreserved(e,t){let n=new Set(t);for(let t of yn(e).filter(e=>!n.has(e)))xn(M(e,t),{recursive:!0})}const ni={".svg":`image/svg+xml`,".ico":`image/x-icon`,".png":`image/png`,".gif":`image/gif`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`};function inlineSingleFileFavicon(e){let t=M(e,`index.html`);if(!_n(t))return;let n=vn(t,`utf8`),r=/<link\b[^>]*\brel=(["'])icon\1[^>]*>/i.exec(n)?.[0];if(!r)return;let i=/\bhref=(["'])([^"']*)\1/i,a=i.exec(r)?.[2];if(!a||a.startsWith(`data:`)||/^(https?:)?\/\//i.test(a))return;let s=M(e,a.replace(/^\.?\//,``));if(!_n(s))return;let c=`data:${ni[Kt(s).toLowerCase()]??`application/octet-stream`};base64,${vn(s).toString(`base64`)}`,l=r.replace(i,(e,t)=>`href=${t}${c}${t}`);Cn(t,n.replace(r,l))}async function viteBuild({buildWebcomponent:e=!0,webcomponentPrefix:t=`likec4`,title:n,languageServices:r,likec4AssetsDir:i,outputSingleFile:a,userPublicDir:s,...c}){i??=await Lt(Jt(hn(),`.likec4-assets-`));let l=await viteConfig({...c,languageServices:r,likec4AssetsDir:i,webcomponentPrefix:t,title:n,outputSingleFile:a}),u=!_n(l.build.outDir)||yn(l.build.outDir).length===0,f=await mkTempPublicDir(),p=s?await copyUserPublicDir(s,f):[];for(let e of ti){let t=M(l.root,e);_n(t)&&gn(t,M(f,e))}let m=r.languageServices.projects();if(m.length===1){let e=await r.viewsService.computedViews(),t=await r.diagrams();if(t.length===0)throw process.exitCode=1,Error(`no views found`);t.length===e.length?l.customLogger.info(`${S.dim(`workspace:`)} ${S.green(`✓ all views layouted`)}`):l.customLogger.warn(`${S.dim(`workspace:`)} ${S.yellow(`✗ layouted ${t.length} of ${e.length} views`)}`),t.forEach(e=>{(e.hasLayoutDrift||e.drifts&&e.drifts.length>0)&&l.customLogger.warn(S.dim(`view`)+` `+S.red(e.id)+` `+S.yellow(`is out of date, layout drift detected`))});let n=m[0].config.landingPage;if(n&&(`include`in n||`exclude`in n)){let e=`include`in n?n.include:n.exclude;t.some(t=>e.some(e=>e.startsWith(`#`)?t.tags?.some(t=>t===e.slice(1)):t.id===e))||l.customLogger.warn(S.dim(`landingPage:`)+` `+S.yellow(`no views match the configured filter`))}}else for(let e of m){let t=await r.viewsService.computedViews(e.id);t.length===0?l.customLogger.warn(`${S.dim(`project:`)} ${e.id} ${S.yellow(`✗ no views found`)}`):l.customLogger.info(`${S.dim(`project:`)} ${e.id} ${S.green(`${t.length} views`)}`);let n=await r.diagrams(e.id),i=e.config.landingPage;if(i&&(`include`in i||`exclude`in i)){let t=`include`in i?i.include:i.exclude;n.some(e=>t.some(t=>t.startsWith(`#`)?e.tags?.some(e=>e===t.slice(1)):e.id===t))||l.customLogger.warn(`${S.dim(`project:`)} ${e.id} ${S.yellow(`landingPage: no views match the configured filter`)}`)}}if(e&&!a){let e=viteWebcomponentConfig({webcomponentPrefix:t,languageServices:r,outDir:f,base:l.base});await Un(e)}if(await Un({...l,publicDir:f}),a){if(!u){l.customLogger.warn(S.yellow(`outDir was not empty, skipping cleanup`));return}inlineSingleFileFavicon(l.build.outDir),removeAllButPreserved(l.build.outDir,[`index.html`,...p])}let h=M(l.build.outDir,`index.html`);_n(h)&&gn(h,M(l.build.outDir,`404.html`))}let ri;function hasDockerEnv(){try{return N.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return N.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return ri===void 0&&(ri=hasDockerEnv()||hasDockerCGroup()),ri}let ii;const hasContainerEnv=()=>{try{return N.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return ii===void 0&&(ii=hasContainerEnv()||isDocker()),ii}var HTTPError=class extends Error{response;request;options;constructor(e,t,n){let r=`${e.status||e.status===0?e.status:``} ${e.statusText??``}`.trim(),i=r?`status code ${r}`:`an unknown error`;super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name=`HTTPError`,this.response=e,this.request=t,this.options=n}},NonError=class extends Error{name=`NonError`;value;constructor(e){let t=`Non-error value was thrown`;try{typeof e==`string`?t=e:e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`&&(t=e.message)}catch{}super(t),this.value=e}},ForceRetryError=class extends Error{name=`ForceRetryError`;customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new NonError(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:`Forced retry`,t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};const ai=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream==`function`,r=typeof globalThis.Request==`function`;if(n&&r)try{t=new globalThis.Request(`https://empty.invalid`,{body:new globalThis.ReadableStream,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`)}catch(e){if(e instanceof Error&&e.message===`unsupported BodyInit type`)return!1;throw e}return e&&!t})(),oi=typeof globalThis.AbortController==`function`,si=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,ci=typeof globalThis.ReadableStream==`function`,li=typeof globalThis.FormData==`function`,ui=[`get`,`post`,`put`,`patch`,`head`,`delete`],di={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},fi=2147483647,pi=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,mi=Symbol(`stop`);var RetryMarker=class{options;constructor(e){this.options=e}};const retry=e=>new RetryMarker(e),hi={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},gi={next:!0},_i={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},getBodySize=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=pi,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r==`string`?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e==`string`)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(`byteLength`in e)return e.byteLength;if(typeof e==`object`&&e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},withProgress=(e,t,n)=>{let r,i=0;return e.pipeThrough(new TransformStream({transform(e,a){if(a.enqueue(e),r){i+=r.byteLength;let e=t===0?0:i/t;e>=1&&(e=1-2**-52),n?.({percent:e,totalBytes:Math.max(t,i),transferredBytes:i},r)}r=e},flush(){r&&(i+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},r))}}))},streamResponse=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get(`content-length`))||0);return new Response(withProgress(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},streamRequest=(e,t,n)=>{if(!e.body)return e;let r=getBodySize(n??e.body);return new Request(e,{duplex:`half`,body:withProgress(e.body,r,t)})},vi=t(e=>typeof e==`object`&&!!e,`isObject`),validateAndMerge=(...e)=>{for(let t of e)if((!vi(t)||Array.isArray(t))&&t!==void 0)throw TypeError("The `options` argument must be an object");return deepMerge({},...e)},mergeHeaders=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[e,t]of i.entries())r&&t===`undefined`||t===void 0?n.delete(e):n.set(e,t);return n};function newHookValue(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:deepMerge(e[n]??[],t[n]??[])}const mergeHooks=(e={},t={})=>({beforeRequest:newHookValue(e,t,`beforeRequest`),beforeRetry:newHookValue(e,t,`beforeRetry`),afterResponse:newHookValue(e,t,`afterResponse`),beforeError:newHookValue(e,t,`beforeError`)}),appendSearchParameters=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0){if(r instanceof URLSearchParams)for(let[e,t]of r.entries())n.append(e,t);else if(Array.isArray(r))for(let e of r){if(!Array.isArray(e)||e.length!==2)throw TypeError(`Array search parameters must be provided in [[key, value], ...] format`);n.append(String(e[0]),String(e[1]))}else if(vi(r))for(let[e,t]of Object.entries(r))t!==void 0&&n.append(e,String(t));else{let e=new URLSearchParams(r);for(let[t,r]of e.entries())n.append(t,r)}}return n},deepMerge=(...e)=>{let t={},n={},r={},i,a=[];for(let s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(vi(s)){for(let[e,n]of Object.entries(s)){if(e===`signal`&&n instanceof globalThis.AbortSignal){a.push(n);continue}if(e===`context`){if(n!=null&&(!vi(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}};continue}if(e===`searchParams`){i=n==null?void 0:i===void 0?n:appendSearchParameters(i,n);continue}vi(n)&&e in t&&(n=deepMerge(t[e],n)),t={...t,[e]:n}}vi(s.hooks)&&(r=mergeHooks(r,s.hooks),t.hooks=r),vi(s.headers)&&(n=mergeHeaders(n,s.headers),t.headers=n)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:si?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},normalizeRequestMethod=e=>ui.includes(e)?e.toUpperCase():e,yi={limit:2,methods:[`get`,`put`,`head`,`delete`,`options`,`trace`],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},normalizeRetryOptions=(e={})=>{if(typeof e==`number`)return{...yi,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error(`retry.methods must be an array`);if(e.methods&&=e.methods.map(e=>e.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw Error(`retry.statusCodes must be an array`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return{...yi,...t}};var TimeoutError=class extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name=`TimeoutError`,this.request=e}};async function timeout$1(e,t,n,r){return new Promise((i,a)=>{let s=setTimeout(()=>{n&&n.abort(),a(new TimeoutError(e))},r.timeout);r.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(s)})})}t(timeout$1,`timeout`);async function delay$1(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener(`abort`,abortHandler,{once:!0}));function abortHandler(){clearTimeout(i),r(t.reason)}let i=setTimeout(()=>{t?.removeEventListener(`abort`,abortHandler),n()},e)})}t(delay$1,`delay`);const findUnknownOptions=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in _i)&&!(r in hi)&&(!(r in e)||r in gi)&&(n[r]=t[r]);return n},hasSearchParameters=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e==`object`?Object.keys(e).length>0:typeof e==`string`?e.trim().length>0:!!e;function isHTTPError(e){return e instanceof HTTPError||e?.name===HTTPError.name}function isTimeoutError(e){return e instanceof TimeoutError||e?.name===TimeoutError.name}var bi=class Ky{static create(e,t){let n=new Ky(e,t),function_=async()=>{if(typeof n.#i.timeout==`number`&&n.#i.timeout>2147483647)throw RangeError(`The \`timeout\` option cannot be greater than ${fi}`);await Promise.resolve();let e=await n.#m();for(let t of n.#i.hooks.afterResponse){let r=n.#u(e.clone()),i;try{i=await t(n.request,n.#h(),r,{retryCount:n.#n})}catch(t){throw n.#f(r),n.#f(e),t}if(i instanceof RetryMarker)throw n.#f(r),n.#f(e),new ForceRetryError(i.options);let a=i instanceof globalThis.Response?i:e;r!==a&&n.#f(r),e!==a&&n.#f(e),e=a}if(n.#u(e),!e.ok&&(typeof n.#i.throwHttpErrors==`function`?n.#i.throwHttpErrors(e.status):n.#i.throwHttpErrors)){let t=new HTTPError(e,n.request,n.#h());for(let e of n.#i.hooks.beforeError)t=await e(t,{retryCount:n.#n});throw t}if(n.#i.onDownloadProgress){if(typeof n.#i.onDownloadProgress!=`function`)throw TypeError("The `onDownloadProgress` option must be a function");if(!ci)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");let t=e.clone();return n.#f(e),streamResponse(t,n.#i.onDownloadProgress)}return e},r=n.#p(function_).finally(()=>{let e=n.#a;n.#d(e?.body??void 0),n.#d(n.request.body??void 0)});for(let[e,i]of Object.entries(di))(e!==`bytes`||typeof globalThis.Response?.prototype?.bytes==`function`)&&(r[e]=async()=>{n.request.headers.set(`accept`,n.request.headers.get(`accept`)||i);let a=await r;if(e===`json`){if(a.status===204)return``;let e=await a.text();return e===``?``:t.parseJson?t.parseJson(e):JSON.parse(e)}return a[e]()});return r}static#e(e){return e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):e}request;#t;#n=0;#r;#i;#a;#o;#s;constructor(e,t={}){if(this.#r=e,this.#i={...t,headers:mergeHeaders(this.#r.headers,t.headers),hooks:mergeHooks({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:normalizeRequestMethod(t.method??this.#r.method??`GET`),prefixUrl:String(t.prefixUrl||``),retry:normalizeRetryOptions(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#r!=`string`&&!(this.#r instanceof URL||this.#r instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#i.prefixUrl&&typeof this.#r==`string`){if(this.#r.startsWith(`/`))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#i.prefixUrl.endsWith(`/`)||(this.#i.prefixUrl+=`/`),this.#r=this.#i.prefixUrl+this.#r}oi&&si&&(this.#o=this.#i.signal??this.#r.signal,this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal),ai&&(this.#i.duplex=`half`),this.#i.json!==void 0&&(this.#i.body=this.#i.stringifyJson?.(this.#i.json)??JSON.stringify(this.#i.json),this.#i.headers.set(`content-type`,this.#i.headers.get(`content-type`)??`application/json`));let n=t.headers&&new globalThis.Headers(t.headers).has(`content-type`);if(this.#r instanceof globalThis.Request&&(li&&this.#i.body instanceof globalThis.FormData||this.#i.body instanceof URLSearchParams)&&!n&&this.#i.headers.delete(`content-type`),this.request=new globalThis.Request(this.#r,this.#i),hasSearchParameters(this.#i.searchParams)){let e=`?`+(typeof this.#i.searchParams==`string`?this.#i.searchParams.replace(/^\?/,``):new URLSearchParams(Ky.#e(this.#i.searchParams)).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);this.request=new globalThis.Request(t,this.#i)}if(this.#i.onUploadProgress){if(typeof this.#i.onUploadProgress!=`function`)throw TypeError("The `onUploadProgress` option must be a function");if(!ai)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#_(this.request,this.#i.body??void 0)}}#c(){let e=this.#i.retry.delay(this.#n),t=e;this.#i.retry.jitter===!0?t=Math.random()*e:typeof this.#i.retry.jitter==`function`&&(t=this.#i.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e));let n=this.#i.retry.backoffLimit??1/0;return Math.min(n,t)}async#l(e){if(this.#n++,this.#n>this.#i.retry.limit)throw e;let t=e instanceof Error?e:new NonError(e);if(t instanceof ForceRetryError)return t.customDelay??this.#c();if(!this.#i.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#i.retry.shouldRetry!==void 0){let n=await this.#i.retry.shouldRetry({error:t,retryCount:this.#n});if(n===!1)throw e;if(n===!0)return this.#c()}if(isTimeoutError(e)&&!this.#i.retry.retryOnTimeout)throw e;if(isHTTPError(e)){if(!this.#i.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get(`Retry-After`)??e.response.headers.get(`RateLimit-Reset`)??e.response.headers.get(`X-RateLimit-Retry-After`)??e.response.headers.get(`X-RateLimit-Reset`)??e.response.headers.get(`X-Rate-Limit-Reset`);if(t&&this.#i.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t)*1e3;Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse(`2024-01-01`)&&(e-=Date.now());let n=this.#i.retry.maxRetryAfter??e;return e<n?e:n}if(e.response.status===413)throw e}return this.#c()}#u(e){return this.#i.parseJson&&(e.json=async()=>this.#i.parseJson(await e.text())),e}#d(e){e&&e.cancel().catch(()=>void 0)}#f(e){this.#d(e.body??void 0)}async#p(e){try{return await e()}catch(t){let n=Math.min(await this.#l(t),fi);if(this.#n<1)throw t;if(await delay$1(n,this.#o?{signal:this.#o}:{}),t instanceof ForceRetryError&&t.customRequest){let e=this.#i.signal?new globalThis.Request(t.customRequest,{signal:this.#i.signal}):new globalThis.Request(t.customRequest);this.#g(e)}for(let e of this.#i.hooks.beforeRetry){let n=await e({request:this.request,options:this.#h(),error:t,retryCount:this.#n});if(n instanceof globalThis.Request){this.#g(n);break}if(n instanceof globalThis.Response)return n;if(n===mi)return}return this.#p(e)}}async#m(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#i.signal}));for(let e of this.#i.hooks.beforeRequest){let t=await e(this.request,this.#h(),{retryCount:this.#n});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#g(t);break}}let e=findUnknownOptions(this.request,this.#i);return this.#a=this.request,this.request=this.#a.clone(),this.#i.timeout===!1?this.#i.fetch(this.#a,e):timeout$1(this.#a,e,this.#t,this.#i)}#h(){if(!this.#s){let{hooks:e,...t}=this.#i;this.#s=Object.freeze(t)}return this.#s}#g(e){this.#s=void 0,this.request=this.#_(e)}#_(e,t){return!this.#i.onUploadProgress||!e.body?e:streamRequest(e,this.#i.onUploadProgress,t??this.#i.body??void 0)}};
162
+ `.repeat(n.margin.bottom)),s},sanitizeOptions=e=>{if(e.fullscreen&&I?.stdout){let t=[I.stdout.columns,I.stdout.rows];typeof e.fullscreen==`function`&&(t=e.fullscreen(...t)),e.width||=t[0],e.height||=t[1]}return e.width&&=Math.max(1,e.width-getBorderWidth(e.borderStyle)),e.height&&=Math.max(1,e.height-getBorderWidth(e.borderStyle)),e},formatTitle=(e,t)=>t===Zr?e:` ${e} `,determineDimensions=(e,t)=>{t=sanitizeOptions(t);let n=t.width!==void 0,r=terminalColumns(),i=getBorderWidth(t.borderStyle),a=r-t.margin.left-t.margin.right-i,s=widestLine(wrapAnsi(e,r-i,{hard:!0,trim:!1}))+t.padding.left+t.padding.right;if(t.title&&n?(t.title=t.title.slice(0,Math.max(0,t.width-2)),t.title&&=formatTitle(t.title,t.borderStyle)):t.title&&(t.title=t.title.slice(0,Math.max(0,a-2)),t.title&&(t.title=formatTitle(t.title,t.borderStyle),stringWidth(t.title)>s&&(t.width=stringWidth(t.title)))),t.width||=s,!n){if(t.margin.left&&t.margin.right&&t.width>a){let e=(r-t.width-i)/(t.margin.left+t.margin.right);t.margin.left=Math.max(0,Math.floor(t.margin.left*e)),t.margin.right=Math.max(0,Math.floor(t.margin.right*e))}t.width=Math.min(t.width,r-i-t.margin.left-t.margin.right)}return t.width-(t.padding.left+t.padding.right)<=0&&(t.padding.left=0,t.padding.right=0),t.height&&t.height-(t.padding.top+t.padding.bottom)<=0&&(t.padding.top=0,t.padding.bottom=0),t},isHex=e=>e.match(/^#(?:[0-f]{3}){1,2}$/i),isColorValid=e=>typeof e==`string`&&(kr[e]??isHex(e)),getColorFunction=e=>isHex(e)?kr.hex(e):kr[e],getBGColorFunction=e=>isHex(e)?kr.bgHex(e):kr[camelCase([`bg`,e])];function boxen$1(e,t){if(t={padding:0,borderStyle:`single`,dimBorder:!1,textAlignment:`left`,float:`left`,titleAlignment:`left`,...t},t.align&&(t.textAlignment=t.align),t.borderColor&&!isColorValid(t.borderColor))throw Error(`${t.borderColor} is not a valid borderColor`);if(t.backgroundColor&&!isColorValid(t.backgroundColor))throw Error(`${t.backgroundColor} is not a valid backgroundColor`);return t.padding=getObject(t.padding),t.margin=getObject(t.margin),t=determineDimensions(e,t),e=makeContentText(e,t),boxContent(e,t.width,t)}t(boxen$1,`boxen`);const Qr=s.getChild(`cli`);function createLikeC4Logger(e){let t=s.getChild(e);return{info(e){t.info(e)},debug(e,...n){n.length===0?t.debug(e):t.debug(e,{args:n})},warn(e){if(e instanceof Error){t.warn(`${S.red(e.name+` `+e.message)}`,{msg:e});return}if(typeof e==`string`){t.warn(e);return}t.warn`${e}`},warnOnce(e){t.warn(e)},error(e,n){let r=n?.error??e;if(r instanceof Error){if(e===r){t.error(`${S.red(r.name+` `+r.message)}`,{error:r});return}t.error(S.red(e),{error:r});return}if(typeof e==`string`){t.error(S.red(e));return}t.error`${e}`},clearScreen:function(e){},hasErrorLogged:function(e){return!1},hasWarned:!1}}function inMillis(e){let[t,n]=zn(e),r=t*1e3+n/1e6;return{ms:r,pretty:mt(r)}}function startTimer(e){let t=zn();return{stopAndLog(n=`done in `){n=S.green(`${n}${inMillis(t).pretty}`),(e||Qr).info(n)}}}function boxen(e,t){console.log(boxen$1(e,{padding:1,margin:1,dimBorder:!0,...t}))}const toPath=e=>e instanceof URL?kn(e):e;function findUpSync(e,{cwd:t=I.cwd(),type:n=`file`,stopAt:r}={}){let i=N.resolve(toPath(t)??``),{root:a}=N.parse(i);for(r=N.resolve(i,toPath(r)??a);i&&i!==r&&i!==a;){let t=N.isAbsolute(e)?e:N.join(i,e);try{let e=F.statSync(t,{throwIfNoEntry:!1});if(n===`file`&&e?.isFile()||n===`directory`&&e?.isDirectory())return t}catch{}i=N.dirname(i)}}function packageUpSync({cwd:e=I.cwd()}={}){return findUpSync(`package.json`,{cwd:e})}const $r=createLikeC4Logger(`vite`),ei=Ut(kn(import.meta.url));function findPkgRoot(){let e=packageUpSync({cwd:ei});if(!e)throw Error(`likec4 package folder not found`);return Ut(e)}function viteAppRoot(){let e=findPkgRoot(),t=[P(e,`__app__`),P(ei,`../__app__`),P(ei,`../../__app__`),P(ei,`../../dist/__app__`)],n=et(t,vn);if(!n)throw s.error(`likec4 app root does not exist, tried:\n${t.join(`
163
+ `)}`),Error(`likec4 app root does not exist`);return n}async function mkTempPublicDir(){let e=await Ft(Kt(gn(),`.likec4-public-`));return await Vt(Kt(e,`likec4-views.js`),`// generated by likec4
164
+ `),e}function relativeToCwd(e){return qt(Ln(),e)}async function copyUserPublicDir(e,t){if(!vn(e))throw Error(`--public directory does not exist: ${e}`);if(!Cn(e).isDirectory())throw Error(`--public path is not a directory: ${e}`);let n=await Lt(e);return await Nt(e,t,{recursive:!0,errorOnExist:!1}),n}function viteAliases(){let e=findPkgRoot();return{"likec4/react":P(e,`react/index.mjs`),"likec4/model":P(e,`dist/model/index.mjs`),"likec4/vite-plugin/internal":P(e,`dist/vite-plugin/internal/index.mjs`)}}const viteConfig=async({languageServices:e,likec4AssetsDir:t,...n})=>{let r=n.customLogger??$r,i=viteAppRoot();r.info(`${S.cyan(`likec4 app root`)} ${S.dim(relativeToCwd(i))}`);let a=n.outputDir??P(e.workspace,`dist`);r.info(S.cyan(`outDir`)+` `+S.dim(relativeToCwd(a)));let s=`/`;n.base&&(s=ge(n.base),!ve(s)&&s!==`./`&&(s=ye(s))),s!==`/`&&r.info(`${S.green(`app base url`)} ${S.dim(s)}`);let c=n.webcomponentPrefix??`likec4`,l=n.title??`LikeC4`,u=n.outputSingleFile??!1;return{isDev:Nn,likec4AssetsDir:t,webcomponentPrefix:c,title:l,root:i,languageServices:e,clearScreen:!1,base:s,resolve:{alias:{...viteAliases(),"likec4/previews":t}},configFile:!1,mode:`production`,define:{"process.env.NODE_ENV":`"production"`},build:{outDir:a,emptyOutDir:!1,sourcemap:!1,minify:!0,copyPublicDir:!0,chunkSizeWarningLimit:2048,...!u&&{rolldownOptions:{input:[P(i,`index.html`),P(i,`src`,`main.mjs`),P(i,`src`,`fonts.css`),P(i,`src`,`style.css`)]}}},customLogger:r,plugins:[Tt({languageServices:e.languageServices,appConfig:{webcomponentPrefix:c,pageTitle:l,useHashHistory:n.useHashHistory,theme:n.theme}}),u?qn():void 0]}};function viteWebcomponentConfig({languageServices:e,outDir:t,base:n,webcomponentPrefix:r=`likec4`,filename:i=`likec4-views.js`}){let a=createLikeC4Logger([`vite`,`webcomponent`]),s=viteAppRoot();return a.info(S.cyan(`outDir`)+` `+S.dim(t)),{root:s,clearScreen:!1,base:n,configFile:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases()},define:{"process.env.NODE_ENV":`"production"`},build:{outDir:t,emptyOutDir:!1,sourcemap:!1,minify:!0,assetsInlineLimit:512e3,chunkSizeWarningLimit:3072,lib:{entry:`codegen/webcomponent.mjs`,fileName(e,t){return i},formats:[`iife`],name:`LikeC4Views`}},customLogger:a,plugins:[Tt({ai:`disabled`,languageServices:e.languageServices,appConfig:{webcomponentPrefix:r}})]}}const ti=[`favicon.ico`,`robots.txt`];function removeAllButPreserved(e,t){let n=new Set(t);for(let t of bn(e).filter(e=>!n.has(e)))Sn(P(e,t),{recursive:!0})}const ni={".svg":`image/svg+xml`,".ico":`image/x-icon`,".png":`image/png`,".gif":`image/gif`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`};function inlineSingleFileFavicon(e){let t=P(e,`index.html`);if(!vn(t))return;let n=yn(t,`utf8`),r=/<link\b[^>]*\brel=(["'])icon\1[^>]*>/i.exec(n)?.[0];if(!r)return;let i=/\bhref=(["'])([^"']*)\1/i,a=i.exec(r)?.[2];if(!a||a.startsWith(`data:`)||/^(https?:)?\/\//i.test(a))return;let s=P(e,a.replace(/^\.?\//,``));if(!vn(s))return;let c=`data:${ni[Wt(s).toLowerCase()]??`application/octet-stream`};base64,${yn(s).toString(`base64`)}`,l=r.replace(i,(e,t)=>`href=${t}${c}${t}`);wn(t,n.replace(r,l))}async function viteBuild({buildWebcomponent:e=!0,webcomponentPrefix:t=`likec4`,title:n,languageServices:r,likec4AssetsDir:i,outputSingleFile:a,userPublicDir:s,...c}){i??=await Ft(Kt(gn(),`.likec4-assets-`));let l=await viteConfig({...c,languageServices:r,likec4AssetsDir:i,webcomponentPrefix:t,title:n,outputSingleFile:a}),u=!vn(l.build.outDir)||bn(l.build.outDir).length===0,f=await mkTempPublicDir(),p=s?await copyUserPublicDir(s,f):[];for(let e of ti){let t=P(l.root,e);vn(t)&&_n(t,P(f,e))}let m=r.languageServices.projects();if(m.length===1){let e=await r.viewsService.computedViews(),t=await r.diagrams();if(t.length===0)throw process.exitCode=1,Error(`no views found`);t.length===e.length?l.customLogger.info(`${S.dim(`workspace:`)} ${S.green(`✓ all views layouted`)}`):l.customLogger.warn(`${S.dim(`workspace:`)} ${S.yellow(`✗ layouted ${t.length} of ${e.length} views`)}`),t.forEach(e=>{(e.hasLayoutDrift||e.drifts&&e.drifts.length>0)&&l.customLogger.warn(S.dim(`view`)+` `+S.red(e.id)+` `+S.yellow(`is out of date, layout drift detected`))});let n=m[0].config.landingPage;if(n&&(`include`in n||`exclude`in n)){let e=`include`in n?n.include:n.exclude;t.some(t=>e.some(e=>e.startsWith(`#`)?t.tags?.some(t=>t===e.slice(1)):t.id===e))||l.customLogger.warn(S.dim(`landingPage:`)+` `+S.yellow(`no views match the configured filter`))}}else for(let e of m){let t=await r.viewsService.computedViews(e.id);t.length===0?l.customLogger.warn(`${S.dim(`project:`)} ${e.id} ${S.yellow(`✗ no views found`)}`):l.customLogger.info(`${S.dim(`project:`)} ${e.id} ${S.green(`${t.length} views`)}`);let n=await r.diagrams(e.id),i=e.config.landingPage;if(i&&(`include`in i||`exclude`in i)){let t=`include`in i?i.include:i.exclude;n.some(e=>t.some(t=>t.startsWith(`#`)?e.tags?.some(e=>e===t.slice(1)):e.id===t))||l.customLogger.warn(`${S.dim(`project:`)} ${e.id} ${S.yellow(`landingPage: no views match the configured filter`)}`)}}if(e&&!a){let e=viteWebcomponentConfig({webcomponentPrefix:t,languageServices:r,outDir:f,base:l.base});await Wn(e)}if(await Wn({...l,publicDir:f}),a){if(!u){l.customLogger.warn(S.yellow(`outDir was not empty, skipping cleanup`));return}inlineSingleFileFavicon(l.build.outDir),removeAllButPreserved(l.build.outDir,[`index.html`,...p])}let h=P(l.build.outDir,`index.html`);vn(h)&&_n(h,P(l.build.outDir,`404.html`))}let ri;function hasDockerEnv(){try{return F.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return F.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return ri===void 0&&(ri=hasDockerEnv()||hasDockerCGroup()),ri}let ii;const hasContainerEnv=()=>{try{return F.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return ii===void 0&&(ii=hasContainerEnv()||isDocker()),ii}var HTTPError=class extends Error{response;request;options;constructor(e,t,n){let r=`${e.status||e.status===0?e.status:``} ${e.statusText??``}`.trim(),i=r?`status code ${r}`:`an unknown error`;super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name=`HTTPError`,this.response=e,this.request=t,this.options=n}},NonError=class extends Error{name=`NonError`;value;constructor(e){let t=`Non-error value was thrown`;try{typeof e==`string`?t=e:e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`&&(t=e.message)}catch{}super(t),this.value=e}},ForceRetryError=class extends Error{name=`ForceRetryError`;customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new NonError(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:`Forced retry`,t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};const ai=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream==`function`,r=typeof globalThis.Request==`function`;if(n&&r)try{t=new globalThis.Request(`https://empty.invalid`,{body:new globalThis.ReadableStream,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`)}catch(e){if(e instanceof Error&&e.message===`unsupported BodyInit type`)return!1;throw e}return e&&!t})(),oi=typeof globalThis.AbortController==`function`,si=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,ci=typeof globalThis.ReadableStream==`function`,li=typeof globalThis.FormData==`function`,ui=[`get`,`post`,`put`,`patch`,`head`,`delete`],di={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},fi=2147483647,pi=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,mi=Symbol(`stop`);var RetryMarker=class{options;constructor(e){this.options=e}};const retry=e=>new RetryMarker(e),hi={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},gi={next:!0},_i={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},getBodySize=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=pi,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r==`string`?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e==`string`)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(`byteLength`in e)return e.byteLength;if(typeof e==`object`&&e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},withProgress=(e,t,n)=>{let r,i=0;return e.pipeThrough(new TransformStream({transform(e,a){if(a.enqueue(e),r){i+=r.byteLength;let e=t===0?0:i/t;e>=1&&(e=1-2**-52),n?.({percent:e,totalBytes:Math.max(t,i),transferredBytes:i},r)}r=e},flush(){r&&(i+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},r))}}))},streamResponse=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get(`content-length`))||0);return new Response(withProgress(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},streamRequest=(e,t,n)=>{if(!e.body)return e;let r=getBodySize(n??e.body);return new Request(e,{duplex:`half`,body:withProgress(e.body,r,t)})},vi=t(e=>typeof e==`object`&&!!e,`isObject`),validateAndMerge=(...e)=>{for(let t of e)if((!vi(t)||Array.isArray(t))&&t!==void 0)throw TypeError("The `options` argument must be an object");return deepMerge({},...e)},mergeHeaders=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[e,t]of i.entries())r&&t===`undefined`||t===void 0?n.delete(e):n.set(e,t);return n};function newHookValue(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:deepMerge(e[n]??[],t[n]??[])}const mergeHooks=(e={},t={})=>({beforeRequest:newHookValue(e,t,`beforeRequest`),beforeRetry:newHookValue(e,t,`beforeRetry`),afterResponse:newHookValue(e,t,`afterResponse`),beforeError:newHookValue(e,t,`beforeError`)}),appendSearchParameters=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0){if(r instanceof URLSearchParams)for(let[e,t]of r.entries())n.append(e,t);else if(Array.isArray(r))for(let e of r){if(!Array.isArray(e)||e.length!==2)throw TypeError(`Array search parameters must be provided in [[key, value], ...] format`);n.append(String(e[0]),String(e[1]))}else if(vi(r))for(let[e,t]of Object.entries(r))t!==void 0&&n.append(e,String(t));else{let e=new URLSearchParams(r);for(let[t,r]of e.entries())n.append(t,r)}}return n},deepMerge=(...e)=>{let t={},n={},r={},i,a=[];for(let s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(vi(s)){for(let[e,n]of Object.entries(s)){if(e===`signal`&&n instanceof globalThis.AbortSignal){a.push(n);continue}if(e===`context`){if(n!=null&&(!vi(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}};continue}if(e===`searchParams`){i=n==null?void 0:i===void 0?n:appendSearchParameters(i,n);continue}vi(n)&&e in t&&(n=deepMerge(t[e],n)),t={...t,[e]:n}}vi(s.hooks)&&(r=mergeHooks(r,s.hooks),t.hooks=r),vi(s.headers)&&(n=mergeHeaders(n,s.headers),t.headers=n)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:si?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},normalizeRequestMethod=e=>ui.includes(e)?e.toUpperCase():e,yi={limit:2,methods:[`get`,`put`,`head`,`delete`,`options`,`trace`],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},normalizeRetryOptions=(e={})=>{if(typeof e==`number`)return{...yi,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error(`retry.methods must be an array`);if(e.methods&&=e.methods.map(e=>e.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw Error(`retry.statusCodes must be an array`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return{...yi,...t}};var TimeoutError=class extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name=`TimeoutError`,this.request=e}};async function timeout$1(e,t,n,r){return new Promise((i,a)=>{let s=setTimeout(()=>{n&&n.abort(),a(new TimeoutError(e))},r.timeout);r.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(s)})})}t(timeout$1,`timeout`);async function delay$1(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener(`abort`,abortHandler,{once:!0}));function abortHandler(){clearTimeout(i),r(t.reason)}let i=setTimeout(()=>{t?.removeEventListener(`abort`,abortHandler),n()},e)})}t(delay$1,`delay`);const findUnknownOptions=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in _i)&&!(r in hi)&&(!(r in e)||r in gi)&&(n[r]=t[r]);return n},hasSearchParameters=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e==`object`?Object.keys(e).length>0:typeof e==`string`?e.trim().length>0:!!e;function isHTTPError(e){return e instanceof HTTPError||e?.name===HTTPError.name}function isTimeoutError(e){return e instanceof TimeoutError||e?.name===TimeoutError.name}var bi=class Ky{static create(e,t){let n=new Ky(e,t),function_=async()=>{if(typeof n.#i.timeout==`number`&&n.#i.timeout>2147483647)throw RangeError(`The \`timeout\` option cannot be greater than ${fi}`);await Promise.resolve();let e=await n.#m();for(let t of n.#i.hooks.afterResponse){let r=n.#u(e.clone()),i;try{i=await t(n.request,n.#h(),r,{retryCount:n.#n})}catch(t){throw n.#f(r),n.#f(e),t}if(i instanceof RetryMarker)throw n.#f(r),n.#f(e),new ForceRetryError(i.options);let a=i instanceof globalThis.Response?i:e;r!==a&&n.#f(r),e!==a&&n.#f(e),e=a}if(n.#u(e),!e.ok&&(typeof n.#i.throwHttpErrors==`function`?n.#i.throwHttpErrors(e.status):n.#i.throwHttpErrors)){let t=new HTTPError(e,n.request,n.#h());for(let e of n.#i.hooks.beforeError)t=await e(t,{retryCount:n.#n});throw t}if(n.#i.onDownloadProgress){if(typeof n.#i.onDownloadProgress!=`function`)throw TypeError("The `onDownloadProgress` option must be a function");if(!ci)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");let t=e.clone();return n.#f(e),streamResponse(t,n.#i.onDownloadProgress)}return e},r=n.#p(function_).finally(()=>{let e=n.#a;n.#d(e?.body??void 0),n.#d(n.request.body??void 0)});for(let[e,i]of Object.entries(di))(e!==`bytes`||typeof globalThis.Response?.prototype?.bytes==`function`)&&(r[e]=async()=>{n.request.headers.set(`accept`,n.request.headers.get(`accept`)||i);let a=await r;if(e===`json`){if(a.status===204)return``;let e=await a.text();return e===``?``:t.parseJson?t.parseJson(e):JSON.parse(e)}return a[e]()});return r}static#e(e){return e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):e}request;#t;#n=0;#r;#i;#a;#o;#s;constructor(e,t={}){if(this.#r=e,this.#i={...t,headers:mergeHeaders(this.#r.headers,t.headers),hooks:mergeHooks({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:normalizeRequestMethod(t.method??this.#r.method??`GET`),prefixUrl:String(t.prefixUrl||``),retry:normalizeRetryOptions(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#r!=`string`&&!(this.#r instanceof URL||this.#r instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#i.prefixUrl&&typeof this.#r==`string`){if(this.#r.startsWith(`/`))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#i.prefixUrl.endsWith(`/`)||(this.#i.prefixUrl+=`/`),this.#r=this.#i.prefixUrl+this.#r}oi&&si&&(this.#o=this.#i.signal??this.#r.signal,this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal),ai&&(this.#i.duplex=`half`),this.#i.json!==void 0&&(this.#i.body=this.#i.stringifyJson?.(this.#i.json)??JSON.stringify(this.#i.json),this.#i.headers.set(`content-type`,this.#i.headers.get(`content-type`)??`application/json`));let n=t.headers&&new globalThis.Headers(t.headers).has(`content-type`);if(this.#r instanceof globalThis.Request&&(li&&this.#i.body instanceof globalThis.FormData||this.#i.body instanceof URLSearchParams)&&!n&&this.#i.headers.delete(`content-type`),this.request=new globalThis.Request(this.#r,this.#i),hasSearchParameters(this.#i.searchParams)){let e=`?`+(typeof this.#i.searchParams==`string`?this.#i.searchParams.replace(/^\?/,``):new URLSearchParams(Ky.#e(this.#i.searchParams)).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);this.request=new globalThis.Request(t,this.#i)}if(this.#i.onUploadProgress){if(typeof this.#i.onUploadProgress!=`function`)throw TypeError("The `onUploadProgress` option must be a function");if(!ai)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#_(this.request,this.#i.body??void 0)}}#c(){let e=this.#i.retry.delay(this.#n),t=e;this.#i.retry.jitter===!0?t=Math.random()*e:typeof this.#i.retry.jitter==`function`&&(t=this.#i.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e));let n=this.#i.retry.backoffLimit??1/0;return Math.min(n,t)}async#l(e){if(this.#n++,this.#n>this.#i.retry.limit)throw e;let t=e instanceof Error?e:new NonError(e);if(t instanceof ForceRetryError)return t.customDelay??this.#c();if(!this.#i.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#i.retry.shouldRetry!==void 0){let n=await this.#i.retry.shouldRetry({error:t,retryCount:this.#n});if(n===!1)throw e;if(n===!0)return this.#c()}if(isTimeoutError(e)&&!this.#i.retry.retryOnTimeout)throw e;if(isHTTPError(e)){if(!this.#i.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get(`Retry-After`)??e.response.headers.get(`RateLimit-Reset`)??e.response.headers.get(`X-RateLimit-Retry-After`)??e.response.headers.get(`X-RateLimit-Reset`)??e.response.headers.get(`X-Rate-Limit-Reset`);if(t&&this.#i.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t)*1e3;Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse(`2024-01-01`)&&(e-=Date.now());let n=this.#i.retry.maxRetryAfter??e;return e<n?e:n}if(e.response.status===413)throw e}return this.#c()}#u(e){return this.#i.parseJson&&(e.json=async()=>this.#i.parseJson(await e.text())),e}#d(e){e&&e.cancel().catch(()=>void 0)}#f(e){this.#d(e.body??void 0)}async#p(e){try{return await e()}catch(t){let n=Math.min(await this.#l(t),fi);if(this.#n<1)throw t;if(await delay$1(n,this.#o?{signal:this.#o}:{}),t instanceof ForceRetryError&&t.customRequest){let e=this.#i.signal?new globalThis.Request(t.customRequest,{signal:this.#i.signal}):new globalThis.Request(t.customRequest);this.#g(e)}for(let e of this.#i.hooks.beforeRetry){let n=await e({request:this.request,options:this.#h(),error:t,retryCount:this.#n});if(n instanceof globalThis.Request){this.#g(n);break}if(n instanceof globalThis.Response)return n;if(n===mi)return}return this.#p(e)}}async#m(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#i.signal}));for(let e of this.#i.hooks.beforeRequest){let t=await e(this.request,this.#h(),{retryCount:this.#n});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#g(t);break}}let e=findUnknownOptions(this.request,this.#i);return this.#a=this.request,this.request=this.#a.clone(),this.#i.timeout===!1?this.#i.fetch(this.#a,e):timeout$1(this.#a,e,this.#t,this.#i)}#h(){if(!this.#s){let{hooks:e,...t}=this.#i;this.#s=Object.freeze(t)}return this.#s}#g(e){this.#s=void 0,this.request=this.#_(e)}#_(e,t){return!this.#i.onUploadProgress||!e.body?e:streamRequest(e,this.#i.onUploadProgress,t??this.#i.body??void 0)}};
165
165
  /*! MIT License © Sindre Sorhus */
166
- const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(let t of ui)ky[t]=(n,r)=>bi.create(n,validateAndMerge(e,r,{method:t}));return ky.create=e=>createInstance(validateAndMerge(e)),ky.extend=t=>(typeof t==`function`&&(t=t(e??{})),createInstance(validateAndMerge(e,t))),ky.stop=mi,ky.retry=retry,ky},xi=createInstance();var Si=r(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Ci=r(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),wi=r(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Si(),a=Ci();e=t.exports={};let s=e.re=[],c=e.safeRe=[],l=e.src=[],u=e.safeSrc=[],f=e.t={},p=0,m=`[a-zA-Z0-9-]`,h=[[`\\s`,1],[`\\d`,i],[m,r]],makeSafeRegex=e=>{for(let[t,n]of h)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},createToken=(e,t,n)=>{let r=makeSafeRegex(t),i=p++;a(e,i,t),f[e]=i,l[i]=t,u[i]=r,s[i]=new RegExp(t,n?`g`:void 0),c[i]=new RegExp(r,n?`g`:void 0)};createToken(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),createToken(`NUMERICIDENTIFIERLOOSE`,`\\d+`),createToken(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${m}*`),createToken(`MAINVERSION`,`(${l[f.NUMERICIDENTIFIER]})\\.(${l[f.NUMERICIDENTIFIER]})\\.(${l[f.NUMERICIDENTIFIER]})`),createToken(`MAINVERSIONLOOSE`,`(${l[f.NUMERICIDENTIFIERLOOSE]})\\.(${l[f.NUMERICIDENTIFIERLOOSE]})\\.(${l[f.NUMERICIDENTIFIERLOOSE]})`),createToken(`PRERELEASEIDENTIFIER`,`(?:${l[f.NONNUMERICIDENTIFIER]}|${l[f.NUMERICIDENTIFIER]})`),createToken(`PRERELEASEIDENTIFIERLOOSE`,`(?:${l[f.NONNUMERICIDENTIFIER]}|${l[f.NUMERICIDENTIFIERLOOSE]})`),createToken(`PRERELEASE`,`(?:-(${l[f.PRERELEASEIDENTIFIER]}(?:\\.${l[f.PRERELEASEIDENTIFIER]})*))`),createToken(`PRERELEASELOOSE`,`(?:-?(${l[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[f.PRERELEASEIDENTIFIERLOOSE]})*))`),createToken(`BUILDIDENTIFIER`,`${m}+`),createToken(`BUILD`,`(?:\\+(${l[f.BUILDIDENTIFIER]}(?:\\.${l[f.BUILDIDENTIFIER]})*))`),createToken(`FULLPLAIN`,`v?${l[f.MAINVERSION]}${l[f.PRERELEASE]}?${l[f.BUILD]}?`),createToken(`FULL`,`^${l[f.FULLPLAIN]}$`),createToken(`LOOSEPLAIN`,`[v=\\s]*${l[f.MAINVERSIONLOOSE]}${l[f.PRERELEASELOOSE]}?${l[f.BUILD]}?`),createToken(`LOOSE`,`^${l[f.LOOSEPLAIN]}$`),createToken(`GTLT`,`((?:<|>)?=?)`),createToken(`XRANGEIDENTIFIERLOOSE`,`${l[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),createToken(`XRANGEIDENTIFIER`,`${l[f.NUMERICIDENTIFIER]}|x|X|\\*`),createToken(`XRANGEPLAIN`,`[v=\\s]*(${l[f.XRANGEIDENTIFIER]})(?:\\.(${l[f.XRANGEIDENTIFIER]})(?:\\.(${l[f.XRANGEIDENTIFIER]})(?:${l[f.PRERELEASE]})?${l[f.BUILD]}?)?)?`),createToken(`XRANGEPLAINLOOSE`,`[v=\\s]*(${l[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[f.XRANGEIDENTIFIERLOOSE]})(?:${l[f.PRERELEASELOOSE]})?${l[f.BUILD]}?)?)?`),createToken(`XRANGE`,`^${l[f.GTLT]}\\s*${l[f.XRANGEPLAIN]}$`),createToken(`XRANGELOOSE`,`^${l[f.GTLT]}\\s*${l[f.XRANGEPLAINLOOSE]}$`),createToken(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),createToken(`COERCE`,`${l[f.COERCEPLAIN]}(?:$|[^\\d])`),createToken(`COERCEFULL`,l[f.COERCEPLAIN]+`(?:${l[f.PRERELEASE]})?(?:${l[f.BUILD]})?(?:$|[^\\d])`),createToken(`COERCERTL`,l[f.COERCE],!0),createToken(`COERCERTLFULL`,l[f.COERCEFULL],!0),createToken(`LONETILDE`,`(?:~>?)`),createToken(`TILDETRIM`,`(\\s*)${l[f.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,createToken(`TILDE`,`^${l[f.LONETILDE]}${l[f.XRANGEPLAIN]}$`),createToken(`TILDELOOSE`,`^${l[f.LONETILDE]}${l[f.XRANGEPLAINLOOSE]}$`),createToken(`LONECARET`,`(?:\\^)`),createToken(`CARETTRIM`,`(\\s*)${l[f.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,createToken(`CARET`,`^${l[f.LONECARET]}${l[f.XRANGEPLAIN]}$`),createToken(`CARETLOOSE`,`^${l[f.LONECARET]}${l[f.XRANGEPLAINLOOSE]}$`),createToken(`COMPARATORLOOSE`,`^${l[f.GTLT]}\\s*(${l[f.LOOSEPLAIN]})$|^$`),createToken(`COMPARATOR`,`^${l[f.GTLT]}\\s*(${l[f.FULLPLAIN]})$|^$`),createToken(`COMPARATORTRIM`,`(\\s*)${l[f.GTLT]}\\s*(${l[f.LOOSEPLAIN]}|${l[f.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,createToken(`HYPHENRANGE`,`^\\s*(${l[f.XRANGEPLAIN]})\\s+-\\s+(${l[f.XRANGEPLAIN]})\\s*$`),createToken(`HYPHENRANGELOOSE`,`^\\s*(${l[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[f.XRANGEPLAINLOOSE]})\\s*$`),createToken(`STAR`,`(<|>)?=?\\s*\\*`),createToken(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),createToken(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Ti=r(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({}),parseOptions=e=>e?typeof e==`object`?e:n:r;t.exports=parseOptions})),Ei=r(((e,t)=>{let n=/^[0-9]+$/,compareIdentifiers=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1},rcompareIdentifiers=(e,t)=>compareIdentifiers(t,e);t.exports={compareIdentifiers,rcompareIdentifiers}})),Di=r(((e,t)=>{let n=Ci(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Si(),{safeRe:a,t:s}=wi(),c=Ti(),{compareIdentifiers:l}=Ei(),isPrereleaseIdentifier=(e,t)=>{let n=t.split(`.`);if(n.length>e.length)return!1;for(let t=0;t<n.length;t++)if(l(e[t],n[t])!==0)return!1;return!0};t.exports=class SemVer{constructor(e,t){if(t=c(t),e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let l=e.trim().match(t.loose?a[s.LOOSE]:a[s.FULL]);if(!l)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);this.prerelease=l[4]?l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(e){if(n(`SemVer.compare`,this.version,this.options,e),!(e instanceof SemVer)){if(typeof e==`string`&&e===this.version)return 0;e=new SemVer(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof SemVer||(e=new SemVer(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:+(this.patch>e.patch)}comparePre(e){if(e instanceof SemVer||(e=new SemVer(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let r=this.prerelease[t],i=e.prerelease[t];if(n(`prerelease compare`,t,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r!==i)return l(r,i)}while(++t)}compareBuild(e){e instanceof SemVer||(e=new SemVer(e,this.options));let t=0;do{let r=this.build[t],i=e.build[t];if(n(`build compare`,t,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r!==i)return l(r,i)}while(++t)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[s.PRERELEASELOOSE]:a[s.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];if(n===!1&&(r=[t]),isPrereleaseIdentifier(this.prerelease,t)){let e=this.prerelease[t.split(`.`).length];isNaN(e)&&(this.prerelease=r)}else this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Oi=r(((e,t)=>{let n=Di(),parse=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}};t.exports=parse})),ki=r(((e,t)=>{let n=Oi(),valid=(e,t)=>{let r=n(e,t);return r?r.version:null};t.exports=valid})),Ai=r(((e,t)=>{let n=Oi(),clean=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null};t.exports=clean})),ji=r(((e,t)=>{let n=Di(),inc=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}};t.exports=inc})),Mi=r(((e,t)=>{let n=Oi(),diff=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let s=a>0,c=s?r:i,l=s?i:r,u=!!c.prerelease.length;if(l.prerelease.length&&!u){if(!l.patch&&!l.minor)return`major`;if(l.compareMain(c)===0)return l.minor&&!l.patch?`minor`:`patch`}let f=u?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:f+`patch`:f+`minor`:f+`major`};t.exports=diff})),Ni=r(((e,t)=>{let n=Di(),major=(e,t)=>new n(e,t).major;t.exports=major})),Pi=r(((e,t)=>{let n=Di(),minor=(e,t)=>new n(e,t).minor;t.exports=minor})),Fi=r(((e,t)=>{let n=Di(),patch=(e,t)=>new n(e,t).patch;t.exports=patch})),Ii=r(((e,t)=>{let n=Oi(),prerelease=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};t.exports=prerelease})),Li=r(((e,t)=>{let n=Di(),compare=(e,t,r)=>new n(e,r).compare(new n(t,r));t.exports=compare})),Ri=r(((e,t)=>{let n=Li(),rcompare=(e,t,r)=>n(t,e,r);t.exports=rcompare})),zi=r(((e,t)=>{let n=Li(),compareLoose=(e,t)=>n(e,t,!0);t.exports=compareLoose})),Bi=r(((e,t)=>{let n=Di(),compareBuild=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)};t.exports=compareBuild})),Vi=r(((e,t)=>{let n=Bi(),sort=(e,t)=>e.sort((e,r)=>n(e,r,t));t.exports=sort})),Hi=r(((e,t)=>{let n=Bi(),rsort=(e,t)=>e.sort((e,r)=>n(r,e,t));t.exports=rsort})),Ui=r(((e,t)=>{let n=Li(),gt=(e,t,r)=>n(e,t,r)>0;t.exports=gt})),Wi=r(((e,t)=>{let n=Li(),lt=(e,t,r)=>n(e,t,r)<0;t.exports=lt})),Gi=r(((e,t)=>{let n=Li(),eq=(e,t,r)=>n(e,t,r)===0;t.exports=eq})),Ki=r(((e,t)=>{let n=Li(),neq=(e,t,r)=>n(e,t,r)!==0;t.exports=neq})),qi=r(((e,t)=>{let n=Li(),gte=(e,t,r)=>n(e,t,r)>=0;t.exports=gte})),Ji=r(((e,t)=>{let n=Li(),lte=(e,t,r)=>n(e,t,r)<=0;t.exports=lte})),Yi=r(((e,t)=>{let n=Gi(),r=Ki(),i=Ui(),a=qi(),s=Wi(),c=Ji(),cmp=(e,t,l,u)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof l==`object`&&(l=l.version),e===l;case`!==`:return typeof e==`object`&&(e=e.version),typeof l==`object`&&(l=l.version),e!==l;case``:case`=`:case`==`:return n(e,l,u);case`!=`:return r(e,l,u);case`>`:return i(e,l,u);case`>=`:return a(e,l,u);case`<`:return s(e,l,u);case`<=`:return c(e,l,u);default:throw TypeError(`Invalid operator: ${t}`)}};t.exports=cmp})),Xi=r(((e,t)=>{let n=Di(),r=Oi(),{safeRe:i,t:a}=wi(),coerce=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let s=null;if(!t.rtl)s=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!s||s.index+s[0].length!==e.length);)(!s||r.index+r[0].length!==s.index+s[0].length)&&(s=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(s===null)return null;let c=s[2],l=s[3]||`0`,u=s[4]||`0`,f=t.includePrerelease&&s[5]?`-${s[5]}`:``,p=t.includePrerelease&&s[6]?`+${s[6]}`:``;return r(`${c}.${l}.${u}${f}${p}`,t)};t.exports=coerce})),Zi=r(((e,t)=>{let n=Oi(),r=Si(),i=Di(),truncate=(e,t,n)=>{if(!r.RELEASE_TYPES.includes(t))return null;let i=cloneInputVersion(e,n);return i&&doTruncation(i,t)},cloneInputVersion=(e,t)=>{let r=e instanceof i?e.version:e;return n(r,t)},doTruncation=(e,t)=>{if(isPrerelease(t))return e.version;switch(e.prerelease=[],t){case`major`:e.minor=0,e.patch=0;break;case`minor`:e.patch=0}return e.format()},isPrerelease=e=>e.startsWith(`pre`);t.exports=truncate})),Qi=r(((e,t)=>{var LRUCache=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}};t.exports=LRUCache})),$i=r(((e,t)=>{let n=/\s+/g;t.exports=class Range{constructor(e,t){if(t=i(t),e instanceof Range)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new Range(e.raw,t);if(e instanceof a)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!isNullSet(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&isAny(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(y,``);let t=((this.options.includePrerelease&&g)|(this.options.loose&&v))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,c=i?l[f.HYPHENRANGELOOSE]:l[f.HYPHENRANGE];e=e.replace(c,hyphenReplace(this.options.includePrerelease)),s(`hyphen replace`,e),e=e.replace(l[f.COMPARATORTRIM],p),s(`comparator trim`,e),e=e.replace(l[f.TILDETRIM],m),s(`tilde trim`,e),e=e.replace(l[f.CARETTRIM],h),s(`caret trim`,e);let u=e.split(` `).map(e=>parseComparator(e,this.options)).join(` `).split(/\s+/).map(e=>replaceGTE0(e,this.options));i&&(u=u.filter(e=>(s(`loose invalid filter`,e,this.options),!!e.match(l[f.COMPARATORLOOSE])))),s(`range list`,u);let b=new Map,ee=u.map(e=>new a(e,this.options));for(let e of ee){if(isNullSet(e))return[e];b.set(e.value,e)}b.size>1&&b.has(``)&&b.delete(``);let te=[...b.values()];return r.set(t,te),te}intersects(e,t){if(!(e instanceof Range))throw TypeError(`a Range is required`);return this.set.some(n=>isSatisfiable(n,t)&&e.set.some(e=>isSatisfiable(e,t)&&n.every(n=>e.every(e=>n.intersects(e,t)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(testSet(this.set[t],e,this.options))return!0;return!1}};let r=new(Qi()),i=Ti(),a=ea(),s=Ci(),c=Di(),{safeRe:l,src:u,t:f,comparatorTrimReplace:p,tildeTrimReplace:m,caretTrimReplace:h}=wi(),{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:v}=Si(),y=new RegExp(u[f.BUILD],`g`),isNullSet=e=>e.value===`<0.0.0-0`,isAny=e=>e.value===``,isSatisfiable=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},parseComparator=(e,t)=>(e=e.replace(l[f.BUILD],``),s(`comp`,e,t),e=replaceCarets(e,t),s(`caret`,e),e=replaceTildes(e,t),s(`tildes`,e),e=replaceXRanges(e,t),s(`xrange`,e),e=replaceStars(e,t),s(`stars`,e),e),isX=e=>!e||e.toLowerCase()===`x`||e===`*`,invalidXRangeOrder=(e,t,n)=>isX(e)&&!isX(t)||isX(t)&&n&&!isX(n),replaceTildes=(e,t)=>e.trim().split(/\s+/).map(e=>replaceTilde(e,t)).join(` `),replaceTilde=(e,t)=>{let n=t.loose?l[f.TILDELOOSE]:l[f.TILDE],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,c)=>{s(`tilde`,e,t,n,i,a,c);let l;return isX(n)?l=``:isX(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:isX(a)?l=`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:c?(s(`replaceTilde pr`,c),l=`>=${n}.${i}.${a}-${c} <${n}.${+i+1}.0-0`):l=`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`,s(`tilde return`,l),l})},replaceCarets=(e,t)=>e.trim().split(/\s+/).map(e=>replaceCaret(e,t)).join(` `),replaceCaret=(e,t)=>{s(`caret`,e,t);let n=t.loose?l[f.CARETLOOSE]:l[f.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,c)=>{s(`caret`,e,t,n,i,a,c);let l;return isX(n)?l=``:isX(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:isX(a)?l=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:c?(s(`replaceCaret pr`,c),l=n===`0`?i===`0`?`>=${n}.${i}.${a}-${c} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${c} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${c} <${+n+1}.0.0-0`):(s(`no pr`),l=n===`0`?i===`0`?`>=${n}.${i}.${a} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),s(`caret return`,l),l})},replaceXRanges=(e,t)=>(s(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>replaceXRange(e,t)).join(` `)),replaceXRange=(e,t)=>{e=e.trim();let n=t.loose?l[f.XRANGELOOSE]:l[f.XRANGE];return e.replace(n,(n,r,i,a,c,l)=>{if(s(`xRange`,e,n,r,i,a,c,l),invalidXRangeOrder(i,a,c))return e;let u=isX(i),f=u||isX(a),p=f||isX(c),m=p;return r===`=`&&m&&(r=``),l=t.includePrerelease?`-0`:``,u?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&m?(f&&(a=0),c=0,r===`>`?(r=`>=`,f?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):r===`<=`&&(r=`<`,f?i=+i+1:a=+a+1),r===`<`&&(l=`-0`),n=`${r+i}.${a}.${c}${l}`):f?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),s(`xRange return`,n),n})},replaceStars=(e,t)=>(s(`replaceStars`,e,t),e.trim().replace(l[f.STAR],``)),replaceGTE0=(e,t)=>(s(`replaceGTE0`,e,t),e.trim().replace(l[t.includePrerelease?f.GTE0PRE:f.GTE0],``)),hyphenReplace=e=>(t,n,r,i,a,s,c,l,u,f,p,m)=>(n=isX(r)?``:isX(i)?`>=${r}.0.0${e?`-0`:``}`:isX(a)?`>=${r}.${i}.0${e?`-0`:``}`:s?`>=${n}`:`>=${n}${e?`-0`:``}`,l=isX(u)?``:isX(f)?`<${+u+1}.0.0-0`:isX(p)?`<${u}.${+f+1}.0-0`:m?`<=${u}.${f}.${p}-${m}`:e?`<${u}.${f}.${+p+1}-0`:`<=${l}`,`${n} ${l}`.trim()),testSet=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(s(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),ea=r(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class Comparator{static get ANY(){return n}constructor(e,t){if(t=r(t),e instanceof Comparator){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(` `),c(`comparator`,e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.value=this.semver===n?``:this.operator+this.semver.version,c(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),this.semver=r[2]?new l(r[2],this.options.loose):n}toString(){return this.value}test(e){if(c(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new l(e,this.options)}catch{return!1}return s(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``||new u(e.value,t).test(this.value):e.operator===``?e.value===``||new u(this.value,t).test(e.semver):(t=r(t),t.includePrerelease&&(this.value===`<0.0.0-0`||e.value===`<0.0.0-0`)||!t.includePrerelease&&(this.value.startsWith(`<0.0.0`)||e.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&e.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&e.operator.startsWith(`<`)||this.semver.version===e.semver.version&&this.operator.includes(`=`)&&e.operator.includes(`=`)||s(this.semver,`<`,e.semver,t)&&this.operator.startsWith(`>`)&&e.operator.startsWith(`<`)||s(this.semver,`>`,e.semver,t)&&this.operator.startsWith(`<`)&&e.operator.startsWith(`>`)))}};let r=Ti(),{safeRe:i,t:a}=wi(),s=Yi(),c=Ci(),l=Di(),u=$i()})),ta=r(((e,t)=>{let n=$i(),satisfies=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)};t.exports=satisfies})),na=r(((e,t)=>{let n=$i(),toComparators=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `));t.exports=toComparators})),ra=r(((e,t)=>{let n=Di(),r=$i(),maxSatisfying=(e,t,i)=>{let a=null,s=null,c=null;try{c=new r(t,i)}catch{return null}return e.forEach(e=>{c.test(e)&&(!a||s.compare(e)===-1)&&(a=e,s=new n(a,i))}),a};t.exports=maxSatisfying})),ia=r(((e,t)=>{let n=Di(),r=$i(),minSatisfying=(e,t,i)=>{let a=null,s=null,c=null;try{c=new r(t,i)}catch{return null}return e.forEach(e=>{c.test(e)&&(!a||s.compare(e)===1)&&(a=e,s=new n(a,i))}),a};t.exports=minSatisfying})),aa=r(((e,t)=>{let n=Di(),r=$i(),i=Ui(),minVersion=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],s=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!s||i(t,s))&&(s=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),s&&(!a||i(a,s))&&(a=s)}return a&&e.test(a)?a:null};t.exports=minVersion})),oa=r(((e,t)=>{let n=$i(),validRange=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}};t.exports=validRange})),sa=r(((e,t)=>{let n=Di(),r=ea(),{ANY:i}=r,a=$i(),s=ta(),c=Ui(),l=Wi(),u=Ji(),f=qi(),outside=(e,t,p,m)=>{e=new n(e,m),t=new a(t,m);let h,g,v,y,b;switch(p){case`>`:h=c,g=u,v=l,y=`>`,b=`>=`;break;case`<`:h=l,g=f,v=c,y=`<`,b=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(s(e,t,m))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],s=null,c=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),s||=e,c||=e,h(e.semver,s.semver,m)?s=e:v(e.semver,c.semver,m)&&(c=e)}),s.operator===y||s.operator===b||(!c.operator||c.operator===y)&&g(e,c.semver)||c.operator===b&&v(e,c.semver))return!1}return!0};t.exports=outside})),ca=r(((e,t)=>{let n=sa(),gtr=(e,t,r)=>n(e,t,`>`,r);t.exports=gtr})),la=r(((e,t)=>{let n=sa(),ltr=(e,t,r)=>n(e,t,`<`,r);t.exports=ltr})),ua=r(((e,t)=>{let n=$i(),intersects=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r));t.exports=intersects})),da=r(((e,t)=>{let n=ta(),r=Li();t.exports=(e,t,i)=>{let a=[],s=null,c=null,l=e.sort((e,t)=>r(e,t,i));for(let e of l)n(e,t,i)?(c=e,s||=e):(c&&a.push([s,c]),c=null,s=null);s&&a.push([s,null]);let u=[];for(let[e,t]of a)e===t?u.push(e):!t&&e===l[0]?u.push(`*`):t?e===l[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`);let f=u.join(` || `),p=typeof t.raw==`string`?t.raw:String(t);return f.length<p.length?f:t}})),fa=r(((e,t)=>{let n=$i(),r=ea(),{ANY:i}=r,a=ta(),s=Li(),subset=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=simpleSubset(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],simpleSubset=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,u,f;for(let t of e)t.operator===`>`||t.operator===`>=`?u=higherGT(u,t,n):t.operator===`<`||t.operator===`<=`?f=lowerLT(f,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(u&&f&&(p=s(u.semver,f.semver,n),p>0||p===0&&(u.operator!==`>=`||f.operator!==`<=`)))return null;for(let e of r){if(u&&!a(e,String(u),n)||f&&!a(e,String(f),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,v,y=f&&!n.includePrerelease&&f.semver.prerelease.length?f.semver:!1,b=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1;y&&y.prerelease.length===1&&f.operator===`<`&&y.prerelease[0]===0&&(y=!1);for(let e of t){if(v=v||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,u){if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),e.operator===`>`||e.operator===`>=`){if(m=higherGT(u,e,n),m===e&&m!==u)return!1}else if(u.operator===`>=`&&!e.test(u.semver))return!1}if(f){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`<`||e.operator===`<=`){if(h=lowerLT(f,e,n),h===e&&h!==f)return!1}else if(f.operator===`<=`&&!e.test(f.semver))return!1}if(!e.operator&&(f||u)&&p!==0)return!1}return!(u&&g&&!f&&p!==0||f&&v&&!u&&p!==0||b||y)},higherGT=(e,t,n)=>{if(!e)return t;let r=s(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},lowerLT=(e,t,n)=>{if(!e)return t;let r=s(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=subset})),pa=e(r(((e,t)=>{let n=wi(),r=Si(),i=Di(),a=Ei();t.exports={parse:Oi(),valid:ki(),clean:Ai(),inc:ji(),diff:Mi(),major:Ni(),minor:Pi(),patch:Fi(),prerelease:Ii(),compare:Li(),rcompare:Ri(),compareLoose:zi(),compareBuild:Bi(),sort:Vi(),rsort:Hi(),gt:Ui(),lt:Wi(),eq:Gi(),neq:Ki(),gte:qi(),lte:Ji(),cmp:Yi(),coerce:Xi(),truncate:Zi(),Comparator:ea(),Range:$i(),satisfies:ta(),toComparators:na(),maxSatisfying:ra(),minSatisfying:ia(),minVersion:aa(),validRange:oa(),outside:sa(),gtr:ca(),ltr:la(),intersects:ua(),simplifyRange:da(),subset:fa(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))(),1);const isObject=e=>{let t=typeof e;return e!==null&&(t===`object`||t===`function`)},ma=new Set([`__proto__`,`prototype`,`constructor`]),ha=1e6,isDigit=e=>e>=`0`&&e<=`9`;function shouldCoerceToNumber(e){if(e===`0`)return!0;if(/^[1-9]\d*$/.test(e)){let t=Number.parseInt(e,10);return t<=2**53-1&&t<=ha}return!1}function processSegment(e,t){return!ma.has(e)&&(e&&shouldCoerceToNumber(e)?t.push(Number.parseInt(e,10)):t.push(e),!0)}function parsePath(e){if(typeof e!=`string`)throw TypeError(`Expected a string, got ${typeof e}`);let t=[],n=``,r=`start`,i=!1,a=0;for(let s of e){if(a++,i){n+=s,i=!1;continue}if(s===`\\`){if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);i=!0,r=r===`start`?`property`:r;continue}switch(s){case`.`:if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`){r=`property`;break}if(!processSegment(n,t))return[];n=``,r=`property`;break;case`[`:if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`){r=`index`;break}if(r===`property`||r===`start`){if((n||r===`property`)&&!processSegment(n,t))return[];n=``}r=`index`;break;case`]`:if(r===`index`){if(n===``)n=(t.pop()||``)+`[]`,r=`property`;else{let e=Number.parseInt(n,10);!Number.isNaN(e)&&Number.isFinite(e)&&e>=0&&e<=2**53-1&&e<=ha&&n===String(e)?t.push(e):t.push(n),n=``,r=`indexEnd`}break}if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);n+=s;break;default:if(r===`index`&&!isDigit(s))throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);r===`start`&&(r=`property`),n+=s}}switch(i&&(n+=`\\`),r){case`property`:if(!processSegment(n,t))return[];break;case`index`:throw Error(`Index was not closed`);case`start`:t.push(``)}return t}function normalizePath(e){if(typeof e==`string`)return parsePath(e);if(Array.isArray(e)){let t=[];for(let[n,r]of e.entries()){if(typeof r!=`string`&&typeof r!=`number`)throw TypeError(`Expected a string or number for path segment at index ${n}, got ${typeof r}`);if(typeof r==`number`&&!Number.isFinite(r))throw TypeError(`Path segment at index ${n} must be a finite number, got ${r}`);if(ma.has(r))return[];typeof r==`string`&&shouldCoerceToNumber(r)?t.push(Number.parseInt(r,10)):t.push(r)}return t}return[]}function getProperty(e,t,n){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return n===void 0?e:n;let r=normalizePath(t);if(r.length===0)return n;for(let t=0;t<r.length;t++){let i=r[t];if(e=e[i],e==null){if(t!==r.length-1)return n;break}}return e===void 0?n:e}function setProperty(e,t,n){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return e;let r=e,i=normalizePath(t);if(i.length===0)return e;for(let t=0;t<i.length;t++){let r=i[t];if(t===i.length-1)e[r]=n;else if(!isObject(e[r])){let n=typeof i[t+1]==`number`;e[r]=n?[]:{}}e=e[r]}return r}function deleteProperty(e,t){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return!1;let n=normalizePath(t);if(n.length===0)return!1;for(let t=0;t<n.length;t++){let r=n[t];if(t===n.length-1)return Object.hasOwn(e,r)?(delete e[r],!0):!1;if(e=e[r],!isObject(e))return!1}}function hasProperty(e,t){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return!1;let n=normalizePath(t);if(n.length===0)return!1;for(let t of n){if(!isObject(e)||!(t in e))return!1;e=e[t]}return!0}const ga=mn.homedir(),_a=mn.tmpdir(),{env:va}=P,macos=e=>{let t=j.join(ga,`Library`);return{data:j.join(t,`Application Support`,e),config:j.join(t,`Preferences`,e),cache:j.join(t,`Caches`,e),log:j.join(t,`Logs`,e),temp:j.join(_a,e)}},windows=e=>{let t=va.APPDATA||j.join(ga,`AppData`,`Roaming`),n=va.LOCALAPPDATA||j.join(ga,`AppData`,`Local`);return{data:j.join(n,e,`Data`),config:j.join(t,e,`Config`),cache:j.join(n,e,`Cache`),log:j.join(n,e,`Log`),temp:j.join(_a,e)}},linux=e=>{let t=j.basename(ga);return{data:j.join(va.XDG_DATA_HOME||j.join(ga,`.local`,`share`),e),config:j.join(va.XDG_CONFIG_HOME||j.join(ga,`.config`),e),cache:j.join(va.XDG_CACHE_HOME||j.join(ga,`.cache`),e),log:j.join(va.XDG_STATE_HOME||j.join(ga,`.local`,`state`),e),temp:j.join(_a,t,e)}};function envPaths(e,{suffix:t=`nodejs`}={}){if(typeof e!=`string`)throw TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),P.platform===`darwin`?macos(e):P.platform===`win32`?windows(e):linux(e)}const attemptifyAsync=(e,t)=>function attemptified(...n){return e.apply(void 0,n).catch(t)},attemptifySync=(e,t)=>function attemptified(...n){try{return e.apply(void 0,n)}catch(e){return t(e)}},ya=P.getuid?!P.getuid():!1,NOOP=()=>void 0,L={isChangeErrorOk:e=>{if(!L.isNodeError(e))return!1;let{code:t}=e;return t===`ENOSYS`||!ya&&(t===`EINVAL`||t===`EPERM`)},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!L.isNodeError(e))return!1;let{code:t}=e;return t===`EMFILE`||t===`ENFILE`||t===`EAGAIN`||t===`EBUSY`||t===`EACCESS`||t===`EACCES`||t===`EACCS`||t===`EPERM`},onChangeError:e=>{if(!L.isNodeError(e)||!L.isChangeErrorOk(e))throw e}};var RetryfyQueue=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=1e4,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||=setInterval(this.tick,this.interval)},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=e=>{this.queueWaiting.add(e),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=e=>{this.queueWaiting.delete(e),this.queueActive.delete(e)},this.schedule=()=>new Promise(e=>{let cleanup=()=>this.remove(resolver),resolver=()=>e(cleanup);this.add(resolver)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let e of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(e),this.queueActive.add(e),e()}}}}},ba=new RetryfyQueue;const retryifyAsync=(e,t)=>function retrified(n){return function attempt(...r){return ba.schedule().then(i=>{let onResolve=e=>(i(),e),onReject=e=>{if(i(),Date.now()>=n)throw e;if(t(e)){let e=Math.round(100*Math.random());return new Promise(t=>setTimeout(t,e)).then(()=>attempt.apply(void 0,r))}throw e};return e.apply(void 0,r).then(onResolve,onReject)})}},retryifySync=(e,t)=>function retrified(n){return function attempt(...r){try{return e.apply(void 0,r)}catch(e){if(Date.now()>n)throw e;if(t(e))return attempt.apply(void 0,r);throw e}}},xa={attempt:{chmod:attemptifyAsync(Nt(N.chmod),L.onChangeError),chown:attemptifyAsync(Nt(N.chown),L.onChangeError),close:attemptifyAsync(Nt(N.close),NOOP),fsync:attemptifyAsync(Nt(N.fsync),NOOP),mkdir:attemptifyAsync(Nt(N.mkdir),NOOP),realpath:attemptifyAsync(Nt(N.realpath),NOOP),stat:attemptifyAsync(Nt(N.stat),NOOP),unlink:attemptifyAsync(Nt(N.unlink),NOOP),chmodSync:attemptifySync(N.chmodSync,L.onChangeError),chownSync:attemptifySync(N.chownSync,L.onChangeError),closeSync:attemptifySync(N.closeSync,NOOP),existsSync:attemptifySync(N.existsSync,NOOP),fsyncSync:attemptifySync(N.fsync,NOOP),mkdirSync:attemptifySync(N.mkdirSync,NOOP),realpathSync:attemptifySync(N.realpathSync,NOOP),statSync:attemptifySync(N.statSync,NOOP),unlinkSync:attemptifySync(N.unlinkSync,NOOP)},retry:{close:retryifyAsync(Nt(N.close),L.isRetriableError),fsync:retryifyAsync(Nt(N.fsync),L.isRetriableError),open:retryifyAsync(Nt(N.open),L.isRetriableError),readFile:retryifyAsync(Nt(N.readFile),L.isRetriableError),rename:retryifyAsync(Nt(N.rename),L.isRetriableError),stat:retryifyAsync(Nt(N.stat),L.isRetriableError),write:retryifyAsync(Nt(N.write),L.isRetriableError),writeFile:retryifyAsync(Nt(N.writeFile),L.isRetriableError),closeSync:retryifySync(N.closeSync,L.isRetriableError),fsyncSync:retryifySync(N.fsyncSync,L.isRetriableError),openSync:retryifySync(N.openSync,L.isRetriableError),readFileSync:retryifySync(N.readFileSync,L.isRetriableError),renameSync:retryifySync(N.renameSync,L.isRetriableError),statSync:retryifySync(N.statSync,L.isRetriableError),writeSync:retryifySync(N.writeSync,L.isRetriableError),writeFileSync:retryifySync(N.writeFileSync,L.isRetriableError)}},Sa={},Ca=mn.userInfo().uid,wa=mn.userInfo().gid,Ta=!!P.getuid;P.getuid&&P.getuid();const isException=e=>e instanceof Error&&`code`in e,Ea=t(e=>typeof e==`string`,`isString`),isUndefined=e=>e===void 0,Da=P.platform===`linux`,Oa=P.platform===`win32`,ka=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`];Oa||ka.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),Da&&ka.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`);var Interceptor=class{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=e=>{if(!this.exited){this.exited=!0;for(let e of this.callbacks)e();e&&(Oa&&e!==`SIGINT`&&e!==`SIGTERM`&&e!==`SIGKILL`?P.kill(P.pid,`SIGTERM`):P.kill(P.pid,e))}},this.hook=()=>{P.once(`exit`,()=>this.exit());for(let e of ka)try{P.once(e,()=>this.exit(e))}catch{}},this.register=e=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}};const Aa=new Interceptor().register,ja={store:{},create:e=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6);return`${e}${`.tmp-${Date.now().toString().slice(-10)}${t}`}`},get:(e,t,n=!0)=>{let r=ja.truncate(t(e));if(r in ja.store)return ja.get(e,t,n);ja.store[r]=n;let disposer=()=>delete ja.store[r];return[r,disposer]},purge:e=>{ja.store[e]&&(delete ja.store[e],xa.attempt.unlink(e))},purgeSync:e=>{ja.store[e]&&(delete ja.store[e],xa.attempt.unlinkSync(e))},purgeSyncAll:()=>{for(let e in ja.store)ja.purgeSync(e)},truncate:e=>{let t=j.basename(e);if(t.length<=128)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-128;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};Aa(ja.purgeSyncAll);function writeFileSync$1(e,t,n=Sa){if(Ea(n))return writeFileSync$1(e,t,{encoding:n});let r=Date.now()+((n.timeout??1e3)||-1),i=null,a=null,s=null;try{let c=xa.attempt.realpathSync(e),l=!!c;e=c||e,[a,i]=ja.get(e,n.tmpCreate||ja.create,n.tmpPurge!==!1);let u=Ta&&isUndefined(n.chown),f=isUndefined(n.mode);if(l&&(u||f)){let t=xa.attempt.statSync(e);t&&(n={...n},u&&(n.chown={uid:t.uid,gid:t.gid}),f&&(n.mode=t.mode))}if(!l){let t=j.dirname(e);xa.attempt.mkdirSync(t,{mode:511,recursive:!0})}s=xa.retry.openSync(r)(a,`w`,n.mode||438),n.tmpCreated&&n.tmpCreated(a),Ea(t)?xa.retry.writeSync(r)(s,t,0,n.encoding||`utf8`):isUndefined(t)||xa.retry.writeSync(r)(s,t,0,t.length,0),n.fsync!==!1&&(n.fsyncWait===!1?xa.attempt.fsync(s):xa.retry.fsyncSync(r)(s)),xa.retry.closeSync(r)(s),s=null,n.chown&&(n.chown.uid!==Ca||n.chown.gid!==wa)&&xa.attempt.chownSync(a,n.chown.uid,n.chown.gid),n.mode&&n.mode!==438&&xa.attempt.chmodSync(a,n.mode);try{xa.retry.renameSync(r)(a,e)}catch(t){if(!isException(t)||t.code!==`ENAMETOOLONG`)throw t;xa.retry.renameSync(r)(a,ja.truncate(e))}i(),a=null}finally{s&&xa.attempt.closeSync(s),a&&ja.purge(a)}}t(writeFileSync$1,`writeFileSync`);var Ma=r((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 _CodeOrName=class{};e._CodeOrName=_CodeOrName,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{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=Name;var _Code=class extends _CodeOrName{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(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof Name&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=_Code,e.nil=new _Code(``);function _(e,...t){let n=[e[0]],r=0;for(;r<t.length;)addCodeArg(n,t[r]),n.push(e[++r]);return new _Code(n)}e._=_;let t=new _Code(`+`);function str(e,...n){let r=[safeStringify(e[0])],i=0;for(;i<n.length;)r.push(t),addCodeArg(r,n[i]),r.push(t,safeStringify(e[++i]));return optimize(r),new _Code(r)}e.str=str;function addCodeArg(e,t){t instanceof _Code?e.push(...t._items):t instanceof Name?e.push(t):e.push(interpolate(t))}e.addCodeArg=addCodeArg;function optimize(e){let n=1;for(;n<e.length-1;){if(e[n]===t){let t=mergeExprItems(e[n-1],e[n+1]);if(t!==void 0){e.splice(n-1,3,t);continue}e[n++]=`+`}n++}}function mergeExprItems(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof Name||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 Name))return`"${e}${t.slice(1)}`}function strConcat(e,t){return t.emptyStr()?e:e.emptyStr()?t:str`${e}${t}`}e.strConcat=strConcat;function interpolate(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:safeStringify(Array.isArray(e)?e.join(`,`):e)}function stringify(e){return new _Code(safeStringify(e))}e.stringify=stringify;function safeStringify(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=safeStringify;function getProperty(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new _Code(`.${t}`):_`[${t}]`}e.getProperty=getProperty;function getEsmExportName(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new _Code(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=getEsmExportName;function regexpCode(e){return new _Code(e.toString())}e.regexpCode=regexpCode})),Na=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ma();var ValueError=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},n;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var Scope=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){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=Scope;var ValueScopeName=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=ValueScopeName;let r=(0,t._)`\n`;var ValueScope=class extends Scope{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?r:t.nil}}get(){return this._scope}name(e){return new ValueScopeName(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let s=this._scope[r]||(this._scope[r]=[]),c=s.length;return s[c]=t.ref,n.setValue(t,{property:r,itemIndex:c}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(r,i,a={},s){let c=t.nil;for(let l in r){let u=r[l];if(!u)continue;let f=a[l]=a[l]||new Map;u.forEach(r=>{if(f.has(r))return;f.set(r,n.Started);let a=i(r);if(a){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${r} = ${a};${this.opts._n}`}else if(a=s?.(r))c=(0,t._)`${c}${a}${this.opts._n}`;else throw new ValueError(r);f.set(r,n.Completed)})}return c}};e.ValueScope=ValueScope})),R=r((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=Ma(),n=Na();var r=Ma();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Na();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.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 Node=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Def=class extends Node{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=optimizeExpr(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},Assign=class extends Node{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,e,n),this}get names(){return addExprNames(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Label=class extends Node{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Break=class extends Node{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},Throw=class extends Node{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},AnyCode=class extends Node{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=optimizeExpr(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},ParentNode=class extends Node{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(subtractNames(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>addNames(e,t.names),{})}},BlockNode=class extends ParentNode{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind=`else`;var a=class If extends BlockNode{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 e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let e=t.optimizeNodes();t=this.else=Array.isArray(e)?new Else(e):e}if(t)return e===!1?t instanceof If?t:t.nodes:this.nodes.length?this:new If(not(e),t instanceof If?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=optimizeExpr(this.condition,e,t),this}get names(){let e=super.names;return addExprNames(e,this.condition),this.else&&addNames(e,this.else.names),e}};a.kind=`if`;var For=class extends BlockNode{};For.kind=`for`;var ForLoop=class extends For{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=optimizeExpr(this.iteration,e,t),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}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=optimizeExpr(this.iterable,e,t),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};Func.kind=`func`;var Return=class extends ParentNode{render(e){return`return `+super.render(e)}};Return.kind=`return`;var Try=class extends BlockNode{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 n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&addNames(e,this.catch.names),this.finally&&addNames(e,this.finally.names),e}},Catch=class extends BlockNode{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Catch.kind=`catch`;var Finally=class extends BlockNode{render(e){return`finally`+super.render(e)}};Finally.kind=`finally`;var CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
167
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new Root]}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 n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}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,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new Def(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new Assign(e,t,n))}add(t,n){return this._leafNode(new AssignOp(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new AnyCode(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new a(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new a(e))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(a,Else)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new ForLoop(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let s=this._scope.toName(e);return this._for(new ForRange(a,s,t,r),()=>i(s))}forOf(e,r,i,a=n.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(s,(0,t._)`${e}[${n}]`),i(s)})}return this._for(new ForIter(`of`,a,s,r),()=>i(s))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let s=this._scope.toName(e);return this._for(new ForIter(`in`,a,s,r),()=>i(s))}endFor(){return this._endBlockNode(For)}label(e){return this._leafNode(new Label(e))}break(e){return this._leafNode(new Break(e))}return(e){let t=new Return;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(Return)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new Try;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new Catch(e),t(e)}return n&&(this._currNode=r.finally=new Finally,this.code(n)),this._endBlockNode(Catch,Finally)}throw(e){return this._leafNode(new Throw(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 n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new Func(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Func)}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 n=this._currNode;if(n instanceof e||t&&n 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 a))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}};e.CodeGen=CodeGen;function addNames(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function addExprNames(e,n){return n instanceof t._CodeOrName?addNames(e,n.names):e}function optimizeExpr(e,n,r){if(e instanceof t.Name)return replaceName(e);if(!canOptimize(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=replaceName(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function replaceName(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function canOptimize(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function subtractNames(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function not(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${par(e)}`}e.not=not;let s=mappend(e.operators.AND);function and(...e){return e.reduce(s)}e.and=and;let c=mappend(e.operators.OR);function or(...e){return e.reduce(c)}e.or=or;function mappend(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${par(n)} ${e} ${par(r)}`}function par(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),z=r((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=R(),n=Ma();function toHash(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=toHash;function alwaysValidSchema(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(checkUnknownRules(e,t),!schemaHasRules(t,e.self.RULES.all))}e.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||checkStrictMode(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=checkUnknownRules;function schemaHasRules(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(e){return unescapeJsonPointer(decodeURIComponent(e))}e.unescapeFragment=unescapeFragment;function escapeFragment(e){return encodeURIComponent(escapeJsonPointer(e))}e.escapeFragment=escapeFragment;function escapeJsonPointer(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=unescapeJsonPointer;function eachItem(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=eachItem;function makeMergeEvaluated({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,s,c,l)=>{let u=c===void 0?s:c instanceof t.Name?(s instanceof t.Name?e(a,s,c):n(a,s,c),c):s instanceof t.Name?(n(a,c,s),s):r(s,c);return l===t.Name&&!(u instanceof t.Name)?i(a,u):u}}e.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),setEvaluated(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function evaluatedPropsToName(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&setEvaluated(e,r,n),r}e.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=setEvaluated;let r={};function useFunc(e,t){return e.scopeValue(`func`,{ref:t,code:r[t.code]||(r[t.code]=new n._Code(t.code))})}e.useFunc=useFunc;var i;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(i||(e.Type=i={}));function getErrorPath(e,n,r){if(e instanceof t.Name){let a=n===i.Num;return r?a?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:a?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+escapeJsonPointer(e)}e.getErrorPath=getErrorPath;function checkStrictMode(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=checkStrictMode})),Pa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R();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`)}})),Fa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=R(),n=z(),r=Pa();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function reportError(n,r=e.keywordError,i,a){let{it:s}=n,{gen:c,compositeRule:l,allErrors:u}=s,f=errorObjectCode(n,r,i);a??(l||u)?addError(c,f):returnErrors(s,(0,t._)`[${f}]`)}e.reportError=reportError;function reportExtraError(t,n=e.keywordError,i){let{it:a}=t,{gen:s,compositeRule:c,allErrors:l}=a;addError(s,errorObjectCode(t,n,i)),c||l||returnErrors(a,r.default.vErrors)}e.reportExtraError=reportExtraError;function resetErrorsCount(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=resetErrorsCount;function extendErrors({gen:e,keyword:n,schemaValue:i,data:a,errsCount:s,it:c}){if(s===void 0)throw Error(`ajv implementation error`);let l=e.name(`err`);e.forRange(`i`,s,r.default.errors,s=>{e.const(l,(0,t._)`${r.default.vErrors}[${s}]`),e.if((0,t._)`${l}.instancePath === undefined`,()=>e.assign((0,t._)`${l}.instancePath`,(0,t.strConcat)(r.default.instancePath,c.errorPath))),e.assign((0,t._)`${l}.schemaPath`,(0,t.str)`${c.errSchemaPath}/${n}`),c.opts.verbose&&(e.assign((0,t._)`${l}.schema`,i),e.assign((0,t._)`${l}.data`,a))})}e.extendErrors=extendErrors;function addError(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function returnErrors(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let i={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 errorObjectCode(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:errorObject(e,n,r)}function errorObject(e,t,n={}){let{gen:r,it:i}=e,a=[errorInstancePath(i,n),errorSchemaPath(e,n)];return extraErrorProps(e,t,a),r.object(...a)}function errorInstancePath({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function errorSchemaPath({keyword:e,it:{errSchemaPath:r}},{schemaPath:a,parentSchema:s}){let c=s?r:(0,t.str)`${r}/${e}`;return a&&(c=(0,t.str)`${c}${(0,n.getErrorPath)(a,n.Type.Str)}`),[i.schemaPath,c]}function extraErrorProps(e,{params:n,message:a},s){let{keyword:c,data:l,schemaValue:u,it:f}=e,{opts:p,propertyName:m,topSchemaRef:h,schemaPath:g}=f;s.push([i.keyword,c],[i.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),p.messages&&s.push([i.message,typeof a==`function`?a(e):a]),p.verbose&&s.push([i.schema,u],[i.parentSchema,(0,t._)`${h}${g}`],[r.default.data,l]),m&&s.push([i.propertyName,m])}})),Ia=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Fa(),n=R(),r=Pa(),i={message:`boolean schema is false`};function topBoolOrEmptySchema(e){let{gen:t,schema:i,validateName:a}=e;i===!1?falseSchemaError(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),falseSchemaError(e)):n.var(t,!0)}e.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(e,n){let{gen:r,data:a}=e,s={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(s,i,void 0,n)}})),La=r((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 isJSONType(e){return typeof e==`string`&&t.has(e)}e.isJSONType=isJSONType;function getRules(){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=getRules})),Ra=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&shouldUseGroup(e,r)}e.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(e,t){return t.rules.some(t=>shouldUseRule(e,t))}e.shouldUseGroup=shouldUseGroup;function shouldUseRule(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=shouldUseRule})),za=r((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=La(),n=Ra(),r=Fa(),i=R(),a=z();var s;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(s||(e.DataType=s={}));function getSchemaTypes(e){let t=getJSONTypes(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=getSchemaTypes;function getJSONTypes(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(e,t){let{gen:r,data:i,opts:a}=e,c=coerceToTypes(t,a.coerceTypes),l=t.length>0&&!(c.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(l){let n=checkDataTypes(t,i,a.strictNumbers,s.Wrong);r.if(n,()=>{c.length?coerceData(e,t,c):reportTypeError(e)})}return l}e.coerceAndCheckDataType=coerceAndCheckDataType;let c=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function coerceToTypes(e,t){return t?e.filter(e=>c.has(e)||t===`array`&&e===`array`):[]}function coerceData(e,t,n){let{gen:r,data:a,opts:s}=e,l=r.let(`dataType`,(0,i._)`typeof ${a}`),u=r.let(`coerced`,(0,i._)`undefined`);s.coerceTypes===`array`&&r.if((0,i._)`${l} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(l,(0,i._)`typeof ${a}`).if(checkDataTypes(t,a,s.strictNumbers),()=>r.assign(u,a))),r.if((0,i._)`${u} !== undefined`);for(let e of n)(c.has(e)||e===`array`&&s.coerceTypes===`array`)&&coerceSpecificType(e);r.else(),reportTypeError(e),r.endIf(),r.if((0,i._)`${u} !== undefined`,()=>{r.assign(a,u),assignParentData(e,u)});function coerceSpecificType(e){switch(e){case`string`:r.elseIf((0,i._)`${l} == "number" || ${l} == "boolean"`).assign(u,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(u,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${l} == "boolean" || ${a} === null
166
+ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(let t of ui)ky[t]=(n,r)=>bi.create(n,validateAndMerge(e,r,{method:t}));return ky.create=e=>createInstance(validateAndMerge(e)),ky.extend=t=>(typeof t==`function`&&(t=t(e??{})),createInstance(validateAndMerge(e,t))),ky.stop=mi,ky.retry=retry,ky},xi=createInstance();var Si=r(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Ci=r(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),wi=r(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Si(),a=Ci();e=t.exports={};let s=e.re=[],c=e.safeRe=[],l=e.src=[],u=e.safeSrc=[],f=e.t={},p=0,m=`[a-zA-Z0-9-]`,h=[[`\\s`,1],[`\\d`,i],[m,r]],makeSafeRegex=e=>{for(let[t,n]of h)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},createToken=(e,t,n)=>{let r=makeSafeRegex(t),i=p++;a(e,i,t),f[e]=i,l[i]=t,u[i]=r,s[i]=new RegExp(t,n?`g`:void 0),c[i]=new RegExp(r,n?`g`:void 0)};createToken(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),createToken(`NUMERICIDENTIFIERLOOSE`,`\\d+`),createToken(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${m}*`),createToken(`MAINVERSION`,`(${l[f.NUMERICIDENTIFIER]})\\.(${l[f.NUMERICIDENTIFIER]})\\.(${l[f.NUMERICIDENTIFIER]})`),createToken(`MAINVERSIONLOOSE`,`(${l[f.NUMERICIDENTIFIERLOOSE]})\\.(${l[f.NUMERICIDENTIFIERLOOSE]})\\.(${l[f.NUMERICIDENTIFIERLOOSE]})`),createToken(`PRERELEASEIDENTIFIER`,`(?:${l[f.NONNUMERICIDENTIFIER]}|${l[f.NUMERICIDENTIFIER]})`),createToken(`PRERELEASEIDENTIFIERLOOSE`,`(?:${l[f.NONNUMERICIDENTIFIER]}|${l[f.NUMERICIDENTIFIERLOOSE]})`),createToken(`PRERELEASE`,`(?:-(${l[f.PRERELEASEIDENTIFIER]}(?:\\.${l[f.PRERELEASEIDENTIFIER]})*))`),createToken(`PRERELEASELOOSE`,`(?:-?(${l[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[f.PRERELEASEIDENTIFIERLOOSE]})*))`),createToken(`BUILDIDENTIFIER`,`${m}+`),createToken(`BUILD`,`(?:\\+(${l[f.BUILDIDENTIFIER]}(?:\\.${l[f.BUILDIDENTIFIER]})*))`),createToken(`FULLPLAIN`,`v?${l[f.MAINVERSION]}${l[f.PRERELEASE]}?${l[f.BUILD]}?`),createToken(`FULL`,`^${l[f.FULLPLAIN]}$`),createToken(`LOOSEPLAIN`,`[v=\\s]*${l[f.MAINVERSIONLOOSE]}${l[f.PRERELEASELOOSE]}?${l[f.BUILD]}?`),createToken(`LOOSE`,`^${l[f.LOOSEPLAIN]}$`),createToken(`GTLT`,`((?:<|>)?=?)`),createToken(`XRANGEIDENTIFIERLOOSE`,`${l[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),createToken(`XRANGEIDENTIFIER`,`${l[f.NUMERICIDENTIFIER]}|x|X|\\*`),createToken(`XRANGEPLAIN`,`[v=\\s]*(${l[f.XRANGEIDENTIFIER]})(?:\\.(${l[f.XRANGEIDENTIFIER]})(?:\\.(${l[f.XRANGEIDENTIFIER]})(?:${l[f.PRERELEASE]})?${l[f.BUILD]}?)?)?`),createToken(`XRANGEPLAINLOOSE`,`[v=\\s]*(${l[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[f.XRANGEIDENTIFIERLOOSE]})(?:${l[f.PRERELEASELOOSE]})?${l[f.BUILD]}?)?)?`),createToken(`XRANGE`,`^${l[f.GTLT]}\\s*${l[f.XRANGEPLAIN]}$`),createToken(`XRANGELOOSE`,`^${l[f.GTLT]}\\s*${l[f.XRANGEPLAINLOOSE]}$`),createToken(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),createToken(`COERCE`,`${l[f.COERCEPLAIN]}(?:$|[^\\d])`),createToken(`COERCEFULL`,l[f.COERCEPLAIN]+`(?:${l[f.PRERELEASE]})?(?:${l[f.BUILD]})?(?:$|[^\\d])`),createToken(`COERCERTL`,l[f.COERCE],!0),createToken(`COERCERTLFULL`,l[f.COERCEFULL],!0),createToken(`LONETILDE`,`(?:~>?)`),createToken(`TILDETRIM`,`(\\s*)${l[f.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,createToken(`TILDE`,`^${l[f.LONETILDE]}${l[f.XRANGEPLAIN]}$`),createToken(`TILDELOOSE`,`^${l[f.LONETILDE]}${l[f.XRANGEPLAINLOOSE]}$`),createToken(`LONECARET`,`(?:\\^)`),createToken(`CARETTRIM`,`(\\s*)${l[f.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,createToken(`CARET`,`^${l[f.LONECARET]}${l[f.XRANGEPLAIN]}$`),createToken(`CARETLOOSE`,`^${l[f.LONECARET]}${l[f.XRANGEPLAINLOOSE]}$`),createToken(`COMPARATORLOOSE`,`^${l[f.GTLT]}\\s*(${l[f.LOOSEPLAIN]})$|^$`),createToken(`COMPARATOR`,`^${l[f.GTLT]}\\s*(${l[f.FULLPLAIN]})$|^$`),createToken(`COMPARATORTRIM`,`(\\s*)${l[f.GTLT]}\\s*(${l[f.LOOSEPLAIN]}|${l[f.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,createToken(`HYPHENRANGE`,`^\\s*(${l[f.XRANGEPLAIN]})\\s+-\\s+(${l[f.XRANGEPLAIN]})\\s*$`),createToken(`HYPHENRANGELOOSE`,`^\\s*(${l[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[f.XRANGEPLAINLOOSE]})\\s*$`),createToken(`STAR`,`(<|>)?=?\\s*\\*`),createToken(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),createToken(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Ti=r(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({}),parseOptions=e=>e?typeof e==`object`?e:n:r;t.exports=parseOptions})),Ei=r(((e,t)=>{let n=/^[0-9]+$/,compareIdentifiers=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1},rcompareIdentifiers=(e,t)=>compareIdentifiers(t,e);t.exports={compareIdentifiers,rcompareIdentifiers}})),Di=r(((e,t)=>{let n=Ci(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Si(),{safeRe:a,t:s}=wi(),c=Ti(),{compareIdentifiers:l}=Ei(),isPrereleaseIdentifier=(e,t)=>{let n=t.split(`.`);if(n.length>e.length)return!1;for(let t=0;t<n.length;t++)if(l(e[t],n[t])!==0)return!1;return!0};t.exports=class SemVer{constructor(e,t){if(t=c(t),e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let l=e.trim().match(t.loose?a[s.LOOSE]:a[s.FULL]);if(!l)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);this.prerelease=l[4]?l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(e){if(n(`SemVer.compare`,this.version,this.options,e),!(e instanceof SemVer)){if(typeof e==`string`&&e===this.version)return 0;e=new SemVer(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof SemVer||(e=new SemVer(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:+(this.patch>e.patch)}comparePre(e){if(e instanceof SemVer||(e=new SemVer(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let r=this.prerelease[t],i=e.prerelease[t];if(n(`prerelease compare`,t,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r!==i)return l(r,i)}while(++t)}compareBuild(e){e instanceof SemVer||(e=new SemVer(e,this.options));let t=0;do{let r=this.build[t],i=e.build[t];if(n(`build compare`,t,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r!==i)return l(r,i)}while(++t)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[s.PRERELEASELOOSE]:a[s.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];if(n===!1&&(r=[t]),isPrereleaseIdentifier(this.prerelease,t)){let e=this.prerelease[t.split(`.`).length];isNaN(e)&&(this.prerelease=r)}else this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Oi=r(((e,t)=>{let n=Di(),parse=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}};t.exports=parse})),ki=r(((e,t)=>{let n=Oi(),valid=(e,t)=>{let r=n(e,t);return r?r.version:null};t.exports=valid})),Ai=r(((e,t)=>{let n=Oi(),clean=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null};t.exports=clean})),ji=r(((e,t)=>{let n=Di(),inc=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}};t.exports=inc})),Mi=r(((e,t)=>{let n=Oi(),diff=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let s=a>0,c=s?r:i,l=s?i:r,u=!!c.prerelease.length;if(l.prerelease.length&&!u){if(!l.patch&&!l.minor)return`major`;if(l.compareMain(c)===0)return l.minor&&!l.patch?`minor`:`patch`}let f=u?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:f+`patch`:f+`minor`:f+`major`};t.exports=diff})),Ni=r(((e,t)=>{let n=Di(),major=(e,t)=>new n(e,t).major;t.exports=major})),Pi=r(((e,t)=>{let n=Di(),minor=(e,t)=>new n(e,t).minor;t.exports=minor})),Fi=r(((e,t)=>{let n=Di(),patch=(e,t)=>new n(e,t).patch;t.exports=patch})),Ii=r(((e,t)=>{let n=Oi(),prerelease=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};t.exports=prerelease})),Li=r(((e,t)=>{let n=Di(),compare=(e,t,r)=>new n(e,r).compare(new n(t,r));t.exports=compare})),Ri=r(((e,t)=>{let n=Li(),rcompare=(e,t,r)=>n(t,e,r);t.exports=rcompare})),zi=r(((e,t)=>{let n=Li(),compareLoose=(e,t)=>n(e,t,!0);t.exports=compareLoose})),Bi=r(((e,t)=>{let n=Di(),compareBuild=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)};t.exports=compareBuild})),Vi=r(((e,t)=>{let n=Bi(),sort=(e,t)=>e.sort((e,r)=>n(e,r,t));t.exports=sort})),Hi=r(((e,t)=>{let n=Bi(),rsort=(e,t)=>e.sort((e,r)=>n(r,e,t));t.exports=rsort})),Ui=r(((e,t)=>{let n=Li(),gt=(e,t,r)=>n(e,t,r)>0;t.exports=gt})),Wi=r(((e,t)=>{let n=Li(),lt=(e,t,r)=>n(e,t,r)<0;t.exports=lt})),Gi=r(((e,t)=>{let n=Li(),eq=(e,t,r)=>n(e,t,r)===0;t.exports=eq})),Ki=r(((e,t)=>{let n=Li(),neq=(e,t,r)=>n(e,t,r)!==0;t.exports=neq})),qi=r(((e,t)=>{let n=Li(),gte=(e,t,r)=>n(e,t,r)>=0;t.exports=gte})),Ji=r(((e,t)=>{let n=Li(),lte=(e,t,r)=>n(e,t,r)<=0;t.exports=lte})),Yi=r(((e,t)=>{let n=Gi(),r=Ki(),i=Ui(),a=qi(),s=Wi(),c=Ji(),cmp=(e,t,l,u)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof l==`object`&&(l=l.version),e===l;case`!==`:return typeof e==`object`&&(e=e.version),typeof l==`object`&&(l=l.version),e!==l;case``:case`=`:case`==`:return n(e,l,u);case`!=`:return r(e,l,u);case`>`:return i(e,l,u);case`>=`:return a(e,l,u);case`<`:return s(e,l,u);case`<=`:return c(e,l,u);default:throw TypeError(`Invalid operator: ${t}`)}};t.exports=cmp})),Xi=r(((e,t)=>{let n=Di(),r=Oi(),{safeRe:i,t:a}=wi(),coerce=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let s=null;if(!t.rtl)s=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!s||s.index+s[0].length!==e.length);)(!s||r.index+r[0].length!==s.index+s[0].length)&&(s=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(s===null)return null;let c=s[2],l=s[3]||`0`,u=s[4]||`0`,f=t.includePrerelease&&s[5]?`-${s[5]}`:``,p=t.includePrerelease&&s[6]?`+${s[6]}`:``;return r(`${c}.${l}.${u}${f}${p}`,t)};t.exports=coerce})),Zi=r(((e,t)=>{let n=Oi(),r=Si(),i=Di(),truncate=(e,t,n)=>{if(!r.RELEASE_TYPES.includes(t))return null;let i=cloneInputVersion(e,n);return i&&doTruncation(i,t)},cloneInputVersion=(e,t)=>{let r=e instanceof i?e.version:e;return n(r,t)},doTruncation=(e,t)=>{if(isPrerelease(t))return e.version;switch(e.prerelease=[],t){case`major`:e.minor=0,e.patch=0;break;case`minor`:e.patch=0}return e.format()},isPrerelease=e=>e.startsWith(`pre`);t.exports=truncate})),Qi=r(((e,t)=>{var LRUCache=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}};t.exports=LRUCache})),$i=r(((e,t)=>{let n=/\s+/g;t.exports=class Range{constructor(e,t){if(t=i(t),e instanceof Range)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new Range(e.raw,t);if(e instanceof a)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!isNullSet(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&isAny(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(y,``);let t=((this.options.includePrerelease&&g)|(this.options.loose&&v))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,c=i?l[f.HYPHENRANGELOOSE]:l[f.HYPHENRANGE];e=e.replace(c,hyphenReplace(this.options.includePrerelease)),s(`hyphen replace`,e),e=e.replace(l[f.COMPARATORTRIM],p),s(`comparator trim`,e),e=e.replace(l[f.TILDETRIM],m),s(`tilde trim`,e),e=e.replace(l[f.CARETTRIM],h),s(`caret trim`,e);let u=e.split(` `).map(e=>parseComparator(e,this.options)).join(` `).split(/\s+/).map(e=>replaceGTE0(e,this.options));i&&(u=u.filter(e=>(s(`loose invalid filter`,e,this.options),!!e.match(l[f.COMPARATORLOOSE])))),s(`range list`,u);let b=new Map,ee=u.map(e=>new a(e,this.options));for(let e of ee){if(isNullSet(e))return[e];b.set(e.value,e)}b.size>1&&b.has(``)&&b.delete(``);let te=[...b.values()];return r.set(t,te),te}intersects(e,t){if(!(e instanceof Range))throw TypeError(`a Range is required`);return this.set.some(n=>isSatisfiable(n,t)&&e.set.some(e=>isSatisfiable(e,t)&&n.every(n=>e.every(e=>n.intersects(e,t)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(testSet(this.set[t],e,this.options))return!0;return!1}};let r=new(Qi()),i=Ti(),a=ea(),s=Ci(),c=Di(),{safeRe:l,src:u,t:f,comparatorTrimReplace:p,tildeTrimReplace:m,caretTrimReplace:h}=wi(),{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:v}=Si(),y=new RegExp(u[f.BUILD],`g`),isNullSet=e=>e.value===`<0.0.0-0`,isAny=e=>e.value===``,isSatisfiable=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},parseComparator=(e,t)=>(e=e.replace(l[f.BUILD],``),s(`comp`,e,t),e=replaceCarets(e,t),s(`caret`,e),e=replaceTildes(e,t),s(`tildes`,e),e=replaceXRanges(e,t),s(`xrange`,e),e=replaceStars(e,t),s(`stars`,e),e),isX=e=>!e||e.toLowerCase()===`x`||e===`*`,invalidXRangeOrder=(e,t,n)=>isX(e)&&!isX(t)||isX(t)&&n&&!isX(n),replaceTildes=(e,t)=>e.trim().split(/\s+/).map(e=>replaceTilde(e,t)).join(` `),replaceTilde=(e,t)=>{let n=t.loose?l[f.TILDELOOSE]:l[f.TILDE],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,c)=>{s(`tilde`,e,t,n,i,a,c);let l;return isX(n)?l=``:isX(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:isX(a)?l=`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:c?(s(`replaceTilde pr`,c),l=`>=${n}.${i}.${a}-${c} <${n}.${+i+1}.0-0`):l=`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`,s(`tilde return`,l),l})},replaceCarets=(e,t)=>e.trim().split(/\s+/).map(e=>replaceCaret(e,t)).join(` `),replaceCaret=(e,t)=>{s(`caret`,e,t);let n=t.loose?l[f.CARETLOOSE]:l[f.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,c)=>{s(`caret`,e,t,n,i,a,c);let l;return isX(n)?l=``:isX(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:isX(a)?l=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:c?(s(`replaceCaret pr`,c),l=n===`0`?i===`0`?`>=${n}.${i}.${a}-${c} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${c} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${c} <${+n+1}.0.0-0`):(s(`no pr`),l=n===`0`?i===`0`?`>=${n}.${i}.${a} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),s(`caret return`,l),l})},replaceXRanges=(e,t)=>(s(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>replaceXRange(e,t)).join(` `)),replaceXRange=(e,t)=>{e=e.trim();let n=t.loose?l[f.XRANGELOOSE]:l[f.XRANGE];return e.replace(n,(n,r,i,a,c,l)=>{if(s(`xRange`,e,n,r,i,a,c,l),invalidXRangeOrder(i,a,c))return e;let u=isX(i),f=u||isX(a),p=f||isX(c),m=p;return r===`=`&&m&&(r=``),l=t.includePrerelease?`-0`:``,u?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&m?(f&&(a=0),c=0,r===`>`?(r=`>=`,f?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):r===`<=`&&(r=`<`,f?i=+i+1:a=+a+1),r===`<`&&(l=`-0`),n=`${r+i}.${a}.${c}${l}`):f?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),s(`xRange return`,n),n})},replaceStars=(e,t)=>(s(`replaceStars`,e,t),e.trim().replace(l[f.STAR],``)),replaceGTE0=(e,t)=>(s(`replaceGTE0`,e,t),e.trim().replace(l[t.includePrerelease?f.GTE0PRE:f.GTE0],``)),hyphenReplace=e=>(t,n,r,i,a,s,c,l,u,f,p,m)=>(n=isX(r)?``:isX(i)?`>=${r}.0.0${e?`-0`:``}`:isX(a)?`>=${r}.${i}.0${e?`-0`:``}`:s?`>=${n}`:`>=${n}${e?`-0`:``}`,l=isX(u)?``:isX(f)?`<${+u+1}.0.0-0`:isX(p)?`<${u}.${+f+1}.0-0`:m?`<=${u}.${f}.${p}-${m}`:e?`<${u}.${f}.${+p+1}-0`:`<=${l}`,`${n} ${l}`.trim()),testSet=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(s(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),ea=r(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class Comparator{static get ANY(){return n}constructor(e,t){if(t=r(t),e instanceof Comparator){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(` `),c(`comparator`,e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.value=this.semver===n?``:this.operator+this.semver.version,c(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),this.semver=r[2]?new l(r[2],this.options.loose):n}toString(){return this.value}test(e){if(c(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new l(e,this.options)}catch{return!1}return s(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``||new u(e.value,t).test(this.value):e.operator===``?e.value===``||new u(this.value,t).test(e.semver):(t=r(t),t.includePrerelease&&(this.value===`<0.0.0-0`||e.value===`<0.0.0-0`)||!t.includePrerelease&&(this.value.startsWith(`<0.0.0`)||e.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&e.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&e.operator.startsWith(`<`)||this.semver.version===e.semver.version&&this.operator.includes(`=`)&&e.operator.includes(`=`)||s(this.semver,`<`,e.semver,t)&&this.operator.startsWith(`>`)&&e.operator.startsWith(`<`)||s(this.semver,`>`,e.semver,t)&&this.operator.startsWith(`<`)&&e.operator.startsWith(`>`)))}};let r=Ti(),{safeRe:i,t:a}=wi(),s=Yi(),c=Ci(),l=Di(),u=$i()})),ta=r(((e,t)=>{let n=$i(),satisfies=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)};t.exports=satisfies})),na=r(((e,t)=>{let n=$i(),toComparators=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `));t.exports=toComparators})),ra=r(((e,t)=>{let n=Di(),r=$i(),maxSatisfying=(e,t,i)=>{let a=null,s=null,c=null;try{c=new r(t,i)}catch{return null}return e.forEach(e=>{c.test(e)&&(!a||s.compare(e)===-1)&&(a=e,s=new n(a,i))}),a};t.exports=maxSatisfying})),ia=r(((e,t)=>{let n=Di(),r=$i(),minSatisfying=(e,t,i)=>{let a=null,s=null,c=null;try{c=new r(t,i)}catch{return null}return e.forEach(e=>{c.test(e)&&(!a||s.compare(e)===1)&&(a=e,s=new n(a,i))}),a};t.exports=minSatisfying})),aa=r(((e,t)=>{let n=Di(),r=$i(),i=Ui(),minVersion=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],s=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!s||i(t,s))&&(s=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),s&&(!a||i(a,s))&&(a=s)}return a&&e.test(a)?a:null};t.exports=minVersion})),oa=r(((e,t)=>{let n=$i(),validRange=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}};t.exports=validRange})),sa=r(((e,t)=>{let n=Di(),r=ea(),{ANY:i}=r,a=$i(),s=ta(),c=Ui(),l=Wi(),u=Ji(),f=qi(),outside=(e,t,p,m)=>{e=new n(e,m),t=new a(t,m);let h,g,v,y,b;switch(p){case`>`:h=c,g=u,v=l,y=`>`,b=`>=`;break;case`<`:h=l,g=f,v=c,y=`<`,b=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(s(e,t,m))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],s=null,c=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),s||=e,c||=e,h(e.semver,s.semver,m)?s=e:v(e.semver,c.semver,m)&&(c=e)}),s.operator===y||s.operator===b||(!c.operator||c.operator===y)&&g(e,c.semver)||c.operator===b&&v(e,c.semver))return!1}return!0};t.exports=outside})),ca=r(((e,t)=>{let n=sa(),gtr=(e,t,r)=>n(e,t,`>`,r);t.exports=gtr})),la=r(((e,t)=>{let n=sa(),ltr=(e,t,r)=>n(e,t,`<`,r);t.exports=ltr})),ua=r(((e,t)=>{let n=$i(),intersects=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r));t.exports=intersects})),da=r(((e,t)=>{let n=ta(),r=Li();t.exports=(e,t,i)=>{let a=[],s=null,c=null,l=e.sort((e,t)=>r(e,t,i));for(let e of l)n(e,t,i)?(c=e,s||=e):(c&&a.push([s,c]),c=null,s=null);s&&a.push([s,null]);let u=[];for(let[e,t]of a)e===t?u.push(e):!t&&e===l[0]?u.push(`*`):t?e===l[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`);let f=u.join(` || `),p=typeof t.raw==`string`?t.raw:String(t);return f.length<p.length?f:t}})),fa=r(((e,t)=>{let n=$i(),r=ea(),{ANY:i}=r,a=ta(),s=Li(),subset=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=simpleSubset(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],simpleSubset=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,u,f;for(let t of e)t.operator===`>`||t.operator===`>=`?u=higherGT(u,t,n):t.operator===`<`||t.operator===`<=`?f=lowerLT(f,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(u&&f&&(p=s(u.semver,f.semver,n),p>0||p===0&&(u.operator!==`>=`||f.operator!==`<=`)))return null;for(let e of r){if(u&&!a(e,String(u),n)||f&&!a(e,String(f),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,v,y=f&&!n.includePrerelease&&f.semver.prerelease.length?f.semver:!1,b=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1;y&&y.prerelease.length===1&&f.operator===`<`&&y.prerelease[0]===0&&(y=!1);for(let e of t){if(v=v||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,u){if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),e.operator===`>`||e.operator===`>=`){if(m=higherGT(u,e,n),m===e&&m!==u)return!1}else if(u.operator===`>=`&&!e.test(u.semver))return!1}if(f){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`<`||e.operator===`<=`){if(h=lowerLT(f,e,n),h===e&&h!==f)return!1}else if(f.operator===`<=`&&!e.test(f.semver))return!1}if(!e.operator&&(f||u)&&p!==0)return!1}return!(u&&g&&!f&&p!==0||f&&v&&!u&&p!==0||b||y)},higherGT=(e,t,n)=>{if(!e)return t;let r=s(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},lowerLT=(e,t,n)=>{if(!e)return t;let r=s(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=subset})),pa=e(r(((e,t)=>{let n=wi(),r=Si(),i=Di(),a=Ei();t.exports={parse:Oi(),valid:ki(),clean:Ai(),inc:ji(),diff:Mi(),major:Ni(),minor:Pi(),patch:Fi(),prerelease:Ii(),compare:Li(),rcompare:Ri(),compareLoose:zi(),compareBuild:Bi(),sort:Vi(),rsort:Hi(),gt:Ui(),lt:Wi(),eq:Gi(),neq:Ki(),gte:qi(),lte:Ji(),cmp:Yi(),coerce:Xi(),truncate:Zi(),Comparator:ea(),Range:$i(),satisfies:ta(),toComparators:na(),maxSatisfying:ra(),minSatisfying:ia(),minVersion:aa(),validRange:oa(),outside:sa(),gtr:ca(),ltr:la(),intersects:ua(),simplifyRange:da(),subset:fa(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))(),1);const isObject=e=>{let t=typeof e;return e!==null&&(t===`object`||t===`function`)},ma=new Set([`__proto__`,`prototype`,`constructor`]),ha=1e6,isDigit=e=>e>=`0`&&e<=`9`;function shouldCoerceToNumber(e){if(e===`0`)return!0;if(/^[1-9]\d*$/.test(e)){let t=Number.parseInt(e,10);return t<=2**53-1&&t<=ha}return!1}function processSegment(e,t){return!ma.has(e)&&(e&&shouldCoerceToNumber(e)?t.push(Number.parseInt(e,10)):t.push(e),!0)}function parsePath(e){if(typeof e!=`string`)throw TypeError(`Expected a string, got ${typeof e}`);let t=[],n=``,r=`start`,i=!1,a=0;for(let s of e){if(a++,i){n+=s,i=!1;continue}if(s===`\\`){if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);i=!0,r=r===`start`?`property`:r;continue}switch(s){case`.`:if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`){r=`property`;break}if(!processSegment(n,t))return[];n=``,r=`property`;break;case`[`:if(r===`index`)throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`){r=`index`;break}if(r===`property`||r===`start`){if((n||r===`property`)&&!processSegment(n,t))return[];n=``}r=`index`;break;case`]`:if(r===`index`){if(n===``)n=(t.pop()||``)+`[]`,r=`property`;else{let e=Number.parseInt(n,10);!Number.isNaN(e)&&Number.isFinite(e)&&e>=0&&e<=2**53-1&&e<=ha&&n===String(e)?t.push(e):t.push(n),n=``,r=`indexEnd`}break}if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);n+=s;break;default:if(r===`index`&&!isDigit(s))throw Error(`Invalid character '${s}' in an index at position ${a}`);if(r===`indexEnd`)throw Error(`Invalid character '${s}' after an index at position ${a}`);r===`start`&&(r=`property`),n+=s}}switch(i&&(n+=`\\`),r){case`property`:if(!processSegment(n,t))return[];break;case`index`:throw Error(`Index was not closed`);case`start`:t.push(``)}return t}function normalizePath(e){if(typeof e==`string`)return parsePath(e);if(Array.isArray(e)){let t=[];for(let[n,r]of e.entries()){if(typeof r!=`string`&&typeof r!=`number`)throw TypeError(`Expected a string or number for path segment at index ${n}, got ${typeof r}`);if(typeof r==`number`&&!Number.isFinite(r))throw TypeError(`Path segment at index ${n} must be a finite number, got ${r}`);if(ma.has(r))return[];typeof r==`string`&&shouldCoerceToNumber(r)?t.push(Number.parseInt(r,10)):t.push(r)}return t}return[]}function getProperty(e,t,n){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return n===void 0?e:n;let r=normalizePath(t);if(r.length===0)return n;for(let t=0;t<r.length;t++){let i=r[t];if(e=e[i],e==null){if(t!==r.length-1)return n;break}}return e===void 0?n:e}function setProperty(e,t,n){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return e;let r=e,i=normalizePath(t);if(i.length===0)return e;for(let t=0;t<i.length;t++){let r=i[t];if(t===i.length-1)e[r]=n;else if(!isObject(e[r])){let n=typeof i[t+1]==`number`;e[r]=n?[]:{}}e=e[r]}return r}function deleteProperty(e,t){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return!1;let n=normalizePath(t);if(n.length===0)return!1;for(let t=0;t<n.length;t++){let r=n[t];if(t===n.length-1)return Object.hasOwn(e,r)?(delete e[r],!0):!1;if(e=e[r],!isObject(e))return!1}}function hasProperty(e,t){if(!isObject(e)||typeof t!=`string`&&!Array.isArray(t))return!1;let n=normalizePath(t);if(n.length===0)return!1;for(let t of n){if(!isObject(e)||!(t in e))return!1;e=e[t]}return!0}const ga=hn.homedir(),_a=hn.tmpdir(),{env:va}=I,macos=e=>{let t=N.join(ga,`Library`);return{data:N.join(t,`Application Support`,e),config:N.join(t,`Preferences`,e),cache:N.join(t,`Caches`,e),log:N.join(t,`Logs`,e),temp:N.join(_a,e)}},windows=e=>{let t=va.APPDATA||N.join(ga,`AppData`,`Roaming`),n=va.LOCALAPPDATA||N.join(ga,`AppData`,`Local`);return{data:N.join(n,e,`Data`),config:N.join(t,e,`Config`),cache:N.join(n,e,`Cache`),log:N.join(n,e,`Log`),temp:N.join(_a,e)}},linux=e=>{let t=N.basename(ga);return{data:N.join(va.XDG_DATA_HOME||N.join(ga,`.local`,`share`),e),config:N.join(va.XDG_CONFIG_HOME||N.join(ga,`.config`),e),cache:N.join(va.XDG_CACHE_HOME||N.join(ga,`.cache`),e),log:N.join(va.XDG_STATE_HOME||N.join(ga,`.local`,`state`),e),temp:N.join(_a,t,e)}};function envPaths(e,{suffix:t=`nodejs`}={}){if(typeof e!=`string`)throw TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),I.platform===`darwin`?macos(e):I.platform===`win32`?windows(e):linux(e)}const attemptifyAsync=(e,t)=>function attemptified(...n){return e.apply(void 0,n).catch(t)},attemptifySync=(e,t)=>function attemptified(...n){try{return e.apply(void 0,n)}catch(e){return t(e)}},ya=I.getuid?!I.getuid():!1,NOOP=()=>void 0,B={isChangeErrorOk:e=>{if(!B.isNodeError(e))return!1;let{code:t}=e;return t===`ENOSYS`||!ya&&(t===`EINVAL`||t===`EPERM`)},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!B.isNodeError(e))return!1;let{code:t}=e;return t===`EMFILE`||t===`ENFILE`||t===`EAGAIN`||t===`EBUSY`||t===`EACCESS`||t===`EACCES`||t===`EACCS`||t===`EPERM`},onChangeError:e=>{if(!B.isNodeError(e)||!B.isChangeErrorOk(e))throw e}};var RetryfyQueue=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=1e4,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||=setInterval(this.tick,this.interval)},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=e=>{this.queueWaiting.add(e),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=e=>{this.queueWaiting.delete(e),this.queueActive.delete(e)},this.schedule=()=>new Promise(e=>{let cleanup=()=>this.remove(resolver),resolver=()=>e(cleanup);this.add(resolver)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let e of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(e),this.queueActive.add(e),e()}}}}},ba=new RetryfyQueue;const retryifyAsync=(e,t)=>function retrified(n){return function attempt(...r){return ba.schedule().then(i=>{let onResolve=e=>(i(),e),onReject=e=>{if(i(),Date.now()>=n)throw e;if(t(e)){let e=Math.round(100*Math.random());return new Promise(t=>setTimeout(t,e)).then(()=>attempt.apply(void 0,r))}throw e};return e.apply(void 0,r).then(onResolve,onReject)})}},retryifySync=(e,t)=>function retrified(n){return function attempt(...r){try{return e.apply(void 0,r)}catch(e){if(Date.now()>n)throw e;if(t(e))return attempt.apply(void 0,r);throw e}}},xa={attempt:{chmod:attemptifyAsync(jt(F.chmod),B.onChangeError),chown:attemptifyAsync(jt(F.chown),B.onChangeError),close:attemptifyAsync(jt(F.close),NOOP),fsync:attemptifyAsync(jt(F.fsync),NOOP),mkdir:attemptifyAsync(jt(F.mkdir),NOOP),realpath:attemptifyAsync(jt(F.realpath),NOOP),stat:attemptifyAsync(jt(F.stat),NOOP),unlink:attemptifyAsync(jt(F.unlink),NOOP),chmodSync:attemptifySync(F.chmodSync,B.onChangeError),chownSync:attemptifySync(F.chownSync,B.onChangeError),closeSync:attemptifySync(F.closeSync,NOOP),existsSync:attemptifySync(F.existsSync,NOOP),fsyncSync:attemptifySync(F.fsync,NOOP),mkdirSync:attemptifySync(F.mkdirSync,NOOP),realpathSync:attemptifySync(F.realpathSync,NOOP),statSync:attemptifySync(F.statSync,NOOP),unlinkSync:attemptifySync(F.unlinkSync,NOOP)},retry:{close:retryifyAsync(jt(F.close),B.isRetriableError),fsync:retryifyAsync(jt(F.fsync),B.isRetriableError),open:retryifyAsync(jt(F.open),B.isRetriableError),readFile:retryifyAsync(jt(F.readFile),B.isRetriableError),rename:retryifyAsync(jt(F.rename),B.isRetriableError),stat:retryifyAsync(jt(F.stat),B.isRetriableError),write:retryifyAsync(jt(F.write),B.isRetriableError),writeFile:retryifyAsync(jt(F.writeFile),B.isRetriableError),closeSync:retryifySync(F.closeSync,B.isRetriableError),fsyncSync:retryifySync(F.fsyncSync,B.isRetriableError),openSync:retryifySync(F.openSync,B.isRetriableError),readFileSync:retryifySync(F.readFileSync,B.isRetriableError),renameSync:retryifySync(F.renameSync,B.isRetriableError),statSync:retryifySync(F.statSync,B.isRetriableError),writeSync:retryifySync(F.writeSync,B.isRetriableError),writeFileSync:retryifySync(F.writeFileSync,B.isRetriableError)}},Sa={},Ca=hn.userInfo().uid,wa=hn.userInfo().gid,Ta=!!I.getuid;I.getuid&&I.getuid();const isException=e=>e instanceof Error&&`code`in e,Ea=t(e=>typeof e==`string`,`isString`),isUndefined=e=>e===void 0,Da=I.platform===`linux`,Oa=I.platform===`win32`,ka=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`];Oa||ka.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),Da&&ka.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`);var Interceptor=class{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=e=>{if(!this.exited){this.exited=!0;for(let e of this.callbacks)e();e&&(Oa&&e!==`SIGINT`&&e!==`SIGTERM`&&e!==`SIGKILL`?I.kill(I.pid,`SIGTERM`):I.kill(I.pid,e))}},this.hook=()=>{I.once(`exit`,()=>this.exit());for(let e of ka)try{I.once(e,()=>this.exit(e))}catch{}},this.register=e=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}};const Aa=new Interceptor().register,ja={store:{},create:e=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6);return`${e}${`.tmp-${Date.now().toString().slice(-10)}${t}`}`},get:(e,t,n=!0)=>{let r=ja.truncate(t(e));if(r in ja.store)return ja.get(e,t,n);ja.store[r]=n;let disposer=()=>delete ja.store[r];return[r,disposer]},purge:e=>{ja.store[e]&&(delete ja.store[e],xa.attempt.unlink(e))},purgeSync:e=>{ja.store[e]&&(delete ja.store[e],xa.attempt.unlinkSync(e))},purgeSyncAll:()=>{for(let e in ja.store)ja.purgeSync(e)},truncate:e=>{let t=N.basename(e);if(t.length<=128)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-128;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};Aa(ja.purgeSyncAll);function writeFileSync$1(e,t,n=Sa){if(Ea(n))return writeFileSync$1(e,t,{encoding:n});let r=Date.now()+((n.timeout??1e3)||-1),i=null,a=null,s=null;try{let c=xa.attempt.realpathSync(e),l=!!c;e=c||e,[a,i]=ja.get(e,n.tmpCreate||ja.create,n.tmpPurge!==!1);let u=Ta&&isUndefined(n.chown),f=isUndefined(n.mode);if(l&&(u||f)){let t=xa.attempt.statSync(e);t&&(n={...n},u&&(n.chown={uid:t.uid,gid:t.gid}),f&&(n.mode=t.mode))}if(!l){let t=N.dirname(e);xa.attempt.mkdirSync(t,{mode:511,recursive:!0})}s=xa.retry.openSync(r)(a,`w`,n.mode||438),n.tmpCreated&&n.tmpCreated(a),Ea(t)?xa.retry.writeSync(r)(s,t,0,n.encoding||`utf8`):isUndefined(t)||xa.retry.writeSync(r)(s,t,0,t.length,0),n.fsync!==!1&&(n.fsyncWait===!1?xa.attempt.fsync(s):xa.retry.fsyncSync(r)(s)),xa.retry.closeSync(r)(s),s=null,n.chown&&(n.chown.uid!==Ca||n.chown.gid!==wa)&&xa.attempt.chownSync(a,n.chown.uid,n.chown.gid),n.mode&&n.mode!==438&&xa.attempt.chmodSync(a,n.mode);try{xa.retry.renameSync(r)(a,e)}catch(t){if(!isException(t)||t.code!==`ENAMETOOLONG`)throw t;xa.retry.renameSync(r)(a,ja.truncate(e))}i(),a=null}finally{s&&xa.attempt.closeSync(s),a&&ja.purge(a)}}t(writeFileSync$1,`writeFileSync`);var Ma=r((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 _CodeOrName=class{};e._CodeOrName=_CodeOrName,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Name=class extends _CodeOrName{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=Name;var _Code=class extends _CodeOrName{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(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof Name&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=_Code,e.nil=new _Code(``);function _(e,...t){let n=[e[0]],r=0;for(;r<t.length;)addCodeArg(n,t[r]),n.push(e[++r]);return new _Code(n)}e._=_;let t=new _Code(`+`);function str(e,...n){let r=[safeStringify(e[0])],i=0;for(;i<n.length;)r.push(t),addCodeArg(r,n[i]),r.push(t,safeStringify(e[++i]));return optimize(r),new _Code(r)}e.str=str;function addCodeArg(e,t){t instanceof _Code?e.push(...t._items):t instanceof Name?e.push(t):e.push(interpolate(t))}e.addCodeArg=addCodeArg;function optimize(e){let n=1;for(;n<e.length-1;){if(e[n]===t){let t=mergeExprItems(e[n-1],e[n+1]);if(t!==void 0){e.splice(n-1,3,t);continue}e[n++]=`+`}n++}}function mergeExprItems(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof Name||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 Name))return`"${e}${t.slice(1)}`}function strConcat(e,t){return t.emptyStr()?e:e.emptyStr()?t:str`${e}${t}`}e.strConcat=strConcat;function interpolate(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:safeStringify(Array.isArray(e)?e.join(`,`):e)}function stringify(e){return new _Code(safeStringify(e))}e.stringify=stringify;function safeStringify(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=safeStringify;function getProperty(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new _Code(`.${t}`):_`[${t}]`}e.getProperty=getProperty;function getEsmExportName(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new _Code(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=getEsmExportName;function regexpCode(e){return new _Code(e.toString())}e.regexpCode=regexpCode})),Na=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ma();var ValueError=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},n;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var Scope=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){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=Scope;var ValueScopeName=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=ValueScopeName;let r=(0,t._)`\n`;var ValueScope=class extends Scope{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?r:t.nil}}get(){return this._scope}name(e){return new ValueScopeName(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let s=this._scope[r]||(this._scope[r]=[]),c=s.length;return s[c]=t.ref,n.setValue(t,{property:r,itemIndex:c}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(r,i,a={},s){let c=t.nil;for(let l in r){let u=r[l];if(!u)continue;let f=a[l]=a[l]||new Map;u.forEach(r=>{if(f.has(r))return;f.set(r,n.Started);let a=i(r);if(a){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${r} = ${a};${this.opts._n}`}else if(a=s?.(r))c=(0,t._)`${c}${a}${this.opts._n}`;else throw new ValueError(r);f.set(r,n.Completed)})}return c}};e.ValueScope=ValueScope})),V=r((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=Ma(),n=Na();var r=Ma();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Na();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.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 Node=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Def=class extends Node{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=optimizeExpr(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},Assign=class extends Node{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=optimizeExpr(this.rhs,e,n),this}get names(){return addExprNames(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},AssignOp=class extends Assign{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Label=class extends Node{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Break=class extends Node{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},Throw=class extends Node{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},AnyCode=class extends Node{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=optimizeExpr(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},ParentNode=class extends Node{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(subtractNames(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>addNames(e,t.names),{})}},BlockNode=class extends ParentNode{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},Root=class extends ParentNode{},Else=class extends BlockNode{};Else.kind=`else`;var a=class If extends BlockNode{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 e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let e=t.optimizeNodes();t=this.else=Array.isArray(e)?new Else(e):e}if(t)return e===!1?t instanceof If?t:t.nodes:this.nodes.length?this:new If(not(e),t instanceof If?[t]:t.nodes);if(e!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=optimizeExpr(this.condition,e,t),this}get names(){let e=super.names;return addExprNames(e,this.condition),this.else&&addNames(e,this.else.names),e}};a.kind=`if`;var For=class extends BlockNode{};For.kind=`for`;var ForLoop=class extends For{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=optimizeExpr(this.iteration,e,t),this}get names(){return addNames(super.names,this.iteration.names)}},ForRange=class extends For{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return addExprNames(addExprNames(super.names,this.from),this.to)}},ForIter=class extends For{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}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=optimizeExpr(this.iterable,e,t),this}get names(){return addNames(super.names,this.iterable.names)}},Func=class extends BlockNode{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};Func.kind=`func`;var Return=class extends ParentNode{render(e){return`return `+super.render(e)}};Return.kind=`return`;var Try=class extends BlockNode{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 n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&addNames(e,this.catch.names),this.finally&&addNames(e,this.finally.names),e}},Catch=class extends BlockNode{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Catch.kind=`catch`;var Finally=class extends BlockNode{render(e){return`finally`+super.render(e)}};Finally.kind=`finally`;var CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
167
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new Root]}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 n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}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,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new Def(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new Assign(e,t,n))}add(t,n){return this._leafNode(new AssignOp(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new AnyCode(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new a(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new a(e))}else(){return this._elseNode(new Else)}endIf(){return this._endBlockNode(a,Else)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new ForLoop(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let s=this._scope.toName(e);return this._for(new ForRange(a,s,t,r),()=>i(s))}forOf(e,r,i,a=n.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(s,(0,t._)`${e}[${n}]`),i(s)})}return this._for(new ForIter(`of`,a,s,r),()=>i(s))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let s=this._scope.toName(e);return this._for(new ForIter(`in`,a,s,r),()=>i(s))}endFor(){return this._endBlockNode(For)}label(e){return this._leafNode(new Label(e))}break(e){return this._leafNode(new Break(e))}return(e){let t=new Return;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(Return)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new Try;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new Catch(e),t(e)}return n&&(this._currNode=r.finally=new Finally,this.code(n)),this._endBlockNode(Catch,Finally)}throw(e){return this._leafNode(new Throw(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 n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new Func(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Func)}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 n=this._currNode;if(n instanceof e||t&&n 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 a))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}};e.CodeGen=CodeGen;function addNames(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function addExprNames(e,n){return n instanceof t._CodeOrName?addNames(e,n.names):e}function optimizeExpr(e,n,r){if(e instanceof t.Name)return replaceName(e);if(!canOptimize(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=replaceName(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function replaceName(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function canOptimize(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function subtractNames(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function not(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${par(e)}`}e.not=not;let s=mappend(e.operators.AND);function and(...e){return e.reduce(s)}e.and=and;let c=mappend(e.operators.OR);function or(...e){return e.reduce(c)}e.or=or;function mappend(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${par(n)} ${e} ${par(r)}`}function par(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),H=r((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=V(),n=Ma();function toHash(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=toHash;function alwaysValidSchema(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(checkUnknownRules(e,t),!schemaHasRules(t,e.self.RULES.all))}e.alwaysValidSchema=alwaysValidSchema;function checkUnknownRules(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||checkStrictMode(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=checkUnknownRules;function schemaHasRules(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=schemaHasRules;function schemaHasRulesButRef(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=schemaHasRulesButRef;function schemaRefOrVal({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=schemaRefOrVal;function unescapeFragment(e){return unescapeJsonPointer(decodeURIComponent(e))}e.unescapeFragment=unescapeFragment;function escapeFragment(e){return encodeURIComponent(escapeJsonPointer(e))}e.escapeFragment=escapeFragment;function escapeJsonPointer(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=escapeJsonPointer;function unescapeJsonPointer(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=unescapeJsonPointer;function eachItem(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=eachItem;function makeMergeEvaluated({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,s,c,l)=>{let u=c===void 0?s:c instanceof t.Name?(s instanceof t.Name?e(a,s,c):n(a,s,c),c):s instanceof t.Name?(n(a,c,s),s):r(s,c);return l===t.Name&&!(u instanceof t.Name)?i(a,u):u}}e.mergeEvaluated={props:makeMergeEvaluated({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),setEvaluated(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:evaluatedPropsToName}),items:makeMergeEvaluated({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function evaluatedPropsToName(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&setEvaluated(e,r,n),r}e.evaluatedPropsToName=evaluatedPropsToName;function setEvaluated(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=setEvaluated;let r={};function useFunc(e,t){return e.scopeValue(`func`,{ref:t,code:r[t.code]||(r[t.code]=new n._Code(t.code))})}e.useFunc=useFunc;var i;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(i||(e.Type=i={}));function getErrorPath(e,n,r){if(e instanceof t.Name){let a=n===i.Num;return r?a?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:a?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+escapeJsonPointer(e)}e.getErrorPath=getErrorPath;function checkStrictMode(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=checkStrictMode})),Pa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V();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`)}})),Fa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=V(),n=H(),r=Pa();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function reportError(n,r=e.keywordError,i,a){let{it:s}=n,{gen:c,compositeRule:l,allErrors:u}=s,f=errorObjectCode(n,r,i);a??(l||u)?addError(c,f):returnErrors(s,(0,t._)`[${f}]`)}e.reportError=reportError;function reportExtraError(t,n=e.keywordError,i){let{it:a}=t,{gen:s,compositeRule:c,allErrors:l}=a;addError(s,errorObjectCode(t,n,i)),c||l||returnErrors(a,r.default.vErrors)}e.reportExtraError=reportExtraError;function resetErrorsCount(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=resetErrorsCount;function extendErrors({gen:e,keyword:n,schemaValue:i,data:a,errsCount:s,it:c}){if(s===void 0)throw Error(`ajv implementation error`);let l=e.name(`err`);e.forRange(`i`,s,r.default.errors,s=>{e.const(l,(0,t._)`${r.default.vErrors}[${s}]`),e.if((0,t._)`${l}.instancePath === undefined`,()=>e.assign((0,t._)`${l}.instancePath`,(0,t.strConcat)(r.default.instancePath,c.errorPath))),e.assign((0,t._)`${l}.schemaPath`,(0,t.str)`${c.errSchemaPath}/${n}`),c.opts.verbose&&(e.assign((0,t._)`${l}.schema`,i),e.assign((0,t._)`${l}.data`,a))})}e.extendErrors=extendErrors;function addError(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function returnErrors(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let i={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 errorObjectCode(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:errorObject(e,n,r)}function errorObject(e,t,n={}){let{gen:r,it:i}=e,a=[errorInstancePath(i,n),errorSchemaPath(e,n)];return extraErrorProps(e,t,a),r.object(...a)}function errorInstancePath({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function errorSchemaPath({keyword:e,it:{errSchemaPath:r}},{schemaPath:a,parentSchema:s}){let c=s?r:(0,t.str)`${r}/${e}`;return a&&(c=(0,t.str)`${c}${(0,n.getErrorPath)(a,n.Type.Str)}`),[i.schemaPath,c]}function extraErrorProps(e,{params:n,message:a},s){let{keyword:c,data:l,schemaValue:u,it:f}=e,{opts:p,propertyName:m,topSchemaRef:h,schemaPath:g}=f;s.push([i.keyword,c],[i.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),p.messages&&s.push([i.message,typeof a==`function`?a(e):a]),p.verbose&&s.push([i.schema,u],[i.parentSchema,(0,t._)`${h}${g}`],[r.default.data,l]),m&&s.push([i.propertyName,m])}})),Ia=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Fa(),n=V(),r=Pa(),i={message:`boolean schema is false`};function topBoolOrEmptySchema(e){let{gen:t,schema:i,validateName:a}=e;i===!1?falseSchemaError(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=topBoolOrEmptySchema;function boolOrEmptySchema(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),falseSchemaError(e)):n.var(t,!0)}e.boolOrEmptySchema=boolOrEmptySchema;function falseSchemaError(e,n){let{gen:r,data:a}=e,s={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(s,i,void 0,n)}})),La=r((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 isJSONType(e){return typeof e==`string`&&t.has(e)}e.isJSONType=isJSONType;function getRules(){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=getRules})),Ra=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function schemaHasRulesForType({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&shouldUseGroup(e,r)}e.schemaHasRulesForType=schemaHasRulesForType;function shouldUseGroup(e,t){return t.rules.some(t=>shouldUseRule(e,t))}e.shouldUseGroup=shouldUseGroup;function shouldUseRule(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=shouldUseRule})),za=r((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=La(),n=Ra(),r=Fa(),i=V(),a=H();var s;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(s||(e.DataType=s={}));function getSchemaTypes(e){let t=getJSONTypes(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=getSchemaTypes;function getJSONTypes(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=getJSONTypes;function coerceAndCheckDataType(e,t){let{gen:r,data:i,opts:a}=e,c=coerceToTypes(t,a.coerceTypes),l=t.length>0&&!(c.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(l){let n=checkDataTypes(t,i,a.strictNumbers,s.Wrong);r.if(n,()=>{c.length?coerceData(e,t,c):reportTypeError(e)})}return l}e.coerceAndCheckDataType=coerceAndCheckDataType;let c=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function coerceToTypes(e,t){return t?e.filter(e=>c.has(e)||t===`array`&&e===`array`):[]}function coerceData(e,t,n){let{gen:r,data:a,opts:s}=e,l=r.let(`dataType`,(0,i._)`typeof ${a}`),u=r.let(`coerced`,(0,i._)`undefined`);s.coerceTypes===`array`&&r.if((0,i._)`${l} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(l,(0,i._)`typeof ${a}`).if(checkDataTypes(t,a,s.strictNumbers),()=>r.assign(u,a))),r.if((0,i._)`${u} !== undefined`);for(let e of n)(c.has(e)||e===`array`&&s.coerceTypes===`array`)&&coerceSpecificType(e);r.else(),reportTypeError(e),r.endIf(),r.if((0,i._)`${u} !== undefined`,()=>{r.assign(a,u),assignParentData(e,u)});function coerceSpecificType(e){switch(e){case`string`:r.elseIf((0,i._)`${l} == "number" || ${l} == "boolean"`).assign(u,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(u,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${l} == "boolean" || ${a} === null
168
168
  || (${l} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${l} === "boolean" || ${a} === null
169
169
  || (${l} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(u,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(u,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(u,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(u,null);return;case`array`:r.elseIf((0,i._)`${l} === "string" || ${l} === "number"
170
- || ${l} === "boolean" || ${a} === null`).assign(u,(0,i._)`[${a}]`)}}}function assignParentData({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function checkDataType(e,t,n,r=s.Correct){let a=r===s.Correct?i.operators.EQ:i.operators.NEQ,c;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:c=(0,i._)`Array.isArray(${t})`;break;case`object`:c=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:c=numCond((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:c=numCond();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===s.Correct?c:(0,i.not)(c);function numCond(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=checkDataType;function checkDataTypes(e,t,n,r){if(e.length===1)return checkDataType(e[0],t,n,r);let s,c=(0,a.toHash)(e);if(c.array&&c.object){let e=(0,i._)`typeof ${t} != "object"`;s=c.null?e:(0,i._)`!${t} || ${e}`,delete c.null,delete c.array,delete c.object}else s=i.nil;c.number&&delete c.integer;for(let e in c)s=(0,i.and)(s,checkDataType(e,t,n,r));return s}e.checkDataTypes=checkDataTypes;let l={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function reportTypeError(e){let t=getTypeErrorContext(e);(0,r.reportError)(t,l)}e.reportTypeError=reportTypeError;function getTypeErrorContext(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Ba=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=R(),n=z();function assignDefaults(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)assignDefault(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>assignDefault(e,n,t.default))}e.assignDefaults=assignDefaults;function assignDefault(e,r,i){let{gen:a,compositeRule:s,data:c,opts:l}=e;if(i===void 0)return;let u=(0,t._)`${c}${(0,t.getProperty)(r)}`;if(s){(0,n.checkStrictMode)(e,`default is ignored for: ${u}`);return}let f=(0,t._)`${u} === undefined`;l.useDefaults===`empty`&&(f=(0,t._)`${f} || ${u} === null || ${u} === ""`),a.if(f,(0,t._)`${u} = ${(0,t.stringify)(i)}`)}})),Va=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=R(),n=z(),r=Pa(),i=z();function checkReportMissingProp(e,n){let{gen:r,data:i,it:a}=e;r.if(noPropertyInData(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(noPropertyInData(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=checkMissingProp;function reportMissingProp(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=reportMissingProp;function hasPropFunc(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=hasPropFunc;function isOwnProperty(e,n,r){return(0,t._)`${hasPropFunc(e)}.call(${n}, ${r})`}e.isOwnProperty=isOwnProperty;function propertyInData(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${isOwnProperty(e,n,r)}`:a}e.propertyInData=propertyInData;function noPropertyInData(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(isOwnProperty(e,n,r))):a}e.noPropertyInData=noPropertyInData;function allSchemaProperties(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=allSchemaProperties;function schemaProperties(e,t){return allSchemaProperties(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=schemaProperties;function callValidateCode({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:s,errorPath:c},it:l},u,f,p){let m=p?(0,t._)`${e}, ${n}, ${a}${s}`:n,h=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,c)],[r.default.parentData,l.parentData],[r.default.parentDataProperty,l.parentDataProperty],[r.default.rootData,r.default.rootData]];l.opts.dynamicRef&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let g=(0,t._)`${m}, ${i.object(...h)}`;return f===t.nil?(0,t._)`${u}(${g})`:(0,t._)`${u}.call(${f}, ${g})`}e.callValidateCode=callValidateCode;let a=(0,t._)`new RegExp`;function usePattern({gen:e,it:{opts:n}},r){let s=n.unicodeRegExp?`u`:``,{regExp:c}=n.code,l=c(r,s);return e.scopeValue(`pattern`,{key:l.toString(),ref:l,code:(0,t._)`${c.code===`new RegExp`?a:(0,i.useFunc)(e,c)}(${r}, ${s})`})}e.usePattern=usePattern;function validateArray(e){let{gen:r,data:i,keyword:a,it:s}=e,c=r.name(`valid`);if(s.allErrors){let e=r.let(`valid`,!0);return validateItems(()=>r.assign(e,!1)),e}return r.var(c,!0),validateItems(()=>r.break()),c;function validateItems(s){let l=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,l,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},c),r.if((0,t.not)(c),s)})}}e.validateArray=validateArray;function validateUnion(e){let{gen:r,schema:i,keyword:a,it:s}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;let c=r.let(`valid`,!1),l=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let s=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},l);r.assign(c,(0,t._)`${c} || ${l}`),e.mergeValidEvaluated(s,l)||r.if((0,t.not)(c))})),e.result(c,()=>e.reset(),()=>e.error(!0))}e.validateUnion=validateUnion})),Ha=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=R(),n=Pa(),r=Va(),i=Fa();function macroKeywordCode(e,n){let{gen:r,keyword:i,schema:a,parentSchema:s,it:c}=e,l=n.macro.call(c.self,a,s,c),u=useKeyword(r,i,l);c.opts.validateSchema!==!1&&c.self.validateSchema(l,!0);let f=r.name(`valid`);e.subschema({schema:l,schemaPath:t.nil,errSchemaPath:`${c.errSchemaPath}/${i}`,topSchemaRef:u,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}e.macroKeywordCode=macroKeywordCode;function funcKeywordCode(e,i){let{gen:a,keyword:s,schema:c,parentSchema:l,$data:u,it:f}=e;checkAsyncKeyword(f,i);let p=useKeyword(a,s,!u&&i.compile?i.compile.call(f.self,c,l,f):i.validate),m=a.let(`valid`);e.block$data(m,validateKeyword),e.ok(i.valid??m);function validateKeyword(){if(i.errors===!1)assignValid(),i.modifying&&modifyData(e),reportErrs(()=>e.error());else{let t=i.async?validateAsync():validateSync();i.modifying&&modifyData(e),reportErrs(()=>addErrs(e,t))}}function validateAsync(){let e=a.let(`ruleErrs`,null);return a.try(()=>assignValid((0,t._)`await `),n=>a.assign(m,!1).if((0,t._)`${n} instanceof ${f.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function validateSync(){let e=(0,t._)`${p}.errors`;return a.assign(e,null),assignValid(t.nil),e}function assignValid(s=i.async?(0,t._)`await `:t.nil){let c=f.opts.passContext?n.default.this:n.default.self,l=!(`compile`in i&&!u||i.schema===!1);a.assign(m,(0,t._)`${s}${(0,r.callValidateCode)(e,p,c,l)}`,i.modifying)}function reportErrs(e){a.if((0,t.not)(i.valid??m),e)}}e.funcKeywordCode=funcKeywordCode;function modifyData(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function addErrs(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function checkAsyncKeyword({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function useKeyword(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function validSchemaType(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=validSchemaType;function validateKeywordUsage({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let s=i.dependencies;if(s?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${s.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=validateKeywordUsage})),Ua=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=R(),n=z();function getSubschema(e,{keyword:r,schemaProp:i,schema:a,schemaPath:s,errSchemaPath:c,topSchemaRef:l}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(s===void 0||c===void 0||l===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:s,topSchemaRef:l,errSchemaPath:c}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=getSubschema;function extendSubschemaData(e,r,{dataProp:i,dataPropType:a,data:s,dataTypes:c,propertyName:l}){if(s!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:u}=r;if(i!==void 0){let{errorPath:s,dataPathArr:c,opts:l}=r;dataContextProps(u.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${s}${(0,n.getErrorPath)(i,a,l.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...c,e.parentDataProperty]}s!==void 0&&(dataContextProps(s instanceof t.Name?s:u.let(`data`,s,!0)),l!==void 0&&(e.propertyName=l)),c&&(e.dataTypes=c);function dataContextProps(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=extendSubschemaMode})),Wa=r(((e,t)=>{t.exports=function equal(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(e.constructor!==t.constructor)return!1;var n,r,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!equal(e[r],t[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){var a=i[r];if(!equal(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}})),Ga=r(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var r=typeof n==`function`?n:n.pre||function(){},i=n.post||function(){};_traverse(t,r,i,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(e,t,r,i,a,s,c,l,u,f){if(i&&typeof i==`object`&&!Array.isArray(i)){for(var p in t(i,a,s,c,l,u,f),i){var m=i[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)_traverse(e,t,r,m[h],a+`/`+p+`/`+h,s,a,p,i,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)_traverse(e,t,r,m[g],a+`/`+p+`/`+escapeJsonPtr(g),s,a,p,i,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&_traverse(e,t,r,m,a+`/`+p,s,a,p,i)}r(i,a,s,c,l,u,f)}}function escapeJsonPtr(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Ka=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=z(),n=Wa(),r=Ga(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function inlineRef(e,t=!0){return typeof e==`boolean`?!0:t===!0?!hasRef(e):t?countKeys(e)<=t:!1}e.inlineRef=inlineRef;let a=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function hasRef(e){for(let t in e){if(a.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(hasRef)||typeof n==`object`&&hasRef(n))return!0}return!1}function countKeys(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=countKeys(e)),n===1/0)))return 1/0;return n}function getFullPath(e,t=``,n){return n!==!1&&(t=normalizeId(t)),_getFullPath(e,e.parse(t))}e.getFullPath=getFullPath;function _getFullPath(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=_getFullPath;let s=/#\/?$/;function normalizeId(e){return e?e.replace(s,``):``}e.normalizeId=normalizeId;function resolveUrl(e,t,n){return n=normalizeId(n),e.resolve(t,n)}e.resolveUrl=resolveUrl;let c=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,s=normalizeId(e[i]||t),l={"":s},u=getFullPath(a,s,!1),f={},p=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=u+t,s=l[r];typeof e[i]==`string`&&(s=addRef.call(this,e[i])),addAnchor.call(this,e.$anchor),addAnchor.call(this,e.$dynamicAnchor),l[t]=s;function addRef(t){let n=this.opts.uriResolver.resolve;if(t=normalizeId(s?n(s,t):t),p.has(t))throw ambiguos(t);p.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?checkAmbiguosRef(e,r.schema,t):t!==normalizeId(a)&&(t[0]===`#`?(checkAmbiguosRef(e,f[t],t),f[t]=e):this.refs[t]=a),t}function addAnchor(e){if(typeof e==`string`){if(!c.test(e))throw Error(`invalid anchor "${e}"`);addRef.call(this,`#${e}`)}}}),f;function checkAmbiguosRef(e,t,r){if(t!==void 0&&!n(e,t))throw ambiguos(r)}function ambiguos(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=getSchemaRefs})),qa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ia(),n=za(),r=Ra(),i=za(),a=Ba(),s=Ha(),c=Ua(),l=R(),u=Pa(),f=Ka(),p=z(),m=Fa();function validateFunctionCode(e){if(isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))){topSchemaObjCode(e);return}validateFunction(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=validateFunctionCode;function validateFunction({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,l._)`${u.default.data}, ${u.default.valCxt}`,r.$async,()=>{e.code((0,l._)`"use strict"; ${funcSourceUrl(n,i)}`),destructureValCxtES5(e,i),e.code(a)}):e.func(t,(0,l._)`${u.default.data}, ${destructureValCxt(i)}`,r.$async,()=>e.code(funcSourceUrl(n,i)).code(a))}function destructureValCxt(e){return(0,l._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${e.dynamicRef?(0,l._)`, ${u.default.dynamicAnchors}={}`:l.nil}}={}`}function destructureValCxtES5(e,t){e.if(u.default.valCxt,()=>{e.var(u.default.instancePath,(0,l._)`${u.default.valCxt}.${u.default.instancePath}`),e.var(u.default.parentData,(0,l._)`${u.default.valCxt}.${u.default.parentData}`),e.var(u.default.parentDataProperty,(0,l._)`${u.default.valCxt}.${u.default.parentDataProperty}`),e.var(u.default.rootData,(0,l._)`${u.default.valCxt}.${u.default.rootData}`),t.dynamicRef&&e.var(u.default.dynamicAnchors,(0,l._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{e.var(u.default.instancePath,(0,l._)`""`),e.var(u.default.parentData,(0,l._)`undefined`),e.var(u.default.parentDataProperty,(0,l._)`undefined`),e.var(u.default.rootData,u.default.data),t.dynamicRef&&e.var(u.default.dynamicAnchors,(0,l._)`{}`)})}function topSchemaObjCode(e){let{schema:t,opts:n,gen:r}=e;validateFunction(e,()=>{n.$comment&&t.$comment&&commentKeyword(e),checkNoDefault(e),r.let(u.default.vErrors,null),r.let(u.default.errors,0),n.unevaluated&&resetEvaluated(e),typeAndKeywords(e),returnResults(e)})}function resetEvaluated(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,l._)`${n}.evaluated`),t.if((0,l._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,l._)`${e.evaluated}.props`,(0,l._)`undefined`)),t.if((0,l._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,l._)`${e.evaluated}.items`,(0,l._)`undefined`))}function funcSourceUrl(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,l._)`/*# sourceURL=${n} */`:l.nil}function subschemaCode(e,n){if(isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))){subSchemaObjCode(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function schemaCxtHasRules({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function isSchemaObj(e){return typeof e.schema!=`boolean`}function subSchemaObjCode(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&commentKeyword(e),updateContext(e),checkAsyncSchema(e);let a=r.const(`_errs`,u.default.errors);typeAndKeywords(e,a),r.var(t,(0,l._)`${a} === ${u.default.errors}`)}function checkKeywords(e){(0,p.checkUnknownRules)(e),checkRefsAndKeywords(e)}function typeAndKeywords(e,t){if(e.opts.jtd)return schemaKeywords(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);schemaKeywords(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function checkRefsAndKeywords(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function checkNoDefault(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,p.checkStrictMode)(e,`default is ignored in the schema root`)}function updateContext(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,f.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function checkAsyncSchema(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function commentKeyword({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,l._)`${u.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,l.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,l._)`${u.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function returnResults(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,l._)`${u.default.errors} === 0`,()=>t.return(u.default.data),()=>t.throw((0,l._)`new ${i}(${u.default.vErrors})`)):(t.assign((0,l._)`${r}.errors`,u.default.vErrors),a.unevaluated&&assignEvaluated(e),t.return((0,l._)`${u.default.errors} === 0`))}function assignEvaluated({gen:e,evaluated:t,props:n,items:r}){n instanceof l.Name&&e.assign((0,l._)`${t}.props`,n),r instanceof l.Name&&e.assign((0,l._)`${t}.items`,r)}function schemaKeywords(e,t,n,a){let{gen:s,schema:c,data:f,allErrors:m,opts:h,self:g}=e,{RULES:v}=g;if(c.$ref&&(h.ignoreKeywordsWithRef||!(0,p.schemaHasRulesButRef)(c,v))){s.block(()=>keywordCode(e,`$ref`,v.all.$ref.definition));return}h.jtd||checkStrictTypes(e,t),s.block(()=>{for(let e of v.rules)groupKeywords(e);groupKeywords(v.post)});function groupKeywords(p){(0,r.shouldUseGroup)(c,p)&&(p.type?(s.if((0,i.checkDataType)(p.type,f,h.strictNumbers)),iterateKeywords(e,p),t.length===1&&t[0]===p.type&&n&&(s.else(),(0,i.reportTypeError)(e)),s.endIf()):iterateKeywords(e,p),m||s.if((0,l._)`${u.default.errors} === ${a||0}`))}}function iterateKeywords(e,t){let{gen:n,schema:i,opts:{useDefaults:s}}=e;s&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&keywordCode(e,n.keyword,n.definition,t.type)})}function checkStrictTypes(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(checkContextTypes(e,t),e.opts.allowUnionTypes||checkMultipleTypes(e,t),checkKeywordTypes(e,e.dataTypes))}function checkContextTypes(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{includesType(e.dataTypes,t)||strictTypesError(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),narrowSchemaTypes(e,t)}}function checkMultipleTypes(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&strictTypesError(e,`use allowUnionTypes to allow union type keyword`)}function checkKeywordTypes(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>hasApplicableType(t,e))&&strictTypesError(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function hasApplicableType(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function includesType(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function narrowSchemaTypes(e,t){let n=[];for(let r of e.dataTypes)includesType(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function strictTypesError(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,p.checkStrictMode)(e,t,e.opts.strictTypes)}var KeywordCxt=class{constructor(e,t,n){if((0,s.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,p.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,getData(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,u.default.errors))}result(e,t,n){this.failResult((0,l.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,l.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,l._)`${t} !== undefined && (${(0,l.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?m.reportExtraError:m.reportError)(this,this.def.error,t)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=l.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=l.nil,t=l.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,l.or)((0,l._)`${r} === undefined`,t)),e!==l.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==l.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,l.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(n.length){if(!(t instanceof l.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,l._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return l.nil}function invalid$DataSchema(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,l._)`!${n}(${t})`}return l.nil}}subschema(e,t){let n=(0,c.getSubschema)(this.it,e);(0,c.extendSubschemaData)(n,this.it,e),(0,c.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return subschemaCode(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=p.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=p.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,l.Name)),!0}};e.KeywordCxt=KeywordCxt;function keywordCode(e,t,n,r){let i=new KeywordCxt(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,s.funcKeywordCode)(i,n):`macro`in n?(0,s.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,s.funcKeywordCode)(i,n)}let h=/^\/(?:[^~]|~0|~1)*$/,g=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return u.default.rootData;if(e[0]===`/`){if(!h.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=u.default.rootData}else{let s=g.exec(e);if(!s)throw Error(`Invalid JSON-pointer: ${e}`);let c=+s[1];if(i=s[2],i===`#`){if(c>=t)throw Error(errorMsg(`property/index`,c));return r[t-c]}if(c>t)throw Error(errorMsg(`data`,c));if(a=n[t-c],!i)return a}let s=a,c=i.split(`/`);for(let e of c)e&&(a=(0,l._)`${a}${(0,l.getProperty)((0,p.unescapeJsonPointer)(e))}`,s=(0,l._)`${s} && ${a}`);return s;function errorMsg(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=getData})),Ja=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});var ValidationError=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}};e.default=ValidationError})),Ya=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ka();var MissingRefError=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}};e.default=MissingRefError})),Xa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=R(),n=Ja(),r=Pa(),i=Ka(),a=z(),s=qa();var SchemaEnv=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=SchemaEnv;function compileSchema(e){let a=getCompilingSchema.call(this,e);if(a)return a;let c=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:l,lines:u}=this.opts.code,{ownProperties:f}=this.opts,p=new t.CodeGen(this.scope,{es5:l,lines:u,ownProperties:f}),m;e.$async&&(m=p.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let h=p.scopeName(`validate`);e.validateName=h;let g={gen:p,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:h,ValidationError:m,schema:e.schema,schemaEnv:e,rootId:c,baseId:e.baseId||c,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},v;try{this._compilations.add(e),(0,s.validateFunctionCode)(g),p.optimize(this.opts.code.optimize);let n=p.toString();v=`${p.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(v=this.opts.code.process(v,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,v)(this,this.scope.get());if(this.scope.value(h,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:h,validateCode:n,scopeValues:p._values}),this.opts.unevaluated){let{props:e,items:n}=g;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,v&&this.logger.error(`Error compiling schema, function code:`,v),t}finally{this._compilations.delete(e)}}e.compileSchema=compileSchema;function resolveRef(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=resolve.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new SchemaEnv({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=inlineOrCompile.call(this,a)}e.resolveRef=resolveRef;function inlineOrCompile(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:compileSchema.call(this,e)}function getCompilingSchema(e){for(let t of this._compilations)if(sameSchemaEnv(t,e))return t}e.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function resolve(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||resolveSchema.call(this,e,t)}function resolveSchema(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return getJsonPointer.call(this,n,e);let s=(0,i.normalizeId)(r),c=this.refs[s]||this.schemas[s];if(typeof c==`string`){let t=resolveSchema.call(this,e,c);return typeof t?.schema==`object`?getJsonPointer.call(this,n,t):void 0}if(typeof c?.schema==`object`){if(c.validate||compileSchema.call(this,c),s===(0,i.normalizeId)(t)){let{schema:t}=c,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new SchemaEnv({schema:t,schemaId:n,root:e,baseId:a})}return getJsonPointer.call(this,n,c)}}e.resolveSchema=resolveSchema;let c=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function getJsonPointer(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let s=typeof n==`object`&&n[this.opts.schemaId];!c.has(r)&&s&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,s))}let s;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=resolveSchema.call(this,r,e)}let{schemaId:l}=this.opts;if(s||=new SchemaEnv({schema:n,schemaId:l,root:r,baseId:t}),s.schema!==s.root.schema)return s}})),Za=r(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Qa=r(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function stringArrayToHexStripped(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function consumeIsZone(e){return e.length=0,!0}function consumeHextets(e,t,n){if(e.length){let r=stringArrayToHexStripped(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function getIPV6(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,s=!1,c=consumeHextets;for(let l=0;l<e.length;l++){let u=e[l];if(u!==`[`&&u!==`]`){if(u===`:`){if(a===!0&&(s=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}l>0&&e[l-1]===`:`&&(a=!0),r.push(`:`);continue}if(u===`%`){if(!c(i,r,n))break;c=consumeIsZone}else{i.push(u);continue}}}return i.length&&(c===consumeIsZone?n.zone=i.join(``):s?r.push(i.join(``)):r.push(stringArrayToHexStripped(i))),n.address=r.join(``),n}function normalizeIPv6(e){if(findToken(e,`:`)<2)return{host:e,isIPV6:!1};let t=getIPV6(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function findToken(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function removeDotSegments(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function normalizeComponentEncoding(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function recomposeAuthority(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=normalizeIPv6(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:i,recomposeAuthority,normalizeComponentEncoding,removeDotSegments,isIPv4:r,isUUID:n,normalizeIPv6,stringArrayToHexStripped}})),$a=r(((e,t)=>{let{isUUID:n}=Qa(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function isValidSchemeName(e){return i.indexOf(e)!==-1}function wsIsSecure(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function httpParse(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function httpSerialize(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function wsParse(e){return e.secure=wsIsSecure(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function wsSerialize(e){if((e.port===(wsIsSecure(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function urnParse(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=getSchemeHandler(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function urnSerialize(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=getSchemeHandler(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,s=e.nss;return a.path=`${r||t.nid}:${s}`,t.skipEscape=!0,a}function urnuuidParse(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function urnuuidSerialize(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let a={scheme:`http`,domainHost:!0,parse:httpParse,serialize:httpSerialize},s={scheme:`https`,domainHost:a.domainHost,parse:httpParse,serialize:httpSerialize},c={scheme:`ws`,domainHost:!0,parse:wsParse,serialize:wsSerialize},l={http:a,https:s,ws:c,wss:{scheme:`wss`,domainHost:c.domainHost,parse:c.parse,serialize:c.serialize},urn:{scheme:`urn`,parse:urnParse,serialize:urnSerialize,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:!0}};Object.setPrototypeOf(l,null);function getSchemeHandler(e){return e&&(l[e]||l[e.toLowerCase()])||void 0}t.exports={wsIsSecure,SCHEMES:l,isValidSchemeName,getSchemeHandler}})),eo=r(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:s,nonSimpleDomain:c}=Qa(),{SCHEMES:l,getSchemeHandler:u}=$a();function normalize(e,t){return typeof e==`string`?e=serialize(parse(e,t),t):typeof e==`object`&&(e=parse(serialize(e,t),t)),e}function resolve(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=resolveComponent(parse(e,r),parse(t,r),r,!0);return r.skipEscape=!0,serialize(i,r)}function resolveComponent(e,t,n,i){let a={};return i||(e=parse(serialize(e,n),n),t=parse(serialize(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function equal(e,t,n){return typeof e==`string`?(e=unescape(e),e=serialize(a(parse(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=serialize(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=serialize(a(parse(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=serialize(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function serialize(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),s=[],c=u(a.scheme||n.scheme);c&&c.serialize&&c.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&s.push(n.scheme,`:`);let l=i(n);if(l!==void 0&&(a.reference!==`suffix`&&s.push(`//`),s.push(l),n.path&&n.path[0]!==`/`&&s.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!c||!c.absolutePath)&&(e=r(e)),l===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),s.push(e)}return n.query!==void 0&&s.push(`?`,n.query),n.fragment!==void 0&&s.push(`#`,n.fragment),s.join(``)}let f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function parse(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let l=e.match(f);if(l){if(i.scheme=l[1],i.userinfo=l[3],i.host=l[4],i.port=parseInt(l[5],10),i.path=l[6]||``,i.query=l[7],i.fragment=l[8],isNaN(i.port)&&(i.port=l[5]),i.host){if(s(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=u(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&c(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let p={SCHEMES:l,normalize,resolve,resolveComponent,equal,serialize,parse};t.exports=p,t.exports.default=p,t.exports.fastUri=p})),to=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=eo();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),no=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=R();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Ja(),i=Ya(),a=La(),s=Xa(),c=R(),l=Ka(),u=za(),f=z(),p=Za(),m=to(),defaultRegExp=(e,t)=>new RegExp(e,t);defaultRegExp.code=`new RegExp`;let h=[`removeAdditional`,`useDefaults`,`coerceTypes`],g=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),v={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},y={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function requiredOptions(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??defaultRegExp,a=e.uriResolver??m.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var Ajv=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...requiredOptions(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:g,es5:t,lines:n}),this.logger=getLogger(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),checkOptions.call(this,v,e,`NOT SUPPORTED`),checkOptions.call(this,y,e,`DEPRECATED`,`warn`),this._metaOpts=getMetaSchemaOptions.call(this),e.formats&&addInitialFormats.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&addInitialKeywords.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),addInitialSchemas.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=p;n===`id`&&(r={...p},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return runCompileAsync.call(this,e,t);async function runCompileAsync(e,t){await loadMetaSchema.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||_compileAsync.call(this,n)}async function loadMetaSchema(e){e&&!this.getSchema(e)&&await runCompileAsync.call(this,{$ref:e},!0)}async function _compileAsync(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return checkLoaded.call(this,t),await loadMissingSchema.call(this,t.missingSchema),_compileAsync.call(this,e)}}function checkLoaded({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function loadMissingSchema(e){let n=await _loadSchema.call(this,e);this.refs[e]||await loadMetaSchema.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function _loadSchema(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,l.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=getSchEnv.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new s.SchemaEnv({schema:{},schemaId:n});if(t=s.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=getSchEnv.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,l.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(checkKeyword.call(this,n,t),!t)return(0,f.eachItem)(n,e=>addRule.call(this,e)),this;keywordMetaschema.call(this,t);let r={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,f.eachItem)(n,r.type.length===0?e=>addRule.call(this,e,r):e=>r.type.forEach(t=>addRule.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=schemaOrData(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:c}=this.opts;if(typeof e==`object`)a=e[c];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let u=this._cache.get(e);if(u!==void 0)return u;n=(0,l.normalizeId)(a||n);let f=l.getSchemaRefs.call(this,e,n);return u=new s.SchemaEnv({schema:e,schemaId:c,meta:t,baseId:n,localRefs:f}),this._cache.set(u.schema,u),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=u),r&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):s.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}};Ajv.ValidationError=r.default,Ajv.MissingRefError=i.default,e.default=Ajv;function checkOptions(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function getSchEnv(e){return e=(0,l.normalizeId)(e),this.schemas[e]||this.refs[e]}function addInitialSchemas(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function addInitialFormats(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function addInitialKeywords(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function getMetaSchemaOptions(){let e={...this.opts};for(let t of h)delete e[t];return e}let b={log(){},warn(){},error(){}};function getLogger(e){if(e===!1)return b;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ee=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(e,t){let{RULES:n}=this;if((0,f.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ee.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function addRule(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,s=i?a.post:a.rules.find(({type:e})=>e===n);if(s||(s={type:n,rules:[]},a.rules.push(s)),a.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?addBeforeRule.call(this,s,c,t.before):s.rules.push(c),a.all[e]=c,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function addBeforeRule(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function keywordMetaschema(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=schemaOrData(t)),e.validateSchema=this.compile(t,!0))}let te={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function schemaOrData(e){return{anyOf:[e,te]}}})),ro=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),io=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Ya(),n=Va(),r=R(),i=Pa(),a=Xa(),s=z(),c={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:s}=e,{baseId:c,schemaEnv:l,validateName:u,opts:f,self:p}=s,{root:m}=l;if((i===`#`||i===`#/`)&&c===m.baseId)return callRootRef();let h=a.resolveRef.call(p,m,c,i);if(h===void 0)throw new t.default(s.opts.uriResolver,c,i);if(h instanceof a.SchemaEnv)return callValidate(h);return inlineRefSchema(h);function callRootRef(){if(l===m)return callRef(e,u,l,l.$async);let t=n.scopeValue(`root`,{ref:m});return callRef(e,(0,r._)`${t}.validate`,m,m.$async)}function callValidate(t){callRef(e,getValidate(e,t),t,t.$async)}function inlineRefSchema(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),s=n.name(`valid`),c=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},s);e.mergeEvaluated(c),e.ok(s)}}};function getValidate(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=getValidate;function callRef(e,t,a,c){let{gen:l,it:u}=e,{allErrors:f,schemaEnv:p,opts:m}=u,h=m.passContext?i.default.this:r.nil;c?callAsyncRef():callSyncRef();function callAsyncRef(){if(!p.$async)throw Error(`async schema referenced by sync schema`);let i=l.let(`valid`);l.try(()=>{l.code((0,r._)`await ${(0,n.callValidateCode)(e,t,h)}`),addEvaluatedFrom(t),f||l.assign(i,!0)},e=>{l.if((0,r._)`!(${e} instanceof ${u.ValidationError})`,()=>l.throw(e)),addErrorsFrom(e),f||l.assign(i,!1)}),e.ok(i)}function callSyncRef(){e.result((0,n.callValidateCode)(e,t,h),()=>addEvaluatedFrom(t),()=>addErrorsFrom(t))}function addErrorsFrom(e){let t=(0,r._)`${e}.errors`;l.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),l.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function addEvaluatedFrom(e){if(!u.opts.unevaluated)return;let t=a?.validate?.evaluated;if(u.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(u.props=s.mergeEvaluated.props(l,t.props,u.props));else{let t=l.var(`props`,(0,r._)`${e}.evaluated.props`);u.props=s.mergeEvaluated.props(l,t,u.props,r.Name)}}if(u.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(u.items=s.mergeEvaluated.items(l,t.items,u.items));else{let t=l.var(`items`,(0,r._)`${e}.evaluated.items`);u.items=s.mergeEvaluated.items(l,t,u.items,r.Name)}}}}e.callRef=callRef,e.default=c})),ao=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=io();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),oo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),so=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,s=a.opts.multipleOfPrecision,c=n.let(`res`),l=s?(0,t._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${s}`:(0,t._)`${c} !== parseInt(${c})`;e.fail$data((0,t._)`(${i} === 0 || (${c} = ${r}/${i}, ${l}))`)}}})),co=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});function ucs2length(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=ucs2length,ucs2length.code=`require("ajv/dist/runtime/ucs2length").default`})),lo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r=co();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:s,it:c}=e,l=i===`maxLength`?t.operators.GT:t.operators.LT,u=c.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${u} ${l} ${s}`)}}})),uo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=z(),r=R();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:s,schema:c,schemaCode:l,it:u}=e,f=u.opts.unicodeRegExp?`u`:``;if(s){let{regExp:t}=u.opts.code,s=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),c=i.let(`valid`);i.try(()=>i.assign(c,(0,r._)`${s}(${l}, ${f}).test(${a})`),()=>i.assign(c,!1)),e.fail$data((0,r._)`!${c}`)}else{let n=(0,t.usePattern)(e,c);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),fo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),po=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=R(),r=z();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:s,data:c,$data:l,it:u}=e,{opts:f}=u;if(!l&&a.length===0)return;let p=a.length>=f.loopRequired;if(u.allErrors?allErrorsMode():exitOnErrorMode(),f.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${u.schemaEnv.baseId+u.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(u,t,u.opts.strictRequired)}}function allErrorsMode(){if(p||l)e.block$data(n.nil,loopAllRequired);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function exitOnErrorMode(){let n=i.let(`missing`);if(p||l){let t=i.let(`valid`,!0);e.block$data(t,()=>loopUntilMissing(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function loopAllRequired(){i.forOf(`prop`,s,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,c,n,f.ownProperties),()=>e.error())})}function loopUntilMissing(r,a){e.setParams({missingProperty:r}),i.forOf(r,s,()=>{i.assign(a,(0,t.propertyInData)(i,c,r,f.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),mo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),ho=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wa();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),go=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=za(),n=R(),r=z(),i=ho();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:s,$data:c,schema:l,parentSchema:u,schemaCode:f,it:p}=e;if(!c&&!l)return;let m=a.let(`valid`),h=u.items?(0,t.getSchemaTypes)(u.items):[];e.block$data(m,validateUniqueItems,(0,n._)`${f} === false`),e.ok(m);function validateUniqueItems(){let t=a.let(`i`,(0,n._)`${s}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(m,!0),a.if((0,n._)`${t} > 1`,()=>(canOptimize()?loopN:loopN2)(t,r))}function canOptimize(){return h.length>0&&!h.some(e=>e===`object`||e===`array`)}function loopN(r,i){let c=a.name(`item`),l=(0,t.checkDataTypes)(h,c,p.opts.strictNumbers,t.DataType.Wrong),u=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(c,(0,n._)`${s}[${r}]`),a.if(l,(0,n._)`continue`),h.length>1&&a.if((0,n._)`typeof ${c} == "string"`,(0,n._)`${c} += "_"`),a.if((0,n._)`typeof ${u}[${c}] == "number"`,()=>{a.assign(i,(0,n._)`${u}[${c}]`),e.error(),a.assign(m,!1).break()}).code((0,n._)`${u}[${c}] = ${r}`)})}function loopN2(t,c){let l=(0,r.useFunc)(a,i.default),u=a.name(`outer`);a.label(u).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${c} = ${t}; ${c}--;`,()=>a.if((0,n._)`${l}(${s}[${t}], ${s}[${c}])`,()=>{e.error(),a.assign(m,!1).break(u)})))}}}})),_o=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r=ho();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:s,schemaCode:c,schema:l}=e;s||l&&typeof l==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${c})`):e.fail((0,t._)`${l} !== ${a}`)}}})),vo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r=ho();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:s,schema:c,schemaCode:l,it:u}=e;if(!s&&c.length===0)throw Error(`enum must have non-empty array`);let f=c.length>=u.opts.loopEnum,p,getEql=()=>p??=(0,n.useFunc)(i,r.default),m;if(f||s)m=i.let(`valid`),e.block$data(m,loopEnum);else{if(!Array.isArray(c))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,l);m=(0,t.or)(...c.map((t,n)=>equalCode(e,n)))}e.pass(m);function loopEnum(){i.assign(m,!1),i.forOf(`v`,l,e=>i.if((0,t._)`${getEql()}(${a}, ${e})`,()=>i.assign(m,!0).break()))}function equalCode(e,n){let r=c[n];return typeof r==`object`&&r?(0,t._)`${getEql()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),yo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=oo(),n=so(),r=lo(),i=uo(),a=fo(),s=po(),c=mo(),l=go(),u=_o(),f=vo();e.default=[t.default,n.default,r.default,i.default,a.default,s.default,c.default,l.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},u.default,f.default]})),bo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=R(),n=z(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}validateAdditionalItems(e,i)}};function validateAdditionalItems(e,r){let{gen:i,schema:a,data:s,keyword:c,it:l}=e;l.items=!0;let u=i.const(`len`,(0,t._)`${s}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${u} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(l,a)){let n=i.var(`valid`,(0,t._)`${u} <= ${r.length}`);i.if((0,t.not)(n),()=>validateItems(n)),e.ok(n)}function validateItems(a){i.forRange(`i`,r.length,u,r=>{e.subschema({keyword:c,dataProp:r,dataPropType:n.Type.Num},a),l.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=validateAdditionalItems,e.default=r})),xo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=R(),n=z(),r=Va(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return validateTuple(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function validateTuple(e,r,i=e.schema){let{gen:a,parentSchema:s,data:c,keyword:l,it:u}=e;checkStrictTuple(s),u.opts.unevaluated&&i.length&&u.items!==!0&&(u.items=n.mergeEvaluated.items(a,i.length,u.items));let f=a.name(`valid`),p=a.const(`len`,(0,t._)`${c}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(u,r)||(a.if((0,t._)`${p} > ${i}`,()=>e.subschema({keyword:l,schemaProp:i,dataProp:i},f)),e.ok(f))});function checkStrictTuple(e){let{opts:t,errSchemaPath:a}=u,s=i.length,c=s===e.minItems&&(s===e.maxItems||e[r]===!1);if(t.strictTuples&&!c){let e=`"${l}" is ${s}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(u,e,t.strictTuples)}}}e.validateTuple=validateTuple,e.default=i})),So=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xo();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Co=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r=Va(),i=bo();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:s}=e,{prefixItems:c}=a;s.items=!0,!(0,n.alwaysValidSchema)(s,t)&&(c?(0,i.validateAdditionalItems)(e,c):e.ok((0,r.validateArray)(e)))}}})),wo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:s,it:c}=e,l,u,{minContains:f,maxContains:p}=a;c.opts.next?(l=f===void 0?1:f,u=p):l=1;let m=r.const(`len`,(0,t._)`${s}.length`);if(e.setParams({min:l,max:u}),u===void 0&&l===0){(0,n.checkStrictMode)(c,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(u!==void 0&&l>u){(0,n.checkStrictMode)(c,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(c,i)){let n=(0,t._)`${m} >= ${l}`;u!==void 0&&(n=(0,t._)`${n} && ${m} <= ${u}`),e.pass(n);return}c.items=!0;let h=r.name(`valid`);u===void 0&&l===1?validateItems(h,()=>r.if(h,()=>r.break())):l===0?(r.let(h,!0),u!==void 0&&r.if((0,t._)`${s}.length > 0`,validateItemsWithCount)):(r.let(h,!1),validateItemsWithCount()),e.result(h,()=>e.reset());function validateItemsWithCount(){let e=r.name(`_valid`),t=r.let(`count`,0);validateItems(e,()=>r.if(e,()=>checkLimits(t)))}function validateItems(t,i){r.forRange(`i`,0,m,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function checkLimits(e){r.code((0,t._)`${e}++`),u===void 0?r.if((0,t._)`${e} >= ${l}`,()=>r.assign(h,!0).break()):(r.if((0,t._)`${e} > ${u}`,()=>r.assign(h,!1).break()),l===1?r.assign(h,!0):r.if((0,t._)`${e} >= ${l}`,()=>r.assign(h,!0)))}}}})),To=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=R(),n=z(),r=Va();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
170
+ || ${l} === "boolean" || ${a} === null`).assign(u,(0,i._)`[${a}]`)}}}function assignParentData({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function checkDataType(e,t,n,r=s.Correct){let a=r===s.Correct?i.operators.EQ:i.operators.NEQ,c;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:c=(0,i._)`Array.isArray(${t})`;break;case`object`:c=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:c=numCond((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:c=numCond();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===s.Correct?c:(0,i.not)(c);function numCond(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=checkDataType;function checkDataTypes(e,t,n,r){if(e.length===1)return checkDataType(e[0],t,n,r);let s,c=(0,a.toHash)(e);if(c.array&&c.object){let e=(0,i._)`typeof ${t} != "object"`;s=c.null?e:(0,i._)`!${t} || ${e}`,delete c.null,delete c.array,delete c.object}else s=i.nil;c.number&&delete c.integer;for(let e in c)s=(0,i.and)(s,checkDataType(e,t,n,r));return s}e.checkDataTypes=checkDataTypes;let l={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function reportTypeError(e){let t=getTypeErrorContext(e);(0,r.reportError)(t,l)}e.reportTypeError=reportTypeError;function getTypeErrorContext(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Ba=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=V(),n=H();function assignDefaults(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)assignDefault(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>assignDefault(e,n,t.default))}e.assignDefaults=assignDefaults;function assignDefault(e,r,i){let{gen:a,compositeRule:s,data:c,opts:l}=e;if(i===void 0)return;let u=(0,t._)`${c}${(0,t.getProperty)(r)}`;if(s){(0,n.checkStrictMode)(e,`default is ignored for: ${u}`);return}let f=(0,t._)`${u} === undefined`;l.useDefaults===`empty`&&(f=(0,t._)`${f} || ${u} === null || ${u} === ""`),a.if(f,(0,t._)`${u} = ${(0,t.stringify)(i)}`)}})),Va=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=V(),n=H(),r=Pa(),i=H();function checkReportMissingProp(e,n){let{gen:r,data:i,it:a}=e;r.if(noPropertyInData(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=checkReportMissingProp;function checkMissingProp({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(noPropertyInData(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=checkMissingProp;function reportMissingProp(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=reportMissingProp;function hasPropFunc(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=hasPropFunc;function isOwnProperty(e,n,r){return(0,t._)`${hasPropFunc(e)}.call(${n}, ${r})`}e.isOwnProperty=isOwnProperty;function propertyInData(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${isOwnProperty(e,n,r)}`:a}e.propertyInData=propertyInData;function noPropertyInData(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(isOwnProperty(e,n,r))):a}e.noPropertyInData=noPropertyInData;function allSchemaProperties(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=allSchemaProperties;function schemaProperties(e,t){return allSchemaProperties(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=schemaProperties;function callValidateCode({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:s,errorPath:c},it:l},u,f,p){let m=p?(0,t._)`${e}, ${n}, ${a}${s}`:n,h=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,c)],[r.default.parentData,l.parentData],[r.default.parentDataProperty,l.parentDataProperty],[r.default.rootData,r.default.rootData]];l.opts.dynamicRef&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let g=(0,t._)`${m}, ${i.object(...h)}`;return f===t.nil?(0,t._)`${u}(${g})`:(0,t._)`${u}.call(${f}, ${g})`}e.callValidateCode=callValidateCode;let a=(0,t._)`new RegExp`;function usePattern({gen:e,it:{opts:n}},r){let s=n.unicodeRegExp?`u`:``,{regExp:c}=n.code,l=c(r,s);return e.scopeValue(`pattern`,{key:l.toString(),ref:l,code:(0,t._)`${c.code===`new RegExp`?a:(0,i.useFunc)(e,c)}(${r}, ${s})`})}e.usePattern=usePattern;function validateArray(e){let{gen:r,data:i,keyword:a,it:s}=e,c=r.name(`valid`);if(s.allErrors){let e=r.let(`valid`,!0);return validateItems(()=>r.assign(e,!1)),e}return r.var(c,!0),validateItems(()=>r.break()),c;function validateItems(s){let l=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,l,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},c),r.if((0,t.not)(c),s)})}}e.validateArray=validateArray;function validateUnion(e){let{gen:r,schema:i,keyword:a,it:s}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(s,e))&&!s.opts.unevaluated)return;let c=r.let(`valid`,!1),l=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let s=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},l);r.assign(c,(0,t._)`${c} || ${l}`),e.mergeValidEvaluated(s,l)||r.if((0,t.not)(c))})),e.result(c,()=>e.reset(),()=>e.error(!0))}e.validateUnion=validateUnion})),Ha=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=V(),n=Pa(),r=Va(),i=Fa();function macroKeywordCode(e,n){let{gen:r,keyword:i,schema:a,parentSchema:s,it:c}=e,l=n.macro.call(c.self,a,s,c),u=useKeyword(r,i,l);c.opts.validateSchema!==!1&&c.self.validateSchema(l,!0);let f=r.name(`valid`);e.subschema({schema:l,schemaPath:t.nil,errSchemaPath:`${c.errSchemaPath}/${i}`,topSchemaRef:u,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}e.macroKeywordCode=macroKeywordCode;function funcKeywordCode(e,i){let{gen:a,keyword:s,schema:c,parentSchema:l,$data:u,it:f}=e;checkAsyncKeyword(f,i);let p=useKeyword(a,s,!u&&i.compile?i.compile.call(f.self,c,l,f):i.validate),m=a.let(`valid`);e.block$data(m,validateKeyword),e.ok(i.valid??m);function validateKeyword(){if(i.errors===!1)assignValid(),i.modifying&&modifyData(e),reportErrs(()=>e.error());else{let t=i.async?validateAsync():validateSync();i.modifying&&modifyData(e),reportErrs(()=>addErrs(e,t))}}function validateAsync(){let e=a.let(`ruleErrs`,null);return a.try(()=>assignValid((0,t._)`await `),n=>a.assign(m,!1).if((0,t._)`${n} instanceof ${f.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function validateSync(){let e=(0,t._)`${p}.errors`;return a.assign(e,null),assignValid(t.nil),e}function assignValid(s=i.async?(0,t._)`await `:t.nil){let c=f.opts.passContext?n.default.this:n.default.self,l=!(`compile`in i&&!u||i.schema===!1);a.assign(m,(0,t._)`${s}${(0,r.callValidateCode)(e,p,c,l)}`,i.modifying)}function reportErrs(e){a.if((0,t.not)(i.valid??m),e)}}e.funcKeywordCode=funcKeywordCode;function modifyData(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function addErrs(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function checkAsyncKeyword({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function useKeyword(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function validSchemaType(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=validSchemaType;function validateKeywordUsage({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let s=i.dependencies;if(s?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${s.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=validateKeywordUsage})),Ua=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=V(),n=H();function getSubschema(e,{keyword:r,schemaProp:i,schema:a,schemaPath:s,errSchemaPath:c,topSchemaRef:l}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(s===void 0||c===void 0||l===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:s,topSchemaRef:l,errSchemaPath:c}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=getSubschema;function extendSubschemaData(e,r,{dataProp:i,dataPropType:a,data:s,dataTypes:c,propertyName:l}){if(s!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:u}=r;if(i!==void 0){let{errorPath:s,dataPathArr:c,opts:l}=r;dataContextProps(u.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${s}${(0,n.getErrorPath)(i,a,l.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...c,e.parentDataProperty]}s!==void 0&&(dataContextProps(s instanceof t.Name?s:u.let(`data`,s,!0)),l!==void 0&&(e.propertyName=l)),c&&(e.dataTypes=c);function dataContextProps(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=extendSubschemaData;function extendSubschemaMode(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=extendSubschemaMode})),Wa=r(((e,t)=>{t.exports=function equal(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(e.constructor!==t.constructor)return!1;var n,r,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!equal(e[r],t[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){var a=i[r];if(!equal(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}})),Ga=r(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var r=typeof n==`function`?n:n.pre||function(){},i=n.post||function(){};_traverse(t,r,i,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _traverse(e,t,r,i,a,s,c,l,u,f){if(i&&typeof i==`object`&&!Array.isArray(i)){for(var p in t(i,a,s,c,l,u,f),i){var m=i[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)_traverse(e,t,r,m[h],a+`/`+p+`/`+h,s,a,p,i,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)_traverse(e,t,r,m[g],a+`/`+p+`/`+escapeJsonPtr(g),s,a,p,i,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&_traverse(e,t,r,m,a+`/`+p,s,a,p,i)}r(i,a,s,c,l,u,f)}}function escapeJsonPtr(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Ka=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=H(),n=Wa(),r=Ga(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function inlineRef(e,t=!0){return typeof e==`boolean`?!0:t===!0?!hasRef(e):t?countKeys(e)<=t:!1}e.inlineRef=inlineRef;let a=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function hasRef(e){for(let t in e){if(a.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(hasRef)||typeof n==`object`&&hasRef(n))return!0}return!1}function countKeys(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=countKeys(e)),n===1/0)))return 1/0;return n}function getFullPath(e,t=``,n){return n!==!1&&(t=normalizeId(t)),_getFullPath(e,e.parse(t))}e.getFullPath=getFullPath;function _getFullPath(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=_getFullPath;let s=/#\/?$/;function normalizeId(e){return e?e.replace(s,``):``}e.normalizeId=normalizeId;function resolveUrl(e,t,n){return n=normalizeId(n),e.resolve(t,n)}e.resolveUrl=resolveUrl;let c=/^[a-z_][-a-z0-9._]*$/i;function getSchemaRefs(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,s=normalizeId(e[i]||t),l={"":s},u=getFullPath(a,s,!1),f={},p=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=u+t,s=l[r];typeof e[i]==`string`&&(s=addRef.call(this,e[i])),addAnchor.call(this,e.$anchor),addAnchor.call(this,e.$dynamicAnchor),l[t]=s;function addRef(t){let n=this.opts.uriResolver.resolve;if(t=normalizeId(s?n(s,t):t),p.has(t))throw ambiguos(t);p.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?checkAmbiguosRef(e,r.schema,t):t!==normalizeId(a)&&(t[0]===`#`?(checkAmbiguosRef(e,f[t],t),f[t]=e):this.refs[t]=a),t}function addAnchor(e){if(typeof e==`string`){if(!c.test(e))throw Error(`invalid anchor "${e}"`);addRef.call(this,`#${e}`)}}}),f;function checkAmbiguosRef(e,t,r){if(t!==void 0&&!n(e,t))throw ambiguos(r)}function ambiguos(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=getSchemaRefs})),qa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ia(),n=za(),r=Ra(),i=za(),a=Ba(),s=Ha(),c=Ua(),l=V(),u=Pa(),f=Ka(),p=H(),m=Fa();function validateFunctionCode(e){if(isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))){topSchemaObjCode(e);return}validateFunction(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=validateFunctionCode;function validateFunction({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,l._)`${u.default.data}, ${u.default.valCxt}`,r.$async,()=>{e.code((0,l._)`"use strict"; ${funcSourceUrl(n,i)}`),destructureValCxtES5(e,i),e.code(a)}):e.func(t,(0,l._)`${u.default.data}, ${destructureValCxt(i)}`,r.$async,()=>e.code(funcSourceUrl(n,i)).code(a))}function destructureValCxt(e){return(0,l._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${e.dynamicRef?(0,l._)`, ${u.default.dynamicAnchors}={}`:l.nil}}={}`}function destructureValCxtES5(e,t){e.if(u.default.valCxt,()=>{e.var(u.default.instancePath,(0,l._)`${u.default.valCxt}.${u.default.instancePath}`),e.var(u.default.parentData,(0,l._)`${u.default.valCxt}.${u.default.parentData}`),e.var(u.default.parentDataProperty,(0,l._)`${u.default.valCxt}.${u.default.parentDataProperty}`),e.var(u.default.rootData,(0,l._)`${u.default.valCxt}.${u.default.rootData}`),t.dynamicRef&&e.var(u.default.dynamicAnchors,(0,l._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{e.var(u.default.instancePath,(0,l._)`""`),e.var(u.default.parentData,(0,l._)`undefined`),e.var(u.default.parentDataProperty,(0,l._)`undefined`),e.var(u.default.rootData,u.default.data),t.dynamicRef&&e.var(u.default.dynamicAnchors,(0,l._)`{}`)})}function topSchemaObjCode(e){let{schema:t,opts:n,gen:r}=e;validateFunction(e,()=>{n.$comment&&t.$comment&&commentKeyword(e),checkNoDefault(e),r.let(u.default.vErrors,null),r.let(u.default.errors,0),n.unevaluated&&resetEvaluated(e),typeAndKeywords(e),returnResults(e)})}function resetEvaluated(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,l._)`${n}.evaluated`),t.if((0,l._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,l._)`${e.evaluated}.props`,(0,l._)`undefined`)),t.if((0,l._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,l._)`${e.evaluated}.items`,(0,l._)`undefined`))}function funcSourceUrl(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,l._)`/*# sourceURL=${n} */`:l.nil}function subschemaCode(e,n){if(isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))){subSchemaObjCode(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function schemaCxtHasRules({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function isSchemaObj(e){return typeof e.schema!=`boolean`}function subSchemaObjCode(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&commentKeyword(e),updateContext(e),checkAsyncSchema(e);let a=r.const(`_errs`,u.default.errors);typeAndKeywords(e,a),r.var(t,(0,l._)`${a} === ${u.default.errors}`)}function checkKeywords(e){(0,p.checkUnknownRules)(e),checkRefsAndKeywords(e)}function typeAndKeywords(e,t){if(e.opts.jtd)return schemaKeywords(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);schemaKeywords(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function checkRefsAndKeywords(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function checkNoDefault(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,p.checkStrictMode)(e,`default is ignored in the schema root`)}function updateContext(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,f.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function checkAsyncSchema(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function commentKeyword({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,l._)`${u.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,l.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,l._)`${u.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function returnResults(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,l._)`${u.default.errors} === 0`,()=>t.return(u.default.data),()=>t.throw((0,l._)`new ${i}(${u.default.vErrors})`)):(t.assign((0,l._)`${r}.errors`,u.default.vErrors),a.unevaluated&&assignEvaluated(e),t.return((0,l._)`${u.default.errors} === 0`))}function assignEvaluated({gen:e,evaluated:t,props:n,items:r}){n instanceof l.Name&&e.assign((0,l._)`${t}.props`,n),r instanceof l.Name&&e.assign((0,l._)`${t}.items`,r)}function schemaKeywords(e,t,n,a){let{gen:s,schema:c,data:f,allErrors:m,opts:h,self:g}=e,{RULES:v}=g;if(c.$ref&&(h.ignoreKeywordsWithRef||!(0,p.schemaHasRulesButRef)(c,v))){s.block(()=>keywordCode(e,`$ref`,v.all.$ref.definition));return}h.jtd||checkStrictTypes(e,t),s.block(()=>{for(let e of v.rules)groupKeywords(e);groupKeywords(v.post)});function groupKeywords(p){(0,r.shouldUseGroup)(c,p)&&(p.type?(s.if((0,i.checkDataType)(p.type,f,h.strictNumbers)),iterateKeywords(e,p),t.length===1&&t[0]===p.type&&n&&(s.else(),(0,i.reportTypeError)(e)),s.endIf()):iterateKeywords(e,p),m||s.if((0,l._)`${u.default.errors} === ${a||0}`))}}function iterateKeywords(e,t){let{gen:n,schema:i,opts:{useDefaults:s}}=e;s&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&keywordCode(e,n.keyword,n.definition,t.type)})}function checkStrictTypes(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(checkContextTypes(e,t),e.opts.allowUnionTypes||checkMultipleTypes(e,t),checkKeywordTypes(e,e.dataTypes))}function checkContextTypes(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{includesType(e.dataTypes,t)||strictTypesError(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),narrowSchemaTypes(e,t)}}function checkMultipleTypes(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&strictTypesError(e,`use allowUnionTypes to allow union type keyword`)}function checkKeywordTypes(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>hasApplicableType(t,e))&&strictTypesError(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function hasApplicableType(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function includesType(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function narrowSchemaTypes(e,t){let n=[];for(let r of e.dataTypes)includesType(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function strictTypesError(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,p.checkStrictMode)(e,t,e.opts.strictTypes)}var KeywordCxt=class{constructor(e,t,n){if((0,s.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,p.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,getData(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,u.default.errors))}result(e,t,n){this.failResult((0,l.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,l.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,l._)`${t} !== undefined && (${(0,l.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?m.reportExtraError:m.reportError)(this,this.def.error,t)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=l.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=l.nil,t=l.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,l.or)((0,l._)`${r} === undefined`,t)),e!==l.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==l.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,l.or)(wrong$DataType(),invalid$DataSchema());function wrong$DataType(){if(n.length){if(!(t instanceof l.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,l._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return l.nil}function invalid$DataSchema(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,l._)`!${n}(${t})`}return l.nil}}subschema(e,t){let n=(0,c.getSubschema)(this.it,e);(0,c.extendSubschemaData)(n,this.it,e),(0,c.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return subschemaCode(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=p.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=p.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,l.Name)),!0}};e.KeywordCxt=KeywordCxt;function keywordCode(e,t,n,r){let i=new KeywordCxt(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,s.funcKeywordCode)(i,n):`macro`in n?(0,s.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,s.funcKeywordCode)(i,n)}let h=/^\/(?:[^~]|~0|~1)*$/,g=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return u.default.rootData;if(e[0]===`/`){if(!h.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=u.default.rootData}else{let s=g.exec(e);if(!s)throw Error(`Invalid JSON-pointer: ${e}`);let c=+s[1];if(i=s[2],i===`#`){if(c>=t)throw Error(errorMsg(`property/index`,c));return r[t-c]}if(c>t)throw Error(errorMsg(`data`,c));if(a=n[t-c],!i)return a}let s=a,c=i.split(`/`);for(let e of c)e&&(a=(0,l._)`${a}${(0,l.getProperty)((0,p.unescapeJsonPointer)(e))}`,s=(0,l._)`${s} && ${a}`);return s;function errorMsg(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=getData})),Ja=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});var ValidationError=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}};e.default=ValidationError})),Ya=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ka();var MissingRefError=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}};e.default=MissingRefError})),Xa=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=V(),n=Ja(),r=Pa(),i=Ka(),a=H(),s=qa();var SchemaEnv=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=SchemaEnv;function compileSchema(e){let a=getCompilingSchema.call(this,e);if(a)return a;let c=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:l,lines:u}=this.opts.code,{ownProperties:f}=this.opts,p=new t.CodeGen(this.scope,{es5:l,lines:u,ownProperties:f}),m;e.$async&&(m=p.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let h=p.scopeName(`validate`);e.validateName=h;let g={gen:p,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:h,ValidationError:m,schema:e.schema,schemaEnv:e,rootId:c,baseId:e.baseId||c,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},v;try{this._compilations.add(e),(0,s.validateFunctionCode)(g),p.optimize(this.opts.code.optimize);let n=p.toString();v=`${p.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(v=this.opts.code.process(v,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,v)(this,this.scope.get());if(this.scope.value(h,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:h,validateCode:n,scopeValues:p._values}),this.opts.unevaluated){let{props:e,items:n}=g;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,v&&this.logger.error(`Error compiling schema, function code:`,v),t}finally{this._compilations.delete(e)}}e.compileSchema=compileSchema;function resolveRef(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=resolve.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new SchemaEnv({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=inlineOrCompile.call(this,a)}e.resolveRef=resolveRef;function inlineOrCompile(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:compileSchema.call(this,e)}function getCompilingSchema(e){for(let t of this._compilations)if(sameSchemaEnv(t,e))return t}e.getCompilingSchema=getCompilingSchema;function sameSchemaEnv(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function resolve(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||resolveSchema.call(this,e,t)}function resolveSchema(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return getJsonPointer.call(this,n,e);let s=(0,i.normalizeId)(r),c=this.refs[s]||this.schemas[s];if(typeof c==`string`){let t=resolveSchema.call(this,e,c);return typeof t?.schema==`object`?getJsonPointer.call(this,n,t):void 0}if(typeof c?.schema==`object`){if(c.validate||compileSchema.call(this,c),s===(0,i.normalizeId)(t)){let{schema:t}=c,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new SchemaEnv({schema:t,schemaId:n,root:e,baseId:a})}return getJsonPointer.call(this,n,c)}}e.resolveSchema=resolveSchema;let c=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function getJsonPointer(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let s=typeof n==`object`&&n[this.opts.schemaId];!c.has(r)&&s&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,s))}let s;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=resolveSchema.call(this,r,e)}let{schemaId:l}=this.opts;if(s||=new SchemaEnv({schema:n,schemaId:l,root:r,baseId:t}),s.schema!==s.root.schema)return s}})),Za=r(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Qa=r(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function stringArrayToHexStripped(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function consumeIsZone(e){return e.length=0,!0}function consumeHextets(e,t,n){if(e.length){let r=stringArrayToHexStripped(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function getIPV6(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,s=!1,c=consumeHextets;for(let l=0;l<e.length;l++){let u=e[l];if(u!==`[`&&u!==`]`){if(u===`:`){if(a===!0&&(s=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}l>0&&e[l-1]===`:`&&(a=!0),r.push(`:`);continue}if(u===`%`){if(!c(i,r,n))break;c=consumeIsZone}else{i.push(u);continue}}}return i.length&&(c===consumeIsZone?n.zone=i.join(``):s?r.push(i.join(``)):r.push(stringArrayToHexStripped(i))),n.address=r.join(``),n}function normalizeIPv6(e){if(findToken(e,`:`)<2)return{host:e,isIPV6:!1};let t=getIPV6(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function findToken(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function removeDotSegments(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function normalizeComponentEncoding(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function recomposeAuthority(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=normalizeIPv6(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:i,recomposeAuthority,normalizeComponentEncoding,removeDotSegments,isIPv4:r,isUUID:n,normalizeIPv6,stringArrayToHexStripped}})),$a=r(((e,t)=>{let{isUUID:n}=Qa(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function isValidSchemeName(e){return i.indexOf(e)!==-1}function wsIsSecure(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function httpParse(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function httpSerialize(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function wsParse(e){return e.secure=wsIsSecure(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function wsSerialize(e){if((e.port===(wsIsSecure(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function urnParse(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=getSchemeHandler(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function urnSerialize(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=getSchemeHandler(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,s=e.nss;return a.path=`${r||t.nid}:${s}`,t.skipEscape=!0,a}function urnuuidParse(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function urnuuidSerialize(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let a={scheme:`http`,domainHost:!0,parse:httpParse,serialize:httpSerialize},s={scheme:`https`,domainHost:a.domainHost,parse:httpParse,serialize:httpSerialize},c={scheme:`ws`,domainHost:!0,parse:wsParse,serialize:wsSerialize},l={http:a,https:s,ws:c,wss:{scheme:`wss`,domainHost:c.domainHost,parse:c.parse,serialize:c.serialize},urn:{scheme:`urn`,parse:urnParse,serialize:urnSerialize,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:urnuuidParse,serialize:urnuuidSerialize,skipNormalize:!0}};Object.setPrototypeOf(l,null);function getSchemeHandler(e){return e&&(l[e]||l[e.toLowerCase()])||void 0}t.exports={wsIsSecure,SCHEMES:l,isValidSchemeName,getSchemeHandler}})),eo=r(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:s,nonSimpleDomain:c}=Qa(),{SCHEMES:l,getSchemeHandler:u}=$a();function normalize(e,t){return typeof e==`string`?e=serialize(parse(e,t),t):typeof e==`object`&&(e=parse(serialize(e,t),t)),e}function resolve(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=resolveComponent(parse(e,r),parse(t,r),r,!0);return r.skipEscape=!0,serialize(i,r)}function resolveComponent(e,t,n,i){let a={};return i||(e=parse(serialize(e,n),n),t=parse(serialize(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function equal(e,t,n){return typeof e==`string`?(e=unescape(e),e=serialize(a(parse(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=serialize(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=serialize(a(parse(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=serialize(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function serialize(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),s=[],c=u(a.scheme||n.scheme);c&&c.serialize&&c.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&s.push(n.scheme,`:`);let l=i(n);if(l!==void 0&&(a.reference!==`suffix`&&s.push(`//`),s.push(l),n.path&&n.path[0]!==`/`&&s.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!c||!c.absolutePath)&&(e=r(e)),l===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),s.push(e)}return n.query!==void 0&&s.push(`?`,n.query),n.fragment!==void 0&&s.push(`#`,n.fragment),s.join(``)}let f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function parse(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let l=e.match(f);if(l){if(i.scheme=l[1],i.userinfo=l[3],i.host=l[4],i.port=parseInt(l[5],10),i.path=l[6]||``,i.query=l[7],i.fragment=l[8],isNaN(i.port)&&(i.port=l[5]),i.host){if(s(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=u(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&c(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let p={SCHEMES:l,normalize,resolve,resolveComponent,equal,serialize,parse};t.exports=p,t.exports.default=p,t.exports.fastUri=p})),to=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=eo();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),no=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=V();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Ja(),i=Ya(),a=La(),s=Xa(),c=V(),l=Ka(),u=za(),f=H(),p=Za(),m=to(),defaultRegExp=(e,t)=>new RegExp(e,t);defaultRegExp.code=`new RegExp`;let h=[`removeAdditional`,`useDefaults`,`coerceTypes`],g=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),v={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},y={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function requiredOptions(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??defaultRegExp,a=e.uriResolver??m.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var Ajv=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...requiredOptions(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:g,es5:t,lines:n}),this.logger=getLogger(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),checkOptions.call(this,v,e,`NOT SUPPORTED`),checkOptions.call(this,y,e,`DEPRECATED`,`warn`),this._metaOpts=getMetaSchemaOptions.call(this),e.formats&&addInitialFormats.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&addInitialKeywords.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),addInitialSchemas.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=p;n===`id`&&(r={...p},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return runCompileAsync.call(this,e,t);async function runCompileAsync(e,t){await loadMetaSchema.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||_compileAsync.call(this,n)}async function loadMetaSchema(e){e&&!this.getSchema(e)&&await runCompileAsync.call(this,{$ref:e},!0)}async function _compileAsync(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return checkLoaded.call(this,t),await loadMissingSchema.call(this,t.missingSchema),_compileAsync.call(this,e)}}function checkLoaded({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function loadMissingSchema(e){let n=await _loadSchema.call(this,e);this.refs[e]||await loadMetaSchema.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function _loadSchema(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,l.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=getSchEnv.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new s.SchemaEnv({schema:{},schemaId:n});if(t=s.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=getSchEnv.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,l.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(checkKeyword.call(this,n,t),!t)return(0,f.eachItem)(n,e=>addRule.call(this,e)),this;keywordMetaschema.call(this,t);let r={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,f.eachItem)(n,r.type.length===0?e=>addRule.call(this,e,r):e=>r.type.forEach(t=>addRule.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=schemaOrData(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:c}=this.opts;if(typeof e==`object`)a=e[c];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let u=this._cache.get(e);if(u!==void 0)return u;n=(0,l.normalizeId)(a||n);let f=l.getSchemaRefs.call(this,e,n);return u=new s.SchemaEnv({schema:e,schemaId:c,meta:t,baseId:n,localRefs:f}),this._cache.set(u.schema,u),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=u),r&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):s.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}};Ajv.ValidationError=r.default,Ajv.MissingRefError=i.default,e.default=Ajv;function checkOptions(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function getSchEnv(e){return e=(0,l.normalizeId)(e),this.schemas[e]||this.refs[e]}function addInitialSchemas(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function addInitialFormats(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function addInitialKeywords(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function getMetaSchemaOptions(){let e={...this.opts};for(let t of h)delete e[t];return e}let b={log(){},warn(){},error(){}};function getLogger(e){if(e===!1)return b;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ee=/^[a-z_$][a-z0-9_$:-]*$/i;function checkKeyword(e,t){let{RULES:n}=this;if((0,f.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ee.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function addRule(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,s=i?a.post:a.rules.find(({type:e})=>e===n);if(s||(s={type:n,rules:[]},a.rules.push(s)),a.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?addBeforeRule.call(this,s,c,t.before):s.rules.push(c),a.all[e]=c,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function addBeforeRule(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function keywordMetaschema(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=schemaOrData(t)),e.validateSchema=this.compile(t,!0))}let te={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function schemaOrData(e){return{anyOf:[e,te]}}})),ro=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),io=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Ya(),n=Va(),r=V(),i=Pa(),a=Xa(),s=H(),c={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:s}=e,{baseId:c,schemaEnv:l,validateName:u,opts:f,self:p}=s,{root:m}=l;if((i===`#`||i===`#/`)&&c===m.baseId)return callRootRef();let h=a.resolveRef.call(p,m,c,i);if(h===void 0)throw new t.default(s.opts.uriResolver,c,i);if(h instanceof a.SchemaEnv)return callValidate(h);return inlineRefSchema(h);function callRootRef(){if(l===m)return callRef(e,u,l,l.$async);let t=n.scopeValue(`root`,{ref:m});return callRef(e,(0,r._)`${t}.validate`,m,m.$async)}function callValidate(t){callRef(e,getValidate(e,t),t,t.$async)}function inlineRefSchema(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),s=n.name(`valid`),c=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},s);e.mergeEvaluated(c),e.ok(s)}}};function getValidate(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=getValidate;function callRef(e,t,a,c){let{gen:l,it:u}=e,{allErrors:f,schemaEnv:p,opts:m}=u,h=m.passContext?i.default.this:r.nil;c?callAsyncRef():callSyncRef();function callAsyncRef(){if(!p.$async)throw Error(`async schema referenced by sync schema`);let i=l.let(`valid`);l.try(()=>{l.code((0,r._)`await ${(0,n.callValidateCode)(e,t,h)}`),addEvaluatedFrom(t),f||l.assign(i,!0)},e=>{l.if((0,r._)`!(${e} instanceof ${u.ValidationError})`,()=>l.throw(e)),addErrorsFrom(e),f||l.assign(i,!1)}),e.ok(i)}function callSyncRef(){e.result((0,n.callValidateCode)(e,t,h),()=>addEvaluatedFrom(t),()=>addErrorsFrom(t))}function addErrorsFrom(e){let t=(0,r._)`${e}.errors`;l.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),l.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function addEvaluatedFrom(e){if(!u.opts.unevaluated)return;let t=a?.validate?.evaluated;if(u.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(u.props=s.mergeEvaluated.props(l,t.props,u.props));else{let t=l.var(`props`,(0,r._)`${e}.evaluated.props`);u.props=s.mergeEvaluated.props(l,t,u.props,r.Name)}}if(u.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(u.items=s.mergeEvaluated.items(l,t.items,u.items));else{let t=l.var(`items`,(0,r._)`${e}.evaluated.items`);u.items=s.mergeEvaluated.items(l,t,u.items,r.Name)}}}}e.callRef=callRef,e.default=c})),ao=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=io();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),oo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),so=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,s=a.opts.multipleOfPrecision,c=n.let(`res`),l=s?(0,t._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${s}`:(0,t._)`${c} !== parseInt(${c})`;e.fail$data((0,t._)`(${i} === 0 || (${c} = ${r}/${i}, ${l}))`)}}})),co=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});function ucs2length(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=ucs2length,ucs2length.code=`require("ajv/dist/runtime/ucs2length").default`})),lo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r=co();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:s,it:c}=e,l=i===`maxLength`?t.operators.GT:t.operators.LT,u=c.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${u} ${l} ${s}`)}}})),uo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=H(),r=V();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:s,schema:c,schemaCode:l,it:u}=e,f=u.opts.unicodeRegExp?`u`:``;if(s){let{regExp:t}=u.opts.code,s=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),c=i.let(`valid`);i.try(()=>i.assign(c,(0,r._)`${s}(${l}, ${f}).test(${a})`),()=>i.assign(c,!1)),e.fail$data((0,r._)`!${c}`)}else{let n=(0,t.usePattern)(e,c);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),fo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),po=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=V(),r=H();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:s,data:c,$data:l,it:u}=e,{opts:f}=u;if(!l&&a.length===0)return;let p=a.length>=f.loopRequired;if(u.allErrors?allErrorsMode():exitOnErrorMode(),f.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${u.schemaEnv.baseId+u.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(u,t,u.opts.strictRequired)}}function allErrorsMode(){if(p||l)e.block$data(n.nil,loopAllRequired);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function exitOnErrorMode(){let n=i.let(`missing`);if(p||l){let t=i.let(`valid`,!0);e.block$data(t,()=>loopUntilMissing(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function loopAllRequired(){i.forOf(`prop`,s,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,c,n,f.ownProperties),()=>e.error())})}function loopUntilMissing(r,a){e.setParams({missingProperty:r}),i.forOf(r,s,()=>{i.assign(a,(0,t.propertyInData)(i,c,r,f.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),mo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),ho=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wa();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),go=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=za(),n=V(),r=H(),i=ho();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:s,$data:c,schema:l,parentSchema:u,schemaCode:f,it:p}=e;if(!c&&!l)return;let m=a.let(`valid`),h=u.items?(0,t.getSchemaTypes)(u.items):[];e.block$data(m,validateUniqueItems,(0,n._)`${f} === false`),e.ok(m);function validateUniqueItems(){let t=a.let(`i`,(0,n._)`${s}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(m,!0),a.if((0,n._)`${t} > 1`,()=>(canOptimize()?loopN:loopN2)(t,r))}function canOptimize(){return h.length>0&&!h.some(e=>e===`object`||e===`array`)}function loopN(r,i){let c=a.name(`item`),l=(0,t.checkDataTypes)(h,c,p.opts.strictNumbers,t.DataType.Wrong),u=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(c,(0,n._)`${s}[${r}]`),a.if(l,(0,n._)`continue`),h.length>1&&a.if((0,n._)`typeof ${c} == "string"`,(0,n._)`${c} += "_"`),a.if((0,n._)`typeof ${u}[${c}] == "number"`,()=>{a.assign(i,(0,n._)`${u}[${c}]`),e.error(),a.assign(m,!1).break()}).code((0,n._)`${u}[${c}] = ${r}`)})}function loopN2(t,c){let l=(0,r.useFunc)(a,i.default),u=a.name(`outer`);a.label(u).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${c} = ${t}; ${c}--;`,()=>a.if((0,n._)`${l}(${s}[${t}], ${s}[${c}])`,()=>{e.error(),a.assign(m,!1).break(u)})))}}}})),_o=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r=ho();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:s,schemaCode:c,schema:l}=e;s||l&&typeof l==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${c})`):e.fail((0,t._)`${l} !== ${a}`)}}})),vo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r=ho();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:s,schema:c,schemaCode:l,it:u}=e;if(!s&&c.length===0)throw Error(`enum must have non-empty array`);let f=c.length>=u.opts.loopEnum,p,getEql=()=>p??=(0,n.useFunc)(i,r.default),m;if(f||s)m=i.let(`valid`),e.block$data(m,loopEnum);else{if(!Array.isArray(c))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,l);m=(0,t.or)(...c.map((t,n)=>equalCode(e,n)))}e.pass(m);function loopEnum(){i.assign(m,!1),i.forOf(`v`,l,e=>i.if((0,t._)`${getEql()}(${a}, ${e})`,()=>i.assign(m,!0).break()))}function equalCode(e,n){let r=c[n];return typeof r==`object`&&r?(0,t._)`${getEql()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),yo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=oo(),n=so(),r=lo(),i=uo(),a=fo(),s=po(),c=mo(),l=go(),u=_o(),f=vo();e.default=[t.default,n.default,r.default,i.default,a.default,s.default,c.default,l.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},u.default,f.default]})),bo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=V(),n=H(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}validateAdditionalItems(e,i)}};function validateAdditionalItems(e,r){let{gen:i,schema:a,data:s,keyword:c,it:l}=e;l.items=!0;let u=i.const(`len`,(0,t._)`${s}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${u} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(l,a)){let n=i.var(`valid`,(0,t._)`${u} <= ${r.length}`);i.if((0,t.not)(n),()=>validateItems(n)),e.ok(n)}function validateItems(a){i.forRange(`i`,r.length,u,r=>{e.subschema({keyword:c,dataProp:r,dataPropType:n.Type.Num},a),l.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=validateAdditionalItems,e.default=r})),xo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=V(),n=H(),r=Va(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return validateTuple(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function validateTuple(e,r,i=e.schema){let{gen:a,parentSchema:s,data:c,keyword:l,it:u}=e;checkStrictTuple(s),u.opts.unevaluated&&i.length&&u.items!==!0&&(u.items=n.mergeEvaluated.items(a,i.length,u.items));let f=a.name(`valid`),p=a.const(`len`,(0,t._)`${c}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(u,r)||(a.if((0,t._)`${p} > ${i}`,()=>e.subschema({keyword:l,schemaProp:i,dataProp:i},f)),e.ok(f))});function checkStrictTuple(e){let{opts:t,errSchemaPath:a}=u,s=i.length,c=s===e.minItems&&(s===e.maxItems||e[r]===!1);if(t.strictTuples&&!c){let e=`"${l}" is ${s}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(u,e,t.strictTuples)}}}e.validateTuple=validateTuple,e.default=i})),So=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xo();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Co=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r=Va(),i=bo();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:s}=e,{prefixItems:c}=a;s.items=!0,!(0,n.alwaysValidSchema)(s,t)&&(c?(0,i.validateAdditionalItems)(e,c):e.ok((0,r.validateArray)(e)))}}})),wo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:s,it:c}=e,l,u,{minContains:f,maxContains:p}=a;c.opts.next?(l=f===void 0?1:f,u=p):l=1;let m=r.const(`len`,(0,t._)`${s}.length`);if(e.setParams({min:l,max:u}),u===void 0&&l===0){(0,n.checkStrictMode)(c,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(u!==void 0&&l>u){(0,n.checkStrictMode)(c,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(c,i)){let n=(0,t._)`${m} >= ${l}`;u!==void 0&&(n=(0,t._)`${n} && ${m} <= ${u}`),e.pass(n);return}c.items=!0;let h=r.name(`valid`);u===void 0&&l===1?validateItems(h,()=>r.if(h,()=>r.break())):l===0?(r.let(h,!0),u!==void 0&&r.if((0,t._)`${s}.length > 0`,validateItemsWithCount)):(r.let(h,!1),validateItemsWithCount()),e.result(h,()=>e.reset());function validateItemsWithCount(){let e=r.name(`_valid`),t=r.let(`count`,0);validateItems(e,()=>r.if(e,()=>checkLimits(t)))}function validateItems(t,i){r.forRange(`i`,0,m,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function checkLimits(e){r.code((0,t._)`${e}++`),u===void 0?r.if((0,t._)`${e} >= ${l}`,()=>r.assign(h,!0).break()):(r.if((0,t._)`${e} > ${u}`,()=>r.assign(h,!1).break()),l===1?r.assign(h,!0):r.if((0,t._)`${e} >= ${l}`,()=>r.assign(h,!0)))}}}})),To=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=V(),n=H(),r=Va();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
171
171
  missingProperty: ${i},
172
172
  depsCount: ${n},
173
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=splitDependencies(e);validatePropertyDeps(e,t),validateSchemaDeps(e,n)}};function splitDependencies({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function validatePropertyDeps(e,n=e.schema){let{gen:i,data:a,it:s}=e;if(Object.keys(n).length===0)return;let c=i.let(`missing`);for(let l in n){let u=n[l];if(u.length===0)continue;let f=(0,r.propertyInData)(i,a,l,s.opts.ownProperties);e.setParams({property:l,depsCount:u.length,deps:u.join(`, `)}),s.allErrors?i.if(f,()=>{for(let t of u)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${f} && (${(0,r.checkMissingProp)(e,u,c)})`),(0,r.reportMissingProp)(e,c),i.else())}}e.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(e,t=e.schema){let{gen:i,data:a,keyword:s,it:c}=e,l=i.name(`valid`);for(let u in t)(0,n.alwaysValidSchema)(c,t[u])||(i.if((0,r.propertyInData)(i,a,u,c.opts.ownProperties),()=>{let t=e.subschema({keyword:s,schemaProp:u},l);e.mergeValidEvaluated(t,l)},()=>i.var(l,!0)),e.ok(l))}e.validateSchemaDeps=validateSchemaDeps,e.default=i})),Eo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z();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:r,schema:i,data:a,it:s}=e;if((0,n.alwaysValidSchema)(s,i))return;let c=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},c),r.if((0,t.not)(c),()=>{e.error(!0),s.allErrors||r.break()})}),e.ok(c)}}})),Do=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=R(),r=Pa(),i=z();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:s,parentSchema:c,data:l,errsCount:u,it:f}=e;if(!u)throw Error(`ajv implementation error`);let{allErrors:p,opts:m}=f;if(f.props=!0,m.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(f,s))return;let h=(0,t.allSchemaProperties)(c.properties),g=(0,t.allSchemaProperties)(c.patternProperties);checkAdditionalProperties(),e.ok((0,n._)`${u} === ${r.default.errors}`);function checkAdditionalProperties(){a.forIn(`key`,l,e=>{!h.length&&!g.length?additionalPropertyCode(e):a.if(isAdditional(e),()=>additionalPropertyCode(e))})}function isAdditional(r){let s;if(h.length>8){let e=(0,i.schemaRefOrVal)(f,c.properties,`properties`);s=(0,t.isOwnProperty)(a,e,r)}else s=h.length?(0,n.or)(...h.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return g.length&&(s=(0,n.or)(s,...g.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(s)}function deleteAdditional(e){a.code((0,n._)`delete ${l}[${e}]`)}function additionalPropertyCode(t){if(m.removeAdditional===`all`||m.removeAdditional&&s===!1){deleteAdditional(t);return}if(s===!1){e.setParams({additionalProperty:t}),e.error(),p||a.break();return}if(typeof s==`object`&&!(0,i.alwaysValidSchema)(f,s)){let r=a.name(`valid`);m.removeAdditional===`failing`?(applyAdditionalSchema(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),deleteAdditional(t)})):(applyAdditionalSchema(t,r),p||a.if((0,n.not)(r),()=>a.break()))}}function applyAdditionalSchema(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Oo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qa(),n=Va(),r=z(),i=Do();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:s,parentSchema:c,data:l,it:u}=e;u.opts.removeAdditional===`all`&&c.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(u,i.default,`additionalProperties`));let f=(0,n.allSchemaProperties)(s);for(let e of f)u.definedProperties.add(e);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),u.props));let p=f.filter(e=>!(0,r.alwaysValidSchema)(u,s[e]));if(p.length===0)return;let m=a.name(`valid`);for(let t of p)hasDefault(t)?applyPropertySchema(t):(a.if((0,n.propertyInData)(a,l,t,u.opts.ownProperties)),applyPropertySchema(t),u.allErrors||a.else().var(m,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(m);function hasDefault(e){return u.opts.useDefaults&&!u.compositeRule&&s[e].default!==void 0}function applyPropertySchema(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},m)}}}})),ko=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=R(),r=z(),i=z();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:s,data:c,parentSchema:l,it:u}=e,{opts:f}=u,p=(0,t.allSchemaProperties)(s),m=p.filter(e=>(0,r.alwaysValidSchema)(u,s[e]));if(p.length===0||m.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;let h=f.strictSchema&&!f.allowMatchingProperties&&l.properties,g=a.name(`valid`);u.props!==!0&&!(u.props instanceof n.Name)&&(u.props=(0,i.evaluatedPropsToName)(a,u.props));let{props:v}=u;validatePatternProperties();function validatePatternProperties(){for(let e of p)h&&checkMatchingProperties(e),u.allErrors?validateProperties(e):(a.var(g,!0),validateProperties(e),a.if(g))}function checkMatchingProperties(e){for(let t in h)new RegExp(e).test(t)&&(0,r.checkStrictMode)(u,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function validateProperties(r){a.forIn(`key`,c,s=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${s})`,()=>{let t=m.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:s,dataPropType:i.Type.Str},g),u.opts.unevaluated&&v!==!0?a.assign((0,n._)`${v}[${s}]`,!0):!t&&!u.allErrors&&a.if((0,n.not)(g),()=>a.break())})})}}}})),Ao=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=z();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),jo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Va().validateUnion,error:{message:`must match a schema in anyOf`}}})),Mo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z();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:r,schema:i,parentSchema:a,it:s}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(s.opts.discriminator&&a.discriminator)return;let c=i,l=r.let(`valid`,!1),u=r.let(`passing`,null),f=r.name(`_valid`);e.setParams({passing:u}),r.block(validateOneOf),e.result(l,()=>e.reset(),()=>e.error(!0));function validateOneOf(){c.forEach((i,a)=>{let c;(0,n.alwaysValidSchema)(s,i)?r.var(f,!0):c=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},f),a>0&&r.if((0,t._)`${f} && ${l}`).assign(l,!1).assign(u,(0,t._)`[${u}, ${a}]`).else(),r.if(f,()=>{r.assign(l,!0),r.assign(u,a),c&&e.mergeEvaluated(c,t.Name)})})}}}})),No=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=z();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let s=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(s)})}}})),Po=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r={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:r,parentSchema:i,it:a}=e;i.then===void 0&&i.else===void 0&&(0,n.checkStrictMode)(a,`"if" without "then" and "else" is ignored`);let s=hasSchema(a,`then`),c=hasSchema(a,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(validateIf(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,validateClause(`then`,t),validateClause(`else`,t))}else s?r.if(u,validateClause(`then`)):r.if((0,t.not)(u),validateClause(`else`));e.pass(l,()=>e.error(!0));function validateIf(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function validateClause(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function hasSchema(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Fo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=z();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Io=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bo(),n=So(),r=xo(),i=Co(),a=wo(),s=To(),c=Eo(),l=Do(),u=Oo(),f=ko(),p=Ao(),m=jo(),h=Mo(),g=No(),v=Po(),y=Fo();function getApplicator(e=!1){let b=[p.default,m.default,h.default,g.default,v.default,y.default,c.default,l.default,s.default,u.default,f.default];return e?b.push(n.default,i.default):b.push(t.default,r.default),b.push(a.default),b}e.default=getApplicator})),Lo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=R(),n=Pa(),r=Xa(),i=io(),a={keyword:`$dynamicAnchor`,schemaType:`string`,code:e=>dynamicAnchor(e,e.schema)};function dynamicAnchor(e,r){let{gen:i,it:a}=e;a.schemaEnv.root.dynamicAnchors[r]=!0;let s=(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(r)}`,c=a.errSchemaPath===`#`?a.validateName:_getValidate(e);i.if((0,t._)`!${s}`,()=>i.assign(s,c))}e.dynamicAnchor=dynamicAnchor;function _getValidate(e){let{schemaEnv:t,schema:n,self:a}=e.it,{root:s,baseId:c,localRefs:l,meta:u}=t.root,{schemaId:f}=a.opts,p=new r.SchemaEnv({schema:n,schemaId:f,root:s,baseId:c,localRefs:l,meta:u});return r.compileSchema.call(a,p),(0,i.getValidate)(e,p)}e.default=a})),Ro=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=R(),n=Pa(),r=io(),i={keyword:`$dynamicRef`,schemaType:`string`,code:e=>dynamicRef(e,e.schema)};function dynamicRef(e,i){let{gen:a,keyword:s,it:c}=e;if(i[0]!==`#`)throw Error(`"${s}" only supports hash fragment reference`);let l=i.slice(1);if(c.allErrors)_dynamicRef();else{let t=a.let(`valid`,!1);_dynamicRef(t),e.ok(t)}function _dynamicRef(e){if(c.schemaEnv.root.dynamicAnchors[l]){let r=a.let(`_v`,(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(l)}`);a.if(r,_callRef(r,e),_callRef(c.validateName,e))}else _callRef(c.validateName,e)()}function _callRef(t,n){return n?()=>a.block(()=>{(0,r.callRef)(e,t),a.let(n,!0)}):()=>(0,r.callRef)(e,t)}}e.dynamicRef=dynamicRef,e.default=i})),zo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Lo(),n=z();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),Bo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ro();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),Vo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Lo(),n=Ro(),r=zo(),i=Bo();e.default=[t.default,n.default,r.default,i.default]})),Ho=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=To();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),Uo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=To();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),Wo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=z();e.default={keyword:[`maxContains`,`minContains`],type:`array`,schemaType:`number`,code({keyword:e,parentSchema:n,it:r}){n.contains===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}}})),Go=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ho(),n=Uo(),r=Wo();e.default=[t.default,n.default,r.default]})),Ko=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z(),r=Pa();e.default={keyword:`unevaluatedProperties`,type:`object`,schemaType:[`boolean`,`object`],trackErrors:!0,error:{message:`must NOT have unevaluated properties`,params:({params:e})=>(0,t._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){let{gen:i,schema:a,data:s,errsCount:c,it:l}=e;if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f instanceof t.Name?i.if((0,t._)`${f} !== true`,()=>i.forIn(`key`,s,e=>i.if(unevaluatedDynamic(f,e),()=>unevaluatedPropCode(e)))):f!==!0&&i.forIn(`key`,s,e=>f===void 0?unevaluatedPropCode(e):i.if(unevaluatedStatic(f,e),()=>unevaluatedPropCode(e))),l.props=!0,e.ok((0,t._)`${c} === ${r.default.errors}`);function unevaluatedPropCode(r){if(a===!1){e.setParams({unevaluatedProperty:r}),e.error(),u||i.break();return}if(!(0,n.alwaysValidSchema)(l,a)){let a=i.name(`valid`);e.subschema({keyword:`unevaluatedProperties`,dataProp:r,dataPropType:n.Type.Str},a),u||i.if((0,t.not)(a),()=>i.break())}}function unevaluatedDynamic(e,n){return(0,t._)`!${e} || !${e}[${n}]`}function unevaluatedStatic(e,n){let r=[];for(let i in e)e[i]===!0&&r.push((0,t._)`${n} !== ${i}`);return(0,t.and)(...r)}}}})),qo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=z();e.default={keyword:`unevaluatedItems`,type:`array`,schemaType:[`boolean`,`object`],error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{gen:r,schema:i,data:a,it:s}=e,c=s.items||0;if(c===!0)return;let l=r.const(`len`,(0,t._)`${a}.length`);if(i===!1)e.setParams({len:c}),e.fail((0,t._)`${l} > ${c}`);else if(typeof i==`object`&&!(0,n.alwaysValidSchema)(s,i)){let n=r.var(`valid`,(0,t._)`${l} <= ${c}`);r.if((0,t.not)(n),()=>validateItems(n,c)),e.ok(n)}s.items=!0;function validateItems(i,a){r.forRange(`i`,a,l,a=>{e.subschema({keyword:`unevaluatedItems`,dataProp:a,dataPropType:n.Type.Num},i),s.allErrors||r.if((0,t.not)(i),()=>r.break())})}}}})),Jo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),n=qo();e.default=[t.default,n.default]})),Yo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R();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,n){let{gen:r,data:i,$data:a,schema:s,schemaCode:c,it:l}=e,{opts:u,errSchemaPath:f,schemaEnv:p,self:m}=l;if(!u.validateFormats)return;a?validate$DataFormat():validateFormat();function validate$DataFormat(){let a=r.scopeValue(`formats`,{ref:m.formats,code:u.code.formats}),s=r.const(`fDef`,(0,t._)`${a}[${c}]`),l=r.let(`fType`),f=r.let(`format`);r.if((0,t._)`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(l,(0,t._)`${s}.type || "string"`).assign(f,(0,t._)`${s}.validate`),()=>r.assign(l,(0,t._)`"string"`).assign(f,s)),e.fail$data((0,t.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return u.strictSchema===!1?t.nil:(0,t._)`${c} && !${f}`}function invalidFmt(){let e=p.$async?(0,t._)`(${s}.async ? await ${f}(${i}) : ${f}(${i}))`:(0,t._)`${f}(${i})`,r=(0,t._)`(typeof ${f} == "function" ? ${e} : ${f}.test(${i}))`;return(0,t._)`${f} && ${f} !== true && ${l} === ${n} && !${r}`}}function validateFormat(){let a=m.formats[s];if(!a){unknownFormat();return}if(a===!0)return;let[c,l,h]=getFormat(a);c===n&&e.pass(validCondition());function unknownFormat(){if(u.strictSchema===!1){m.logger.warn(unknownMsg());return}throw Error(unknownMsg());function unknownMsg(){return`unknown format "${s}" ignored in schema at path "${f}"`}}function getFormat(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):u.code.formats?(0,t._)`${u.code.formats}${(0,t.getProperty)(s)}`:void 0,i=r.scopeValue(`formats`,{key:s,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function validCondition(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!p.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${h}(${i})`}return typeof l==`function`?(0,t._)`${h}(${i})`:(0,t._)`${h}.test(${i})`}}}}})),Xo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Yo().default]})),Zo=r((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`]})),Qo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ao(),n=yo(),r=Io(),i=Vo(),a=Go(),s=Jo(),c=Xo(),l=Zo();e.default=[i.default,t.default,n.default,(0,r.default)(!0),c.default,l.metadataVocabulary,l.contentVocabulary,a.default,s.default]})),$o=r((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={}))})),es=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=R(),n=$o(),r=Xa(),i=Ya(),a=z();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:s,data:c,schema:l,parentSchema:u,it:f}=e,{oneOf:p}=u;if(!f.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let m=l.propertyName;if(typeof m!=`string`)throw Error(`discriminator: requires propertyName`);if(l.mapping)throw Error(`discriminator: mapping is not supported`);if(!p)throw Error(`discriminator: requires oneOf keyword`);let h=s.let(`valid`,!1),g=s.const(`tag`,(0,t._)`${c}${(0,t.getProperty)(m)}`);s.if((0,t._)`typeof ${g} == "string"`,()=>validateMapping(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:g,tagName:m})),e.ok(h);function validateMapping(){let r=getMapping();s.if(!1);for(let e in r)s.elseIf((0,t._)`${g} === ${e}`),s.assign(h,applyTagSchema(r[e]));s.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:g,tagName:m}),s.endIf()}function applyTagSchema(n){let r=s.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function getMapping(){let e={},t=hasRequired(u),n=!0;for(let e=0;e<p.length;e++){let s=p[e];if(s?.$ref&&!(0,a.schemaHasRulesButRef)(s,f.self.RULES)){let e=s.$ref;if(s=r.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,e),s instanceof r.SchemaEnv&&(s=s.schema),s===void 0)throw new i.default(f.opts.uriResolver,f.baseId,e)}let c=s?.properties?.[m];if(typeof c!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);n&&=t||hasRequired(s),addMappings(c,e)}if(!n)throw Error(`discriminator: "${m}" must be required`);return e;function hasRequired({required:e}){return Array.isArray(e)&&e.includes(m)}function addMappings(e,t){if(e.const)addMapping(e.const,t);else if(e.enum)for(let n of e.enum)addMapping(n,t);else throw Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function addMapping(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${m}" values must be unique strings`);e[t]=n}}}}})),ts=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}}})),ns=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}}})),rs=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}}})),is=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}})),as=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}}})),os=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),ss=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),cs=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),ls=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ts(),n=ns(),r=rs(),i=is(),a=as(),s=os(),c=ss(),l=cs(),u=[`/properties`];function addMetaSchema2020(e){return[t,n,r,i,a,with$data(this,s),c,with$data(this,l)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function with$data(t,n){return e?t.$dataMetaSchema(n,u):n}}e.default=addMetaSchema2020})),us=r(((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.Ajv2020=void 0;let n=no(),r=Qo(),i=es(),a=ls(),s=`https://json-schema.org/draft/2020-12/schema`;var Ajv2020=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(a.default.call(this,e),this.refs[`http://json-schema.org/schema`]=s)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv2020=Ajv2020,t.exports=e=Ajv2020,t.exports.Ajv2020=Ajv2020,Object.defineProperty(e,"__esModule",{value:!0}),e.default=Ajv2020;var c=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=R();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 u=Ja();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var f=Ya();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),ds=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function fmtDef(e,t){return{validate:e,compare:t}}e.fullFormats={date:fmtDef(date,compareDate),time:fmtDef(getTime(!0),compareTime),"date-time":fmtDef(getDateTime(!0),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"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,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,int32:{type:`number`,validate:validateInt32},int64:{type:`number`,validate:validateInt64},float:{type:`number`,validate:validateNumber},double:{type:`number`,validate:validateNumber},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\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,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\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,compareIsoDateTime),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 isLeapYear(e){return e%4==0&&(e%100!=0||e%400==0)}let t=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(e){let r=t.exec(e);if(!r)return!1;let i=+r[1],a=+r[2],s=+r[3];return a>=1&&a<=12&&s>=1&&s<=(a===2&&isLeapYear(i)?29:n[a])}function compareDate(e,t){if(e&&t)return e>t?1:e<t?-1:0}let r=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(e){return function time(t){let n=r.exec(t);if(!n)return!1;let i=+n[1],a=+n[2],s=+n[3],c=n[4],l=n[5]===`-`?-1:1,u=+(n[6]||0),f=+(n[7]||0);if(u>23||f>59||e&&!c)return!1;if(i<=23&&a<=59&&s<60)return!0;let p=a-f*l,m=i-u*l-+(p<0);return(m===23||m===-1)&&(p===59||p===-1)&&s<61}}function compareTime(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function compareIsoTime(e,t){if(!(e&&t))return;let n=r.exec(e),i=r.exec(t);if(n&&i)return e=n[1]+n[2]+n[3],t=i[1]+i[2]+i[3],e>t?1:e<t?-1:0}let i=/t|\s/i;function getDateTime(e){let t=getTime(e);return function date_time(e){let n=e.split(i);return n.length===2&&date(n[0])&&t(n[1])}}function compareDateTime(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function compareIsoDateTime(e,t){if(!(e&&t))return;let[n,r]=e.split(i),[a,s]=t.split(i),c=compareDate(n,a);if(c!==void 0)return c||compareTime(r,s)}let a=/\/|:/,s=/^(?:[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 uri(e){return a.test(e)&&s.test(e)}let c=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(e){return c.lastIndex=0,c.test(e)}let l=-(2**31),u=2**31-1;function validateInt32(e){return Number.isInteger(e)&&e<=u&&e>=l}function validateInt64(e){return Number.isInteger(e)}function validateNumber(){return!0}let f=/[^\\]\\Z/;function regex(e){if(f.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),fs=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ao(),n=yo(),r=Io(),i=Xo(),a=Zo();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),ps=r(((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}})),ms=r(((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 n=no(),r=fs(),i=es(),a=ps(),s=[`/properties`],c=`http://json-schema.org/draft-07/schema`;var Ajv=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,s):a;this.addMetaSchema(e,c,!1),this.refs[`http://json-schema.org/schema`]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};e.Ajv=Ajv,t.exports=e=Ajv,t.exports.Ajv=Ajv,Object.defineProperty(e,"__esModule",{value:!0}),e.default=Ajv;var l=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=R();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var f=Ja();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Ya();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),hs=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=ms(),n=R(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:s,keyword:c,it:l}=e,{opts:u,self:f}=l;if(!u.validateFormats)return;let p=new t.KeywordCxt(l,f.RULES.all.format.definition,`format`);p.$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let t=r.scopeValue(`formats`,{ref:f.formats,code:u.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${p.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,compareCode(i)))}function validateFormat(){let t=p.schema,i=f.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${c}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:u.code.formats?(0,n._)`${u.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(compareCode(a))}function compareCode(e){return(0,n._)`${e}.compare(${a}, ${s}) ${i[c].fail} 0`}},dependencies:[`format`]};let formatLimitPlugin=t=>(t.addKeyword(e.formatLimitDefinition),t);e.default=formatLimitPlugin})),gs=r(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=ds(),r=hs(),i=R(),a=new i.Name(`fullFormats`),s=new i.Name(`fastFormats`),formatsPlugin=(e,t={keywords:!0})=>{if(Array.isArray(t))return addFormats(e,t,n.fullFormats,a),e;let[i,c]=t.mode===`fast`?[n.fastFormats,s]:[n.fullFormats,a];return addFormats(e,t.formats||n.formatNames,i,c),t.keywords&&(0,r.default)(e),e};formatsPlugin.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function addFormats(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=formatsPlugin,Object.defineProperty(e,"__esModule",{value:!0}),e.default=formatsPlugin})),_s=us(),vs=e(gs(),1);const copyProperty=(e,t,n,r)=>{if(n===`length`||n===`prototype`||n===`arguments`||n===`caller`)return;let i=Object.getOwnPropertyDescriptor(e,n),a=Object.getOwnPropertyDescriptor(t,n);!canCopyProperty(i,a)&&r||Object.defineProperty(e,n,a)},canCopyProperty=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},changePrototype=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},wrappedToString=(e,t)=>`/* Wrapped ${e}*/\n${t}`,ys=Object.getOwnPropertyDescriptor(Function.prototype,`toString`),bs=Object.getOwnPropertyDescriptor(Function.prototype.toString,`name`),changeToString=(e,t,n)=>{let r=n===``?``:`with ${n.trim()}() `,i=wrappedToString.bind(null,r,t.toString());Object.defineProperty(i,"name",bs);let{writable:a,enumerable:s,configurable:c}=ys;Object.defineProperty(e,"toString",{value:i,writable:a,enumerable:s,configurable:c})};function mimicFunction(e,t,{ignoreNonConfigurable:n=!1}={}){let{name:r}=e;for(let r of Reflect.ownKeys(t))copyProperty(e,t,r,n);return changePrototype(e,t),changeToString(e,t,r),e}const debounceFunction=(e,t={})=>{if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:n=0,maxWait:r=1/0,before:i=!1,after:a=!0}=t;if(n<0||r<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!i&&!a)throw Error("Both `before` and `after` are false, function wouldn't be called.");let s,c,l,debouncedFunction=function(...t){let u=this,later=()=>{s=void 0,c&&=(clearTimeout(c),void 0),a&&(l=e.apply(u,t))},maxLater=()=>{c=void 0,s&&=(clearTimeout(s),void 0),a&&(l=e.apply(u,t))},f=i&&!s;return clearTimeout(s),s=setTimeout(later,n),r>0&&r!==1/0&&!c&&(c=setTimeout(maxLater,r)),f&&(l=e.apply(u,t)),l};return mimicFunction(debouncedFunction,e),debouncedFunction.cancel=()=>{s&&=(clearTimeout(s),void 0),c&&=(clearTimeout(c),void 0)},debouncedFunction},xs=Object.prototype.toString;function isType(e,t,n){return e?e.constructor===t||xs.call(e)===n:!1}function isUint8Array(e){return isType(e,Uint8Array,`[object Uint8Array]`)}function isArrayBuffer(e){return isType(e,ArrayBuffer,`[object ArrayBuffer]`)}function isUint8ArrayOrArrayBuffer(e){return isUint8Array(e)||isArrayBuffer(e)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function assertUint8ArrayOrArrayBuffer(e){if(!isUint8ArrayOrArrayBuffer(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)assertUint8Array(t),n.set(t,r),r+=t.length;return n}const Ss={utf8:new globalThis.TextDecoder(`utf8`)};function uint8ArrayToString(e,t=`utf8`){return assertUint8ArrayOrArrayBuffer(e),Ss[t]??=new globalThis.TextDecoder(t),Ss[t].decode(e)}function assertString(e){if(typeof e!=`string`)throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}const Cs=new globalThis.TextEncoder;function stringToUint8Array(e){return assertString(e),Cs.encode(e)}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));const ws=`aes-256-cbc`,Ts=new Set([`aes-256-cbc`,`aes-256-gcm`,`aes-256-ctr`]),isSupportedEncryptionAlgorithm=e=>typeof e==`string`&&Ts.has(e),createPlainObject=()=>Object.create(null),isExist=e=>e!==void 0,checkValueType=(e,t)=>{let n=new Set([`undefined`,`symbol`,`function`]),r=typeof t;if(n.has(r))throw TypeError(`Setting a value of type \`${r}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},Es=`__internal__`,Ds=`${Es}.migrations.version`;var Conf=class{path;events;#e;#t;#n;#r;#i={};#a=!1;#o;#s;#c;constructor(e={}){let t=this.#l(e);this.#r=t,this.#u(t),this.#f(t),this.#p(t),this.events=new EventTarget,this.#t=t.encryptionKey,this.#n=t.encryptionAlgorithm??ws,this.path=this.#m(t),this.#h(t),t.watch&&this._watch()}get(e,t){if(this.#r.accessPropertiesByDotNotation)return this._get(e,t);let{store:n}=this;return e in n?n[e]:t}set(e,t){if(typeof e!=`string`&&typeof e!=`object`)throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=`object`&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${Es} key, as it's used to manage this module internal operations.`);let{store:n}=this,set=(e,t)=>{if(checkValueType(e,t),this.#r.accessPropertiesByDotNotation)setProperty(n,e,t);else{if(e===`__proto__`||e===`constructor`||e===`prototype`)return;n[e]=t}};if(typeof e==`object`){let t=e;for(let[e,n]of Object.entries(t))set(e,n)}else set(e,t);this.store=n}has(e){return this.#r.accessPropertiesByDotNotation?hasProperty(this.store,e):e in this.store}appendToArray(e,t){checkValueType(e,t);let n=this.#r.accessPropertiesByDotNotation?this._get(e,[]):e in this.store?this.store[e]:[];if(!Array.isArray(n))throw TypeError(`The key \`${e}\` is already set to a non-array value`);this.set(e,[...n,t])}reset(...e){for(let t of e)isExist(this.#i[t])&&this.set(t,this.#i[t])}delete(e){let{store:t}=this;this.#r.accessPropertiesByDotNotation?deleteProperty(t,e):delete t[e],this.store=t}clear(){let e=createPlainObject();for(let t of Object.keys(this.#i))isExist(this.#i[t])&&(checkValueType(t,this.#i[t]),this.#r.accessPropertiesByDotNotation?setProperty(e,t,this.#i[t]):e[t]=this.#i[t]);this.store=e}onDidChange(e,t){if(typeof e!=`string`)throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleValueChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleStoreChange(e)}get size(){return Object.keys(this.store).filter(e=>!this._isReservedKeyPath(e)).length}get store(){try{let e=N.readFileSync(this.path,this.#t?null:`utf8`),t=this._decryptData(e),parseStore=e=>{let t=this._deserialize(e);return this.#a||this._validate(t),Object.assign(createPlainObject(),t)};return parseStore(t)}catch(e){if(e?.code===`ENOENT`)return this._ensureDirectory(),createPlainObject();if(this.#r.clearInvalidConfig){let t=e;if(t.name===`SyntaxError`||t.message?.startsWith(`Config schema violation:`)||t.message===`Failed to decrypt config data.`)return createPlainObject()}throw e}}set store(e){if(this._ensureDirectory(),!hasProperty(e,Es))try{let t=N.readFileSync(this.path,this.#t?null:`utf8`),n=this._decryptData(t),r=this._deserialize(n);hasProperty(r,Es)&&setProperty(e,Es,getProperty(r,Es))}catch{}this.#a||this._validate(e),this._write(e),this.events.dispatchEvent(new Event(`change`))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))this._isReservedKeyPath(e)||(yield[e,t])}_closeWatcher(){this.#o&&=(this.#o.close(),void 0),this.#s&&=(N.unwatchFile(this.path),!1),this.#c=void 0}_decryptData(e){let t=this.#t;if(!t)return typeof e==`string`?e:uint8ArrayToString(e);let n=this.#n,r=n===`aes-256-gcm`?16:0,i=`:`.codePointAt(0),a=typeof e==`string`?e.codePointAt(16):e[16];if(i===void 0||a!==i){if(n===`aes-256-cbc`)return typeof e==`string`?e:uint8ArrayToString(e);throw Error(`Failed to decrypt config data.`)}let getEncryptedPayload=e=>{if(r===0)return{ciphertext:e};let t=e.length-r;if(t<0)throw Error(`Invalid authentication tag length.`);return{ciphertext:e.slice(0,t),authenticationTag:e.slice(t)}},s=e.slice(0,16),c=e.slice(17),l=typeof c==`string`?stringToUint8Array(c):c,decrypt=e=>{let{ciphertext:r,authenticationTag:i}=getEncryptedPayload(l),a=wn.pbkdf2Sync(t,e,1e4,32,`sha512`),c=wn.createDecipheriv(n,a,s);return i&&c.setAuthTag(i),uint8ArrayToString(concatUint8Arrays([c.update(r),c.final()]))};try{return decrypt(s)}catch{try{return decrypt(s.toString())}catch{}}if(n===`aes-256-cbc`)return typeof e==`string`?e:uint8ArrayToString(e);throw Error(`Failed to decrypt config data.`)}_handleStoreChange(e){let t=this.store,onChange=()=>{let n=t,r=this.store;Mt(r,n)||(t=r,e.call(this,r,n))};return this.events.addEventListener(`change`,onChange),()=>{this.events.removeEventListener(`change`,onChange)}}_handleValueChange(e,t){let n=e(),onChange=()=>{let r=n,i=e();Mt(i,r)||(n=i,t.call(this,i,r))};return this.events.addEventListener(`change`,onChange),()=>{this.events.removeEventListener(`change`,onChange)}}_deserialize=e=>JSON.parse(e);_serialize=e=>JSON.stringify(e,void 0,` `);_validate(e){if(!this.#e||this.#e(e)||!this.#e.errors)return;let t=this.#e.errors.map(({instancePath:e,message:t=``})=>`\`${e.slice(1)}\` ${t}`);throw Error(`Config schema violation: `+t.join(`; `))}_ensureDirectory(){N.mkdirSync(j.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e),n=this.#t;if(n){let e=wn.randomBytes(16),r=wn.pbkdf2Sync(n,e,1e4,32,`sha512`),i=wn.createCipheriv(this.#n,r,e),a=concatUint8Arrays([i.update(stringToUint8Array(t)),i.final()]),s=[e,stringToUint8Array(`:`),a];this.#n===`aes-256-gcm`&&s.push(i.getAuthTag()),t=concatUint8Arrays(s)}if(P.env.SNAP)N.writeFileSync(this.path,t,{mode:this.#r.configFileMode});else try{writeFileSync$1(this.path,t,{mode:this.#r.configFileMode})}catch(e){if(e?.code===`EXDEV`){N.writeFileSync(this.path,t,{mode:this.#r.configFileMode});return}throw e}}_watch(){if(this._ensureDirectory(),N.existsSync(this.path)||this._write(createPlainObject()),P.platform===`win32`||P.platform===`darwin`){this.#c??=debounceFunction(()=>{this.events.dispatchEvent(new Event(`change`))},{wait:100});let e=j.dirname(this.path),t=j.basename(this.path);this.#o=N.watch(e,{persistent:!1,encoding:`utf8`},(e,n)=>{n&&n!==t||typeof this.#c==`function`&&this.#c()})}else this.#c??=debounceFunction(()=>{this.events.dispatchEvent(new Event(`change`))},{wait:1e3}),N.watchFile(this.path,{persistent:!1},(e,t)=>{typeof this.#c==`function`&&this.#c()}),this.#s=!0}_migrate(e,t,n){let r=this._get(Ds,`0.0.0`),i=Object.keys(e).filter(e=>this._shouldPerformMigration(e,r,t)),a=structuredClone(this.store);for(let s of i)try{n&&n(this,{fromVersion:r,toVersion:s,finalVersion:t,versions:i});let c=e[s];c?.(this),this._set(Ds,s),r=s,a=structuredClone(this.store)}catch(e){this.store=a;let t=e instanceof Error?e.message:String(e);throw Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${t}`)}(this._isVersionInRangeFormat(r)||!pa.default.eq(r,t))&&this._set(Ds,t)}_containsReservedKey(e){return typeof e==`string`?this._isReservedKeyPath(e):!e||typeof e!=`object`?!1:this._objectContainsReservedKey(e)}_objectContainsReservedKey(e){if(!e||typeof e!=`object`)return!1;for(let[t,n]of Object.entries(e))if(this._isReservedKeyPath(t)||this._objectContainsReservedKey(n))return!0;return!1}_isReservedKeyPath(e){return e===Es||e.startsWith(`${Es}.`)}_isVersionInRangeFormat(e){return pa.default.clean(e)===null}_shouldPerformMigration(e,t,n){return this._isVersionInRangeFormat(e)?t!==`0.0.0`&&pa.default.satisfies(t,e)?!1:pa.default.satisfies(n,e):!(pa.default.lte(e,t)||pa.default.gt(e,n))}_get(e,t){return getProperty(this.store,e,t)}_set(e,t){let{store:n}=this;setProperty(n,e,t),this.store=n}#l(e){let t={configName:`config`,fileExtension:`json`,projectSuffix:`nodejs`,clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(t.encryptionAlgorithm??=ws,!isSupportedEncryptionAlgorithm(t.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...Ts].join(`, `)}`);if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=envPaths(t.projectName,{suffix:t.projectSuffix}).config}return typeof t.fileExtension==`string`&&(t.fileExtension=t.fileExtension.replace(/^\.+/,``)),t}#u(e){if(!(e.schema??e.ajvOptions??e.rootSchema))return;if(e.schema&&typeof e.schema!=`object`)throw TypeError("The `schema` option must be an object.");let t=vs.default.default,n=new _s.Ajv2020({allErrors:!0,useDefaults:!0,...e.ajvOptions});t(n);let r={...e.rootSchema,type:`object`,properties:e.schema};this.#e=n.compile(r),this.#d(e.schema)}#d(e){let t=Object.entries(e??{});for(let[e,n]of t){if(!n||typeof n!=`object`||!Object.hasOwn(n,`default`))continue;let{default:t}=n;t!==void 0&&(this.#i[e]=t)}}#f(e){e.defaults&&Object.assign(this.#i,e.defaults)}#p(e){e.serialize&&(this._serialize=e.serialize),e.deserialize&&(this._deserialize=e.deserialize)}#m(e){let t=typeof e.fileExtension==`string`?e.fileExtension:void 0,n=t?`.${t}`:``;return j.resolve(e.cwd,`${e.configName??`config`}${n}`)}#h(e){if(e.migrations){this.#g(e),this._validate(this.store);return}let t=this.store,n=Object.assign(createPlainObject(),e.defaults??{},t);this._validate(n);try{qn.deepEqual(t,n)}catch{this.store=n}}#g(e){let{migrations:t,projectVersion:n}=e;if(t){if(!n)throw Error("Please specify the `projectVersion` option.");this.#a=!0;try{let r=this.store,i=Object.assign(createPlainObject(),e.defaults??{},r);try{qn.deepEqual(r,i)}catch{this._write(i)}this._migrate(t,n,e.beforeEachMigration)}finally{this.#a=!1}}}};const Os={name:ar,version:sr},ks=ot(()=>{try{return new Conf({projectName:ar,clearInvalidConfig:!0,watch:!1})}catch(e){Qr.debug(`Failed to create config store`,{error:e});return}}),As=`check-update`;async function notifyAvailableUpdate(){if(jn||Nn||Pn===As||isInsideContainer())return;let e=ks();if(!e)return;let t=e.get(`lastUpdateCheck`),n=e.get(`latestVersion`);if(Qe(n)||Qe(t)||t+864e5<Date.now()){try{pn(`likec4`,[`check-update`],{stdio:`ignore`,timeout:5e3,preferLocal:!0,detached:!0,env:{NODE_ENV:As}}).catch(()=>{})}catch{}return}n&&(0,pa.gt)(n,Os.version)&&boxen([`Update available: `,S.dim(Os.version),S.reset(` → `),S.green(n)].join(``))}async function checkAvailableUpdate(e=!0){try{let t=ks();t?.set({lastUpdateCheck:Date.now()});let n=await fetchLatestVersion();if(Qt(n,`No version found in latest npm`),t?.set({lastUpdateCheck:Date.now(),latestVersion:n}),(0,pa.gt)(n,Os.version)){boxen([`Update available: `,S.dim(Os.version),S.reset(` → `),S.green(n)].join(``));return}e&&boxen(S.dim(`Up to date: `)+` `+S.green(Os.version))}catch(e){Qr.warning(a(e))}}async function fetchLatestVersion(){return(await xi(`https://registry.npmjs.org/likec4/latest`,{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},timeout:5e3,keepalive:!0}).json()).version}function isInstalled(e){try{return!!jt.createRequire(import.meta.url).resolve(e)}catch(e){return Qr.debug(a(e)),!1}}async function ensureReact(){if(isInstalled(`react`)&&isInstalled(`react-dom`)){Qr.debug(`react already installed`);return}Qr.warn(`react not installed`);let e=await kt();e||(Qr.error`Package manager not detected, please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));let t=Ot(e.agent,`add`,[`react`,`react-dom`]);t||(Qr.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));try{await pn(t.command,t.args,{stdio:`inherit`})}catch(e){Qr.debug(a(e)),Qr.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1)}}async function ensurePlaywright(){if(isInstalled(`playwright`)){Qr.debug(`playwright already installed`);return}Qr.warn(`playwright not installed`);let e=await kt();e||(Qr.error`Package manager not detected, please install dependencies manually: ${`playwright`}`,process.exit(1));let t=Ot(e.agent,`add`,[`playwright`]);t||(Qr.error`Please install dependencies manually: ${`playwright`}`,process.exit(1));try{await pn(t.command,t.args,{preferLocal:!0,stdio:`inherit`})}catch(e){Qr.debug(a(e)),Qr.error`Please install dependencies manually: ${`playwright`}`,process.exit(1)}}const B={type:`string`,desc:`<directory> with LikeC4 sources (default is current directory or 'LIKEC4_WORKSPACE' env)`,normalize:!0,default:An.LIKEC4_WORKSPACE||`.`,coerce:M},js={alias:`use-dot-bin`,boolean:!0,type:`boolean`,desc:isInsideContainer()?`enabled in container, disable by --no-use-dot`:`use graphviz binaries ("dot" should be on PATH)`,default:isInsideContainer()},Ms={boolean:!0,type:`boolean`,desc:"use `@likec4/core` package in types",default:!1},Ns={boolean:!0,type:`boolean`,desc:`use hash history for navigation, e.g. "/#/view" instead of "/view"`},Ps={alias:[`o`,`output`],string:!0,desc:`output directory`,normalize:!0,nargs:1,coerce:M},Fs={alias:`w`,string:!0,desc:`prefix for Webcomponents, e.g "c4" generates <c4-view ../>`,default:`likec4`,nargs:1},Is={alias:`t`,string:!0,desc:`base title of the app pages (default is "LikeC4")`,default:`LikeC4`,nargs:1},Ls={choices:[`light`,`dark`],desc:`default color scheme for the built website (default: auto, follows system preference)`,nargs:1},Rs={alias:[`base-url`],string:!0,desc:`base url the app is being served from, e.g. "/" or "/pages/"`,nargs:1},zs={boolean:!0,desc:`outputs a single self-contained HTML file with all required resources inlined`},Bs={alias:`public-dir`,string:!0,desc:`directory whose files are copied to the output as-is (Vite publicDir, e.g. images linked from views)`,normalize:!0,nargs:1,coerce:M},Vs={array:!0,string:!0,desc:`hostname allowed to respond to (Vite server.allowedHosts); can be repeated. Defaults to allowing all hosts.`,requiresArg:!0},Hs={alias:`l`,string:!0,...isInsideContainer()?{desc:`listen 0.0.0.0 by default in container`,default:`0.0.0.0`}:{desc:`ip address of the network interface to listen on`},nargs:1},Us={number:!0,desc:`port number for the dev server (default is 5173, or PORT environment variable)`,nargs:1},Ws={number:!0,desc:`port number for the HMR WebSocket server (default is auto-discovered from 24678-24690, or HMR_PORT environment variable)`,nargs:1},Gs={alias:`p`,string:!0,desc:`select LikeC4 project by name (e.g. "my-project") or by path`,nargs:1},Ks={hidden:!0,nargs:1,desc:`force log level`,choices:[`trace`,`debug`,`info`,`warning`,`error`],conflicts:[`verbose`]},qs={boolean:!0,desc:`verbose logging`,conflicts:[`log-level`]},Js=Mn?`trace`:`debug`,Ys=6e4,Xs=Ys*60*24*7;function showSupportUsMessage(){if(!(jn||Nn))try{let e=Date.now(),t=ks();if(!t)return;let n=t.get(`lastSupportUsMessage`);if(!n){t.set(`lastSupportUsMessage`,e-Xs+5*Ys);return}if(n+Xs>e)return;t.set(`lastSupportUsMessage`,e),boxen([S.dim(`If you are working in a commercial environment`),S.dim(`consider supporting the project`),``,S.dim(`How to get more?`)+` `+S.underline(`https://likec4.dev/sponsor/`)].join(`
174
- `))}catch{}}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const buildCmd=e=>e.command({command:`build [path]`,aliases:[`bundle`],describe:`Build a static website`,builder:e=>e.positional(`path`,B).option(`output`,{alias:`o`,type:`string`,desc:`output directory for production build`,normalize:!0,coerce:M}).option(`base`,Rs).option(`use-hash-history`,Ns).option(`use-dot`,js).option(`webcomponent-prefix`,Fs).option(`build-webcomponent`,{type:`boolean`,default:!0,describe:`enable/disable webcomponent build`}).option(`title`,Is).option(`output-single-file`,zs).option(`public`,Bs).option(`theme`,Ls).example(`${S.green(`$0 build -o ./build ./src`)}`,S.gray(`Search for likec4 files in 'src' and output static site to 'build'`)).example(`${S.green(`$0 build --theme dark -o ./build ./src`)}`,S.gray(`Build with dark color scheme as default`)).example(`${S.green(`$0 build --public ./assets -o ./build ./src`)}`,S.gray(`Copy files from 'assets' to the output directory as-is`)),handler:async e=>{try{var t=_usingCtx();let n={useHashHistory:e[`use-hash-history`]??!1,useDotBin:e[`use-dot`],webcomponentPrefix:e[`webcomponent-prefix`],buildWebcomponent:e[`build-webcomponent`],outputSingleFile:e[`output-single-file`]??!1};await notifyAvailableUpdate(),await ensureReact();let r=createLikeC4Logger(`c4:build`),i=t.a(await x(e.path,{graphviz:e[`use-dot`]?`binary`:`wasm`,watch:!1})),a=e.output??M(i.workspace,`dist`),s=M(a,`assets`);await viteBuild({base:e.base,useHashHistory:n.outputSingleFile||n.useHashHistory,customLogger:r,webcomponentPrefix:n.webcomponentPrefix,buildWebcomponent:n.buildWebcomponent,title:e.title,theme:e.theme,languageServices:i,likec4AssetsDir:s,outputDir:a,outputSingleFile:n.outputSingleFile,userPublicDir:e.public}),showSupportUsMessage()}catch(e){t.e=e}finally{await t.d()}}}),checkUpdateCmd=e=>e.command({command:`check-update`,describe:`Check for updates`,handler:async()=>{await checkAvailableUpdate()}});function ensureProjectId(e,t){if(!t)return e.languageServices.projectsManager.ensureProjectId();let n=M(t);if(n===e.workspace)return e.languageServices.projectsManager.ensureProjectId();if(_n(n)&&Sn(n).isDirectory()){Qr.debug`Project path exists: ${n}`;let t=ce.file(n.endsWith(Xt)?n:n+Xt),r=e.languageServices.projects().find(e=>e.folder.fsPath===t.fsPath);if(r)return Qr.debug`Found project ${r.id} at path: ${n}`,r.id;Qr.debug`No project registered at path: ${n}`}return e.languageServices.projectsManager.ensureProjectId(t)}function ensureProject(e,t){let n=ensureProjectId(e,t),r=e.languageServices.projectsManager.getProject(n);return e.languageServices.projectsManager.defaultProjectId=n,{projectId:n,projectFolder:r.folderUri.fsPath,config:r.config}}const Zs=Qr.getChild(`generator`);async function customHandler({name:e,path:t,useDotBin:n,project:r}){try{var i=_usingCtx();let a=startTimer(Zs),s=i.a(await x(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:c,config:l}=ensureProject(s,r);r&&Zs.info(`${S.dim(`project`)} ${S.green(c)}`);let u=l.generators?.[e];if(!u)throw Zs.error(S.red(`generator ${e} does not exist in project config`)),Error(`generator ${e} does not exist in project config`);Zs.info(`${S.dim(`generator`)} ${S.green(e)}`),await runCustomGenerator({likec4:s,model:await s.layoutedModel(c),generator:u,logger:Zs.getChild(e)}),a.stopAndLog()}catch(e){i.e=e}finally{await i.d()}}async function runCustomGenerator({likec4:e,model:t,generator:n,logger:r}){let i=e.languageServices,a=new Set,s=i.project(t.project.id),c=t.project.id;r.debug(`${S.dim(`running for project:`)} ${S.green(s.id)}`),await Promise.resolve().then(()=>n({likec4model:t,ctx:{workspace:e.languageServices.workspaceUri,project:s,locate:e=>{let t=null;switch(!0){case ln(e):t=i.locate({element:e.id,projectId:c});break;case un(e):t=i.locate({view:e.id,projectId:c});break;case on(e):t=i.locate({deployment:e.id,projectId:c});break;case dn(e):case cn(e):t=i.locate({relation:e.id,projectId:c});break;default:$t(e)}if(!t)throw r.error(`Cannot locate ${e.id}`,{target:e}),Error(`Cannot locate ${e.id}`);let n=ce.parse(t.uri);return{range:t.range,document:n,relativePath:le.relative(s.folder,n),folder:le.dirname(n).fsPath,filename:le.basename(n)}},write:async({path:e,content:t})=>{let n;n=Array.isArray(e)?M(s.folder.fsPath,...e):ce.isUri(e)?e.fsPath:M(s.folder.fsPath,`${e}`);let i=Gt(n);a.has(i)||(_n(i)||(r.debug(`${S.dim(`create directory`)} ${i}`),await It(i,{recursive:!0})),a.add(i)),r.debug(`${S.dim(`write`)} ${n}`),await Ut(n,t)},abort:e=>{throw r.error(e||`Generator aborted`),Error(e||`Generator aborted`)}}}))}function relativeOutputDir(e){if(!e)return`.`;let t=e.split(/[\\/]+/);t.pop();let n=[];for(let e of t){let t=e.replace(/^[a-zA-Z]:/,``);switch(t){case``:case`.`:break;case`..`:n.pop();break;default:n.push(t)}}return n.length>0?Jt(...n):`.`}async function singleFileCodegenAction(e,t,n){t??=M(e.workspace,`likec4.generated.ts`),Kt(t)!==`.ts`&&(t+=`.ts`),await It(Gt(t),{recursive:!0});let r=generateViewsDataTs([...await e.diagrams()]);await Ut(t,r),n.info(`${S.dim(`generated`)} ${Yt(process.cwd(),t)}`)}async function dotCodegenAction(e,t,n){await It(t,{recursive:!0}),n.info(`${S.dim(`format`)} ${S.green(`dot`)}`),n.info(`${S.dim(`outdir`)} ${t}`);let r=new Set,i=await e.computedModel(),a=dt(i.$data.views),s=0;for(let c of a)try{let a=await e.viewsService.layouter.dot({view:c,styles:i.$styles}),l=M(t,relativeOutputDir(c.sourcePath));r.has(l)||(await It(l,{recursive:!0}),r.add(l));let u=M(l,c.id+`.dot`);await Ut(u,a),n.info(`${S.dim(`generated`)} ${Yt(process.cwd(),u)}`),s++}catch(e){Qr.error(`error while generating ${c.id}`,{error:e})}s>0&&n.info(`${S.dim(`total`)} ${s} files`)}async function multipleFilesCodegenAction(e,t,n,r){await It(n,{recursive:!0}),r.info(`${S.dim(`format`)} ${S.green(t)}`),r.info(`${S.dim(`outdir`)} ${n}`);let i,a;switch(t){case`d2`:i=`.d2`,a=bt;break;case`mermaid`:i=`.mmd`,a=Tt;break;case`plantuml`:i=`.puml`,a=Ct;break;default:$t(t)}let s=new Set,c=await e.layoutedModel(),l=0;for(let e of c.views()){let t=e.$view;try{let c=M(n,relativeOutputDir(t.sourcePath));s.has(c)||(await It(c,{recursive:!0}),s.add(c));let u=M(c,t.id+i),f=a(e);await Ut(u,f),r.info(`${S.dim(`generated`)} ${Yt(process.cwd(),u)}`),l++}catch(e){r.error(`error while generating ${t.id}`,{error:e})}}l>0&&r.info(`${S.dim(`total`)} ${l} files`)}async function legacyHandler({path:e,useDotBin:t,...n}){let r=createLikeC4Logger(`c4:codegen`),i=startTimer(r),a=await x(e,{graphviz:t?`binary`:`wasm`,watch:!1});if(a.ensureSingleProject(),(await a.viewsService.computedViews()).length===0)throw r.warn(`no views found`),process.exitCode=1,Error(`no views found`);switch(n.format){case`views`:await singleFileCodegenAction(a,n.outfile,r);break;case`dot`:await dotCodegenAction(a,n.outdir??e,r);break;case`d2`:case`mermaid`:case`plantuml`:await multipleFilesCodegenAction(a,n.format,n.outdir??e,r);break;default:$t(n)}i.stopAndLog()}const Qs=Gt(On(import.meta.url));function readVersion(){try{let e=JSON.parse(vn(Jt(Qs,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}try{let e=JSON.parse(vn(Jt(Qs,`..`,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}return`0.1.0`}const $s=readVersion(),ec=`leanix`,tc=new Set([`factSheetTypes`,`relationTypes`,`metadataToFields`]);function isPlainObjectRecordOfStrings(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e))if(typeof t!=`string`)return!1;return!0}function parseLeanixMappingInput(e){if(e==null)return e;if(typeof e!=`object`||Array.isArray(e))throw Error(`LeanIX mapping must be a plain object (not an array or primitive)`);let t=e;for(let e of Object.keys(t))if(!tc.has(e))throw Error(`LeanIX mapping has unknown key "${e}". Allowed: factSheetTypes, relationTypes, metadataToFields`);if(t.factSheetTypes!==void 0&&!isPlainObjectRecordOfStrings(t.factSheetTypes))throw Error(`LeanIX mapping "factSheetTypes" must be an object with string keys and string values`);if(t.relationTypes!==void 0&&!isPlainObjectRecordOfStrings(t.relationTypes))throw Error(`LeanIX mapping "relationTypes" must be an object with string keys and string values`);if(t.metadataToFields!==void 0&&!isPlainObjectRecordOfStrings(t.metadataToFields))throw Error(`LeanIX mapping "metadataToFields" must be an object with string keys and string values`);return e}const nc={factSheetTypes:{system:`Application`,container:`ITComponent`,component:`ITComponent`,actor:`Provider`},relationTypes:{default:`depends on`},metadataToFields:{title:`name`,description:`description`,technology:`technology`}};function mergeWithDefault(e){let t=parseLeanixMappingInput(e),n={factSheetTypes:{...nc.factSheetTypes},relationTypes:{...nc.relationTypes},metadataToFields:{...nc.metadataToFields}};return t?{factSheetTypes:{...n.factSheetTypes,...t.factSheetTypes},relationTypes:{...n.relationTypes,...t.relationTypes},metadataToFields:{...n.metadataToFields,...t.metadataToFields}}:n}function getFactSheetType(e,t){return t.factSheetTypes[e]??t.factSheetTypes.default??`Application`}function getRelationType(e,t){let n=e??`default`;return t.relationTypes[n]??t.relationTypes.default??`depends on`}const rc={manifestVersion:`1.0`,bridgeVersion:$s,mappingProfile:`default`};function buildManifestEntities(e){let t={};for(let n of e.elements())t[n.id]={canonicalId:n.id,external:{}};return t}function buildManifestViews(e){let t={};for(let n of e.views())t[n.id]={viewId:n.id,external:{}};return t}function buildManifestRelations(e){let t=[];for(let n of e.relationships())t.push({relationId:n.id,sourceFqn:n.source.id,targetFqn:n.target.id,compositeKey:`${n.source.id}|${n.target.id}|${n.id}`,external:{}});return t}function toBridgeManifest(e,t={}){let n={...rc,...t,generatedAt:t.generatedAt??new Date().toISOString()};return{manifestVersion:n.manifestVersion,generatedAt:n.generatedAt,bridgeVersion:n.bridgeVersion,mappingProfile:n.mappingProfile,projectId:e.projectId,entities:buildManifestEntities(e),views:buildManifestViews(e),relations:buildManifestRelations(e)}}function buildFactSheetsFromModel(e,t){let n=[];for(let r of e.elements()){let e=getFactSheetType(r.kind,t),i=r.getMetadata(),a=typeof i.description==`string`?i.description:void 0,s=r.technology??(typeof i.technology==`string`?i.technology:void 0);n.push({type:e,likec4Id:r.id,name:r.title,...a!==void 0&&{description:a},...s!==void 0&&{technology:s},...r.tags.length>0&&{tags:[...r.tags]},...Object.keys(i).length>0&&{metadata:{...i}}})}return n.sort((e,t)=>e.likec4Id.localeCompare(t.likec4Id)),n}function buildRelationsFromModel(e,t){let n=[];for(let r of e.relationships()){let e=r.title??r.kind;n.push({type:getRelationType(r.kind,t),likec4RelationId:r.id,sourceLikec4Id:r.source.id,targetLikec4Id:r.target.id,...e!=null&&e!==``&&{title:String(e)}})}return n.sort((e,t)=>e.likec4RelationId.localeCompare(t.likec4RelationId)),n}function toLeanixInventoryDryRun(e,t={}){let n=mergeWithDefault(t.mapping),r=t.generatedAt??new Date().toISOString(),i=t.mappingProfile??(t.mapping?`custom`:`default`);return{generatedAt:r,projectId:e.projectId,mappingProfile:i,factSheets:buildFactSheetsFromModel(e,n),relations:buildRelationsFromModel(e,n)}}function buildCoherenceErrorMessage(e,t){let n=[];return e.projectId!==t.projectId&&n.push(`projectId (manifest: ${e.projectId}, leanixDryRun: ${t.projectId})`),e.mappingProfile!==t.mappingProfile&&n.push(`mappingProfile (manifest: ${e.mappingProfile}, leanixDryRun: ${t.mappingProfile})`),`Manifest and LeanIX dry-run must belong to the same run. Mismatch: ${n.join(`; `)}`}function buildBridgeReport(e,t){if(e.projectId!==t.projectId||e.mappingProfile!==t.mappingProfile)throw Error(buildCoherenceErrorMessage(e,t));return{generatedAt:e.generatedAt,projectId:e.projectId,manifestVersion:e.manifestVersion,bridgeVersion:e.bridgeVersion,mappingProfile:e.mappingProfile,counts:{entities:Object.keys(e.entities).length,views:Object.keys(e.views).length,relations:e.relations.length,factSheets:t.factSheets.length,leanixRelations:t.relations.length},artifacts:{manifest:`manifest.json`,leanixDryRun:`leanix-dry-run.json`}}}var LeanixApiError=class extends Error{statusCode;graphqlErrors;constructor(e,t,n){super(e),this.statusCode=t,this.graphqlErrors=n,this.name=`LeanixApiError`}};function sleep(e){return new Promise(t=>setTimeout(t,e))}var LeanixApiClient=class{baseUrl;apiToken;requestDelayMs;lastRequestTime=0;rateLimitLock=Promise.resolve();constructor(e){this.apiToken=e.apiToken,this.baseUrl=(e.baseUrl??`https://app.leanix.net`).replace(/\/$/,``),this.requestDelayMs=e.requestDelayMs??200}async graphql(e,t){let run=async()=>{let n=Date.now()-this.lastRequestTime;n<this.requestDelayMs&&await sleep(this.requestDelayMs-n),this.lastRequestTime=Date.now();let r=`${this.baseUrl}/services/pathfinder/v1/graphql`,i;try{i=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiToken}`},body:JSON.stringify({query:e,variables:t})})}catch(e){throw new LeanixApiError(`GraphQL request failed: ${r} POST - ${e instanceof Error?e.message:String(e)}`)}let a;try{a=await i.json()}catch(e){let t=e instanceof Error?e.message:String(e);throw new LeanixApiError(`Invalid JSON response: ${r} ${i.status} ${i.statusText} - ${t}`,i.status)}if(!i.ok)throw new LeanixApiError(a.errors?.[0]?.message??`HTTP ${i.status} ${i.statusText}`,i.status,a.errors);if(a.errors&&a.errors.length>0)throw new LeanixApiError(a.errors.map(e=>e.message).join(`; `),i.status,a.errors);if(a.data===void 0)throw new LeanixApiError(`GraphQL response had no data and no errors`);return a.data},n=this.rateLimitLock,r;this.rateLimitLock=new Promise(e=>{r=e}),await n;try{return await run()}finally{r()}}};async function findFactSheetByNameAndType(e,t,n){let r=(await e.graphql(`
173
+ deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=splitDependencies(e);validatePropertyDeps(e,t),validateSchemaDeps(e,n)}};function splitDependencies({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function validatePropertyDeps(e,n=e.schema){let{gen:i,data:a,it:s}=e;if(Object.keys(n).length===0)return;let c=i.let(`missing`);for(let l in n){let u=n[l];if(u.length===0)continue;let f=(0,r.propertyInData)(i,a,l,s.opts.ownProperties);e.setParams({property:l,depsCount:u.length,deps:u.join(`, `)}),s.allErrors?i.if(f,()=>{for(let t of u)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${f} && (${(0,r.checkMissingProp)(e,u,c)})`),(0,r.reportMissingProp)(e,c),i.else())}}e.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(e,t=e.schema){let{gen:i,data:a,keyword:s,it:c}=e,l=i.name(`valid`);for(let u in t)(0,n.alwaysValidSchema)(c,t[u])||(i.if((0,r.propertyInData)(i,a,u,c.opts.ownProperties),()=>{let t=e.subschema({keyword:s,schemaProp:u},l);e.mergeValidEvaluated(t,l)},()=>i.var(l,!0)),e.ok(l))}e.validateSchemaDeps=validateSchemaDeps,e.default=i})),Eo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H();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:r,schema:i,data:a,it:s}=e;if((0,n.alwaysValidSchema)(s,i))return;let c=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},c),r.if((0,t.not)(c),()=>{e.error(!0),s.allErrors||r.break()})}),e.ok(c)}}})),Do=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=V(),r=Pa(),i=H();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:s,parentSchema:c,data:l,errsCount:u,it:f}=e;if(!u)throw Error(`ajv implementation error`);let{allErrors:p,opts:m}=f;if(f.props=!0,m.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(f,s))return;let h=(0,t.allSchemaProperties)(c.properties),g=(0,t.allSchemaProperties)(c.patternProperties);checkAdditionalProperties(),e.ok((0,n._)`${u} === ${r.default.errors}`);function checkAdditionalProperties(){a.forIn(`key`,l,e=>{!h.length&&!g.length?additionalPropertyCode(e):a.if(isAdditional(e),()=>additionalPropertyCode(e))})}function isAdditional(r){let s;if(h.length>8){let e=(0,i.schemaRefOrVal)(f,c.properties,`properties`);s=(0,t.isOwnProperty)(a,e,r)}else s=h.length?(0,n.or)(...h.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return g.length&&(s=(0,n.or)(s,...g.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(s)}function deleteAdditional(e){a.code((0,n._)`delete ${l}[${e}]`)}function additionalPropertyCode(t){if(m.removeAdditional===`all`||m.removeAdditional&&s===!1){deleteAdditional(t);return}if(s===!1){e.setParams({additionalProperty:t}),e.error(),p||a.break();return}if(typeof s==`object`&&!(0,i.alwaysValidSchema)(f,s)){let r=a.name(`valid`);m.removeAdditional===`failing`?(applyAdditionalSchema(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),deleteAdditional(t)})):(applyAdditionalSchema(t,r),p||a.if((0,n.not)(r),()=>a.break()))}}function applyAdditionalSchema(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Oo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qa(),n=Va(),r=H(),i=Do();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:s,parentSchema:c,data:l,it:u}=e;u.opts.removeAdditional===`all`&&c.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(u,i.default,`additionalProperties`));let f=(0,n.allSchemaProperties)(s);for(let e of f)u.definedProperties.add(e);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),u.props));let p=f.filter(e=>!(0,r.alwaysValidSchema)(u,s[e]));if(p.length===0)return;let m=a.name(`valid`);for(let t of p)hasDefault(t)?applyPropertySchema(t):(a.if((0,n.propertyInData)(a,l,t,u.opts.ownProperties)),applyPropertySchema(t),u.allErrors||a.else().var(m,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(m);function hasDefault(e){return u.opts.useDefaults&&!u.compositeRule&&s[e].default!==void 0}function applyPropertySchema(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},m)}}}})),ko=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Va(),n=V(),r=H(),i=H();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:s,data:c,parentSchema:l,it:u}=e,{opts:f}=u,p=(0,t.allSchemaProperties)(s),m=p.filter(e=>(0,r.alwaysValidSchema)(u,s[e]));if(p.length===0||m.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;let h=f.strictSchema&&!f.allowMatchingProperties&&l.properties,g=a.name(`valid`);u.props!==!0&&!(u.props instanceof n.Name)&&(u.props=(0,i.evaluatedPropsToName)(a,u.props));let{props:v}=u;validatePatternProperties();function validatePatternProperties(){for(let e of p)h&&checkMatchingProperties(e),u.allErrors?validateProperties(e):(a.var(g,!0),validateProperties(e),a.if(g))}function checkMatchingProperties(e){for(let t in h)new RegExp(e).test(t)&&(0,r.checkStrictMode)(u,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function validateProperties(r){a.forIn(`key`,c,s=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${s})`,()=>{let t=m.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:s,dataPropType:i.Type.Str},g),u.opts.unevaluated&&v!==!0?a.assign((0,n._)`${v}[${s}]`,!0):!t&&!u.allErrors&&a.if((0,n.not)(g),()=>a.break())})})}}}})),Ao=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),jo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Va().validateUnion,error:{message:`must match a schema in anyOf`}}})),Mo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H();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:r,schema:i,parentSchema:a,it:s}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(s.opts.discriminator&&a.discriminator)return;let c=i,l=r.let(`valid`,!1),u=r.let(`passing`,null),f=r.name(`_valid`);e.setParams({passing:u}),r.block(validateOneOf),e.result(l,()=>e.reset(),()=>e.error(!0));function validateOneOf(){c.forEach((i,a)=>{let c;(0,n.alwaysValidSchema)(s,i)?r.var(f,!0):c=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},f),a>0&&r.if((0,t._)`${f} && ${l}`).assign(l,!1).assign(u,(0,t._)`[${u}, ${a}]`).else(),r.if(f,()=>{r.assign(l,!0),r.assign(u,a),c&&e.mergeEvaluated(c,t.Name)})})}}}})),No=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let s=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(s)})}}})),Po=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r={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:r,parentSchema:i,it:a}=e;i.then===void 0&&i.else===void 0&&(0,n.checkStrictMode)(a,`"if" without "then" and "else" is ignored`);let s=hasSchema(a,`then`),c=hasSchema(a,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(validateIf(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,validateClause(`then`,t),validateClause(`else`,t))}else s?r.if(u,validateClause(`then`)):r.if((0,t.not)(u),validateClause(`else`));e.pass(l,()=>e.error(!0));function validateIf(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function validateClause(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function hasSchema(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Fo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Io=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bo(),n=So(),r=xo(),i=Co(),a=wo(),s=To(),c=Eo(),l=Do(),u=Oo(),f=ko(),p=Ao(),m=jo(),h=Mo(),g=No(),v=Po(),y=Fo();function getApplicator(e=!1){let b=[p.default,m.default,h.default,g.default,v.default,y.default,c.default,l.default,s.default,u.default,f.default];return e?b.push(n.default,i.default):b.push(t.default,r.default),b.push(a.default),b}e.default=getApplicator})),Lo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=V(),n=Pa(),r=Xa(),i=io(),a={keyword:`$dynamicAnchor`,schemaType:`string`,code:e=>dynamicAnchor(e,e.schema)};function dynamicAnchor(e,r){let{gen:i,it:a}=e;a.schemaEnv.root.dynamicAnchors[r]=!0;let s=(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(r)}`,c=a.errSchemaPath===`#`?a.validateName:_getValidate(e);i.if((0,t._)`!${s}`,()=>i.assign(s,c))}e.dynamicAnchor=dynamicAnchor;function _getValidate(e){let{schemaEnv:t,schema:n,self:a}=e.it,{root:s,baseId:c,localRefs:l,meta:u}=t.root,{schemaId:f}=a.opts,p=new r.SchemaEnv({schema:n,schemaId:f,root:s,baseId:c,localRefs:l,meta:u});return r.compileSchema.call(a,p),(0,i.getValidate)(e,p)}e.default=a})),Ro=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=V(),n=Pa(),r=io(),i={keyword:`$dynamicRef`,schemaType:`string`,code:e=>dynamicRef(e,e.schema)};function dynamicRef(e,i){let{gen:a,keyword:s,it:c}=e;if(i[0]!==`#`)throw Error(`"${s}" only supports hash fragment reference`);let l=i.slice(1);if(c.allErrors)_dynamicRef();else{let t=a.let(`valid`,!1);_dynamicRef(t),e.ok(t)}function _dynamicRef(e){if(c.schemaEnv.root.dynamicAnchors[l]){let r=a.let(`_v`,(0,t._)`${n.default.dynamicAnchors}${(0,t.getProperty)(l)}`);a.if(r,_callRef(r,e),_callRef(c.validateName,e))}else _callRef(c.validateName,e)()}function _callRef(t,n){return n?()=>a.block(()=>{(0,r.callRef)(e,t),a.let(n,!0)}):()=>(0,r.callRef)(e,t)}}e.dynamicRef=dynamicRef,e.default=i})),zo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Lo(),n=H();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),Bo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ro();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),Vo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Lo(),n=Ro(),r=zo(),i=Bo();e.default=[t.default,n.default,r.default,i.default]})),Ho=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=To();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),Uo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=To();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),Wo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();e.default={keyword:[`maxContains`,`minContains`],type:`array`,schemaType:`number`,code({keyword:e,parentSchema:n,it:r}){n.contains===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}}})),Go=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ho(),n=Uo(),r=Wo();e.default=[t.default,n.default,r.default]})),Ko=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H(),r=Pa();e.default={keyword:`unevaluatedProperties`,type:`object`,schemaType:[`boolean`,`object`],trackErrors:!0,error:{message:`must NOT have unevaluated properties`,params:({params:e})=>(0,t._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){let{gen:i,schema:a,data:s,errsCount:c,it:l}=e;if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f instanceof t.Name?i.if((0,t._)`${f} !== true`,()=>i.forIn(`key`,s,e=>i.if(unevaluatedDynamic(f,e),()=>unevaluatedPropCode(e)))):f!==!0&&i.forIn(`key`,s,e=>f===void 0?unevaluatedPropCode(e):i.if(unevaluatedStatic(f,e),()=>unevaluatedPropCode(e))),l.props=!0,e.ok((0,t._)`${c} === ${r.default.errors}`);function unevaluatedPropCode(r){if(a===!1){e.setParams({unevaluatedProperty:r}),e.error(),u||i.break();return}if(!(0,n.alwaysValidSchema)(l,a)){let a=i.name(`valid`);e.subschema({keyword:`unevaluatedProperties`,dataProp:r,dataPropType:n.Type.Str},a),u||i.if((0,t.not)(a),()=>i.break())}}function unevaluatedDynamic(e,n){return(0,t._)`!${e} || !${e}[${n}]`}function unevaluatedStatic(e,n){let r=[];for(let i in e)e[i]===!0&&r.push((0,t._)`${n} !== ${i}`);return(0,t.and)(...r)}}}})),qo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=H();e.default={keyword:`unevaluatedItems`,type:`array`,schemaType:[`boolean`,`object`],error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{gen:r,schema:i,data:a,it:s}=e,c=s.items||0;if(c===!0)return;let l=r.const(`len`,(0,t._)`${a}.length`);if(i===!1)e.setParams({len:c}),e.fail((0,t._)`${l} > ${c}`);else if(typeof i==`object`&&!(0,n.alwaysValidSchema)(s,i)){let n=r.var(`valid`,(0,t._)`${l} <= ${c}`);r.if((0,t.not)(n),()=>validateItems(n,c)),e.ok(n)}s.items=!0;function validateItems(i,a){r.forRange(`i`,a,l,a=>{e.subschema({keyword:`unevaluatedItems`,dataProp:a,dataPropType:n.Type.Num},i),s.allErrors||r.if((0,t.not)(i),()=>r.break())})}}}})),Jo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ko(),n=qo();e.default=[t.default,n.default]})),Yo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V();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,n){let{gen:r,data:i,$data:a,schema:s,schemaCode:c,it:l}=e,{opts:u,errSchemaPath:f,schemaEnv:p,self:m}=l;if(!u.validateFormats)return;a?validate$DataFormat():validateFormat();function validate$DataFormat(){let a=r.scopeValue(`formats`,{ref:m.formats,code:u.code.formats}),s=r.const(`fDef`,(0,t._)`${a}[${c}]`),l=r.let(`fType`),f=r.let(`format`);r.if((0,t._)`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(l,(0,t._)`${s}.type || "string"`).assign(f,(0,t._)`${s}.validate`),()=>r.assign(l,(0,t._)`"string"`).assign(f,s)),e.fail$data((0,t.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return u.strictSchema===!1?t.nil:(0,t._)`${c} && !${f}`}function invalidFmt(){let e=p.$async?(0,t._)`(${s}.async ? await ${f}(${i}) : ${f}(${i}))`:(0,t._)`${f}(${i})`,r=(0,t._)`(typeof ${f} == "function" ? ${e} : ${f}.test(${i}))`;return(0,t._)`${f} && ${f} !== true && ${l} === ${n} && !${r}`}}function validateFormat(){let a=m.formats[s];if(!a){unknownFormat();return}if(a===!0)return;let[c,l,h]=getFormat(a);c===n&&e.pass(validCondition());function unknownFormat(){if(u.strictSchema===!1){m.logger.warn(unknownMsg());return}throw Error(unknownMsg());function unknownMsg(){return`unknown format "${s}" ignored in schema at path "${f}"`}}function getFormat(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):u.code.formats?(0,t._)`${u.code.formats}${(0,t.getProperty)(s)}`:void 0,i=r.scopeValue(`formats`,{key:s,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function validCondition(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!p.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${h}(${i})`}return typeof l==`function`?(0,t._)`${h}(${i})`:(0,t._)`${h}.test(${i})`}}}}})),Xo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Yo().default]})),Zo=r((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`]})),Qo=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ao(),n=yo(),r=Io(),i=Vo(),a=Go(),s=Jo(),c=Xo(),l=Zo();e.default=[i.default,t.default,n.default,(0,r.default)(!0),c.default,l.metadataVocabulary,l.contentVocabulary,a.default,s.default]})),$o=r((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={}))})),es=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=V(),n=$o(),r=Xa(),i=Ya(),a=H();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:s,data:c,schema:l,parentSchema:u,it:f}=e,{oneOf:p}=u;if(!f.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let m=l.propertyName;if(typeof m!=`string`)throw Error(`discriminator: requires propertyName`);if(l.mapping)throw Error(`discriminator: mapping is not supported`);if(!p)throw Error(`discriminator: requires oneOf keyword`);let h=s.let(`valid`,!1),g=s.const(`tag`,(0,t._)`${c}${(0,t.getProperty)(m)}`);s.if((0,t._)`typeof ${g} == "string"`,()=>validateMapping(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:g,tagName:m})),e.ok(h);function validateMapping(){let r=getMapping();s.if(!1);for(let e in r)s.elseIf((0,t._)`${g} === ${e}`),s.assign(h,applyTagSchema(r[e]));s.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:g,tagName:m}),s.endIf()}function applyTagSchema(n){let r=s.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function getMapping(){let e={},t=hasRequired(u),n=!0;for(let e=0;e<p.length;e++){let s=p[e];if(s?.$ref&&!(0,a.schemaHasRulesButRef)(s,f.self.RULES)){let e=s.$ref;if(s=r.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,e),s instanceof r.SchemaEnv&&(s=s.schema),s===void 0)throw new i.default(f.opts.uriResolver,f.baseId,e)}let c=s?.properties?.[m];if(typeof c!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);n&&=t||hasRequired(s),addMappings(c,e)}if(!n)throw Error(`discriminator: "${m}" must be required`);return e;function hasRequired({required:e}){return Array.isArray(e)&&e.includes(m)}function addMappings(e,t){if(e.const)addMapping(e.const,t);else if(e.enum)for(let n of e.enum)addMapping(n,t);else throw Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function addMapping(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${m}" values must be unique strings`);e[t]=n}}}}})),ts=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/schema`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Core and Validation specifications meta-schema`,allOf:[{$ref:`meta/core`},{$ref:`meta/applicator`},{$ref:`meta/unevaluated`},{$ref:`meta/validation`},{$ref:`meta/meta-data`},{$ref:`meta/format-annotation`},{$ref:`meta/content`}],type:[`object`,`boolean`],$comment:`This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.`,properties:{definitions:{$comment:`"definitions" has been replaced by "$defs".`,type:`object`,additionalProperties:{$dynamicRef:`#meta`},deprecated:!0,default:{}},dependencies:{$comment:`"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.`,type:`object`,additionalProperties:{anyOf:[{$dynamicRef:`#meta`},{$ref:`meta/validation#/$defs/stringArray`}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:`"$recursiveAnchor" has been replaced by "$dynamicAnchor".`,$ref:`meta/core#/$defs/anchorString`,deprecated:!0},$recursiveRef:{$comment:`"$recursiveRef" has been replaced by "$dynamicRef".`,$ref:`meta/core#/$defs/uriReferenceString`,deprecated:!0}}}})),ns=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/applicator`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:`meta`,title:`Applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{prefixItems:{$ref:`#/$defs/schemaArray`},items:{$dynamicRef:`#meta`},contains:{$dynamicRef:`#meta`},additionalProperties:{$dynamicRef:`#meta`},properties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},patternProperties:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},propertyNames:{format:`regex`},default:{}},dependentSchemas:{type:`object`,additionalProperties:{$dynamicRef:`#meta`},default:{}},propertyNames:{$dynamicRef:`#meta`},if:{$dynamicRef:`#meta`},then:{$dynamicRef:`#meta`},else:{$dynamicRef:`#meta`},allOf:{$ref:`#/$defs/schemaArray`},anyOf:{$ref:`#/$defs/schemaArray`},oneOf:{$ref:`#/$defs/schemaArray`},not:{$dynamicRef:`#meta`}},$defs:{schemaArray:{type:`array`,minItems:1,items:{$dynamicRef:`#meta`}}}}})),rs=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/unevaluated`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:`meta`,title:`Unevaluated applicator vocabulary meta-schema`,type:[`object`,`boolean`],properties:{unevaluatedItems:{$dynamicRef:`#meta`},unevaluatedProperties:{$dynamicRef:`#meta`}}}})),is=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/content`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:`meta`,title:`Content vocabulary meta-schema`,type:[`object`,`boolean`],properties:{contentEncoding:{type:`string`},contentMediaType:{type:`string`},contentSchema:{$dynamicRef:`#meta`}}}})),as=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/core`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:`meta`,title:`Core vocabulary meta-schema`,type:[`object`,`boolean`],properties:{$id:{$ref:`#/$defs/uriReferenceString`,$comment:`Non-empty fragments not allowed.`,pattern:`^[^#]*#?$`},$schema:{$ref:`#/$defs/uriString`},$ref:{$ref:`#/$defs/uriReferenceString`},$anchor:{$ref:`#/$defs/anchorString`},$dynamicRef:{$ref:`#/$defs/uriReferenceString`},$dynamicAnchor:{$ref:`#/$defs/anchorString`},$vocabulary:{type:`object`,propertyNames:{$ref:`#/$defs/uriString`},additionalProperties:{type:`boolean`}},$comment:{type:`string`},$defs:{type:`object`,additionalProperties:{$dynamicRef:`#meta`}}},$defs:{anchorString:{type:`string`,pattern:`^[A-Za-z_][-A-Za-z0-9._]*$`},uriString:{type:`string`,format:`uri`},uriReferenceString:{type:`string`,format:`uri-reference`}}}})),os=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/format-annotation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:`meta`,title:`Format vocabulary meta-schema for annotation results`,type:[`object`,`boolean`],properties:{format:{type:`string`}}}})),ss=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/meta-data`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:`meta`,title:`Meta-data vocabulary meta-schema`,type:[`object`,`boolean`],properties:{title:{type:`string`},description:{type:`string`},default:!0,deprecated:{type:`boolean`,default:!1},readOnly:{type:`boolean`,default:!1},writeOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0}}}})),cs=r(((e,t)=>{t.exports={$schema:`https://json-schema.org/draft/2020-12/schema`,$id:`https://json-schema.org/draft/2020-12/meta/validation`,$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:`meta`,title:`Validation vocabulary meta-schema`,type:[`object`,`boolean`],properties:{type:{anyOf:[{$ref:`#/$defs/simpleTypes`},{type:`array`,items:{$ref:`#/$defs/simpleTypes`},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/$defs/nonNegativeInteger`},minLength:{$ref:`#/$defs/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},maxItems:{$ref:`#/$defs/nonNegativeInteger`},minItems:{$ref:`#/$defs/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},maxContains:{$ref:`#/$defs/nonNegativeInteger`},minContains:{$ref:`#/$defs/nonNegativeInteger`,default:1},maxProperties:{$ref:`#/$defs/nonNegativeInteger`},minProperties:{$ref:`#/$defs/nonNegativeIntegerDefault0`},required:{$ref:`#/$defs/stringArray`},dependentRequired:{type:`object`,additionalProperties:{$ref:`#/$defs/stringArray`}}},$defs:{nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{$ref:`#/$defs/nonNegativeInteger`,default:0},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}}}})),ls=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ts(),n=ns(),r=rs(),i=is(),a=as(),s=os(),c=ss(),l=cs(),u=[`/properties`];function addMetaSchema2020(e){return[t,n,r,i,a,with$data(this,s),c,with$data(this,l)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function with$data(t,n){return e?t.$dataMetaSchema(n,u):n}}e.default=addMetaSchema2020})),us=r(((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.Ajv2020=void 0;let n=no(),r=Qo(),i=es(),a=ls(),s=`https://json-schema.org/draft/2020-12/schema`;var Ajv2020=class extends n.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(a.default.call(this,e),this.refs[`http://json-schema.org/schema`]=s)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv2020=Ajv2020,t.exports=e=Ajv2020,t.exports.Ajv2020=Ajv2020,Object.defineProperty(e,"__esModule",{value:!0}),e.default=Ajv2020;var c=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=V();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 u=Ja();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var f=Ya();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),ds=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function fmtDef(e,t){return{validate:e,compare:t}}e.fullFormats={date:fmtDef(date,compareDate),time:fmtDef(getTime(!0),compareTime),"date-time":fmtDef(getDateTime(!0),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"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,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,int32:{type:`number`,validate:validateInt32},int64:{type:`number`,validate:validateInt64},float:{type:`number`,validate:validateNumber},double:{type:`number`,validate:validateNumber},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\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,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\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,compareIsoDateTime),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 isLeapYear(e){return e%4==0&&(e%100!=0||e%400==0)}let t=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(e){let r=t.exec(e);if(!r)return!1;let i=+r[1],a=+r[2],s=+r[3];return a>=1&&a<=12&&s>=1&&s<=(a===2&&isLeapYear(i)?29:n[a])}function compareDate(e,t){if(e&&t)return e>t?1:e<t?-1:0}let r=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(e){return function time(t){let n=r.exec(t);if(!n)return!1;let i=+n[1],a=+n[2],s=+n[3],c=n[4],l=n[5]===`-`?-1:1,u=+(n[6]||0),f=+(n[7]||0);if(u>23||f>59||e&&!c)return!1;if(i<=23&&a<=59&&s<60)return!0;let p=a-f*l,m=i-u*l-+(p<0);return(m===23||m===-1)&&(p===59||p===-1)&&s<61}}function compareTime(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function compareIsoTime(e,t){if(!(e&&t))return;let n=r.exec(e),i=r.exec(t);if(n&&i)return e=n[1]+n[2]+n[3],t=i[1]+i[2]+i[3],e>t?1:e<t?-1:0}let i=/t|\s/i;function getDateTime(e){let t=getTime(e);return function date_time(e){let n=e.split(i);return n.length===2&&date(n[0])&&t(n[1])}}function compareDateTime(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function compareIsoDateTime(e,t){if(!(e&&t))return;let[n,r]=e.split(i),[a,s]=t.split(i),c=compareDate(n,a);if(c!==void 0)return c||compareTime(r,s)}let a=/\/|:/,s=/^(?:[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 uri(e){return a.test(e)&&s.test(e)}let c=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(e){return c.lastIndex=0,c.test(e)}let l=-(2**31),u=2**31-1;function validateInt32(e){return Number.isInteger(e)&&e<=u&&e>=l}function validateInt64(e){return Number.isInteger(e)}function validateNumber(){return!0}let f=/[^\\]\\Z/;function regex(e){if(f.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),fs=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ao(),n=yo(),r=Io(),i=Xo(),a=Zo();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),ps=r(((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}})),ms=r(((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 n=no(),r=fs(),i=es(),a=ps(),s=[`/properties`],c=`http://json-schema.org/draft-07/schema`;var Ajv=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,s):a;this.addMetaSchema(e,c,!1),this.refs[`http://json-schema.org/schema`]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};e.Ajv=Ajv,t.exports=e=Ajv,t.exports.Ajv=Ajv,Object.defineProperty(e,"__esModule",{value:!0}),e.default=Ajv;var l=qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=V();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var f=Ja();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Ya();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),hs=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=ms(),n=V(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:s,keyword:c,it:l}=e,{opts:u,self:f}=l;if(!u.validateFormats)return;let p=new t.KeywordCxt(l,f.RULES.all.format.definition,`format`);p.$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let t=r.scopeValue(`formats`,{ref:f.formats,code:u.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${p.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,compareCode(i)))}function validateFormat(){let t=p.schema,i=f.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${c}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:u.code.formats?(0,n._)`${u.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(compareCode(a))}function compareCode(e){return(0,n._)`${e}.compare(${a}, ${s}) ${i[c].fail} 0`}},dependencies:[`format`]};let formatLimitPlugin=t=>(t.addKeyword(e.formatLimitDefinition),t);e.default=formatLimitPlugin})),gs=r(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=ds(),r=hs(),i=V(),a=new i.Name(`fullFormats`),s=new i.Name(`fastFormats`),formatsPlugin=(e,t={keywords:!0})=>{if(Array.isArray(t))return addFormats(e,t,n.fullFormats,a),e;let[i,c]=t.mode===`fast`?[n.fastFormats,s]:[n.fullFormats,a];return addFormats(e,t.formats||n.formatNames,i,c),t.keywords&&(0,r.default)(e),e};formatsPlugin.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function addFormats(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=formatsPlugin,Object.defineProperty(e,"__esModule",{value:!0}),e.default=formatsPlugin})),_s=us(),vs=e(gs(),1);const copyProperty=(e,t,n,r)=>{if(n===`length`||n===`prototype`||n===`arguments`||n===`caller`)return;let i=Object.getOwnPropertyDescriptor(e,n),a=Object.getOwnPropertyDescriptor(t,n);(canCopyProperty(i,a)||!r)&&Object.defineProperty(e,n,a)},canCopyProperty=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},changePrototype=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},wrappedToString=(e,t)=>`/* Wrapped ${e}*/\n${t}`,ys=Object.getOwnPropertyDescriptor(Function.prototype,`toString`),bs=Object.getOwnPropertyDescriptor(Function.prototype.toString,`name`),changeToString=(e,t,n)=>{let r=n===``?``:`with ${n.trim()}() `,i=wrappedToString.bind(null,r,t.toString());Object.defineProperty(i,"name",bs);let{writable:a,enumerable:s,configurable:c}=ys;Object.defineProperty(e,"toString",{value:i,writable:a,enumerable:s,configurable:c})};function mimicFunction(e,t,{ignoreNonConfigurable:n=!1}={}){let{name:r}=e;for(let r of Reflect.ownKeys(t))copyProperty(e,t,r,n);return changePrototype(e,t),changeToString(e,t,r),e}const debounceFunction=(e,t={})=>{if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:n=0,maxWait:r=1/0,before:i=!1,after:a=!0}=t;if(n<0||r<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!i&&!a)throw Error("Both `before` and `after` are false, function wouldn't be called.");let s,c,l,debouncedFunction=function(...t){let u=this,later=()=>{s=void 0,c&&=(clearTimeout(c),void 0),a&&(l=e.apply(u,t))},maxLater=()=>{c=void 0,s&&=(clearTimeout(s),void 0),a&&(l=e.apply(u,t))},f=i&&!s;return clearTimeout(s),s=setTimeout(later,n),r>0&&r!==1/0&&!c&&(c=setTimeout(maxLater,r)),f&&(l=e.apply(u,t)),l};return mimicFunction(debouncedFunction,e),debouncedFunction.cancel=()=>{s&&=(clearTimeout(s),void 0),c&&=(clearTimeout(c),void 0)},debouncedFunction},xs=Object.prototype.toString;function isType(e,t,n){return e?e.constructor===t||xs.call(e)===n:!1}function isUint8Array(e){return isType(e,Uint8Array,`[object Uint8Array]`)}function isArrayBuffer(e){return isType(e,ArrayBuffer,`[object ArrayBuffer]`)}function isUint8ArrayOrArrayBuffer(e){return isUint8Array(e)||isArrayBuffer(e)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function assertUint8ArrayOrArrayBuffer(e){if(!isUint8ArrayOrArrayBuffer(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)assertUint8Array(t),n.set(t,r),r+=t.length;return n}const Ss={utf8:new globalThis.TextDecoder(`utf8`)};function uint8ArrayToString(e,t=`utf8`){return assertUint8ArrayOrArrayBuffer(e),Ss[t]??=new globalThis.TextDecoder(t),Ss[t].decode(e)}function assertString(e){if(typeof e!=`string`)throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}const Cs=new globalThis.TextEncoder;function stringToUint8Array(e){return assertString(e),Cs.encode(e)}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));const ws=`aes-256-cbc`,Ts=new Set([`aes-256-cbc`,`aes-256-gcm`,`aes-256-ctr`]),isSupportedEncryptionAlgorithm=e=>typeof e==`string`&&Ts.has(e),createPlainObject=()=>Object.create(null),isExist=e=>e!==void 0,checkValueType=(e,t)=>{let n=new Set([`undefined`,`symbol`,`function`]),r=typeof t;if(n.has(r))throw TypeError(`Setting a value of type \`${r}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},Es=`__internal__`,Ds=`${Es}.migrations.version`;var Conf=class{path;events;#e;#t;#n;#r;#i={};#a=!1;#o;#s;#c;constructor(e={}){let t=this.#l(e);this.#r=t,this.#u(t),this.#f(t),this.#p(t),this.events=new EventTarget,this.#t=t.encryptionKey,this.#n=t.encryptionAlgorithm??ws,this.path=this.#m(t),this.#h(t),t.watch&&this._watch()}get(e,t){if(this.#r.accessPropertiesByDotNotation)return this._get(e,t);let{store:n}=this;return e in n?n[e]:t}set(e,t){if(typeof e!=`string`&&typeof e!=`object`)throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=`object`&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${Es} key, as it's used to manage this module internal operations.`);let{store:n}=this,set=(e,t)=>{if(checkValueType(e,t),this.#r.accessPropertiesByDotNotation)setProperty(n,e,t);else{if(e===`__proto__`||e===`constructor`||e===`prototype`)return;n[e]=t}};if(typeof e==`object`){let t=e;for(let[e,n]of Object.entries(t))set(e,n)}else set(e,t);this.store=n}has(e){return this.#r.accessPropertiesByDotNotation?hasProperty(this.store,e):e in this.store}appendToArray(e,t){checkValueType(e,t);let n=this.#r.accessPropertiesByDotNotation?this._get(e,[]):e in this.store?this.store[e]:[];if(!Array.isArray(n))throw TypeError(`The key \`${e}\` is already set to a non-array value`);this.set(e,[...n,t])}reset(...e){for(let t of e)isExist(this.#i[t])&&this.set(t,this.#i[t])}delete(e){let{store:t}=this;this.#r.accessPropertiesByDotNotation?deleteProperty(t,e):delete t[e],this.store=t}clear(){let e=createPlainObject();for(let t of Object.keys(this.#i))isExist(this.#i[t])&&(checkValueType(t,this.#i[t]),this.#r.accessPropertiesByDotNotation?setProperty(e,t,this.#i[t]):e[t]=this.#i[t]);this.store=e}onDidChange(e,t){if(typeof e!=`string`)throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleValueChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleStoreChange(e)}get size(){return Object.keys(this.store).filter(e=>!this._isReservedKeyPath(e)).length}get store(){try{let e=F.readFileSync(this.path,this.#t?null:`utf8`),t=this._decryptData(e),parseStore=e=>{let t=this._deserialize(e);return this.#a||this._validate(t),Object.assign(createPlainObject(),t)};return parseStore(t)}catch(e){if(e?.code===`ENOENT`)return this._ensureDirectory(),createPlainObject();if(this.#r.clearInvalidConfig){let t=e;if(t.name===`SyntaxError`||t.message?.startsWith(`Config schema violation:`)||t.message===`Failed to decrypt config data.`)return createPlainObject()}throw e}}set store(e){if(this._ensureDirectory(),!hasProperty(e,Es))try{let t=F.readFileSync(this.path,this.#t?null:`utf8`),n=this._decryptData(t),r=this._deserialize(n);hasProperty(r,Es)&&setProperty(e,Es,getProperty(r,Es))}catch{}this.#a||this._validate(e),this._write(e),this.events.dispatchEvent(new Event(`change`))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))this._isReservedKeyPath(e)||(yield[e,t])}_closeWatcher(){this.#o&&=(this.#o.close(),void 0),this.#s&&=(F.unwatchFile(this.path),!1),this.#c=void 0}_decryptData(e){let t=this.#t;if(!t)return typeof e==`string`?e:uint8ArrayToString(e);let n=this.#n,r=n===`aes-256-gcm`?16:0,i=`:`.codePointAt(0),a=typeof e==`string`?e.codePointAt(16):e[16];if(i===void 0||a!==i){if(n===`aes-256-cbc`)return typeof e==`string`?e:uint8ArrayToString(e);throw Error(`Failed to decrypt config data.`)}let getEncryptedPayload=e=>{if(r===0)return{ciphertext:e};let t=e.length-r;if(t<0)throw Error(`Invalid authentication tag length.`);return{ciphertext:e.slice(0,t),authenticationTag:e.slice(t)}},s=e.slice(0,16),c=e.slice(17),l=typeof c==`string`?stringToUint8Array(c):c,decrypt=e=>{let{ciphertext:r,authenticationTag:i}=getEncryptedPayload(l),a=Tn.pbkdf2Sync(t,e,1e4,32,`sha512`),c=Tn.createDecipheriv(n,a,s);return i&&c.setAuthTag(i),uint8ArrayToString(concatUint8Arrays([c.update(r),c.final()]))};try{return decrypt(s)}catch{try{return decrypt(s.toString())}catch{}}if(n===`aes-256-cbc`)return typeof e==`string`?e:uint8ArrayToString(e);throw Error(`Failed to decrypt config data.`)}_handleStoreChange(e){let t=this.store,onChange=()=>{let n=t,r=this.store;At(r,n)||(t=r,e.call(this,r,n))};return this.events.addEventListener(`change`,onChange),()=>{this.events.removeEventListener(`change`,onChange)}}_handleValueChange(e,t){let n=e(),onChange=()=>{let r=n,i=e();At(i,r)||(n=i,t.call(this,i,r))};return this.events.addEventListener(`change`,onChange),()=>{this.events.removeEventListener(`change`,onChange)}}_deserialize=e=>JSON.parse(e);_serialize=e=>JSON.stringify(e,void 0,` `);_validate(e){if(!this.#e||this.#e(e)||!this.#e.errors)return;let t=this.#e.errors.map(({instancePath:e,message:t=``})=>`\`${e.slice(1)}\` ${t}`);throw Error(`Config schema violation: `+t.join(`; `))}_ensureDirectory(){F.mkdirSync(N.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e),n=this.#t;if(n){let e=Tn.randomBytes(16),r=Tn.pbkdf2Sync(n,e,1e4,32,`sha512`),i=Tn.createCipheriv(this.#n,r,e),a=concatUint8Arrays([i.update(stringToUint8Array(t)),i.final()]),s=[e,stringToUint8Array(`:`),a];this.#n===`aes-256-gcm`&&s.push(i.getAuthTag()),t=concatUint8Arrays(s)}if(I.env.SNAP)F.writeFileSync(this.path,t,{mode:this.#r.configFileMode});else try{writeFileSync$1(this.path,t,{mode:this.#r.configFileMode})}catch(e){if(e?.code===`EXDEV`){F.writeFileSync(this.path,t,{mode:this.#r.configFileMode});return}throw e}}_watch(){if(this._ensureDirectory(),F.existsSync(this.path)||this._write(createPlainObject()),I.platform===`win32`||I.platform===`darwin`){this.#c??=debounceFunction(()=>{this.events.dispatchEvent(new Event(`change`))},{wait:100});let e=N.dirname(this.path),t=N.basename(this.path);this.#o=F.watch(e,{persistent:!1,encoding:`utf8`},(e,n)=>{n&&n!==t||typeof this.#c==`function`&&this.#c()})}else this.#c??=debounceFunction(()=>{this.events.dispatchEvent(new Event(`change`))},{wait:1e3}),F.watchFile(this.path,{persistent:!1},(e,t)=>{typeof this.#c==`function`&&this.#c()}),this.#s=!0}_migrate(e,t,n){let r=this._get(Ds,`0.0.0`),i=Object.keys(e).filter(e=>this._shouldPerformMigration(e,r,t)),a=structuredClone(this.store);for(let s of i)try{n&&n(this,{fromVersion:r,toVersion:s,finalVersion:t,versions:i});let c=e[s];c?.(this),this._set(Ds,s),r=s,a=structuredClone(this.store)}catch(e){this.store=a;let t=e instanceof Error?e.message:String(e);throw Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${t}`)}(this._isVersionInRangeFormat(r)||!pa.default.eq(r,t))&&this._set(Ds,t)}_containsReservedKey(e){return typeof e==`string`?this._isReservedKeyPath(e):!e||typeof e!=`object`?!1:this._objectContainsReservedKey(e)}_objectContainsReservedKey(e){if(!e||typeof e!=`object`)return!1;for(let[t,n]of Object.entries(e))if(this._isReservedKeyPath(t)||this._objectContainsReservedKey(n))return!0;return!1}_isReservedKeyPath(e){return e===Es||e.startsWith(`${Es}.`)}_isVersionInRangeFormat(e){return pa.default.clean(e)===null}_shouldPerformMigration(e,t,n){return this._isVersionInRangeFormat(e)?t!==`0.0.0`&&pa.default.satisfies(t,e)?!1:pa.default.satisfies(n,e):!(pa.default.lte(e,t)||pa.default.gt(e,n))}_get(e,t){return getProperty(this.store,e,t)}_set(e,t){let{store:n}=this;setProperty(n,e,t),this.store=n}#l(e){let t={configName:`config`,fileExtension:`json`,projectSuffix:`nodejs`,clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(t.encryptionAlgorithm??=ws,!isSupportedEncryptionAlgorithm(t.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...Ts].join(`, `)}`);if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=envPaths(t.projectName,{suffix:t.projectSuffix}).config}return typeof t.fileExtension==`string`&&(t.fileExtension=t.fileExtension.replace(/^\.+/,``)),t}#u(e){if(!(e.schema??e.ajvOptions??e.rootSchema))return;if(e.schema&&typeof e.schema!=`object`)throw TypeError("The `schema` option must be an object.");let t=vs.default.default,n=new _s.Ajv2020({allErrors:!0,useDefaults:!0,...e.ajvOptions});t(n);let r={...e.rootSchema,type:`object`,properties:e.schema};this.#e=n.compile(r),this.#d(e.schema)}#d(e){let t=Object.entries(e??{});for(let[e,n]of t){if(!n||typeof n!=`object`||!Object.hasOwn(n,`default`))continue;let{default:t}=n;t!==void 0&&(this.#i[e]=t)}}#f(e){e.defaults&&Object.assign(this.#i,e.defaults)}#p(e){e.serialize&&(this._serialize=e.serialize),e.deserialize&&(this._deserialize=e.deserialize)}#m(e){let t=typeof e.fileExtension==`string`?e.fileExtension:void 0,n=t?`.${t}`:``;return N.resolve(e.cwd,`${e.configName??`config`}${n}`)}#h(e){if(e.migrations){this.#g(e),this._validate(this.store);return}let t=this.store,n=Object.assign(createPlainObject(),e.defaults??{},t);this._validate(n);try{Jn.deepEqual(t,n)}catch{this.store=n}}#g(e){let{migrations:t,projectVersion:n}=e;if(t){if(!n)throw Error("Please specify the `projectVersion` option.");this.#a=!0;try{let r=this.store,i=Object.assign(createPlainObject(),e.defaults??{},r);try{Jn.deepEqual(r,i)}catch{this._write(i)}this._migrate(t,n,e.beforeEachMigration)}finally{this.#a=!1}}}};const Os={name:sr,version:cr},ks=it(()=>{try{return new Conf({projectName:sr,clearInvalidConfig:!0,watch:!1})}catch(e){Qr.debug(`Failed to create config store`,{error:e});return}}),As=`check-update`;async function notifyAvailableUpdate(){if(Mn||Pn||Fn===As||isInsideContainer())return;let e=ks();if(!e)return;let t=e.get(`lastUpdateCheck`),n=e.get(`latestVersion`);if(Xe(n)||Xe(t)||t+864e5<Date.now()){try{mn(`likec4`,[`check-update`],{stdio:`ignore`,timeout:5e3,preferLocal:!0,detached:!0,env:{NODE_ENV:As}}).catch(()=>{})}catch{}return}n&&(0,pa.gt)(n,Os.version)&&boxen([`Update available: `,S.dim(Os.version),S.reset(` → `),S.green(n)].join(``))}async function checkAvailableUpdate(e=!0){try{let t=ks();t?.set({lastUpdateCheck:Date.now()});let n=await fetchLatestVersion();if($t(n,`No version found in latest npm`),t?.set({lastUpdateCheck:Date.now(),latestVersion:n}),(0,pa.gt)(n,Os.version)){boxen([`Update available: `,S.dim(Os.version),S.reset(` → `),S.green(n)].join(``));return}e&&boxen(S.dim(`Up to date: `)+` `+S.green(Os.version))}catch(e){Qr.warning(a(e))}}async function fetchLatestVersion(){return(await xi(`https://registry.npmjs.org/likec4/latest`,{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},timeout:5e3,keepalive:!0}).json()).version}function isInstalled(e){try{return!!kt.createRequire(import.meta.url).resolve(e)}catch(e){return Qr.debug(a(e)),!1}}async function ensureReact(){if(isInstalled(`react`)&&isInstalled(`react-dom`)){Qr.debug(`react already installed`);return}Qr.warn(`react not installed`);let e=await Dt();e||(Qr.error`Package manager not detected, please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));let t=Et(e.agent,`add`,[`react`,`react-dom`]);t||(Qr.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));try{await mn(t.command,t.args,{stdio:`inherit`})}catch(e){Qr.debug(a(e)),Qr.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1)}}async function ensurePlaywright(){if(isInstalled(`playwright`)){Qr.debug(`playwright already installed`);return}Qr.warn(`playwright not installed`);let e=await Dt();e||(Qr.error`Package manager not detected, please install dependencies manually: ${`playwright`}`,process.exit(1));let t=Et(e.agent,`add`,[`playwright`]);t||(Qr.error`Please install dependencies manually: ${`playwright`}`,process.exit(1));try{await mn(t.command,t.args,{preferLocal:!0,stdio:`inherit`})}catch(e){Qr.debug(a(e)),Qr.error`Please install dependencies manually: ${`playwright`}`,process.exit(1)}}const U={type:`string`,desc:`<directory> with LikeC4 sources (default is current directory or 'LIKEC4_WORKSPACE' env)`,normalize:!0,default:jn.LIKEC4_WORKSPACE||`.`,coerce:P},W={alias:`use-dot-bin`,boolean:!0,type:`boolean`,desc:isInsideContainer()?`enabled in container, disable by --no-use-dot`:`use graphviz binaries ("dot" should be on PATH)`,default:isInsideContainer()},js={boolean:!0,type:`boolean`,desc:"use `@likec4/core` package in types",default:!1},Ms={boolean:!0,type:`boolean`,desc:`use hash history for navigation, e.g. "/#/view" instead of "/view"`},Ns={alias:[`o`,`output`],string:!0,desc:`output directory`,normalize:!0,nargs:1,coerce:P},Ps={alias:`w`,string:!0,desc:`prefix for Webcomponents, e.g "c4" generates <c4-view ../>`,default:`likec4`,nargs:1},Fs={alias:`t`,string:!0,desc:`base title of the app pages (default is "LikeC4")`,default:`LikeC4`,nargs:1},Is={choices:[`light`,`dark`],desc:`default color scheme for the built website (default: auto, follows system preference)`,nargs:1},Ls={alias:[`base-url`],string:!0,desc:`base url the app is being served from, e.g. "/" or "/pages/"`,nargs:1},Rs={boolean:!0,desc:`outputs a single self-contained HTML file with all required resources inlined`},zs={alias:`public-dir`,string:!0,desc:`directory whose files are copied to the output as-is (Vite publicDir, e.g. images linked from views)`,normalize:!0,nargs:1,coerce:P},Bs={array:!0,string:!0,desc:`hostname allowed to respond to (Vite server.allowedHosts); can be repeated. Defaults to allowing all hosts.`,requiresArg:!0},Vs={alias:`l`,string:!0,...isInsideContainer()?{desc:`listen 0.0.0.0 by default in container`,default:`0.0.0.0`}:{desc:`ip address of the network interface to listen on`},nargs:1},Hs={number:!0,desc:`port number for the dev server (default is 5173, or PORT environment variable)`,nargs:1},Us={number:!0,desc:`port number for the HMR WebSocket server (default is auto-discovered from 24678-24690, or HMR_PORT environment variable)`,nargs:1},Ws={alias:`p`,string:!0,desc:`select LikeC4 project by name (e.g. "my-project") or by path`,nargs:1},Gs={hidden:!0,nargs:1,desc:`force log level`,choices:[`trace`,`debug`,`info`,`warning`,`error`],conflicts:[`verbose`]},Ks={boolean:!0,desc:`verbose logging`,conflicts:[`log-level`]},qs=Nn?`trace`:`debug`,Js=6e4,Ys=Js*60*24*7;function showSupportUsMessage(){if(!(Mn||Pn))try{let e=Date.now(),t=ks();if(!t)return;let n=t.get(`lastSupportUsMessage`);if(!n){t.set(`lastSupportUsMessage`,e-Ys+5*Js);return}if(n+Ys>e)return;t.set(`lastSupportUsMessage`,e),boxen([S.dim(`If you are working in a commercial environment`),S.dim(`consider supporting the project`),``,S.dim(`How to get more?`)+` `+S.underline(`https://likec4.dev/sponsor/`)].join(`
174
+ `))}catch{}}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const buildCmd=e=>e.command({command:`build [path]`,aliases:[`bundle`],describe:`Build a static website`,builder:e=>e.positional(`path`,U).option(`output`,{alias:`o`,type:`string`,desc:`output directory for production build`,normalize:!0,coerce:P}).option(`base`,Ls).option(`use-hash-history`,Ms).option(`use-dot`,W).option(`webcomponent-prefix`,Ps).option(`build-webcomponent`,{type:`boolean`,default:!0,describe:`enable/disable webcomponent build`}).option(`title`,Fs).option(`output-single-file`,Rs).option(`public`,zs).option(`theme`,Is).example(`${S.green(`$0 build -o ./build ./src`)}`,S.gray(`Search for likec4 files in 'src' and output static site to 'build'`)).example(`${S.green(`$0 build --theme dark -o ./build ./src`)}`,S.gray(`Build with dark color scheme as default`)).example(`${S.green(`$0 build --public ./assets -o ./build ./src`)}`,S.gray(`Copy files from 'assets' to the output directory as-is`)),handler:async e=>{try{var t=_usingCtx();let n={useHashHistory:e[`use-hash-history`]??!1,useDotBin:e[`use-dot`],webcomponentPrefix:e[`webcomponent-prefix`],buildWebcomponent:e[`build-webcomponent`],outputSingleFile:e[`output-single-file`]??!1};await notifyAvailableUpdate(),await ensureReact();let r=createLikeC4Logger(`c4:build`),i=t.a(await x(e.path,{graphviz:e[`use-dot`]?`binary`:`wasm`,watch:!1})),a=e.output??P(i.workspace,`dist`),s=P(a,`assets`);await viteBuild({base:e.base,useHashHistory:n.outputSingleFile||n.useHashHistory,customLogger:r,webcomponentPrefix:n.webcomponentPrefix,buildWebcomponent:n.buildWebcomponent,title:e.title,theme:e.theme,languageServices:i,likec4AssetsDir:s,outputDir:a,outputSingleFile:n.outputSingleFile,userPublicDir:e.public}),showSupportUsMessage()}catch(e){t.e=e}finally{await t.d()}}}),checkUpdateCmd=e=>e.command({command:`check-update`,describe:`Check for updates`,handler:async()=>{await checkAvailableUpdate()}});function ensureProjectId(e,t){if(!t)return e.languageServices.projectsManager.ensureProjectId();let n=P(t);if(n===e.workspace)return e.languageServices.projectsManager.ensureProjectId();if(vn(n)&&Cn(n).isDirectory()){Qr.debug`Project path exists: ${n}`;let t=ce.file(n.endsWith(Jt)?n:n+Jt),r=e.languageServices.projects().find(e=>e.folder.fsPath===t.fsPath);if(r)return Qr.debug`Found project ${r.id} at path: ${n}`,r.id;Qr.debug`No project registered at path: ${n}`}return e.languageServices.projectsManager.ensureProjectId(t)}function ensureProject(e,t){let n=ensureProjectId(e,t),r=e.languageServices.projectsManager.getProject(n);return e.languageServices.projectsManager.defaultProjectId=n,{projectId:n,projectFolder:r.folderUri.fsPath,config:r.config}}const Xs=Qr.getChild(`generator`);async function customHandler({name:e,path:t,useDotBin:n,project:r}){try{var i=_usingCtx();let a=startTimer(Xs),s=i.a(await x(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:c,config:l}=ensureProject(s,r);r&&Xs.info(`${S.dim(`project`)} ${S.green(c)}`);let u=l.generators?.[e];if(!u)throw Xs.error(S.red(`generator ${e} does not exist in project config`)),Error(`generator ${e} does not exist in project config`);Xs.info(`${S.dim(`generator`)} ${S.green(e)}`),await runCustomGenerator({likec4:s,model:await s.layoutedModel(c),generator:u,logger:Xs.getChild(e)}),a.stopAndLog()}catch(e){i.e=e}finally{await i.d()}}async function runCustomGenerator({likec4:e,model:t,generator:n,logger:r}){let i=e.languageServices,a=new Set,s=i.project(t.project.id),c=t.project.id;r.debug(`${S.dim(`running for project:`)} ${S.green(s.id)}`),await Promise.resolve().then(()=>n({likec4model:t,ctx:{workspace:e.languageServices.workspaceUri,project:s,locate:e=>{let t=null;switch(!0){case un(e):t=i.locate({element:e.id,projectId:c});break;case dn(e):t=i.locate({view:e.id,projectId:c});break;case sn(e):t=i.locate({deployment:e.id,projectId:c});break;case fn(e):case ln(e):t=i.locate({relation:e.id,projectId:c});break;default:en(e)}if(!t)throw r.error(`Cannot locate ${e.id}`,{target:e}),Error(`Cannot locate ${e.id}`);let n=ce.parse(t.uri);return{range:t.range,document:n,relativePath:le.relative(s.folder,n),folder:le.dirname(n).fsPath,filename:le.basename(n)}},write:async({path:e,content:t})=>{let n;n=Array.isArray(e)?P(s.folder.fsPath,...e):ce.isUri(e)?e.fsPath:P(s.folder.fsPath,`${e}`);let i=Ut(n);a.has(i)||(vn(i)||(r.debug(`${S.dim(`create directory`)} ${i}`),await Pt(i,{recursive:!0})),a.add(i)),r.debug(`${S.dim(`write`)} ${n}`),await Vt(n,t)},abort:e=>{throw r.error(e||`Generator aborted`),Error(e||`Generator aborted`)}}}))}function relativeOutputDir(e){if(!e)return`.`;let t=e.split(/[\\/]+/);t.pop();let n=[];for(let e of t){let t=e.replace(/^[a-zA-Z]:/,``);switch(t){case``:case`.`:break;case`..`:n.pop();break;default:n.push(t)}}return n.length>0?Kt(...n):`.`}async function singleFileCodegenAction(e,t,n){t??=P(e.workspace,`likec4.generated.ts`),Wt(t)!==`.ts`&&(t+=`.ts`),await Pt(Ut(t),{recursive:!0});let r=generateViewsDataTs([...await e.diagrams()]);await Vt(t,r),n.info(`${S.dim(`generated`)} ${qt(process.cwd(),t)}`)}async function dotCodegenAction(e,t,n){await Pt(t,{recursive:!0}),n.info(`${S.dim(`format`)} ${S.green(`dot`)}`),n.info(`${S.dim(`outdir`)} ${t}`);let r=new Set,i=await e.computedModel(),a=ct(i.$data.views),s=0;for(let c of a)try{let a=await e.viewsService.layouter.dot({view:c,styles:i.$styles}),l=P(t,relativeOutputDir(c.sourcePath));r.has(l)||(await Pt(l,{recursive:!0}),r.add(l));let u=P(l,c.id+`.dot`);await Vt(u,a),n.info(`${S.dim(`generated`)} ${qt(process.cwd(),u)}`),s++}catch(e){Qr.error(`error while generating ${c.id}`,{error:e})}s>0&&n.info(`${S.dim(`total`)} ${s} files`)}async function multipleFilesCodegenAction(e,t,n,r){await Pt(n,{recursive:!0}),r.info(`${S.dim(`format`)} ${S.green(t)}`),r.info(`${S.dim(`outdir`)} ${n}`);let i,a;switch(t){case`d2`:i=`.d2`,a=vt;break;case`mermaid`:i=`.mmd`,a=Ct;break;case`plantuml`:i=`.puml`,a=xt;break;default:en(t)}let s=new Set,c=await e.layoutedModel(),l=0;for(let e of c.views()){let t=e.$view;try{let c=P(n,relativeOutputDir(t.sourcePath));s.has(c)||(await Pt(c,{recursive:!0}),s.add(c));let u=P(c,t.id+i),f=a(e);await Vt(u,f),r.info(`${S.dim(`generated`)} ${qt(process.cwd(),u)}`),l++}catch(e){r.error(`error while generating ${t.id}`,{error:e})}}l>0&&r.info(`${S.dim(`total`)} ${l} files`)}async function legacyHandler({path:e,useDotBin:t,...n}){let r=createLikeC4Logger(`c4:codegen`),i=startTimer(r),a=await x(e,{graphviz:t?`binary`:`wasm`,watch:!1});if(a.ensureSingleProject(),(await a.viewsService.computedViews()).length===0)throw r.warn(`no views found`),process.exitCode=1,Error(`no views found`);switch(n.format){case`views`:await singleFileCodegenAction(a,n.outfile,r);break;case`dot`:await dotCodegenAction(a,n.outdir??e,r);break;case`d2`:case`mermaid`:case`plantuml`:await multipleFilesCodegenAction(a,n.format,n.outdir??e,r);break;default:en(n)}i.stopAndLog()}const Zs=Ut(kn(import.meta.url));function readVersion(){try{let e=JSON.parse(yn(Kt(Zs,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}try{let e=JSON.parse(yn(Kt(Zs,`..`,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}return`0.1.0`}const Qs=readVersion(),$s=`leanix`,ec=new Set([`factSheetTypes`,`relationTypes`,`metadataToFields`]);function isPlainObjectRecordOfStrings(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e))if(typeof t!=`string`)return!1;return!0}function parseLeanixMappingInput(e){if(e==null)return e;if(typeof e!=`object`||Array.isArray(e))throw Error(`LeanIX mapping must be a plain object (not an array or primitive)`);let t=e;for(let e of Object.keys(t))if(!ec.has(e))throw Error(`LeanIX mapping has unknown key "${e}". Allowed: factSheetTypes, relationTypes, metadataToFields`);if(t.factSheetTypes!==void 0&&!isPlainObjectRecordOfStrings(t.factSheetTypes))throw Error(`LeanIX mapping "factSheetTypes" must be an object with string keys and string values`);if(t.relationTypes!==void 0&&!isPlainObjectRecordOfStrings(t.relationTypes))throw Error(`LeanIX mapping "relationTypes" must be an object with string keys and string values`);if(t.metadataToFields!==void 0&&!isPlainObjectRecordOfStrings(t.metadataToFields))throw Error(`LeanIX mapping "metadataToFields" must be an object with string keys and string values`);return e}const tc={factSheetTypes:{system:`Application`,container:`ITComponent`,component:`ITComponent`,actor:`Provider`},relationTypes:{default:`depends on`},metadataToFields:{title:`name`,description:`description`,technology:`technology`}};function mergeWithDefault(e){let t=parseLeanixMappingInput(e),n={factSheetTypes:{...tc.factSheetTypes},relationTypes:{...tc.relationTypes},metadataToFields:{...tc.metadataToFields}};return t?{factSheetTypes:{...n.factSheetTypes,...t.factSheetTypes},relationTypes:{...n.relationTypes,...t.relationTypes},metadataToFields:{...n.metadataToFields,...t.metadataToFields}}:n}function getFactSheetType(e,t){return t.factSheetTypes[e]??t.factSheetTypes.default??`Application`}function getRelationType(e,t){let n=e??`default`;return t.relationTypes[n]??t.relationTypes.default??`depends on`}const nc={manifestVersion:`1.0`,bridgeVersion:Qs,mappingProfile:`default`};function buildManifestEntities(e){let t={};for(let n of e.elements())t[n.id]={canonicalId:n.id,external:{}};return t}function buildManifestViews(e){let t={};for(let n of e.views())t[n.id]={viewId:n.id,external:{}};return t}function buildManifestRelations(e){let t=[];for(let n of e.relationships())t.push({relationId:n.id,sourceFqn:n.source.id,targetFqn:n.target.id,compositeKey:`${n.source.id}|${n.target.id}|${n.id}`,external:{}});return t}function toBridgeManifest(e,t={}){let n={...nc,...t,generatedAt:t.generatedAt??new Date().toISOString()};return{manifestVersion:n.manifestVersion,generatedAt:n.generatedAt,bridgeVersion:n.bridgeVersion,mappingProfile:n.mappingProfile,projectId:e.projectId,entities:buildManifestEntities(e),views:buildManifestViews(e),relations:buildManifestRelations(e)}}function buildFactSheetsFromModel(e,t){let n=[];for(let r of e.elements()){let e=getFactSheetType(r.kind,t),i=r.getMetadata(),a=typeof i.description==`string`?i.description:void 0,s=r.technology??(typeof i.technology==`string`?i.technology:void 0);n.push({type:e,likec4Id:r.id,name:r.title,...a!==void 0&&{description:a},...s!==void 0&&{technology:s},...r.tags.length>0&&{tags:[...r.tags]},...Object.keys(i).length>0&&{metadata:{...i}}})}return n.sort((e,t)=>e.likec4Id.localeCompare(t.likec4Id)),n}function buildRelationsFromModel(e,t){let n=[];for(let r of e.relationships()){let e=r.title??r.kind;n.push({type:getRelationType(r.kind,t),likec4RelationId:r.id,sourceLikec4Id:r.source.id,targetLikec4Id:r.target.id,...e!=null&&e!==``&&{title:String(e)}})}return n.sort((e,t)=>e.likec4RelationId.localeCompare(t.likec4RelationId)),n}function toLeanixInventoryDryRun(e,t={}){let n=mergeWithDefault(t.mapping),r=t.generatedAt??new Date().toISOString(),i=t.mappingProfile??(t.mapping?`custom`:`default`);return{generatedAt:r,projectId:e.projectId,mappingProfile:i,factSheets:buildFactSheetsFromModel(e,n),relations:buildRelationsFromModel(e,n)}}function buildCoherenceErrorMessage(e,t){let n=[];return e.projectId!==t.projectId&&n.push(`projectId (manifest: ${e.projectId}, leanixDryRun: ${t.projectId})`),e.mappingProfile!==t.mappingProfile&&n.push(`mappingProfile (manifest: ${e.mappingProfile}, leanixDryRun: ${t.mappingProfile})`),`Manifest and LeanIX dry-run must belong to the same run. Mismatch: ${n.join(`; `)}`}function buildBridgeReport(e,t){if(e.projectId!==t.projectId||e.mappingProfile!==t.mappingProfile)throw Error(buildCoherenceErrorMessage(e,t));return{generatedAt:e.generatedAt,projectId:e.projectId,manifestVersion:e.manifestVersion,bridgeVersion:e.bridgeVersion,mappingProfile:e.mappingProfile,counts:{entities:Object.keys(e.entities).length,views:Object.keys(e.views).length,relations:e.relations.length,factSheets:t.factSheets.length,leanixRelations:t.relations.length},artifacts:{manifest:`manifest.json`,leanixDryRun:`leanix-dry-run.json`}}}var LeanixApiError=class extends Error{statusCode;graphqlErrors;constructor(e,t,n){super(e),this.statusCode=t,this.graphqlErrors=n,this.name=`LeanixApiError`}};function sleep(e){return new Promise(t=>setTimeout(t,e))}var LeanixApiClient=class{baseUrl;apiToken;requestDelayMs;lastRequestTime=0;rateLimitLock=Promise.resolve();constructor(e){this.apiToken=e.apiToken,this.baseUrl=(e.baseUrl??`https://app.leanix.net`).replace(/\/$/,``),this.requestDelayMs=e.requestDelayMs??200}async graphql(e,t){let run=async()=>{let n=Date.now()-this.lastRequestTime;n<this.requestDelayMs&&await sleep(this.requestDelayMs-n),this.lastRequestTime=Date.now();let r=`${this.baseUrl}/services/pathfinder/v1/graphql`,i;try{i=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiToken}`},body:JSON.stringify({query:e,variables:t})})}catch(e){throw new LeanixApiError(`GraphQL request failed: ${r} POST - ${e instanceof Error?e.message:String(e)}`)}let a;try{a=await i.json()}catch(e){let t=e instanceof Error?e.message:String(e);throw new LeanixApiError(`Invalid JSON response: ${r} ${i.status} ${i.statusText} - ${t}`,i.status)}if(!i.ok)throw new LeanixApiError(a.errors?.[0]?.message??`HTTP ${i.status} ${i.statusText}`,i.status,a.errors);if(a.errors&&a.errors.length>0)throw new LeanixApiError(a.errors.map(e=>e.message).join(`; `),i.status,a.errors);if(a.data===void 0)throw new LeanixApiError(`GraphQL response had no data and no errors`);return a.data},n=this.rateLimitLock,r;this.rateLimitLock=new Promise(e=>{r=e}),await n;try{return await run()}finally{r()}}};async function findFactSheetByNameAndType(e,t,n){let r=(await e.graphql(`
175
175
  query FindFactSheet($name: String!, $type: String!) {
176
176
  allFactSheets(filter: { name: $name, factSheetType: $type }) {
177
177
  edges { node { id name type } }
@@ -201,7 +201,7 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
201
201
  relation { id }
202
202
  }
203
203
  }
204
- `,{source:t,target:n,type:r}),s=a.createRelation?.relation?.id;if(!s){let e=JSON.stringify(a,null,2);throw Error(`createRelation did not return relation id (sourceFactSheetId=${t}, targetFactSheetId=${n}, relationType=${r}). Response: ${e}`)}return s}function buildFactSheetPlanEntry(e,t){let n=t?`update`:`create`;return{likec4Id:e.likec4Id,name:e.name,type:e.type,action:n,...t?{existingFactSheetId:t}:{}}}function buildPlanSummary(e,t){return{factSheetsToCreate:e.filter(e=>e.action===`create`).length,factSheetsToUpdate:e.filter(e=>e.action===`update`).length,relationsToCreate:t.length}}function toErrorMessage(e){if(e instanceof Error)return e.stack?`${e.message}\n${e.stack}`:e.message;if(typeof e==`object`&&e)try{return JSON.stringify(e,null,2)}catch{return Object.prototype.toString.call(e)}return String(e)}function applyLeanixIdsToEntities(e,t){let n={...e};for(let[r,i]of Object.entries(e)){let e=t.get(r);e&&(n[r]={...i,external:{...i.external,[ec]:{factSheetId:e,externalId:e}}})}return n}async function resolveExistingFactSheetId(e,t,n,r){if(!n)return null;if(r){let n=await findFactSheetByLikec4IdAttribute(e,r,t.likec4Id);if(n)return n;let i=await findFactSheetByNameAndType(e,t.name,t.type);if(i&&t.likec4Id)try{await patchFactSheetAttribute(e,i,r,t.likec4Id)}catch(e){console.warn(`[leanix-bridge] Failed to backfill likec4Id on fact sheet ${i} (${t.name}/${t.type}): ${e instanceof Error?e.message:String(e)}. Reusing ID.`)}return i??null}return findFactSheetByNameAndType(e,t.name,t.type)}async function syncFactSheetsToLeanix(e,t,n,r){let i=new Map,a=[],s=0,c=0;for(let l of t)try{let t=await resolveExistingFactSheetId(e,l,n,r);t&&c++,t||(t=await createFactSheet(e,l,r),s++),t&&i.set(l.likec4Id,t)}catch(e){a.push(`Fact sheet ${l.likec4Id} (${String(l.name)}): ${toErrorMessage(e)}`)}return{likec4IdToFactSheetId:i,factSheetsCreated:s,factSheetsReused:c,errors:a}}async function syncRelationsToLeanix(e,t,n,r){let i=[],a=[],s=0;for(let c of t){let t=r.get(c.sourceFqn),l=r.get(c.targetFqn),u=c.external?.[ec];if(t&&l&&!u?.relationId){let r=n.find(e=>e.sourceLikec4Id===c.sourceFqn&&e.targetLikec4Id===c.targetFqn&&e.likec4RelationId===c.relationId);if(r)try{let n=await createRelation(e,t,l,r.type,r.title);s++,i.push({...c,external:{...c.external,[ec]:{relationId:n,...c.external?.[ec]}}});continue}catch(e){a.push(`Relation ${c.compositeKey}: ${toErrorMessage(e)}`)}}i.push(c)}return{updatedRelations:i,relationsCreated:s,errors:a}}async function planSyncToLeanix(e,t,n={}){let r=n.idempotent??!0,i=n.likec4IdAttribute,a=n.generatedAt??new Date().toISOString(),s=[],c=[];for(let n of e.factSheets)try{let e=null;r&&(i?(e=await findFactSheetByLikec4IdAttribute(t,i,n.likec4Id),e||=await findFactSheetByNameAndType(t,n.name,n.type)):e=await findFactSheetByNameAndType(t,n.name,n.type)),c.push(buildFactSheetPlanEntry(n,e))}catch(e){s.push(`Fact sheet ${n.likec4Id} (${String(n.name)}): ${toErrorMessage(e)}`),c.push(buildFactSheetPlanEntry(n,null))}let l=e.relations.map(e=>({likec4RelationId:e.likec4RelationId,sourceLikec4Id:e.sourceLikec4Id,targetLikec4Id:e.targetLikec4Id,type:e.type,action:`create`}));return{generatedAt:a,projectId:e.projectId,mappingProfile:e.mappingProfile,summary:buildPlanSummary(c,l),factSheetPlans:c,relationPlans:l,errors:s}}async function syncToLeanix(e,t,n,r={}){let i=r.idempotent??!0,a=r.likec4IdAttribute,s=await syncFactSheetsToLeanix(n,t.factSheets,i,a),c=applyLeanixIdsToEntities(e.entities,s.likec4IdToFactSheetId),l=await syncRelationsToLeanix(n,e.relations,t.relations,s.likec4IdToFactSheetId);return{manifest:{...e,entities:c,relations:l.updatedRelations},factSheetsCreated:s.factSheetsCreated,factSheetsReused:s.factSheetsReused,relationsCreated:l.relationsCreated,errors:[...s.errors,...l.errors]}}async function withGraphQLRetry(e){let t;for(let n=0;n<3;n++)try{return await e()}catch(e){t=e,n<2&&await new Promise(e=>setTimeout(e,500*(n+1)))}throw t}async function fetchLeanixInventorySnapshot(e,t={}){let n=t.generatedAt??new Date().toISOString(),r=t.maxFactSheets??1e3;if(!Number.isInteger(r)||r<0)throw Error(`maxFactSheets must be a non-negative integer`);let i=t.likec4IdAttribute,a=await fetchAllFactSheets(e,{...i==null?{}:{likec4IdAttribute:i},maxFactSheets:r});return{generatedAt:n,factSheets:a,relations:await fetchAllRelations(e,a.map(e=>e.id))}}function mapNodeToFactSheetItem(e,t){if(!e?.id)return null;let n=t!=null&&Array.isArray(e.factSheetAttributes)?e.factSheetAttributes.find(e=>e.key===t)?.value:void 0;return{id:e.id,name:e.name??``,type:e.type??``,...n?{likec4Id:n}:{}}}async function fetchAllFactSheets(e,t){let n=t.likec4IdAttribute,r=Math.min(100,t.maxFactSheets),i=[],a=null,s=!0,c=`
204
+ `,{source:t,target:n,type:r}),s=a.createRelation?.relation?.id;if(!s){let e=JSON.stringify(a,null,2);throw Error(`createRelation did not return relation id (sourceFactSheetId=${t}, targetFactSheetId=${n}, relationType=${r}). Response: ${e}`)}return s}function buildFactSheetPlanEntry(e,t){let n=t?`update`:`create`;return{likec4Id:e.likec4Id,name:e.name,type:e.type,action:n,...t?{existingFactSheetId:t}:{}}}function buildPlanSummary(e,t){return{factSheetsToCreate:e.filter(e=>e.action===`create`).length,factSheetsToUpdate:e.filter(e=>e.action===`update`).length,relationsToCreate:t.length}}function toErrorMessage(e){if(e instanceof Error)return e.stack?`${e.message}\n${e.stack}`:e.message;if(typeof e==`object`&&e)try{return JSON.stringify(e,null,2)}catch{return Object.prototype.toString.call(e)}return String(e)}function applyLeanixIdsToEntities(e,t){let n={...e};for(let[r,i]of Object.entries(e)){let e=t.get(r);e&&(n[r]={...i,external:{...i.external,[$s]:{factSheetId:e,externalId:e}}})}return n}async function resolveExistingFactSheetId(e,t,n,r){if(!n)return null;if(r){let n=await findFactSheetByLikec4IdAttribute(e,r,t.likec4Id);if(n)return n;let i=await findFactSheetByNameAndType(e,t.name,t.type);if(i&&t.likec4Id)try{await patchFactSheetAttribute(e,i,r,t.likec4Id)}catch(e){console.warn(`[leanix-bridge] Failed to backfill likec4Id on fact sheet ${i} (${t.name}/${t.type}): ${e instanceof Error?e.message:String(e)}. Reusing ID.`)}return i??null}return findFactSheetByNameAndType(e,t.name,t.type)}async function syncFactSheetsToLeanix(e,t,n,r){let i=new Map,a=[],s=0,c=0;for(let l of t)try{let t=await resolveExistingFactSheetId(e,l,n,r);t&&c++,t||(t=await createFactSheet(e,l,r),s++),t&&i.set(l.likec4Id,t)}catch(e){a.push(`Fact sheet ${l.likec4Id} (${String(l.name)}): ${toErrorMessage(e)}`)}return{likec4IdToFactSheetId:i,factSheetsCreated:s,factSheetsReused:c,errors:a}}async function syncRelationsToLeanix(e,t,n,r){let i=[],a=[],s=0;for(let c of t){let t=r.get(c.sourceFqn),l=r.get(c.targetFqn),u=c.external?.[$s];if(t&&l&&!u?.relationId){let r=n.find(e=>e.sourceLikec4Id===c.sourceFqn&&e.targetLikec4Id===c.targetFqn&&e.likec4RelationId===c.relationId);if(r)try{let n=await createRelation(e,t,l,r.type,r.title);s++,i.push({...c,external:{...c.external,[$s]:{relationId:n,...c.external?.[$s]}}});continue}catch(e){a.push(`Relation ${c.compositeKey}: ${toErrorMessage(e)}`)}}i.push(c)}return{updatedRelations:i,relationsCreated:s,errors:a}}async function planSyncToLeanix(e,t,n={}){let r=n.idempotent??!0,i=n.likec4IdAttribute,a=n.generatedAt??new Date().toISOString(),s=[],c=[];for(let n of e.factSheets)try{let e=null;r&&(i?(e=await findFactSheetByLikec4IdAttribute(t,i,n.likec4Id),e||=await findFactSheetByNameAndType(t,n.name,n.type)):e=await findFactSheetByNameAndType(t,n.name,n.type)),c.push(buildFactSheetPlanEntry(n,e))}catch(e){s.push(`Fact sheet ${n.likec4Id} (${String(n.name)}): ${toErrorMessage(e)}`),c.push(buildFactSheetPlanEntry(n,null))}let l=e.relations.map(e=>({likec4RelationId:e.likec4RelationId,sourceLikec4Id:e.sourceLikec4Id,targetLikec4Id:e.targetLikec4Id,type:e.type,action:`create`}));return{generatedAt:a,projectId:e.projectId,mappingProfile:e.mappingProfile,summary:buildPlanSummary(c,l),factSheetPlans:c,relationPlans:l,errors:s}}async function syncToLeanix(e,t,n,r={}){let i=r.idempotent??!0,a=r.likec4IdAttribute,s=await syncFactSheetsToLeanix(n,t.factSheets,i,a),c=applyLeanixIdsToEntities(e.entities,s.likec4IdToFactSheetId),l=await syncRelationsToLeanix(n,e.relations,t.relations,s.likec4IdToFactSheetId);return{manifest:{...e,entities:c,relations:l.updatedRelations},factSheetsCreated:s.factSheetsCreated,factSheetsReused:s.factSheetsReused,relationsCreated:l.relationsCreated,errors:[...s.errors,...l.errors]}}async function withGraphQLRetry(e){let t;for(let n=0;n<3;n++)try{return await e()}catch(e){t=e,n<2&&await new Promise(e=>setTimeout(e,500*(n+1)))}throw t}async function fetchLeanixInventorySnapshot(e,t={}){let n=t.generatedAt??new Date().toISOString(),r=t.maxFactSheets??1e3;if(!Number.isInteger(r)||r<0)throw Error(`maxFactSheets must be a non-negative integer`);let i=t.likec4IdAttribute,a=await fetchAllFactSheets(e,{...i==null?{}:{likec4IdAttribute:i},maxFactSheets:r});return{generatedAt:n,factSheets:a,relations:await fetchAllRelations(e,a.map(e=>e.id))}}function mapNodeToFactSheetItem(e,t){if(!e?.id)return null;let n=t!=null&&Array.isArray(e.factSheetAttributes)?e.factSheetAttributes.find(e=>e.key===t)?.value:void 0;return{id:e.id,name:e.name??``,type:e.type??``,...n?{likec4Id:n}:{}}}async function fetchAllFactSheets(e,t){let n=t.likec4IdAttribute,r=Math.min(100,t.maxFactSheets),i=[],a=null,s=!0,c=`
205
205
  query AllFactSheets($first: Int!, $after: String, $filter: FilterInput) {
206
206
  allFactSheets(first: $first, after: $after, filter: $filter) {
207
207
  edges {
@@ -235,26 +235,26 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
235
235
  }
236
236
  }
237
237
  }
238
- `,{id:t,first:100,after:i})),c=s?.factSheet?.relations?.edges??[],l=s?.factSheet?.relations?.pageInfo;for(let e of c){let i=e.node,a=i?.targetFactSheet?.id;!a||!r.has(a)||n.push({...i?.id?{id:i.id}:{},sourceFactSheetId:t,targetFactSheetId:a,type:i?.type??`RELATES_TO`})}a=l?.hasNextPage===!0,i=l?.endCursor??null}return n}for(let e=0;e<t.length;e+=10){let r=t.slice(e,e+10),i=await Promise.all(r.map(e=>fetchRelationsForFactSheet(e)));for(let e of i)n.push(...e)}return n}function tryMatchByManifestFactSheetId(e,t,n,r){let i=e.external?.[ec],a=i?.factSheetId??i?.externalId;if(a==null)return null;let s=n.get(a);return!s||r.has(s.id)?null:(r.add(s.id),{canonicalId:t,factSheetId:s.id,name:s.name,type:s.type})}function tryMatchByLikec4Id(e,t,n){let r=t.get(e);return!r||n.has(r.id)?null:(n.add(r.id),{canonicalId:e,factSheetId:r.id,name:r.name,type:r.type})}function resolveByNameAndType(e,t,n,r,i,a,s,c){let l=`${t??e}${n??``}`,u=r.get(l)?.filter(e=>!i.has(e.id))??[];if(u.length===0)s.push({canonicalId:e,...t===void 0?{}:{name:t},...n===void 0?{}:{type:n}});else if(u.length===1){let t=u[0];a.push({canonicalId:e,factSheetId:t.id,name:t.name,type:t.type}),i.add(t.id)}else c.push({canonicalId:e,...t===void 0?{}:{name:t},...n===void 0?{}:{type:n},candidateFactSheetIds:u.map(e=>e.id)})}function reconcileInventoryWithManifest(e,t,n={}){let r=n.generatedAt??new Date().toISOString(),i=n.dryRun,a=[],s=[],c=[],l=new Map(e.factSheets.map(e=>[e.id,e])),u=new Map,f=new Map;for(let t of e.factSheets){t.likec4Id&&u.set(t.likec4Id,t);let e=`${t.name}${t.type}`;f.has(e)||f.set(e,[]),f.get(e).push(t)}let p=i?new Map(i.factSheets.map(e=>[e.likec4Id,e])):null,m=new Set;for(let[e,n]of Object.entries(t.entities)){let t=tryMatchByManifestFactSheetId(n,e,l,m);if(t){a.push(t);continue}let r=tryMatchByLikec4Id(e,u,m);if(r){a.push(r);continue}let i=p?.get(e);resolveByNameAndType(e,i?.name??void 0,i?.type??void 0,f,m,a,s,c)}let h=e.factSheets.filter(e=>!m.has(e.id)).map(e=>({factSheetId:e.id,name:e.name,type:e.type,...e.likec4Id?{likec4Id:e.likec4Id}:{}}));return{generatedAt:r,manifestProjectId:t.projectId,snapshotGeneratedAt:e.generatedAt,matched:a,unmatchedInLikec4:s,unmatchedInLeanix:h,ambiguous:c,summary:{matched:a.length,unmatchedInLikec4:s.length,unmatchedInLeanix:h.length,ambiguous:c.length}}}function isRecord(e){return typeof e==`object`&&!!e}function isManifestEntity(e){return isRecord(e)?typeof e.canonicalId==`string`:!1}function isManifestView(e){return isRecord(e)?typeof e.viewId==`string`:!1}function isManifestRelation(e){return isRecord(e)?typeof e.relationId==`string`&&typeof e.sourceFqn==`string`&&typeof e.targetFqn==`string`&&typeof e.compositeKey==`string`:!1}function isLeanixFactSheetSnapshotItem(e){return isRecord(e)?typeof e.id==`string`&&typeof e.name==`string`&&typeof e.type==`string`:!1}function isLeanixRelationSnapshotItem(e){return isRecord(e)?typeof e.sourceFactSheetId==`string`&&typeof e.targetFactSheetId==`string`&&typeof e.type==`string`:!1}function isBridgeManifest(e){if(!isRecord(e)||typeof e.manifestVersion!=`string`||typeof e.generatedAt!=`string`||typeof e.bridgeVersion!=`string`||typeof e.mappingProfile!=`string`||typeof e.projectId!=`string`)return!1;let t=e.entities;if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(!isManifestEntity(e))return!1;let n=e.views;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(!isManifestView(e))return!1;let r=e.relations;if(!Array.isArray(r))return!1;for(let e of r)if(!isManifestRelation(e))return!1;return!0}function isLeanixInventorySnapshot(e){if(!isRecord(e)||typeof e.generatedAt!=`string`||e.workspaceId!==void 0&&typeof e.workspaceId!=`string`||!Array.isArray(e.factSheets))return!1;for(let t of e.factSheets)if(!isLeanixFactSheetSnapshotItem(t))return!1;if(!Array.isArray(e.relations))return!1;for(let t of e.relations)if(!isLeanixRelationSnapshotItem(t))return!1;return!0}const ic=`No project or empty model`,ac=`LEANIX_API_TOKEN is required for likec4 sync leanix --apply`,oc=`default`,sc=`manifest.json`,cc=`leanix-dry-run.json`,lc=`report.json`;function asBridgeModel(e){return{projectId:String(e.projectId),elements:()=>e.elements(),relationships:()=>e.relationships(),views:()=>e.views()}}function buildBridgeArtifacts(e){let t=toBridgeManifest(e,{mappingProfile:oc}),n=toLeanixInventoryDryRun(e,{mappingProfile:oc});return{manifest:t,dryRun:n,report:buildBridgeReport(t,n)}}async function writeBridgeArtifacts(e,t,n,r=process.cwd()){await It(e,{recursive:!0});let i=M(e,sc),a=M(e,cc),s=M(e,lc);await Ut(i,JSON.stringify(t.manifest,null,2)),await Ut(a,JSON.stringify(t.dryRun,null,2)),await Ut(s,JSON.stringify(t.report,null,2)),n.info(`${S.dim(`generated`)} ${Yt(r,i)}`),n.info(`${S.dim(`generated`)} ${Yt(r,a)}`),n.info(`${S.dim(`generated`)} ${Yt(r,s)}`)}const uc={manifest:sc,dryRun:cc,report:lc};async function leanixDryRunHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:dry-run`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s}=e;try{try{var c=_usingCtx();let e=c.a(await x(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${S.dim(`project`)} ${S.green(n)}`);let l=await e.layoutedModel(n);if(l===At.EMPTY)throw t.error(ic),Error(ic);await writeBridgeArtifacts(i,buildBridgeArtifacts(asBridgeModel(l)),t)}catch(e){c.e=e}finally{await c.d()}}finally{n.stopAndLog()}}function createLeanixClientFromEnv(){let e=process.env.LEANIX_API_TOKEN?.trim();return e?new LeanixApiClient({apiToken:e,baseUrl:process.env.LEANIX_BASE_URL?.trim()||`https://app.leanix.net`,requestDelayMs:200}):null}function requireLeanixClient(){let e=createLeanixClientFromEnv();if(!e)throw Error(`LEANIX_API_TOKEN is required. Set it in the environment to call the LeanIX API.`);return e}async function leanixInventorySnapshotHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:inventory`),n=startTimer(t),{outdir:r,likec4IdAttribute:i}=e;try{let e=requireLeanixClient(),n={};typeof i==`string`&&i.trim()!==``&&(n.likec4IdAttribute=i.trim());let a=await fetchLeanixInventorySnapshot(e,n);await It(r,{recursive:!0});let s=M(r,`leanix-inventory-snapshot.json`);await Ut(s,JSON.stringify(a,null,2)),t.info(`${S.dim(`generated`)} ${Yt(process.cwd(),s)}`),t.info(`${S.dim(`snapshot`)} ${a.factSheets.length} fact sheets, ${a.relations.length} relations`)}finally{n.stopAndLog()}}const dc=`manifest.json`,fc=`leanix-inventory-snapshot.json`;async function readManifestAndSnapshot(e){let t=M(e,dc),n=M(e,fc),[r,i]=await Promise.all([Rt(t,`utf-8`),Rt(n,`utf-8`)]),a=JSON.parse(r),s=JSON.parse(i);if(!isBridgeManifest(a))throw Error(`Invalid manifest format: missing manifestVersion, projectId, entities, relations, or views`);if(!isLeanixInventorySnapshot(s))throw Error(`Invalid snapshot format: missing factSheets or relations arrays`);return{manifest:a,snapshot:s}}async function loadDryRunFromWorkspace(e,t,n){try{var r=_usingCtx();let i=r.a(await x(e,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:a}=ensureProject(i,t),s=await i.layoutedModel(a);return s===At.EMPTY?void 0:buildBridgeArtifacts(asBridgeModel(s)).dryRun}catch(e){r.e=e}finally{await r.d()}}async function leanixReconcileHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:reconcile`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s}=e;try{let e,n;try{let t=await readManifestAndSnapshot(i);e=t.manifest,n=t.snapshot}catch(e){let n=e instanceof Error?e.message:String(e);throw t.error(`Failed to read ${dc} or ${fc} from ${i}: ${n}`),e}let c;try{c=await loadDryRunFromWorkspace(r,a,s)}catch(e){let n=e instanceof Error?e.message:String(e);if(a!=null&&a!==``)throw t.error(`Failed to load workspace for dryRun enrichment: ${n}`),e;t.warn(`Could not load workspace for dryRun enrichment; proceeding without it: ${n}`),c=void 0}let l=reconcileInventoryWithManifest(n,e,{...c==null?{}:{dryRun:c}}),u=M(i,`reconciliation-report.json`);await Ut(u,JSON.stringify(l,null,2)),t.info(`${S.dim(`generated`)} ${Yt(process.cwd(),u)}`),t.info(`${S.dim(`reconcile`)} matched=${l.summary.matched} unmatchedLikec4=${l.summary.unmatchedInLikec4} unmatchedLeanix=${l.summary.unmatchedInLeanix} ambiguous=${l.summary.ambiguous}`)}finally{n.stopAndLog()}}async function modelHandler({path:e,useDotBin:t,useCorePackage:n,outfile:r,project:i,skipLayout:a}){try{var s=_usingCtx();let c=createLikeC4Logger(`c4:codegen`),l=startTimer(c),u=s.a(await x(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:f,projectFolder:p}=ensureProject(u,i);i&&c.info(`${S.dim(`project`)} ${S.green(f)}`),c.info(`${S.dim(`format`)} ${S.green(`model`)} ${a?S.cyan(`(compute only)`):``}`);let m;if(a)m=await u.computedModel(f);else{m=await u.layoutedModel(f);for(let e of m.views())e.hasLayoutDrifts&&c.warn(S.yellow(`layout drift detected, view:`)+` `+S.red(e.id))}let h=M(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-model.ts`);if(r&&(h=qt(r)?r:M(r),_n(r)&&(await Ht(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let g=Wt(h);c.info(`${S.dim(`filename`)} ${g}`);let v=Kt(g).toLocaleLowerCase();if(![`.ts`,`.mts`,`.cts`].includes(v))throw c.error(`output file ${r} has extension "${v}"`),Error(`output file ${r} must be a .ts, .mts or .cts file`);let y=Gt(h);c.info(`${S.dim(`outdir`)} ${y}`),await It(y,{recursive:!0}),await Ut(h,generateLikeC4Model(m,{useCorePackage:n}),{encoding:`utf-8`}),l.stopAndLog(),boxen(ae(`
238
+ `,{id:t,first:100,after:i})),c=s?.factSheet?.relations?.edges??[],l=s?.factSheet?.relations?.pageInfo;for(let e of c){let i=e.node,a=i?.targetFactSheet?.id;a&&r.has(a)&&n.push({...i?.id?{id:i.id}:{},sourceFactSheetId:t,targetFactSheetId:a,type:i?.type??`RELATES_TO`})}a=l?.hasNextPage===!0,i=l?.endCursor??null}return n}for(let e=0;e<t.length;e+=10){let r=t.slice(e,e+10),i=await Promise.all(r.map(e=>fetchRelationsForFactSheet(e)));for(let e of i)n.push(...e)}return n}function tryMatchByManifestFactSheetId(e,t,n,r){let i=e.external?.[$s],a=i?.factSheetId??i?.externalId;if(a==null)return null;let s=n.get(a);return!s||r.has(s.id)?null:(r.add(s.id),{canonicalId:t,factSheetId:s.id,name:s.name,type:s.type})}function tryMatchByLikec4Id(e,t,n){let r=t.get(e);return!r||n.has(r.id)?null:(n.add(r.id),{canonicalId:e,factSheetId:r.id,name:r.name,type:r.type})}function resolveByNameAndType(e,t,n,r,i,a,s,c){let l=`${t??e}${n??``}`,u=r.get(l)?.filter(e=>!i.has(e.id))??[];if(u.length===0)s.push({canonicalId:e,...t===void 0?{}:{name:t},...n===void 0?{}:{type:n}});else if(u.length===1){let t=u[0];a.push({canonicalId:e,factSheetId:t.id,name:t.name,type:t.type}),i.add(t.id)}else c.push({canonicalId:e,...t===void 0?{}:{name:t},...n===void 0?{}:{type:n},candidateFactSheetIds:u.map(e=>e.id)})}function reconcileInventoryWithManifest(e,t,n={}){let r=n.generatedAt??new Date().toISOString(),i=n.dryRun,a=[],s=[],c=[],l=new Map(e.factSheets.map(e=>[e.id,e])),u=new Map,f=new Map;for(let t of e.factSheets){t.likec4Id&&u.set(t.likec4Id,t);let e=`${t.name}${t.type}`;f.has(e)||f.set(e,[]),f.get(e).push(t)}let p=i?new Map(i.factSheets.map(e=>[e.likec4Id,e])):null,m=new Set;for(let[e,n]of Object.entries(t.entities)){let t=tryMatchByManifestFactSheetId(n,e,l,m);if(t){a.push(t);continue}let r=tryMatchByLikec4Id(e,u,m);if(r){a.push(r);continue}let i=p?.get(e);resolveByNameAndType(e,i?.name??void 0,i?.type??void 0,f,m,a,s,c)}let h=e.factSheets.filter(e=>!m.has(e.id)).map(e=>({factSheetId:e.id,name:e.name,type:e.type,...e.likec4Id?{likec4Id:e.likec4Id}:{}}));return{generatedAt:r,manifestProjectId:t.projectId,snapshotGeneratedAt:e.generatedAt,matched:a,unmatchedInLikec4:s,unmatchedInLeanix:h,ambiguous:c,summary:{matched:a.length,unmatchedInLikec4:s.length,unmatchedInLeanix:h.length,ambiguous:c.length}}}function isRecord(e){return typeof e==`object`&&!!e}function isManifestEntity(e){return isRecord(e)?typeof e.canonicalId==`string`:!1}function isManifestView(e){return isRecord(e)?typeof e.viewId==`string`:!1}function isManifestRelation(e){return isRecord(e)?typeof e.relationId==`string`&&typeof e.sourceFqn==`string`&&typeof e.targetFqn==`string`&&typeof e.compositeKey==`string`:!1}function isLeanixFactSheetSnapshotItem(e){return isRecord(e)?typeof e.id==`string`&&typeof e.name==`string`&&typeof e.type==`string`:!1}function isLeanixRelationSnapshotItem(e){return isRecord(e)?typeof e.sourceFactSheetId==`string`&&typeof e.targetFactSheetId==`string`&&typeof e.type==`string`:!1}function isBridgeManifest(e){if(!isRecord(e)||typeof e.manifestVersion!=`string`||typeof e.generatedAt!=`string`||typeof e.bridgeVersion!=`string`||typeof e.mappingProfile!=`string`||typeof e.projectId!=`string`)return!1;let t=e.entities;if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(!isManifestEntity(e))return!1;let n=e.views;if(typeof n!=`object`||!n||Array.isArray(n))return!1;for(let e of Object.values(n))if(!isManifestView(e))return!1;let r=e.relations;if(!Array.isArray(r))return!1;for(let e of r)if(!isManifestRelation(e))return!1;return!0}function isLeanixInventorySnapshot(e){if(!isRecord(e)||typeof e.generatedAt!=`string`||e.workspaceId!==void 0&&typeof e.workspaceId!=`string`||!Array.isArray(e.factSheets))return!1;for(let t of e.factSheets)if(!isLeanixFactSheetSnapshotItem(t))return!1;if(!Array.isArray(e.relations))return!1;for(let t of e.relations)if(!isLeanixRelationSnapshotItem(t))return!1;return!0}const rc=`No project or empty model`,ic=`LEANIX_API_TOKEN is required for likec4 sync leanix --apply`,ac=`default`,oc=`manifest.json`,sc=`leanix-dry-run.json`,cc=`report.json`;function asBridgeModel(e){return{projectId:String(e.projectId),elements:()=>e.elements(),relationships:()=>e.relationships(),views:()=>e.views()}}function buildBridgeArtifacts(e){let t=toBridgeManifest(e,{mappingProfile:ac}),n=toLeanixInventoryDryRun(e,{mappingProfile:ac});return{manifest:t,dryRun:n,report:buildBridgeReport(t,n)}}async function writeBridgeArtifacts(e,t,n,r=process.cwd()){await Pt(e,{recursive:!0});let i=P(e,oc),a=P(e,sc),s=P(e,cc);await Vt(i,JSON.stringify(t.manifest,null,2)),await Vt(a,JSON.stringify(t.dryRun,null,2)),await Vt(s,JSON.stringify(t.report,null,2)),n.info(`${S.dim(`generated`)} ${qt(r,i)}`),n.info(`${S.dim(`generated`)} ${qt(r,a)}`),n.info(`${S.dim(`generated`)} ${qt(r,s)}`)}const lc={manifest:oc,dryRun:sc,report:cc};async function leanixDryRunHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:dry-run`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s}=e;try{try{var c=_usingCtx();let e=c.a(await x(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${S.dim(`project`)} ${S.green(n)}`);let l=await e.layoutedModel(n);if(l===Ot.EMPTY)throw t.error(rc),Error(rc);await writeBridgeArtifacts(i,buildBridgeArtifacts(asBridgeModel(l)),t)}catch(e){c.e=e}finally{await c.d()}}finally{n.stopAndLog()}}function createLeanixClientFromEnv(){let e=process.env.LEANIX_API_TOKEN?.trim();return e?new LeanixApiClient({apiToken:e,baseUrl:process.env.LEANIX_BASE_URL?.trim()||`https://app.leanix.net`,requestDelayMs:200}):null}function requireLeanixClient(){let e=createLeanixClientFromEnv();if(!e)throw Error(`LEANIX_API_TOKEN is required. Set it in the environment to call the LeanIX API.`);return e}async function leanixInventorySnapshotHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:inventory`),n=startTimer(t),{outdir:r,likec4IdAttribute:i}=e;try{let e=requireLeanixClient(),n={};typeof i==`string`&&i.trim()!==``&&(n.likec4IdAttribute=i.trim());let a=await fetchLeanixInventorySnapshot(e,n);await Pt(r,{recursive:!0});let s=P(r,`leanix-inventory-snapshot.json`);await Vt(s,JSON.stringify(a,null,2)),t.info(`${S.dim(`generated`)} ${qt(process.cwd(),s)}`),t.info(`${S.dim(`snapshot`)} ${a.factSheets.length} fact sheets, ${a.relations.length} relations`)}finally{n.stopAndLog()}}const uc=`manifest.json`,dc=`leanix-inventory-snapshot.json`;async function readManifestAndSnapshot(e){let t=P(e,uc),n=P(e,dc),[r,i]=await Promise.all([It(t,`utf-8`),It(n,`utf-8`)]),a=JSON.parse(r),s=JSON.parse(i);if(!isBridgeManifest(a))throw Error(`Invalid manifest format: missing manifestVersion, projectId, entities, relations, or views`);if(!isLeanixInventorySnapshot(s))throw Error(`Invalid snapshot format: missing factSheets or relations arrays`);return{manifest:a,snapshot:s}}async function loadDryRunFromWorkspace(e,t,n){try{var r=_usingCtx();let i=r.a(await x(e,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:a}=ensureProject(i,t),s=await i.layoutedModel(a);return s===Ot.EMPTY?void 0:buildBridgeArtifacts(asBridgeModel(s)).dryRun}catch(e){r.e=e}finally{await r.d()}}async function leanixReconcileHandler(e){let t=createLikeC4Logger(`c4:gen:leanix:reconcile`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s}=e;try{let e,n;try{let t=await readManifestAndSnapshot(i);e=t.manifest,n=t.snapshot}catch(e){let n=e instanceof Error?e.message:String(e);throw t.error(`Failed to read ${uc} or ${dc} from ${i}: ${n}`),e}let c;try{c=await loadDryRunFromWorkspace(r,a,s)}catch(e){let n=e instanceof Error?e.message:String(e);if(a!=null&&a!==``)throw t.error(`Failed to load workspace for dryRun enrichment: ${n}`),e;t.warn(`Could not load workspace for dryRun enrichment; proceeding without it: ${n}`),c=void 0}let l=reconcileInventoryWithManifest(n,e,{...c==null?{}:{dryRun:c}}),u=P(i,`reconciliation-report.json`);await Vt(u,JSON.stringify(l,null,2)),t.info(`${S.dim(`generated`)} ${qt(process.cwd(),u)}`),t.info(`${S.dim(`reconcile`)} matched=${l.summary.matched} unmatchedLikec4=${l.summary.unmatchedInLikec4} unmatchedLeanix=${l.summary.unmatchedInLeanix} ambiguous=${l.summary.ambiguous}`)}finally{n.stopAndLog()}}async function modelHandler({path:e,useDotBin:t,useCorePackage:n,outfile:r,project:i,skipLayout:a}){try{var s=_usingCtx();let c=createLikeC4Logger(`c4:codegen`),l=startTimer(c),u=s.a(await x(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:f,projectFolder:p}=ensureProject(u,i);i&&c.info(`${S.dim(`project`)} ${S.green(f)}`),c.info(`${S.dim(`format`)} ${S.green(`model`)} ${a?S.cyan(`(compute only)`):``}`);let m;if(a)m=await u.computedModel(f);else{m=await u.layoutedModel(f);for(let e of m.views())e.hasLayoutDrifts&&c.warn(S.yellow(`layout drift detected, view:`)+` `+S.red(e.id))}let h=P(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-model.ts`);if(r&&(h=Gt(r)?r:P(r),vn(r)&&(await Bt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let g=Ht(h);c.info(`${S.dim(`filename`)} ${g}`);let v=Wt(g).toLocaleLowerCase();if(![`.ts`,`.mts`,`.cts`].includes(v))throw c.error(`output file ${r} has extension "${v}"`),Error(`output file ${r} must be a .ts, .mts or .cts file`);let y=Ut(h);c.info(`${S.dim(`outdir`)} ${y}`),await Pt(y,{recursive:!0}),await Vt(h,generateLikeC4Model(m,{useCorePackage:n}),{encoding:`utf-8`}),l.stopAndLog(),boxen(ae(`
239
239
  ${S.dim(`Source generated:`)}
240
- ${Yt(In(),h)}
240
+ ${qt(Ln(),h)}
241
241
 
242
242
  ${S.dim(`How to use:`)}
243
243
  ${S.underline(`https://likec4.dev/tooling/code-generation/model/`)}
244
- `).trim(),{padding:1,borderColor:`green`,borderStyle:`round`})}catch(e){s.e=e}finally{await s.d()}}async function viteReactConfig({languageServices:e,outDir:t,filename:n=`likec4-react.mjs`}){let r=createLikeC4Logger([`vite`,`react`]),i=viteAppRoot();return r.info(`${S.cyan(`likec4 app root`)} ${S.dim(relativeToCwd(i))}`),r.info(S.cyan(`outDir`)+` `+S.dim(relativeToCwd(t))),{customLogger:r,root:i,configFile:!1,clearScreen:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases()},build:{outDir:t,emptyOutDir:!1,sourcemap:!1,minify:!1,copyPublicDir:!1,lib:{entry:`codegen/react.mjs`,fileName(e,t){return n},formats:[`es`]},rolldownOptions:{external:[`likec4/react`,`likec4/model`,/^react(\/.*)?$/,/^react-dom(\/.*)?$/,/^use-sync-external-store(\/.*)?$/,/@likec4\/core.*/]}},plugins:[Dt({ai:`disabled`,languageServices:e.languageServices})]}}async function reactHandler({path:e,useDotBin:t,useCorePackage:n,outfile:r,project:i}){try{var a=_usingCtx();await ensureReact();let s=createLikeC4Logger(`c4:codegen`),c=startTimer(s),l=a.a(await x(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,i);i&&s.info(`${S.dim(`project`)} ${S.green(u)}`),s.info(`${S.dim(`format`)} ${S.green(`react`)}`);let p=await l.diagrams(u);if(p.length===0)throw process.exitCode=1,Error(`no views found`);p.forEach(e=>{if(e.drifts&&e.drifts.length>0){s.info(S.yellow(`layout drift detected, view:`)+` `+S.red(e.id));return}if(e.hasLayoutDrift){s.warn(S.yellow(`drift detected, manual layout can not be applied, view:`)+` `+S.red(e.id));return}});let m=M(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(r&&(m=qt(r)?r:M(r),_n(r)&&(await Ht(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let h=Gt(m);s.info(`${S.dim(`outdir`)} ${h}`);let g=Wt(m);s.info(`${S.dim(`filename`)} ${g}`);let v=Kt(g).toLocaleLowerCase();if(![`.js`,`.mjs`,`.jsx`].includes(v))throw s.error(`output file ${r} has extension "${v}"`),Error(`output file ${r} must be a .js, .jsx or .mjs`);let y=await viteReactConfig({languageServices:l,outDir:h,filename:g});await Un({...y,logLevel:`warn`});let b=await l.layoutedModel(u),ee=M(h,Wt(m,v)+(v===`.mjs`?`.d.mts`:`.d.ts`));await Ut(ee,generateReactTypes(b,{useCorePackage:n})),c.stopAndLog(),boxen(ae(`
244
+ `).trim(),{padding:1,borderColor:`green`,borderStyle:`round`})}catch(e){s.e=e}finally{await s.d()}}async function viteReactConfig({languageServices:e,outDir:t,filename:n=`likec4-react.mjs`}){let r=createLikeC4Logger([`vite`,`react`]),i=viteAppRoot();return r.info(`${S.cyan(`likec4 app root`)} ${S.dim(relativeToCwd(i))}`),r.info(S.cyan(`outDir`)+` `+S.dim(relativeToCwd(t))),{customLogger:r,root:i,configFile:!1,clearScreen:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases()},build:{outDir:t,emptyOutDir:!1,sourcemap:!1,minify:!1,copyPublicDir:!1,lib:{entry:`codegen/react.mjs`,fileName(e,t){return n},formats:[`es`]},rolldownOptions:{external:[`likec4/react`,`likec4/model`,/^react(\/.*)?$/,/^react-dom(\/.*)?$/,/^use-sync-external-store(\/.*)?$/,/@likec4\/core.*/]}},plugins:[Tt({ai:`disabled`,languageServices:e.languageServices})]}}async function reactHandler({path:e,useDotBin:t,useCorePackage:n,outfile:r,project:i}){try{var a=_usingCtx();await ensureReact();let s=createLikeC4Logger(`c4:codegen`),c=startTimer(s),l=a.a(await x(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,i);i&&s.info(`${S.dim(`project`)} ${S.green(u)}`),s.info(`${S.dim(`format`)} ${S.green(`react`)}`);let p=await l.diagrams(u);if(p.length===0)throw process.exitCode=1,Error(`no views found`);p.forEach(e=>{if(e.drifts&&e.drifts.length>0){s.info(S.yellow(`layout drift detected, view:`)+` `+S.red(e.id));return}if(e.hasLayoutDrift){s.warn(S.yellow(`drift detected, manual layout can not be applied, view:`)+` `+S.red(e.id));return}});let m=P(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(r&&(m=Gt(r)?r:P(r),vn(r)&&(await Bt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let h=Ut(m);s.info(`${S.dim(`outdir`)} ${h}`);let g=Ht(m);s.info(`${S.dim(`filename`)} ${g}`);let v=Wt(g).toLocaleLowerCase();if(![`.js`,`.mjs`,`.jsx`].includes(v))throw s.error(`output file ${r} has extension "${v}"`),Error(`output file ${r} must be a .js, .jsx or .mjs`);let y=await viteReactConfig({languageServices:l,outDir:h,filename:g});await Wn({...y,logLevel:`warn`});let b=await l.layoutedModel(u),ee=P(h,Ht(m,v)+(v===`.mjs`?`.d.mts`:`.d.ts`));await Vt(ee,generateReactTypes(b,{useCorePackage:n})),c.stopAndLog(),boxen(ae(`
245
245
  ${S.dim(`Sources generated:`)}
246
- ${Yt(In(),m)}
247
- ${Yt(In(),ee)}
246
+ ${qt(Ln(),m)}
247
+ ${qt(Ln(),ee)}
248
248
 
249
249
  ${S.dim(`How to use:`)}
250
250
  ${S.underline(`https://likec4.dev/tooling/code-generation/react/`)}
251
- `),{padding:1,borderColor:`green`,borderStyle:`round`})}catch(e){a.e=e}finally{await a.d()}}async function webcomponentHandler({project:e,path:t,useDotBin:n,webcomponentPrefix:r=`likec4`,outfile:i}){try{var a=_usingCtx();await ensureReact();let s=createLikeC4Logger(`c4:codegen`),c=startTimer(s),l=a.a(await x(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,e);e&&s.info(`${S.dim(`project`)} ${S.green(u)}`),s.info(`${S.dim(`format`)} ${S.green(`webcomponent`)}`);let p=await l.diagrams(u);if(!Xe(p,1))throw s.warn(`no views found`),process.exitCode=1,Error(`no views found`);p.forEach(e=>{e.hasLayoutDrift&&s.warn(S.yellow(`drift detected, manual layout can not be applied, view:`)+` `+S.red(e.id))});let m=M(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(i&&(m=qt(i)?i:M(i),_n(i)&&(await Ht(i)).isDirectory()))throw Error(`output file is a directory: ${i}`);s.debug(`${S.dim(`outfilepath`)} ${m}`);let h=Wt(m);s.debug(`${S.dim(`filename`)} ${h}`);let g=Kt(h).toLocaleLowerCase();if(g!==`.js`&&g!==`.mjs`)throw s.warn(`output file ${i} has extension "${g}"`),Error(`output file ${i} must be a .js or .mjs`);let v=await mkTempPublicDir();s.debug(`${S.dim(`created temp public`)} ${v}`);let y=viteWebcomponentConfig({languageServices:l,outDir:v,filename:h,webcomponentPrefix:r,base:`/`});s.debug(`${S.dim(`vite build webcomponent`)}`),await Un({...y,logLevel:`warn`});let b=M(v,h);if(!_n(b))throw Error(`output file not found: ${b}`);await It(Gt(m),{recursive:!0}),await Pt(b,m),s.info(`${S.dim(`generated`)} ${m}`),s.debug(`${S.dim(`remove temp public`)}`),await Vt(v,{recursive:!0,force:!0}),c.stopAndLog(),boxen(ae(`
251
+ `),{padding:1,borderColor:`green`,borderStyle:`round`})}catch(e){a.e=e}finally{await a.d()}}async function webcomponentHandler({project:e,path:t,useDotBin:n,webcomponentPrefix:r=`likec4`,outfile:i}){try{var a=_usingCtx();await ensureReact();let s=createLikeC4Logger(`c4:codegen`),c=startTimer(s),l=a.a(await x(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,e);e&&s.info(`${S.dim(`project`)} ${S.green(u)}`),s.info(`${S.dim(`format`)} ${S.green(`webcomponent`)}`);let p=await l.diagrams(u);if(!Je(p,1))throw s.warn(`no views found`),process.exitCode=1,Error(`no views found`);p.forEach(e=>{e.hasLayoutDrift&&s.warn(S.yellow(`drift detected, manual layout can not be applied, view:`)+` `+S.red(e.id))});let m=P(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(i&&(m=Gt(i)?i:P(i),vn(i)&&(await Bt(i)).isDirectory()))throw Error(`output file is a directory: ${i}`);s.debug(`${S.dim(`outfilepath`)} ${m}`);let h=Ht(m);s.debug(`${S.dim(`filename`)} ${h}`);let g=Wt(h).toLocaleLowerCase();if(g!==`.js`&&g!==`.mjs`)throw s.warn(`output file ${i} has extension "${g}"`),Error(`output file ${i} must be a .js or .mjs`);let v=await mkTempPublicDir();s.debug(`${S.dim(`created temp public`)} ${v}`);let y=viteWebcomponentConfig({languageServices:l,outDir:v,filename:h,webcomponentPrefix:r,base:`/`});s.debug(`${S.dim(`vite build webcomponent`)}`),await Wn({...y,logLevel:`warn`});let b=P(v,h);if(!vn(b))throw Error(`output file not found: ${b}`);await Pt(Ut(m),{recursive:!0}),await Mt(b,m),s.info(`${S.dim(`generated`)} ${m}`),s.debug(`${S.dim(`remove temp public`)}`),await zt(v,{recursive:!0,force:!0}),c.stopAndLog(),boxen(ae(`
252
252
  ${S.dim(`Webcomponents generated to:`)}
253
- ${Yt(In(),m)}
253
+ ${qt(Ln(),m)}
254
254
 
255
255
  ${S.dim(`Setup and usage instructions:`)}
256
256
  ${S.blue(`https://likec4.dev/tooling/code-generation/webcomponent/`)}
257
- `))}catch(e){a.e=e}finally{await a.d()}}const codegenCmd=e=>e.command({command:`gen <command> [path]`,aliases:[`generate`,`codegen`],describe:`Generate various artifacts from LikeC4 sources`,builder:e=>e.positional(`path`,B).command(`react [path]`,`generate react component to render likec4 view`,e=>e.positional(`path`,B).option(`project`,Gs).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.jsx, .mjs or .js)`,normalize:!0,coerce:M}).option(`use-dot`,js).option(`use-core-package`,Ms),async e=>{await reactHandler({project:e.project,useDotBin:e.useDotBin,path:e.path,outfile:e.outfile,useCorePackage:e.useCorePackage}),showSupportUsMessage()}).command({command:`webcomponent [path]`,aliases:[`wc`,`webcomp`],describe:`generate js with webcomponents`,builder:e=>e.positional(`path`,B).option(`project`,Gs).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.mjs or .js)`,normalize:!0,coerce:M}).option(`webcomponent-prefix`,Fs).option(`use-dot`,js),handler:async e=>{await webcomponentHandler({project:e.project,useDotBin:e.useDotBin,path:e.path,outfile:e.outfile,webcomponentPrefix:e.webcomponentPrefix}),showSupportUsMessage()}}).command({command:`model [path]`,aliases:[`ts`],describe:`generate LikeC4Model (.ts)`,builder:e=>e.positional(`path`,B).option(`project`,Gs).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.ts)`,normalize:!0,coerce:M}).option(`skip-layout`,{type:`boolean`,desc:`Skip layout (produce compute-only model, faster)`}).option(`use-dot`,js).option(`use-core-package`,Ms),handler:async e=>{await modelHandler({path:e.path,useDotBin:e.useDotBin,useCorePackage:e.useCorePackage,outfile:e.outfile,project:e.project,skipLayout:e.skipLayout??!1}),showSupportUsMessage()}}).command({command:`views-data [path]`,aliases:[`views`],describe:`{deprecated} use codegen model`,deprecated:!0,builder:e=>e.positional(`path`,B).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> output .ts file`,normalize:!0,coerce:M}).option(`use-dot`,js),handler:async e=>{await legacyHandler({format:`views`,path:e.path,useDotBin:e.useDotBin,outfile:e.outfile})}}).command({command:`leanix [path]`,describe:`LeanIX bridge: dry-run, inventory snapshot, reconcile`,builder:e=>e.positional(`path`,B).demandCommand(1,`Choose a subcommand: dry-run, inventory, reconcile`).command(`dry-run [path]`,`generate LeanIX bridge artifacts (manifest, dry-run inventory, report)`,e=>e.positional(`path`,B).option(`outdir`,{...Ps,desc:`<dir> output directory for manifest.json, leanix-dry-run.json, report.json`}).option(`project`,Gs).option(`use-dot`,js).example(`${S.green(`$0 gen leanix dry-run -o out/bridge`)}`,S.gray(`Write bridge artifacts to out/bridge`)),async e=>{await leanixDryRunHandler({path:e.path,outdir:e.outdir??M(process.cwd(),`out`,`bridge`),project:e.project,useDotBin:e.useDotBin})}).command(`inventory`,`fetch LeanIX inventory (read-only) and write leanix-inventory-snapshot.json`,e=>e.option(`outdir`,{...Ps,default:M(process.cwd(),`out`,`bridge`),desc:`<dir> output directory for leanix-inventory-snapshot.json`}).option(`likec4-id-attribute`,{type:`string`,desc:`custom LeanIX attribute key for likec4Id (e.g. "likec4Id")`}).example(`${S.green(`$0 gen leanix inventory -o out/bridge`)}`,S.gray(`Requires LEANIX_API_TOKEN`)),async e=>{await leanixInventorySnapshotHandler({outdir:e.outdir??M(process.cwd(),`out`,`bridge`),...e.likec4IdAttribute==null?{}:{likec4IdAttribute:e.likec4IdAttribute}})}).command(`reconcile [path]`,`reconcile manifest with leanix-inventory-snapshot; write reconciliation-report.json`,e=>e.positional(`path`,B).option(`outdir`,{...Ps,default:M(process.cwd(),`out`,`bridge`),desc:`<dir> directory with manifest.json and leanix-inventory-snapshot.json`}).option(`project`,Gs).option(`use-dot`,js).example(`${S.green(`$0 gen leanix reconcile -o out/bridge`)}`,S.gray(`Reads manifest + snapshot from outdir; optional workspace for name+type matching`)),async e=>{await leanixReconcileHandler({path:e.path,outdir:e.outdir??M(process.cwd(),`out`,`bridge`),project:e.project,useDotBin:e.useDotBin})}),handler:async()=>{}}).command({command:`dot [path]`,describe:`generate graphviz files (.dot)`,builder:e=>e.positional(`path`,B).option(`outdir`,Ps).option(`use-dot`,js),handler:async e=>{await legacyHandler({format:`dot`,path:e.path,useDotBin:e.useDotBin,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`d2 [path]`,describe:`generate D2 files (.d2)`,builder:e=>e.positional(`path`,B).option(`outdir`,Ps).option(`use-dot`,js),handler:async e=>{await legacyHandler({format:`d2`,path:e.path,useDotBin:e.useDotBin,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`mermaid [path]`,aliases:[`mmd`],describe:`generate Mermaid files (.mmd)`,builder:e=>e.positional(`path`,B).option(`outdir`,Ps).option(`use-dot`,js),handler:async e=>{await legacyHandler({format:`mermaid`,useDotBin:e.useDotBin,path:e.path,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`plantuml [path]`,aliases:[`puml`],describe:`generate PlantUML files (.puml)`,builder:e=>e.positional(`path`,B).option(`outdir`,Ps).option(`use-dot`,js),handler:async e=>{await legacyHandler({format:`plantuml`,useDotBin:e.useDotBin,path:e.path,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`<custom> [path]`,describe:`run custom generator from likec4 config`,builder:e=>e.positional(`path`,B).option(`project`,Gs).option(`use-dot`,js),handler:async e=>{await customHandler({name:`custom`,path:e.path,project:e.project,useDotBin:e.useDotBin})}}).epilog(`${S.bold(`Examples:`)}
257
+ `))}catch(e){a.e=e}finally{await a.d()}}const codegenCmd=e=>e.command({command:`gen <command> [path]`,aliases:[`generate`,`codegen`],describe:`Generate various artifacts from LikeC4 sources`,builder:e=>e.positional(`path`,U).command(`react [path]`,`generate react component to render likec4 view`,e=>e.positional(`path`,U).option(`project`,Ws).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.jsx, .mjs or .js)`,normalize:!0,coerce:P}).option(`use-dot`,W).option(`use-core-package`,js),async e=>{await reactHandler({project:e.project,useDotBin:e.useDotBin,path:e.path,outfile:e.outfile,useCorePackage:e.useCorePackage}),showSupportUsMessage()}).command({command:`webcomponent [path]`,aliases:[`wc`,`webcomp`],describe:`generate js with webcomponents`,builder:e=>e.positional(`path`,U).option(`project`,Ws).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.mjs or .js)`,normalize:!0,coerce:P}).option(`webcomponent-prefix`,Ps).option(`use-dot`,W),handler:async e=>{await webcomponentHandler({project:e.project,useDotBin:e.useDotBin,path:e.path,outfile:e.outfile,webcomponentPrefix:e.webcomponentPrefix}),showSupportUsMessage()}}).command({command:`model [path]`,aliases:[`ts`],describe:`generate LikeC4Model (.ts)`,builder:e=>e.positional(`path`,U).option(`project`,Ws).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.ts)`,normalize:!0,coerce:P}).option(`skip-layout`,{type:`boolean`,desc:`Skip layout (produce compute-only model, faster)`}).option(`use-dot`,W).option(`use-core-package`,js),handler:async e=>{await modelHandler({path:e.path,useDotBin:e.useDotBin,useCorePackage:e.useCorePackage,outfile:e.outfile,project:e.project,skipLayout:e.skipLayout??!1}),showSupportUsMessage()}}).command({command:`views-data [path]`,aliases:[`views`],describe:`{deprecated} use codegen model`,deprecated:!0,builder:e=>e.positional(`path`,U).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> output .ts file`,normalize:!0,coerce:P}).option(`use-dot`,W),handler:async e=>{await legacyHandler({format:`views`,path:e.path,useDotBin:e.useDotBin,outfile:e.outfile})}}).command({command:`leanix [path]`,describe:`LeanIX bridge: dry-run, inventory snapshot, reconcile`,builder:e=>e.positional(`path`,U).demandCommand(1,`Choose a subcommand: dry-run, inventory, reconcile`).command(`dry-run [path]`,`generate LeanIX bridge artifacts (manifest, dry-run inventory, report)`,e=>e.positional(`path`,U).option(`outdir`,{...Ns,desc:`<dir> output directory for manifest.json, leanix-dry-run.json, report.json`}).option(`project`,Ws).option(`use-dot`,W).example(`${S.green(`$0 gen leanix dry-run -o out/bridge`)}`,S.gray(`Write bridge artifacts to out/bridge`)),async e=>{await leanixDryRunHandler({path:e.path,outdir:e.outdir??P(process.cwd(),`out`,`bridge`),project:e.project,useDotBin:e.useDotBin})}).command(`inventory`,`fetch LeanIX inventory (read-only) and write leanix-inventory-snapshot.json`,e=>e.option(`outdir`,{...Ns,default:P(process.cwd(),`out`,`bridge`),desc:`<dir> output directory for leanix-inventory-snapshot.json`}).option(`likec4-id-attribute`,{type:`string`,desc:`custom LeanIX attribute key for likec4Id (e.g. "likec4Id")`}).example(`${S.green(`$0 gen leanix inventory -o out/bridge`)}`,S.gray(`Requires LEANIX_API_TOKEN`)),async e=>{await leanixInventorySnapshotHandler({outdir:e.outdir??P(process.cwd(),`out`,`bridge`),...e.likec4IdAttribute==null?{}:{likec4IdAttribute:e.likec4IdAttribute}})}).command(`reconcile [path]`,`reconcile manifest with leanix-inventory-snapshot; write reconciliation-report.json`,e=>e.positional(`path`,U).option(`outdir`,{...Ns,default:P(process.cwd(),`out`,`bridge`),desc:`<dir> directory with manifest.json and leanix-inventory-snapshot.json`}).option(`project`,Ws).option(`use-dot`,W).example(`${S.green(`$0 gen leanix reconcile -o out/bridge`)}`,S.gray(`Reads manifest + snapshot from outdir; optional workspace for name+type matching`)),async e=>{await leanixReconcileHandler({path:e.path,outdir:e.outdir??P(process.cwd(),`out`,`bridge`),project:e.project,useDotBin:e.useDotBin})}),handler:async()=>{}}).command({command:`dot [path]`,describe:`generate graphviz files (.dot)`,builder:e=>e.positional(`path`,U).option(`outdir`,Ns).option(`use-dot`,W),handler:async e=>{await legacyHandler({format:`dot`,path:e.path,useDotBin:e.useDotBin,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`d2 [path]`,describe:`generate D2 files (.d2)`,builder:e=>e.positional(`path`,U).option(`outdir`,Ns).option(`use-dot`,W),handler:async e=>{await legacyHandler({format:`d2`,path:e.path,useDotBin:e.useDotBin,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`mermaid [path]`,aliases:[`mmd`],describe:`generate Mermaid files (.mmd)`,builder:e=>e.positional(`path`,U).option(`outdir`,Ns).option(`use-dot`,W),handler:async e=>{await legacyHandler({format:`mermaid`,useDotBin:e.useDotBin,path:e.path,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`plantuml [path]`,aliases:[`puml`],describe:`generate PlantUML files (.puml)`,builder:e=>e.positional(`path`,U).option(`outdir`,Ns).option(`use-dot`,W),handler:async e=>{await legacyHandler({format:`plantuml`,useDotBin:e.useDotBin,path:e.path,outdir:e.outdir}),showSupportUsMessage()}}).command({command:`<custom> [path]`,describe:`run custom generator from likec4 config`,builder:e=>e.positional(`path`,U).option(`project`,Ws).option(`use-dot`,W),handler:async e=>{await customHandler({name:`custom`,path:e.path,project:e.project,useDotBin:e.useDotBin})}}).epilog(`${S.bold(`Examples:`)}
258
258
  likec4 gen react -o dist/likec4-views.mjs ./src/likec4
259
259
  likec4 gen model -o likec4-model.ts
260
260
  likec4 gen leanix dry-run -o out/bridge
@@ -265,9 +265,9 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
265
265
  likec4 gen mmd --outdir assets/
266
266
  likec4 gen plantuml --outdir assets/
267
267
  likec4 gen dot -o out .
268
- `),handler:async e=>{await customHandler({name:e.command,path:e.path,project:e.project,useDotBin:e.useDotBin})}}),pc=new Set([`node_modules`,`.git`]);function isSourceFile(e){return e.endsWith(`.c4`)||e.endsWith(`.likec4`)}function joinNonEmptyFiles(e,t=`
268
+ `),handler:async e=>{await customHandler({name:e.command,path:e.path,project:e.project,useDotBin:e.useDotBin})}}),fc=new Set([`node_modules`,`.git`]);function isSourceFile(e){return e.endsWith(`.c4`)||e.endsWith(`.likec4`)}function joinNonEmptyFiles(e,t=`
269
269
 
270
- `){return e.filter(e=>e.trim()!==``).join(t)}const mc=`No project or empty model`,hc=`No views could be exported`;function getDrawioEpilog(){return`${S.bold(`Examples:`)}
270
+ `){return e.filter(e=>e.trim()!==``).join(t)}const pc=`No project or empty model`,mc=`No views could be exported`;function getDrawioEpilog(){return`${S.bold(`Examples:`)}
271
271
  ${S.green(`$0 export drawio`)}
272
272
  ${S.gray(`Export each view to a separate .drawio file`)}
273
273
 
@@ -281,13 +281,13 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
281
281
  ${S.gray(`Export with raw XML (no compression) for draw.io desktop compatibility`)}
282
282
 
283
283
  ${S.green(`$0 export drawio --profile leanix -o ./out`)}
284
- ${S.gray(`Export with bridge-managed metadata (likec4Id, likec4ViewId, etc.) for LeanIX interoperability`)}`}function toError(e){return e instanceof Error?e:Error(a(e))}function logAndRethrow(e,t,n){let r=toError(n);throw e.error(t,{error:r}),r}async function readWorkspaceSourceContent(e,t){let n=[],r=new Set;async function walk(e,i){if(i>=50)return;let a=await Bt(e).catch(()=>null);if(a==null||r.has(a))return;r.add(a);let s=await zt(e,{withFileTypes:!0}).catch(n=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readdir failed`,{dir:e,err:n}),[]));for(let r of s){let a=Jt(e,r.name);switch(!0){case r.isDirectory():pc.has(r.name)||await walk(a,i+1);break;case r.isSymbolicLink():if((await Ht(a).catch(()=>null))?.isFile()&&isSourceFile(r.name)){let e=await Rt(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readFile failed`,{file:a,err:e}),``));e&&n.push(e)}break;case r.isFile()&&isSourceFile(r.name):{let e=await Rt(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readFile failed`,{file:a,err:e}),``));e&&n.push(e);break}}}}return await walk(e,0),joinNonEmptyFiles(n)}async function getSourceContentIfRoundtrip(e,t,n){if(t)return readWorkspaceSourceContent(M(e),n)}function buildDrawioExportOverrides(e,t,n){let r=e?{compressed:!1}:{compressed:!0};return t===`leanix`&&(r.profile=`leanix`,r.projectId=n),r}function buildOptionsByViewId(e,t,n,r,i){let a=e.map(e=>String(e.$view.id)),s=buildDrawioExportOverrides(n,r,i);return xt(a,t,s)}async function exportDrawioAllInOne(e){let{viewmodels:t,outdir:n,workspacePath:r,roundtrip:i,uncompressed:a,profile:s,projectId:c,logger:l}=e,u=buildOptionsByViewId(t,await getSourceContentIfRoundtrip(r,i,l),a,s,c),f=wt(t,u),p=M(n,Et);await Ut(p,f),l.info(`${S.dim(`generated`)} ${Yt(process.cwd(),p)} (${t.length} tab(s))`)}async function writeViewToFile(e,t,n,r){let i=String(e.$view.id);try{let a=yt(e,t[i]),s=M(n,i+`.drawio`);return await It(Gt(s),{recursive:!0}),await Ut(s,a),r.info(`${S.dim(`generated`)} ${Yt(process.cwd(),s)}`),!0}catch(e){return r.error(`Failed to export view ${i}`,{error:toError(e)}),!1}}async function exportDrawioPerView(e){let{viewmodels:t,outdir:n,workspacePath:r,roundtrip:i,uncompressed:a,profile:s,projectId:c,logger:l}=e,u=buildOptionsByViewId(t,await getSourceContentIfRoundtrip(r,i,l),a,s,c),f=0;for(let e of t)await writeViewToFile(e,u,n,l)&&f++;return{succeeded:f}}async function runExportDrawio(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1}));e.project||i.ensureSingleProject();let a=e.project==null?void 0:i.languageServices.projectsManager.ensureProjectId(e.project),s=await i.layoutedModel(a);if(s===At.EMPTY)throw t.error(mc),Error(mc);let c=[...s.views()];if(c.length===0)throw t.error(`No views to export`),Error(hc);await It(e.outdir,{recursive:!0});let l=String(s.projectId),u={viewmodels:c,outdir:e.outdir,workspacePath:e.path,roundtrip:e.roundtrip,uncompressed:e.uncompressed,profile:e.profile,projectId:l,logger:t};if(e.allInOne)try{await exportDrawioAllInOne(u)}catch(e){logAndRethrow(t,`Failed to export DrawIO`,e)}else{let{succeeded:e}=await exportDrawioPerView(u);if(e===0)throw t.error(hc),Error(hc);t.info(`${S.dim(`total`)} ${e} DrawIO file(s)`)}r.stopAndLog(`✓ export drawio in `)}catch(e){n.e=e}finally{await n.d()}}function drawioCmd(e){return e.command({command:`drawio [path]`,describe:`export view(s) to DrawIO (.drawio) for editing in draw.io`,builder:e=>e.positional(`path`,B).option(`outdir`,{alias:`o`,type:`string`,desc:`<dir> output directory for .drawio files`,normalize:!0,coerce:M}).option(`all-in-one`,{type:`boolean`,default:!1,desc:`write one .drawio file with all views as tabs (diagrams)`}).option(`roundtrip`,{type:`boolean`,default:!1,desc:`apply layout/stroke/waypoints from DrawIO round-trip comment blocks in .c4 source`}).option(`uncompressed`,{type:`boolean`,default:!1,desc:`write diagram XML uncompressed inside .drawio (larger file; use if draw.io desktop fails to open compressed export)`}).option(`profile`,{type:`string`,choices:[`default`,`leanix`],default:`default`,desc:`export profile: default (round-trip) or leanix (bridge-managed metadata for LeanIX interoperability)`}).options({project:Gs,"use-dot":js}).epilog(getDrawioEpilog()),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportDrawio({path:e.path,outdir:e.outdir??e.path,allInOne:!!e.allInOne,roundtrip:!!e.roundtrip,uncompressed:!!e.uncompressed,profile:e.profile===`leanix`?`leanix`:`default`,project:e.project,useDot:!!e[`use-dot`]},t)}})}function resolveServerUrl(e){if(e.resolvedUrls)return Ze(e.resolvedUrls.network)??Ze(e.resolvedUrls.local)}function printServerUrls(e){if(!e.resolvedUrls)throw Error(`Vite server is not ready, no resolvedUrls`);boxen([S.green(`LikeC4 served at:`),``,S.dim(`Local: `)+e.resolvedUrls.local.join(`
284
+ ${S.gray(`Export with bridge-managed metadata (likec4Id, likec4ViewId, etc.) for LeanIX interoperability`)}`}function toError(e){return e instanceof Error?e:Error(a(e))}function logAndRethrow(e,t,n){let r=toError(n);throw e.error(t,{error:r}),r}async function readWorkspaceSourceContent(e,t){let n=[],r=new Set;async function walk(e,i){if(i>=50)return;let a=await Rt(e).catch(()=>null);if(a==null||r.has(a))return;r.add(a);let s=await Lt(e,{withFileTypes:!0}).catch(n=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readdir failed`,{dir:e,err:n}),[]));for(let r of s){let a=Kt(e,r.name);switch(!0){case r.isDirectory():fc.has(r.name)||await walk(a,i+1);break;case r.isSymbolicLink():if((await Bt(a).catch(()=>null))?.isFile()&&isSourceFile(r.name)){let e=await It(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readFile failed`,{file:a,err:e}),``));e&&n.push(e)}break;case r.isFile()&&isSourceFile(r.name):{let e=await It(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${S.dim(`Roundtrip:`)} readFile failed`,{file:a,err:e}),``));e&&n.push(e);break}}}}return await walk(e,0),joinNonEmptyFiles(n)}async function getSourceContentIfRoundtrip(e,t,n){if(t)return readWorkspaceSourceContent(P(e),n)}function buildDrawioExportOverrides(e,t,n){let r=e?{compressed:!1}:{compressed:!0};return t===`leanix`&&(r.profile=`leanix`,r.projectId=n),r}function buildOptionsByViewId(e,t,n,r,i){let a=e.map(e=>String(e.$view.id)),s=buildDrawioExportOverrides(n,r,i);return yt(a,t,s)}async function exportDrawioAllInOne(e){let{viewmodels:t,outdir:n,workspacePath:r,roundtrip:i,uncompressed:a,profile:s,projectId:c,logger:l}=e,u=buildOptionsByViewId(t,await getSourceContentIfRoundtrip(r,i,l),a,s,c),f=St(t,u),p=P(n,wt);await Vt(p,f),l.info(`${S.dim(`generated`)} ${qt(process.cwd(),p)} (${t.length} tab(s))`)}async function writeViewToFile(e,t,n,r){let i=String(e.$view.id);try{let a=_t(e,t[i]),s=P(n,i+`.drawio`);return await Pt(Ut(s),{recursive:!0}),await Vt(s,a),r.info(`${S.dim(`generated`)} ${qt(process.cwd(),s)}`),!0}catch(e){return r.error(`Failed to export view ${i}`,{error:toError(e)}),!1}}async function exportDrawioPerView(e){let{viewmodels:t,outdir:n,workspacePath:r,roundtrip:i,uncompressed:a,profile:s,projectId:c,logger:l}=e,u=buildOptionsByViewId(t,await getSourceContentIfRoundtrip(r,i,l),a,s,c),f=0;for(let e of t)await writeViewToFile(e,u,n,l)&&f++;return{succeeded:f}}async function runExportDrawio(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1}));e.project||i.ensureSingleProject();let a=e.project==null?void 0:i.languageServices.projectsManager.ensureProjectId(e.project),s=await i.layoutedModel(a);if(s===Ot.EMPTY)throw t.error(pc),Error(pc);let c=[...s.views()];if(c.length===0)throw t.error(`No views to export`),Error(mc);await Pt(e.outdir,{recursive:!0});let l=String(s.projectId),u={viewmodels:c,outdir:e.outdir,workspacePath:e.path,roundtrip:e.roundtrip,uncompressed:e.uncompressed,profile:e.profile,projectId:l,logger:t};if(e.allInOne)try{await exportDrawioAllInOne(u)}catch(e){logAndRethrow(t,`Failed to export DrawIO`,e)}else{let{succeeded:e}=await exportDrawioPerView(u);if(e===0)throw t.error(mc),Error(mc);t.info(`${S.dim(`total`)} ${e} DrawIO file(s)`)}r.stopAndLog(`✓ export drawio in `)}catch(e){n.e=e}finally{await n.d()}}function drawioCmd(e){return e.command({command:`drawio [path]`,describe:`export view(s) to DrawIO (.drawio) for editing in draw.io`,builder:e=>e.positional(`path`,U).option(`outdir`,{alias:`o`,type:`string`,desc:`<dir> output directory for .drawio files`,normalize:!0,coerce:P}).option(`all-in-one`,{type:`boolean`,default:!1,desc:`write one .drawio file with all views as tabs (diagrams)`}).option(`roundtrip`,{type:`boolean`,default:!1,desc:`apply layout/stroke/waypoints from DrawIO round-trip comment blocks in .c4 source`}).option(`uncompressed`,{type:`boolean`,default:!1,desc:`write diagram XML uncompressed inside .drawio (larger file; use if draw.io desktop fails to open compressed export)`}).option(`profile`,{type:`string`,choices:[`default`,`leanix`],default:`default`,desc:`export profile: default (round-trip) or leanix (bridge-managed metadata for LeanIX interoperability)`}).options({project:Ws,"use-dot":W}).epilog(getDrawioEpilog()),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportDrawio({path:e.path,outdir:e.outdir??e.path,allInOne:!!e.allInOne,roundtrip:!!e.roundtrip,uncompressed:!!e.uncompressed,profile:e.profile===`leanix`?`leanix`:`default`,project:e.project,useDot:!!e[`use-dot`]},t)}})}function resolveServerUrl(e){if(e.resolvedUrls)return Ye(e.resolvedUrls.network)??Ye(e.resolvedUrls.local)}function printServerUrls(e){if(!e.resolvedUrls)throw Error(`Vite server is not ready, no resolvedUrls`);boxen([S.green(`LikeC4 served at:`),``,S.dim(`Local: `)+e.resolvedUrls.local.join(`
285
285
  `+``.padEnd(9,` `)),e.resolvedUrls.network.length?S.dim(`Network: `)+e.resolvedUrls.network.join(`
286
- `+``.padEnd(9,` `)):void 0].filter(e=>tt(e)).join(`
287
- `))}var Locked=class extends Error{constructor(e){super(`${e} is locked`)}};const gc={old:new Set,young:new Set},_c=new Set,vc=1024,yc=65535;let bc;const getLocalHosts=()=>{let e=mn.networkInterfaces(),t=new Set([void 0,`0.0.0.0`]);for(let n of Object.values(e))for(let e of n)t.add(e.address);return t},checkAvailablePort=e=>new Promise((t,n)=>{let r=Dn.createServer();r.unref(),r.on(`error`,n),r.listen(e,()=>{let{port:e}=r.address();r.close(()=>{t(e)})})}),getAvailablePort=async(e,t)=>{if(e.host||e.port===0)return checkAvailablePort(e);for(let n of t)try{await checkAvailablePort({port:e.port,host:n})}catch(e){if(![`EADDRNOTAVAIL`,`EINVAL`].includes(e.code))throw e}return e.port},isLockedPort=e=>gc.old.has(e)||gc.young.has(e)||_c.has(e),portCheckSequence=function*(e){e&&(yield*e),yield 0};async function getPorts(e){let t,n=new Set;if(e&&(e.port&&(t=typeof e.port==`number`?[e.port]:e.port),e.exclude)){let t=e.exclude;if(typeof t[Symbol.iterator]!=`function`)throw TypeError("The `exclude` option must be an iterable.");for(let e of t){if(typeof e!=`number`)throw TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(e))throw TypeError(`Number ${e} in the exclude option is not a safe integer and can't be used`)}n=new Set(t)}let{reserve:r,...i}=e??{};bc===void 0&&(bc=setTimeout(()=>{bc=void 0,gc.old=gc.young,gc.young=new Set},15e3),bc.unref&&bc.unref());let a=getLocalHosts();for(let e of portCheckSequence(t))try{if(n.has(e))continue;let t=await getAvailablePort({...i,port:e},a);for(;isLockedPort(t);){if(e!==0)throw new Locked(e);t=await getAvailablePort({...i,port:e},a)}return r?_c.add(t):gc.young.add(t),t}catch(e){if(![`EADDRINUSE`,`EACCES`].includes(e.code)&&!(e instanceof Locked))throw e}throw Error(`No available ports found`)}function portNumbers(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw TypeError("`from` and `to` must be integer numbers");if(e<vc||e>yc)throw RangeError(`'from' must be between ${vc} and ${yc}`);if(t<vc||t>yc)throw RangeError(`'to' must be between ${vc} and ${yc}`);if(e>t)throw RangeError("`to` must be greater than or equal to `from`");let generator=function*(e,t){for(let n=e;n<=t;n++)yield n};return generator(e,t)}function validatePort(e,t){if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Invalid HMR port from ${t}: ${e}. Must be an integer between 1 and 65535.`)}async function resolveHmrPort(e,t){if(t){if(e!==void 0)return validatePort(e,`explicitPort`),e;if(An.HMR_PORT){let e=Number.parseInt(An.HMR_PORT,10);return validatePort(e,`HMR_PORT`),e}return getPorts({port:portNumbers(24678,24690)})}}async function viteDev({buildWebcomponent:e=!1,hmr:t=!0,webcomponentPrefix:n=`likec4`,title:r,languageServices:i,likec4AssetsDir:s,openBrowser:c,listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m,...h}){s??=await Lt(Jt(hn(),`.likec4-assets-`));let{isDev:g,...v}=await viteConfig({...h,languageServices:i,likec4AssetsDir:s,webcomponentPrefix:n,title:r}),y=v.customLogger;u??=An.PORT?parseInt(An.PORT,10):void 0,u||=await getPorts({port:[5173,5174,...portNumbers(61e3,61010),...portNumbers(62002,62010)]});let b=await mkTempPublicDir();p&&await copyUserPublicDir(p,b);let ee=l??(isInsideContainer()?`0.0.0.0`:`localhost`),te=await resolveHmrPort(f,t);if(t&&te!==void 0){let e=f?` (explicit)`:An.HMR_PORT?` (env)`:` (auto-discovered)`;y.info(`Enabling HMR: localhost:${te}${e}`),v.plugins=[Jn(),...v.plugins],isInsideContainer()&&y.info(S.yellow(`ensure port ${te} is published from container`))}else t||y.info(`Disabling HMR`);let ne=await Wn({...v,define:t?{...v.define,"process.env.NODE_ENV":`"development"`}:v.define,mode:t?`development`:v.mode,publicDir:b,optimizeDeps:{holdUntilCrawlEnd:!1,ignoreOutdatedRequests:!0,include:[`react`,`react-dom`,`react/compiler-runtime`,`react/jsx-runtime`,`react-dom/client`,`use-sync-external-store/shim/with-selector`,`likec4/vite-plugin/internal`,`@likec4/core/styles`,`@likec4/core/geometry`,`@likec4/core/utils`,`@likec4/core/compute-view`,`@likec4/core/types`,`@likec4/core/model`,`@likec4/core`,`likec4/react`,`likec4/model`]},server:{host:ee,allowedHosts:m&&m.length>0?m:!0,port:u,hmr:t&&{overlay:!0,...te===void 0?{}:{port:te}},fs:{strict:!1},open:c??(!g&&!isInsideContainer())}});if(await ne.listen(),e){let e=viteWebcomponentConfig({webcomponentPrefix:n,languageServices:i,outDir:b,base:v.base});y.info(`Building webcomponent`),await Un({...e,logLevel:`warn`}).catch(e=>{y.warn(a(e)),y.warn(`webcomponent build failed, ignoring error and continue`)})}else y.info(`Skip webcomponent build`);return ne}function createExportViewUrl({viewId:e,padding:t,theme:n,dynamicVariant:r,format:i=`png`,notation:a=!1,description:s=!1}){return he(`export/${encodeURIComponent(e)}/`,{padding:t,theme:n,dynamic:r,...a?{notation:!0}:{},...s?{description:!0}:{},...i===`jpeg`?{format:`jpeg`}:{}})}async function takeScreenshot({browserContext:e,views:t,output:n,logger:r,timeout:i,maxAttempts:a,dynamicVariant:s,outputType:c,theme:l,format:u=`png`,quality:f,notation:p=!1,description:m=!1}){let h,g=t.map(e=>({view:e,attempt:1})),v=[],y;for(;y=g.shift();){let{view:t,attempt:b}=y,ee=`export/${encodeURIComponent(t.id)}/`;try{if(b>1){h&&=(h.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),void 0);let e=ut(b*200,{min:200,max:1e3});r.info(S.cyan(ee)+S.dim(` attempt ${b} of ${a} after ${e}ms`)),await Yn(e)}else t.hasLayoutDrift&&r.warn(S.yellow(`Drift detected, manual layout can not be applied, view may be invalid: `)+S.red(t.id));let g=`.`;c===`relative`&&(g=t.sourcePath??`.`,g=g.includes(`/`)?g.slice(0,g.lastIndexOf(`/`)):`.`);let y=u===`jpeg`?`.jpg`:`.png`,te=M(n,g,`${t.id}${y}`);h??=await e.newPage();let ne=t.bounds;s===`sequence`&&t._type===`dynamic`&&(ne=t.sequenceLayout.bounds),await h.setViewportSize({width:ne.width+40+20,height:ne.height+40+20}),await h.goto(createExportViewUrl({viewId:t.id,padding:20,theme:l,dynamicVariant:s,format:u,notation:p,description:m})),r.info(S.cyan(ee)+S.dim(` -> ${Yt(n,te)}`)),await h.waitForSelector(`.react-flow.initialized`);let x=h.getByTestId(`export-page`),re=await x.boundingBox();if(re){let e=Math.ceil(re.width),t=Math.ceil(re.height),n=h.viewportSize();(!n||e>n.width||t>n.height)&&await h.setViewportSize({width:e,height:t})}t.nodes.some(e=>mt(e.icon)&&e.icon.toLowerCase().startsWith(`http`))&&await waitAllImages(h,i),await x.screenshot({animations:`disabled`,path:te,type:u===`jpeg`?`jpeg`:`png`,...u===`jpeg`?{quality:f??80,omitBackground:!1}:{omitBackground:!0}}),v.push({view:t,path:te})}catch(e){h?.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),r.error(S.red(`failed `+ee+`
286
+ `+``.padEnd(9,` `)):void 0].filter(e=>$e(e)).join(`
287
+ `))}var Locked=class extends Error{constructor(e){super(`${e} is locked`)}};const hc={old:new Set,young:new Set},gc=new Set,_c=1024,vc=65535;let yc;const getLocalHosts=()=>{let e=hn.networkInterfaces(),t=new Set([void 0,`0.0.0.0`]);for(let n of Object.values(e))for(let e of n)t.add(e.address);return t},checkAvailablePort=e=>new Promise((t,n)=>{let r=On.createServer();r.unref(),r.on(`error`,n),r.listen(e,()=>{let{port:e}=r.address();r.close(()=>{t(e)})})}),getAvailablePort=async(e,t)=>{if(e.host||e.port===0)return checkAvailablePort(e);for(let n of t)try{await checkAvailablePort({port:e.port,host:n})}catch(e){if(![`EADDRNOTAVAIL`,`EINVAL`].includes(e.code))throw e}return e.port},isLockedPort=e=>hc.old.has(e)||hc.young.has(e)||gc.has(e),portCheckSequence=function*(e){e&&(yield*e),yield 0};async function getPorts(e){let t,n=new Set;if(e&&(e.port&&(t=typeof e.port==`number`?[e.port]:e.port),e.exclude)){let t=e.exclude;if(typeof t[Symbol.iterator]!=`function`)throw TypeError("The `exclude` option must be an iterable.");for(let e of t){if(typeof e!=`number`)throw TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(e))throw TypeError(`Number ${e} in the exclude option is not a safe integer and can't be used`)}n=new Set(t)}let{reserve:r,...i}=e??{};yc===void 0&&(yc=setTimeout(()=>{yc=void 0,hc.old=hc.young,hc.young=new Set},15e3),yc.unref&&yc.unref());let a=getLocalHosts();for(let e of portCheckSequence(t))try{if(n.has(e))continue;let t=await getAvailablePort({...i,port:e},a);for(;isLockedPort(t);){if(e!==0)throw new Locked(e);t=await getAvailablePort({...i,port:e},a)}return r?gc.add(t):hc.young.add(t),t}catch(e){if(![`EADDRINUSE`,`EACCES`].includes(e.code)&&!(e instanceof Locked))throw e}throw Error(`No available ports found`)}function portNumbers(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw TypeError("`from` and `to` must be integer numbers");if(e<_c||e>vc)throw RangeError(`'from' must be between ${_c} and ${vc}`);if(t<_c||t>vc)throw RangeError(`'to' must be between ${_c} and ${vc}`);if(e>t)throw RangeError("`to` must be greater than or equal to `from`");let generator=function*(e,t){for(let n=e;n<=t;n++)yield n};return generator(e,t)}function validatePort(e,t){if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Invalid HMR port from ${t}: ${e}. Must be an integer between 1 and 65535.`)}async function resolveHmrPort(e,t){if(t){if(e!==void 0)return validatePort(e,`explicitPort`),e;if(jn.HMR_PORT){let e=Number.parseInt(jn.HMR_PORT,10);return validatePort(e,`HMR_PORT`),e}return getPorts({port:portNumbers(24678,24690)})}}async function viteDev({buildWebcomponent:e=!1,hmr:t=!0,webcomponentPrefix:n=`likec4`,title:r,languageServices:i,likec4AssetsDir:s,openBrowser:c,listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m,...h}){s??=await Ft(Kt(gn(),`.likec4-assets-`));let{isDev:g,...v}=await viteConfig({...h,languageServices:i,likec4AssetsDir:s,webcomponentPrefix:n,title:r}),y=v.customLogger;u??=jn.PORT?parseInt(jn.PORT,10):void 0,u||=await getPorts({port:[5173,5174,...portNumbers(61e3,61010),...portNumbers(62002,62010)]});let b=await mkTempPublicDir();p&&await copyUserPublicDir(p,b);let ee=l??(isInsideContainer()?`0.0.0.0`:`localhost`),te=await resolveHmrPort(f,t);if(t&&te!==void 0){let e=f?` (explicit)`:jn.HMR_PORT?` (env)`:` (auto-discovered)`;y.info(`Enabling HMR: localhost:${te}${e}`),v.plugins=[Yn(),...v.plugins],isInsideContainer()&&y.info(S.yellow(`ensure port ${te} is published from container`))}else t||y.info(`Disabling HMR`);let ne=await Gn({...v,define:t?{...v.define,"process.env.NODE_ENV":`"development"`}:v.define,mode:t?`development`:v.mode,publicDir:b,optimizeDeps:{holdUntilCrawlEnd:!1,ignoreOutdatedRequests:!0,include:[`react`,`react-dom`,`react/compiler-runtime`,`react/jsx-runtime`,`react-dom/client`,`use-sync-external-store/shim/with-selector`,`likec4/vite-plugin/internal`,`@likec4/core/styles`,`@likec4/core/geometry`,`@likec4/core/utils`,`@likec4/core/compute-view`,`@likec4/core/types`,`@likec4/core/model`,`@likec4/core`,`likec4/react`,`likec4/model`]},server:{host:ee,allowedHosts:m&&m.length>0?m:!0,port:u,hmr:t&&{overlay:!0,...te===void 0?{}:{port:te}},fs:{strict:!1},open:c??(!g&&!isInsideContainer())}});if(await ne.listen(),e){let e=viteWebcomponentConfig({webcomponentPrefix:n,languageServices:i,outDir:b,base:v.base});y.info(`Building webcomponent`),await Wn({...e,logLevel:`warn`}).catch(e=>{y.warn(a(e)),y.warn(`webcomponent build failed, ignoring error and continue`)})}else y.info(`Skip webcomponent build`);return ne}function createExportViewUrl({viewId:e,padding:t,theme:n,dynamicVariant:r,format:i=`png`,notation:a=!1,description:s=!1}){return he(`export/${encodeURIComponent(e)}/`,{padding:t,theme:n,dynamic:r,...a?{notation:!0}:{},...s?{description:!0}:{},...i===`jpeg`?{format:`jpeg`}:{}})}async function takeScreenshot({browserContext:e,views:t,output:n,logger:r,timeout:i,maxAttempts:a,dynamicVariant:s,outputType:c,theme:l,format:u=`png`,quality:f,notation:p=!1,description:m=!1}){let h,g=t.map(e=>({view:e,attempt:1})),v=[],y;for(;y=g.shift();){let{view:t,attempt:b}=y,ee=`export/${encodeURIComponent(t.id)}/`;try{if(b>1){h&&=(h.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),void 0);let e=st(b*200,{min:200,max:1e3});r.info(S.cyan(ee)+S.dim(` attempt ${b} of ${a} after ${e}ms`)),await Xn(e)}else t.hasLayoutDrift&&r.warn(S.yellow(`Drift detected, manual layout can not be applied, view may be invalid: `)+S.red(t.id));let g=`.`;c===`relative`&&(g=t.sourcePath??`.`,g=g.includes(`/`)?g.slice(0,g.lastIndexOf(`/`)):`.`);let y=u===`jpeg`?`.jpg`:`.png`,te=P(n,g,`${t.id}${y}`);h??=await e.newPage();let ne=t.bounds;s===`sequence`&&t._type===`dynamic`&&(ne=t.sequenceLayout.bounds),await h.setViewportSize({width:ne.width+40+20,height:ne.height+40+20}),await h.goto(createExportViewUrl({viewId:t.id,padding:20,theme:l,dynamicVariant:s,format:u,notation:p,description:m})),r.info(S.cyan(ee)+S.dim(` -> ${qt(n,te)}`)),await h.waitForSelector(`.react-flow.initialized`);let x=h.getByTestId(`export-page`),re=await x.boundingBox();if(re){let e=Math.ceil(re.width),t=Math.ceil(re.height),n=h.viewportSize();(!n||e>n.width||t>n.height)&&await h.setViewportSize({width:e,height:t})}t.nodes.some(e=>ft(e.icon)&&e.icon.toLowerCase().startsWith(`http`))&&await waitAllImages(h,i),await x.screenshot({animations:`disabled`,path:te,type:u===`jpeg`?`jpeg`:`png`,...u===`jpeg`?{quality:f??80,omitBackground:!1}:{omitBackground:!0}}),v.push({view:t,path:te})}catch(e){h?.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),r.error(S.red(`failed `+ee+`
288
288
  `+e)),b<a&&(g.push({view:t,attempt:b+1}),r.info(S.dim(`retry ${ee}`))),h=void 0}}return v}async function waitAllImages(e,t){let n=await e.locator(`//img`).all();if(!n.length)return;let r=n.map(e=>e.evaluate(e=>e.complete||new Promise(t=>{e.onload=t,e.onerror=t}),{timeout:Math.max(15e3,t)}));await Promise.allSettled(r)}async function exportViewsToPNG({logger:e,serverUrl:t,theme:n=`light`,timeoutMs:r=15e3,views:i,output:a,outputType:s=`relative`,maxAttempts:c=3,chromiumSandbox:l=!1,sequence:u=!1,format:f=`png`,quality:p,notation:m=!1,description:h=!1}){e.info(`${S.dim(`output`)} ${a}`),e.info(`${S.dim(`base url`)} ${t}\n`);let{chromium:g}=await import(`playwright`),v=g.executablePath();e.info(S.cyan(`Start chromium`)+` `+S.dim(v));let y=await g.launch({chromiumSandbox:l,headless:!0});e.info(S.cyan(`Color scheme: `)+n+`
289
- `);let b=await y.newContext({deviceScaleFactor:2,colorScheme:n,baseURL:t,bypassCSP:!0,ignoreHTTPSErrors:!0,isMobile:!1});b.setDefaultNavigationTimeout(r),b.setDefaultTimeout(r);try{return await takeScreenshot({browserContext:b,views:i,output:a,outputType:s,logger:e,maxAttempts:c,dynamicVariant:u?`sequence`:`diagram`,timeout:r,theme:n,format:f,quality:p,notation:m,description:h})}finally{e.info(S.cyan(`close chromium`)),await b.close(),await y.close()}}async function runExportPng(e,t){try{var n=_usingCtx();let{path:r,useDotBin:i,project:a,theme:s=`light`,output:c,outputType:l,serverUrl:u,ignore:f=!1,timeoutMs:p=15e3,maxAttempts:m=3,filter:h,sequence:g=!1,chromiumSandbox:v=!1,format:y=`png`,quality:b,notation:ee=!1,description:te=!1}=e,ne=n.a(await x(r,{graphviz:i?`binary`:`wasm`,watch:!1})),re=c??ne.workspace,ie,ae=u,oe=[...ne.languageServices.projects()];if(a&&!oe.some(e=>e.id===a))throw t.error(`project not found: ${a}`),Error(`project not found: ${a}`);try{if(!ae&&(t.info(S.cyan(`start preview server`)),ie=await viteDev({languageServices:ne,buildWebcomponent:!1,openBrowser:!1,hmr:!1}),ae=resolveServerUrl(ie),!ae))throw t.error(`Vite server is not ready, no resolvedUrls`),Error(`Vite server is not ready, no resolvedUrls`);for(let e of oe){if(a&&e.id!==a)continue;oe.length>1&&(t.info(S.dim(`---------`)),t.info(`${S.dim(`project:`)} ${e.id}`),t.info(`${S.dim(`folder:`)} ${e.folder.fsPath}`));let n=await ne.diagrams(e.id);if(h&&Xe(h,1)&&Xe(n,1)){let e=(0,nr.default)(h);t.info(`${S.cyan(`filter`)} ${S.dim(JSON.stringify(h))}`),n=n.filter(n=>e(n.id)?(t.info(`${S.green(`include`)} ${n.id} ✅`),!0):(t.info(`${S.gray(`skip`)} ${S.dim(n.id)}`),!1))}if(!Xe(n,1)){t.warn(`no views found`);continue}let r=oe.length>1?ge(_e(ae,`project`,e.id)):ae,i=oe.length>1?_e(re,e.id):re,c=Rn(),u=await exportViewsToPNG({logger:t,serverUrl:r,theme:s,timeoutMs:p,views:n,output:i,outputType:l,maxAttempts:m,sequence:g,chromiumSandbox:v,format:y,quality:b,notation:ee,description:te}),{pretty:x}=inMillis(c);if(u.length>0&&t.info(S.green(`exported ${u.length} views in ${x}`)+`
290
- `),u.length!==n.length&&(f&&u.length>0?t.info(S.dim(`ignore`)+` `+S.red(`failed ${n.length-u.length} out of ${n.length} views`)):t.error(S.red(`failed ${n.length-u.length} out of ${n.length} views`))),u.length!==n.length&&(u.length===0||!f))throw Error(`Failed ${n.length-u.length} out of ${n.length} views`)}}finally{ie&&(t.info(S.cyan(`stop server`)),await ie.close().catch(e=>{t.error(e)}))}}catch(e){n.e=e}finally{await n.d()}}async function pngHandler(e){await runExportPng(e,createLikeC4Logger(`c4:export`))}function pngCmd(e){return e.command({command:`png [path]`,describe:`export views to PNG`,builder:e=>e.positional(`path`,B).options({outdir:{alias:[`o`,`output`],type:`string`,desc:`output directory for PNG files; if not specified, images are saved next to sources`,normalize:!0,nargs:1,coerce:M},project:Gs,theme:{choices:[`light`,`dark`],desc:`color-scheme to use, defaults to light`,conflicts:[`dark`,`light`],nargs:1},dark:{type:`boolean`,desc:`use dark theme, shortcut for --theme=dark`,conflicts:[`theme`,`light`]},light:{type:`boolean`,desc:`use light theme, shortcut for --theme=light`,conflicts:[`theme`,`dark`]},"use-dot":js,seq:{alias:[`sequence`],type:`boolean`,desc:`use sequence layout for dynamic views`},flat:{alias:[`flatten`],type:`boolean`,desc:`flatten all images in outdir ignoring sources structure`},filter:{alias:`f`,array:!0,string:!0,desc:`include views with ids matching given patterns
289
+ `);let b=await y.newContext({deviceScaleFactor:2,colorScheme:n,baseURL:t,bypassCSP:!0,ignoreHTTPSErrors:!0,isMobile:!1});b.setDefaultNavigationTimeout(r),b.setDefaultTimeout(r);try{return await takeScreenshot({browserContext:b,views:i,output:a,outputType:s,logger:e,maxAttempts:c,dynamicVariant:u?`sequence`:`diagram`,timeout:r,theme:n,format:f,quality:p,notation:m,description:h})}finally{e.info(S.cyan(`close chromium`)),await b.close(),await y.close()}}async function runExportPng(e,t){try{var n=_usingCtx();let{path:r,useDotBin:i,project:a,theme:s=`light`,output:c,outputType:l,serverUrl:u,ignore:f=!1,timeoutMs:p=15e3,maxAttempts:m=3,filter:h,sequence:g=!1,chromiumSandbox:v=!1,format:y=`png`,quality:b,notation:ee=!1,description:te=!1}=e,ne=n.a(await x(r,{graphviz:i?`binary`:`wasm`,watch:!1})),re=c??ne.workspace,ie,ae=u,oe=[...ne.languageServices.projects()];if(a&&!oe.some(e=>e.id===a))throw t.error(`project not found: ${a}`),Error(`project not found: ${a}`);try{if(!ae&&(t.info(S.cyan(`start preview server`)),ie=await viteDev({languageServices:ne,buildWebcomponent:!1,openBrowser:!1,hmr:!1}),ae=resolveServerUrl(ie),!ae))throw t.error(`Vite server is not ready, no resolvedUrls`),Error(`Vite server is not ready, no resolvedUrls`);for(let e of oe){if(a&&e.id!==a)continue;oe.length>1&&(t.info(S.dim(`---------`)),t.info(`${S.dim(`project:`)} ${e.id}`),t.info(`${S.dim(`folder:`)} ${e.folder.fsPath}`));let n=await ne.diagrams(e.id);if(h&&Je(h,1)&&Je(n,1)){let e=(0,rr.default)(h);t.info(`${S.cyan(`filter`)} ${S.dim(JSON.stringify(h))}`),n=n.filter(n=>e(n.id)?(t.info(`${S.green(`include`)} ${n.id} ✅`),!0):(t.info(`${S.gray(`skip`)} ${S.dim(n.id)}`),!1))}if(!Je(n,1)){t.warn(`no views found`);continue}let r=oe.length>1?ge(_e(ae,`project`,e.id)):ae,i=oe.length>1?_e(re,e.id):re,c=zn(),u=await exportViewsToPNG({logger:t,serverUrl:r,theme:s,timeoutMs:p,views:n,output:i,outputType:l,maxAttempts:m,sequence:g,chromiumSandbox:v,format:y,quality:b,notation:ee,description:te}),{pretty:x}=inMillis(c);if(u.length>0&&t.info(S.green(`exported ${u.length} views in ${x}`)+`
290
+ `),u.length!==n.length&&(f&&u.length>0?t.info(S.dim(`ignore`)+` `+S.red(`failed ${n.length-u.length} out of ${n.length} views`)):t.error(S.red(`failed ${n.length-u.length} out of ${n.length} views`))),u.length!==n.length&&(u.length===0||!f))throw Error(`Failed ${n.length-u.length} out of ${n.length} views`)}}finally{ie&&(t.info(S.cyan(`stop server`)),await ie.close().catch(e=>{t.error(e)}))}}catch(e){n.e=e}finally{await n.d()}}async function pngHandler(e){await runExportPng(e,createLikeC4Logger(`c4:export`))}function pngCmd(e){return e.command({command:`png [path]`,describe:`export views to PNG`,builder:e=>e.positional(`path`,U).options({outdir:{alias:[`o`,`output`],type:`string`,desc:`output directory for PNG files; if not specified, images are saved next to sources`,normalize:!0,nargs:1,coerce:P},project:Ws,theme:{choices:[`light`,`dark`],desc:`color-scheme to use, defaults to light`,conflicts:[`dark`,`light`],nargs:1},dark:{type:`boolean`,desc:`use dark theme, shortcut for --theme=dark`,conflicts:[`theme`,`light`]},light:{type:`boolean`,desc:`use light theme, shortcut for --theme=light`,conflicts:[`theme`,`dark`]},"use-dot":W,seq:{alias:[`sequence`],type:`boolean`,desc:`use sequence layout for dynamic views`},flat:{alias:[`flatten`],type:`boolean`,desc:`flatten all images in outdir ignoring sources structure`},filter:{alias:`f`,array:!0,string:!0,desc:`include views with ids matching given patterns
291
291
  multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`continue if export fails for some views`},timeout:{type:`number`,alias:`t`,desc:`timeout for playwright (in seconds)`,default:15,nargs:1},"max-attempts":{type:`number`,desc:`max attempts to export failing view, 1 means no retry`,default:3,nargs:1},"server-url":{type:`string`,desc:`use this url instead of starting new likec4 server`,nargs:1},"chromium-sandbox":{boolean:!0,desc:`enable chromium sandbox (see Playwright docs)`,default:!1},notation:{boolean:!0,desc:`include view notation in exported PNG files`,default:!1},description:{boolean:!0,desc:`include view description in exported PNG files`,default:!1}}).epilog(`${S.bold(`Examples:`)}
292
292
  ${S.green(`$0 export png`)}
293
293
  ${S.gray(`Search for likec4 files in current directory and output PNG next to sources`)}
@@ -300,7 +300,7 @@ multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`cont
300
300
 
301
301
  ${S.green(`$0 export png -f "use-case*" --sequence src/likec4`)}
302
302
  ${S.gray(`Export views matching use-case* using sequence layout`)}
303
- `),handler:async e=>{Qt(e.timeout>=1,`timeout must be >= 1`),Qt(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await pngHandler({path:e.path,useDotBin:e[`use-dot`],output:e.outdir,project:e.project,timeoutMs:e.timeout*1e3,maxAttempts:e[`max-attempts`],ignore:e.ignore===!0,outputType:e.flat?`flat`:`relative`,serverUrl:e[`server-url`],theme:t,filter:e.filter,sequence:e.seq,chromiumSandbox:e[`chromium-sandbox`],notation:e.notation,description:e.description})}})}async function jpgHandler(e){let t=createLikeC4Logger(`c4:export`);await runExportPng({...e,format:`jpeg`},t)}function jpgCmd(e){return e.command({command:`jpg [path]`,describe:`export views to JPEG`,builder:e=>e.positional(`path`,B).options({outdir:{alias:[`o`,`output`],type:`string`,desc:`output directory for JPEG files; if not specified, images are saved next to sources`,normalize:!0,nargs:1,coerce:M},project:Gs,quality:{alias:`q`,type:`number`,desc:`JPEG quality (1-100)`,default:80,nargs:1},theme:{choices:[`light`,`dark`],desc:`color-scheme to use, defaults to light`,conflicts:[`dark`,`light`],nargs:1},dark:{type:`boolean`,desc:`use dark theme, shortcut for --theme=dark`,conflicts:[`theme`,`light`]},light:{type:`boolean`,desc:`use light theme, shortcut for --theme=light`,conflicts:[`theme`,`dark`]},"use-dot":js,seq:{alias:[`sequence`],type:`boolean`,desc:`use sequence layout for dynamic views`},flat:{alias:[`flatten`],type:`boolean`,desc:`flatten all images in outdir ignoring sources structure`},filter:{alias:`f`,array:!0,string:!0,desc:`include views with ids matching given patterns
303
+ `),handler:async e=>{$t(e.timeout>=1,`timeout must be >= 1`),$t(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await pngHandler({path:e.path,useDotBin:e[`use-dot`],output:e.outdir,project:e.project,timeoutMs:e.timeout*1e3,maxAttempts:e[`max-attempts`],ignore:e.ignore===!0,outputType:e.flat?`flat`:`relative`,serverUrl:e[`server-url`],theme:t,filter:e.filter,sequence:e.seq,chromiumSandbox:e[`chromium-sandbox`],notation:e.notation,description:e.description})}})}async function jpgHandler(e){let t=createLikeC4Logger(`c4:export`);await runExportPng({...e,format:`jpeg`},t)}function jpgCmd(e){return e.command({command:`jpg [path]`,describe:`export views to JPEG`,builder:e=>e.positional(`path`,U).options({outdir:{alias:[`o`,`output`],type:`string`,desc:`output directory for JPEG files; if not specified, images are saved next to sources`,normalize:!0,nargs:1,coerce:P},project:Ws,quality:{alias:`q`,type:`number`,desc:`JPEG quality (1-100)`,default:80,nargs:1},theme:{choices:[`light`,`dark`],desc:`color-scheme to use, defaults to light`,conflicts:[`dark`,`light`],nargs:1},dark:{type:`boolean`,desc:`use dark theme, shortcut for --theme=dark`,conflicts:[`theme`,`light`]},light:{type:`boolean`,desc:`use light theme, shortcut for --theme=light`,conflicts:[`theme`,`dark`]},"use-dot":W,seq:{alias:[`sequence`],type:`boolean`,desc:`use sequence layout for dynamic views`},flat:{alias:[`flatten`],type:`boolean`,desc:`flatten all images in outdir ignoring sources structure`},filter:{alias:`f`,array:!0,string:!0,desc:`include views with ids matching given patterns
304
304
  multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`continue if export fails for some views`},timeout:{type:`number`,alias:`t`,desc:`timeout for playwright (in seconds)`,default:15,nargs:1},"max-attempts":{type:`number`,desc:`max attempts to export failing view, 1 means no retry`,default:3,nargs:1},"server-url":{type:`string`,desc:`use this url instead of starting new likec4 server`,nargs:1},"chromium-sandbox":{boolean:!0,desc:`enable chromium sandbox (see Playwright docs)`,default:!1},notation:{boolean:!0,desc:`include view notation in exported JPEG files`,default:!1},description:{boolean:!0,desc:`include view description in exported JPEG files`,default:!1}}).epilog(`${S.bold(`Examples:`)}
305
305
  ${S.green(`$0 export jpg`)}
306
306
  ${S.gray(`Search for likec4 files in current directory and output JPEG next to sources`)}
@@ -313,20 +313,20 @@ multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`cont
313
313
 
314
314
  ${S.green(`$0 export jpg -f "team1*" -f "team2*" --flat -o ./jpg src/likec4`)}
315
315
  ${S.gray(`Export views matching team1* or team2* only`)}
316
- `),handler:async e=>{Qt(e.quality>=1&&e.quality<=100,`quality must be between 1 and 100`),Qt(e.timeout>=1,`timeout must be >= 1`),Qt(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await jpgHandler({path:e.path,useDotBin:e[`use-dot`],output:e.outdir,project:e.project,timeoutMs:e.timeout*1e3,maxAttempts:e[`max-attempts`],ignore:e.ignore===!0,outputType:e.flat?`flat`:`relative`,serverUrl:e[`server-url`],theme:t,filter:e.filter,sequence:e.seq,chromiumSandbox:e[`chromium-sandbox`],format:`jpeg`,quality:e.quality,notation:e.notation,description:e.description})}})}const xc=`project not found`,Sc=`No projects found`;async function runExportJson(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1})),a=[...i.projectsManager.all];if(e.project){if(a=a.filter(t=>t===e.project),!Xe(a,1))throw t.error(`${xc}: ${e.project}`),Error(`${xc}: ${e.project}`)}else{if(!Xe(a,1))throw t.error(Sc),Error(Sc);t.info(`${S.dim(`workspace:`)} Found ${a.length} projects`)}let s=[];for(let n of a){let r;if(e.skipLayout?(t.info(`Generate model for project ${S.green(n)} ${S.dim(`(skip layout)`)}`),r=await i.computedModel(n)):(t.info(`Generating layouted model for project ${S.green(n)}`),r=await i.layoutedModel(n)),r===At.EMPTY){t.warn(S.yellow(`Project ${n} is empty, skipping`));continue}s.push(r.$data)}if(s.length===0)throw t.warn(`No models generated, aborting export`),Error(`No models generated; all projects are empty or were skipped`);let c=e.outfile;Kt(c).toLowerCase()!==`.json`&&(c+=`.json`),await It(Gt(c),{recursive:!0});let l=s.length===1?s[0]:s,u=e.pretty?JSON.stringify(l,void 0,2):JSON.stringify(l);await Ut(c,u);let f=c.startsWith(e.path)?Yt(e.path,c):c;t.info(`${S.dim(`generated`)} ${f}`),r.stopAndLog(`✓ export in `)}catch(e){n.e=e}finally{await n.d()}}function jsonCmd(e){return e.command({command:`json [path]`,describe:`export model(s) to JSON`,builder:e=>e.positional(`path`,B).option(`outfile`,{alias:`o`,type:`string`,desc:`<file> output .json file`,default:`likec4.json`,normalize:!0,coerce:M}).options({project:Gs,"use-dot":js,"skip-layout":{type:`boolean`,desc:`skip layout (produce compute-only model, faster)`},pretty:{type:`boolean`,desc:`indented JSON output`}}).epilog(`${S.bold(`Examples:`)}
316
+ `),handler:async e=>{$t(e.quality>=1&&e.quality<=100,`quality must be between 1 and 100`),$t(e.timeout>=1,`timeout must be >= 1`),$t(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await jpgHandler({path:e.path,useDotBin:e[`use-dot`],output:e.outdir,project:e.project,timeoutMs:e.timeout*1e3,maxAttempts:e[`max-attempts`],ignore:e.ignore===!0,outputType:e.flat?`flat`:`relative`,serverUrl:e[`server-url`],theme:t,filter:e.filter,sequence:e.seq,chromiumSandbox:e[`chromium-sandbox`],format:`jpeg`,quality:e.quality,notation:e.notation,description:e.description})}})}const bc=`project not found`,xc=`No projects found`;async function runExportJson(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1})),a=[...i.projectsManager.all];if(e.project){if(a=a.filter(t=>t===e.project),!Je(a,1))throw t.error(`${bc}: ${e.project}`),Error(`${bc}: ${e.project}`)}else{if(!Je(a,1))throw t.error(xc),Error(xc);t.info(`${S.dim(`workspace:`)} Found ${a.length} projects`)}let s=[];for(let n of a){let r;if(e.skipLayout?(t.info(`Generate model for project ${S.green(n)} ${S.dim(`(skip layout)`)}`),r=await i.computedModel(n)):(t.info(`Generating layouted model for project ${S.green(n)}`),r=await i.layoutedModel(n)),r===Ot.EMPTY){t.warn(S.yellow(`Project ${n} is empty, skipping`));continue}s.push(r.$data)}if(s.length===0)throw t.warn(`No models generated, aborting export`),Error(`No models generated; all projects are empty or were skipped`);let c=e.outfile;Wt(c).toLowerCase()!==`.json`&&(c+=`.json`),await Pt(Ut(c),{recursive:!0});let l=s.length===1?s[0]:s,u=e.pretty?JSON.stringify(l,void 0,2):JSON.stringify(l);await Vt(c,u);let f=c.startsWith(e.path)?qt(e.path,c):c;t.info(`${S.dim(`generated`)} ${f}`),r.stopAndLog(`✓ export in `)}catch(e){n.e=e}finally{await n.d()}}function jsonCmd(e){return e.command({command:`json [path]`,describe:`export model(s) to JSON`,builder:e=>e.positional(`path`,U).option(`outfile`,{alias:`o`,type:`string`,desc:`<file> output .json file`,default:`likec4.json`,normalize:!0,coerce:P}).options({project:Ws,"use-dot":W,"skip-layout":{type:`boolean`,desc:`skip layout (produce compute-only model, faster)`},pretty:{type:`boolean`,desc:`indented JSON output`}}).epilog(`${S.bold(`Examples:`)}
317
317
  ${S.green(`$0 export json --skip-layout`)}
318
318
  ${S.gray(`Search for likec4 files in current directory and output JSON to likec4.json (no layout)`)}
319
319
 
320
320
  ${S.green(`$0 export json --pretty -o ./generated/likec4.json src/likec4 `)}
321
321
  ${S.gray(`Search for likec4 files in src/likec4 and output JSON to generated/likec4.json`)}
322
- `),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportJson({path:e.path,outfile:e.outfile,project:e.project,skipLayout:!!e.skipLayout,pretty:!!e.pretty,useDot:!!e[`use-dot`]},t)}})}const Cc=`project not found`,wc=`<!-- Generated by likec4 export markdown. Do not edit manually. -->`;function hasAuthoredViews(e){for(let t of e.views())if(t.$view.sourcePath!==void 0)return!0;return!1}function projectDescription(e){let t=e?.description;return typeof t==`string`?t:void 0}async function canWrite(e,t){if(t)return!0;let n;try{n=await Rt(e,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!0;throw e}return n.startsWith(wc)}async function runExportMarkdown(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1})),a=[...i.languageServices.projects()];if(e.project){if(a=a.filter(t=>t.id===e.project),a.length===0)throw t.error(`${Cc}: ${e.project}`),Error(`${Cc}: ${e.project}`)}else t.info(`${S.dim(`workspace:`)} Found ${a.length} projects`);let s=0;for(let n of a){let r=await i.layoutedModel(n.id);if(r===At.EMPTY||!hasAuthoredViews(r)){t.warn(S.yellow(`Project ${n.id} has no views, skipping`));continue}let a=Jt(n.folder.fsPath,`README.md`);if(!await canWrite(a,!!e.force)){t.warn(S.yellow(`${a} already exists and was not generated by this command, skipping (pass --force to overwrite)`));continue}let c=projectDescription(n.config.metadata),l=generateMarkdown(r,c===void 0?{}:{description:c});await Ut(a,`${wc}\n\n${l}`),s++,t.info(`${S.dim(`generated`)} ${a}`)}if(s===0)throw Error(`No documents generated; all projects were skipped`);r.stopAndLog(`✓ export in `)}catch(e){n.e=e}finally{await n.d()}}function markdownCmd(e){return e.command({command:`markdown [path]`,describe:`export project(s) to README.md in each project folder`,builder:e=>e.positional(`path`,B).options({project:Gs,"use-dot":js,force:{type:`boolean`,desc:`overwrite an existing README.md even if it was not generated by this command`}}).epilog(`${S.bold(`Examples:`)}
322
+ `),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportJson({path:e.path,outfile:e.outfile,project:e.project,skipLayout:!!e.skipLayout,pretty:!!e.pretty,useDot:!!e[`use-dot`]},t)}})}const Sc=`project not found`,Cc=`<!-- Generated by likec4 export markdown. Do not edit manually. -->`;function hasAuthoredViews(e){for(let t of e.views())if(t.$view.sourcePath!==void 0)return!0;return!1}function projectDescription(e){let t=e?.description;return typeof t==`string`?t:void 0}async function canWrite(e,t){if(t)return!0;let n;try{n=await It(e,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!0;throw e}return n.startsWith(Cc)}async function runExportMarkdown(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await x(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1})),a=[...i.languageServices.projects()];if(e.project){if(a=a.filter(t=>t.id===e.project),a.length===0)throw t.error(`${Sc}: ${e.project}`),Error(`${Sc}: ${e.project}`)}else t.info(`${S.dim(`workspace:`)} Found ${a.length} projects`);let s=0;for(let n of a){let r=await i.layoutedModel(n.id);if(r===Ot.EMPTY||!hasAuthoredViews(r)){t.warn(S.yellow(`Project ${n.id} has no views, skipping`));continue}let a=Kt(n.folder.fsPath,`README.md`);if(!await canWrite(a,!!e.force)){t.warn(S.yellow(`${a} already exists and was not generated by this command, skipping (pass --force to overwrite)`));continue}let c=projectDescription(n.config.metadata),l=generateMarkdown(r,c===void 0?{}:{description:c});await Vt(a,`${Cc}\n\n${l}`),s++,t.info(`${S.dim(`generated`)} ${a}`)}if(s===0)throw Error(`No documents generated; all projects were skipped`);r.stopAndLog(`✓ export in `)}catch(e){n.e=e}finally{await n.d()}}function markdownCmd(e){return e.command({command:`markdown [path]`,describe:`export project(s) to README.md in each project folder`,builder:e=>e.positional(`path`,U).options({project:Ws,"use-dot":W,force:{type:`boolean`,desc:`overwrite an existing README.md even if it was not generated by this command`}}).epilog(`${S.bold(`Examples:`)}
323
323
  ${S.green(`$0 export markdown`)}
324
324
  ${S.gray(`Render every project to README.md in its own project folder`)}
325
325
 
326
326
  ${S.green(`$0 export markdown -p my-project src/likec4`)}
327
327
  ${S.gray(`Render only my-project to its README.md under src/likec4`)}
328
- `),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportMarkdown({path:e.path,project:e.project,useDot:!!e[`use-dot`],force:!!e.force},t)}})}const exportCmd=e=>e.command({command:`export <format> [path]`,describe:`Export to images, JSON, DrawIO, or Markdown`,builder:e=>ft(e.usage(`${S.bold(`Usage:`)} $0 export <format> [path]`),pngCmd,jpgCmd,jsonCmd,drawioCmd,markdownCmd).updateStrings({"Commands:":S.bold(`Formats:`)}),handler:()=>void 0}),formatCmd=e=>e.command({command:`format [path]`,aliases:[`fmt`],describe:`Format LikeC4 source files`,builder:e=>e.positional(`path`,B).options({project:{alias:`p`,type:`string`,array:!0,desc:`select project(s) to format (repeatable)`},files:{type:`string`,array:!0,normalize:!0,coerce:e=>e.map(e=>M(e)),desc:`specific file(s) to format (repeatable)`},check:{type:`boolean`,desc:`Check if files are formatted (exit with 1 if not)`,default:!1}}),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:format`),r=startTimer(n),i=e.check,a;try{a=await x(e.path,{watch:!1})}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}t.a(a);let s=e.project?.filter(Boolean),c=e.files?.filter(Boolean).map(e=>kn(e).toString());if(n.debug(`workspace: ${e.path}`),s?.length){n.debug(`projects:`);for(let e of s)n.debug(` ${e}`)}if(c?.length){n.debug(`files:`);for(let e of c)n.debug(` ${On(e)}`)}let l;try{l=await a.format({...s?.length&&{projects:s},...c?.length&&{documentUris:c}})}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}n.debug(`${l.size} document(s) to process`);let u=process.cwd(),displayPath=e=>{let t=Yt(u,e);return t.startsWith(`..`)?e:t};if(c){let e=c.filter(e=>!l.has(e));for(let t of e)n.warn(`${S.yellow(`skipped`)} ${displayPath(On(t))} (not found in workspace)`)}let f=0,p=0,m=[];for(let[e,t]of l){let r=On(e),a=displayPath(r),s;try{s=await Rt(r,`utf-8`)}catch(e){n.error(`Failed to read ${a}: ${e}`),p++;continue}if(s===t){n.debug(`${S.dim(`unchanged`)} ${a}`);continue}if(f++,m.push(a),i)n.info(`${S.yellow(`needs formatting`)} ${a}`);else try{await Ut(r,t,`utf-8`),n.info(`${S.green(`formatted`)} ${a}`)}catch(e){n.error(`Failed to write ${a}: ${e}`),p++}}if(p>0){n.error(`${p} file(s) failed to process`),process.exitCode=1;return}if(i){if(f>0){n.error(`${f} of ${l.size} file(s) need formatting:\n${m.map(e=>` ${e}`).join(`
329
- `)}`),process.exitCode=1;return}n.info(S.green(`All ${l.size} file(s) are formatted`))}else f>0?n.info(`${S.green(String(f))} of ${l.size} file(s) formatted`):n.info(S.green(`All ${l.size} file(s) already formatted`));r.stopAndLog(`✓ format in `)}catch(e){t.e=e}finally{await t.d()}}}),listIconsCmd=e=>e.command({command:`list-icons`,describe:`List available built-in icons`,builder:e=>e.option(`format`,{alias:`f`,choices:[`text`,`json`],default:`text`,description:`Output format`}).option(`group`,{alias:`g`,choices:y,description:`Filter icons by group`}),handler:e=>{let t=e.group?[e.group]:y;switch(!0){case e.format===`json`:{let e=Object.fromEntries(t.map(e=>[e,ie[e]]));console.log(JSON.stringify(e,null,2));break}default:for(let e of t)for(let t of ie[e])console.log(`${e}:${t}`)}}});var Tc=r(((e,t)=>{t.exports=de()}))();function lsp_default(e){return e.command({command:`lsp`,aliases:[],describe:`Start LSP server`,builder:e=>e.usage(`${S.bold(`Usage:`)} $0 lsp`).option(`log-level`,Ks).option(`verbose`,qs).options({"node-ipc":{boolean:!0,description:`use node-ipc transport`,conflicts:[`stdio`,`socket`,`pipe`]},stdio:{boolean:!0,description:`use stdio transport`,conflicts:[`node-ipc`,`socket`,`pipe`]},socket:{number:!0,description:`use socket transport on specified port`,conflicts:[`node-ipc`,`stdio`,`pipe`],nargs:1},pipe:{string:!0,description:`use pipe transport with specified pipe name`,conflicts:[`node-ipc`,`stdio`,`socket`],nargs:1},"manual-layouts":{boolean:!0,description:`enable/disable manual layouts`,default:!0,defaultDescription:`enabled`},watch:{alias:`w`,boolean:!0,description:`enable built-in watcher`,default:!1,defaultDescription:`disabled`},telemetry:{boolean:!0,default:!0,defaultDescription:`IDE setting`,description:`enable/disable telemetry`,hidden:!0}}).option(`use-dot`,js).showHidden().epilog(`${S.bold(`Examples:`)}
328
+ `),handler:async e=>{let t=createLikeC4Logger(`c4:export`);await runExportMarkdown({path:e.path,project:e.project,useDot:!!e[`use-dot`],force:!!e.force},t)}})}const exportCmd=e=>e.command({command:`export <format> [path]`,describe:`Export to images, JSON, DrawIO, or Markdown`,builder:e=>ut(e.usage(`${S.bold(`Usage:`)} $0 export <format> [path]`),pngCmd,jpgCmd,jsonCmd,drawioCmd,markdownCmd).updateStrings({"Commands:":S.bold(`Formats:`)}),handler:()=>void 0}),formatCmd=e=>e.command({command:`format [path]`,aliases:[`fmt`],describe:`Format LikeC4 source files`,builder:e=>e.positional(`path`,U).options({project:{alias:`p`,type:`string`,array:!0,desc:`select project(s) to format (repeatable)`},files:{type:`string`,array:!0,normalize:!0,coerce:e=>e.map(e=>P(e)),desc:`specific file(s) to format (repeatable)`},check:{type:`boolean`,desc:`Check if files are formatted (exit with 1 if not)`,default:!1}}),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:format`),r=startTimer(n),i=e.check,a;try{a=await x(e.path,{watch:!1})}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}t.a(a);let s=e.project?.filter(Boolean),c=e.files?.filter(Boolean).map(e=>An(e).toString());if(n.debug(`workspace: ${e.path}`),s?.length){n.debug(`projects:`);for(let e of s)n.debug(` ${e}`)}if(c?.length){n.debug(`files:`);for(let e of c)n.debug(` ${kn(e)}`)}let l;try{l=await a.format({...s?.length&&{projects:s},...c?.length&&{documentUris:c}})}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}n.debug(`${l.size} document(s) to process`);let u=process.cwd(),displayPath=e=>{let t=qt(u,e);return t.startsWith(`..`)?e:t};if(c){let e=c.filter(e=>!l.has(e));for(let t of e)n.warn(`${S.yellow(`skipped`)} ${displayPath(kn(t))} (not found in workspace)`)}let f=0,p=0,m=[];for(let[e,t]of l){let r=kn(e),a=displayPath(r),s;try{s=await It(r,`utf-8`)}catch(e){n.error(`Failed to read ${a}: ${e}`),p++;continue}if(s===t){n.debug(`${S.dim(`unchanged`)} ${a}`);continue}if(f++,m.push(a),i)n.info(`${S.yellow(`needs formatting`)} ${a}`);else try{await Vt(r,t,`utf-8`),n.info(`${S.green(`formatted`)} ${a}`)}catch(e){n.error(`Failed to write ${a}: ${e}`),p++}}if(p>0){n.error(`${p} file(s) failed to process`),process.exitCode=1;return}if(i){if(f>0){n.error(`${f} of ${l.size} file(s) need formatting:\n${m.map(e=>` ${e}`).join(`
329
+ `)}`),process.exitCode=1;return}n.info(S.green(`All ${l.size} file(s) are formatted`))}else f>0?n.info(`${S.green(String(f))} of ${l.size} file(s) formatted`):n.info(S.green(`All ${l.size} file(s) already formatted`));r.stopAndLog(`✓ format in `)}catch(e){t.e=e}finally{await t.d()}}}),listIconsCmd=e=>e.command({command:`list-icons`,describe:`List available built-in icons`,builder:e=>e.option(`format`,{alias:`f`,choices:[`text`,`json`],default:`text`,description:`Output format`}).option(`group`,{alias:`g`,choices:y,description:`Filter icons by group`}),handler:e=>{let t=e.group?[e.group]:y;switch(!0){case e.format===`json`:{let e=Object.fromEntries(t.map(e=>[e,ie[e]]));console.log(JSON.stringify(e,null,2));break}default:for(let e of t)for(let t of ie[e])console.log(`${e}:${t}`)}}});var wc=r(((e,t)=>{t.exports=de()}))();function lsp_default(e){return e.command({command:`lsp`,aliases:[],describe:`Start LSP server`,builder:e=>e.usage(`${S.bold(`Usage:`)} $0 lsp`).option(`log-level`,Gs).option(`verbose`,Ks).options({"node-ipc":{boolean:!0,description:`use node-ipc transport`,conflicts:[`stdio`,`socket`,`pipe`]},stdio:{boolean:!0,description:`use stdio transport`,conflicts:[`node-ipc`,`socket`,`pipe`]},socket:{number:!0,description:`use socket transport on specified port`,conflicts:[`node-ipc`,`stdio`,`pipe`],nargs:1},pipe:{string:!0,description:`use pipe transport with specified pipe name`,conflicts:[`node-ipc`,`stdio`,`socket`],nargs:1},"manual-layouts":{boolean:!0,description:`enable/disable manual layouts`,default:!0,defaultDescription:`enabled`},watch:{alias:`w`,boolean:!0,description:`enable built-in watcher`,default:!1,defaultDescription:`disabled`},telemetry:{boolean:!0,default:!0,defaultDescription:`IDE setting`,description:`enable/disable telemetry`,hidden:!0}}).option(`use-dot`,W).showHidden().epilog(`${S.bold(`Examples:`)}
330
330
 
331
331
  ${S.green(`$0 lsp --stdio `)}
332
332
  ${S.gray(`Start LSP with stdio transport`)}
@@ -334,18 +334,18 @@ ${S.gray(`Start LSP with stdio transport`)}
334
334
  ${S.green(`$0 lsp --node-ipc --watch --no-manual-layouts --no-color `)}
335
335
  ${S.gray(`Start LSP with node-ipc transport and watcher, disabled manual layouts and disabled color`)}
336
336
 
337
- `),handler:e=>{let t;if(e.nodeIpc||e.stdio||e.socket||e.pipe)t=(0,Tc.createConnection)(Tc.ProposedFeatures.all);else throw Error(`No transport specified`);m({lspConnection:t,useStdErr:e.stdio===!0,colors:S.isColorSupported,enableTelemetry:e.telemetry,logLevel:e.verbose?Js:e.logLevel}),startLanguageServer({connection:t,enableManualLayouts:e.manualLayouts,enableWatcher:e.watch,graphviz:e.useDot?`binary`:`wasm`,configureLogger:!1})}})}t(lsp_default,`default`);function createContext(e={}){let t,n=!1,checkConflict=e=>{if(t&&t!==e)throw Error(`Context conflict`)},r;if(e.asyncContext){let t=e.AsyncLocalStorage||globalThis.AsyncLocalStorage;t?r=new t:console.warn("[unctx] `AsyncLocalStorage` is not provided.")}let _getCurrentInstance=()=>{if(r){let e=r.getStore();if(e!==void 0)return e}return t};return{use:()=>{let e=_getCurrentInstance();if(e===void 0)throw Error(`Context is not available`);return e},tryUse:()=>_getCurrentInstance(),set:(e,r)=>{r||checkConflict(e),t=e,n=!0},unset:()=>{t=void 0,n=!1},call:(e,i)=>{checkConflict(e),t=e;try{return r?r.run(e,i):i()}finally{n||(t=void 0)}},async callAsync(e,i){t=e;let onRestore=()=>{t=e},onLeave=()=>t===e?onRestore:void 0;kc.add(onLeave);try{let a=r?r.run(e,i):i();return n||(t=void 0),await a}finally{kc.delete(onLeave)}}}}function createNamespace(e={}){let t={};return{get(n,r={}){return t[n]||(t[n]=createContext({...e,...r})),t[n]}}}const Ec=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof global<`u`?global:typeof window<`u`?window:{},Dc=`__unctx__`;Ec[Dc]||(Ec[Dc]=createNamespace());const Oc=`__unctx_async_handlers__`,kc=Ec[Oc]||(Ec[Oc]=new Set),Ac=createContext(),jc=createContext();function useLanguageServices(){return jc.use()}function setMcpServerCtx(e){return e?Ac.set(e,!0):Ac.unset(),e}function setLanguageServicesCtx(e){return e?jc.set(e,!0):jc.unset(),e}const Mc=`2025-11-25`,Nc=[Mc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Pc=`io.modelcontextprotocol/related-task`,Fc=Re(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Ic=w([T(),A().int()]),Lc=T();Fe({ttl:A().optional(),pollInterval:A().optional()});const Rc=E({ttl:A().optional()}),zc=E({taskId:T()}),Bc=Fe({progressToken:Ic.optional(),[Pc]:zc.optional()}),Vc=E({_meta:Bc.optional()}),Hc=Vc.extend({task:Rc.optional()}),isTaskAugmentedRequestParams=e=>Hc.safeParse(e).success,Uc=E({method:T(),params:Vc.loose().optional()}),Wc=E({_meta:Bc.optional()}),Gc=E({method:T(),params:Wc.loose().optional()}),Kc=Fe({_meta:Bc.optional()}),qc=w([T(),A().int()]),Jc=E({jsonrpc:D(`2.0`),id:qc,...Uc.shape}).strict(),isJSONRPCRequest=e=>Jc.safeParse(e).success,Yc=E({jsonrpc:D(`2.0`),...Gc.shape}).strict(),isJSONRPCNotification=e=>Yc.safeParse(e).success,Xc=E({jsonrpc:D(`2.0`),id:qc,result:Kc}).strict(),isJSONRPCResultResponse=e=>Xc.safeParse(e).success;var V;(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`})(V||={});const Zc=E({jsonrpc:D(`2.0`),id:qc.optional(),error:E({code:A().int(),message:T(),data:Oe().optional()})}).strict(),isJSONRPCErrorResponse=e=>Zc.safeParse(e).success,Qc=w([Jc,Yc,Xc,Zc]);w([Xc,Zc]);const $c=Kc.strict(),el=Wc.extend({requestId:qc.optional(),reason:T().optional()}),tl=Gc.extend({method:D(`notifications/cancelled`),params:el}),nl=E({src:T(),mimeType:T().optional(),sizes:O(T()).optional(),theme:Ie([`light`,`dark`]).optional()}),rl=E({icons:O(nl).optional()}),il=E({name:T(),title:T().optional()}),al=il.extend({...il.shape,...rl.shape,version:T(),websiteUrl:T().optional(),description:T().optional()}),ol=Ue(E({applyDefaults:k().optional()}),C(T(),Oe())),sl=je(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ue(E({form:ol.optional(),url:Fc.optional()}),C(T(),Oe()).optional())),cl=Fe({list:Fc.optional(),cancel:Fc.optional(),requests:Fe({sampling:Fe({createMessage:Fc.optional()}).optional(),elicitation:Fe({create:Fc.optional()}).optional()}).optional()}),ll=Fe({list:Fc.optional(),cancel:Fc.optional(),requests:Fe({tools:Fe({call:Fc.optional()}).optional()}).optional()}),ul=E({experimental:C(T(),Fc).optional(),sampling:E({context:Fc.optional(),tools:Fc.optional()}).optional(),elicitation:sl.optional(),roots:E({listChanged:k().optional()}).optional(),tasks:cl.optional(),extensions:C(T(),Fc).optional()}),dl=Vc.extend({protocolVersion:T(),capabilities:ul,clientInfo:al}),fl=Uc.extend({method:D(`initialize`),params:dl}),isInitializeRequest=e=>fl.safeParse(e).success,pl=E({experimental:C(T(),Fc).optional(),logging:Fc.optional(),completions:Fc.optional(),prompts:E({listChanged:k().optional()}).optional(),resources:E({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:E({listChanged:k().optional()}).optional(),tasks:ll.optional(),extensions:C(T(),Fc).optional()}),ml=Kc.extend({protocolVersion:T(),capabilities:pl,serverInfo:al,instructions:T().optional()}),hl=Gc.extend({method:D(`notifications/initialized`),params:Wc.optional()}),gl=Uc.extend({method:D(`ping`),params:Vc.optional()}),_l=E({progress:A(),total:Ye(A()),message:Ye(T())}),vl=E({...Wc.shape,..._l.shape,progressToken:Ic}),yl=Gc.extend({method:D(`notifications/progress`),params:vl}),bl=Vc.extend({cursor:Lc.optional()}),xl=Uc.extend({params:bl.optional()}),Sl=Kc.extend({nextCursor:Lc.optional()}),Cl=Ie([`working`,`input_required`,`completed`,`failed`,`cancelled`]),wl=E({taskId:T(),status:Cl,ttl:w([A(),Ge()]),createdAt:T(),lastUpdatedAt:T(),pollInterval:Ye(A()),statusMessage:Ye(T())}),Tl=Kc.extend({task:wl}),El=Wc.merge(wl),Dl=Gc.extend({method:D(`notifications/tasks/status`),params:El}),Ol=Uc.extend({method:D(`tasks/get`),params:Vc.extend({taskId:T()})}),kl=Kc.merge(wl),Al=Uc.extend({method:D(`tasks/result`),params:Vc.extend({taskId:T()})});Kc.loose();const jl=xl.extend({method:D(`tasks/list`)}),Ml=Sl.extend({tasks:O(wl)}),Nl=Uc.extend({method:D(`tasks/cancel`),params:Vc.extend({taskId:T()})}),Pl=Kc.merge(wl),Fl=E({uri:T(),mimeType:Ye(T()),_meta:C(T(),Oe()).optional()}),Il=Fl.extend({text:T()}),Ll=T().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Rl=Fl.extend({blob:Ll}),zl=Ie([`user`,`assistant`]),Bl=E({audience:O(zl).optional(),priority:A().min(0).max(1).optional(),lastModified:Ve({offset:!0}).optional()}),Vl=E({...il.shape,...rl.shape,uri:T(),description:Ye(T()),mimeType:Ye(T()),size:Ye(A()),annotations:Bl.optional(),_meta:Ye(Fe({}))}),Hl=E({...il.shape,...rl.shape,uriTemplate:T(),description:Ye(T()),mimeType:Ye(T()),annotations:Bl.optional(),_meta:Ye(Fe({}))}),Ul=xl.extend({method:D(`resources/list`)}),Wl=Sl.extend({resources:O(Vl)}),Gl=xl.extend({method:D(`resources/templates/list`)}),Kl=Sl.extend({resourceTemplates:O(Hl)}),ql=Vc.extend({uri:T()}),Jl=ql,Yl=Uc.extend({method:D(`resources/read`),params:Jl}),Xl=Kc.extend({contents:O(w([Il,Rl]))}),Zl=Gc.extend({method:D(`notifications/resources/list_changed`),params:Wc.optional()}),Ql=ql,$l=Uc.extend({method:D(`resources/subscribe`),params:Ql}),eu=ql,tu=Uc.extend({method:D(`resources/unsubscribe`),params:eu}),nu=Wc.extend({uri:T()}),ru=Gc.extend({method:D(`notifications/resources/updated`),params:nu}),iu=E({name:T(),description:Ye(T()),required:Ye(k())}),au=E({...il.shape,...rl.shape,description:Ye(T()),arguments:Ye(O(iu)),_meta:Ye(Fe({}))}),ou=xl.extend({method:D(`prompts/list`)}),su=Sl.extend({prompts:O(au)}),cu=Vc.extend({name:T(),arguments:C(T(),T()).optional()}),lu=Uc.extend({method:D(`prompts/get`),params:cu}),uu=E({type:D(`text`),text:T(),annotations:Bl.optional(),_meta:C(T(),Oe()).optional()}),du=E({type:D(`image`),data:Ll,mimeType:T(),annotations:Bl.optional(),_meta:C(T(),Oe()).optional()}),fu=E({type:D(`audio`),data:Ll,mimeType:T(),annotations:Bl.optional(),_meta:C(T(),Oe()).optional()}),pu=E({type:D(`tool_use`),name:T(),id:T(),input:C(T(),Oe()),_meta:C(T(),Oe()).optional()}),mu=E({type:D(`resource`),resource:w([Il,Rl]),annotations:Bl.optional(),_meta:C(T(),Oe()).optional()}),hu=Vl.extend({type:D(`resource_link`)}),gu=w([uu,du,fu,hu,mu]),_u=E({role:zl,content:gu}),vu=Kc.extend({description:T().optional(),messages:O(_u)}),yu=Gc.extend({method:D(`notifications/prompts/list_changed`),params:Wc.optional()}),bu=E({title:T().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),xu=E({taskSupport:Ie([`required`,`optional`,`forbidden`]).optional()}),Su=E({...il.shape,...rl.shape,description:T().optional(),inputSchema:E({type:D(`object`),properties:C(T(),Fc).optional(),required:O(T()).optional()}).catchall(Oe()),outputSchema:E({type:D(`object`),properties:C(T(),Fc).optional(),required:O(T()).optional()}).catchall(Oe()).optional(),annotations:bu.optional(),execution:xu.optional(),_meta:C(T(),Oe()).optional()}),Cu=xl.extend({method:D(`tools/list`)}),wu=Sl.extend({tools:O(Su)}),Tu=Kc.extend({content:O(gu).default([]),structuredContent:C(T(),Oe()).optional(),isError:k().optional()});Tu.or(Kc.extend({toolResult:Oe()}));const Eu=Hc.extend({name:T(),arguments:C(T(),Oe()).optional()}),Du=Uc.extend({method:D(`tools/call`),params:Eu}),Ou=Gc.extend({method:D(`notifications/tools/list_changed`),params:Wc.optional()});E({autoRefresh:k().default(!0),debounceMs:A().int().nonnegative().default(300)});const ku=Ie([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Au=Vc.extend({level:ku}),ju=Uc.extend({method:D(`logging/setLevel`),params:Au}),Mu=Wc.extend({level:ku,logger:T().optional(),data:Oe()}),Nu=Gc.extend({method:D(`notifications/message`),params:Mu}),Pu=E({name:T().optional()}),Fu=E({hints:O(Pu).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Iu=E({mode:Ie([`auto`,`required`,`none`]).optional()}),Lu=E({type:D(`tool_result`),toolUseId:T().describe(`The unique identifier for the corresponding tool call.`),content:O(gu).default([]),structuredContent:E({}).loose().optional(),isError:k().optional(),_meta:C(T(),Oe()).optional()}),Ru=ze(`type`,[uu,du,fu]),zu=ze(`type`,[uu,du,fu,pu,Lu]),Bu=E({role:zl,content:w([zu,O(zu)]),_meta:C(T(),Oe()).optional()}),Vu=Hc.extend({messages:O(Bu),modelPreferences:Fu.optional(),systemPrompt:T().optional(),includeContext:Ie([`none`,`thisServer`,`allServers`]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:O(T()).optional(),metadata:Fc.optional(),tools:O(Su).optional(),toolChoice:Iu.optional()}),Hu=Uc.extend({method:D(`sampling/createMessage`),params:Vu}),Uu=Kc.extend({model:T(),stopReason:Ye(Ie([`endTurn`,`stopSequence`,`maxTokens`]).or(T())),role:zl,content:Ru}),Wu=Kc.extend({model:T(),stopReason:Ye(Ie([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(T())),role:zl,content:w([zu,O(zu)])}),Gu=E({type:D(`boolean`),title:T().optional(),description:T().optional(),default:k().optional()}),Ku=E({type:D(`string`),title:T().optional(),description:T().optional(),minLength:A().optional(),maxLength:A().optional(),format:Ie([`email`,`uri`,`date`,`date-time`]).optional(),default:T().optional()}),qu=E({type:Ie([`number`,`integer`]),title:T().optional(),description:T().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),Ju=E({type:D(`string`),title:T().optional(),description:T().optional(),enum:O(T()),default:T().optional()}),Yu=E({type:D(`string`),title:T().optional(),description:T().optional(),oneOf:O(E({const:T(),title:T()})),default:T().optional()}),Xu=E({type:D(`string`),title:T().optional(),description:T().optional(),enum:O(T()),enumNames:O(T()).optional(),default:T().optional()}),Zu=w([Ju,Yu]),Qu=E({type:D(`array`),title:T().optional(),description:T().optional(),minItems:A().optional(),maxItems:A().optional(),items:E({type:D(`string`),enum:O(T())}),default:O(T()).optional()}),$u=E({type:D(`array`),title:T().optional(),description:T().optional(),minItems:A().optional(),maxItems:A().optional(),items:E({anyOf:O(E({const:T(),title:T()}))}),default:O(T()).optional()}),ed=w([Qu,$u]),td=w([Xu,Zu,ed]),nd=w([td,Gu,Ku,qu]),rd=Hc.extend({mode:D(`form`).optional(),message:T(),requestedSchema:E({type:D(`object`),properties:C(T(),nd),required:O(T()).optional()})}),id=Hc.extend({mode:D(`url`),message:T(),elicitationId:T(),url:T().url()}),ad=w([rd,id]),od=Uc.extend({method:D(`elicitation/create`),params:ad}),sd=Wc.extend({elicitationId:T()}),cd=Gc.extend({method:D(`notifications/elicitation/complete`),params:sd}),ld=Kc.extend({action:Ie([`accept`,`decline`,`cancel`]),content:je(e=>e===null?void 0:e,C(T(),w([T(),A(),k(),O(T())])).optional())}),ud=E({type:D(`ref/resource`),uri:T()}),dd=E({type:D(`ref/prompt`),name:T()}),fd=Vc.extend({ref:w([dd,ud]),argument:E({name:T(),value:T()}),context:E({arguments:C(T(),T()).optional()}).optional()}),pd=Uc.extend({method:D(`completion/complete`),params:fd});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 md=Kc.extend({completion:Fe({values:O(T()).max(100),total:Ye(A().int()),hasMore:Ye(k())})}),hd=E({uri:T().startsWith(`file://`),name:T().optional(),_meta:C(T(),Oe()).optional()}),gd=Uc.extend({method:D(`roots/list`),params:Vc.optional()}),_d=Kc.extend({roots:O(hd)}),vd=Gc.extend({method:D(`notifications/roots/list_changed`),params:Wc.optional()});w([gl,fl,pd,ju,lu,ou,Ul,Gl,Yl,$l,tu,Du,Cu,Ol,Al,jl,Nl]),w([tl,yl,hl,vd,Dl]),w([$c,Uu,Wu,ld,_d,kl,Ml,Tl]),w([gl,Hu,od,gd,Ol,Al,jl,Nl]),w([tl,yl,Nu,ru,Zl,Ou,yu,Dl,cd]),w([$c,ml,md,vu,su,Wl,Kl,Xl,Tu,wu,kl,Ml,Tl]);var H=class McpError extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(e,t,n){if(e===V.UrlElicitationRequired&&n){let e=n;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,t)}return new McpError(e,t,n)}},UrlElicitationRequiredError=class extends H{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(V.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ReadBuffer=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
338
- `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),deserializeMessage(t)}clear(){this._buffer=void 0}};function deserializeMessage(e){return Qc.parse(JSON.parse(e))}function serializeMessage(e){return JSON.stringify(e)+`
339
- `}var StdioServerTransport=class{constructor(e=P.stdin,t=P.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ReadBuffer,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=serializeMessage(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const U=s.getChild(`mcp`);function likec4Tool(e){return t=>n=>{let{name:r,description:i,...s}=e,c={description:i?.trim()??``,...s};return n.registerTool(r,c,async(...e)=>{let n=useLanguageServices();U.debug(`Calling tool {name}, args: {args}`,{name:r,args:e});try{let r=await t.apply(null,[n,...e]);return typeof r==`string`?{content:[{type:`text`,text:r}]}:Qe(c.outputSchema)?Zt(r,`content`)?r:{content:[{type:`text`,text:JSON.stringify(r)}]}:{content:[],structuredContent:r}}catch(e){return U.error(`Tool ${r} failed`,{err:e}),{content:[{type:`text`,text:a(e)}],isError:!0}}}),n}}var W;(function(e){e.assertEqual=e=>{};function assertIs(e){}e.assertIs=assertIs;function assertNever(e){throw Error()}e.assertNever=assertNever,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},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 n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function joinValues(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=joinValues,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(W||={});var yd;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(yd||={});const G=W.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 G.undefined;case`string`:return G.string;case`number`:return Number.isNaN(e)?G.nan:G.number;case`boolean`:return G.boolean;case`function`:return G.function;case`bigint`:return G.bigint;case`symbol`:return G.symbol;case`object`:return Array.isArray(e)?G.array:e===null?G.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?G.promise:typeof Map<`u`&&e instanceof Map?G.map:typeof Set<`u`&&e instanceof Set?G.set:typeof Date<`u`&&e instanceof Date?G.date:G.object;default:return G.unknown}},K=W.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 bd=class ZodError 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},n={_errors:[]},processError=e=>{for(let r of e.issues)if(r.code===`invalid_union`)r.unionErrors.map(processError);else if(r.code===`invalid_return_type`)processError(r.returnTypeError);else if(r.code===`invalid_arguments`)processError(r.argumentsError);else if(r.path.length===0)n._errors.push(t(r));else{let e=n,i=0;for(;i<r.path.length;){let n=r.path[i];i===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return processError(this),n}static assert(e){if(!(e instanceof ZodError))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,W.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};bd.create=e=>new bd(e);const errorMap=(e,t)=>{let n;switch(e.code){case K.invalid_type:n=e.received===G.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case K.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,W.jsonStringifyReplacer)}`;break;case K.unrecognized_keys:n=`Unrecognized key(s) in object: ${W.joinValues(e.keys,`, `)}`;break;case K.invalid_union:n=`Invalid input`;break;case K.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${W.joinValues(e.options)}`;break;case K.invalid_enum_value:n=`Invalid enum value. Expected ${W.joinValues(e.options)}, received '${e.received}'`;break;case K.invalid_arguments:n=`Invalid function arguments`;break;case K.invalid_return_type:n=`Invalid function return type`;break;case K.invalid_date:n=`Invalid date`;break;case K.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:W.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case K.too_small:n=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 K.too_big:n=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 K.custom:n=`Invalid input`;break;case K.invalid_intersection_types:n=`Intersection results could not be merged`;break;case K.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case K.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,W.assertNever(e)}return{message:n}};let xd=errorMap;function getErrorMap(){return xd}const makeIssue=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],s={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let c=``,l=r.filter(e=>!!e).slice().reverse();for(let e of l)c=e(s,{data:t,defaultError:c}).message;return{...i,path:a,message:c}};function addIssueToContext(e,t){let n=getErrorMap(),r=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(r)}var Sd=class ParseStatus{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return q;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let e of t){let t=await e.key,r=await e.value;n.push({key:t,value:r})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return q;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const q=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 J;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(J||={});var ParseInputLazyPath=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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(){if(this._error)return this._error;let t=new bd(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};let customMap=(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}};return{errorMap:customMap,description:i}}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 Sd,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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},r=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,r)}"~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 n=this._parseSync({data:e,path:[],parent:t});return isValid(n)?{value:n.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 n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(isAsync(r)?r:Promise.resolve(r));return handleResult(n,i)}refine(e,t){let getIssueProperties=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,n)=>{let r=e(t),setError=()=>n.addIssue({code:K.custom,...getIssueProperties(t)});return typeof Promise<`u`&&r instanceof Promise?r.then(e=>e?!0:(setError(),!1)):r?!0:(setError(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:Y.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 Wd.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:Y.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:Y.ZodDefault})}brand(){return new ZodBranded({typeName:Y.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:Y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Qd.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Cd=/^c[^\s-]{8,}$/i,wd=/^[0-9a-z]+$/,Td=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ed=/^[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,Dd=/^[a-z0-9_-]{21}$/i,Od=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kd=/^[-+]?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)?)??$/,Ad=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let jd;const Md=/^(?:(?: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])$/,Nd=/^(?:(?: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])$/,Pd=/^(([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]))$/,Fd=/^(([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])$/,Id=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ld=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rd=`((\\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])))`,zd=RegExp(`^${Rd}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${Rd}T${timeRegexSource(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&Md.test(e)||(t===`v6`||!t)&&Pd.test(e))}function isValidJWT(e,t){if(!Od.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&Nd.test(e)||(t===`v6`||!t)&&Fd.test(e))}var Bd=class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.string,received:t.parsedType}),q}let t=new Sd,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?addIssueToContext(n,{code:K.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&addIssueToContext(n,{code:K.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Ad.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`email`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)jd||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),jd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`emoji`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Ed.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`uuid`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Dd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`nanoid`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Cd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cuid`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)wd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cuid2`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Td.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`ulid`,code:K.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`url`,code:K.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`regex`,code:K.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?datetimeRegex(r).test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?zd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?timeRegex(r).test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?kd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`duration`,code:K.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?isValidIP(e.data,r.version)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`ip`,code:K.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?isValidJWT(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`jwt`,code:K.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?isValidCidr(e.data,r.version)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cidr`,code:K.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Id.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`base64`,code:K.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ld.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`base64url`,code:K.invalid_string,message:r.message}),t.dirty()):W.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:K.invalid_string,...J.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:`email`,...J.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...J.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...J.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...J.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...J.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...J.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...J.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...J.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...J.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...J.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...J.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,...J.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,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new ZodString({...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}};Bd.create=e=>new Bd({checks:[],typeName:Y.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Vd=class ZodNumber 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)!==G.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.number,received:t.parsedType}),q}let t,n=new Sd;for(let r of this._def.checks)r.kind===`int`?W.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?floatSafeRemainder(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.not_finite,message:r.message}),n.dirty()):W.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(e,t,n,r){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:J.toString(r)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:`int`,message:J.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:J.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:J.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:J.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`&&W.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Vd.create=e=>new Vd({checks:[],typeName:Y.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var Hd=class ZodBigInt 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)!==G.bigint)return this._getInvalidInput(e);let t,n=new Sd;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:K.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):W.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit(`min`,e,!0,J.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,J.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,J.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,J.toString(t))}setLimit(e,t,n,r){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:J.toString(r)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:J.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}};Hd.create=e=>new Hd({checks:[],typeName:Y.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)!==G.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.boolean,received:t.parsedType}),q}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:Y.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var Ud=class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.date,received:t.parsedType}),q}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:K.invalid_date}),q;let t=new Sd,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:K.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):W.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:J.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)}};Ud.create=e=>new Ud({checks:[],coerce:e?.coerce||!1,typeName:Y.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==G.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.symbol,received:t.parsedType}),q}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:Y.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==G.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.undefined,received:t.parsedType}),q}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:Y.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==G.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.null,received:t.parsedType}),q}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:Y.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:Y.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:Y.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.never,received:t.parsedType}),q}};ZodNever.create=e=>new ZodNever({typeName:Y.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==G.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.void,received:t.parsedType}),q}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:Y.ZodVoid,...processCreateParams(e)});var Wd=class ZodArray extends ZodType{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==G.array)return addIssueToContext(t,{code:K.invalid_type,expected:G.array,received:t.parsedType}),q;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(addIssueToContext(t,{code:e?K.too_big:K.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(addIssueToContext(t,{code:K.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(addIssueToContext(t,{code:K.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new ParseInputLazyPath(t,e,t.path,n)))).then(e=>Sd.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ParseInputLazyPath(t,e,t.path,n)));return Sd.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:J.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:J.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:J.toString(t)}})}nonempty(e){return this.min(1,e)}};Wd.create=(e,t)=>new Wd({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof Gd){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ZodOptional.create(deepPartialify(r))}return new Gd({...e._def,shape:()=>t})}return e instanceof Wd?new Wd({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof qd?qd.create(e.items.map(e=>deepPartialify(e))):e}var Gd=class ZodObject 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(),t=W.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==G.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.object,received:t.parsedType}),q}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let s=[];for(let e of i){let t=r[e],i=n.data[e];s.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)s.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(addIssueToContext(n,{code:K.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];s.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Sd.mergeObjectSync(t,e)):Sd.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new ZodObject({...this._def,unknownKeys:`strict`,...e===void 0?{}:{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;return t.code===`unrecognized_keys`?{message:J.errToObj(e).message??r}:{message:r}}}})}strip(){return new ZodObject({...this._def,unknownKeys:`strip`})}passthrough(){return new ZodObject({...this._def,unknownKeys:`passthrough`})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){let t={};for(let n of W.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}omit(e){let t={};for(let n of W.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){let t={};for(let n of W.objectKeys(this.shape)){let r=this.shape[n];t[n]=e&&!e[n]?r:r.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){let t={};for(let n of W.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof ZodOptional;)e=e._def.innerType;t[n]=e}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(W.objectKeys(this.shape))}};Gd.create=(e,t)=>new Gd({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:Y.ZodObject,...processCreateParams(t)}),Gd.strictCreate=(e,t)=>new Gd({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:Y.ZodObject,...processCreateParams(t)}),Gd.lazycreate=(e,t)=>new Gd({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:Y.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function handleResults(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new bd(e.ctx.common.issues));return addIssueToContext(t,{code:K.invalid_union,unionErrors:n}),q}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(handleResults);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new bd(e));return addIssueToContext(t,{code:K.invalid_union,unionErrors:i}),q}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:Y.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 Zd?e.options:e instanceof ZodNativeEnum?W.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 Kd=class ZodDiscriminatedUnion extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.object)return addIssueToContext(t,{code:K.invalid_type,expected:G.object,received:t.parsedType}),q;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:K.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let n of t){let t=getDiscriminator(n.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,n)}}return new ZodDiscriminatedUnion({typeName:Y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...processCreateParams(n)})}};function mergeValues(e,t){let n=getParsedType(e),r=getParsedType(t);if(e===t)return{valid:!0,data:e};if(n===G.object&&r===G.object){let n=W.objectKeys(t),r=W.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===G.array&&r===G.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],s=mergeValues(i,a);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===G.date&&r===G.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),handleParsed=(e,r)=>{if(isAborted(e)||isAborted(r))return q;let i=mergeValues(e.value,r.value);return i.valid?((isDirty(e)||isDirty(r))&&t.dirty(),{status:t.value,value:i.data}):(addIssueToContext(n,{code:K.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>handleParsed(e,t)):handleParsed(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ZodIntersection.create=(e,t,n)=>new ZodIntersection({left:e,right:t,typeName:Y.ZodIntersection,...processCreateParams(n)});var qd=class ZodTuple extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==G.array)return addIssueToContext(n,{code:K.invalid_type,expected:G.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:K.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),q;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:K.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new ParseInputLazyPath(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Sd.mergeArray(t,e)):Sd.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}};qd.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new qd({items:e,typeName:Y.ZodTuple,rest:null,...processCreateParams(t)})};var Jd=class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==G.object)return addIssueToContext(n,{code:K.invalid_type,expected:G.object,received:n.parsedType}),q;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ParseInputLazyPath(n,e,n.path,e)),value:a._parse(new ParseInputLazyPath(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Sd.mergeObjectAsync(t,r):Sd.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:Y.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:Bd.create(),valueType:e,typeName:Y.ZodRecord,...processCreateParams(t)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==G.map)return addIssueToContext(n,{code:K.invalid_type,expected:G.map,received:n.parsedType}),q;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ParseInputLazyPath(n,e,n.path,[a,`key`])),value:i._parse(new ParseInputLazyPath(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return q;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,n)=>new ZodMap({valueType:t,keyType:e,typeName:Y.ZodMap,...processCreateParams(n)});var Yd=class ZodSet extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==G.set)return addIssueToContext(n,{code:K.invalid_type,expected:G.set,received:n.parsedType}),q;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(addIssueToContext(n,{code:K.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(addIssueToContext(n,{code:K.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function finalizeSet(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return q;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let a=[...n.data.values()].map((e,t)=>i._parse(new ParseInputLazyPath(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>finalizeSet(e)):finalizeSet(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:J.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:J.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Yd.create=(e,t)=>new Yd({valueType:e,minSize:null,maxSize:null,typeName:Y.ZodSet,...processCreateParams(t)});var Xd=class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.function)return addIssueToContext(t,{code:K.invalid_type,expected:G.function,received:t.parsedType}),q;function makeArgsIssue(e,n){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:K.invalid_arguments,argumentsError:n}})}function makeReturnsIssue(e,n){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:K.invalid_return_type,returnTypeError:n}})}let n={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let i=new bd([]),a=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(makeArgsIssue(t,e)),i}),s=await Reflect.apply(r,this,a);return await e._def.returns._def.type.parseAsync(s,n).catch(e=>{throw i.addIssue(makeReturnsIssue(s,e)),i})})}{let e=this;return OK(function(...t){let i=e._def.args.safeParse(t,n);if(!i.success)throw new bd([makeArgsIssue(t,i.error)]);let a=Reflect.apply(r,this,i.data),s=e._def.returns.safeParse(a,n);if(!s.success)throw new bd([makeReturnsIssue(a,s.error)]);return s.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:qd.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ZodFunction({args:e||qd.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:Y.ZodFunction,...processCreateParams(n)})}},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:Y.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:K.invalid_literal,expected:this._def.value}),q}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:Y.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new Zd({values:e,typeName:Y.ZodEnum,...processCreateParams(t)})}var Zd=class ZodEnum extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{expected:W.joinValues(n),received:t.parsedType,code:K.invalid_type}),q}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:K.invalid_enum_value,options:n}),q}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(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}};Zd.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=W.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==G.string&&n.parsedType!==G.number){let e=W.objectValues(t);return addIssueToContext(n,{expected:W.joinValues(e),received:n.parsedType,code:K.invalid_type}),q}if(this._cache||=new Set(W.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=W.objectValues(t);return addIssueToContext(n,{received:n.data,code:K.invalid_enum_value,options:e}),q}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:Y.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==G.promise&&t.common.async===!1)return addIssueToContext(t,{code:K.invalid_type,expected:G.promise,received:t.parsedType}),q;let n=t.parsedType===G.promise?t.data:Promise.resolve(t.data);return OK(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:Y.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{addIssueToContext(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return q;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?DIRTY(r.value):r});{if(t.value===`aborted`)return q;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?q:r.status===`dirty`||t.value===`dirty`?DIRTY(r.value):r}}if(r.type===`refinement`){let executeRefinement=e=>{let t=r.refinement(e,i);if(n.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(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value),{status:t.value,value:e.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>e.status===`aborted`?q:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value).then(()=>({status:t.value,value:e.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(e))return q;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>isValid(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):q)}W.assertNever(r)}};ZodEffects.create=(e,t,n)=>new ZodEffects({schema:e,typeName:Y.ZodEffects,effect:t,...processCreateParams(n)}),ZodEffects.createWithPreprocess=(e,t,n)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:Y.ZodEffects,...processCreateParams(n)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===G.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:Y.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===G.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:Y.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===G.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:Y.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),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new bd(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new bd(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:Y.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==G.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:K.invalid_type,expected:G.nan,received:t.parsedType}),q}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:Y.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Qd=class ZodPipeline extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){let handleAsync=async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})};return handleAsync()}{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?q:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:Y.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),freeze=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>freeze(e)):freeze(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:Y.ZodReadonly,...processCreateParams(t)}),Gd.lazycreate;var Y;(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`})(Y||={});const X=Bd.create,Z=Vd.create;ZodNaN.create,Hd.create;const $d=ZodBoolean.create;Ud.create,ZodSymbol.create,ZodUndefined.create,ZodNull.create,ZodAny.create;const ef=ZodUnknown.create;ZodNever.create,ZodVoid.create;const Q=Wd.create,$=Gd.create;Gd.strictCreate;const tf=ZodUnion.create,nf=Kd.create;ZodIntersection.create,qd.create;const rf=Jd.create;ZodMap.create,Yd.create,Xd.create,ZodLazy.create;const af=ZodLiteral.create,of=Zd.create;ZodNativeEnum.create,ZodPromise.create,ZodEffects.create,ZodOptional.create,ZodNullable.create,ZodEffects.createWithPreprocess,Qd.create;const sf=Me(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ke.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Se(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Te(e,t,n),e.parseAsync=async(t,n)=>we(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ae(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>xe(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),cf=Me(`ZodMiniObject`,(e,t)=>{De.init(e,t),sf.init(e,t),Ne(e,`shape`,()=>t.shape)});function object(e,t){let n={type:`object`,shape:e??{},...Ce(t)};return new cf(n)}function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let n=t.every(isZ4Schema),r=t.every(e=>!isZ4Schema(e));if(n)return object(e);if(r)return $(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?Te(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await Ae(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,n=e;if(!t._def&&!n._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 n=e.value;if(n!==void 0)return n}function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const lf=Symbol(`Let zodToJsonSchema decide on which parser to use`),uf={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`?{...uf,name:e}:{...uf,...e},getRefs=e=>{let t=getDefaultOptions(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function setResponseValueAndErrors(e,t,n,r,i){e[t]=n,addErrorMessage(e,t,r,i)}const getRelativePath=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].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 n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Y.ZodAny&&(n.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(n,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function parseBigintDef(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`minimum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`maximum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:setResponseValueAndErrors(n,`multipleOf`,r.value,r.message,t)}return n}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,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>parseDateDef(e,t,n))};switch(r){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 n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:setResponseValueAndErrors(n,`minimum`,r.value,r.message,t);break;case`max`:setResponseValueAndErrors(n,`maximum`,r.value,r.message,t)}return n};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 n=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(isJsonSchema7AllOfType(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function parseLiteralDef(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let df;const ff={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:()=>(df===void 0&&(df=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),df),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 n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:setResponseValueAndErrors(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:setResponseValueAndErrors(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(n,`email`,r.message,t);break;case`format:idn-email`:addFormat(n,`idn-email`,r.message,t);break;case`pattern:zod`:addPattern(n,ff.email,r.message,t)}break;case`url`:addFormat(n,`uri`,r.message,t);break;case`uuid`:addFormat(n,`uuid`,r.message,t);break;case`regex`:addPattern(n,r.regex,r.message,t);break;case`cuid`:addPattern(n,ff.cuid,r.message,t);break;case`cuid2`:addPattern(n,ff.cuid2,r.message,t);break;case`startsWith`:addPattern(n,RegExp(`^${escapeLiteralCheckValue(r.value,t)}`),r.message,t);break;case`endsWith`:addPattern(n,RegExp(`${escapeLiteralCheckValue(r.value,t)}$`),r.message,t);break;case`datetime`:addFormat(n,`date-time`,r.message,t);break;case`date`:addFormat(n,`date`,r.message,t);break;case`time`:addFormat(n,`time`,r.message,t);break;case`duration`:addFormat(n,`duration`,r.message,t);break;case`length`:setResponseValueAndErrors(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),setResponseValueAndErrors(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:addPattern(n,RegExp(escapeLiteralCheckValue(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&addFormat(n,`ipv4`,r.message,t),r.version!==`v4`&&addFormat(n,`ipv6`,r.message,t);break;case`base64url`:addPattern(n,ff.base64url,r.message,t);break;case`jwt`:addPattern(n,ff.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&addPattern(n,ff.ipv4Cidr,r.message,t),r.version!==`v4`&&addPattern(n,ff.ipv6Cidr,r.message,t);break;case`emoji`:addPattern(n,ff.emoji(),r.message,t);break;case`ulid`:addPattern(n,ff.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(n,`binary`,r.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:addPattern(n,ff.base64,r.message,t)}break;case`nanoid`:addPattern(n,ff.nanoid,r.message,t)}return n}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const pf=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let n=0;n<e.length;n++)pf.has(e[n])||(t+=`\\`),t+=e[n];return t}function addFormat(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):setResponseValueAndErrors(e,`format`,t,n,r)}function addPattern(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.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,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,r),n,r)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,s=!1,c=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(s){if(r[e].match(/[a-z]/)){c?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),c=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],c=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
337
+ `),handler:e=>{let t;if(e.nodeIpc||e.stdio||e.socket||e.pipe)t=(0,wc.createConnection)(wc.ProposedFeatures.all);else throw Error(`No transport specified`);m({lspConnection:t,useStdErr:e.stdio===!0,colors:S.isColorSupported,enableTelemetry:e.telemetry,logLevel:e.verbose?qs:e.logLevel}),startLanguageServer({connection:t,enableManualLayouts:e.manualLayouts,enableWatcher:e.watch,graphviz:e.useDot?`binary`:`wasm`,configureLogger:!1})}})}t(lsp_default,`default`);function createContext(e={}){let t,n=!1,checkConflict=e=>{if(t&&t!==e)throw Error(`Context conflict`)},r;if(e.asyncContext){let t=e.AsyncLocalStorage||globalThis.AsyncLocalStorage;t?r=new t:console.warn("[unctx] `AsyncLocalStorage` is not provided.")}let _getCurrentInstance=()=>{if(r){let e=r.getStore();if(e!==void 0)return e}return t};return{use:()=>{let e=_getCurrentInstance();if(e===void 0)throw Error(`Context is not available`);return e},tryUse:()=>_getCurrentInstance(),set:(e,r)=>{r||checkConflict(e),t=e,n=!0},unset:()=>{t=void 0,n=!1},call:(e,i)=>{checkConflict(e),t=e;try{return r?r.run(e,i):i()}finally{n||(t=void 0)}},async callAsync(e,i){t=e;let onRestore=()=>{t=e},onLeave=()=>t===e?onRestore:void 0;Oc.add(onLeave);try{let a=r?r.run(e,i):i();return n||(t=void 0),await a}finally{Oc.delete(onLeave)}}}}function createNamespace(e={}){let t={};return{get(n,r={}){return t[n]||(t[n]=createContext({...e,...r})),t[n]}}}const Tc=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof global<`u`?global:typeof window<`u`?window:{},Ec=`__unctx__`;Tc[Ec]||(Tc[Ec]=createNamespace());const Dc=`__unctx_async_handlers__`,Oc=Tc[Dc]||(Tc[Dc]=new Set),kc=createContext(),Ac=createContext();function useLanguageServices(){return Ac.use()}function setMcpServerCtx(e){return e?kc.set(e,!0):kc.unset(),e}function setLanguageServicesCtx(e){return e?Ac.set(e,!0):Ac.unset(),e}const jc=`2025-11-25`,Mc=[jc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Nc=`io.modelcontextprotocol/related-task`,Pc=Ie(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Fc=w([E(),M().int()]),Ic=E();Pe({ttl:M().optional(),pollInterval:M().optional()});const Lc=O({ttl:M().optional()}),Rc=O({taskId:E()}),zc=Pe({progressToken:Fc.optional(),[Nc]:Rc.optional()}),Bc=O({_meta:zc.optional()}),Vc=Bc.extend({task:Lc.optional()}),isTaskAugmentedRequestParams=e=>Vc.safeParse(e).success,Hc=O({method:E(),params:Bc.loose().optional()}),Uc=O({_meta:zc.optional()}),Wc=O({method:E(),params:Uc.loose().optional()}),Gc=Pe({_meta:zc.optional()}),Kc=w([E(),M().int()]),qc=O({jsonrpc:k(`2.0`),id:Kc,...Hc.shape}).strict(),isJSONRPCRequest=e=>qc.safeParse(e).success,Jc=O({jsonrpc:k(`2.0`),...Wc.shape}).strict(),isJSONRPCNotification=e=>Jc.safeParse(e).success,Yc=O({jsonrpc:k(`2.0`),id:Kc,result:Gc}).strict(),isJSONRPCResultResponse=e=>Yc.safeParse(e).success;var G;(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`})(G||={});const Xc=O({jsonrpc:k(`2.0`),id:Kc.optional(),error:O({code:M().int(),message:E(),data:T().optional()})}).strict(),isJSONRPCErrorResponse=e=>Xc.safeParse(e).success,Zc=w([qc,Jc,Yc,Xc]);w([Yc,Xc]);const Qc=Gc.strict(),$c=Uc.extend({requestId:Kc.optional(),reason:E().optional()}),el=Wc.extend({method:k(`notifications/cancelled`),params:$c}),tl=O({src:E(),mimeType:E().optional(),sizes:A(E()).optional(),theme:D([`light`,`dark`]).optional()}),nl=O({icons:A(tl).optional()}),rl=O({name:E(),title:E().optional()}),il=rl.extend({...rl.shape,...nl.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),al=Ve(O({applyDefaults:j().optional()}),C(E(),T())),ol=Ae(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ve(O({form:al.optional(),url:Pc.optional()}),C(E(),T()).optional())),sl=Pe({list:Pc.optional(),cancel:Pc.optional(),requests:Pe({sampling:Pe({createMessage:Pc.optional()}).optional(),elicitation:Pe({create:Pc.optional()}).optional()}).optional()}),cl=Pe({list:Pc.optional(),cancel:Pc.optional(),requests:Pe({tools:Pe({call:Pc.optional()}).optional()}).optional()}),ll=O({experimental:C(E(),Pc).optional(),sampling:O({context:Pc.optional(),tools:Pc.optional()}).optional(),elicitation:ol.optional(),roots:O({listChanged:j().optional()}).optional(),tasks:sl.optional(),extensions:C(E(),Pc).optional()}),ul=Bc.extend({protocolVersion:E(),capabilities:ll,clientInfo:il}),dl=Hc.extend({method:k(`initialize`),params:ul}),isInitializeRequest=e=>dl.safeParse(e).success,fl=O({experimental:C(E(),Pc).optional(),logging:Pc.optional(),completions:Pc.optional(),prompts:O({listChanged:j().optional()}).optional(),resources:O({subscribe:j().optional(),listChanged:j().optional()}).optional(),tools:O({listChanged:j().optional()}).optional(),tasks:cl.optional(),extensions:C(E(),Pc).optional()}),pl=Gc.extend({protocolVersion:E(),capabilities:fl,serverInfo:il,instructions:E().optional()}),ml=Wc.extend({method:k(`notifications/initialized`),params:Uc.optional()}),hl=Hc.extend({method:k(`ping`),params:Bc.optional()}),gl=O({progress:M(),total:qe(M()),message:qe(E())}),_l=O({...Uc.shape,...gl.shape,progressToken:Fc}),vl=Wc.extend({method:k(`notifications/progress`),params:_l}),yl=Bc.extend({cursor:Ic.optional()}),bl=Hc.extend({params:yl.optional()}),xl=Gc.extend({nextCursor:Ic.optional()}),Sl=D([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Cl=O({taskId:E(),status:Sl,ttl:w([M(),Ue()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:qe(M()),statusMessage:qe(E())}),wl=Gc.extend({task:Cl}),Tl=Uc.merge(Cl),El=Wc.extend({method:k(`notifications/tasks/status`),params:Tl}),Dl=Hc.extend({method:k(`tasks/get`),params:Bc.extend({taskId:E()})}),Ol=Gc.merge(Cl),kl=Hc.extend({method:k(`tasks/result`),params:Bc.extend({taskId:E()})});Gc.loose();const Al=bl.extend({method:k(`tasks/list`)}),jl=xl.extend({tasks:A(Cl)}),Ml=Hc.extend({method:k(`tasks/cancel`),params:Bc.extend({taskId:E()})}),Nl=Gc.merge(Cl),Pl=O({uri:E(),mimeType:qe(E()),_meta:C(E(),T()).optional()}),Fl=Pl.extend({text:E()}),Il=E().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ll=Pl.extend({blob:Il}),Rl=D([`user`,`assistant`]),zl=O({audience:A(Rl).optional(),priority:M().min(0).max(1).optional(),lastModified:ze({offset:!0}).optional()}),Bl=O({...rl.shape,...nl.shape,uri:E(),description:qe(E()),mimeType:qe(E()),size:qe(M()),annotations:zl.optional(),_meta:qe(Pe({}))}),Vl=O({...rl.shape,...nl.shape,uriTemplate:E(),description:qe(E()),mimeType:qe(E()),annotations:zl.optional(),_meta:qe(Pe({}))}),Hl=bl.extend({method:k(`resources/list`)}),Ul=xl.extend({resources:A(Bl)}),Wl=bl.extend({method:k(`resources/templates/list`)}),Gl=xl.extend({resourceTemplates:A(Vl)}),Kl=Bc.extend({uri:E()}),ql=Kl,Jl=Hc.extend({method:k(`resources/read`),params:ql}),Yl=Gc.extend({contents:A(w([Fl,Ll]))}),Xl=Wc.extend({method:k(`notifications/resources/list_changed`),params:Uc.optional()}),Zl=Kl,Ql=Hc.extend({method:k(`resources/subscribe`),params:Zl}),$l=Kl,eu=Hc.extend({method:k(`resources/unsubscribe`),params:$l}),tu=Uc.extend({uri:E()}),nu=Wc.extend({method:k(`notifications/resources/updated`),params:tu}),ru=O({name:E(),description:qe(E()),required:qe(j())}),iu=O({...rl.shape,...nl.shape,description:qe(E()),arguments:qe(A(ru)),_meta:qe(Pe({}))}),au=bl.extend({method:k(`prompts/list`)}),ou=xl.extend({prompts:A(iu)}),su=Bc.extend({name:E(),arguments:C(E(),E()).optional()}),cu=Hc.extend({method:k(`prompts/get`),params:su}),lu=O({type:k(`text`),text:E(),annotations:zl.optional(),_meta:C(E(),T()).optional()}),uu=O({type:k(`image`),data:Il,mimeType:E(),annotations:zl.optional(),_meta:C(E(),T()).optional()}),du=O({type:k(`audio`),data:Il,mimeType:E(),annotations:zl.optional(),_meta:C(E(),T()).optional()}),fu=O({type:k(`tool_use`),name:E(),id:E(),input:C(E(),T()),_meta:C(E(),T()).optional()}),pu=O({type:k(`resource`),resource:w([Fl,Ll]),annotations:zl.optional(),_meta:C(E(),T()).optional()}),mu=Bl.extend({type:k(`resource_link`)}),hu=w([lu,uu,du,mu,pu]),gu=O({role:Rl,content:hu}),_u=Gc.extend({description:E().optional(),messages:A(gu)}),vu=Wc.extend({method:k(`notifications/prompts/list_changed`),params:Uc.optional()}),yu=O({title:E().optional(),readOnlyHint:j().optional(),destructiveHint:j().optional(),idempotentHint:j().optional(),openWorldHint:j().optional()}),bu=O({taskSupport:D([`required`,`optional`,`forbidden`]).optional()}),xu=O({...rl.shape,...nl.shape,description:E().optional(),inputSchema:O({type:k(`object`),properties:C(E(),Pc).optional(),required:A(E()).optional()}).catchall(T()),outputSchema:O({type:k(`object`),properties:C(E(),Pc).optional(),required:A(E()).optional()}).catchall(T()).optional(),annotations:yu.optional(),execution:bu.optional(),_meta:C(E(),T()).optional()}),Su=bl.extend({method:k(`tools/list`)}),Cu=xl.extend({tools:A(xu)}),wu=Gc.extend({content:A(hu).default([]),structuredContent:C(E(),T()).optional(),isError:j().optional()});wu.or(Gc.extend({toolResult:T()}));const Tu=Vc.extend({name:E(),arguments:C(E(),T()).optional()}),Eu=Hc.extend({method:k(`tools/call`),params:Tu}),Du=Wc.extend({method:k(`notifications/tools/list_changed`),params:Uc.optional()});O({autoRefresh:j().default(!0),debounceMs:M().int().nonnegative().default(300)});const Ou=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ku=Bc.extend({level:Ou}),Au=Hc.extend({method:k(`logging/setLevel`),params:ku}),ju=Uc.extend({level:Ou,logger:E().optional(),data:T()}),Mu=Wc.extend({method:k(`notifications/message`),params:ju}),Nu=O({name:E().optional()}),Pu=O({hints:A(Nu).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Fu=O({mode:D([`auto`,`required`,`none`]).optional()}),Iu=O({type:k(`tool_result`),toolUseId:E().describe(`The unique identifier for the corresponding tool call.`),content:A(hu).default([]),structuredContent:O({}).loose().optional(),isError:j().optional(),_meta:C(E(),T()).optional()}),Lu=Le(`type`,[lu,uu,du]),Ru=Le(`type`,[lu,uu,du,fu,Iu]),zu=O({role:Rl,content:w([Ru,A(Ru)]),_meta:C(E(),T()).optional()}),Bu=Vc.extend({messages:A(zu),modelPreferences:Pu.optional(),systemPrompt:E().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:A(E()).optional(),metadata:Pc.optional(),tools:A(xu).optional(),toolChoice:Fu.optional()}),Vu=Hc.extend({method:k(`sampling/createMessage`),params:Bu}),Hu=Gc.extend({model:E(),stopReason:qe(D([`endTurn`,`stopSequence`,`maxTokens`]).or(E())),role:Rl,content:Lu}),Uu=Gc.extend({model:E(),stopReason:qe(D([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(E())),role:Rl,content:w([Ru,A(Ru)])}),Wu=O({type:k(`boolean`),title:E().optional(),description:E().optional(),default:j().optional()}),Gu=O({type:k(`string`),title:E().optional(),description:E().optional(),minLength:M().optional(),maxLength:M().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:E().optional()}),Ku=O({type:D([`number`,`integer`]),title:E().optional(),description:E().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),qu=O({type:k(`string`),title:E().optional(),description:E().optional(),enum:A(E()),default:E().optional()}),Ju=O({type:k(`string`),title:E().optional(),description:E().optional(),oneOf:A(O({const:E(),title:E()})),default:E().optional()}),Yu=O({type:k(`string`),title:E().optional(),description:E().optional(),enum:A(E()),enumNames:A(E()).optional(),default:E().optional()}),Xu=w([qu,Ju]),Zu=O({type:k(`array`),title:E().optional(),description:E().optional(),minItems:M().optional(),maxItems:M().optional(),items:O({type:k(`string`),enum:A(E())}),default:A(E()).optional()}),Qu=O({type:k(`array`),title:E().optional(),description:E().optional(),minItems:M().optional(),maxItems:M().optional(),items:O({anyOf:A(O({const:E(),title:E()}))}),default:A(E()).optional()}),$u=w([Zu,Qu]),ed=w([Yu,Xu,$u]),td=w([ed,Wu,Gu,Ku]),nd=Vc.extend({mode:k(`form`).optional(),message:E(),requestedSchema:O({type:k(`object`),properties:C(E(),td),required:A(E()).optional()})}),rd=Vc.extend({mode:k(`url`),message:E(),elicitationId:E(),url:E().url()}),id=w([nd,rd]),ad=Hc.extend({method:k(`elicitation/create`),params:id}),od=Uc.extend({elicitationId:E()}),sd=Wc.extend({method:k(`notifications/elicitation/complete`),params:od}),cd=Gc.extend({action:D([`accept`,`decline`,`cancel`]),content:Ae(e=>e===null?void 0:e,C(E(),w([E(),M(),j(),A(E())])).optional())}),ld=O({type:k(`ref/resource`),uri:E()}),ud=O({type:k(`ref/prompt`),name:E()}),dd=Bc.extend({ref:w([ud,ld]),argument:O({name:E(),value:E()}),context:O({arguments:C(E(),E()).optional()}).optional()}),fd=Hc.extend({method:k(`completion/complete`),params:dd});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 pd=Gc.extend({completion:Pe({values:A(E()).max(100),total:qe(M().int()),hasMore:qe(j())})}),md=O({uri:E().startsWith(`file://`),name:E().optional(),_meta:C(E(),T()).optional()}),hd=Hc.extend({method:k(`roots/list`),params:Bc.optional()}),gd=Gc.extend({roots:A(md)}),_d=Wc.extend({method:k(`notifications/roots/list_changed`),params:Uc.optional()});w([hl,dl,fd,Au,cu,au,Hl,Wl,Jl,Ql,eu,Eu,Su,Dl,kl,Al,Ml]),w([el,vl,ml,_d,El]),w([Qc,Hu,Uu,cd,gd,Ol,jl,wl]),w([hl,Vu,ad,hd,Dl,kl,Al,Ml]),w([el,vl,Mu,nu,Xl,Du,vu,El,sd]),w([Qc,pl,pd,_u,ou,Ul,Gl,Yl,wu,Cu,Ol,jl,wl]);var K=class McpError extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(e,t,n){if(e===G.UrlElicitationRequired&&n){let e=n;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,t)}return new McpError(e,t,n)}},UrlElicitationRequiredError=class extends K{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ReadBuffer=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
338
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),deserializeMessage(t)}clear(){this._buffer=void 0}};function deserializeMessage(e){return Zc.parse(JSON.parse(e))}function serializeMessage(e){return JSON.stringify(e)+`
339
+ `}var StdioServerTransport=class{constructor(e=I.stdin,t=I.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ReadBuffer,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=serializeMessage(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const q=s.getChild(`mcp`);function mcpToolSchema(e){return O(e).meta({$schema:`https://json-schema.org/draft/2020-12/schema`})}function likec4Tool(e){return t=>n=>{let{name:r,description:i,inputSchema:s,outputSchema:c,...l}=e,u=c!==void 0&&!Xe(c),f={description:i?.trim()??``,...l,...s===void 0?{}:{inputSchema:mcpToolSchema(s)},...c===void 0?{}:{outputSchema:mcpToolSchema(c)}};return n.registerTool(r,f,async(...e)=>{let n=useLanguageServices();q.debug(`Calling tool {name}, args: {args}`,{name:r,args:e});try{let r=await t.apply(null,[n,...e]);return typeof r==`string`?{content:[{type:`text`,text:r}]}:u?{content:[],structuredContent:r}:Qt(r,`content`)?r:{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return q.error(`Tool ${r} failed`,{err:e}),{content:[{type:`text`,text:a(e)}],isError:!0}}}),n}}var J;(function(e){e.assertEqual=e=>{};function assertIs(e){}e.assertIs=assertIs;function assertNever(e){throw Error()}e.assertNever=assertNever,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},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 n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function joinValues(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=joinValues,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(J||={});var vd;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(vd||={});const Y=J.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 Y.undefined;case`string`:return Y.string;case`number`:return Number.isNaN(e)?Y.nan:Y.number;case`boolean`:return Y.boolean;case`function`:return Y.function;case`bigint`:return Y.bigint;case`symbol`:return Y.symbol;case`object`:return Array.isArray(e)?Y.array:e===null?Y.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?Y.promise:typeof Map<`u`&&e instanceof Map?Y.map:typeof Set<`u`&&e instanceof Set?Y.set:typeof Date<`u`&&e instanceof Date?Y.date:Y.object;default:return Y.unknown}},X=J.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 yd=class ZodError 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},n={_errors:[]},processError=e=>{for(let r of e.issues)if(r.code===`invalid_union`)r.unionErrors.map(processError);else if(r.code===`invalid_return_type`)processError(r.returnTypeError);else if(r.code===`invalid_arguments`)processError(r.argumentsError);else if(r.path.length===0)n._errors.push(t(r));else{let e=n,i=0;for(;i<r.path.length;){let n=r.path[i];i===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return processError(this),n}static assert(e){if(!(e instanceof ZodError))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};yd.create=e=>new yd(e);const errorMap=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===Y.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,J.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${J.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${J.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${J.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:J.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.too_small:n=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 X.too_big:n=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 X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,J.assertNever(e)}return{message:n}};let bd=errorMap;function getErrorMap(){return bd}const makeIssue=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],s={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let c=``,l=r.filter(e=>!!e).slice().reverse();for(let e of l)c=e(s,{data:t,defaultError:c}).message;return{...i,path:a,message:c}};function addIssueToContext(e,t){let n=getErrorMap(),r=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(r)}var xd=class ParseStatus{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return Z;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let e of t){let t=await e.key,r=await e.value;n.push({key:t,value:r})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return Z;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const Z=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 Q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(Q||={});var ParseInputLazyPath=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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(){if(this._error)return this._error;let t=new yd(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};let customMap=(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}};return{errorMap:customMap,description:i}}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 xd,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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},r=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,r)}"~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 n=this._parseSync({data:e,path:[],parent:t});return isValid(n)?{value:n.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 n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(isAsync(r)?r:Promise.resolve(r));return handleResult(n,i)}refine(e,t){let getIssueProperties=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,n)=>{let r=e(t),setError=()=>n.addIssue({code:X.custom,...getIssueProperties(t)});return typeof Promise<`u`&&r instanceof Promise?r.then(e=>e?!0:(setError(),!1)):r?!0:(setError(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:$.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 Ud.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:$.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:$.ZodDefault})}brand(){return new ZodBranded({typeName:$.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:$.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Zd.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Sd=/^c[^\s-]{8,}$/i,Cd=/^[0-9a-z]+$/,wd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Td=/^[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,Ed=/^[a-z0-9_-]{21}$/i,Dd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Od=/^[-+]?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)?)??$/,kd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Ad;const jd=/^(?:(?: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])$/,Md=/^(?:(?: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])$/,Nd=/^(([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]))$/,Pd=/^(([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])$/,Fd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Id=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ld=`((\\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])))`,Rd=RegExp(`^${Ld}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${Ld}T${timeRegexSource(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!((t!==`v4`&&t||!jd.test(e))&&(t!==`v6`&&t||!Nd.test(e)))}function isValidJWT(e,t){if(!Dd.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!((t!==`v4`&&t||!Md.test(e))&&(t!==`v6`&&t||!Pd.test(e)))}var zd=class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Y.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.string,received:t.parsedType}),Z}let t=new xd,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?addIssueToContext(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&addIssueToContext(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)kd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Ad||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Ad.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Td.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ed.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Sd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Cd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)wd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`url`,code:X.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`regex`,code:X.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?datetimeRegex(r).test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Rd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?timeRegex(r).test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Od.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?isValidIP(e.data,r.version)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?isValidJWT(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?isValidCidr(e.data,r.version)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Fd.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Id.test(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):J.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...Q.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:`email`,...Q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...Q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...Q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...Q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...Q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...Q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...Q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...Q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...Q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...Q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...Q.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,...Q.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,...Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...Q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...Q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...Q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...Q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...Q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...Q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...Q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...Q.errToObj(t)})}nonempty(e){return this.min(1,Q.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new ZodString({...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}};zd.create=e=>new zd({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Bd=class ZodNumber 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)!==Y.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.number,received:t.parsedType}),Z}let t,n=new xd;for(let r of this._def.checks)r.kind===`int`?J.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?floatSafeRemainder(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.not_finite,message:r.message}),n.dirty()):J.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Q.toString(t))}setLimit(e,t,n,r){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Q.toString(r)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:`int`,message:Q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:Q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:Q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:Q.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`&&J.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Bd.create=e=>new Bd({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var Vd=class ZodBigInt 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)!==Y.bigint)return this._getInvalidInput(e);let t,n=new xd;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):J.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.bigint,received:t.parsedType}),Z}gte(e,t){return this.setLimit(`min`,e,!0,Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Q.toString(t))}setLimit(e,t,n,r){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Q.toString(r)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Q.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}};Vd.create=e=>new Vd({checks:[],typeName:$.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)!==Y.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.boolean,received:t.parsedType}),Z}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var Hd=class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Y.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.date,received:t.parsedType}),Z}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:X.invalid_date}),Z;let t=new xd,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):J.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:Q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:Q.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)}};Hd.create=e=>new Hd({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==Y.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.symbol,received:t.parsedType}),Z}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:$.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==Y.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.undefined,received:t.parsedType}),Z}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:$.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==Y.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.null,received:t.parsedType}),Z}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:$.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:$.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:$.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.never,received:t.parsedType}),Z}};ZodNever.create=e=>new ZodNever({typeName:$.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==Y.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.void,received:t.parsedType}),Z}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:$.ZodVoid,...processCreateParams(e)});var Ud=class ZodArray extends ZodType{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==Y.array)return addIssueToContext(t,{code:X.invalid_type,expected:Y.array,received:t.parsedType}),Z;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(addIssueToContext(t,{code:e?X.too_big:X.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(addIssueToContext(t,{code:X.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(addIssueToContext(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new ParseInputLazyPath(t,e,t.path,n)))).then(e=>xd.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ParseInputLazyPath(t,e,t.path,n)));return xd.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:Q.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:Q.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:Q.toString(t)}})}nonempty(e){return this.min(1,e)}};Ud.create=(e,t)=>new Ud({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof Wd){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ZodOptional.create(deepPartialify(r))}return new Wd({...e._def,shape:()=>t})}return e instanceof Ud?new Ud({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof Kd?Kd.create(e.items.map(e=>deepPartialify(e))):e}var Wd=class ZodObject 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(),t=J.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Y.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.object,received:t.parsedType}),Z}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let s=[];for(let e of i){let t=r[e],i=n.data[e];s.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)s.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(addIssueToContext(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];s.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>xd.mergeObjectSync(t,e)):xd.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return Q.errToObj,new ZodObject({...this._def,unknownKeys:`strict`,...e===void 0?{}:{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;return t.code===`unrecognized_keys`?{message:Q.errToObj(e).message??r}:{message:r}}}})}strip(){return new ZodObject({...this._def,unknownKeys:`strip`})}passthrough(){return new ZodObject({...this._def,unknownKeys:`passthrough`})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:$.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){let t={};for(let n of J.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}omit(e){let t={};for(let n of J.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){let t={};for(let n of J.objectKeys(this.shape)){let r=this.shape[n];t[n]=e&&!e[n]?r:r.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){let t={};for(let n of J.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof ZodOptional;)e=e._def.innerType;t[n]=e}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(J.objectKeys(this.shape))}};Wd.create=(e,t)=>new Wd({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:$.ZodObject,...processCreateParams(t)}),Wd.strictCreate=(e,t)=>new Wd({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:$.ZodObject,...processCreateParams(t)}),Wd.lazycreate=(e,t)=>new Wd({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:$.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function handleResults(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new yd(e.ctx.common.issues));return addIssueToContext(t,{code:X.invalid_union,unionErrors:n}),Z}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(handleResults);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new yd(e));return addIssueToContext(t,{code:X.invalid_union,unionErrors:i}),Z}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:$.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 Xd?e.options:e instanceof ZodNativeEnum?J.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 Gd=class ZodDiscriminatedUnion extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Y.object)return addIssueToContext(t,{code:X.invalid_type,expected:Y.object,received:t.parsedType}),Z;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let n of t){let t=getDiscriminator(n.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,n)}}return new ZodDiscriminatedUnion({typeName:$.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...processCreateParams(n)})}};function mergeValues(e,t){let n=getParsedType(e),r=getParsedType(t);if(e===t)return{valid:!0,data:e};if(n===Y.object&&r===Y.object){let n=J.objectKeys(t),r=J.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===Y.array&&r===Y.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],s=mergeValues(i,a);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===Y.date&&r===Y.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),handleParsed=(e,r)=>{if(isAborted(e)||isAborted(r))return Z;let i=mergeValues(e.value,r.value);return i.valid?((isDirty(e)||isDirty(r))&&t.dirty(),{status:t.value,value:i.data}):(addIssueToContext(n,{code:X.invalid_intersection_types}),Z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>handleParsed(e,t)):handleParsed(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ZodIntersection.create=(e,t,n)=>new ZodIntersection({left:e,right:t,typeName:$.ZodIntersection,...processCreateParams(n)});var Kd=class ZodTuple extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.array)return addIssueToContext(n,{code:X.invalid_type,expected:Y.array,received:n.parsedType}),Z;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),Z;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new ParseInputLazyPath(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>xd.mergeArray(t,e)):xd.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}};Kd.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Kd({items:e,typeName:$.ZodTuple,rest:null,...processCreateParams(t)})};var qd=class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.object)return addIssueToContext(n,{code:X.invalid_type,expected:Y.object,received:n.parsedType}),Z;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ParseInputLazyPath(n,e,n.path,e)),value:a._parse(new ParseInputLazyPath(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?xd.mergeObjectAsync(t,r):xd.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:$.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:zd.create(),valueType:e,typeName:$.ZodRecord,...processCreateParams(t)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.map)return addIssueToContext(n,{code:X.invalid_type,expected:Y.map,received:n.parsedType}),Z;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ParseInputLazyPath(n,e,n.path,[a,`key`])),value:i._parse(new ParseInputLazyPath(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return Z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return Z;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,n)=>new ZodMap({valueType:t,keyType:e,typeName:$.ZodMap,...processCreateParams(n)});var Jd=class ZodSet extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Y.set)return addIssueToContext(n,{code:X.invalid_type,expected:Y.set,received:n.parsedType}),Z;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(addIssueToContext(n,{code:X.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(addIssueToContext(n,{code:X.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function finalizeSet(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return Z;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let a=[...n.data.values()].map((e,t)=>i._parse(new ParseInputLazyPath(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>finalizeSet(e)):finalizeSet(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:Q.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:Q.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Jd.create=(e,t)=>new Jd({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...processCreateParams(t)});var Yd=class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Y.function)return addIssueToContext(t,{code:X.invalid_type,expected:Y.function,received:t.parsedType}),Z;function makeArgsIssue(e,n){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function makeReturnsIssue(e,n){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let n={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let i=new yd([]),a=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(makeArgsIssue(t,e)),i}),s=await Reflect.apply(r,this,a);return await e._def.returns._def.type.parseAsync(s,n).catch(e=>{throw i.addIssue(makeReturnsIssue(s,e)),i})})}{let e=this;return OK(function(...t){let i=e._def.args.safeParse(t,n);if(!i.success)throw new yd([makeArgsIssue(t,i.error)]);let a=Reflect.apply(r,this,i.data),s=e._def.returns.safeParse(a,n);if(!s.success)throw new yd([makeReturnsIssue(a,s.error)]);return s.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:Kd.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ZodFunction({args:e||Kd.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:$.ZodFunction,...processCreateParams(n)})}},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:$.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:X.invalid_literal,expected:this._def.value}),Z}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:$.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new Xd({values:e,typeName:$.ZodEnum,...processCreateParams(t)})}var Xd=class ZodEnum extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{expected:J.joinValues(n),received:t.parsedType,code:X.invalid_type}),Z}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:X.invalid_enum_value,options:n}),Z}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(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}};Xd.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Y.string&&n.parsedType!==Y.number){let e=J.objectValues(t);return addIssueToContext(n,{expected:J.joinValues(e),received:n.parsedType,code:X.invalid_type}),Z}if(this._cache||=new Set(J.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=J.objectValues(t);return addIssueToContext(n,{received:n.data,code:X.invalid_enum_value,options:e}),Z}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:$.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Y.promise&&t.common.async===!1)return addIssueToContext(t,{code:X.invalid_type,expected:Y.promise,received:t.parsedType}),Z;let n=t.parsedType===Y.promise?t.data:Promise.resolve(t.data);return OK(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:$.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{addIssueToContext(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return Z;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?Z:r.status===`dirty`||t.value===`dirty`?DIRTY(r.value):r});{if(t.value===`aborted`)return Z;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?Z:r.status===`dirty`||t.value===`dirty`?DIRTY(r.value):r}}if(r.type===`refinement`){let executeRefinement=e=>{let t=r.refinement(e,i);if(n.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(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?Z:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value),{status:t.value,value:e.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>e.status===`aborted`?Z:(e.status===`dirty`&&t.dirty(),executeRefinement(e.value).then(()=>({status:t.value,value:e.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(e))return Z;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>isValid(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):Z)}J.assertNever(r)}};ZodEffects.create=(e,t,n)=>new ZodEffects({schema:e,typeName:$.ZodEffects,effect:t,...processCreateParams(n)}),ZodEffects.createWithPreprocess=(e,t,n)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:$.ZodEffects,...processCreateParams(n)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===Y.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:$.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===Y.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:$.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===Y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:$.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),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new yd(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new yd(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==Y.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:X.invalid_type,expected:Y.nan,received:t.parsedType}),Z}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:$.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Zd=class ZodPipeline extends ZodType{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){let handleAsync=async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?Z:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})};return handleAsync()}{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?Z:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:$.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),freeze=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>freeze(e)):freeze(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:$.ZodReadonly,...processCreateParams(t)}),Wd.lazycreate;var $;(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`})($||={});const Qd=zd.create;Bd.create,ZodNaN.create,Vd.create,ZodBoolean.create,Hd.create,ZodSymbol.create,ZodUndefined.create,ZodNull.create,ZodAny.create,ZodUnknown.create,ZodNever.create,ZodVoid.create,Ud.create;const $d=Wd.create;Wd.strictCreate,ZodUnion.create,Gd.create,ZodIntersection.create,Kd.create,qd.create,ZodMap.create,Jd.create,Yd.create,ZodLazy.create,ZodLiteral.create,Xd.create,ZodNativeEnum.create,ZodPromise.create,ZodEffects.create,ZodOptional.create,ZodNullable.create,ZodEffects.createWithPreprocess,Zd.create;const ef=je(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Oe.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Se(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Te(e,t,n),e.parseAsync=async(t,n)=>we(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ke(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>xe(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),tf=je(`ZodMiniObject`,(e,t)=>{De.init(e,t),ef.init(e,t),Me(e,`shape`,()=>t.shape)});function object(e,t){let n={type:`object`,shape:e??{},...Ce(t)};return new tf(n)}function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let n=t.every(isZ4Schema),r=t.every(e=>!isZ4Schema(e));if(n)return object(e);if(r)return $d(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?Te(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await ke(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,n=e;if(!t._def&&!n._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 n=e.value;if(n!==void 0)return n}function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const nf=Symbol(`Let zodToJsonSchema decide on which parser to use`),rf={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`?{...rf,name:e}:{...rf,...e},getRefs=e=>{let t=getDefaultOptions(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function setResponseValueAndErrors(e,t,n,r,i){e[t]=n,addErrorMessage(e,t,r,i)}const getRelativePath=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].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 n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==$.ZodAny&&(n.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(n,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function parseBigintDef(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`minimum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`maximum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:setResponseValueAndErrors(n,`multipleOf`,r.value,r.message,t)}return n}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,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>parseDateDef(e,t,n))};switch(r){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 n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:setResponseValueAndErrors(n,`minimum`,r.value,r.message,t);break;case`max`:setResponseValueAndErrors(n,`maximum`,r.value,r.message,t)}return n};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 n=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(isJsonSchema7AllOfType(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function parseLiteralDef(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let af;const of={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:()=>(af===void 0&&(af=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),af),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 n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:setResponseValueAndErrors(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:setResponseValueAndErrors(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(n,`email`,r.message,t);break;case`format:idn-email`:addFormat(n,`idn-email`,r.message,t);break;case`pattern:zod`:addPattern(n,of.email,r.message,t)}break;case`url`:addFormat(n,`uri`,r.message,t);break;case`uuid`:addFormat(n,`uuid`,r.message,t);break;case`regex`:addPattern(n,r.regex,r.message,t);break;case`cuid`:addPattern(n,of.cuid,r.message,t);break;case`cuid2`:addPattern(n,of.cuid2,r.message,t);break;case`startsWith`:addPattern(n,RegExp(`^${escapeLiteralCheckValue(r.value,t)}`),r.message,t);break;case`endsWith`:addPattern(n,RegExp(`${escapeLiteralCheckValue(r.value,t)}$`),r.message,t);break;case`datetime`:addFormat(n,`date-time`,r.message,t);break;case`date`:addFormat(n,`date`,r.message,t);break;case`time`:addFormat(n,`time`,r.message,t);break;case`duration`:addFormat(n,`duration`,r.message,t);break;case`length`:setResponseValueAndErrors(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),setResponseValueAndErrors(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:addPattern(n,RegExp(escapeLiteralCheckValue(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&addFormat(n,`ipv4`,r.message,t),r.version!==`v4`&&addFormat(n,`ipv6`,r.message,t);break;case`base64url`:addPattern(n,of.base64url,r.message,t);break;case`jwt`:addPattern(n,of.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&addPattern(n,of.ipv4Cidr,r.message,t),r.version!==`v4`&&addPattern(n,of.ipv6Cidr,r.message,t);break;case`emoji`:addPattern(n,of.emoji(),r.message,t);break;case`ulid`:addPattern(n,of.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(n,`binary`,r.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:addPattern(n,of.base64,r.message,t)}break;case`nanoid`:addPattern(n,of.nanoid,r.message,t)}return n}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const sf=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let n=0;n<e.length;n++)sf.has(e[n])||(t+=`\\`),t+=e[n];return t}function addFormat(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):setResponseValueAndErrors(e,`format`,t,n,r)}function addPattern(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.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,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,r),n,r)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,s=!1,c=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(s){if(r[e].match(/[a-z]/)){c?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),c=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],c=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
340
340
  ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
341
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=s?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:s&&r[e]===`]`?s=!1:!s&&r[e]===`[`&&(s=!0)}try{new RegExp(i)}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 i}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===Y.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Y.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=parseStringDef(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===Y.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=parseBrandedDef(e.keyType._def,t);return{...n,propertyNames:i}}return n}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,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}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 mf={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in mf&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=mf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}: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:mf[e.innerType._def.typeName],nullable:!0}:{type:[mf[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function parseNumberDef(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,addErrorMessage(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`minimum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`maximum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:setResponseValueAndErrors(n,`multipleOf`,r.value,r.message,t)}return n}function parseObjectDef(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let s=a[e];if(s===void 0||s._def===void 0)continue;let c=safeIsOptional(s);c&&n&&(s._def.typeName===`ZodOptional`&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),c=!1);let l=parseDef(s._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});l!==void 0&&(r.properties[e]=l,c||i.push(e))}i.length&&(r.required=i);let s=decideAdditionalProperties(e,t);return s!==void 0&&(r.additionalProperties=s),r}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 n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:parseAnyDef(t)},n]}: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 n=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let n={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).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,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).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,n)=>{switch(t){case Y.ZodString:return parseStringDef(e,n);case Y.ZodNumber:return parseNumberDef(e,n);case Y.ZodObject:return parseObjectDef(e,n);case Y.ZodBigInt:return parseBigintDef(e,n);case Y.ZodBoolean:return parseBooleanDef();case Y.ZodDate:return parseDateDef(e,n);case Y.ZodUndefined:return parseUndefinedDef(n);case Y.ZodNull:return parseNullDef(n);case Y.ZodArray:return parseArrayDef(e,n);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return parseUnionDef(e,n);case Y.ZodIntersection:return parseIntersectionDef(e,n);case Y.ZodTuple:return parseTupleDef(e,n);case Y.ZodRecord:return parseRecordDef(e,n);case Y.ZodLiteral:return parseLiteralDef(e,n);case Y.ZodEnum:return parseEnumDef(e);case Y.ZodNativeEnum:return parseNativeEnumDef(e);case Y.ZodNullable:return parseNullableDef(e,n);case Y.ZodOptional:return parseOptionalDef(e,n);case Y.ZodMap:return parseMapDef(e,n);case Y.ZodSet:return parseSetDef(e,n);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return parsePromiseDef(e,n);case Y.ZodNaN:case Y.ZodNever:return parseNeverDef(n);case Y.ZodEffects:return parseEffectsDef(e,n);case Y.ZodAny:return parseAnyDef(n);case Y.ZodUnknown:return parseUnknownDef(n);case Y.ZodDefault:return parseDefaultDef(e,n);case Y.ZodBranded:return parseBrandedDef(e,n);case Y.ZodReadonly:return parseReadonlyDef(e,n);case Y.ZodCatch:return parseCatchDef(e,n);case Y.ZodPipeline:return parsePipelineDef(e,n);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==lf)return i}if(r&&!n){let e=get$ref(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=selectParser(e,e.typeName,t),s=typeof a==`function`?parseDef(a(),t):a;if(s&&addMeta(e,t,s),t.postProcess){let n=t.postProcess(s,e,t);return i.jsonSchema=s,n}return i.jsonSchema=s,s}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,n)=>t.currentPath[n]===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,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),zodToJsonSchema=(e,t)=>{let n=getRefs(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:parseDef(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??parseAnyDef(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=parseDef(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??parseAnyDef(n),s=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;s!==void 0&&(a.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let c=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?c.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(c.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in c||`oneOf`in c||`allOf`in c||`type`in c&&Array.isArray(c.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),c};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)?Ee(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 n=getLiteralValue(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function parseWithCompat(e,t){let n=safeParse(e,t);if(!n.success)throw n.error;return n.data}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(tl,e=>{this._oncancel(e)}),this.setNotificationHandler(yl,e=>{this._onprogress(e)}),this.setRequestHandler(gl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ol,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new H(V.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Al,async(e,t)=>{let handleTaskResult=async()=>{let n=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new H(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 ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let r=await this._taskStore.getTask(n,t.sessionId);if(!r)throw new H(V.InvalidParams,`Task not found: ${n}`);if(!isTerminal(r.status))return await this._waitForTaskUpdate(n,t.signal),await handleTaskResult();if(isTerminal(r.status)){let e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n),{...e,_meta:{...e._meta,[Pc]:{taskId:n}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(jl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new H(V.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Nl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new H(V.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(n.status))throw new H(V.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new H(V.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof H?e:new H(V.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,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(V.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});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 n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(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=H.fromError(V.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(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 n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Pc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:V.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,l={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new H(V.ConnectionClosed,`Request was cancelled`);let s={...r,relatedRequestId:e.id};i&&!s.relatedTask&&(s.relatedTask={taskId:i});let l=s.relatedTask?.taskId??i;return l&&c&&await c.updateTaskStatus(l,`input_required`),await this.request(t,n,s)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:V.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?n(e):n(new H(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===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 i=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?r(e):r(H.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,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof H?e:new H(V.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Tl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new H(V.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new H(V.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new H(V.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof H?e:new H(V.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let earlyReject=e=>{u(e)};if(!this._transport){earlyReject(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(e){earlyReject(e);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:`2.0`,id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Pc]:c}});let cancel=e=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:f,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),u(e instanceof H?e:new H(V.RequestTimeout,String(e)))};this._responseHandlers.set(f,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return u(e);try{let n=safeParse(t,e.result);n.success?l(n.data):u(n.error)}catch(e){u(e)}}}),n?.signal?.addEventListener(`abort`,()=>{cancel(n?.signal?.reason)});let m=n?.timeout??6e4,timeoutHandler=()=>cancel(H.fromError(V.RequestTimeout,`Request timed out`,{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,timeoutHandler,n?.resetTimeoutOnProgress??!1);let h=c?.taskId;if(h){let responseResolver=e=>{let t=this._responseHandlers.get(f);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,responseResolver),this._enqueueTaskMessage(h,{type:`request`,message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(f),u(e)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(f),u(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},kl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Ml,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Pl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Pc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,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 n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Pc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Pc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=getMethodLiteral(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=parseWithCompat(e,n);return Promise.resolve(t(i,r))})}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 n=getMethodLiteral(e);this._notificationHandlers.set(n,n=>{let r=parseWithCompat(e,n);return Promise.resolve(t(r))})}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,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&isJSONRPCRequest(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new H(V.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new H(V.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new H(V.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new H(V.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Dl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),isTerminal(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new H(V.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(a.status))throw new H(V.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let s=await n.getTask(e,t);if(s){let t=Dl.parse({method:`notifications/tasks/status`,params:s});await this.notification(t),isTerminal(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=isPlainObject(a)&&isPlainObject(i)?{...a,...i}:i}return n}var hf=e(ms(),1);function createDefaultAjvInstance(){let e=new hf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,vs.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,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],s=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!s)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(s){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.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},Uu,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},ld,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}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,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function assertClientRequestTaskCapability(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ku.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(fl,e=>this._oninitialize(e)),this.setNotificationHandler(hl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ju,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ku.safeParse(r);return i.success&&this._loggingLevels.set(n,i.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 n=getObjectShape(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(isZ4Schema(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);if(r===`tools/call`){let wrappedHandler=async(e,n)=>{let r=safeParse(Du,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=safeParse(Tl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new H(V.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=safeParse(Tu,a);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,wrappedHandler)}return 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})`)}}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})`)}}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})`)}}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:Nc.includes(t)?t:Mc,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`},$c)}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],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],s=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!s)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(s){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.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},Wu,t):this.request({method:`sampling/createMessage`,params:e},Uu,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 n=e;return this.request({method:`elicitation/create`,params:n},ld,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},ld,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new H(V.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof H?e:new H(V.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}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},_d,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 gf=Symbol.for(`mcp.completable`);function completable(e,t){return Object.defineProperty(e,gf,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function isCompletable(e){return!!e&&typeof e==`object`&&gf in e}function getCompleter(e){return e[gf]?.complete}var _f;(function(e){e.Completable=`McpCompletable`})(_f||={});const vf=1e6,yf=1e6,bf=1e4;var xf=class UriTemplate{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(e){UriTemplate.validateLength(e,vf,`Template`),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let t=[],n=``,r=0,i=0;for(;r<e.length;)if(e[r]===`{`){n&&=(t.push(n),``);let a=e.indexOf(`}`,r);if(a===-1)throw Error(`Unclosed template expression`);if(i++,i>bf)throw Error(`Template contains too many expressions (max ${bf})`);let s=e.slice(r+1,a),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),f=u[0];for(let e of u)UriTemplate.validateLength(e,yf,`Variable name`);t.push({name:f,operator:c,names:u,exploded:l}),r=a+1}else n+=e[r],r++;return n&&t.push(n),t}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(e,t){return UriTemplate.validateLength(e,yf,`Variable value`),t===`+`||t===`#`?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&((r.operator===`?`||r.operator===`&`)&&n?t+=i.replace(`?`,`&`):t+=i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}partToRegExp(e){let t=[];for(let t of e.names)UriTemplate.validateLength(t,yf,`Variable name`);if(e.operator===`?`||e.operator===`&`){for(let n=0;n<e.names.length;n++){let r=e.names[n],i=n===0?`\\`+e.operator:`&`;t.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return t}let n,r=e.name;switch(e.operator){case``:n=e.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:n=`(.+)`;break;case`.`:n=`\\.([^/,]+)`;break;case`/`:n=`/`+(e.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:n=`([^/]+)`}return t.push({pattern:n,name:r}),t}match(e){UriTemplate.validateLength(e,vf,`URI`);let t=`^`,n=[];for(let e of this.parts)if(typeof e==`string`)t+=this.escapeRegExp(e);else{let r=this.partToRegExp(e);for(let{pattern:i,name:a}of r)t+=i,n.push({name:a,exploded:e.exploded})}t+=`$`,UriTemplate.validateLength(t,1e6,`Generated regex pattern`);let r=new RegExp(t),i=e.match(r);if(!i)return null;let a={};for(let e=0;e<n.length;e++){let{name:t,exploded:r}=n[e],s=i[e+1],c=t.replace(`*`,``);a[c]=r&&s.includes(`,`)?s.split(`,`):s}return a}};const Sf=/^[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`),!Sf.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.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,n){let r={taskSupport:`required`,...t.execution};if(r.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,r,t._meta,n)}},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(Cu)),this.server.assertCanSetRequestHandler(getMethodValue(Du)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Cu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):Cf})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(n.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Du,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new H(V.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new H(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,t);return r||await this.validateToolOutput(n,c,e.params.name),c}catch(e){if(e instanceof H&&e.code===V.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,n){if(!e.inputSchema)return;let r=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new H(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!r.success){let e=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},s=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),c=s.task.taskId,l=s.task,u=l.pollInterval??5e3;for(;l.status!==`completed`&&l.status!==`failed`&&l.status!==`cancelled`;){await new Promise(e=>setTimeout(e,u));let e=await n.taskStore.getTask(c);if(!e)throw new H(V.InternalError,`Task ${c} not found during polling`);l=e}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(pd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pd,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 H(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new H(V.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return wf;let r=getObjectShape(n.argsSchema)?.[e.params.argument.name];if(!isCompletable(r))return wf;let i=getCompleter(r);return i?createCompletionResult(await i(e.params.argument.value,e.params.context)):wf}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return wf;throw new H(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?createCompletionResult(await r(e.params.argument.value,e.params.context)):wf}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(Ul)),this.server.assertCanSetRequestHandler(getMethodValue(Gl)),this.server.assertCanSetRequestHandler(getMethodValue(Yl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ul,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Gl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Yl,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new H(V.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new H(V.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ou)),this.server.assertCanSetRequestHandler(getMethodValue(lu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ou,()=>({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(lu,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await safeParseAsync(normalizeObjectSchema(n.argsSchema),e.params.arguments);if(!r.success){let t=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new H(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:objectFromShape(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>isCompletable(e instanceof Be?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,s,c,l){validateAndWarnToolName(e);let u={title:t,description:n,inputSchema:getZodSchemaObject(r),outputSchema:getZodSchemaObject(i),annotations:a,execution:s,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.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]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description),t.paramsSchema!==void 0&&(u.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(u.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(u.handler=t.callback),t.annotations!==void 0&&(u.annotations=t.annotations),t._meta!==void 0&&(u._meta=t._meta),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(isZodRawShapeCompat(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,s)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,a,s,c,{taskSupport:`forbidden`},l,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,s=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}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()}},ResourceTemplate=class{constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new xf(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};const Cf={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||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 n=getLiteralValue(t);if(typeof n==`string`)return n;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 wf={completion:{values:[],hasMore:!1}};var Tf=`1.59.3`;function applySemanticLayoutPrompt(e){let t=useLanguageServices();return e.registerPrompt(`apply_semantic_layout`,{title:`Prepare prompt for applying semantic layout to a likec4 view`,argsSchema:{projectId:completable(X().describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(pt(`id`))),viewId:completable(X().describe(`View ID`),async(n=``,r)=>{let i=r?.arguments?.projectId??t.projectsManager.default.id,a=await t.computedModel(i);return a?Array.from(a.views()).filter(e=>e.id.startsWith(n)).map(pt(`id`)):(await e.sendLoggingMessage({level:`warning`,data:`Completing viewId for project ${i} with input value "${n}", model not found`}),[])})}},async({viewId:e,projectId:t},n)=>({messages:[{role:`user`,content:{type:`text`,text:["Call `apply-semantic-layout` tool from `likec4` MCP with these arguments:","projectId: `"+t+"`","viewId: `"+e+"`"].join(`
342
- `)}}]})),e}function projectResource(e){let t=useLanguageServices();return e.registerResource(`likec4-project`,new ResourceTemplate(`likec4://project/{projectId}`,{list:async()=>({resources:t.projects().map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,name:e.title}))}),complete:{projectId:e=>{if(!e)return t.projects().map(pt(`id`));let n=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(n)).map(pt(`id`))}}}),{description:`LikeC4 project resource`,mimeType:`application/json`},async(e,{projectId:n})=>{if(!n)return{contents:[]};let r=typeof n==`string`?[n]:n;return{contents:t.projects().filter(e=>r.includes(e.id)).map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,text:JSON.stringify({id:e.id,title:e.title,folder:e.folder.fsPath})}))}}),e}(e=>typeof n<`u`?n:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof n<`u`?n:e)[t]}):e)(function(e){if(typeof n<`u`)return n.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)});var Ef=w([D(`light`),D(`dark`)]).describe(`Color theme preference for the host environment.`),Df=w([D(`inline`),D(`fullscreen`),D(`pip`)]).describe(`Display mode for UI presentation.`),Of=w([D(`--color-background-primary`),D(`--color-background-secondary`),D(`--color-background-tertiary`),D(`--color-background-inverse`),D(`--color-background-ghost`),D(`--color-background-info`),D(`--color-background-danger`),D(`--color-background-success`),D(`--color-background-warning`),D(`--color-background-disabled`),D(`--color-text-primary`),D(`--color-text-secondary`),D(`--color-text-tertiary`),D(`--color-text-inverse`),D(`--color-text-ghost`),D(`--color-text-info`),D(`--color-text-danger`),D(`--color-text-success`),D(`--color-text-warning`),D(`--color-text-disabled`),D(`--color-border-primary`),D(`--color-border-secondary`),D(`--color-border-tertiary`),D(`--color-border-inverse`),D(`--color-border-ghost`),D(`--color-border-info`),D(`--color-border-danger`),D(`--color-border-success`),D(`--color-border-warning`),D(`--color-border-disabled`),D(`--color-ring-primary`),D(`--color-ring-secondary`),D(`--color-ring-inverse`),D(`--color-ring-info`),D(`--color-ring-danger`),D(`--color-ring-success`),D(`--color-ring-warning`),D(`--font-sans`),D(`--font-mono`),D(`--font-weight-normal`),D(`--font-weight-medium`),D(`--font-weight-semibold`),D(`--font-weight-bold`),D(`--font-text-xs-size`),D(`--font-text-sm-size`),D(`--font-text-md-size`),D(`--font-text-lg-size`),D(`--font-heading-xs-size`),D(`--font-heading-sm-size`),D(`--font-heading-md-size`),D(`--font-heading-lg-size`),D(`--font-heading-xl-size`),D(`--font-heading-2xl-size`),D(`--font-heading-3xl-size`),D(`--font-text-xs-line-height`),D(`--font-text-sm-line-height`),D(`--font-text-md-line-height`),D(`--font-text-lg-line-height`),D(`--font-heading-xs-line-height`),D(`--font-heading-sm-line-height`),D(`--font-heading-md-line-height`),D(`--font-heading-lg-line-height`),D(`--font-heading-xl-line-height`),D(`--font-heading-2xl-line-height`),D(`--font-heading-3xl-line-height`),D(`--border-radius-xs`),D(`--border-radius-sm`),D(`--border-radius-md`),D(`--border-radius-lg`),D(`--border-radius-xl`),D(`--border-radius-full`),D(`--border-width-regular`),D(`--shadow-hairline`),D(`--shadow-sm`),D(`--shadow-md`),D(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),kf=C(Of.describe(`Style variables for theming MCP apps.
341
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=s?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:s&&r[e]===`]`?s=!1:!s&&r[e]===`[`&&(s=!0)}try{new RegExp(i)}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 i}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===$.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=parseStringDef(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=parseBrandedDef(e.keyType._def,t);return{...n,propertyNames:i}}return n}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,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}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 cf={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in cf&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=cf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}: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:cf[e.innerType._def.typeName],nullable:!0}:{type:[cf[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function parseNumberDef(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,addErrorMessage(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`minimum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?setResponseValueAndErrors(n,`maximum`,r.value,r.message,t):setResponseValueAndErrors(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:setResponseValueAndErrors(n,`multipleOf`,r.value,r.message,t)}return n}function parseObjectDef(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let s=a[e];if(s===void 0||s._def===void 0)continue;let c=safeIsOptional(s);c&&n&&(s._def.typeName===`ZodOptional`&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),c=!1);let l=parseDef(s._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});l!==void 0&&(r.properties[e]=l,c||i.push(e))}i.length&&(r.required=i);let s=decideAdditionalProperties(e,t);return s!==void 0&&(r.additionalProperties=s),r}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 n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:parseAnyDef(t)},n]}: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 n=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let n={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).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,n)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).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,n)=>{switch(t){case $.ZodString:return parseStringDef(e,n);case $.ZodNumber:return parseNumberDef(e,n);case $.ZodObject:return parseObjectDef(e,n);case $.ZodBigInt:return parseBigintDef(e,n);case $.ZodBoolean:return parseBooleanDef();case $.ZodDate:return parseDateDef(e,n);case $.ZodUndefined:return parseUndefinedDef(n);case $.ZodNull:return parseNullDef(n);case $.ZodArray:return parseArrayDef(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return parseUnionDef(e,n);case $.ZodIntersection:return parseIntersectionDef(e,n);case $.ZodTuple:return parseTupleDef(e,n);case $.ZodRecord:return parseRecordDef(e,n);case $.ZodLiteral:return parseLiteralDef(e,n);case $.ZodEnum:return parseEnumDef(e);case $.ZodNativeEnum:return parseNativeEnumDef(e);case $.ZodNullable:return parseNullableDef(e,n);case $.ZodOptional:return parseOptionalDef(e,n);case $.ZodMap:return parseMapDef(e,n);case $.ZodSet:return parseSetDef(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return parsePromiseDef(e,n);case $.ZodNaN:case $.ZodNever:return parseNeverDef(n);case $.ZodEffects:return parseEffectsDef(e,n);case $.ZodAny:return parseAnyDef(n);case $.ZodUnknown:return parseUnknownDef(n);case $.ZodDefault:return parseDefaultDef(e,n);case $.ZodBranded:return parseBrandedDef(e,n);case $.ZodReadonly:return parseReadonlyDef(e,n);case $.ZodCatch:return parseCatchDef(e,n);case $.ZodPipeline:return parsePipelineDef(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==nf)return i}if(r&&!n){let e=get$ref(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=selectParser(e,e.typeName,t),s=typeof a==`function`?parseDef(a(),t):a;if(s&&addMeta(e,t,s),t.postProcess){let n=t.postProcess(s,e,t);return i.jsonSchema=s,n}return i.jsonSchema=s,s}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,n)=>t.currentPath[n]===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,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),zodToJsonSchema=(e,t)=>{let n=getRefs(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:parseDef(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??parseAnyDef(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=parseDef(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??parseAnyDef(n),s=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;s!==void 0&&(a.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let c=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?c.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(c.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in c||`oneOf`in c||`allOf`in c||`type`in c&&Array.isArray(c.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),c};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)?Ee(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 n=getLiteralValue(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function parseWithCompat(e,t){let n=safeParse(e,t);if(!n.success)throw n.error;return n.data}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(el,e=>{this._oncancel(e)}),this.setNotificationHandler(vl,e=>{this._onprogress(e)}),this.setRequestHandler(hl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Dl,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(kl,async(e,t)=>{let handleTaskResult=async()=>{let n=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new K(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 ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let r=await this._taskStore.getTask(n,t.sessionId);if(!r)throw new K(G.InvalidParams,`Task not found: ${n}`);if(!isTerminal(r.status))return await this._waitForTaskUpdate(n,t.signal),await handleTaskResult();if(isTerminal(r.status)){let e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n),{...e,_meta:{...e._meta,[Nc]:{taskId:n}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(Al,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new K(G.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Ml,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(n.status))throw new K(G.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new K(G.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof K?e:new K(G.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,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),K.fromError(G.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});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 n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(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=K.fromError(G.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(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 n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Nc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:G.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,l={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new K(G.ConnectionClosed,`Request was cancelled`);let s={...r,relatedRequestId:e.id};i&&!s.relatedTask&&(s.relatedTask={taskId:i});let l=s.relatedTask?.taskId??i;return l&&c&&await c.updateTaskStatus(l,`input_required`),await this.request(t,n,s)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:G.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?n(e):n(new K(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===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 i=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?r(e):r(K.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,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}return}let i;try{let r=await this.request(e,wl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new K(G.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new K(G.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new K(G.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let earlyReject=e=>{u(e)};if(!this._transport){earlyReject(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(e){earlyReject(e);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:`2.0`,id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Nc]:c}});let cancel=e=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:f,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),u(e instanceof K?e:new K(G.RequestTimeout,String(e)))};this._responseHandlers.set(f,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return u(e);try{let n=safeParse(t,e.result);n.success?l(n.data):u(n.error)}catch(e){u(e)}}}),n?.signal?.addEventListener(`abort`,()=>{cancel(n?.signal?.reason)});let m=n?.timeout??6e4,timeoutHandler=()=>cancel(K.fromError(G.RequestTimeout,`Request timed out`,{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,timeoutHandler,n?.resetTimeoutOnProgress??!1);let h=c?.taskId;if(h){let responseResolver=e=>{let t=this._responseHandlers.get(f);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,responseResolver),this._enqueueTaskMessage(h,{type:`request`,message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(f),u(e)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(f),u(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Ol,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},jl,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Nl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Nc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,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 n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Nc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Nc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=getMethodLiteral(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=parseWithCompat(e,n);return Promise.resolve(t(i,r))})}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 n=getMethodLiteral(e);this._notificationHandlers.set(n,n=>{let r=parseWithCompat(e,n);return Promise.resolve(t(r))})}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,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&isJSONRPCRequest(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new K(G.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new K(G.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new K(G.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=El.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),isTerminal(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new K(G.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(a.status))throw new K(G.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let s=await n.getTask(e,t);if(s){let t=El.parse({method:`notifications/tasks/status`,params:s});await this.notification(t),isTerminal(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=isPlainObject(a)&&isPlainObject(i)?{...a,...i}:i}return n}var lf=e(ms(),1);function createDefaultAjvInstance(){let e=new lf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,vs.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,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],s=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!s)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(s){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.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},Hu,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},cd,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}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,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function assertClientRequestTaskCapability(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ou.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(dl,e=>this._oninitialize(e)),this.setNotificationHandler(ml,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Au,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Ou.safeParse(r);return i.success&&this._loggingLevels.set(n,i.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 n=getObjectShape(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(isZ4Schema(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);if(r===`tools/call`){let wrappedHandler=async(e,n)=>{let r=safeParse(Eu,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=safeParse(wl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=safeParse(wu,a);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new K(G.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,wrappedHandler)}return 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})`)}}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})`)}}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})`)}}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:Mc.includes(t)?t:jc,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`},Qc)}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],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],s=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!s)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(s){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.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},Uu,t):this.request({method:`sampling/createMessage`,params:e},Hu,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 n=e;return this.request({method:`elicitation/create`,params:n},cd,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},cd,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new K(G.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof K?e:new K(G.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}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},gd,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 uf=Symbol.for(`mcp.completable`);function completable(e,t){return Object.defineProperty(e,uf,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function isCompletable(e){return!!e&&typeof e==`object`&&uf in e}function getCompleter(e){return e[uf]?.complete}var df;(function(e){e.Completable=`McpCompletable`})(df||={});const ff=1e6,pf=1e6,mf=1e4;var hf=class UriTemplate{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(e){UriTemplate.validateLength(e,ff,`Template`),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let t=[],n=``,r=0,i=0;for(;r<e.length;)if(e[r]===`{`){n&&=(t.push(n),``);let a=e.indexOf(`}`,r);if(a===-1)throw Error(`Unclosed template expression`);if(i++,i>mf)throw Error(`Template contains too many expressions (max ${mf})`);let s=e.slice(r+1,a),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),f=u[0];for(let e of u)UriTemplate.validateLength(e,pf,`Variable name`);t.push({name:f,operator:c,names:u,exploded:l}),r=a+1}else n+=e[r],r++;return n&&t.push(n),t}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(e,t){return UriTemplate.validateLength(e,pf,`Variable value`),t===`+`||t===`#`?encodeURI(e):encodeURIComponent(e)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&((r.operator===`?`||r.operator===`&`)&&n?t+=i.replace(`?`,`&`):t+=i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}partToRegExp(e){let t=[];for(let t of e.names)UriTemplate.validateLength(t,pf,`Variable name`);if(e.operator===`?`||e.operator===`&`){for(let n=0;n<e.names.length;n++){let r=e.names[n],i=n===0?`\\`+e.operator:`&`;t.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return t}let n,r=e.name;switch(e.operator){case``:n=e.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:n=`(.+)`;break;case`.`:n=`\\.([^/,]+)`;break;case`/`:n=`/`+(e.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:n=`([^/]+)`}return t.push({pattern:n,name:r}),t}match(e){UriTemplate.validateLength(e,ff,`URI`);let t=`^`,n=[];for(let e of this.parts)if(typeof e==`string`)t+=this.escapeRegExp(e);else{let r=this.partToRegExp(e);for(let{pattern:i,name:a}of r)t+=i,n.push({name:a,exploded:e.exploded})}t+=`$`,UriTemplate.validateLength(t,1e6,`Generated regex pattern`);let r=new RegExp(t),i=e.match(r);if(!i)return null;let a={};for(let e=0;e<n.length;e++){let{name:t,exploded:r}=n[e],s=i[e+1],c=t.replace(`*`,``);a[c]=r&&s.includes(`,`)?s.split(`,`):s}return a}};const gf=/^[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`),!gf.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.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,n){let r={taskSupport:`required`,...t.execution};if(r.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,r,t._meta,n)}},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(Su)),this.server.assertCanSetRequestHandler(getMethodValue(Eu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Su,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):_f})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(n.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Eu,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new K(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new K(G.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new K(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new K(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,t);return r||await this.validateToolOutput(n,c,e.params.name),c}catch(e){if(e instanceof K&&e.code===G.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,n){if(!e.inputSchema)return;let r=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new K(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new K(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!r.success){let e=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new K(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},s=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),c=s.task.taskId,l=s.task,u=l.pollInterval??5e3;for(;l.status!==`completed`&&l.status!==`failed`&&l.status!==`cancelled`;){await new Promise(e=>setTimeout(e,u));let e=await n.taskStore.getTask(c);if(!e)throw new K(G.InternalError,`Task ${c} not found during polling`);l=e}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(fd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(fd,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 K(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new K(G.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new K(G.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return vf;let r=getObjectShape(n.argsSchema)?.[e.params.argument.name];if(!isCompletable(r))return vf;let i=getCompleter(r);return i?createCompletionResult(await i(e.params.argument.value,e.params.context)):vf}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return vf;throw new K(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?createCompletionResult(await r(e.params.argument.value,e.params.context)):vf}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(Hl)),this.server.assertCanSetRequestHandler(getMethodValue(Wl)),this.server.assertCanSetRequestHandler(getMethodValue(Jl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Hl,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Wl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Jl,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new K(G.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new K(G.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(au)),this.server.assertCanSetRequestHandler(getMethodValue(cu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(au,()=>({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(cu,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new K(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new K(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await safeParseAsync(normalizeObjectSchema(n.argsSchema),e.params.arguments);if(!r.success){let t=getParseErrorMessage(`error`in r?r.error:`Unknown error`);throw new K(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:objectFromShape(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>isCompletable(e instanceof Re?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,s,c,l){validateAndWarnToolName(e);let u={title:t,description:n,inputSchema:getZodSchemaObject(r),outputSchema:getZodSchemaObject(i),annotations:a,execution:s,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.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]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description),t.paramsSchema!==void 0&&(u.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(u.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(u.handler=t.callback),t.annotations!==void 0&&(u.annotations=t.annotations),t._meta!==void 0&&(u._meta=t._meta),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(isZodRawShapeCompat(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,s)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,a,s,c,{taskSupport:`forbidden`},l,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,s=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}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()}},ResourceTemplate=class{constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new hf(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};const _f={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||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 n=getLiteralValue(t);if(typeof n==`string`)return n;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 vf={completion:{values:[],hasMore:!1}};var yf=`1.59.4`;function applySemanticLayoutPrompt(e){let t=useLanguageServices();return e.registerPrompt(`apply_semantic_layout`,{title:`Prepare prompt for applying semantic layout to a likec4 view`,argsSchema:{projectId:completable(Qd().describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(dt(`id`))),viewId:completable(Qd().describe(`View ID`),async(n=``,r)=>{let i=r?.arguments?.projectId??t.projectsManager.default.id,a=await t.computedModel(i);return a?Array.from(a.views()).filter(e=>e.id.startsWith(n)).map(dt(`id`)):(await e.sendLoggingMessage({level:`warning`,data:`Completing viewId for project ${i} with input value "${n}", model not found`}),[])})}},async({viewId:e,projectId:t},n)=>({messages:[{role:`user`,content:{type:`text`,text:["Call `apply-semantic-layout` tool from `likec4` MCP with these arguments:","projectId: `"+t+"`","viewId: `"+e+"`"].join(`
342
+ `)}}]})),e}function projectResource(e){let t=useLanguageServices();return e.registerResource(`likec4-project`,new ResourceTemplate(`likec4://project/{projectId}`,{list:async()=>({resources:t.projects().map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,name:e.title}))}),complete:{projectId:e=>{if(!e)return t.projects().map(dt(`id`));let n=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(n)).map(dt(`id`))}}}),{description:`LikeC4 project resource`,mimeType:`application/json`},async(e,{projectId:n})=>{if(!n)return{contents:[]};let r=typeof n==`string`?[n]:n;return{contents:t.projects().filter(e=>r.includes(e.id)).map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,text:JSON.stringify({id:e.id,title:e.title,folder:e.folder.fsPath})}))}}),e}(e=>typeof n<`u`?n:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof n<`u`?n:e)[t]}):e)(function(e){if(typeof n<`u`)return n.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)});var bf=w([k(`light`),k(`dark`)]).describe(`Color theme preference for the host environment.`),xf=w([k(`inline`),k(`fullscreen`),k(`pip`)]).describe(`Display mode for UI presentation.`),Sf=w([k(`--color-background-primary`),k(`--color-background-secondary`),k(`--color-background-tertiary`),k(`--color-background-inverse`),k(`--color-background-ghost`),k(`--color-background-info`),k(`--color-background-danger`),k(`--color-background-success`),k(`--color-background-warning`),k(`--color-background-disabled`),k(`--color-text-primary`),k(`--color-text-secondary`),k(`--color-text-tertiary`),k(`--color-text-inverse`),k(`--color-text-ghost`),k(`--color-text-info`),k(`--color-text-danger`),k(`--color-text-success`),k(`--color-text-warning`),k(`--color-text-disabled`),k(`--color-border-primary`),k(`--color-border-secondary`),k(`--color-border-tertiary`),k(`--color-border-inverse`),k(`--color-border-ghost`),k(`--color-border-info`),k(`--color-border-danger`),k(`--color-border-success`),k(`--color-border-warning`),k(`--color-border-disabled`),k(`--color-ring-primary`),k(`--color-ring-secondary`),k(`--color-ring-inverse`),k(`--color-ring-info`),k(`--color-ring-danger`),k(`--color-ring-success`),k(`--color-ring-warning`),k(`--font-sans`),k(`--font-mono`),k(`--font-weight-normal`),k(`--font-weight-medium`),k(`--font-weight-semibold`),k(`--font-weight-bold`),k(`--font-text-xs-size`),k(`--font-text-sm-size`),k(`--font-text-md-size`),k(`--font-text-lg-size`),k(`--font-heading-xs-size`),k(`--font-heading-sm-size`),k(`--font-heading-md-size`),k(`--font-heading-lg-size`),k(`--font-heading-xl-size`),k(`--font-heading-2xl-size`),k(`--font-heading-3xl-size`),k(`--font-text-xs-line-height`),k(`--font-text-sm-line-height`),k(`--font-text-md-line-height`),k(`--font-text-lg-line-height`),k(`--font-heading-xs-line-height`),k(`--font-heading-sm-line-height`),k(`--font-heading-md-line-height`),k(`--font-heading-lg-line-height`),k(`--font-heading-xl-line-height`),k(`--font-heading-2xl-line-height`),k(`--font-heading-3xl-line-height`),k(`--border-radius-xs`),k(`--border-radius-sm`),k(`--border-radius-md`),k(`--border-radius-lg`),k(`--border-radius-xl`),k(`--border-radius-full`),k(`--border-width-regular`),k(`--shadow-hairline`),k(`--shadow-sm`),k(`--shadow-md`),k(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),Cf=C(Sf.describe(`Style variables for theming MCP apps.
343
343
 
344
344
  Individual style keys are optional - hosts may provide any subset of these values.
345
345
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
346
346
 
347
347
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
348
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),w([T(),qe()]).describe(`Style variables for theming MCP apps.
348
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),w([E(),Ge()]).describe(`Style variables for theming MCP apps.
349
349
 
350
350
  Individual style keys are optional - hosts may provide any subset of these values.
351
351
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -357,18 +357,18 @@ Individual style keys are optional - hosts may provide any subset of these value
357
357
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
358
358
 
359
359
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
360
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);E({method:D(`ui/open-link`),params:E({url:T().describe(`URL to open in the host's browser`)})}),E({isError:k().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),E({isError:k().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),E({isError:k().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),E({method:D(`ui/notifications/sandbox-proxy-ready`),params:E({})});var Af=E({connectDomains:O(T()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
360
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);O({method:k(`ui/open-link`),params:O({url:E().describe(`URL to open in the host's browser`)})}),O({isError:j().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),O({isError:j().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),O({isError:j().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),O({method:k(`ui/notifications/sandbox-proxy-ready`),params:O({})});var wf=O({connectDomains:A(E()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
361
361
 
362
362
  - Maps to CSP \`connect-src\` directive
363
- - Empty or omitted → no network connections (secure default)`),resourceDomains:O(T()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:O(T()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:O(T()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),jf=E({camera:E({}).optional().describe(`Request camera access.
363
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:A(E()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:A(E()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:A(E()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Tf=O({camera:O({}).optional().describe(`Request camera access.
364
364
 
365
- Maps to Permission Policy \`camera\` feature.`),microphone:E({}).optional().describe(`Request microphone access.
365
+ Maps to Permission Policy \`camera\` feature.`),microphone:O({}).optional().describe(`Request microphone access.
366
366
 
367
- Maps to Permission Policy \`microphone\` feature.`),geolocation:E({}).optional().describe(`Request geolocation access.
367
+ Maps to Permission Policy \`microphone\` feature.`),geolocation:O({}).optional().describe(`Request geolocation access.
368
368
 
369
- Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:E({}).optional().describe(`Request clipboard write access.
369
+ Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:O({}).optional().describe(`Request clipboard write access.
370
370
 
371
- Maps to Permission Policy \`clipboard-write\` feature.`)});E({method:D(`ui/notifications/size-changed`),params:E({width:A().optional().describe(`New width in pixels.`),height:A().optional().describe(`New height in pixels.`)})}),E({method:D(`ui/notifications/tool-input`),params:E({arguments:C(T(),Oe().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),E({method:D(`ui/notifications/tool-input-partial`),params:E({arguments:C(T(),Oe().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),E({method:D(`ui/notifications/tool-cancelled`),params:E({reason:T().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var Mf=E({fonts:T().optional()}),Nf=E({variables:kf.optional().describe(`CSS variables for theming the app.`),css:Mf.optional().describe(`CSS blocks that apps can inject.`)});E({method:D(`ui/resource-teardown`),params:E({})}),C(T(),Oe());var Pf=E({text:E({}).optional().describe(`Host supports text content blocks.`),image:E({}).optional().describe(`Host supports image content blocks.`),audio:E({}).optional().describe(`Host supports audio content blocks.`),resource:E({}).optional().describe(`Host supports resource content blocks.`),resourceLink:E({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:E({}).optional().describe(`Host supports structured content.`)});E({method:D(`ui/notifications/request-teardown`),params:E({}).optional()});var Ff=E({experimental:C(T(),C(T(),Le()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:E({}).optional().describe(`Host supports opening external URLs.`),downloadFile:E({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:E({listChanged:k().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:E({listChanged:k().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:E({}).optional().describe(`Host accepts log messages.`),sandbox:E({permissions:jf.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:Af.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Pf.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Pf.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:E({tools:E({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Lf=E({experimental:C(T(),C(T(),Le()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:E({listChanged:k().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:O(Df).optional().describe(`Display modes the app supports.`)});E({method:D(`ui/notifications/initialized`),params:E({}).optional()}),E({csp:Af.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:jf.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:T().optional().describe(`Dedicated origin for view sandbox.
371
+ Maps to Permission Policy \`clipboard-write\` feature.`)});O({method:k(`ui/notifications/size-changed`),params:O({width:M().optional().describe(`New width in pixels.`),height:M().optional().describe(`New height in pixels.`)})}),O({method:k(`ui/notifications/tool-input`),params:O({arguments:C(E(),T().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),O({method:k(`ui/notifications/tool-input-partial`),params:O({arguments:C(E(),T().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),O({method:k(`ui/notifications/tool-cancelled`),params:O({reason:E().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var Ef=O({fonts:E().optional()}),Df=O({variables:Cf.optional().describe(`CSS variables for theming the app.`),css:Ef.optional().describe(`CSS blocks that apps can inject.`)});O({method:k(`ui/resource-teardown`),params:O({})}),C(E(),T());var Of=O({text:O({}).optional().describe(`Host supports text content blocks.`),image:O({}).optional().describe(`Host supports image content blocks.`),audio:O({}).optional().describe(`Host supports audio content blocks.`),resource:O({}).optional().describe(`Host supports resource content blocks.`),resourceLink:O({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:O({}).optional().describe(`Host supports structured content.`)});O({method:k(`ui/notifications/request-teardown`),params:O({}).optional()});var kf=O({experimental:C(E(),C(E(),Fe()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:O({}).optional().describe(`Host supports opening external URLs.`),downloadFile:O({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:O({listChanged:j().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:O({listChanged:j().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:O({}).optional().describe(`Host accepts log messages.`),sandbox:O({permissions:Tf.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:wf.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Of.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Of.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:O({tools:O({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Af=O({experimental:C(E(),C(E(),Fe()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:O({listChanged:j().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:A(xf).optional().describe(`Display modes the app supports.`)});O({method:k(`ui/notifications/initialized`),params:O({}).optional()}),O({csp:wf.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:Tf.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:E().optional().describe(`Dedicated origin for view sandbox.
372
372
 
373
373
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
374
374
 
@@ -376,22 +376,26 @@ Useful when views need stable, dedicated origins for OAuth callbacks, CORS polic
376
376
  - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
377
377
  - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
378
378
 
379
- If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:k().optional().describe(`Visual boundary preference - true if view prefers a visible border.
379
+ If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:j().optional().describe(`Visual boundary preference - true if view prefers a visible border.
380
380
 
381
381
  Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
382
382
 
383
383
  - \`true\`: request visible border + background
384
384
  - \`false\`: request no visible border + background
385
- - omitted: host decides border`)}),E({method:D(`ui/request-display-mode`),params:E({mode:Df.describe(`The display mode being requested.`)})}),E({mode:Df.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough();var Rf=w([D(`model`),D(`app`)]).describe(`Tool visibility scope - who can access the tool.`);E({resourceUri:T().optional(),visibility:O(Rf).optional().describe(`Who can access this tool. Default: ["model", "app"]
385
+ - omitted: host decides border`)}),O({method:k(`ui/request-display-mode`),params:O({mode:xf.describe(`The display mode being requested.`)})}),O({mode:xf.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough();var jf=w([k(`model`),k(`app`)]).describe(`Tool visibility scope - who can access the tool.`);O({resourceUri:E().optional(),visibility:A(jf).optional().describe(`Who can access this tool. Default: ["model", "app"]
386
386
  - "model": Tool visible to and callable by the agent
387
- - "app": Tool callable by the app from this server only`),csp:Je().optional(),permissions:Je().optional()}),E({mimeTypes:O(T()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),E({method:D(`ui/download-file`),params:E({contents:O(w([mu,hu])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),E({method:D(`ui/message`),params:E({role:D(`user`).describe(`Message role, currently only "user" is supported.`),content:O(gu).describe(`Message content blocks (text, image, etc.).`)})}),E({method:D(`ui/notifications/sandbox-resource-ready`),params:E({html:T().describe(`HTML content to load into the inner iframe.`),sandbox:T().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Af.optional().describe(`CSP configuration from resource metadata.`),permissions:jf.optional().describe(`Sandbox permissions from resource metadata.`)})}),E({method:D(`ui/notifications/tool-result`),params:Tu.describe(`Standard MCP tool execution result.`)});var zf=E({toolInfo:E({id:qc.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Su.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Ef.optional().describe(`Current color theme preference.`),styles:Nf.optional().describe(`Style configuration for theming the app.`),displayMode:Df.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:O(Df).optional().describe(`Display modes the host supports.`),containerDimensions:w([E({height:A().describe(`Fixed container height in pixels.`)}),E({maxHeight:w([A(),qe()]).optional().describe(`Maximum container height in pixels.`)})]).and(w([E({width:A().describe(`Fixed container width in pixels.`)}),E({maxWidth:w([A(),qe()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
388
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:T().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:T().optional().describe(`User's timezone in IANA format.`),userAgent:T().optional().describe(`Host application identifier.`),platform:w([D(`web`),D(`desktop`),D(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:E({touch:k().optional().describe(`Whether the device supports touch input.`),hover:k().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:E({top:A().describe(`Top safe area inset in pixels.`),right:A().describe(`Right safe area inset in pixels.`),bottom:A().describe(`Bottom safe area inset in pixels.`),left:A().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();E({method:D(`ui/notifications/host-context-changed`),params:zf.describe(`Partial context update containing only changed fields.`)}),E({method:D(`ui/update-model-context`),params:E({content:O(gu).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:C(T(),Oe().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),E({method:D(`ui/initialize`),params:E({appInfo:al.describe(`App identification (name and version).`),appCapabilities:Lf.describe(`Features and capabilities this app provides.`),protocolVersion:T().describe(`Protocol version this app supports.`)})}),E({protocolVersion:T().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:al.describe(`Host application identification and version.`),hostCapabilities:Ff.describe(`Features and capabilities provided by the host.`),hostContext:zf.describe(`Rich context about the host environment.`)}).passthrough();var Bf=`ui/resourceUri`,Vf=`text/html;profile=mcp-app`;function K3(e,t,n,r){let i=n._meta,a=i.ui,s=i[Bf],c=i;return a?.resourceUri&&!s?c={...i,[Bf]:a.resourceUri}:s&&!a?.resourceUri&&(c={...i,ui:{...a,resourceUri:s}}),e.registerTool(t,{...n,_meta:c},r)}function N3(e,t,n,r,i){return e.registerResource(t,n,{mimeType:Vf,...r},i)}function readDistAsset(e){let t=[new URL(`../dist/${e}`,import.meta.url),new URL(`../../dist/${e}`,import.meta.url)];for(let e of t){let t=On(e);if(_n(t))return vn(t,`utf-8`)}throw Error(`Could not locate dist asset '${e}'; tried: ${t.map(String).join(`, `)}`)}function readRenderViewClientBundle(){return readDistAsset(`app/render-view-client.js`)}function readRenderViewClientStyles(){return readDistAsset(`app/render-view-client.css`)}const Hf=$({name:X().describe(`Project identifier`),title:X().optional().describe(`Human-readable project title`),contactPerson:X().optional().describe(`Maintainer contact information`),metadata:rf(X(),ef()).optional().describe(`Custom project metadata as key-value pairs`),extends:tf([X(),Q(X())]).optional().describe(`Style inheritance paths`),exclude:Q(X()).optional().describe(`File exclusion patterns`),include:$({paths:Q(X()).describe(`Include paths`),maxDepth:Z().describe(`Maximum directory depth`),fileThreshold:Z().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:$({outDir:X().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:$({hasTheme:$d().describe(`Whether theme customization is defined`),hasDefaults:$d().describe(`Whether default style values are defined`),hasCustomCss:$d().describe(`Whether custom CSS is defined`)}).optional().describe(`Simplified styles configuration (boolean flags)`)});function serializeConfig(e){let t={name:e.name};return e.title!=null&&(t.title=e.title),e.contactPerson!=null&&(t.contactPerson=e.contactPerson),e.metadata&&(t.metadata=e.metadata),e.extends&&(t.extends=e.extends),e.exclude&&(t.exclude=e.exclude),e.include&&(t.include={paths:e.include.paths||[],maxDepth:e.include.maxDepth??3,fileThreshold:e.include.fileThreshold??30}),e.manualLayouts&&(t.manualLayouts={outDir:e.manualLayouts.outDir??`.likec4`}),e.styles&&(t.styles={hasTheme:!!e.styles.theme,hasDefaults:!!e.styles.defaults,hasCustomCss:!!e.styles.customCss}),t}const Uf=$({id:X().describe(`Element id (FQN)`),name:X().describe(`Element name`),kind:X().describe(`Element kind`),title:X(),tags:Q(X()),metadata:rf(tf([X(),Q(X())])),includedInViews:Q($({id:X().describe(`View id`),title:X().describe(`View title`),type:of([`element`,`deployment`,`dynamic`]).describe(`View type`)})).describe(`Views that include this element`)});function serializeElement(e){return{id:e.id,name:e.name,kind:e.kind,title:e.title,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())}}function traverseGraph(e,t,n,r,i,a){let s=e.findElement(t);Qt(s,`Element "${t}" not found`);let c=new Set,l={},u=0,f=!1,p=[{elementId:t,depth:0}];for(;p.length>0;){let{elementId:t,depth:s}=p.shift();if(s>i||c.has(t))continue;if(c.size>=a){f=!0;break}let m=e.findElement(t);if(!m)continue;c.add(t),u=Math.max(u,s);let h=(n===`incoming`?[...m.incoming(r)]:[...m.outgoing(r)]).map(e=>{let t={elementId:n===`incoming`?e.source.id:e.target.id};return e.title&&(t.relationshipLabel=e.title),e.technology&&(t.technology=e.technology),t});l[t]={...serializeElement(m),neighbors:h,depth:s};for(let e of h)c.has(e.elementId)||p.push({elementId:e.elementId,depth:s+1})}for(let e of Object.values(l))e.neighbors=e.neighbors.filter(e=>e.elementId in l);return{target:t,totalNodes:c.size,maxDepth:u,truncated:f,nodes:l}}const Wf=$({path:X().describe(`Path to the file`),range:$({start:$({line:Z(),character:Z()}),end:$({line:Z(),character:Z()})}).describe(`Range in the file`)}).nullable(),Gf=X().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),Kf=Q($({id:X().describe(`View id`),title:X().describe(`View title`),type:of([`element`,`deployment`,`dynamic`]).describe(`View type`)})),includedInViews=e=>[...e].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type})),mkLocate=(e,t)=>n=>{try{let r=e.locate({projectId:t,...n});return r?{path:ce.parse(r.uri).fsPath,range:r.range}:null}catch(e){return U.debug(`Failed to locate {params}`,{error:e,params:n}),null}};function toolError(e){return{isError:!0,content:[{type:`text`,text:e}]}}function buildRenderPayload(e){return{id:e.viewId,title:e.title,project:e.projectId,view:e.layoutedView,model:{...e.modelData,views:{[e.viewId]:e.layoutedView}}}}const qf=`ui://likec4/render-view.html`;function renderViewTool(e){return K3(e,`render-view`,{title:`Render View`,description:`Renders a LikeC4 view as an interactive diagram (pan/zoom/fit) inline in the chat.
387
+ - "app": Tool callable by the app from this server only`),csp:Ke().optional(),permissions:Ke().optional()}),O({mimeTypes:A(E()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),O({method:k(`ui/download-file`),params:O({contents:A(w([pu,mu])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),O({method:k(`ui/message`),params:O({role:k(`user`).describe(`Message role, currently only "user" is supported.`),content:A(hu).describe(`Message content blocks (text, image, etc.).`)})}),O({method:k(`ui/notifications/sandbox-resource-ready`),params:O({html:E().describe(`HTML content to load into the inner iframe.`),sandbox:E().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:wf.optional().describe(`CSP configuration from resource metadata.`),permissions:Tf.optional().describe(`Sandbox permissions from resource metadata.`)})}),O({method:k(`ui/notifications/tool-result`),params:wu.describe(`Standard MCP tool execution result.`)});var Mf=O({toolInfo:O({id:Kc.optional().describe(`JSON-RPC id of the tools/call request.`),tool:xu.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:bf.optional().describe(`Current color theme preference.`),styles:Df.optional().describe(`Style configuration for theming the app.`),displayMode:xf.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:A(xf).optional().describe(`Display modes the host supports.`),containerDimensions:w([O({height:M().describe(`Fixed container height in pixels.`)}),O({maxHeight:w([M(),Ge()]).optional().describe(`Maximum container height in pixels.`)})]).and(w([O({width:M().describe(`Fixed container width in pixels.`)}),O({maxWidth:w([M(),Ge()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
388
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:E().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:E().optional().describe(`User's timezone in IANA format.`),userAgent:E().optional().describe(`Host application identifier.`),platform:w([k(`web`),k(`desktop`),k(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:O({touch:j().optional().describe(`Whether the device supports touch input.`),hover:j().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:O({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();O({method:k(`ui/notifications/host-context-changed`),params:Mf.describe(`Partial context update containing only changed fields.`)}),O({method:k(`ui/update-model-context`),params:O({content:A(hu).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:C(E(),T().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),O({method:k(`ui/initialize`),params:O({appInfo:il.describe(`App identification (name and version).`),appCapabilities:Af.describe(`Features and capabilities this app provides.`),protocolVersion:E().describe(`Protocol version this app supports.`)})}),O({protocolVersion:E().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:il.describe(`Host application identification and version.`),hostCapabilities:kf.describe(`Features and capabilities provided by the host.`),hostContext:Mf.describe(`Rich context about the host environment.`)}).passthrough();var Nf=`ui/resourceUri`,Pf=`text/html;profile=mcp-app`;function K3(e,t,n,r){let i=n._meta,a=i.ui,s=i[Nf],c=i;return a?.resourceUri&&!s?c={...i,[Nf]:a.resourceUri}:s&&!a?.resourceUri&&(c={...i,ui:{...a,resourceUri:s}}),e.registerTool(t,{...n,_meta:c},r)}function N3(e,t,n,r,i){return e.registerResource(t,n,{mimeType:Pf,...r},i)}function readDistAsset(e){let t=[new URL(`../dist/${e}`,import.meta.url),new URL(`../../dist/${e}`,import.meta.url)];for(let e of t){let t=kn(e);if(vn(t))return yn(t,`utf-8`)}throw Error(`Could not locate dist asset '${e}'; tried: ${t.map(String).join(`, `)}`)}function readRenderViewClientBundle(){return readDistAsset(`app/render-view-client.js`)}function readRenderViewClientStyles(){return readDistAsset(`app/render-view-client.css`)}const Ff=O({name:E().describe(`Project identifier`),title:E().optional().describe(`Human-readable project title`),contactPerson:E().optional().describe(`Maintainer contact information`),metadata:C(E(),T()).optional().describe(`Custom project metadata as key-value pairs`),extends:w([E(),A(E())]).optional().describe(`Style inheritance paths`),exclude:A(E()).optional().describe(`File exclusion patterns`),include:O({paths:A(E()).describe(`Include paths`),maxDepth:M().describe(`Maximum directory depth`),fileThreshold:M().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:O({outDir:E().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:O({hasTheme:j().describe(`Whether theme customization is defined`),hasDefaults:j().describe(`Whether default style values are defined`),hasCustomCss:j().describe(`Whether custom CSS is defined`)}).optional().describe(`Simplified styles configuration (boolean flags)`)});function serializeConfig(e){let t={name:e.name};return e.title!=null&&(t.title=e.title),e.contactPerson!=null&&(t.contactPerson=e.contactPerson),e.metadata&&(t.metadata=e.metadata),e.extends&&(t.extends=e.extends),e.exclude&&(t.exclude=e.exclude),e.include&&(t.include={paths:e.include.paths||[],maxDepth:e.include.maxDepth??3,fileThreshold:e.include.fileThreshold??30}),e.manualLayouts&&(t.manualLayouts={outDir:e.manualLayouts.outDir??`.likec4`}),e.styles&&(t.styles={hasTheme:!!e.styles.theme,hasDefaults:!!e.styles.defaults,hasCustomCss:!!e.styles.customCss}),t}const Lf=O({id:E().describe(`Element id (FQN)`),name:E().describe(`Element name`),kind:E().describe(`Element kind`),title:E(),tags:A(E()),metadata:C(E(),w([E(),A(E())])),includedInViews:A(O({id:E().describe(`View id`),title:E().describe(`View title`),type:D([`element`,`deployment`,`dynamic`]).describe(`View type`)})).describe(`Views that include this element`)});function serializeElement(e){return{id:e.id,name:e.name,kind:e.kind,title:e.title,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())}}function traverseGraph(e,t,n,r,i,a){let s=e.findElement(t);$t(s,`Element "${t}" not found`);let c=new Set,l={},u=0,f=!1,p=[{elementId:t,depth:0}];for(;p.length>0;){let{elementId:t,depth:s}=p.shift();if(s>i||c.has(t))continue;if(c.size>=a){f=!0;break}let m=e.findElement(t);if(!m)continue;c.add(t),u=Math.max(u,s);let h=(n===`incoming`?[...m.incoming(r)]:[...m.outgoing(r)]).map(e=>{let t={elementId:n===`incoming`?e.source.id:e.target.id};return e.title&&(t.relationshipLabel=e.title),e.technology&&(t.technology=e.technology),t});l[t]={...serializeElement(m),neighbors:h,depth:s};for(let e of h)c.has(e.elementId)||p.push({elementId:e.elementId,depth:s+1})}for(let e of Object.values(l))e.neighbors=e.neighbors.filter(e=>e.elementId in l);return{target:t,totalNodes:c.size,maxDepth:u,truncated:f,nodes:l}}const Rf=O({path:E().describe(`Path to the file`),range:O({start:O({line:M(),character:M()}),end:O({line:M(),character:M()})}).describe(`Range in the file`)}).nullable(),zf=A(O({title:E().nullable().describe(`Optional link title`),url:E().describe(`Link URL`),relative:E().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this element`);function serializeLinks(e){return(e.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null}))}const Bf=E().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),Vf=A(O({id:E().describe(`View id`),title:E().describe(`View title`),type:D([`element`,`deployment`,`dynamic`]).describe(`View type`)})),includedInViews=e=>[...e].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type})),mkLocate=(e,t)=>n=>{try{let r=e.locate({projectId:t,...n});return r?{path:ce.parse(r.uri).fsPath,range:r.range}:null}catch(e){return q.debug(`Failed to locate {params}`,{error:e,params:n}),null}};function toolError(e){return{isError:!0,content:[{type:`text`,text:e}]}}function pickRecord(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function buildViewScopedModel(e,t){let n=new Set,r=new Set,i=new Set,a=new Set,includeElement=t=>{let r=e.element(t);n.add(r.id);for(let e of r.ancestors())n.add(e.id)},includeDeployment=t=>{let n=e.deployment.element(t);r.add(n.id);for(let e of n.ancestors())r.add(e.id);n.isInstance()&&includeElement(n.element.id)},includeDeploymentRef=e=>{includeDeployment(e.deployment),Xt.isInsideInstanceRef(e)&&includeElement(e.element)};t._type===`element`&&t.viewOf&&includeElement(t.viewOf);for(let e of t.nodes)e.modelRef&&includeElement(e.modelRef),e.deploymentRef&&includeDeployment(e.deploymentRef);for(let n of t.edges)for(let t of n.relations){let n=e.relationship(t);n.isModelRelation()?(i.add(n.id),includeElement(n.source.id),includeElement(n.target.id)):(a.add(n.id),includeDeploymentRef(n.$relationship.source),includeDeploymentRef(n.$relationship.target))}let s=e.$data,c=Object.fromEntries(Object.entries(s.imports).flatMap(([e,t])=>{let r=t.filter(t=>n.has(Zt(e,t.id)));return r.length>0?[[e,r]]:[]}));return{...s,elements:pickRecord(s.elements,n),imports:c,relations:pickRecord(s.relations,i),deployments:{elements:pickRecord(s.deployments.elements,r),relations:pickRecord(s.deployments.relations,a)},views:{[t.id]:t},manualLayouts:{}}}function inlineLocalSvgIcon(e){if(typeof e!=`string`||!e.startsWith(`file:`)||!e.toLowerCase().split(/[?#]/)[0]?.endsWith(`.svg`))return e;try{return`data:image/svg+xml,${encodeURIComponent(yn(ce.parse(e).fsPath,`utf8`))}`}catch{return null}}function inlineLocalSvgIcons(e){return Array.isArray(e)?e.map(inlineLocalSvgIcons):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,e===`icon`?inlineLocalSvgIcon(t):inlineLocalSvgIcons(t)])):e}function buildRenderPayload(e){let t=e.fullModel?{...e.model.$data,views:{...e.model.$data.views,[e.viewId]:e.layoutedView}}:buildViewScopedModel(e.model,e.layoutedView);return{id:e.viewId,title:e.title,project:e.projectId,view:inlineLocalSvgIcons(e.layoutedView),model:inlineLocalSvgIcons(t)}}const Hf=`ui://likec4/render-view.html`,Uf=O({size:D([`compact`,`standard`,`large`]).default(`standard`),fitView:j().default(!0),initialZoom:M().min(.05).max(3).optional()}).default({size:`standard`,fitView:!0});function renderViewTool(e){return K3(e,`render-view`,{title:`Render View`,description:`Renders a LikeC4 view as an interactive diagram (pan/zoom/fit) inline in the chat.
389
389
 
390
390
  Request:
391
391
  - viewId: string — view id (name)
392
392
  - project: string (optional) — project id. Defaults to "default" if omitted.
393
+ - fullModel: boolean (optional) — include the complete model instead of data scoped to this view. Defaults to false.
394
+ - render.size: "compact", "standard", or "large" (optional) — initial canvas size hint. Defaults to "standard".
395
+ - render.fitView: boolean (optional) — fit the diagram into the canvas initially. Defaults to true.
396
+ - render.initialZoom: number (optional) — initial zoom level. This overrides render.fitView.
393
397
 
394
- Use this when the user wants to *see* a view. Use "read-view" instead when only the view's structure (nodes/edges) is needed.`,inputSchema:{viewId:X().describe(`View id (name)`),project:Gf},outputSchema:{id:X(),title:X(),project:X(),view:rf(X(),ef()).describe(`Full layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:rf(X(),ef()).describe(`Layouted model data (specification, elements, relations, deployments), scoped to this view only. Consumed by the paired UI to build a LikeC4Model for LikeC4ModelProvider — LikeC4Diagram requires one in context.`)},annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:qf}}},async e=>{let t=useLanguageServices(),n=t.projectsManager.ensureProjectId(e.project),r=await t.layoutedModel(n),i=r.findView(e.viewId);if(!i)return toolError(`View with ID '${e.viewId}' not found in project ${n}`);if(!i.isLayouted())return toolError(`View '${e.viewId}' has no layout`);let a=i.$layouted,s=i.title??i.id;return{content:[{type:`text`,text:`Rendered view "${s}"`}],structuredContent:buildRenderPayload({projectId:n,viewId:i.id,title:s,layoutedView:a,modelData:r.$data})}}),e}function renderHtml(e,t){return`<!doctype html>
398
+ Use this when the user wants to *see* a view. Use "read-view" instead when only the view's structure (nodes/edges) is needed.`,inputSchema:mcpToolSchema({viewId:E().describe(`View id (name)`),project:Bf,fullModel:j().default(!1).describe(`Include the complete model instead of data scoped to this view`),render:Uf}),outputSchema:mcpToolSchema({id:E(),title:E(),project:E(),view:C(E(),T()).describe(`Layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:C(E(),T()).describe(`Layouted model data (specification, elements, relations, deployments), scoped to this view by default; complete when fullModel is true. Consumed by the paired UI to build a LikeC4Model for LikeC4ModelProvider — LikeC4Diagram requires one in context.`),render:Uf}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:Hf}}},async e=>{let t=useLanguageServices(),n=t.projectsManager.ensureProjectId(e.project),r=await t.layoutedModel(n),i=r.findView(e.viewId);if(!i)return toolError(`View with ID '${e.viewId}' not found in project ${n}`);if(!i.isLayouted())return toolError(`View '${e.viewId}' has no layout`);let a=i.$layouted,s=i.title??i.id;return{content:[{type:`text`,text:`Rendered view "${s}"`}],structuredContent:{...buildRenderPayload({projectId:n,viewId:i.id,title:s,layoutedView:a,model:r,fullModel:e.fullModel}),render:e.render}}}),e}function renderHtml(e,t){return`<!doctype html>
395
399
  <html>
396
400
  <head>
397
401
  <meta charset="utf-8" />
@@ -405,11 +409,11 @@ Use this when the user wants to *see* a view. Use "read-view" instead when only
405
409
  <div id="root"></div>
406
410
  <script>${e}<\/script>
407
411
  </body>
408
- </html>`}function renderViewResource(e){return N3(e,`Render View UI`,qf,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:qf,mimeType:Vf,text:renderHtml(readRenderViewClientBundle(),readRenderViewClientStyles())}]})),e}function applySemanticLayoutTool(e){let t=useLanguageServices();return e.registerTool(`apply-semantic-layout`,{description:`Apply semantic layout to the likec4 view`,inputSchema:{projectId:completable(X().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(pt(`id`))),viewId:completable(X().describe(`View ID to apply semantic layout to`),async(e,n)=>{let r=n?.arguments?.projectId??t.projectsManager.default.id,i=await t.computedModel(r);if(!i)return[];let a=e??``;return Array.from(i.views()).filter(e=>e.id.startsWith(a)).map(pt(`id`))})},outputSchema:{reasoning:X().describe(`Reasoning behind the layout changes`),snapshotUri:X().nullish().describe(`Where snapshot was saved (after applying layout)`)}},async(n,r)=>{let i=t.projectsManager.ensureProjectId(n.projectId);i!==n.projectId&&await e.sendLoggingMessage({level:`notice`,data:`Using project "${i}" instead of "${n.projectId}"`},r.sessionId);let a=await t.computedModel(i),s=a.findView(n.viewId);if(!s)return toolError(`View "${n.viewId}" not found in project "${i}"`);let c=await St(s.$view,{name:`MCP`,async sendRequest({systemPrompt:e,userPrompt:t,diagram:n}){let i=await r.sendRequest({method:`sampling/createMessage`,params:{maxTokens:2e4,includeContext:`none`,systemPrompt:e,messages:[{role:`user`,content:{type:`text`,text:t+`
412
+ </html>`}function renderViewResource(e){return N3(e,`Render View UI`,Hf,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:Hf,mimeType:Pf,text:renderHtml(readRenderViewClientBundle(),readRenderViewClientStyles())}]})),e}function applySemanticLayoutTool(e){let t=useLanguageServices();return e.registerTool(`apply-semantic-layout`,{description:`Apply semantic layout to the likec4 view`,inputSchema:mcpToolSchema({projectId:completable(E().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(dt(`id`))),viewId:completable(E().describe(`View ID to apply semantic layout to`),async(e,n)=>{let r=n?.arguments?.projectId??t.projectsManager.default.id,i=await t.computedModel(r);if(!i)return[];let a=e??``;return Array.from(i.views()).filter(e=>e.id.startsWith(a)).map(dt(`id`))})}),outputSchema:mcpToolSchema({reasoning:E().describe(`Reasoning behind the layout changes`),snapshotUri:E().nullish().describe(`Where snapshot was saved (after applying layout)`)})},async(n,r)=>{let i=t.projectsManager.ensureProjectId(n.projectId);i!==n.projectId&&await e.sendLoggingMessage({level:`notice`,data:`Using project "${i}" instead of "${n.projectId}"`},r.sessionId);let a=await t.computedModel(i),s=a.findView(n.viewId);if(!s)return toolError(`View "${n.viewId}" not found in project "${i}"`);let c=await bt(s.$view,{name:`MCP`,async sendRequest({systemPrompt:e,userPrompt:t,diagram:n}){let i=await r.sendRequest({method:`sampling/createMessage`,params:{maxTokens:2e4,includeContext:`none`,systemPrompt:e,messages:[{role:`user`,content:{type:`text`,text:t+`
409
413
 
410
- `+n}}]}},$({content:$({type:af(`text`),text:X()})}));return i.content.type===`text`?i.content.text:JSON.stringify(i.content)}},r.signal);if(!c)return await e.sendLoggingMessage({level:`error`,data:`Failed to generate layout hints`},r.sessionId),toolError(`Failed to generate layout hints`);await e.sendLoggingMessage({level:`info`,data:`Applying semantic layout...`},r.sessionId);let l=await t.views.layouter.aiLayout({view:s.$view,styles:a.$styles},c),u=await t.editor.applyChange({change:{op:`save-view-snapshot`,layout:l.diagram},viewId:s.id,projectId:i});return await e.sendLoggingMessage({level:`info`,data:`Layout applied successfully`},r.sessionId),{content:[],structuredContent:{reasoning:c.reasoning,...!!u.location&&{snapshotUri:u.location.uri.toString()}}}}),e}const Jf=Uf.extend({description:X().nullable().describe(`Element description`),technology:X().nullable().describe(`Element technology`),shape:X().describe(`Rendered shape`),color:X().describe(`Rendered color`),children:Q(X()).describe(`Direct child element ids`),incomingCount:Z().describe(`Number of incoming relationships`),outgoingCount:Z().describe(`Number of outgoing relationships`)}),Yf=likec4Tool({name:`batch-read-elements`,description:`
414
+ `+n}}]}},O({content:O({type:k(`text`),text:E()})}));return i.content.type===`text`?i.content.text:JSON.stringify(i.content)}},r.signal);if(!c)return await e.sendLoggingMessage({level:`error`,data:`Failed to generate layout hints`},r.sessionId),toolError(`Failed to generate layout hints`);await e.sendLoggingMessage({level:`info`,data:`Applying semantic layout...`},r.sessionId);let l=await t.views.layouter.aiLayout({view:s.$view,styles:a.$styles},c),u=await t.editor.applyChange({change:{op:`save-view-snapshot`,layout:l.diagram},viewId:s.id,projectId:i});return await e.sendLoggingMessage({level:`info`,data:`Layout applied successfully`},r.sessionId),{content:[],structuredContent:{reasoning:c.reasoning,...!!u.location&&{snapshotUri:u.location.uri.toString()}}}}),e}const Wf=Lf.extend({description:E().nullable().describe(`Element description`),technology:E().nullable().describe(`Element technology`),shape:E().describe(`Rendered shape`),color:E().describe(`Rendered color`),children:A(E()).describe(`Direct child element ids`),incomingCount:M().describe(`Number of incoming relationships`),outgoingCount:M().describe(`Number of outgoing relationships`),links:zf,sourceLocation:Rf}),Gf=likec4Tool({name:`batch-read-elements`,description:`
411
415
  Read details of multiple elements in a single call, reducing round-trips.
412
- Returns a compact summary for each element including metadata, description, technology, shape, children, and relationship counts.
416
+ Returns a compact summary for each element including metadata, description, technology, shape, children, relationship counts, links and source location.
413
417
 
414
418
  Request:
415
419
  - ids: string[] — array of element ids (FQNs) to read (max 50)
@@ -431,6 +435,8 @@ Response (JSON object):
431
435
  - incomingCount: number — number of incoming relationships
432
436
  - outgoingCount: number — number of outgoing relationships
433
437
  - includedInViews: View[] — views that include this element
438
+ - links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this element
439
+ - sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
434
440
  - notFound: string[] — ids that were not found in the project
435
441
 
436
442
  View (object) fields:
@@ -444,6 +450,8 @@ Notes:
444
450
  - Maximum 50 element ids per call.
445
451
  - Elements not found are listed in notFound array (not an error).
446
452
  - More efficient than multiple read-element calls when you need summary data for many elements.
453
+ - Returns the same "links" and "sourceLocation" as read-element, so it fully replaces read-element for that case.
454
+ - Call read-element only when you also need relationships, deployedInstances, defaultView or project.
447
455
 
448
456
  Example response:
449
457
  {
@@ -464,12 +472,19 @@ Example response:
464
472
  "outgoingCount": 3,
465
473
  "includedInViews": [
466
474
  { "id": "system-overview", "title": "System Overview", "type": "element" }
467
- ]
475
+ ],
476
+ "links": [
477
+ { "title": "Documentation", "url": "https://docs.example.com/frontend", "relative": null }
478
+ ],
479
+ "sourceLocation": {
480
+ "path": "/abs/path/project/model.c4",
481
+ "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
482
+ }
468
483
  }
469
484
  ],
470
485
  "notFound": []
471
486
  }
472
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:Q(X()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:Gf},outputSchema:{elements:Q(Jf),notFound:Q(X()).describe(`Element ids that were not found`)}})(async(e,t)=>{Qt(t.ids.length<=50,`Maximum 50 element ids per call`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=[],a=[];for(let e of t.ids){let t=r.findElement(e);if(!t){a.push(e);continue}i.push({...serializeElement(t),description:t.description.text,technology:t.technology,shape:t.shape,color:t.color,children:[...t.children()].map(e=>e.id),incomingCount:t.allIncoming.size,outgoingCount:t.allOutgoing.size})}return{elements:i,notFound:a}}),Xf=$({id:X(),kind:X(),title:X(),description:X().nullable(),technology:X().nullable(),shape:X(),color:X()}),Zf=$({element1:Xf,element2:Xf,propertyDiffs:Q($({property:X().describe(`Property name`),element1Value:X().nullable().describe(`Value in element1`),element2Value:X().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:$({onlyInElement1:Q(X()).describe(`Tags present only in element1`),onlyInElement2:Q(X()).describe(`Tags present only in element2`),common:Q(X()).describe(`Tags present in both elements`)}),metadata:$({onlyInElement1:rf(tf([X(),Q(X())])).describe(`Metadata keys only in element1`),onlyInElement2:rf(tf([X(),Q(X())])).describe(`Metadata keys only in element2`),different:Q($({key:X(),element1Value:tf([X(),Q(X())]),element2Value:tf([X(),Q(X())])})).describe(`Metadata keys present in both but with different values`),common:rf(tf([X(),Q(X())])).describe(`Metadata keys with identical values in both`)}),relationships:$({incomingOnlyElement1:Z().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:Z().describe(`Count of unique source elements sending to element2 only`),incomingShared:Z().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:Z().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:Z().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:Z().describe(`Count of unique target elements receiving from both`)})}),Qf=likec4Tool({name:`element-diff`,description:`
487
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:A(E()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:Bf},outputSchema:{elements:A(Wf),notFound:A(E()).describe(`Element ids that were not found`)}})(async(e,t)=>{$t(t.ids.length<=50,`Maximum 50 element ids per call`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=mkLocate(e,n),a=[],s=[];for(let e of t.ids){let t=r.findElement(e);if(!t){s.push(e);continue}a.push({...serializeElement(t),description:t.description.text,technology:t.technology,shape:t.shape,color:t.color,children:[...t.children()].map(e=>e.id),incomingCount:t.allIncoming.size,outgoingCount:t.allOutgoing.size,links:serializeLinks(t),sourceLocation:i({element:t.id})})}return{elements:a,notFound:s}}),Kf=O({id:E(),kind:E(),title:E(),description:E().nullable(),technology:E().nullable(),shape:E(),color:E()}),qf=O({element1:Kf,element2:Kf,propertyDiffs:A(O({property:E().describe(`Property name`),element1Value:E().nullable().describe(`Value in element1`),element2Value:E().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:O({onlyInElement1:A(E()).describe(`Tags present only in element1`),onlyInElement2:A(E()).describe(`Tags present only in element2`),common:A(E()).describe(`Tags present in both elements`)}),metadata:O({onlyInElement1:C(E(),w([E(),A(E())])).describe(`Metadata keys only in element1`),onlyInElement2:C(E(),w([E(),A(E())])).describe(`Metadata keys only in element2`),different:A(O({key:E(),element1Value:w([E(),A(E())]),element2Value:w([E(),A(E())])})).describe(`Metadata keys present in both but with different values`),common:C(E(),w([E(),A(E())])).describe(`Metadata keys with identical values in both`)}),relationships:O({incomingOnlyElement1:M().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:M().describe(`Count of unique source elements sending to element2 only`),incomingShared:M().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:M().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:M().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:M().describe(`Count of unique target elements receiving from both`)})}),Jf=likec4Tool({name:`element-diff`,description:`
473
488
  Compare two elements side-by-side, showing differences in properties, tags, metadata, and relationships.
474
489
 
475
490
  Request:
@@ -529,7 +544,7 @@ Example response:
529
544
  "outgoingShared": 2
530
545
  }
531
546
  }
532
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:X().describe(`First element id (FQN)`),element2Id:X().describe(`Second element id (FQN)`),project:Gf},outputSchema:Zf.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);Qt(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);Qt(a,`Element "${t.element2Id}" not found in project "${n}"`);let s=[],c=[{name:`kind`,get:e=>e.kind},{name:`title`,get:e=>e.title},{name:`description`,get:e=>e.description.text},{name:`technology`,get:e=>e.technology},{name:`shape`,get:e=>e.shape},{name:`color`,get:e=>e.color}];for(let e of c){let t=e.get(i),n=e.get(a);t!==n&&s.push({property:e.name,element1Value:t,element2Value:n})}let l=new Set(i.tags),u=new Set(a.tags),f=[],p=[],m=[];for(let e of l)u.has(e)?f.push(e):p.push(e);for(let e of u)l.has(e)||m.push(e);let h=i.getMetadata(),g=a.getMetadata(),v=new Set([...Object.keys(h),...Object.keys(g)]),y={},b={},ee=[],te={};for(let e of v){let t=h[e],n=g[e];t!==void 0&&n===void 0?y[e]=t:t===void 0&&n!==void 0?b[e]=n:t!==void 0&&n!==void 0&&(JSON.stringify(t)===JSON.stringify(n)?te[e]=t:ee.push({key:e,element1Value:t,element2Value:n}))}let ne=new Set([...i.incoming()].map(e=>e.source.id)),x=new Set([...a.incoming()].map(e=>e.source.id)),re=new Set([...i.outgoing()].map(e=>e.target.id)),ie=new Set([...a.outgoing()].map(e=>e.target.id)),ae=0,oe=0,S=0;for(let e of ne)x.has(e)?ae++:oe++;for(let e of x)ne.has(e)||S++;let se=0,ce=0,le=0;for(let e of re)ie.has(e)?se++:ce++;for(let e of ie)re.has(e)||le++;return{element1:{id:i.id,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,shape:i.shape,color:i.color},element2:{id:a.id,kind:a.kind,title:a.title,description:a.description.text,technology:a.technology,shape:a.shape,color:a.color},propertyDiffs:s,tags:{onlyInElement1:p,onlyInElement2:m,common:f},metadata:{onlyInElement1:y,onlyInElement2:b,different:ee,common:te},relationships:{incomingOnlyElement1:oe,incomingOnlyElement2:S,incomingShared:ae,outgoingOnlyElement1:ce,outgoingOnlyElement2:le,outgoingShared:se}}}),$f=likec4Tool({name:`find-relationship-paths`,description:`
547
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:E().describe(`First element id (FQN)`),element2Id:E().describe(`Second element id (FQN)`),project:Bf},outputSchema:qf.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);$t(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);$t(a,`Element "${t.element2Id}" not found in project "${n}"`);let s=[],c=[{name:`kind`,get:e=>e.kind},{name:`title`,get:e=>e.title},{name:`description`,get:e=>e.description.text},{name:`technology`,get:e=>e.technology},{name:`shape`,get:e=>e.shape},{name:`color`,get:e=>e.color}];for(let e of c){let t=e.get(i),n=e.get(a);t!==n&&s.push({property:e.name,element1Value:t,element2Value:n})}let l=new Set(i.tags),u=new Set(a.tags),f=[],p=[],m=[];for(let e of l)u.has(e)?f.push(e):p.push(e);for(let e of u)l.has(e)||m.push(e);let h=i.getMetadata(),g=a.getMetadata(),v=new Set([...Object.keys(h),...Object.keys(g)]),y={},b={},ee=[],te={};for(let e of v){let t=h[e],n=g[e];t!==void 0&&n===void 0?y[e]=t:t===void 0&&n!==void 0?b[e]=n:t!==void 0&&n!==void 0&&(JSON.stringify(t)===JSON.stringify(n)?te[e]=t:ee.push({key:e,element1Value:t,element2Value:n}))}let ne=new Set([...i.incoming()].map(e=>e.source.id)),x=new Set([...a.incoming()].map(e=>e.source.id)),re=new Set([...i.outgoing()].map(e=>e.target.id)),ie=new Set([...a.outgoing()].map(e=>e.target.id)),ae=0,oe=0,S=0;for(let e of ne)x.has(e)?ae++:oe++;for(let e of x)ne.has(e)||S++;let se=0,ce=0,le=0;for(let e of re)ie.has(e)?se++:ce++;for(let e of ie)re.has(e)||le++;return{element1:{id:i.id,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,shape:i.shape,color:i.color},element2:{id:a.id,kind:a.kind,title:a.title,description:a.description.text,technology:a.technology,shape:a.shape,color:a.color},propertyDiffs:s,tags:{onlyInElement1:p,onlyInElement2:m,common:f},metadata:{onlyInElement1:y,onlyInElement2:b,different:ee,common:te},relationships:{incomingOnlyElement1:oe,incomingOnlyElement2:S,incomingShared:ae,outgoingOnlyElement1:ce,outgoingOnlyElement2:le,outgoingShared:se}}}),Yf=likec4Tool({name:`find-relationship-paths`,description:`
533
548
  Discover all paths (chains of relationships) between two elements, supporting multi-hop traversal.
534
549
 
535
550
  Request:
@@ -618,7 +633,7 @@ Example response:
618
633
  }
619
634
  ]
620
635
  }
621
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:X().describe(`Source element FQN`),targetId:X().describe(`Target element FQN`),maxDepth:Z().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:$d().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:Gf},outputSchema:{paths:Q($({length:Z().describe(`Number of hops in the path`),steps:Q($({source:X().describe(`Source element FQN`),target:X().describe(`Target element FQN`),relationship:$({kind:X().nullable().describe(`Relationship kind`),title:X().nullable().describe(`Relationship title`),description:X().nullable().describe(`Relationship description`),technology:X().nullable().describe(`Relationship technology`),tags:Q(X()).describe(`Relationship tags`)})})).describe(`Ordered sequence of relationships in the path`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.sourceId);Qt(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);Qt(a,`Target element "${t.targetId}" not found in project "${n}"`),Qt(i.id!==a.id,`Source and target must be different elements`);let s=t.maxDepth,c=t.includeIndirect?`all`:`direct`,l=[{elementId:i.id,path:[],visited:new Set([i.id])}],u=[];for(;l.length>0&&u.length<100;){let e=l.shift();if(e.path.length>=s)continue;let t=r.findElement(e.elementId);if(t)for(let n of t.outgoing(c)){let t=n.target.id;if(t===a.id){let t={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};if(u.push({length:e.path.length+1,steps:[...e.path,t]}),u.length>=100)break;continue}if(e.visited.has(t))continue;let r={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};l.push({elementId:t,path:[...e.path,r],visited:new Set([...e.visited,t])})}}return u.sort((e,t)=>e.length-t.length),{paths:u}}),ep=$({id:X(),title:X(),kind:X()}),tp=$({type:of([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:ep,target:ep,kind:X().nullable().describe(`Relationship kind`),title:X().nullable().describe(`Relationship title`),description:X().nullable().describe(`Relationship description`),technology:X().nullable().describe(`Relationship technology`),tags:Q(X()).describe(`Relationship tags`),includedInViews:Kf.describe(`Views that include this relationship`),sourceLocation:Wf}),np=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`
636
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:E().describe(`Source element FQN`),targetId:E().describe(`Target element FQN`),maxDepth:M().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:j().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:Bf},outputSchema:{paths:A(O({length:M().describe(`Number of hops in the path`),steps:A(O({source:E().describe(`Source element FQN`),target:E().describe(`Target element FQN`),relationship:O({kind:E().nullable().describe(`Relationship kind`),title:E().nullable().describe(`Relationship title`),description:E().nullable().describe(`Relationship description`),technology:E().nullable().describe(`Relationship technology`),tags:A(E()).describe(`Relationship tags`)})})).describe(`Ordered sequence of relationships in the path`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.sourceId);$t(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);$t(a,`Target element "${t.targetId}" not found in project "${n}"`),$t(i.id!==a.id,`Source and target must be different elements`);let s=t.maxDepth,c=t.includeIndirect?`all`:`direct`,l=[{elementId:i.id,path:[],visited:new Set([i.id])}],u=[];for(;l.length>0&&u.length<100;){let e=l.shift();if(e.path.length>=s)continue;let t=r.findElement(e.elementId);if(t)for(let n of t.outgoing(c)){let t=n.target.id;if(t===a.id){let t={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};if(u.push({length:e.path.length+1,steps:[...e.path,t]}),u.length>=100)break;continue}if(e.visited.has(t))continue;let r={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};l.push({elementId:t,path:[...e.path,r],visited:new Set([...e.visited,t])})}}return u.sort((e,t)=>e.length-t.length),{paths:u}}),Xf=O({id:E(),title:E(),kind:E()}),Zf=O({type:D([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:Xf,target:Xf,kind:E().nullable().describe(`Relationship kind`),title:E().nullable().describe(`Relationship title`),description:E().nullable().describe(`Relationship description`),technology:E().nullable().describe(`Relationship technology`),tags:A(E()).describe(`Relationship tags`),includedInViews:Vf.describe(`Views that include this relationship`),sourceLocation:Rf}),Qf=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`
622
637
  Find relationships between two LikeC4 elements within a project.
623
638
 
624
639
  What it does:
@@ -689,7 +704,7 @@ Response:
689
704
  }
690
705
  ]
691
706
  }
692
- `,inputSchema:{element1:X().describe(`Element ID (FQN)`),element2:X().describe(`Element ID (FQN)`),project:Gf},outputSchema:{found:Q(tp)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(rn(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);nn(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);nn(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=fn.findConnection(a,s,`both`).flatMap(e=>[...e.relations]);for(let e of l){let t=e.source===a&&e.target===s||e.source===s&&e.target===a;r.push({type:t?`direct`:`indirect`,source:{id:e.source.id,title:e.source.title,kind:e.source.kind},target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags],includedInViews:includedInViews(e.views()),sourceLocation:c({relation:e.id})})}return{found:r}}),rp=likec4Tool({name:`list-projects`,description:`
707
+ `,inputSchema:{element1:E().describe(`Element ID (FQN)`),element2:E().describe(`Element ID (FQN)`),project:Bf},outputSchema:{found:A(Zf)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(an(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);rn(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);rn(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=pn.findConnection(a,s,`both`).flatMap(e=>[...e.relations]);for(let e of l){let t=e.source===a&&e.target===s||e.source===s&&e.target===a;r.push({type:t?`direct`:`indirect`,source:{id:e.source.id,title:e.source.title,kind:e.source.kind},target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags],includedInViews:includedInViews(e.views()),sourceLocation:c({relation:e.id})})}return{found:r}}),$f=likec4Tool({name:`list-projects`,description:`
693
708
  List LikeC4 projects discoverable in the current workspace.
694
709
 
695
710
  Request:
@@ -722,12 +737,13 @@ Example response:
722
737
  }
723
738
  ]
724
739
  }
725
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:Q($({id:X(),title:X(),folder:X(),sources:Q(X())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))})),ip=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=ip.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(Xt).join(`/`)}function toVirtualSourcePath(e,t,n){let r=toPortablePath(Yt(e,t));return r===``||r.startsWith(`..`)?n:r}function formatDiagnostics(e){return e.map(e=>`- line ${e.range.start.line+1}, column ${e.range.start.character+1}: ${e.message}`).join(`
740
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:A(O({id:E(),title:E(),folder:E(),sources:A(E())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))})),ep=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=ep.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(Jt).join(`/`)}function toVirtualSourcePath(e,t,n){let r=toPortablePath(qt(e,t));return r===``||r.startsWith(`..`)?n:r}function formatDiagnostics(e){return e.map(e=>`- line ${e.range.start.line+1}, column ${e.range.start.character+1}: ${e.message}`).join(`
726
741
  `)}function previewViewTool(e){return K3(e,`preview-view`,{title:`Preview View`,description:`Renders a preview of a LikeC4 view defined by DSL text, in the context of an existing project's real elements — without saving anything to disk.
727
742
 
728
743
  Request:
729
744
  - dsl: string — a single \`view <id> ... { ... }\` definition. It must reference elements that already exist in the target project.
730
745
  - project: string (optional) — project id. Defaults to "default" if omitted.
746
+ - fullModel: boolean (optional) — include the complete model instead of data scoped to this view. Defaults to false.
731
747
 
732
748
  Behavior:
733
749
  - The view id must be new (not already present in the project). If the view id matches an existing view, an error is returned — use a different id, or use "render-view" to render an existing view.
@@ -735,7 +751,7 @@ Behavior:
735
751
 
736
752
  Note: preview styling may not exactly match the real project (custom theme/style extensions aren't applied to the preview). Only \`view <id> ...\` (element view) declarations are recognized for id-detection — a \`dynamic view <id> {...}\` or \`deployment view <id> {...}\` will fail with a generic "could not find a \`view <id>\`" error instead.
737
753
 
738
- Use "preview-view" to iterate on a new view definition before creating it for real. Use "render-view" to render a view that's already saved.`,inputSchema:{dsl:X().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:Gf},outputSchema:{id:X(),title:X(),project:X(),view:rf(X(),ef()),model:rf(X(),ef())},annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:qf}}},async e=>{try{var t=_usingCtx();let n=useLanguageServices(),r=n.projectsManager.ensureProjectId(e.project),i=extractViewId(e.dsl);if(!i)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let a=n.project(r);if((await n.computedModel(r))?.findView(i))return toolError(`View "${i}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let s={};for(let[e,t]of a.documents.entries()){let r=toVirtualSourcePath(a.folder.fsPath,t.fsPath,`seed-${e}.c4`);s[r]=n.documentText(t.toString())??``}let c=`${En()}.c4`;s[c]=wrapAsViewsBlock(e.dsl);let l=t.a(await ee(s,{printErrors:!1,throwIfInvalid:!1})),u=l.getErrors();if(u.length>0)return toolError(`Failed to build preview:\n${formatDiagnostics(u)}`);let f=await l.computedModel(),p=f.findView(i);if(!p)return toolError(`View "${i}" was not found after building the preview.`);let m=await l.viewsService.layoutView({viewId:p.id,projectId:r});if(!m)return toolError(`Failed to layout preview view "${i}".`);let h=p.title??p.id;return{content:[{type:`text`,text:`Rendered preview of view "${h}"`}],structuredContent:buildRenderPayload({projectId:r,viewId:p.id,title:h,layoutedView:m.diagram,modelData:f.$data})}}catch(e){t.e=e}finally{await t.d()}}),e}const ap=of([`exact`,`contains`,`exists`]),op=likec4Tool({name:`query-by-metadata`,description:`
754
+ Use "preview-view" to iterate on a new view definition before creating it for real. Use "render-view" to render a view that's already saved.`,inputSchema:mcpToolSchema({dsl:E().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:Bf,fullModel:j().default(!1).describe(`Include the complete model instead of data scoped to this view`)}),outputSchema:mcpToolSchema({id:E(),title:E(),project:E(),view:C(E(),T()),model:C(E(),T())}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:Hf}}},async e=>{try{var t=_usingCtx();let n=useLanguageServices(),r=n.projectsManager.ensureProjectId(e.project),i=extractViewId(e.dsl);if(!i)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let a=n.project(r);if((await n.computedModel(r))?.findView(i))return toolError(`View "${i}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let s={};for(let[e,t]of a.documents.entries()){let r=toVirtualSourcePath(a.folder.fsPath,t.fsPath,`seed-${e}.c4`);s[r]=n.documentText(t.toString())??``}let c=`${Dn()}.c4`;s[c]=wrapAsViewsBlock(e.dsl);let l=t.a(await ee(s,{printErrors:!1,throwIfInvalid:!1})),u=l.getErrors();if(u.length>0)return toolError(`Failed to build preview:\n${formatDiagnostics(u)}`);let f=await l.computedModel(),p=f.findView(i);if(!p)return toolError(`View "${i}" was not found after building the preview.`);let m=l.projectsManager.ensureProjectId(Yt(f.$data.projectId)),h=await l.viewsService.layoutView({viewId:p.id,projectId:m});if(!h)return toolError(`Failed to layout preview view "${i}".`);let g=p.title??p.id;return{content:[{type:`text`,text:`Rendered preview of view "${g}"`}],structuredContent:buildRenderPayload({projectId:r,viewId:p.id,title:g,layoutedView:h.diagram,model:f,fullModel:e.fullModel})}}catch(e){t.e=e}finally{await t.d()}}),e}const tp=D([`exact`,`contains`,`exists`]),np=likec4Tool({name:`query-by-metadata`,description:`
739
755
  Search elements and deployment nodes by metadata key-value pairs with flexible matching modes.
740
756
 
741
757
  Request:
@@ -801,7 +817,7 @@ Example response:
801
817
  }
802
818
  ]
803
819
  }
804
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:X().describe(`Metadata key to filter by`),value:X().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:ap.optional().default(`exact`).describe(`Matching mode`),project:Gf},outputSchema:{results:Q(Uf.extend({matchedValue:X().describe(`The metadata value that matched`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.matchMode,a=[],matches=(e,t,n)=>{let r=Array.isArray(e)?e:[e];switch(n){case`exists`:return!0;case`exact`:return t!==void 0&&r.some(e=>e===t);case`contains`:{if(t===void 0)return!1;let e=t.toLowerCase();return r.some(t=>t.toLowerCase().includes(e))}default:return!1}},getMatchedValue=(e,t,n)=>{let r=Array.isArray(e)?e:[e];if(n===`exists`||t===void 0)return r[0]||``;if(n===`exact`)return r.find(e=>e===t)||r[0]||``;if(n===`contains`){let e=t.toLowerCase();return r.find(t=>t.toLowerCase().includes(e))||r[0]||``}return r[0]||``};for(let e of r.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}if(a.length<50)for(let e of r.deployment.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}return{results:a}}),sp=likec4Tool({name:`query-by-tag-pattern`,description:`
820
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:E().describe(`Metadata key to filter by`),value:E().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:tp.optional().default(`exact`).describe(`Matching mode`),project:Bf},outputSchema:{results:A(Lf.extend({matchedValue:E().describe(`The metadata value that matched`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.matchMode,a=[],matches=(e,t,n)=>{let r=Array.isArray(e)?e:[e];switch(n){case`exists`:return!0;case`exact`:return t!==void 0&&r.some(e=>e===t);case`contains`:{if(t===void 0)return!1;let e=t.toLowerCase();return r.some(t=>t.toLowerCase().includes(e))}default:return!1}},getMatchedValue=(e,t,n)=>{let r=Array.isArray(e)?e:[e];if(n===`exists`||t===void 0)return r[0]||``;if(n===`exact`)return r.find(e=>e===t)||r[0]||``;if(n===`contains`){let e=t.toLowerCase();return r.find(t=>t.toLowerCase().includes(e))||r[0]||``}return r[0]||``};for(let e of r.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}if(a.length<50)for(let e of r.deployment.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}return{results:a}}),rp=likec4Tool({name:`query-by-tag-pattern`,description:`
805
821
  Search elements by tag patterns using prefix or substring matching.
806
822
  Useful for tag taxonomies with structured naming conventions (e.g., "schedule_*", "*_asil_*").
807
823
 
@@ -856,7 +872,7 @@ Example response:
856
872
  "truncated": false,
857
873
  "matchedTagValues": ["target_asil_qm", "target_asil_asil_b", "target_asil_qm__tbc"]
858
874
  }
859
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:X().min(1).describe(`Tag pattern to match`),matchMode:of([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:Gf},outputSchema:{results:Q(Uf.extend({matchedTags:Q(X()).describe(`Tags that matched the pattern`)})),truncated:$d().describe(`True if results were truncated`),matchedTagValues:Q(X()).describe(`All unique tag values matching the pattern across all elements`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.pattern.toLowerCase(),matchesTag=e=>{let n=e.toLowerCase();switch(t.matchMode){case`prefix`:return n.startsWith(i);case`contains`:return n.includes(i);case`suffix`:return n.endsWith(i)}},a=[],s=!1,c=new Set;for(let e of r.elements()){let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}for(let e of r.deployment.elements()){if(!sn(e))continue;let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}return{results:a,truncated:s,matchedTagValues:[...c].sort((e,t)=>e.localeCompare(t))}}),cp=likec4Tool({name:`query-by-tags`,description:`
875
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:E().min(1).describe(`Tag pattern to match`),matchMode:D([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:Bf},outputSchema:{results:A(Lf.extend({matchedTags:A(E()).describe(`Tags that matched the pattern`)})),truncated:j().describe(`True if results were truncated`),matchedTagValues:A(E()).describe(`All unique tag values matching the pattern across all elements`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.pattern.toLowerCase(),matchesTag=e=>{let n=e.toLowerCase();switch(t.matchMode){case`prefix`:return n.startsWith(i);case`contains`:return n.includes(i);case`suffix`:return n.endsWith(i)}},a=[],s=!1,c=new Set;for(let e of r.elements()){let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}for(let e of r.deployment.elements()){if(!cn(e))continue;let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}return{results:a,truncated:s,matchedTagValues:[...c].sort((e,t)=>e.localeCompare(t))}}),ip=likec4Tool({name:`query-by-tags`,description:`
860
876
  Advanced tag filtering with boolean logic (AND, OR, NOT).
861
877
 
862
878
  Request:
@@ -920,7 +936,7 @@ Example response:
920
936
  }
921
937
  ]
922
938
  }
923
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:Q(X()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:Q(X()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:Q(X()).optional().describe(`Element must have NONE of these tags (NOT)`),project:Gf},outputSchema:{results:Q(Uf),truncated:$d().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{Qt(t.allOf&&t.allOf.length>0||t.anyOf&&t.anyOf.length>0||t.noneOf&&t.noneOf.length>0,`At least one condition (allOf, anyOf, or noneOf) must be specified with at least one tag`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=[],a=!1,matchesTags=e=>{let n=e instanceof Set?e:new Set(e);return!(t.allOf&&t.allOf.length>0&&!t.allOf.every(e=>n.has(e))||t.anyOf&&t.anyOf.length>0&&!t.anyOf.some(e=>n.has(e))||t.noneOf&&t.noneOf.length>0&&t.noneOf.some(e=>n.has(e)))};for(let e of r.elements()){if(i.length>=50){a=!0;break}matchesTags(e.tags)&&i.push(serializeElement(e))}if(!a)for(let e of r.deployment.elements()){if(i.length>=50){a=!0;break}sn(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),lp=of([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),up=likec4Tool({name:`query-graph`,description:`
939
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:A(E()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:A(E()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:A(E()).optional().describe(`Element must have NONE of these tags (NOT)`),project:Bf},outputSchema:{results:A(Lf),truncated:j().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{$t(t.allOf&&t.allOf.length>0||t.anyOf&&t.anyOf.length>0||t.noneOf&&t.noneOf.length>0,`At least one condition (allOf, anyOf, or noneOf) must be specified with at least one tag`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=[],a=!1,matchesTags=e=>{let n=e instanceof Set?e:new Set(e);return!(t.allOf&&t.allOf.length>0&&!t.allOf.every(e=>n.has(e))||t.anyOf&&t.anyOf.length>0&&!t.anyOf.some(e=>n.has(e))||t.noneOf&&t.noneOf.length>0&&t.noneOf.some(e=>n.has(e)))};for(let e of r.elements()){if(i.length>=50){a=!0;break}matchesTags(e.tags)&&i.push(serializeElement(e))}if(!a)for(let e of r.deployment.elements()){if(i.length>=50){a=!0;break}cn(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),ap=D([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),op=likec4Tool({name:`query-graph`,description:`
924
940
  Query element hierarchy and relationships in the architecture graph.
925
941
 
926
942
  Request:
@@ -992,7 +1008,7 @@ Example response:
992
1008
  ],
993
1009
  "truncated": false
994
1010
  }
995
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:X().describe(`Element id (FQN) to query`),queryType:lp.describe(`Type of graph query`),includeIndirect:$d().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:Gf},outputSchema:{results:Q(Uf),truncated:$d().describe(`True if results were truncated due to exceeding maximum limit`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);Qt(r,`Element "${t.elementId}" not found in project "${n}"`);let i=[],a=!1;switch(t.queryType){case`ancestors`:for(let e of r.ancestors()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`descendants`:for(let e of r.descendants()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`siblings`:for(let e of r.siblings()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`children`:for(let e of r.children()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`parent`:{let e=r.parent;e&&i.push(serializeElement(e));break}case`incomers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.incomers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}case`outgoers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.outgoers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}}return{results:i,truncated:a}}),dp=$({elementId:X().describe(`ID of the incoming element`),relationshipLabel:X().optional().describe(`Label on the relationship`),technology:X().optional().describe(`Technology specified on the relationship`)}),fp=likec4Tool({name:`query-incomers-graph`,description:`
1011
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:E().describe(`Element id (FQN) to query`),queryType:ap.describe(`Type of graph query`),includeIndirect:j().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:Bf},outputSchema:{results:A(Lf),truncated:j().describe(`True if results were truncated due to exceeding maximum limit`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);$t(r,`Element "${t.elementId}" not found in project "${n}"`);let i=[],a=!1;switch(t.queryType){case`ancestors`:for(let e of r.ancestors()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`descendants`:for(let e of r.descendants()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`siblings`:for(let e of r.siblings()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`children`:for(let e of r.children()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`parent`:{let e=r.parent;e&&i.push(serializeElement(e));break}case`incomers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.incomers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}case`outgoers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.outgoers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}}return{results:i,truncated:a}}),sp=O({elementId:E().describe(`ID of the incoming element`),relationshipLabel:E().optional().describe(`Label on the relationship`),technology:E().optional().describe(`Technology specified on the relationship`)}),cp=likec4Tool({name:`query-incomers-graph`,description:`
996
1012
  Query the complete graph of all elements that provide input to the target element (recursive incomers/producers).
997
1013
 
998
1014
  This tool performs a breadth-first traversal to discover all upstream dependencies - elements that directly or
@@ -1049,7 +1065,7 @@ Notes:
1049
1065
  Example:
1050
1066
  For a database element, this returns all services, APIs, and components that write to it,
1051
1067
  plus all their dependencies, recursively up to maxDepth levels.
1052
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:X().describe(`Target element id (FQN) to query incomers for`),includeIndirect:$d().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:Z().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:Z().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Gf},outputSchema:{target:X().describe(`Target element id`),totalNodes:Z().describe(`Total number of nodes in the graph`),maxDepth:Z().describe(`Maximum depth reached`),truncated:$d().describe(`True if result was truncated due to maxNodes limit`),nodes:rf(Uf.extend({incomers:Q(dp).describe(`Incoming relationships with details`),depth:Z().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);Qt(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`incoming`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,incomers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),pp=$({elementId:X().describe(`ID of the outgoing element`),relationshipLabel:X().optional().describe(`Label on the relationship`),technology:X().optional().describe(`Technology specified on the relationship`)}),mp=likec4Tool({name:`query-outgoers-graph`,description:`
1068
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:E().describe(`Target element id (FQN) to query incomers for`),includeIndirect:j().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:M().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:M().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Bf},outputSchema:{target:E().describe(`Target element id`),totalNodes:M().describe(`Total number of nodes in the graph`),maxDepth:M().describe(`Maximum depth reached`),truncated:j().describe(`True if result was truncated due to maxNodes limit`),nodes:C(E(),Lf.extend({incomers:A(sp).describe(`Incoming relationships with details`),depth:M().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);$t(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`incoming`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,incomers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),lp=O({elementId:E().describe(`ID of the outgoing element`),relationshipLabel:E().optional().describe(`Label on the relationship`),technology:E().optional().describe(`Technology specified on the relationship`)}),up=likec4Tool({name:`query-outgoers-graph`,description:`
1053
1069
  Query the complete graph of all elements that receive output from the target element (recursive outgoers/consumers).
1054
1070
 
1055
1071
  This tool performs a breadth-first traversal to discover all downstream dependencies - elements that directly or
@@ -1106,7 +1122,7 @@ Notes:
1106
1122
  Example:
1107
1123
  For an API service, this returns all clients, services, and systems that consume its output,
1108
1124
  plus all their consumers, recursively up to maxDepth levels.
1109
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:X().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:$d().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:Z().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:Z().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Gf},outputSchema:{target:X().describe(`Target element id`),totalNodes:Z().describe(`Total number of nodes in the graph`),maxDepth:Z().describe(`Maximum depth reached`),truncated:$d().describe(`True if result was truncated due to maxNodes limit`),nodes:rf(Uf.extend({outgoers:Q(pp).describe(`Outgoing relationships with details`),depth:Z().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);Qt(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`outgoing`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,outgoers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),hp=likec4Tool({name:`read-deployment`,description:`
1125
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:E().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:j().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:M().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:M().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Bf},outputSchema:{target:E().describe(`Target element id`),totalNodes:M().describe(`Total number of nodes in the graph`),maxDepth:M().describe(`Maximum depth reached`),truncated:j().describe(`True if result was truncated due to maxNodes limit`),nodes:C(E(),Lf.extend({outgoers:A(lp).describe(`Outgoing relationships with details`),depth:M().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);$t(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`outgoing`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,outgoers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),dp=likec4Tool({name:`read-deployment`,description:`
1110
1126
  Read details about a deployment node or a deployed instance in a LikeC4 project.
1111
1127
 
1112
1128
  What it does:
@@ -1171,7 +1187,7 @@ Example response (deployed instance):
1171
1187
  "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
1172
1188
  }
1173
1189
  }
1174
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:X().describe(`Deployment id (FQN)`),project:Gf},outputSchema:{type:of([`deployment-node`,`deployed-instance`]),id:X().describe(`Deployment id (FQN)`),kind:X().describe(`Deployment node kind, or element kind for deployed instances`),name:X(),title:X(),description:X().nullable(),technology:X().nullable(),tags:Q(X()),project:X(),metadata:rf(tf([X(),Q(X())])),links:Q($({title:X().nullable().describe(`Optional link title`),url:X().describe(`Link URL`),relative:X().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this deployment entity`),shape:X(),color:X(),children:Q(X()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:Kf.describe(`Views that include this deployment node`),instanceof:$({id:X().describe(`Element ID (FQN)`),title:X(),kind:X()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:Wf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);Qt(r,`Deployment entity "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{type:r.isInstance()?`deployed-instance`:`deployment-node`,id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:(r.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null})),shape:r.shape,color:r.color,children:r.isInstance()?[]:[...r.children()].map(e=>e.id),includedInViews:includedInViews(r.views()),instanceof:r.isInstance()?{id:r.element.id,title:r.element.title,kind:r.element.kind}:null,sourceLocation:i({deployment:r.id})}}),gp=likec4Tool({name:`read-element`,description:`
1190
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:E().describe(`Deployment id (FQN)`),project:Bf},outputSchema:{type:D([`deployment-node`,`deployed-instance`]),id:E().describe(`Deployment id (FQN)`),kind:E().describe(`Deployment node kind, or element kind for deployed instances`),name:E(),title:E(),description:E().nullable(),technology:E().nullable(),tags:A(E()),project:E(),metadata:C(E(),w([E(),A(E())])),links:zf.describe(`External links associated with this deployment entity`),shape:E(),color:E(),children:A(E()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:Vf.describe(`Views that include this deployment node`),instanceof:O({id:E().describe(`Element ID (FQN)`),title:E(),kind:E()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:Rf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);$t(r,`Deployment entity "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{type:r.isInstance()?`deployed-instance`:`deployment-node`,id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:serializeLinks(r),shape:r.shape,color:r.color,children:r.isInstance()?[]:[...r.children()].map(e=>e.id),includedInViews:includedInViews(r.views()),instanceof:r.isInstance()?{id:r.element.id,title:r.element.title,kind:r.element.kind}:null,sourceLocation:i({deployment:r.id})}}),fp=likec4Tool({name:`read-element`,description:`
1175
1191
  Read detailed information about a LikeC4 element.
1176
1192
 
1177
1193
  Request:
@@ -1258,7 +1274,7 @@ Example response:
1258
1274
  "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
1259
1275
  }
1260
1276
  }
1261
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:X().describe(`Element id (FQN)`),project:Gf},outputSchema:{id:X().describe(`Element id (FQN)`),kind:X().describe(`Element kind`),name:X().describe(`Element name`),title:X(),description:X().nullable(),technology:X().nullable(),tags:Q(X()),project:X(),metadata:rf(tf([X(),Q(X())])),links:Q($({title:X().nullable().describe(`Optional link title`),url:X().describe(`Link URL`),relative:X().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this element`),shape:X(),color:X(),children:Q(X()).describe(`Children of this element (Array of FQNs)`),defaultView:X().nullable().describe(`Name of the default view of this element`),includedInViews:Kf.describe(`Views that include this element`),relationships:$({incoming:Q($({source:$({id:X(),title:X(),kind:X()}).describe(`Source element of this relationship`),kind:X().nullable().describe(`Relationship kind`),target:X().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:X().nullable().describe(`Relationship title`),description:X().nullable().describe(`Relationship description`),technology:X().nullable().describe(`Relationship technology`),tags:Q(X()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:Q($({source:X().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:$({id:X(),title:X(),kind:X()}).describe(`Target element of this relationship`),kind:X().nullable().describe(`Relationship kind`),title:X().nullable().describe(`Relationship title`),description:X().nullable().describe(`Relationship description`),technology:X().nullable().describe(`Relationship technology`),tags:Q(X()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:Q(X()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:Wf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.id);Qt(r,`Element "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:(r.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null})),shape:r.shape,color:r.color,children:[...r.children()].map(e=>e.id),defaultView:r.defaultView?.id||null,includedInViews:includedInViews(r.views()),relationships:{incoming:[...r.incoming()].map(e=>({source:{id:e.source.id,title:e.source.title,kind:e.source.kind},kind:e.kind,target:e.target.id,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]})),outgoing:[...r.outgoing()].map(e=>({source:e.source.id,target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]}))},deployedInstances:[...r.deployments()].map(e=>e.id),sourceLocation:i({element:r.id})}}),_p=likec4Tool({name:`read-project-summary`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read project summary`},description:`
1277
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:E().describe(`Element id (FQN)`),project:Bf},outputSchema:{id:E().describe(`Element id (FQN)`),kind:E().describe(`Element kind`),name:E().describe(`Element name`),title:E(),description:E().nullable(),technology:E().nullable(),tags:A(E()),project:E(),metadata:C(E(),w([E(),A(E())])),links:zf,shape:E(),color:E(),children:A(E()).describe(`Children of this element (Array of FQNs)`),defaultView:E().nullable().describe(`Name of the default view of this element`),includedInViews:Vf.describe(`Views that include this element`),relationships:O({incoming:A(O({source:O({id:E(),title:E(),kind:E()}).describe(`Source element of this relationship`),kind:E().nullable().describe(`Relationship kind`),target:E().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:E().nullable().describe(`Relationship title`),description:E().nullable().describe(`Relationship description`),technology:E().nullable().describe(`Relationship technology`),tags:A(E()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:A(O({source:E().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:O({id:E(),title:E(),kind:E()}).describe(`Target element of this relationship`),kind:E().nullable().describe(`Relationship kind`),title:E().nullable().describe(`Relationship title`),description:E().nullable().describe(`Relationship description`),technology:E().nullable().describe(`Relationship technology`),tags:A(E()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:A(E()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:Rf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.id);$t(r,`Element "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:serializeLinks(r),shape:r.shape,color:r.color,children:[...r.children()].map(e=>e.id),defaultView:r.defaultView?.id||null,includedInViews:includedInViews(r.views()),relationships:{incoming:[...r.incoming()].map(e=>({source:{id:e.source.id,title:e.source.title,kind:e.source.kind},kind:e.kind,target:e.target.id,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]})),outgoing:[...r.outgoing()].map(e=>({source:e.source.id,target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]}))},deployedInstances:[...r.deployments()].map(e=>e.id),sourceLocation:i({element:r.id})}}),pp=likec4Tool({name:`read-project-summary`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read project summary`},description:`
1262
1278
  Request:
1263
1279
  - project: string (optional) — project id. Defaults to "default" if omitted.
1264
1280
 
@@ -1349,7 +1365,7 @@ Example response:
1349
1365
  }
1350
1366
  ]
1351
1367
  }
1352
- `,inputSchema:{project:Gf},outputSchema:{title:X(),folder:X(),sources:Q(X()),config:Hf.describe(`Project configuration`),specification:$({elementKinds:Q(X()),relationshipKinds:Q(X()),deploymentKinds:Q(X()),tags:Q(X()),metadataKeys:Q(X())}),elements:Q($({id:X(),kind:X(),title:X(),tags:Q(X())})).describe(`List of elements in the project`),deployments:Q(nf(`type`,[$({type:af(`deployment-node`),id:X().describe(`Node ID`),kind:X().describe(`Deployment node kind`),title:X().describe(`Node title`),tags:Q(X())}),$({type:af(`deployed-instance`),id:X().describe(`Node ID`),title:X().describe(`Node title`),tags:Q(X()),referencedElementId:X().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:Q($({id:X(),title:X(),type:of([`element`,`deployment`,`dynamic`])}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=await e.computedModel(n);return{title:r.title,folder:r.folder.fsPath,sources:r.documents?.map(e=>e.fsPath)??[],config:serializeConfig(r.config),specification:{elementKinds:et(i.specification.elements),relationshipKinds:et(i.specification.relationships),deploymentKinds:et(i.specification.deployments),tags:[...i.tags],metadataKeys:i.specification.metadataKeys??[]},elements:[...i.elements()].filter(e=>!e.imported).map(e=>({id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]})),deployments:[...i.deployment.elements()].map(e=>e.isInstance()?{type:`deployed-instance`,id:e.id,title:e.title,tags:[...e.tags],referencedElementId:e.element.id}:{type:`deployment-node`,id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]}),views:[...i.views()].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type}))}}),modelRef=e=>e.hasElement()?e.element.id:e.hasDeployment()?e.deployment.id:null,vp=nf(`type`,[$({type:af(`element`),id:X().describe(`Node ID`),elementId:X().describe(`Element ID (FQN)`),kind:X().describe(`Element kind`),title:X().describe(`Node title`),description:X().nullable(),technology:X().nullable(),children:Q(X()).describe(`Children nodes, array of node IDs`),shape:X().describe(`Rendered shape`),color:X().describe(`Rendered color`),tags:Q(X())}),$({type:af(`deployment-node`),id:X().describe(`Node ID`),deploymentId:X().describe(`Deployment entity ID (FQN)`),kind:X().describe(`Deployment kind`),title:X().describe(`Node title`),description:X().nullable(),technology:X().nullable(),children:Q(X()).describe(`Children nodes, array of node IDs`),shape:X().describe(`Rendered shape`),color:X().describe(`Rendered color`),tags:Q(X())}),$({type:af(`deployed-instance`),id:X().describe(`Node ID`),deploymentId:X().describe(`Deployment entity ID (FQN)`),title:X().describe(`Node title`),description:X().nullable(),technology:X().nullable(),referencedElement:$({id:X().describe(`Element ID (FQN)`),kind:X().describe(`Element kind`),title:X().describe(`Element title`)}),shape:X().describe(`Rendered shape`),color:X().describe(`Rendered color`),tags:Q(X())})]),yp=likec4Tool({name:`read-view`,description:`
1368
+ `,inputSchema:{project:Bf},outputSchema:{title:E(),folder:E(),sources:A(E()),config:Ff.describe(`Project configuration`),specification:O({elementKinds:A(E()),relationshipKinds:A(E()),deploymentKinds:A(E()),tags:A(E()),metadataKeys:A(E())}),elements:A(O({id:E(),kind:E(),title:E(),tags:A(E())})).describe(`List of elements in the project`),deployments:A(Le(`type`,[O({type:k(`deployment-node`),id:E().describe(`Node ID`),kind:E().describe(`Deployment node kind`),title:E().describe(`Node title`),tags:A(E())}),O({type:k(`deployed-instance`),id:E().describe(`Node ID`),title:E().describe(`Node title`),tags:A(E()),referencedElementId:E().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:A(O({id:E(),title:E(),type:D([`element`,`deployment`,`dynamic`])}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=await e.computedModel(n);return{title:r.title,folder:r.folder.fsPath,sources:r.documents?.map(e=>e.fsPath)??[],config:serializeConfig(r.config),specification:{elementKinds:Qe(i.specification.elements),relationshipKinds:Qe(i.specification.relationships),deploymentKinds:Qe(i.specification.deployments),tags:[...i.tags],metadataKeys:i.specification.metadataKeys??[]},elements:[...i.elements()].filter(e=>!e.imported).map(e=>({id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]})),deployments:[...i.deployment.elements()].map(e=>e.isInstance()?{type:`deployed-instance`,id:e.id,title:e.title,tags:[...e.tags],referencedElementId:e.element.id}:{type:`deployment-node`,id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]}),views:[...i.views()].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type}))}}),modelRef=e=>e.hasElement()?e.element.id:e.hasDeployment()?e.deployment.id:null,mp=Le(`type`,[O({type:k(`element`),id:E().describe(`Node ID`),elementId:E().describe(`Element ID (FQN)`),kind:E().describe(`Element kind`),title:E().describe(`Node title`),description:E().nullable(),technology:E().nullable(),children:A(E()).describe(`Children nodes, array of node IDs`),shape:E().describe(`Rendered shape`),color:E().describe(`Rendered color`),tags:A(E())}),O({type:k(`deployment-node`),id:E().describe(`Node ID`),deploymentId:E().describe(`Deployment entity ID (FQN)`),kind:E().describe(`Deployment kind`),title:E().describe(`Node title`),description:E().nullable(),technology:E().nullable(),children:A(E()).describe(`Children nodes, array of node IDs`),shape:E().describe(`Rendered shape`),color:E().describe(`Rendered color`),tags:A(E())}),O({type:k(`deployed-instance`),id:E().describe(`Node ID`),deploymentId:E().describe(`Deployment entity ID (FQN)`),title:E().describe(`Node title`),description:E().nullable(),technology:E().nullable(),referencedElement:O({id:E().describe(`Element ID (FQN)`),kind:E().describe(`Element kind`),title:E().describe(`Element title`)}),shape:E().describe(`Rendered shape`),color:E().describe(`Rendered color`),tags:A(E())})]),hp=likec4Tool({name:`read-view`,description:`
1353
1369
  Read detailed information about a LikeC4 view.
1354
1370
 
1355
1371
  Request:
@@ -1397,7 +1413,7 @@ Example response:
1397
1413
  "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 30, "character": 0 } }
1398
1414
  }
1399
1415
  }
1400
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:X().describe(`View id (name)`),project:Gf},outputSchema:{id:X(),type:of([`element`,`deployment`,`dynamic`]).describe(`View type`),title:X(),description:X().nullable(),tags:Q(X()),project:X(),nodes:Q(vp),edges:Q($({source:X().describe(`Source node`),target:X().describe(`Target node`),label:X().nullable(),description:X().nullable(),technology:X().nullable(),tags:Q(X())})).describe(`Edge represents relationship between nodes`),sourceLocation:Wf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=(await e.computedModel(n)).findView(t.viewId);if(!i)throw Error(`View with ID '${t.viewId}' not found in project ${r.id}`);let a=mkLocate(e,r.id);return{id:i.id,type:i.$view._type,title:i.title??i.id,description:i.description.text,tags:[...i.tags],project:r.id,nodes:[...i.nodes()].flatMap(e=>{let t={id:e.id,title:e.title,description:e.description.text,technology:e.technology,shape:e.shape,color:e.color,tags:[...e.tags]};return e.hasDeployedInstance()?{...t,type:`deployed-instance`,deploymentId:e.deployment.id,referencedElement:{id:e.deployment.element.id,kind:e.deployment.element.kind,title:e.deployment.element.title}}:e.hasDeployment()?{...t,type:`deployment-node`,kind:e.deployment.kind,deploymentId:e.deployment.id,children:[...e.children()].map(e=>e.id)}:e.hasElement()?{...t,type:`element`,elementId:e.element.id,kind:e.element.kind,children:[...e.children()].flatMap(e=>modelRef(e)??[])}:[]}),edges:[...i.edges()].map(e=>({source:e.source.id,target:e.target.id,label:e.label,description:e.description.text,technology:e.technology,tags:[...e.tags]})),sourceLocation:a({view:i.id})}}),bp=Q(nf(`type`,[$({type:af(`element`),project:X().describe(`Project ID`),id:X().describe(`Element ID (FQN)`),name:X().describe(`Element name`),kind:X(),title:X(),technology:X().nullable(),shape:X(),includedInViews:Kf,metadata:rf(tf([X(),Q(X())])),tags:Q(X())}),$({type:af(`deployment-node`),project:X().describe(`Project ID`),id:X().describe(`Deployment ID (FQN)`),name:X().describe(`Deployment name`),kind:X(),title:X(),technology:X().nullable(),shape:X(),includedInViews:Kf,metadata:rf(tf([X(),Q(X())])),tags:Q(X())})])),xp=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`
1416
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:E().describe(`View id (name)`),project:Bf},outputSchema:{id:E(),type:D([`element`,`deployment`,`dynamic`]).describe(`View type`),title:E(),description:E().nullable(),tags:A(E()),project:E(),nodes:A(mp),edges:A(O({source:E().describe(`Source node`),target:E().describe(`Target node`),label:E().nullable(),description:E().nullable(),technology:E().nullable(),tags:A(E())})).describe(`Edge represents relationship between nodes`),sourceLocation:Rf}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=(await e.computedModel(n)).findView(t.viewId);if(!i)throw Error(`View with ID '${t.viewId}' not found in project ${r.id}`);let a=mkLocate(e,r.id);return{id:i.id,type:i.$view._type,title:i.title??i.id,description:i.description.text,tags:[...i.tags],project:r.id,nodes:[...i.nodes()].flatMap(e=>{let t={id:e.id,title:e.title,description:e.description.text,technology:e.technology,shape:e.shape,color:e.color,tags:[...e.tags]};return e.hasDeployedInstance()?{...t,type:`deployed-instance`,deploymentId:e.deployment.id,referencedElement:{id:e.deployment.element.id,kind:e.deployment.element.kind,title:e.deployment.element.title}}:e.hasDeployment()?{...t,type:`deployment-node`,kind:e.deployment.kind,deploymentId:e.deployment.id,children:[...e.children()].map(e=>e.id)}:e.hasElement()?{...t,type:`element`,elementId:e.element.id,kind:e.element.kind,children:[...e.children()].flatMap(e=>modelRef(e)??[])}:[]}),edges:[...i.edges()].map(e=>({source:e.source.id,target:e.target.id,label:e.label,description:e.description.text,technology:e.technology,tags:[...e.tags]})),sourceLocation:a({view:i.id})}}),gp=A(Le(`type`,[O({type:k(`element`),project:E().describe(`Project ID`),id:E().describe(`Element ID (FQN)`),name:E().describe(`Element name`),kind:E(),title:E(),technology:E().nullable(),shape:E(),includedInViews:Vf,metadata:C(E(),w([E(),A(E())])),tags:A(E())}),O({type:k(`deployment-node`),project:E().describe(`Project ID`),id:E().describe(`Deployment ID (FQN)`),name:E().describe(`Deployment name`),kind:E(),title:E(),technology:E().nullable(),shape:E(),includedInViews:Vf,metadata:C(E(),w([E(),A(E())])),tags:A(E())})])),_p=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`
1401
1417
  Search LikeC4 elements and deployment nodes across all projects.
1402
1418
 
1403
1419
  Query syntax (case-insensitive):
@@ -1452,7 +1468,7 @@ Example response:
1452
1468
  }
1453
1469
  ]
1454
1470
  }
1455
- `,inputSchema:{search:X().min(2,`Search must be at least 2 characters long`)},outputSchema:{total:Z(),found:bp}})(async(e,t)=>{let n=e.projects(),r=[],i=t.search.toLowerCase(),predicate;i.startsWith(`kind:`)?(i=i.slice(5),U.debug(`search by kind: {search}`,{search:i}),predicate=e=>e.kind.toLowerCase()===i):i.startsWith(`shape:`)?(i=i.slice(6),U.debug(`search by shape: {search}`,{search:i}),predicate=e=>e.shape.toLowerCase()===i):i.startsWith(`meta:`)?(i=i.slice(5),U.debug(`search by metadata: {search}`,{search:i}),predicate=e=>!!e.getMetadata(i)):i.startsWith(`#`)?(i=i.slice(1),U.debug(`search by tag: {search}`,{search:i}),predicate=e=>e.tags.some(e=>e.toLowerCase().includes(i))):(U.debug(`search by id/title: {search}`,{search:i}),predicate=e=>e.id.toLowerCase().includes(i)||e.title.toLowerCase().includes(i));for(let t of n)try{let n=await e.computedModel(t.id);for(let e of tn(n.elements(),e=>!e.imported&&predicate(e)))r.push({type:`element`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())});for(let e of tn(n.deployment.nodes(),predicate))r.push({type:`deployment-node`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())})}catch(e){U.error(`Error searching in project ${t.id}:`,{error:e})}return{total:r.length,found:r.slice(0,20)}}),Sp=$({id:X().describe(`Element id (FQN)`),name:X().describe(`Element name`),kind:X().describe(`Element kind`),title:X().describe(`Human-readable title`),depth:Z().describe(`Depth relative to the root element (1 = direct child)`),tags:Q(X()).describe(`Assigned tags`),metadata:rf(tf([X(),Q(X())])).describe(`Element metadata`),childCount:Z().describe(`Number of direct children`),incomingCount:Z().describe(`Number of incoming relationships`),outgoingCount:Z().describe(`Number of outgoing relationships`)}),Cp=likec4Tool({name:`subgraph-summary`,description:`
1471
+ `,inputSchema:{search:E().min(2,`Search must be at least 2 characters long`)},outputSchema:{total:M(),found:gp}})(async(e,t)=>{let n=e.projects(),r=[],i=t.search.toLowerCase(),predicate;i.startsWith(`kind:`)?(i=i.slice(5),q.debug(`search by kind: {search}`,{search:i}),predicate=e=>e.kind.toLowerCase()===i):i.startsWith(`shape:`)?(i=i.slice(6),q.debug(`search by shape: {search}`,{search:i}),predicate=e=>e.shape.toLowerCase()===i):i.startsWith(`meta:`)?(i=i.slice(5),q.debug(`search by metadata: {search}`,{search:i}),predicate=e=>!!e.getMetadata(i)):i.startsWith(`#`)?(i=i.slice(1),q.debug(`search by tag: {search}`,{search:i}),predicate=e=>e.tags.some(e=>e.toLowerCase().includes(i))):(q.debug(`search by id/title: {search}`,{search:i}),predicate=e=>e.id.toLowerCase().includes(i)||e.title.toLowerCase().includes(i));for(let t of n)try{let n=await e.computedModel(t.id);for(let e of nn(n.elements(),e=>!e.imported&&predicate(e)))r.push({type:`element`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())});for(let e of nn(n.deployment.nodes(),predicate))r.push({type:`deployment-node`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())})}catch(e){q.error(`Error searching in project ${t.id}:`,{error:e})}return{total:r.length,found:r.slice(0,20)}}),vp=O({id:E().describe(`Element id (FQN)`),name:E().describe(`Element name`),kind:E().describe(`Element kind`),title:E().describe(`Human-readable title`),depth:M().describe(`Depth relative to the root element (1 = direct child)`),tags:A(E()).describe(`Assigned tags`),metadata:C(E(),w([E(),A(E())])).describe(`Element metadata`),childCount:M().describe(`Number of direct children`),incomingCount:M().describe(`Number of incoming relationships`),outgoingCount:M().describe(`Number of outgoing relationships`)}),yp=likec4Tool({name:`subgraph-summary`,description:`
1456
1472
  Get a compact, table-friendly summary of all descendants of a parent element.
1457
1473
  Returns each descendant with its depth, metadata, tags, and relationship counts in a single call.
1458
1474
  Much more efficient than calling read-element for each descendant individually.
@@ -1518,7 +1534,7 @@ Example response:
1518
1534
  "truncated": false,
1519
1535
  "truncatedByDepth": false
1520
1536
  }
1521
- `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:X().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:Z().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:Q(X()).optional().describe(`If provided, only include these metadata keys in the response`),project:Gf},outputSchema:{root:$({id:X(),kind:X(),title:X(),childCount:Z()}),descendants:Q(Sp),totalDescendants:Z().describe(`Total number of descendants found`),truncated:$d().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:$d().describe(`True if deeper descendants exist beyond maxDepth`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);Qt(r,`Element "${t.elementId}" not found in project "${n}"`);let i=t.maxDepth,a=t.metadataKeys,s=[],c=0,l=!1,u=!1,f=[],p=[...r.children()];for(let e of p)f.push({element:e,depth:1});for(;f.length>0;){let{element:e,depth:t}=f.shift();if(t>i){u=!0;continue}c++;let n=[...e.children()];if(s.length<200){let r=e.getMetadata(),i=a?Object.fromEntries(a.filter(e=>e in r).map(e=>[e,r[e]])):r;s.push({id:e.id,name:e.name,kind:e.kind,title:e.title,depth:t,tags:[...e.tags],metadata:i,childCount:n.length,incomingCount:[...e.incoming()].length,outgoingCount:[...e.outgoing()].length})}else l=!0;for(let e of n)f.push({element:e,depth:t+1})}return{root:{id:r.id,kind:r.kind,title:r.title,childCount:p.length},descendants:s,totalDescendants:c,truncated:l,truncatedByDepth:u}});function createMCPServer(e){let t=new McpServer({name:`LikeC4`,version:Tf},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
1537
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:E().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:M().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:A(E()).optional().describe(`If provided, only include these metadata keys in the response`),project:Bf},outputSchema:{root:O({id:E(),kind:E(),title:E(),childCount:M()}),descendants:A(vp),totalDescendants:M().describe(`Total number of descendants found`),truncated:j().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:j().describe(`True if deeper descendants exist beyond maxDepth`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);$t(r,`Element "${t.elementId}" not found in project "${n}"`);let i=t.maxDepth,a=t.metadataKeys,s=[],c=0,l=!1,u=!1,f=[],p=[...r.children()];for(let e of p)f.push({element:e,depth:1});for(;f.length>0;){let{element:e,depth:t}=f.shift();if(t>i){u=!0;continue}c++;let n=[...e.children()];if(s.length<200){let r=e.getMetadata(),i=a?Object.fromEntries(a.filter(e=>e in r).map(e=>[e,r[e]])):r;s.push({id:e.id,name:e.name,kind:e.kind,title:e.title,depth:t,tags:[...e.tags],metadata:i,childCount:n.length,incomingCount:[...e.incoming()].length,outgoingCount:[...e.outgoing()].length})}else l=!0;for(let e of n)f.push({element:e,depth:t+1})}return{root:{id:r.id,kind:r.kind,title:r.title,childCount:p.length},descendants:s,totalDescendants:c,truncated:l,truncatedByDepth:u}});function createMCPServer(e){let t=new McpServer({name:`LikeC4`,version:yf},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
1522
1538
 
1523
1539
  Conventions:
1524
1540
  - All tools are read-only and idempotent.
@@ -1540,7 +1556,7 @@ Available tools:
1540
1556
  - query-by-metadata — Search elements by metadata key-value pairs with exact/contains/exists matching. Input: { key, value?, matchMode?, project? }.
1541
1557
  - query-by-tags — Advanced tag filtering with boolean logic (allOf, anyOf, noneOf). Input: { allOf?, anyOf?, noneOf?, project? }.
1542
1558
  - find-relationship-paths — Discover all paths (chains of relationships) between two elements with BFS traversal. Input: { sourceId, targetId, maxDepth?, includeIndirect?, project? }.
1543
- - batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Input: { ids, project? }.
1559
+ - batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Includes links and sourceLocation, same as read-element. Input: { ids, project? }.
1544
1560
  - query-by-tag-pattern — Search elements by tag prefix/contains/suffix patterns. Input: { pattern, matchMode?, project? }.
1545
1561
  - element-diff — Compare two elements side-by-side showing differences in properties, tags, metadata, and relationships. Input: { element1Id, element2Id, project? }.
1546
1562
  - subgraph-summary — Compact summary of all descendants of a parent element with metadata, tags, and relationship counts. Input: { elementId, maxDepth?, metadataKeys?, project? }.
@@ -1553,21 +1569,21 @@ Instructions:
1553
1569
  - If response returns "sourceLocation", provide link to this location in the editor
1554
1570
 
1555
1571
  Full documentation: https://likec4.dev/llms-full.txt
1556
- `,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{s.error(a(e))},ft(t,setMcpServerCtx,rp,_p,gp,hp,yp,xp,np,$f,at(up,fp,mp,op,cp,sp),at(Yf,Qf,Cp),at(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),at(projectResource,renderViewResource))}var StdioLikeC4MCPServer=class{services;options;transport=void 0;_mcp=void 0;constructor(e,t={}){this.services=e,this.options=t}get mcp(){if(!this._mcp)throw Error(`MCP server is not started`);return this._mcp}get isStarted(){return this.transport!==void 0}get port(){return NaN}async dispose(){await this.stop()}async start(){if(!this.transport){U.info(`Starting MCP stdio server`),this._mcp=createMCPServer(this.services),setMcpServerCtx(this._mcp),this.transport=new StdioServerTransport(this.options.stdin,this.options.stdout);try{await this._mcp.connect(this.transport)}catch(e){throw await this.stop(),e}U.info(`LikeC4 MCP Server running on stdio`)}}async stop(){if(this.transport)try{U.info(`Stopping MCP stdio server`),await this.transport.close(),this._mcp&&await this._mcp.close()}finally{this._mcp=void 0,this.transport=void 0,setMcpServerCtx(void 0)}}},OAuthError=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},InvalidRequestError=class extends OAuthError{};InvalidRequestError.errorCode=`invalid_request`;var InvalidClientError=class extends OAuthError{};InvalidClientError.errorCode=`invalid_client`;var InvalidGrantError=class extends OAuthError{};InvalidGrantError.errorCode=`invalid_grant`;var UnauthorizedClientError=class extends OAuthError{};UnauthorizedClientError.errorCode=`unauthorized_client`;var UnsupportedGrantTypeError=class extends OAuthError{};UnsupportedGrantTypeError.errorCode=`unsupported_grant_type`;var InvalidScopeError=class extends OAuthError{};InvalidScopeError.errorCode=`invalid_scope`;var AccessDeniedError=class extends OAuthError{};AccessDeniedError.errorCode=`access_denied`;var ServerError=class extends OAuthError{};ServerError.errorCode=`server_error`;var TemporarilyUnavailableError=class extends OAuthError{};TemporarilyUnavailableError.errorCode=`temporarily_unavailable`;var UnsupportedResponseTypeError=class extends OAuthError{};UnsupportedResponseTypeError.errorCode=`unsupported_response_type`;var UnsupportedTokenTypeError=class extends OAuthError{};UnsupportedTokenTypeError.errorCode=`unsupported_token_type`;var InvalidTokenError=class extends OAuthError{};InvalidTokenError.errorCode=`invalid_token`;var MethodNotAllowedError=class extends OAuthError{};MethodNotAllowedError.errorCode=`method_not_allowed`;var TooManyRequestsError=class extends OAuthError{};TooManyRequestsError.errorCode=`too_many_requests`;var InvalidClientMetadataError=class extends OAuthError{};InvalidClientMetadataError.errorCode=`invalid_client_metadata`;var InsufficientScopeError=class extends OAuthError{};InsufficientScopeError.errorCode=`insufficient_scope`;var InvalidTargetError=class extends OAuthError{};InvalidTargetError.errorCode=`invalid_target`,InvalidRequestError.errorCode,InvalidClientError.errorCode,InvalidGrantError.errorCode,UnauthorizedClientError.errorCode,UnsupportedGrantTypeError.errorCode,InvalidScopeError.errorCode,AccessDeniedError.errorCode,ServerError.errorCode,TemporarilyUnavailableError.errorCode,UnsupportedResponseTypeError.errorCode,UnsupportedTokenTypeError.errorCode,InvalidTokenError.errorCode,MethodNotAllowedError.errorCode,TooManyRequestsError.errorCode,InvalidClientMetadataError.errorCode,InsufficientScopeError.errorCode,InvalidTargetError.errorCode;var compose=(e,t,n)=>(r,i)=>{let a=-1;return dispatch(0);async function dispatch(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>dispatch(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},HTTPException=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},wp=Symbol(),bufferToFormData=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Tp=32,Ep=1e4,isRawRequest=e=>`headers`in e,parseBody=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(isRawRequest(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?parseFormData(e,{all:n,dot:r}):{}};async function parseFormData(e,t){if(!isRawRequest(e)&&e.bodyCache.formData)return convertFormDataToBodyData(await e.bodyCache.formData,t);let n=isRawRequest(e)?e.headers:e.raw.headers,r=bufferToFormData(await e.arrayBuffer(),n.get(`Content-Type`)||``);isRawRequest(e)||(e.bodyCache.formData=r);let i=await r;return i?convertFormDataToBodyData(i,t):{}}function convertFormDataToBodyData(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?handleParsingAllValues(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(handleParsingNestedValues(n,e,t,r),delete n[e])}),n}var handleParsingAllValues=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},handleParsingNestedValues=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Tp+2);a.length>Tp+1&&throwNestingLimitExceeded(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=Ep&&throwNestingLimitExceeded(),i[e]=Object.create(null)),i=i[e])})},throwNestingLimitExceeded=()=>{throw Error(`Nesting limit exceeded`)},splitPath=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},splitRoutingPath=e=>{let{groups:t,path:n}=extractGroupsFromPath(e);return replaceGroupMarks(splitPath(n),t)},extractGroupsFromPath=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},replaceGroupMarks=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},Dp={},getPattern=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return Dp[r]||(Dp[r]=n[2]?t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:[e,n[1],!0]),Dp[r]}return null},tryDecode=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},tryDecodeURI=e=>tryDecode(e,decodeURI),getPath=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),s=t.slice(n,a);return tryDecodeURI(s.includes(`%25`)?s.replace(/%25/g,`%2525`):s)}if(e===63||e===35)break}return t.slice(n,r)},getPathNoStrict=e=>{let t=getPath(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},mergePath=(e,t,...n)=>(n.length&&(t=mergePath(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),checkOptionalParameter=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e)){if(e.charCodeAt(e.length-1)===63){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.slice(0,-1);r+=`/`+t,n.push(r)}else r+=`/`+e}}),n.filter((e,t,n)=>n.indexOf(e)===t)},tryDecodeURIComponent=e=>e.indexOf(`%`)===-1?e:tryDecode(e,kp),_decodeURI=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),tryDecodeURIComponent(e)),_getQueryParam=(e,t,n)=>{let r=e.indexOf(`#`,8);r!==-1&&(e=e.slice(0,r));let i;if(!n&&t&&t.indexOf(`%`)===-1&&t.indexOf(`+`)===-1){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return _decodeURI(e.slice(r,i===-1?void 0:i))}if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(i=/[%+]/.test(e),!i)return}let a=Object.create(null);i??=/[%+]/.test(e);let s=e.indexOf(`?`,8);for(;s!==-1;){let t=e.indexOf(`&`,s+1),r=e.indexOf(`=`,s);r>t&&t!==-1&&(r=-1);let c=e.slice(s+1,r===-1?t===-1?void 0:t:r);if(i&&(c=_decodeURI(c)),s=t,c===``)continue;let l;r===-1?l=``:(l=e.slice(r+1,t===-1?void 0:t),i&&(l=_decodeURI(l))),n?(a[c]&&Array.isArray(a[c])||(a[c]=[]),a[c].push(l)):a[c]??=l}return t?a[t]:a},Op=_getQueryParam,getQueryParams=(e,t)=>_getQueryParam(e,t,!0),kp=decodeURIComponent,HonoRequest=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&tryDecodeURIComponent(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=tryDecodeURIComponent(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Op(this.url,e)}queries(e){return getQueryParams(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return parseBody(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let n in t)return t[n].then(t=>(n===`json`&&(t=JSON.stringify(t)),new Response(t)[e]()));return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[wp](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Ap={Stringify:1,BeforeStream:2,Stream:3},raw=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},resolveCallback=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let s=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>resolveCallback(e,t,!1,r,i))).then(()=>i[0]));return n?raw(await s,a):s},jp=`text/plain; charset=UTF-8`,setDefaultContentType=(e,t)=>({"Content-Type":e,...t}),createResponseInstance=(e,t)=>new Response(e,t),Context=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new HonoRequest(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=createResponseInstance(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=createResponseInstance(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=createResponseInstance(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return createResponseInstance(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,setDefaultContentType(jp,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,setDefaultContentType(`application/json`,n));html=(e,t,n)=>{let res=e=>this.#f(e,t,setDefaultContentType(`text/html; charset=UTF-8`,n));return typeof e==`object`?resolveCallback(e,Ap.Stringify,!1,{}).then(res):res(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>createResponseInstance(),this.#c(this))},Mp=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],Np=`Can not add a route since the matcher is already built.`,UnsupportedPathError=class extends Error{},Pp=`__COMPOSED_HANDLER`,notFoundHandler=e=>e.text(`404 Not Found`,404),errorHandler=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Fp=class _Hono{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...Mp,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??getPath:getPathNoStrict}#t(){let e=new _Hono({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=notFoundHandler;errorHandler=errorHandler;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let handler;t.errorHandler===errorHandler?handler=e.handler:(handler=async(n,r)=>(await compose([],t.errorHandler)(n,()=>e.handler(n,r))).res,handler[Pp]=e.handler),n.#r(e.method,e.path,handler,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=mergePath(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=mergePath(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})();let handler=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#r(`ALL`,mergePath(e,`*`),handler),this}#r(e,t,n,r){e=e.toUpperCase(),t=mergePath(this._basePath,t);let i={basePath:r===void 0?this._basePath:mergePath(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),s=new Context(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(e){return this.#i(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#n(s))).catch(e=>this.#i(e,s)):e??this.#n(s)}let c=compose(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,s)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${mergePath(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},createNullObject=()=>Object.create(null),Ip=[];function match(e,t){let n=this.buildAllMatchers(),match2=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Ip];let s=a.indexOf(``,1);return[r[1][s],a]});return this.match=match2,match2(e,t)}var Lp=`[^/]+`,Rp=`(?:|/.*)`,zp=Symbol(),Bp=new Set(`.\\+*[^]$()`);function compareKey(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Vp=class _Node{#e;#t;#n=createNullObject();insert(e,t,n,r,i){let a=this;for(let t=0,i=e.length;t<i;t++){let s=e[t],c=s.length===1?s===`*`?t===i-1?[``,``,`.*`]:[``,``,Lp]:null:s===`/*`?[``,``,Rp]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let e=c[1],t=c[2]||`[^/]+`;if(e&&c[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))||t.length===1&&Bp.has(t)))throw zp;if(l=a.#n[t],!l){if(t!==`.*`&&t!==`(?:|/.*)`){for(let e in a.#n)if((t.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw zp}l=a.#n[t]=new _Node}e!==``&&(l.#t??=r.varIndex++,n.push([e,l.#t]))}else if(l=a.#n[s],!l){for(let e in a.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw zp;l=a.#n[s]=new _Node}a=l}if(a.#e!==void 0)throw zp;a.#e=i?-1:t}buildRegExpStr(){let e=Object.keys(this.#n).sort(compareKey).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Bp.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Trie=class{#e={varIndex:0};#t=new Vp;#n=0;paths=createNullObject();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Hp=createNullObject();function buildWildcardRegExp(e){return Hp[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Rp:e===`*`?`.*`:`/:${Lp}`)}$`)}function findMiddleware(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(buildWildcardRegExp(n).test(t))return[...e[n]]}var RegExpRouter=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:createNullObject()},this.#t={ALL:createNullObject()},this.#n={ALL:new Trie}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===zp?new UnsupportedPathError(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(Np);if(!r[e]){this.#n[e]=new Trie;for(let t of[r,i]){t[e]=createNullObject();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=buildWildcardRegExp(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=findMiddleware(r[e],t)||findMiddleware(r.ALL,t)||[]);for(let s of[r,i])for(let r of a)for(let i in s[r])e.test(i)&&s[r][i].push([n,t]);return}let s=checkOptionalParameter(t)||[t];for(let e of s)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=findMiddleware(r[t],e)||findMiddleware(r.ALL,e)||[]),i[t][e].push([n,e])}match=match;buildAllMatchers(){let e=createNullObject();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Hp=createNullObject(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=createNullObject(),a=[],[s,c,l]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],s=r.paths[t];if(!s){i[t]=[n.map(([e])=>[e,createNullObject()]),Ip];continue}a[s[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=l[s[1][n][1]],e),createNullObject())])}return[s,c.map(e=>a[e]),i]}},SmartRouter=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(Np);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,s;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);s=i.match(e,t)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},Up=createNullObject(),Wp=0,Gp=class _Node{#e=[];#t=createNullObject();#n=[];#r;#i=Up;insert(e,t,n){let r=this,i=splitRoutingPath(t),a=new Set,s=0;for(let e of i){let t=i[++s],n=getPattern(e,t)||(t===void 0&&e&&e.indexOf(`*`)===e.length-1?e:null),c=Array.isArray(n),l=c?n[0]:n||e,u=r.#t[l]||=new _Node;n&&!u.#r&&(u.#r=n,r.#n.push(u)),r=u,c&&a.add(n[1])}r.#e.push({[e]:{handler:n,possibleKeys:[...a],score:++Wp}})}#a(e,t,n,r,i){for(let a=0,s=t.#e.length;a<s;a++){let s=t.#e[a],c=s[n]||s.ALL;if(c){c.params=createNullObject(),e.push(c);for(let e=0,t=c.possibleKeys.length;e<t;e++){let t=c.possibleKeys[e];c.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=Up;let r=[this],i=splitPath(t),a=[],s=i.length,c=null;for(let l=0;l<s;l++){let u=i[l],f=l===s-1,p=[];for(let m=0,h=r.length;m<h;m++){let h=r[m],g=h.#t[u];g&&(g.#i=h.#i,f?(g.#t[`*`]&&this.#a(n,g.#t[`*`],e,h.#i),this.#a(n,g,e,h.#i)):p.push(g));for(let r of h.#n){let m=r.#r,g=h.#i===Up?{}:{...h.#i};if(typeof m==`string`){(m===`*`||u.startsWith(m.slice(0,-1)))&&(this.#a(n,r,e,h.#i),m===`*`&&(r.#i=g,p.push(r)));continue}let[,v,y]=m;if(!(!u&&y===!0)){if(y!==!0){if(!c){c=[];let e=+(t[0]===`/`);for(let t=0;t<s;t++)c[t]=e,e+=i[t].length+1}let u=t.slice(c[l]),f=y.exec(u);if(f){g[v]=f[0],this.#a(n,r,e,h.#i,g),f[0].length===u.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,h.#i,g);for(let e in r.#t){r.#i=g;let e=f[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(y===!0||y.test(u))&&(g[v]=u,f?(this.#a(n,r,e,g,h.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,g,h.#i)):(r.#i=g,p.push(r)))}}}let m=a.shift();r=m?p.concat(m):p}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},TrieRouter=class{name=`TrieRouter`;#e=new Gp;add(e,t,n){for(let r of checkOptionalParameter(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},Hono=class extends Fp{constructor(e={}){super(e),this.router=e.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}},cors=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function cors2(e,s){function set(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&set(`Access-Control-Allow-Origin`,c),t.credentials&&set(`Access-Control-Allow-Credentials`,`true`),n&&set(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&set(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&set(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(set(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await s(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};const Kp=He().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ke.custom,message:`URL must be parseable`,fatal:!0}),Pe}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`});Fe({resource:T().url(),authorization_servers:O(Kp).optional(),jwks_uri:T().url().optional(),scopes_supported:O(T()).optional(),bearer_methods_supported:O(T()).optional(),resource_signing_alg_values_supported:O(T()).optional(),resource_name:T().optional(),resource_documentation:T().optional(),resource_policy_uri:T().url().optional(),resource_tos_uri:T().url().optional(),tls_client_certificate_bound_access_tokens:k().optional(),authorization_details_types_supported:O(T()).optional(),dpop_signing_alg_values_supported:O(T()).optional(),dpop_bound_access_tokens_required:k().optional()});const qp=Fe({issuer:T(),authorization_endpoint:Kp,token_endpoint:Kp,registration_endpoint:Kp.optional(),scopes_supported:O(T()).optional(),response_types_supported:O(T()),response_modes_supported:O(T()).optional(),grant_types_supported:O(T()).optional(),token_endpoint_auth_methods_supported:O(T()).optional(),token_endpoint_auth_signing_alg_values_supported:O(T()).optional(),service_documentation:Kp.optional(),revocation_endpoint:Kp.optional(),revocation_endpoint_auth_methods_supported:O(T()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O(T()).optional(),introspection_endpoint:T().optional(),introspection_endpoint_auth_methods_supported:O(T()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O(T()).optional(),code_challenge_methods_supported:O(T()).optional(),client_id_metadata_document_supported:k().optional()}),Jp=Fe({issuer:T(),authorization_endpoint:Kp,token_endpoint:Kp,userinfo_endpoint:Kp.optional(),jwks_uri:Kp,registration_endpoint:Kp.optional(),scopes_supported:O(T()).optional(),response_types_supported:O(T()),response_modes_supported:O(T()).optional(),grant_types_supported:O(T()).optional(),acr_values_supported:O(T()).optional(),subject_types_supported:O(T()),id_token_signing_alg_values_supported:O(T()),id_token_encryption_alg_values_supported:O(T()).optional(),id_token_encryption_enc_values_supported:O(T()).optional(),userinfo_signing_alg_values_supported:O(T()).optional(),userinfo_encryption_alg_values_supported:O(T()).optional(),userinfo_encryption_enc_values_supported:O(T()).optional(),request_object_signing_alg_values_supported:O(T()).optional(),request_object_encryption_alg_values_supported:O(T()).optional(),request_object_encryption_enc_values_supported:O(T()).optional(),token_endpoint_auth_methods_supported:O(T()).optional(),token_endpoint_auth_signing_alg_values_supported:O(T()).optional(),display_values_supported:O(T()).optional(),claim_types_supported:O(T()).optional(),claims_supported:O(T()).optional(),service_documentation:T().optional(),claims_locales_supported:O(T()).optional(),ui_locales_supported:O(T()).optional(),claims_parameter_supported:k().optional(),request_parameter_supported:k().optional(),request_uri_parameter_supported:k().optional(),require_request_uri_registration:k().optional(),op_policy_uri:Kp.optional(),op_tos_uri:Kp.optional(),client_id_metadata_document_supported:k().optional()});E({...Jp.shape,...qp.pick({code_challenge_methods_supported:!0}).shape}),E({access_token:T(),id_token:T().optional(),token_type:T(),expires_in:We().optional(),scope:T().optional(),refresh_token:T().optional()}).strip(),E({error:T(),error_description:T().optional(),error_uri:T().optional()});const Yp=Kp.optional().or(D(``).transform(()=>void 0)),Xp=E({redirect_uris:O(Kp),token_endpoint_auth_method:T().optional(),grant_types:O(T()).optional(),response_types:O(T()).optional(),client_name:T().optional(),client_uri:Kp.optional(),logo_uri:Yp,scope:T().optional(),contacts:O(T()).optional(),tos_uri:Yp,policy_uri:T().optional(),jwks_uri:Kp.optional(),jwks:Le().optional(),software_id:T().optional(),software_version:T().optional(),software_statement:T().optional()}).strip(),Zp=E({client_id:T(),client_secret:T().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip();Xp.merge(Zp),E({error:T(),error_description:T().optional()}).strip(),E({token:T(),token_type_hint:T().optional()}).strip(),globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto),E({client_id:T(),redirect_uri:T().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),E({response_type:D(`code`),code_challenge:T(),code_challenge_method:D(`S256`),scope:T().optional(),state:T().optional(),resource:He().optional()}),E({grant_type:T()}),E({code:T(),code_verifier:T(),redirect_uri:T().optional(),resource:He().optional()}),E({refresh_token:T(),scope:T().optional(),resource:He().optional()}),E({client_id:T(),client_secret:T().optional()});var StreamingApi=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let n=t.getReader();this.abortSubscribers.push(async()=>{await n.cancel()}),this.responseReadable=new ReadableStream({async pull(e){let{done:t,value:r}=await n.read();t?e.close():e.enqueue(r)},cancel:()=>{this.closed||this.abort()}})}async write(e){try{typeof e==`string`&&(e=this.encoder.encode(e)),await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
1557
- `),this}sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0;try{await this.writer.close()}catch{}}async pipe(e){this.writer.releaseLock();try{await e.pipeTo(this.writable,{preventClose:!0,preventAbort:!0})}finally{this.writer=this.writable.getWriter()}}onAbort(e){this.abortSubscribers.push(e)}abort(){this.aborted||(this.aborted=!0,this.abortSubscribers.forEach(e=>{try{Promise.resolve(e()).catch(()=>{})}catch{}}))}},SSEStreamingApi=class extends StreamingApi{constructor(e,t){super(e,t)}async writeSSE(e){let t=(await resolveCallback(e.data,Ap.Stringify,!1,{})).split(/\r\n|\r|\n/).map(e=>`data: ${e}`).join(`
1572
+ `,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{s.error(a(e))},ut(t,setMcpServerCtx,$f,pp,fp,dp,hp,_p,Qf,Yf,rt(op,cp,up,np,ip,rp),rt(Gf,Jf,yp),rt(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),rt(projectResource,renderViewResource))}var StdioLikeC4MCPServer=class{services;options;transport=void 0;_mcp=void 0;constructor(e,t={}){this.services=e,this.options=t}get mcp(){if(!this._mcp)throw Error(`MCP server is not started`);return this._mcp}get isStarted(){return this.transport!==void 0}get port(){return NaN}async dispose(){await this.stop()}async start(){if(!this.transport){q.info(`Starting MCP stdio server`),this._mcp=createMCPServer(this.services),setMcpServerCtx(this._mcp),this.transport=new StdioServerTransport(this.options.stdin,this.options.stdout);try{await this._mcp.connect(this.transport)}catch(e){throw await this.stop(),e}q.info(`LikeC4 MCP Server running on stdio`)}}async stop(){if(this.transport)try{q.info(`Stopping MCP stdio server`),await this.transport.close(),this._mcp&&await this._mcp.close()}finally{this._mcp=void 0,this.transport=void 0,setMcpServerCtx(void 0)}}},OAuthError=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},InvalidRequestError=class extends OAuthError{};InvalidRequestError.errorCode=`invalid_request`;var InvalidClientError=class extends OAuthError{};InvalidClientError.errorCode=`invalid_client`;var InvalidGrantError=class extends OAuthError{};InvalidGrantError.errorCode=`invalid_grant`;var UnauthorizedClientError=class extends OAuthError{};UnauthorizedClientError.errorCode=`unauthorized_client`;var UnsupportedGrantTypeError=class extends OAuthError{};UnsupportedGrantTypeError.errorCode=`unsupported_grant_type`;var InvalidScopeError=class extends OAuthError{};InvalidScopeError.errorCode=`invalid_scope`;var AccessDeniedError=class extends OAuthError{};AccessDeniedError.errorCode=`access_denied`;var ServerError=class extends OAuthError{};ServerError.errorCode=`server_error`;var TemporarilyUnavailableError=class extends OAuthError{};TemporarilyUnavailableError.errorCode=`temporarily_unavailable`;var UnsupportedResponseTypeError=class extends OAuthError{};UnsupportedResponseTypeError.errorCode=`unsupported_response_type`;var UnsupportedTokenTypeError=class extends OAuthError{};UnsupportedTokenTypeError.errorCode=`unsupported_token_type`;var InvalidTokenError=class extends OAuthError{};InvalidTokenError.errorCode=`invalid_token`;var MethodNotAllowedError=class extends OAuthError{};MethodNotAllowedError.errorCode=`method_not_allowed`;var TooManyRequestsError=class extends OAuthError{};TooManyRequestsError.errorCode=`too_many_requests`;var InvalidClientMetadataError=class extends OAuthError{};InvalidClientMetadataError.errorCode=`invalid_client_metadata`;var InsufficientScopeError=class extends OAuthError{};InsufficientScopeError.errorCode=`insufficient_scope`;var InvalidTargetError=class extends OAuthError{};InvalidTargetError.errorCode=`invalid_target`,InvalidRequestError.errorCode,InvalidClientError.errorCode,InvalidGrantError.errorCode,UnauthorizedClientError.errorCode,UnsupportedGrantTypeError.errorCode,InvalidScopeError.errorCode,AccessDeniedError.errorCode,ServerError.errorCode,TemporarilyUnavailableError.errorCode,UnsupportedResponseTypeError.errorCode,UnsupportedTokenTypeError.errorCode,InvalidTokenError.errorCode,MethodNotAllowedError.errorCode,TooManyRequestsError.errorCode,InvalidClientMetadataError.errorCode,InsufficientScopeError.errorCode,InvalidTargetError.errorCode;var compose=(e,t,n)=>(r,i)=>{let a=-1;return dispatch(0);async function dispatch(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>dispatch(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},HTTPException=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},bp=Symbol(),bufferToFormData=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),xp=32,Sp=1e4,isRawRequest=e=>`headers`in e,parseBody=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(isRawRequest(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?parseFormData(e,{all:n,dot:r}):{}};async function parseFormData(e,t){if(!isRawRequest(e)&&e.bodyCache.formData)return convertFormDataToBodyData(await e.bodyCache.formData,t);let n=isRawRequest(e)?e.headers:e.raw.headers,r=bufferToFormData(await e.arrayBuffer(),n.get(`Content-Type`)||``);isRawRequest(e)||(e.bodyCache.formData=r);let i=await r;return i?convertFormDataToBodyData(i,t):{}}function convertFormDataToBodyData(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?handleParsingAllValues(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(handleParsingNestedValues(n,e,t,r),delete n[e])}),n}var handleParsingAllValues=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},handleParsingNestedValues=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,xp+2);a.length>xp+1&&throwNestingLimitExceeded(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=Sp&&throwNestingLimitExceeded(),i[e]=Object.create(null)),i=i[e])})},throwNestingLimitExceeded=()=>{throw Error(`Nesting limit exceeded`)},splitPath=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},splitRoutingPath=e=>{let{groups:t,path:n}=extractGroupsFromPath(e);return replaceGroupMarks(splitPath(n),t)},extractGroupsFromPath=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},replaceGroupMarks=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},Cp={},getPattern=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return Cp[r]||(Cp[r]=n[2]?t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:[e,n[1],!0]),Cp[r]}return null},tryDecode=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},tryDecodeURI=e=>tryDecode(e,decodeURI),getPath=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),s=t.slice(n,a);return tryDecodeURI(s.includes(`%25`)?s.replace(/%25/g,`%2525`):s)}if(e===63||e===35)break}return t.slice(n,r)},getPathNoStrict=e=>{let t=getPath(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},mergePath=(e,t,...n)=>(n.length&&(t=mergePath(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),checkOptionalParameter=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e)){if(e.charCodeAt(e.length-1)===63){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.slice(0,-1);r+=`/`+t,n.push(r)}else r+=`/`+e}}),n.filter((e,t,n)=>n.indexOf(e)===t)},tryDecodeURIComponent=e=>e.indexOf(`%`)===-1?e:tryDecode(e,Tp),_decodeURI=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),tryDecodeURIComponent(e)),_getQueryParam=(e,t,n)=>{let r=e.indexOf(`#`,8);r!==-1&&(e=e.slice(0,r));let i;if(!n&&t&&t.indexOf(`%`)===-1&&t.indexOf(`+`)===-1){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return _decodeURI(e.slice(r,i===-1?void 0:i))}if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(i=/[%+]/.test(e),!i)return}let a=Object.create(null);i??=/[%+]/.test(e);let s=e.indexOf(`?`,8);for(;s!==-1;){let t=e.indexOf(`&`,s+1),r=e.indexOf(`=`,s);r>t&&t!==-1&&(r=-1);let c=e.slice(s+1,r===-1?t===-1?void 0:t:r);if(i&&(c=_decodeURI(c)),s=t,c===``)continue;let l;r===-1?l=``:(l=e.slice(r+1,t===-1?void 0:t),i&&(l=_decodeURI(l))),n?(a[c]&&Array.isArray(a[c])||(a[c]=[]),a[c].push(l)):a[c]??=l}return t?a[t]:a},wp=_getQueryParam,getQueryParams=(e,t)=>_getQueryParam(e,t,!0),Tp=decodeURIComponent,HonoRequest=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&tryDecodeURIComponent(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=tryDecodeURIComponent(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return wp(this.url,e)}queries(e){return getQueryParams(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return parseBody(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let r in t)return t[r].then(t=>{r===`json`&&(t=JSON.stringify(t));let i=r===`formData`?void 0:n.headers.get(`content-type`);return new Response(t,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[bp](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Ep={Stringify:1,BeforeStream:2,Stream:3},raw=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},resolveCallback=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let s=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>resolveCallback(e,t,!1,r,i))).then(()=>i[0]));return n?raw(await s,a):s},Dp=`text/plain; charset=UTF-8`,setDefaultContentType=(e,t)=>({"Content-Type":e,...t}),createResponseInstance=(e,t)=>new Response(e,t),Context=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new HonoRequest(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=createResponseInstance(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=createResponseInstance(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=createResponseInstance(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return createResponseInstance(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,setDefaultContentType(Dp,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,setDefaultContentType(`application/json`,n));html=(e,t,n)=>{let res=e=>this.#f(e,t,setDefaultContentType(`text/html; charset=UTF-8`,n));return typeof e==`object`?resolveCallback(e,Ep.Stringify,!1,{}).then(res):res(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>createResponseInstance(),this.#c(this))},Op=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],kp=`Can not add a route since the matcher is already built.`,UnsupportedPathError=class extends Error{},Ap=`__COMPOSED_HANDLER`,notFoundHandler=e=>e.text(`404 Not Found`,404),errorHandler=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},jp=class _Hono{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...Op,`all`].forEach(e=>{this[e]=(t,...n)=>{let r=e.toUpperCase();return typeof t==`string`?this.#e=t:this.#r(r,this.#e,t),n.forEach(e=>{this.#r(r,this.#e,e)}),this}}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat()){let e=t.toUpperCase();for(let t of n)this.#r(e,this.#e,t)}}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??getPath:getPathNoStrict}#t(){let e=new _Hono({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=notFoundHandler;errorHandler=errorHandler;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let handler;t.errorHandler===errorHandler?handler=e.handler:(handler=async(n,r)=>(await compose([],t.errorHandler)(n,()=>e.handler(n,r))).res,handler[Ap]=e.handler),n.#r(e.method,e.path,handler,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=mergePath(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=mergePath(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})();let handler=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#r(`ALL`,mergePath(e,`*`),handler),this}#r(e,t,n,r){t=mergePath(this._basePath,t);let i={basePath:r===void 0?this._basePath:mergePath(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),s=new Context(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](s,async()=>{s.res=await this.#n(s)})}catch(e){return this.#i(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#n(s))).catch(e=>this.#i(e,s)):e??this.#n(s)}let c=compose(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,s)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${mergePath(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},createNullObject=()=>Object.create(null),Mp=[];function match(e,t){let n=this.buildAllMatchers(),match2=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Mp];let s=a.indexOf(``,1);return[r[1][s],a]});return this.match=match2,match2(e,t)}var Np=`[^/]+`,Pp=`(?:|/.*)`,Fp=Symbol(),Ip=new Set(`.\\+*[^]$()`);function compareKey(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Lp=class _Node{#e;#t;#n=createNullObject();insert(e,t,n,r,i){let a=this;for(let t=0,i=e.length;t<i;t++){let s=e[t],c=s.length===1?s===`*`?t===i-1?[``,``,`.*`]:[``,``,Np]:null:s===`/*`?[``,``,Pp]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let e=c[1],t=c[2]||`[^/]+`;if(e&&c[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))||t.length===1&&Ip.has(t)))throw Fp;if(l=a.#n[t],!l){if(t!==`.*`&&t!==`(?:|/.*)`){for(let e in a.#n)if((t.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw Fp}l=a.#n[t]=new _Node}e!==``&&(l.#t??=r.varIndex++,n.push([e,l.#t]))}else if(l=a.#n[s],!l){for(let e in a.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw Fp;l=a.#n[s]=new _Node}a=l}if(a.#e!==void 0)throw Fp;a.#e=i?-1:t}buildRegExpStr(){let e=Object.keys(this.#n).sort(compareKey).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Ip.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Trie=class{#e={varIndex:0};#t=new Lp;#n=0;paths=createNullObject();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Rp=createNullObject();function buildWildcardRegExp(e){return Rp[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Pp:e===`*`?`.*`:`/:${Np}`)}$`)}function findMiddleware(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(buildWildcardRegExp(n).test(t))return[...e[n]]}var RegExpRouter=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:createNullObject()},this.#t={ALL:createNullObject()},this.#n={ALL:new Trie}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Fp?new UnsupportedPathError(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(kp);if(!r[e]){this.#n[e]=new Trie;for(let t of[r,i]){t[e]=createNullObject();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=buildWildcardRegExp(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=findMiddleware(r[e],t)||findMiddleware(r.ALL,t)||[]);for(let s of[r,i])for(let r of a)for(let i in s[r])e.test(i)&&s[r][i].push([n,t]);return}let s=checkOptionalParameter(t)||[t];for(let e of s)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=findMiddleware(r[t],e)||findMiddleware(r.ALL,e)||[]),i[t][e].push([n,e])}match=match;buildAllMatchers(){let e=createNullObject();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Rp=createNullObject(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=createNullObject(),a=[],[s,c,l]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],s=r.paths[t];if(!s){i[t]=[n.map(([e])=>[e,createNullObject()]),Mp];continue}a[s[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=l[s[1][n][1]],e),createNullObject())])}return[s,c.map(e=>a[e]),i]}},SmartRouter=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(kp);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,s;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);s=i.match(e,t)}catch(e){if(e instanceof UnsupportedPathError)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},zp=createNullObject(),Bp=0,Vp=class _Node{#e=[];#t=createNullObject();#n=[];#r;#i=zp;insert(e,t,n){let r=this,i=splitRoutingPath(t),a=new Set,s=0;for(let e of i){let t=i[++s],n=getPattern(e,t)||(t===void 0&&e&&e.indexOf(`*`)===e.length-1?e:null),c=Array.isArray(n),l=c?n[0]:n||e,u=r.#t[l]||=new _Node;n&&!u.#r&&(u.#r=n,r.#n.push(u)),r=u,c&&a.add(n[1])}r.#e.push({[e]:{handler:n,possibleKeys:[...a],score:++Bp}})}#a(e,t,n,r,i){for(let a=0,s=t.#e.length;a<s;a++){let s=t.#e[a],c=s[n]||s.ALL;if(c){c.params=createNullObject(),e.push(c);for(let e=0,t=c.possibleKeys.length;e<t;e++){let t=c.possibleKeys[e];c.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=zp;let r=[this],i=splitPath(t),a=[],s=i.length,c=null;for(let l=0;l<s;l++){let u=i[l],f=l===s-1,p=[];for(let m=0,h=r.length;m<h;m++){let h=r[m],g=h.#t[u];g&&(g.#i=h.#i,f?(g.#t[`*`]&&this.#a(n,g.#t[`*`],e,h.#i),this.#a(n,g,e,h.#i)):p.push(g));for(let r of h.#n){let m=r.#r,g=h.#i===zp?{}:{...h.#i};if(typeof m==`string`){(m===`*`||u.startsWith(m.slice(0,-1)))&&(this.#a(n,r,e,h.#i),m===`*`&&(r.#i=g,p.push(r)));continue}let[,v,y]=m;if(u||y!==!0){if(y!==!0){if(!c){c=[];let e=+(t[0]===`/`);for(let t=0;t<s;t++)c[t]=e,e+=i[t].length+1}let u=t.slice(c[l]),f=y.exec(u);if(f){g[v]=f[0],this.#a(n,r,e,h.#i,g),f[0].length===u.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,h.#i,g);for(let e in r.#t){r.#i=g;let e=f[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(y===!0||y.test(u))&&(g[v]=u,f?(this.#a(n,r,e,g,h.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,g,h.#i)):(r.#i=g,p.push(r)))}}}let m=a.shift();r=m?p.concat(m):p}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},TrieRouter=class{name=`TrieRouter`;#e=new Vp;add(e,t,n){for(let r of checkOptionalParameter(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},Hono=class extends jp{constructor(e={}){super(e),this.router=e.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}},cors=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function cors2(e,s){function set(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&set(`Access-Control-Allow-Origin`,c),t.credentials&&set(`Access-Control-Allow-Credentials`,`true`),n&&set(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&set(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&set(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(set(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await s(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};const Hp=Be().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:We.custom,message:`URL must be parseable`,fatal:!0}),Ne}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`});Pe({resource:E().url(),authorization_servers:A(Hp).optional(),jwks_uri:E().url().optional(),scopes_supported:A(E()).optional(),bearer_methods_supported:A(E()).optional(),resource_signing_alg_values_supported:A(E()).optional(),resource_name:E().optional(),resource_documentation:E().optional(),resource_policy_uri:E().url().optional(),resource_tos_uri:E().url().optional(),tls_client_certificate_bound_access_tokens:j().optional(),authorization_details_types_supported:A(E()).optional(),dpop_signing_alg_values_supported:A(E()).optional(),dpop_bound_access_tokens_required:j().optional()});const Up=Pe({issuer:E(),authorization_endpoint:Hp,token_endpoint:Hp,registration_endpoint:Hp.optional(),scopes_supported:A(E()).optional(),response_types_supported:A(E()),response_modes_supported:A(E()).optional(),grant_types_supported:A(E()).optional(),token_endpoint_auth_methods_supported:A(E()).optional(),token_endpoint_auth_signing_alg_values_supported:A(E()).optional(),service_documentation:Hp.optional(),revocation_endpoint:Hp.optional(),revocation_endpoint_auth_methods_supported:A(E()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A(E()).optional(),introspection_endpoint:E().optional(),introspection_endpoint_auth_methods_supported:A(E()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A(E()).optional(),code_challenge_methods_supported:A(E()).optional(),client_id_metadata_document_supported:j().optional()}),Wp=Pe({issuer:E(),authorization_endpoint:Hp,token_endpoint:Hp,userinfo_endpoint:Hp.optional(),jwks_uri:Hp,registration_endpoint:Hp.optional(),scopes_supported:A(E()).optional(),response_types_supported:A(E()),response_modes_supported:A(E()).optional(),grant_types_supported:A(E()).optional(),acr_values_supported:A(E()).optional(),subject_types_supported:A(E()),id_token_signing_alg_values_supported:A(E()),id_token_encryption_alg_values_supported:A(E()).optional(),id_token_encryption_enc_values_supported:A(E()).optional(),userinfo_signing_alg_values_supported:A(E()).optional(),userinfo_encryption_alg_values_supported:A(E()).optional(),userinfo_encryption_enc_values_supported:A(E()).optional(),request_object_signing_alg_values_supported:A(E()).optional(),request_object_encryption_alg_values_supported:A(E()).optional(),request_object_encryption_enc_values_supported:A(E()).optional(),token_endpoint_auth_methods_supported:A(E()).optional(),token_endpoint_auth_signing_alg_values_supported:A(E()).optional(),display_values_supported:A(E()).optional(),claim_types_supported:A(E()).optional(),claims_supported:A(E()).optional(),service_documentation:E().optional(),claims_locales_supported:A(E()).optional(),ui_locales_supported:A(E()).optional(),claims_parameter_supported:j().optional(),request_parameter_supported:j().optional(),request_uri_parameter_supported:j().optional(),require_request_uri_registration:j().optional(),op_policy_uri:Hp.optional(),op_tos_uri:Hp.optional(),client_id_metadata_document_supported:j().optional()});O({...Wp.shape,...Up.pick({code_challenge_methods_supported:!0}).shape}),O({access_token:E(),id_token:E().optional(),token_type:E(),expires_in:He().optional(),scope:E().optional(),refresh_token:E().optional()}).strip(),O({error:E(),error_description:E().optional(),error_uri:E().optional()});const Gp=Hp.optional().or(k(``).transform(()=>void 0)),Kp=O({redirect_uris:A(Hp),token_endpoint_auth_method:E().optional(),grant_types:A(E()).optional(),response_types:A(E()).optional(),client_name:E().optional(),client_uri:Hp.optional(),logo_uri:Gp,scope:E().optional(),contacts:A(E()).optional(),tos_uri:Gp,policy_uri:E().optional(),jwks_uri:Hp.optional(),jwks:Fe().optional(),software_id:E().optional(),software_version:E().optional(),software_statement:E().optional()}).strip(),qp=O({client_id:E(),client_secret:E().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip();Kp.merge(qp),O({error:E(),error_description:E().optional()}).strip(),O({token:E(),token_type_hint:E().optional()}).strip(),globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto),O({client_id:E(),redirect_uri:E().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),O({response_type:k(`code`),code_challenge:E(),code_challenge_method:k(`S256`),scope:E().optional(),state:E().optional(),resource:Be().optional()}),O({grant_type:E()}),O({code:E(),code_verifier:E(),redirect_uri:E().optional(),resource:Be().optional()}),O({refresh_token:E(),scope:E().optional(),resource:Be().optional()}),O({client_id:E(),client_secret:E().optional()});var StreamingApi=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let n=t.getReader();this.abortSubscribers.push(async()=>{await n.cancel()}),this.responseReadable=new ReadableStream({async pull(e){let{done:t,value:r}=await n.read();t?e.close():e.enqueue(r)},cancel:()=>{this.closed||this.abort()}})}async write(e){try{typeof e==`string`&&(e=this.encoder.encode(e)),await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
1573
+ `),this}sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0;try{await this.writer.close()}catch{}}async pipe(e){this.writer.releaseLock();try{await e.pipeTo(this.writable,{preventClose:!0,preventAbort:!0})}finally{this.writer=this.writable.getWriter()}}onAbort(e){this.abortSubscribers.push(e)}abort(){this.aborted||(this.aborted=!0,this.abortSubscribers.forEach(e=>{try{Promise.resolve(e()).catch(()=>{})}catch{}}))}},SSEStreamingApi=class extends StreamingApi{constructor(e,t){super(e,t)}async writeSSE(e){let t=(await resolveCallback(e.data,Ep.Stringify,!1,{})).split(/\r\n|\r|\n/).map(e=>`data: ${e}`).join(`
1558
1574
  `);for(let t of[`event`,`id`]){let n=e[t];if(n&&/[\r\n]/.test(n))throw Error(`${t} must not contain "\\r" or "\\n"`)}let n=[e.event&&`event: ${e.event}`,t,e.id!==void 0&&`id: ${e.id}`,e.retry!==void 0&&`retry: ${e.retry}`].filter(Boolean).join(`
1559
1575
  `)+`
1560
1576
 
1561
- `;await this.write(n)}};let isOldBunVersion=()=>{let e=typeof Bun<`u`?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith(`1.1`)||e.startsWith(`1.0`)||e.startsWith(`0.`);return isOldBunVersion=()=>t,t};const run=async(e,t,n)=>{try{await t(e)}catch(t){t instanceof Error&&n?(await n(t,e),await e.writeSSE({event:`error`,data:t.message})):console.error(t)}},Qp=new WeakMap,streamSSE=(e,t,n)=>{let{readable:r,writable:i}=new TransformStream,a=new SSEStreamingApi(i,r);return isOldBunVersion()&&e.req.raw.signal.addEventListener(`abort`,()=>{a.closed||a.abort()}),Qp.set(a.responseReadable,e),e.header(`Transfer-Encoding`,`chunked`),e.header(`Content-Type`,`text/event-stream`),e.header(`Cache-Control`,`no-cache`),e.header(`Connection`,`keep-alive`),run(a,t,n),e.newResponse(a.responseReadable)};var StreamableHTTPTransport=class{#e=!1;#t=!1;#n;#r;#i;#a;#o;#s=!1;#c=`_GET_stream`;#l=new Map;#u=new Map;#d=new Map;#f;#p;#m;#h;sessionId;onclose;onerror;onmessage;constructor(e){this.#a=e?.sessionIdGenerator,this.#s=e?.enableJsonResponse??!1,this.#o=e?.eventStore,this.#n=e?.onsessioninitialized,this.#r=e?.onsessionclosed,this.#i=e?.onsessiondisconnected,this.#f=e?.allowedHosts,this.#p=e?.allowedOrigins,this.#m=e?.enableDnsRebindingProtection??!1,this.#h=e?.strictAcceptHeader??!1}async start(){if(this.#e)throw Error(`Transport already started`);this.#e=!0}#g(e){if(this.#m){if(this.#f&&this.#f.length>0){let t=e.req.header(`Host`);if(!t||!this.#f.includes(t))return`Invalid Host header: ${t}`}if(this.#p&&this.#p.length>0){let t=e.req.header(`Origin`);if(!t||!this.#p.includes(t))return`Invalid Origin header: ${t}`}}}async handleRequest(e,t){let n=this.#g(e);if(n)throw new HTTPException(403,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:n},id:null})});switch(e.req.method){case`GET`:return this.handleGetRequest(e);case`POST`:return this.handlePostRequest(e,t);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest(e)}}async handleGetRequest(e){try{let t=e.req.header(`Accept`)??`*/*`;if(!t.includes(`text/event-stream`)&&!t.includes(`*/*`))throw new HTTPException(406,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Not Acceptable: Client must accept text/event-stream`},id:null})});this.#_(e),this.#v(e),this.sessionId!==void 0&&e.header(`mcp-session-id`,this.sessionId);let streamId=this.#c;if(this.#o){let t=this.#o,n=e.req.header(`last-event-id`);n&&(streamId=e=>t.replayEventsAfter(n,{send:async(t,n)=>{try{await e.writeSSE({id:t,event:`message`,data:JSON.stringify(n)})}catch{throw this.onerror?.(Error(`Failed replay events`)),new HTTPException(500,{message:`Failed replay events`})}}}))}if(typeof streamId==`string`&&this.#l.get(streamId)!==void 0)throw new HTTPException(409,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Conflict: Only one SSE stream is allowed per session`},id:null})});return streamSSE(e,async t=>{let n=typeof streamId==`string`?streamId:await streamId(t),r=setInterval(()=>{t.closed||t.writeSSE({data:``,event:`ping`}).catch(()=>{t.abort()})},3e4);typeof r==`object`&&`unref`in r&&r.unref(),this.#l.set(n,{ctx:{header:e.header},stream:t,cleanup:()=>{clearInterval(r),this.#l.delete(n)}}),t.onAbort(()=>{this.#l.get(n)?.cleanup();let e=this.#i,t=this.sessionId;n===this.#c&&e&&t&&Promise.resolve().then(()=>e(t)).catch(e=>{this.onerror?.(e instanceof Error?e:Error(String(e)))})})})}catch(e){throw e instanceof HTTPException?e:(this.onerror?.(e),new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ParseError,message:`Parse error`,data:String(e)},id:null})}))}}async handlePostRequest(e,t){try{let n=e.req.header(`Accept`)??`*/*`;if(!(this.#h?n.includes(`application/json`)&&n.includes(`text/event-stream`):n.includes(`application/json`)||n.includes(`text/event-stream`)||n.includes(`*/*`)))throw new HTTPException(406,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:this.#h?`Not Acceptable: Client must accept both application/json and text/event-stream`:`Not Acceptable: Client must accept application/json or text/event-stream`},id:null})});if(!e.req.header(`Content-Type`)?.includes(`application/json`))throw new HTTPException(415,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Unsupported Media Type: Content-Type must be application/json`},id:null})});let r=e.get(`auth`),i={headers:e.req.header()},a=t;a===void 0&&(a=await e.req.json());let s;s=Array.isArray(a)?a.map(e=>Qc.parse(e)):[Qc.parse(a)];let c=s.some(isInitializeRequest);if(c){if(this.#t&&this.sessionId!==void 0)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.InvalidRequest,message:`Invalid Request: Server already initialized`},id:null})});if(s.length>1)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.InvalidRequest,message:`Invalid Request: Only one initialization request is allowed`},id:null})});this.sessionId=this.#a?.(),this.#t=!0,this.sessionId&&this.#n&&await this.#n(this.sessionId)}c||(this.#_(e),this.#v(e));let l=s.some(isJSONRPCRequest);if(!l){for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i});return e.json(null,{status:202})}if(l){let t=crypto.randomUUID();return!this.#s&&this.sessionId!==void 0&&e.header(`mcp-session-id`,this.sessionId),this.#s?await new Promise(n=>{for(let r of s)isJSONRPCRequest(r)&&(this.#l.set(t,{ctx:{header:e.header,json:t=>{n(e.json(t))}},cleanup:()=>{this.#l.delete(t)}}),this.#u.set(r.id,t));for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i})}):streamSSE(e,async n=>{for(let r of s)isJSONRPCRequest(r)&&(this.#l.set(t,{ctx:{header:e.header},stream:n,cleanup:()=>{this.#l.delete(t)}}),this.#u.set(r.id,t));for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i});n.onAbort(()=>{this.#l.get(t)?.cleanup()})})}}catch(e){throw e instanceof HTTPException?e:(this.onerror?.(e),new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ParseError,message:`Parse error`,data:String(e)},id:null})}))}}async handleDeleteRequest(e){return this.#_(e),this.#v(e),this.#r&&this.sessionId&&await Promise.resolve(this.#r(this.sessionId)),await this.close(),e.body(null,200)}handleUnsupportedRequest(e){return e.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`}})}#_(e){if(this.#a===void 0)return!0;if(!this.#t)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Bad Request: Server not initialized`},id:null})});let t=e.req.header(`mcp-session-id`);if(!t)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Bad Request: Mcp-Session-Id header is required`},id:null})});if(Array.isArray(t))throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Bad Request: Mcp-Session-Id header must be a single value`},id:null})});if(t!==this.sessionId)throw new HTTPException(404,{res:Response.json({jsonrpc:`2.0`,error:{code:V.RequestTimeout,message:`Session not found`},id:null})});return!0}#v(e){let t=e.req.header(`mcp-protocol-version`)??`2025-03-26`;if(Array.isArray(t)&&(t=t[t.length-1]),!Nc.includes(t))throw new HTTPException(404,{res:Response.json({jsonrpc:`2.0`,error:{code:V.ConnectionClosed,message:`Bad Request: Unsupported protocol version (supported versions: ${Nc.join(`, `)})`},id:null})});return!0}async close(){for(let{stream:e}of this.#l.values())e?.abort();this.#l.clear(),this.#d.clear(),this.onclose?.()}async send(e,t){let n=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(n=e.id),n===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.#l.get(this.#c);if(t===void 0)return;let n;return this.#o&&(n=await this.#o.storeEvent(this.#c,e)),t.stream?.writeSSE({id:n,event:`message`,data:JSON.stringify(e)})}let r=this.#u.get(n),i=this.#l.get(r);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);if(!this.#s){let t;this.#o&&(t=await this.#o.storeEvent(r,e)),i&&await i.stream?.writeSSE({id:t,event:`message`,data:JSON.stringify(e)})}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this.#d.set(n,e);let t=Array.from(this.#u.entries()).filter(([,e])=>this.#l.get(e)===i).map(([e])=>e);if(t.every(e=>this.#d.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this.#s){this.sessionId!==void 0&&i.ctx.header(`mcp-session-id`,this.sessionId);let e=t.map(e=>this.#d.get(e));i.ctx.json?.(e.length===1?e[0]:e);return}i.stream?.abort();for(let e of t)this.#d.delete(e),this.#u.delete(e)}}}},MemoryEventStore=class{#e;#t;#n;#r;#i;constructor(e={}){let{streamBufferSize:t=100,eventsPerStreamBufferSize:n=100,idGenerator=()=>crypto.randomUUID()}=e;this.#n=new Map,this.#r=new Map,this.#e=n,this.#i=idGenerator,this.#t=new RingBuffer(t,({streamId:e,events:t})=>{this.#n.delete(e),t.reset()})}async storeEvent(e,t){let n=this.#i();return this.#r.set(n,e),(!this.#n.has(e)||this.#t.get(this.#n.get(e))==null)&&(this.#n.set(e,this.#t.head),this.#t.push({streamId:e,events:new RingBuffer(this.#e,({id:e})=>{this.#r.delete(e)})})),this.#t.get(this.#n.get(e)).events.push({id:n,message:t}),n}async replayEventsAfter(e,t){let n=this.#r.get(e);if(!n)return`_unknown_stream`;let r=this.#t.get(this.#n.get(n)).events.read(),i=r.findIndex(t=>t.id===e),a=i>-1?r.slice(i+1):r;for(let e of a)await t.send(e.id,e.message);return n}reset(){this.#t.reset(),this.#n.clear(),this.#r.clear()}},RingBuffer=class{#e;#t;#n;#r;#i;constructor(e,t){this.#e=Array(e),this.#t=0,this.#n=0,this.#r=e,this.#i=t}get head(){return this.#t}push(e){let t=this.#t%this.#r,n=this.#e[t];n!=null&&this.#i!=null&&this.#i(n),this.#e[t]=e,this.#t++,this.#n=Math.max(this.#n,this.#t-this.#r)}get(e){if(!(e<this.#n||e>=this.#t))return this.#e[e%this.#r]}read(){let e=[];for(let t=this.#n;t<this.#t;t++){let n=this.get(t);if(n==null)break;e.push(n)}return e}reset(){if(this.#i!=null)for(let e of this.read())this.#i(e);this.#e=Array(this.#r),this.#t=0,this.#n=0}},RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}};const $p=new Set([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`server`,`user-agent`]),em=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,normalizeHeaderValue=e=>{if(!isHttpWhitespace(e.charCodeAt(0))&&!isHttpWhitespace(e.charCodeAt(e.length-1)))return e;let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},tm=/[\0\r\n]/,nm=globalThis.Headers,materializeHeaders=(e,t=nm)=>{let n=new t;for(let t=0;t<e.length;t+=2){let r=e[t];r.startsWith(`:`)||n.append(r,e[t+1])}return n};var RequestHeaders=class{#e;#t;#n;#r;constructor(e){this.#e=e,e instanceof Qn&&(this.#t=e.rawHeaders.slice())}get#i(){return this.#t??=this.#e.rawHeaders.slice()}get#a(){return this.#n||(this.#n=materializeHeaders(this.#i),this.#t=void 0),this.#n}#o(e){if(typeof e==`string`){if(!em.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof Qn?void 0:this.#e.headers;if(!t||$p.has(e)||e===`set-cookie`||e===`__proto__`)return;if(!Object.hasOwn(t,e))return null;let n=t[e];if(typeof n==`string`){let e=normalizeHeaderValue(n);return tm.test(e)?void 0:e}}#c(e,t){let n=t===`cookie`?`; `:`, `,r=null;for(let i=0;i<e.length;i+=2){let a=e[i];if(a.length===t.length&&a.toLowerCase()===t){let t=normalizeHeaderValue(e[i+1]);if(tm.test(t)){this.#r=!0;return}r=r===null?t:r+n+t}}return r}append(e,t){this.#a.append(e,t)}delete(e){this.#a.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e;let n=this.#c(this.#i,t);if(n!==void 0)return n}return this.#a.get(e)}has(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e!==null;let n=this.#c(this.#i,t);if(n!==void 0)return n!==null}return this.#a.has(e)}set(e,t){this.#a.set(e,t)}getSetCookie(){return this.#a.getSetCookie()}keys(){return this.#a.keys()}values(){return this.#a.values()}entries(){return this.#a.entries()}forEach(e,t){this.#a.forEach((n,r)=>{e.call(t,n,r,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(RequestHeaders.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Headers (lightweight) ${n(Object.fromEntries(this),{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(RequestHeaders.prototype,nm.prototype);const newHeadersFromIncoming=e=>globalThis.Headers===nm?new RequestHeaders(e):materializeHeaders(e.rawHeaders,globalThis.Headers),rm=/^\/[!#$&-;=?-\[\]_a-z~]*$/,im=/\/\.\.?(?:[/?#]|$)/,am=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,buildUrl=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!am.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new RequestError(`Invalid host header`);return e.href}if(n.length===0)return r+`/`;if(n.charCodeAt(0)!==47)throw new RequestError(`Invalid URL`);return!rm.test(n)||im.test(n)?new URL(r).href:r},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),om=global.Request;var Request$1=class extends om{constructor(e,t){if(typeof e==`object`&&dm in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[Sm]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[dm]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const sm=Symbol(`wrapBodyStream`),cm=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),isByteExactEncoding=e=>e===null||cm.has(e),lm=Symbol(`bodyBufferedBeforeDisconnect`),um=Symbol(`bodyBufferedLengthBeforeDisconnect`),toBufferChunk=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),isRecoverableDisconnectedIncoming=e=>!(e instanceof Qn)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&isByteExactEncoding(e.readableEncoding),recordBodyBufferedBeforeDisconnect=e=>{if(e.readableDidRead||!isRecoverableDisconnectedIncoming(e))return;let t=e;t[um]??=e.readableLength},readBodyBufferedBeforeDisconnect=(e,t)=>{if(e.readableDidRead&&!t||!isRecoverableDisconnectedIncoming(e))return;let n=e;if(n[lm]!==void 0)return n[lm];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[um]!==void 0&&e.readableLength!==n[um])r=newBodyUnusableError();else{let n=t??[],i=e.read();i!==null&&n.push(toBufferChunk(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let s=e.headers[`content-length`];if(typeof s==`string`&&/^\d+$/.test(s)){let e=Number(s);Number.isSafeInteger(e)&&a.length!==e&&(r=newBodyUnusableError())}}return n[lm]=r,r},enqueueBufferedBody=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},newRequestFromIncoming=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Request$1(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[sm]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=readBodyBufferedBeforeDisconnect(r);if(e!==void 0){enqueueBufferedBody(t,e);return}}e||=er.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=readBodyBufferedBeforeDisconnect(r);a.body=e===void 0?er.toWeb(r):new ReadableStream({start(t){enqueueBufferedBody(t,e)}})}}return new Request$1(t,a)},dm=Symbol(`getRequestCache`),fm=Symbol(`requestCache`),pm=Symbol(`incomingKey`),mm=Symbol(`urlKey`),hm=Symbol(`methodKey`),gm=Symbol(`headersKey`),_m=Symbol(`abortControllerKey`),vm=Symbol(`getAbortController`),ym=Symbol(`abortRequest`),bm=Symbol(`bodyBuffer`),xm=Symbol(`bodyReadPromise`),Sm=Symbol(`bodyConsumedDirectly`),Cm=Symbol(`bodyLockReader`),wm=Symbol(`abortReason`),newBodyUnusableError=()=>TypeError(`Body is unusable`),rejectBodyUnusable=()=>Promise.reject(newBodyUnusableError()),Tm=new TextDecoder,consumeBodyDirectOnce=e=>{if(e[Sm])return rejectBodyUnusable();e[Sm]=!0},toArrayBuffer=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),contentType=e=>(e[gm]||=newHeadersFromIncoming(e[pm])).get(`content-type`)||``,Em=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,normalizeIncomingMethod=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`PATCH`:case`POST`:case`PUT`:case`QUERY`:return e}let t=e.toUpperCase();switch(t){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`:return t;default:return e}},validateDirectReadMethod=e=>{if(!Em.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},readBodyWithFastPath=(e,t,n)=>{if(e[Sm])return rejectBodyUnusable();let r=e.method;if(r===`GET`||r===`HEAD`)return e[dm]()[t]();let i=validateDirectReadMethod(r);if(i)return Promise.reject(i);if(e[fm]&&r!==`TRACE`)return e[fm][t]();let a=consumeBodyDirectOnce(e);if(a)return a;let s=readRawBodyIfAvailable(e);if(s){let t=Promise.resolve(n(s,e));return e[bm]=void 0,t}return readBodyDirect(e).then(t=>{let r=n(t,e);return e[bm]=void 0,r})},readRawBodyIfAvailable=e=>{let t=e[pm];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},normalizeAbortError=(e,t)=>{if(t.errored)return t.errored;let n=e[wm];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},readBodyDirect=e=>{if(e[bm])return Promise.resolve(e[bm]);if(e[xm])return e[xm];let t=e[pm];if(t.readableDidRead)return rejectBodyUnusable();let n=readBodyBufferedBeforeDisconnect(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[bm]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,finish=e=>{a||(a=!0,cleanup(),e())},recoverCompleteBodyAfterDisconnect=a=>{let s=t.errored??a;return!isRecoverableDisconnectedIncoming(t)||s&&s.code!==`ECONNRESET`?!1:(finish(()=>{let s=readBodyBufferedBeforeDisconnect(t,i);s instanceof Error?r(s):s===void 0?r(a??normalizeAbortError(e,t)):(e[bm]=s,n(s))}),!0)},onData=e=>{i.push(toBufferChunk(e,t.readableEncoding))},onEnd=()=>{finish(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[bm]=t,n(t)})},onError=e=>{recoverCompleteBodyAfterDisconnect(e)||finish(()=>{r(e)})},onClose=()=>{if(t.readableEnded){onEnd();return}recoverCompleteBodyAfterDisconnect()||finish(()=>{r(normalizeAbortError(e,t))})},cleanup=()=>{t.off(`data`,onData),t.off(`end`,onEnd),t.off(`error`,onError),t.off(`close`,onClose),e[xm]=void 0};t.on(`data`,onData),t.on(`end`,onEnd),t.on(`error`,onError),t.on(`close`,onClose),queueMicrotask(()=>{a||(t.readableEnded?onEnd():t.errored?onError(t.errored):t.destroyed&&onClose())})});return e[xm]=r,r},Dm={get method(){return this[hm]},get url(){return this[mm]},get headers(){return this[gm]||=newHeadersFromIncoming(this[pm])},[ym](e){this[wm]===void 0&&(this[wm]=e);let t=this[_m];t&&!t.signal.aborted&&t.abort(e)},[vm](){return this[_m]||=new AbortController,this[wm]!==void 0&&!this[_m].signal.aborted&&this[_m].abort(this[wm]),this[_m]},[dm](){let e=this[vm]();if(this[fm])return this[fm];let t=this.method;if(this[Sm]&&t!==`GET`&&t!==`HEAD`){this[bm]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new Request$1(this[mm],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[fm]=r}return this[fm]=newRequestFromIncoming(this.method,this[mm],this.headers,this[pm],e)},get body(){if(!this[Sm])return this[dm]().body;let e=this[dm]();return!this[Cm]&&e.body&&(this[Cm]=e.body.getReader()),e.body},get bodyUsed(){return this[Sm]?!0:this[fm]?this[fm].bodyUsed:!1}};Object.defineProperty(Dm,"signal",{get(){return this[vm]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(Dm,e,{get(){return this[dm]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(Dm,e,{value:function(){if(this[Sm]){if(e===`clone`)throw newBodyUnusableError();return rejectBodyUnusable()}return this[dm]()[e]()}})}),Object.defineProperty(Dm,"text",{value:function(){return readBodyWithFastPath(this,`text`,e=>Tm.decode(e))}}),Object.defineProperty(Dm,"arrayBuffer",{value:function(){return readBodyWithFastPath(this,`arrayBuffer`,e=>toArrayBuffer(e))}}),Object.defineProperty(Dm,"blob",{value:function(){return readBodyWithFastPath(this,`blob`,(e,t)=>{let n=contentType(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(Dm,"json",{value:function(){return this[Sm]?rejectBodyUnusable():this.text().then(JSON.parse)}}),Object.defineProperty(Dm,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[fm]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Dm,Request$1.prototype);const newRequest=(e,t)=>{let n=Object.create(Dm);n[pm]=e,n[hm]=normalizeIncomingMethod(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof Qn)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{n[mm]=new URL(r).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof Qn?e.authority:e.headers.host)||t;if(!i)throw new RequestError(`Missing host header`);let a;if(e instanceof Qn){if(a=e.scheme,a!==`http`&&a!==`https`)throw new RequestError(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[mm]=buildUrl(a,i,r)}catch(e){throw e instanceof RequestError?e:new RequestError(`Invalid URL`,{cause:e})}return n},Om=`text/plain; charset=UTF-8`,km=Symbol(`responseCache`),Am=Symbol(`getResponseCache`),jm=Symbol(`cache`),Mm=global.Response;var Nm=class Response$1{#e;#t;[Am](){let e=this[jm],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[jm],this[km]||=new Mm(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(e,t){let n;if(this.#e=e,t instanceof Mm){let e=t[km];if(e){this.#t=e,this[Am]();return}this.#t=t instanceof Response$1?t.#t:t,n=new Headers(t.headers)}else this.#t=t;(e==null||typeof e==`string`||e?.getReader!==void 0||e instanceof Blob||e instanceof Uint8Array)&&(this[jm]=[t?.status||200,e??null,n||t?.headers])}get headers(){let e=this[jm];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Om}))),e[2]):this[Am]().headers}get status(){return this[jm]?.[0]??this[Am]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Nm.prototype,e,{get(){return this[Am]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Nm.prototype,e,{value:function(){return this[Am]()[e]()}})}),Object.defineProperty(Nm.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[km]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Nm,Mm),Object.setPrototypeOf(Nm.prototype,Mm.prototype);const Pm=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,parseRedirectUrl=e=>e instanceof URL?e.href:Pm.test(e)?e:new URL(e).href,Fm=new Set([301,302,303,307,308]);Object.defineProperty(Nm,"redirect",{value:function redirect(e,t=302){if(!Fm.has(t))throw RangeError(`Invalid status code`);return new Nm(null,{status:t,headers:{location:parseRedirectUrl(e)}})},writable:!0,configurable:!0}),Object.defineProperty(Nm,"json",{value:function json(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new Nm(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,n){let cancel=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,cancel),t.on(`error`,cancel),(n??e.read()).then(flow,handleStreamError),e.closed.finally(()=>{t.off(`close`,cancel),t.off(`error`,cancel)});function handleStreamError(e){e&&t.destroy(e)}function onDrain(){e.read().then(flow,handleStreamError)}function flow({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,onDrain);else return e.read().then(flow,handleStreamError)}catch(e){handleStreamError(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}const buildOutgoingHttpHeaders=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},Im=Symbol(`outgoingEnded`),Lm=Symbol(`incomingDraining`),drainIncoming=e=>{let t=e;if(e.destroyed||t[Lm])return;if(t[Lm]=!0,e instanceof Qn){try{e.stream?.close?.($n.NGHTTP2_NO_ERROR)}catch{}return}let n=0,cleanup=()=>{clearTimeout(r),e.off(`data`,onData),e.off(`end`,cleanup),e.off(`error`,cleanup)},forceClose=()=>{cleanup();let t=e.socket;t&&!t.destroyed&&(typeof t.destroySoon==`function`?t.destroySoon():typeof t.destroy==`function`&&t.destroy())},r=setTimeout(forceClose,500);r.unref?.();let onData=e=>{n+=e.length,n>67108864&&forceClose()};e.on(`data`,onData),e.on(`end`,cleanup),e.on(`error`,cleanup),e.resume()},makeCloseHandler=(e,t,n,r)=>()=>{t.errored?(recordBodyBufferedBeforeDisconnect(t),e[ym](t.errored.toString())):n.writableFinished||(recordBodyBufferedBeforeDisconnect(t),e[ym](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{drainIncoming(t)})})},isImmediateCacheableResponse=e=>{if(!(jm in e))return!1;let t=e[jm][1];return t===null||typeof t==`string`||t instanceof Uint8Array},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 n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.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: ${n.message}`),t.destroy(n))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[n,r,i]=e[jm];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":Om,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":Om,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":Om,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":Om}),flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[Im]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=buildOutgoingHttpHeaders(i,r===null?void 0:Om);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=buildOutgoingHttpHeaders(e,r===null?void 0:Om)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[Im]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,n={})=>{if(isPromise(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(handleFetchError)}if(jm in e)return responseViaCache(e,t);let r=buildOutgoingHttpHeaders(e.headers,e.body===null?void 0:Om);if(e.body){let n=e.body.getReader(),i=[],a=!1,s;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){s||=n.read();let r=await readWithoutBlocking(s).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(s=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(n,t,s))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[Im]?.()},getRequestListener=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,"Request",{value:Request$1}),Object.defineProperty(global,"Response",{value:Nm})),async(r,i)=>{let a,s,c=!1,l=!1,ensureCloseHandler=()=>{!s||l||(l=!0,i.on(`close`,makeCloseHandler(s,r,i,c)))};try{if(s=newRequest(r,t.hostname),c=n&&r.method!==`GET`&&r.method!==`HEAD`,c&&(r[sm]=!0,r instanceof Qn&&(i[Im]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),i.destroy()})})})),a=e(s,{incoming:r,outgoing:i}),!isPromise(a)&&isImmediateCacheableResponse(a))return c&&!r.readableEnded&&i.once(`finish`,()=>{r.readableEnded||drainIncoming(r)}),responseViaCache(a,i);ensureCloseHandler()}catch(e){if(a)return handleResponseError(e,i);if(t.errorHandler){if(ensureCloseHandler(),a=await t.errorHandler(s?e:toRequestError(e)),!a)return}else a=s?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(a,i,t)}catch(e){return handleResponseError(e,i)}}};globalThis.CloseEvent,globalThis.ErrorEvent;const Rm=Symbol(`CONNECTION_SYMBOL_KEY`),zm=Symbol(`WAIT_FOR_WEBSOCKET_SYMBOL`),Bm=new Set([`connection`,`content-length`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`sec-websocket-accept`,`sec-websocket-extensions`,`sec-websocket-protocol`]),appendResponseHeaders=(e,t)=>{t&&t.forEach((t,n)=>{Bm.has(n.toLowerCase())||e.push(`${n}: ${t}`)})},rejectUpgradeRequest=(e,t,n)=>{let r=[`Connection: close`,`Content-Length: 0`];appendResponseHeaders(r,n),e.end(`HTTP/1.1 ${t.toString()} ${Xn[t]??``}\r\n${r.join(`\r
1577
+ `;await this.write(n)}};let isOldBunVersion=()=>{let e=typeof Bun<`u`?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith(`1.1`)||e.startsWith(`1.0`)||e.startsWith(`0.`);return isOldBunVersion=()=>t,t};const run=async(e,t,n)=>{try{await t(e)}catch(t){t instanceof Error&&n?(await n(t,e),await e.writeSSE({event:`error`,data:t.message})):console.error(t)}},Jp=new WeakMap,streamSSE=(e,t,n)=>{let{readable:r,writable:i}=new TransformStream,a=new SSEStreamingApi(i,r);return isOldBunVersion()&&e.req.raw.signal.addEventListener(`abort`,()=>{a.closed||a.abort()}),Jp.set(a.responseReadable,e),e.header(`Transfer-Encoding`,`chunked`),e.header(`Content-Type`,`text/event-stream`),e.header(`Cache-Control`,`no-cache`),e.header(`Connection`,`keep-alive`),run(a,t,n),e.newResponse(a.responseReadable)};var StreamableHTTPTransport=class{#e=!1;#t=!1;#n;#r;#i;#a;#o;#s=!1;#c=`_GET_stream`;#l=new Map;#u=new Map;#d=new Map;#f;#p;#m;#h;sessionId;onclose;onerror;onmessage;constructor(e){this.#a=e?.sessionIdGenerator,this.#s=e?.enableJsonResponse??!1,this.#o=e?.eventStore,this.#n=e?.onsessioninitialized,this.#r=e?.onsessionclosed,this.#i=e?.onsessiondisconnected,this.#f=e?.allowedHosts,this.#p=e?.allowedOrigins,this.#m=e?.enableDnsRebindingProtection??!1,this.#h=e?.strictAcceptHeader??!1}async start(){if(this.#e)throw Error(`Transport already started`);this.#e=!0}#g(e){if(this.#m){if(this.#f&&this.#f.length>0){let t=e.req.header(`Host`);if(!t||!this.#f.includes(t))return`Invalid Host header: ${t}`}if(this.#p&&this.#p.length>0){let t=e.req.header(`Origin`);if(!t||!this.#p.includes(t))return`Invalid Origin header: ${t}`}}}async handleRequest(e,t){let n=this.#g(e);if(n)throw new HTTPException(403,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:n},id:null})});switch(e.req.method){case`GET`:return this.handleGetRequest(e);case`POST`:return this.handlePostRequest(e,t);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest(e)}}async handleGetRequest(e){try{let t=e.req.header(`Accept`)??`*/*`;if(!t.includes(`text/event-stream`)&&!t.includes(`*/*`))throw new HTTPException(406,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Not Acceptable: Client must accept text/event-stream`},id:null})});this.#_(e),this.#v(e),this.sessionId!==void 0&&e.header(`mcp-session-id`,this.sessionId);let streamId=this.#c;if(this.#o){let t=this.#o,n=e.req.header(`last-event-id`);n&&(streamId=e=>t.replayEventsAfter(n,{send:async(t,n)=>{try{await e.writeSSE({id:t,event:`message`,data:JSON.stringify(n)})}catch{throw this.onerror?.(Error(`Failed replay events`)),new HTTPException(500,{message:`Failed replay events`})}}}))}if(typeof streamId==`string`&&this.#l.get(streamId)!==void 0)throw new HTTPException(409,{res:Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Conflict: Only one SSE stream is allowed per session`},id:null})});return streamSSE(e,async t=>{let n=typeof streamId==`string`?streamId:await streamId(t),r=setInterval(()=>{t.closed||t.writeSSE({data:``,event:`ping`}).catch(()=>{t.abort()})},3e4);typeof r==`object`&&`unref`in r&&r.unref(),this.#l.set(n,{ctx:{header:e.header},stream:t,cleanup:()=>{clearInterval(r),this.#l.delete(n)}}),t.onAbort(()=>{this.#l.get(n)?.cleanup();let e=this.#i,t=this.sessionId;n===this.#c&&e&&t&&Promise.resolve().then(()=>e(t)).catch(e=>{this.onerror?.(e instanceof Error?e:Error(String(e)))})})})}catch(e){throw e instanceof HTTPException?e:(this.onerror?.(e),new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ParseError,message:`Parse error`,data:String(e)},id:null})}))}}async handlePostRequest(e,t){try{let n=e.req.header(`Accept`)??`*/*`;if(!(this.#h?n.includes(`application/json`)&&n.includes(`text/event-stream`):n.includes(`application/json`)||n.includes(`text/event-stream`)||n.includes(`*/*`)))throw new HTTPException(406,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:this.#h?`Not Acceptable: Client must accept both application/json and text/event-stream`:`Not Acceptable: Client must accept application/json or text/event-stream`},id:null})});if(!e.req.header(`Content-Type`)?.includes(`application/json`))throw new HTTPException(415,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Unsupported Media Type: Content-Type must be application/json`},id:null})});let r=e.get(`auth`),i={headers:e.req.header()},a=t;a===void 0&&(a=await e.req.json());let s;s=Array.isArray(a)?a.map(e=>Zc.parse(e)):[Zc.parse(a)];let c=s.some(isInitializeRequest);if(c){if(this.#t&&this.sessionId!==void 0)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.InvalidRequest,message:`Invalid Request: Server already initialized`},id:null})});if(s.length>1)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.InvalidRequest,message:`Invalid Request: Only one initialization request is allowed`},id:null})});this.sessionId=this.#a?.(),this.#t=!0,this.sessionId&&this.#n&&await this.#n(this.sessionId)}c||(this.#_(e),this.#v(e));let l=s.some(isJSONRPCRequest);if(!l){for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i});return e.json(null,{status:202})}if(l){let t=crypto.randomUUID();return!this.#s&&this.sessionId!==void 0&&e.header(`mcp-session-id`,this.sessionId),this.#s?await new Promise(n=>{for(let r of s)isJSONRPCRequest(r)&&(this.#l.set(t,{ctx:{header:e.header,json:t=>{n(e.json(t))}},cleanup:()=>{this.#l.delete(t)}}),this.#u.set(r.id,t));for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i})}):streamSSE(e,async n=>{for(let r of s)isJSONRPCRequest(r)&&(this.#l.set(t,{ctx:{header:e.header},stream:n,cleanup:()=>{this.#l.delete(t)}}),this.#u.set(r.id,t));for(let e of s)this.onmessage?.(e,{authInfo:r,requestInfo:i});n.onAbort(()=>{this.#l.get(t)?.cleanup()})})}}catch(e){throw e instanceof HTTPException?e:(this.onerror?.(e),new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ParseError,message:`Parse error`,data:String(e)},id:null})}))}}async handleDeleteRequest(e){return this.#_(e),this.#v(e),this.#r&&this.sessionId&&await Promise.resolve(this.#r(this.sessionId)),await this.close(),e.body(null,200)}handleUnsupportedRequest(e){return e.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`}})}#_(e){if(this.#a===void 0)return!0;if(!this.#t)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Bad Request: Server not initialized`},id:null})});let t=e.req.header(`mcp-session-id`);if(!t)throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Bad Request: Mcp-Session-Id header is required`},id:null})});if(Array.isArray(t))throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Bad Request: Mcp-Session-Id header must be a single value`},id:null})});if(t!==this.sessionId)throw new HTTPException(404,{res:Response.json({jsonrpc:`2.0`,error:{code:G.RequestTimeout,message:`Session not found`},id:null})});return!0}#v(e){let t=e.req.header(`mcp-protocol-version`)??`2025-03-26`;if(Array.isArray(t)&&(t=t[t.length-1]),!Mc.includes(t))throw new HTTPException(404,{res:Response.json({jsonrpc:`2.0`,error:{code:G.ConnectionClosed,message:`Bad Request: Unsupported protocol version (supported versions: ${Mc.join(`, `)})`},id:null})});return!0}async close(){for(let{stream:e}of this.#l.values())e?.abort();this.#l.clear(),this.#d.clear(),this.onclose?.()}async send(e,t){let n=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(n=e.id),n===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.#l.get(this.#c);if(t===void 0)return;let n;return this.#o&&(n=await this.#o.storeEvent(this.#c,e)),t.stream?.writeSSE({id:n,event:`message`,data:JSON.stringify(e)})}let r=this.#u.get(n),i=this.#l.get(r);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);if(!this.#s){let t;this.#o&&(t=await this.#o.storeEvent(r,e)),i&&await i.stream?.writeSSE({id:t,event:`message`,data:JSON.stringify(e)})}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this.#d.set(n,e);let t=Array.from(this.#u.entries()).filter(([,e])=>this.#l.get(e)===i).map(([e])=>e);if(t.every(e=>this.#d.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this.#s){this.sessionId!==void 0&&i.ctx.header(`mcp-session-id`,this.sessionId);let e=t.map(e=>this.#d.get(e));i.ctx.json?.(e.length===1?e[0]:e);return}i.stream?.abort();for(let e of t)this.#d.delete(e),this.#u.delete(e)}}}},MemoryEventStore=class{#e;#t;#n;#r;#i;constructor(e={}){let{streamBufferSize:t=100,eventsPerStreamBufferSize:n=100,idGenerator=()=>crypto.randomUUID()}=e;this.#n=new Map,this.#r=new Map,this.#e=n,this.#i=idGenerator,this.#t=new RingBuffer(t,({streamId:e,events:t})=>{this.#n.delete(e),t.reset()})}async storeEvent(e,t){let n=this.#i();return this.#r.set(n,e),(!this.#n.has(e)||this.#t.get(this.#n.get(e))==null)&&(this.#n.set(e,this.#t.head),this.#t.push({streamId:e,events:new RingBuffer(this.#e,({id:e})=>{this.#r.delete(e)})})),this.#t.get(this.#n.get(e)).events.push({id:n,message:t}),n}async replayEventsAfter(e,t){let n=this.#r.get(e);if(!n)return`_unknown_stream`;let r=this.#t.get(this.#n.get(n)).events.read(),i=r.findIndex(t=>t.id===e),a=i>-1?r.slice(i+1):r;for(let e of a)await t.send(e.id,e.message);return n}reset(){this.#t.reset(),this.#n.clear(),this.#r.clear()}},RingBuffer=class{#e;#t;#n;#r;#i;constructor(e,t){this.#e=Array(e),this.#t=0,this.#n=0,this.#r=e,this.#i=t}get head(){return this.#t}push(e){let t=this.#t%this.#r,n=this.#e[t];n!=null&&this.#i!=null&&this.#i(n),this.#e[t]=e,this.#t++,this.#n=Math.max(this.#n,this.#t-this.#r)}get(e){if(!(e<this.#n||e>=this.#t))return this.#e[e%this.#r]}read(){let e=[];for(let t=this.#n;t<this.#t;t++){let n=this.get(t);if(n==null)break;e.push(n)}return e}reset(){if(this.#i!=null)for(let e of this.read())this.#i(e);this.#e=Array(this.#r),this.#t=0,this.#n=0}},RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}};const Yp=new Set([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`server`,`user-agent`]),Xp=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,normalizeHeaderValue=e=>{if(!isHttpWhitespace(e.charCodeAt(0))&&!isHttpWhitespace(e.charCodeAt(e.length-1)))return e;let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},Zp=/[\0\r\n]/,Qp=globalThis.Headers,materializeHeaders=(e,t=Qp)=>{let n=new t;for(let t=0;t<e.length;t+=2){let r=e[t];r.startsWith(`:`)||n.append(r,e[t+1])}return n};var RequestHeaders=class{#e;#t;#n;#r;constructor(e){this.#e=e,e instanceof $n&&(this.#t=e.rawHeaders.slice())}get#i(){return this.#t??=this.#e.rawHeaders.slice()}get#a(){return this.#n||(this.#n=materializeHeaders(this.#i),this.#t=void 0),this.#n}#o(e){if(typeof e==`string`){if(!Xp.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof $n?void 0:this.#e.headers;if(!t||Yp.has(e)||e===`set-cookie`||e===`__proto__`)return;if(!Object.hasOwn(t,e))return null;let n=t[e];if(typeof n==`string`){let e=normalizeHeaderValue(n);return Zp.test(e)?void 0:e}}#c(e,t){let n=t===`cookie`?`; `:`, `,r=null;for(let i=0;i<e.length;i+=2){let a=e[i];if(a.length===t.length&&a.toLowerCase()===t){let t=normalizeHeaderValue(e[i+1]);if(Zp.test(t)){this.#r=!0;return}r=r===null?t:r+n+t}}return r}append(e,t){this.#a.append(e,t)}delete(e){this.#a.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e;let n=this.#c(this.#i,t);if(n!==void 0)return n}return this.#a.get(e)}has(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e!==null;let n=this.#c(this.#i,t);if(n!==void 0)return n!==null}return this.#a.has(e)}set(e,t){this.#a.set(e,t)}getSetCookie(){return this.#a.getSetCookie()}keys(){return this.#a.keys()}values(){return this.#a.values()}entries(){return this.#a.entries()}forEach(e,t){this.#a.forEach((n,r)=>{e.call(t,n,r,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(RequestHeaders.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Headers (lightweight) ${n(Object.fromEntries(this),{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(RequestHeaders.prototype,Qp.prototype);const newHeadersFromIncoming=e=>globalThis.Headers===Qp?new RequestHeaders(e):materializeHeaders(e.rawHeaders,globalThis.Headers),$p=/^\/[!#$&-;=?-\[\]_a-z~]*$/,em=/\/\.\.?(?:[/?#]|$)/,tm=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,buildUrl=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!tm.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new RequestError(`Invalid host header`);return e.href}if(n.length===0)return r+`/`;if(n.charCodeAt(0)!==47)throw new RequestError(`Invalid URL`);return!$p.test(n)||em.test(n)?new URL(r).href:r},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),nm=global.Request;var Request$1=class extends nm{constructor(e,t){if(typeof e==`object`&&sm in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[vm]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[sm]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const rm=Symbol(`wrapBodyStream`),im=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),isByteExactEncoding=e=>e===null||im.has(e),am=Symbol(`bodyBufferedBeforeDisconnect`),om=Symbol(`bodyBufferedLengthBeforeDisconnect`),toBufferChunk=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),isRecoverableDisconnectedIncoming=e=>!(e instanceof $n)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&isByteExactEncoding(e.readableEncoding),recordBodyBufferedBeforeDisconnect=e=>{if(e.readableDidRead||!isRecoverableDisconnectedIncoming(e))return;let t=e;t[om]??=e.readableLength},readBodyBufferedBeforeDisconnect=(e,t)=>{if(e.readableDidRead&&!t||!isRecoverableDisconnectedIncoming(e))return;let n=e;if(n[am]!==void 0)return n[am];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[om]!==void 0&&e.readableLength!==n[om])r=newBodyUnusableError();else{let n=t??[],i=e.read();i!==null&&n.push(toBufferChunk(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let s=e.headers[`content-length`];if(typeof s==`string`&&/^\d+$/.test(s)){let e=Number(s);Number.isSafeInteger(e)&&a.length!==e&&(r=newBodyUnusableError())}}return n[am]=r,r},enqueueBufferedBody=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},newRequestFromIncoming=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Request$1(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[rm]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=readBodyBufferedBeforeDisconnect(r);if(e!==void 0){enqueueBufferedBody(t,e);return}}e||=tr.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=readBodyBufferedBeforeDisconnect(r);a.body=e===void 0?tr.toWeb(r):new ReadableStream({start(t){enqueueBufferedBody(t,e)}})}}return new Request$1(t,a)},sm=Symbol(`getRequestCache`),cm=Symbol(`requestCache`),lm=Symbol(`incomingKey`),um=Symbol(`urlKey`),dm=Symbol(`methodKey`),fm=Symbol(`headersKey`),pm=Symbol(`abortControllerKey`),mm=Symbol(`getAbortController`),hm=Symbol(`abortRequest`),gm=Symbol(`bodyBuffer`),_m=Symbol(`bodyReadPromise`),vm=Symbol(`bodyConsumedDirectly`),ym=Symbol(`bodyLockReader`),bm=Symbol(`abortReason`),newBodyUnusableError=()=>TypeError(`Body is unusable`),rejectBodyUnusable=()=>Promise.reject(newBodyUnusableError()),xm=new TextDecoder,consumeBodyDirectOnce=e=>{if(e[vm])return rejectBodyUnusable();e[vm]=!0},toArrayBuffer=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),contentType=e=>(e[fm]||=newHeadersFromIncoming(e[lm])).get(`content-type`)||``,Sm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,normalizeIncomingMethod=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`PATCH`:case`POST`:case`PUT`:case`QUERY`:return e}let t=e.toUpperCase();switch(t){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`:return t;default:return e}},validateDirectReadMethod=e=>{if(!Sm.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},readBodyWithFastPath=(e,t,n)=>{if(e[vm])return rejectBodyUnusable();let r=e.method;if(r===`GET`||r===`HEAD`)return e[sm]()[t]();let i=validateDirectReadMethod(r);if(i)return Promise.reject(i);if(e[cm]&&r!==`TRACE`)return e[cm][t]();let a=consumeBodyDirectOnce(e);if(a)return a;let s=readRawBodyIfAvailable(e);if(s){let t=Promise.resolve(n(s,e));return e[gm]=void 0,t}return readBodyDirect(e).then(t=>{let r=n(t,e);return e[gm]=void 0,r})},readRawBodyIfAvailable=e=>{let t=e[lm];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},normalizeAbortError=(e,t)=>{if(t.errored)return t.errored;let n=e[bm];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},readBodyDirect=e=>{if(e[gm])return Promise.resolve(e[gm]);if(e[_m])return e[_m];let t=e[lm];if(t.readableDidRead)return rejectBodyUnusable();let n=readBodyBufferedBeforeDisconnect(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[gm]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,finish=e=>{a||(a=!0,cleanup(),e())},recoverCompleteBodyAfterDisconnect=a=>{let s=t.errored??a;return!isRecoverableDisconnectedIncoming(t)||s&&s.code!==`ECONNRESET`?!1:(finish(()=>{let s=readBodyBufferedBeforeDisconnect(t,i);s instanceof Error?r(s):s===void 0?r(a??normalizeAbortError(e,t)):(e[gm]=s,n(s))}),!0)},onData=e=>{i.push(toBufferChunk(e,t.readableEncoding))},onEnd=()=>{finish(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[gm]=t,n(t)})},onError=e=>{recoverCompleteBodyAfterDisconnect(e)||finish(()=>{r(e)})},onClose=()=>{if(t.readableEnded){onEnd();return}recoverCompleteBodyAfterDisconnect()||finish(()=>{r(normalizeAbortError(e,t))})},cleanup=()=>{t.off(`data`,onData),t.off(`end`,onEnd),t.off(`error`,onError),t.off(`close`,onClose),e[_m]=void 0};t.on(`data`,onData),t.on(`end`,onEnd),t.on(`error`,onError),t.on(`close`,onClose),queueMicrotask(()=>{a||(t.readableEnded?onEnd():t.errored?onError(t.errored):t.destroyed&&onClose())})});return e[_m]=r,r},Cm={get method(){return this[dm]},get url(){return this[um]},get headers(){return this[fm]||=newHeadersFromIncoming(this[lm])},[hm](e){this[bm]===void 0&&(this[bm]=e);let t=this[pm];t&&!t.signal.aborted&&t.abort(e)},[mm](){return this[pm]||=new AbortController,this[bm]!==void 0&&!this[pm].signal.aborted&&this[pm].abort(this[bm]),this[pm]},[sm](){let e=this[mm]();if(this[cm])return this[cm];let t=this.method;if(this[vm]&&t!==`GET`&&t!==`HEAD`){this[gm]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new Request$1(this[um],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[cm]=r}return this[cm]=newRequestFromIncoming(this.method,this[um],this.headers,this[lm],e)},get body(){if(!this[vm])return this[sm]().body;let e=this[sm]();return!this[ym]&&e.body&&(this[ym]=e.body.getReader()),e.body},get bodyUsed(){return this[vm]?!0:this[cm]?this[cm].bodyUsed:!1}};Object.defineProperty(Cm,"signal",{get(){return this[mm]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(Cm,e,{get(){return this[sm]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(Cm,e,{value:function(){if(this[vm]){if(e===`clone`)throw newBodyUnusableError();return rejectBodyUnusable()}return this[sm]()[e]()}})}),Object.defineProperty(Cm,"text",{value:function(){return readBodyWithFastPath(this,`text`,e=>xm.decode(e))}}),Object.defineProperty(Cm,"arrayBuffer",{value:function(){return readBodyWithFastPath(this,`arrayBuffer`,e=>toArrayBuffer(e))}}),Object.defineProperty(Cm,"blob",{value:function(){return readBodyWithFastPath(this,`blob`,(e,t)=>{let n=contentType(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(Cm,"json",{value:function(){return this[vm]?rejectBodyUnusable():this.text().then(JSON.parse)}}),Object.defineProperty(Cm,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[cm]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Cm,Request$1.prototype);const newRequest=(e,t)=>{let n=Object.create(Cm);n[lm]=e,n[dm]=normalizeIncomingMethod(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof $n)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{n[um]=new URL(r).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof $n?e.authority:e.headers.host)||t;if(!i)throw new RequestError(`Missing host header`);let a;if(e instanceof $n){if(a=e.scheme,a!==`http`&&a!==`https`)throw new RequestError(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[um]=buildUrl(a,i,r)}catch(e){throw e instanceof RequestError?e:new RequestError(`Invalid URL`,{cause:e})}return n},wm=`text/plain; charset=UTF-8`,Tm=Symbol(`responseCache`),Em=Symbol(`getResponseCache`),Dm=Symbol(`cache`),Om=global.Response;var km=class Response$1{#e;#t;[Em](){let e=this[Dm],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Dm],this[Tm]||=new Om(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(e,t){let n;if(this.#e=e,t instanceof Om){let e=t[Tm];if(e){this.#t=e,this[Em]();return}this.#t=t instanceof Response$1?t.#t:t,n=new Headers(t.headers)}else this.#t=t;(e==null||typeof e==`string`||e?.getReader!==void 0||e instanceof Blob||e instanceof Uint8Array)&&(this[Dm]=[t?.status||200,e??null,n||t?.headers])}get headers(){let e=this[Dm];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":wm}))),e[2]):this[Em]().headers}get status(){return this[Dm]?.[0]??this[Em]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(km.prototype,e,{get(){return this[Em]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(km.prototype,e,{value:function(){return this[Em]()[e]()}})}),Object.defineProperty(km.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Tm]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(km,Om),Object.setPrototypeOf(km.prototype,Om.prototype);const Am=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,parseRedirectUrl=e=>e instanceof URL?e.href:Am.test(e)?e:new URL(e).href,jm=new Set([301,302,303,307,308]);Object.defineProperty(km,"redirect",{value:function redirect(e,t=302){if(!jm.has(t))throw RangeError(`Invalid status code`);return new km(null,{status:t,headers:{location:parseRedirectUrl(e)}})},writable:!0,configurable:!0}),Object.defineProperty(km,"json",{value:function json(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new km(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,n){let cancel=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,cancel),t.on(`error`,cancel),(n??e.read()).then(flow,handleStreamError),e.closed.finally(()=>{t.off(`close`,cancel),t.off(`error`,cancel)});function handleStreamError(e){e&&t.destroy(e)}function onDrain(){e.read().then(flow,handleStreamError)}function flow({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,onDrain);else return e.read().then(flow,handleStreamError)}catch(e){handleStreamError(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}const buildOutgoingHttpHeaders=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},Mm=Symbol(`outgoingEnded`),Nm=Symbol(`incomingDraining`),drainIncoming=e=>{let t=e;if(e.destroyed||t[Nm])return;if(t[Nm]=!0,e instanceof $n){try{e.stream?.close?.(er.NGHTTP2_NO_ERROR)}catch{}return}let n=0,cleanup=()=>{clearTimeout(r),e.off(`data`,onData),e.off(`end`,cleanup),e.off(`error`,cleanup)},forceClose=()=>{cleanup();let t=e.socket;t&&!t.destroyed&&(typeof t.destroySoon==`function`?t.destroySoon():typeof t.destroy==`function`&&t.destroy())},r=setTimeout(forceClose,500);r.unref?.();let onData=e=>{n+=e.length,n>67108864&&forceClose()};e.on(`data`,onData),e.on(`end`,cleanup),e.on(`error`,cleanup),e.resume()},makeCloseHandler=(e,t,n,r)=>()=>{t.errored?(recordBodyBufferedBeforeDisconnect(t),e[hm](t.errored.toString())):n.writableFinished||(recordBodyBufferedBeforeDisconnect(t),e[hm](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{drainIncoming(t)})})},isImmediateCacheableResponse=e=>{if(!(Dm in e))return!1;let t=e[Dm][1];return t===null||typeof t==`string`||t instanceof Uint8Array},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 n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.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: ${n.message}`),t.destroy(n))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[n,r,i]=e[Dm];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":wm,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":wm,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":wm,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":wm}),flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[Mm]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=buildOutgoingHttpHeaders(i,r===null?void 0:wm);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=buildOutgoingHttpHeaders(e,r===null?void 0:wm)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[Mm]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,n={})=>{if(isPromise(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(handleFetchError)}if(Dm in e)return responseViaCache(e,t);let r=buildOutgoingHttpHeaders(e.headers,e.body===null?void 0:wm);if(e.body){let n=e.body.getReader(),i=[],a=!1,s;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){s||=n.read();let r=await readWithoutBlocking(s).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(s=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(n,t,s))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[Mm]?.()},getRequestListener=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,"Request",{value:Request$1}),Object.defineProperty(global,"Response",{value:km})),async(r,i)=>{let a,s,c=!1,l=!1,ensureCloseHandler=()=>{s&&!l&&(l=!0,i.on(`close`,makeCloseHandler(s,r,i,c)))};try{if(s=newRequest(r,t.hostname),c=n&&r.method!==`GET`&&r.method!==`HEAD`,c&&(r[rm]=!0,r instanceof $n&&(i[Mm]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),i.destroy()})})})),a=e(s,{incoming:r,outgoing:i}),!isPromise(a)&&isImmediateCacheableResponse(a))return c&&!r.readableEnded&&i.once(`finish`,()=>{r.readableEnded||drainIncoming(r)}),responseViaCache(a,i);ensureCloseHandler()}catch(e){if(a)return handleResponseError(e,i);if(t.errorHandler){if(ensureCloseHandler(),a=await t.errorHandler(s?e:toRequestError(e)),!a)return}else a=s?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(a,i,t)}catch(e){return handleResponseError(e,i)}}};globalThis.CloseEvent,globalThis.ErrorEvent;const Pm=Symbol(`CONNECTION_SYMBOL_KEY`),Fm=Symbol(`WAIT_FOR_WEBSOCKET_SYMBOL`),Im=new Set([`connection`,`content-length`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`sec-websocket-accept`,`sec-websocket-extensions`,`sec-websocket-protocol`]),appendResponseHeaders=(e,t)=>{t&&t.forEach((t,n)=>{Im.has(n.toLowerCase())||e.push(`${n}: ${t}`)})},rejectUpgradeRequest=(e,t,n)=>{let r=[`Connection: close`,`Content-Length: 0`];appendResponseHeaders(r,n),e.end(`HTTP/1.1 ${t.toString()} ${Zn[t]??``}\r\n${r.join(`\r
1562
1578
  `)}\r\n\r
1563
- `)},createUpgradeRequest=e=>{let t=e.socket.encrypted?`https`:`http`,n=new URL(e.url??`/`,`${t}://${e.headers.host??`localhost`}`),r=new Headers;for(let t in e.headers){let n=e.headers[t];n&&r.append(t,Array.isArray(n)?n[0]:n)}return new Request(n,{headers:r})},setupWebSocket=e=>{let{server:t,fetchCallback:n,wss:r}=e,i=new Map;r.on(`connection`,(e,t)=>{let n=i.get(t);n&&(n.resolve(e),i.delete(t))});let rejectWaiter=e=>{let t=i.get(e);t&&(i.delete(e),t.reject(Error(`WebSocket handshake aborted`)))},waitForWebSocket=(e,t)=>new Promise((n,r)=>{i.set(e,{resolve:n,reject:r,connectionSymbol:t})});t.on(`upgrade`,async(e,a,s)=>{if(e.headers.upgrade?.toLowerCase()!==`websocket`)return;let c={incoming:e,outgoing:void 0,wss:r,[zm]:waitForWebSocket},l=400,u;try{let t=await n(createUpgradeRequest(e),c);t instanceof Response&&(l=t.status,u=t.headers)}catch{t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,500);return}let f=i.get(e);if(!f||f.connectionSymbol!==c[Rm]){rejectWaiter(e),t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,l,u);return}let addResponseHeaders=e=>{appendResponseHeaders(e,u)},reclaimWaiterOnClose=()=>rejectWaiter(e);a.once(`close`,reclaimWaiterOnClose),r.on(`headers`,addResponseHeaders);try{r.handleUpgrade(e,a,s,t=>{a.off(`close`,reclaimWaiterOnClose),r.emit(`connection`,t,e)})}finally{r.off(`headers`,addResponseHeaders)}}),t.on(`close`,()=>{r.close()})},createAdaptorServer=e=>{let t=e.fetch,n=getRequestListener(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),r=(e.createServer||Zn)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw Error(`WebSocket server must be created with { noServer: true } option`);setupWebSocket({server:r,fetchCallback:t,wss:e.websocket.server})}return r},serve=(e,t)=>{let n=createAdaptorServer(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};async function createHonoApp(e){let t=new Hono;t.use(`*`,cors({origin:`*`,allowHeaders:[`Content-Type`,`mcp-session-id`,`Last-Event-ID`,`mcp-protocol-version`],exposeHeaders:[`mcp-session-id`,`mcp-protocol-version`]})),t.get(`/health`,e=>e.json({status:`ok`}));let n=e();setMcpServerCtx(n);let r=new StreamableHTTPTransport({eventStore:new MemoryEventStore({})});return t.all(`/mcp`,async e=>(n.isConnected()||await n.connect(r),await r.handleRequest(e))),t.notFound(e=>(U.debug(`${e.req.method} ${e.req.url} not found`),e.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not found.`},id:null},{status:404}))),t.onError((e,t)=>(U.error(a(e)),t.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null},{status:500}))),t}async function startServer(e){let{factory:t,port:n}=e,r=await createHonoApp(t);return new Promise((e,t)=>{let i=serve({fetch:r.fetch,hostname:`0.0.0.0`,port:n}).prependOnceListener(`error`,t).prependOnceListener(`listening`,()=>{i.removeListener(`error`,t),e(i.unref())})})}var StreamableLikeC4MCPServer=class{services;_port;server=void 0;constructor(e,t=33335){this.services=e,this._port=t}get mcp(){throw Error(`StreamableLikeC4MCPServer has access to McpServer only during the request`)}get isStarted(){return this.server?.listening===!0}get port(){return this._port}async dispose(){await this.stop()}async start(e=this._port){if(this.server){if(this.port===e)return;await this.stop()}U.info(`Starting MCP server on port {port}`,{port:e}),this._port=e,this.server=await startServer({factory:()=>createMCPServer(this.services),port:e}),U.info(`MCP server ready at http://0.0.0.0:{port}/mcp`,{port:e})}stop(){let e=this.server;return e?(U.info(`Stopping MCP server`),this.server=void 0,setMcpServerCtx(void 0),new Promise(t=>{e.close(e=>{e?U.error(`Failed to stop MCP server`,{err:e}):U.info(`MCP server stopped`),t()})})):(U.info(`MCP server is not running, nothing to stop`),Promise.resolve())}};async function initLikeC4MCP(e){let t=se(e,{workspacePath:`.`,mcp:`stdio`,graphviz:`wasm`,watch:!0,throwIfInvalid:!1,configureLogger:!0});t.configureLogger&&(m({useStdErr:t.mcp===`stdio`,colors:S.isColorSupported&&t.mcp!==`stdio`,logLevel:Mn?`debug`:`info`}),process.on(`uncaughtException`,e=>{U.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{U.error(`unhandledRejection`,{err:e})}));let n=M(t.workspacePath);U.info`Loading LikeC4 from workspace: ${n}`;let r=await x(n,{graphviz:t.graphviz,manualLayouts:!0,configureLogger:!1,watch:t.watch,throwIfInvalid:t.throwIfInvalid}),i=setLanguageServicesCtx(r.languageServices);return{server:t.mcp===`stdio`?new StdioLikeC4MCPServer(i,t.stdio):new StreamableLikeC4MCPServer(i,t.mcp.port),likec4:r}}async function startLikeC4MCP(e){let t=e?.mcp===void 0||e.mcp===`stdio`?e?.stdio?.stdin??process.stdin:void 0,n,r=!1,i=t?t.readableEnded||t.destroyed:!1,a,cleanup=async()=>{let e=n;e&&(a??=(async()=>{try{await e.server.stop()}finally{try{await e.likec4.dispose()}finally{setLanguageServicesCtx(void 0)}}})(),await a)};function stopObservingStdin(){t&&(t.off(`end`,onStdinClosed),t.off(`close`,onStdinClosed))}function onStdinClosed(){i=!0,stopObservingStdin(),r&&cleanup().catch(e=>{U.error(`Failed to stop MCP stdio server after stdin closed`,{err:e})})}t&&!i&&(t.once(`end`,onStdinClosed),t.once(`close`,onStdinClosed),i=t.readableEnded||t.destroyed);try{if(n=await initLikeC4MCP(e),n.server instanceof StdioLikeC4MCPServer){if(i)return stopObservingStdin(),await cleanup(),n;await n.server.start(),r=!0,i&&await cleanup()}else await n.server.start();return n}catch(e){if(stopObservingStdin(),n)try{await cleanup()}catch(e){U.error(`Failed to clean up MCP stdio server after start error`,{err:e})}throw e}}const mcpCmd=e=>e.command({command:`mcp [path]`,aliases:[],describe:`Start MCP server`,builder:e=>e.usage(`${S.bold(`Usage:`)} $0 mcp [path]`).positional(`path`,B).option(`stdio`,{boolean:!0,description:`use stdio transport`,conflicts:[`http`,`port`]}).option(`http`,{boolean:!0,description:`use streamable http transport (use 33335 port by default)`,conflicts:`stdio`}).option(`port`,{alias:`p`,number:!0,description:`enables http transport and sets the port`,conflicts:`stdio`}).option(`use-dot`,js).option(`log-level`,Ks).option(`verbose`,qs).showHidden().epilog(`${S.bold(`Examples:`)}
1579
+ `)},createUpgradeRequest=e=>{let t=e.socket.encrypted?`https`:`http`,n=new URL(e.url??`/`,`${t}://${e.headers.host??`localhost`}`),r=new Headers;for(let t in e.headers){let n=e.headers[t];n&&r.append(t,Array.isArray(n)?n[0]:n)}return new Request(n,{headers:r})},setupWebSocket=e=>{let{server:t,fetchCallback:n,wss:r}=e,i=new Map;r.on(`connection`,(e,t)=>{let n=i.get(t);n&&(n.resolve(e),i.delete(t))});let rejectWaiter=e=>{let t=i.get(e);t&&(i.delete(e),t.reject(Error(`WebSocket handshake aborted`)))},waitForWebSocket=(e,t)=>new Promise((n,r)=>{i.set(e,{resolve:n,reject:r,connectionSymbol:t})});t.on(`upgrade`,async(e,a,s)=>{if(e.headers.upgrade?.toLowerCase()!==`websocket`)return;let c={incoming:e,outgoing:void 0,wss:r,[Fm]:waitForWebSocket},l=400,u;try{let t=await n(createUpgradeRequest(e),c);t instanceof Response&&(l=t.status,u=t.headers)}catch{t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,500);return}let f=i.get(e);if(!f||f.connectionSymbol!==c[Pm]){rejectWaiter(e),t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,l,u);return}let addResponseHeaders=e=>{appendResponseHeaders(e,u)},reclaimWaiterOnClose=()=>rejectWaiter(e);a.once(`close`,reclaimWaiterOnClose),r.on(`headers`,addResponseHeaders);try{r.handleUpgrade(e,a,s,t=>{a.off(`close`,reclaimWaiterOnClose),r.emit(`connection`,t,e)})}finally{r.off(`headers`,addResponseHeaders)}}),t.on(`close`,()=>{r.close()})},createAdaptorServer=e=>{let t=e.fetch,n=getRequestListener(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),r=(e.createServer||Qn)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw Error(`WebSocket server must be created with { noServer: true } option`);setupWebSocket({server:r,fetchCallback:t,wss:e.websocket.server})}return r},serve=(e,t)=>{let n=createAdaptorServer(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};async function createHonoApp(e){let t=new Hono;t.use(`*`,cors({origin:`*`,allowHeaders:[`Content-Type`,`mcp-session-id`,`Last-Event-ID`,`mcp-protocol-version`],exposeHeaders:[`mcp-session-id`,`mcp-protocol-version`]})),t.get(`/health`,e=>e.json({status:`ok`}));let n=e();setMcpServerCtx(n);let r=new StreamableHTTPTransport({eventStore:new MemoryEventStore({})});return t.all(`/mcp`,async e=>(n.isConnected()||await n.connect(r),await r.handleRequest(e))),t.notFound(e=>(q.debug(`${e.req.method} ${e.req.url} not found`),e.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not found.`},id:null},{status:404}))),t.onError((e,t)=>(q.error(a(e)),t.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null},{status:500}))),t}async function startServer(e){let{factory:t,port:n}=e,r=await createHonoApp(t);return new Promise((e,t)=>{let i=serve({fetch:r.fetch,hostname:`0.0.0.0`,port:n}).prependOnceListener(`error`,t).prependOnceListener(`listening`,()=>{i.removeListener(`error`,t),e(i.unref())})})}var StreamableLikeC4MCPServer=class{services;_port;server=void 0;constructor(e,t=33335){this.services=e,this._port=t}get mcp(){throw Error(`StreamableLikeC4MCPServer has access to McpServer only during the request`)}get isStarted(){return this.server?.listening===!0}get port(){return this._port}async dispose(){await this.stop()}async start(e=this._port){if(this.server){if(this.port===e)return;await this.stop()}q.info(`Starting MCP server on port {port}`,{port:e}),this._port=e,this.server=await startServer({factory:()=>createMCPServer(this.services),port:e}),q.info(`MCP server ready at http://0.0.0.0:{port}/mcp`,{port:e})}stop(){let e=this.server;return e?(q.info(`Stopping MCP server`),this.server=void 0,setMcpServerCtx(void 0),new Promise(t=>{e.close(e=>{e?q.error(`Failed to stop MCP server`,{err:e}):q.info(`MCP server stopped`),t()})})):(q.info(`MCP server is not running, nothing to stop`),Promise.resolve())}};async function initLikeC4MCP(e){let t=se(e,{workspacePath:`.`,mcp:`stdio`,graphviz:`wasm`,watch:!0,throwIfInvalid:!1,configureLogger:!0});t.configureLogger&&(m({useStdErr:t.mcp===`stdio`,colors:S.isColorSupported&&t.mcp!==`stdio`,logLevel:Nn?`debug`:`info`}),process.on(`uncaughtException`,e=>{q.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{q.error(`unhandledRejection`,{err:e})}));let n=P(t.workspacePath);q.info`Loading LikeC4 from workspace: ${n}`;let r=await x(n,{graphviz:t.graphviz,manualLayouts:!0,configureLogger:!1,watch:t.watch,throwIfInvalid:t.throwIfInvalid}),i=setLanguageServicesCtx(r.languageServices);return{server:t.mcp===`stdio`?new StdioLikeC4MCPServer(i,t.stdio):new StreamableLikeC4MCPServer(i,t.mcp.port),likec4:r}}async function startLikeC4MCP(e){let t=e?.mcp===void 0||e.mcp===`stdio`?e?.stdio?.stdin??process.stdin:void 0,n,r=!1,i=t?t.readableEnded||t.destroyed:!1,a,cleanup=async()=>{let e=n;e&&(a??=(async()=>{try{await e.server.stop()}finally{try{await e.likec4.dispose()}finally{setLanguageServicesCtx(void 0)}}})(),await a)};function stopObservingStdin(){t&&(t.off(`end`,onStdinClosed),t.off(`close`,onStdinClosed))}function onStdinClosed(){i=!0,stopObservingStdin(),r&&cleanup().catch(e=>{q.error(`Failed to stop MCP stdio server after stdin closed`,{err:e})})}t&&!i&&(t.once(`end`,onStdinClosed),t.once(`close`,onStdinClosed),i=t.readableEnded||t.destroyed);try{if(n=await initLikeC4MCP(e),n.server instanceof StdioLikeC4MCPServer){if(i)return stopObservingStdin(),await cleanup(),n;await n.server.start(),r=!0,i&&await cleanup()}else await n.server.start();return n}catch(e){if(stopObservingStdin(),n)try{await cleanup()}catch(e){q.error(`Failed to clean up MCP stdio server after start error`,{err:e})}throw e}}const mcpCmd=e=>e.command({command:`mcp [path]`,aliases:[],describe:`Start MCP server`,builder:e=>e.usage(`${S.bold(`Usage:`)} $0 mcp [path]`).positional(`path`,U).option(`stdio`,{boolean:!0,description:`use stdio transport`,conflicts:[`http`,`port`]}).option(`http`,{boolean:!0,description:`use streamable http transport (use 33335 port by default)`,conflicts:`stdio`}).option(`port`,{alias:`p`,number:!0,description:`enables http transport and sets the port`,conflicts:`stdio`}).option(`use-dot`,W).option(`log-level`,Gs).option(`verbose`,Ks).showHidden().epilog(`${S.bold(`Examples:`)}
1564
1580
  ${S.green(`$0 mcp`)}
1565
1581
  ${S.gray(`Start MCP with default stdio transport`)}
1566
1582
  ${S.green(`$0 mcp --http ./src`)}
1567
1583
  ${S.gray(`Start MCP with streamable http transport on port 33335 at ./src folder`)}
1568
1584
  ${S.green(`$0 mcp -p 1234`)}
1569
1585
  ${S.gray(`Start MCP with streamable http transport on port 1234`)}
1570
- `),handler:async e=>{e.http||e.port?(m({colors:S.isColorSupported,logLevel:e.verbose?Js:e.logLevel}),await startHttpMcp(e.path,e.useDot,e.port)):(m({useStdErr:!0,colors:!1,logLevel:e.verbose?Js:e.logLevel}),await startStdioMcp(e.path,e.useDot))}});async function startHttpMcp(e,t,n=33335){await startLikeC4MCP({workspacePath:e,mcp:{port:n},watch:!0,configureLogger:!1,graphviz:t?`binary`:`wasm`}),boxen([S.green(`LikeC4 MCP served at:`),`
1586
+ `),handler:async e=>{e.http||e.port?(m({colors:S.isColorSupported,logLevel:e.verbose?qs:e.logLevel}),await startHttpMcp(e.path,e.useDot,e.port)):(m({useStdErr:!0,colors:!1,logLevel:e.verbose?qs:e.logLevel}),await startStdioMcp(e.path,e.useDot))}});async function startHttpMcp(e,t,n=33335){await startLikeC4MCP({workspacePath:e,mcp:{port:n},watch:!0,configureLogger:!1,graphviz:t?`binary`:`wasm`}),boxen([S.green(`LikeC4 MCP served at:`),`
1571
1587
  {
1572
1588
  "mcpServers": {
1573
1589
  "likec4": {
@@ -1579,10 +1595,10 @@ ${S.green(`$0 mcp -p 1234`)}
1579
1595
  ${S.dim(`Documentation:`)}
1580
1596
  ${S.underline(`https://likec4.dev/tooling/mcp/#using-extension`)}
1581
1597
  `].join(`
1582
- `))}async function startStdioMcp(e,t){await startLikeC4MCP({workspacePath:e,mcp:`stdio`,watch:!0,configureLogger:!1,graphviz:t?`binary`:`wasm`})}async function vitePreview(e){let t=await viteConfig({...e,likec4AssetsDir:``,webcomponentPrefix:void 0}),n=await getPorts({port:portNumbers(62001,62010)}),r=e?.open??!1;return await Gn({...t,customLogger:t.customLogger,mode:`production`,preview:{host:e.listen??`127.0.0.1`,allowedHosts:!0,port:n,open:r}})}async function handler$1({path:e,output:t,base:n,listen:r}){printServerUrls(await vitePreview({base:n,languageServices:await x(e,{watch:!1}),outputDir:t,open:!isInsideContainer(),listen:r}))}t(handler$1,`handler`);const previewCmd=e=>e.command({command:`preview [path]`,describe:`Start local server to preview production build`,builder:e=>e.positional(`path`,{type:`string`,desc:`Directory with LikeC4 source files
1583
- if not specified search in current directory`,normalize:!0}).options({output:{alias:`o`,type:`string`,desc:`output directory from production build`,normalize:!0},base:{type:`string`,desc:`base url the app is being served from`},listen:{alias:`l`,type:`string`,desc:`ip address of the network interface to listen on`}}).coerce([`path`,`output`],M).default(`path`,M(`.`),`.`).default(`listen`,`127.0.0.1`,`localhost`),handler:async e=>{await handler$1(e)}}),Vm=`icon`;function collectFileIcons(e){let t=new Set,visit=e=>{if(Array.isArray(e)){for(let t of e)visit(t);return}if(!(typeof e!=`object`||!e))for(let[n,r]of Object.entries(e)){if(n===Vm&&typeof r==`string`){r.startsWith(`file://`)&&t.add(r);continue}visit(r)}};return visit(e),t}function rewriteFileIcons(e,t){if(t.size===0)return e;let visit=e=>{if(Array.isArray(e)){let t=!1,n=e.map(e=>{let n=visit(e);return t||=n!==e,n});return t?n:e}if(typeof e!=`object`||!e)return e;let n=!1,r={};for(let[i,a]of Object.entries(e)){let e=i===Vm&&typeof a==`string`?t.get(a)??a:visit(a);n||=e!==a,r[i]=e}return n?r:e};return visit(e)}var AssetError=class extends Error{constructor(e,t){super(e,t),this.name=`AssetError`}};function toFilePath(e){try{let t=new URL(e);if(t.protocol===`file:`&&t.hostname!==``&&t.hostname!==`localhost`)throw Error(`unsupported file url host "${t.hostname}"`);return On(t)}catch(t){throw new AssetError(`Icon "${e}" is not a local file path`,{cause:t})}}async function readAsset(e){let t=toFilePath(e),n;try{n=await Rt(t)}catch(e){let n=e.code;throw new AssetError(n===`ENOENT`?`Icon file "${t}" does not exist`:`Icon file "${t}" could not be read (${n??`unknown error`})`,{cause:e})}if(n.byteLength>1048576)throw new AssetError(`Icon file "${t}" is ${n.byteLength} bytes, over the 1048576 bytes per-asset limit`);return{path:t,content:n}}async function collectAssets({projects:e,force:t,logger:n}){let r={},i=new Map,a=new Set,s=0,c=0,l=[];for(let u of e){for(let e of collectFileIcons(u.data))if(!(i.has(e)||a.has(e)))try{let{path:t,content:n}=await readAsset(e),a=Tn(`sha256`).update(n).digest(`hex`);if(!Object.hasOwn(r,a)){if(c>=200)throw new AssetError(`Too many icon files: at most 200 per publish, "${t}" is over the limit`);if(s+n.byteLength>10485760)throw new AssetError(`Icon files exceed the 10485760 bytes total limit, "${t}" is over it`);r[a]={filename:Wt(t),bytes:n.toString(`base64`)},s+=n.byteLength,c++}i.set(e,`asset://${a}`)}catch(r){if(!t)throw r instanceof AssetError?new AssetError(`${r.message}\nReferenced by project "${u.name}". Pass --force to skip it and publish anyway.`,{cause:r.cause}):r;a.add(e),n.warn(S.yellow(`${r instanceof Error?r.message:String(r)}\nReferenced by project "${u.name}" - skipping it, the icon will not render.`))}l.push({...u,data:rewriteFileIcons(u.data,i)})}return{projects:l,assets:r,totalBytes:s}}function createGitRunner(e,t=pn){return async n=>{let{stdout:r}=await t(`git`,n,{cwd:e});return r.trim()}}function nonEmpty(e){if(e==null)return null;let t=e.trim();return t===``?null:t}const Hm=/^[a-z][a-z0-9+.-]*:\/\//i,Um=/^(?:[^@/]+@)?([^@/:]+):(.+)$/,Wm=new Set([`.`,`..`]);function parseGitOrigin(e){let t=e.trim();if(t===``)return null;let n;switch(!0){case Hm.test(t):try{n=new URL(t).pathname}catch{return null}break;default:{let e=Um.exec(t);if(!e)return null;n=e[2]??``}}let r=n.split(`/`).filter(e=>e!==``);if(r.length!==2)return null;let i=r[0],a=r[1].replace(/\.git$/,``);return a===``||Wm.has(i)||Wm.has(a)?null:`${i}/${a}`}function parseCommit(e){let t=e.replace(/\r?\n+$/,``).split(`\0`);if(t.length<4)throw Error(`Unexpected "git log" output: ${JSON.stringify(e)}`);let n=t[0],r=t[1],i=t[2],a=t.slice(3).join(`\0`),s=new Date(i);if(Number.isNaN(s.getTime()))throw Error(`Unexpected commit date from git: ${JSON.stringify(i)}`);return{message:a,author:n,email:r,date:s.toISOString()}}function resolveBranch(e,t){let n=nonEmpty(e.GITHUB_HEAD_REF);if(n!==null)return n;if(e.GITHUB_REF_TYPE===`branch`){let t=nonEmpty(e.GITHUB_REF_NAME);if(t!==null)return t}return nonEmpty(t)}function resolveTag(e,t){if(e.GITHUB_REF_TYPE===`tag`){let t=nonEmpty(e.GITHUB_REF_NAME);if(t!==null)return t}return nonEmpty(t)}const Gm=`Run "likec4 publish" inside a git repository, or pass both --origin and --sha explicitly.`;async function softRun(e,t){try{return nonEmpty(await e(t))}catch{return null}}async function readGitProvenance({runner:e,env:t,overrides:n={}}){let r=nonEmpty(n.origin),i=nonEmpty(n.sha),a=r!==null&&i!==null,s=null;try{s=nonEmpty(await e([`rev-parse`,`--show-toplevel`]))}catch(e){if(!a)throw Error(`Failed to read git repository. ${Gm}`,{cause:e})}if(s===null){if(!a)throw Error(`Failed to resolve the git repository root. ${Gm}`);return{origin:r,sha:i,branch:nonEmpty(n.branch)??resolveBranch(t,null),tag:nonEmpty(n.tag)??resolveTag(t,null),commit:unknownCommit(),root:``,dirty:null}}let c=r??await readOrigin(e),l=i??await readSha(e),u=await readCommit(e,i!==null),f=await softRun(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`]),p=nonEmpty(n.branch)??resolveBranch(t,f),m=firstLine(await softRun(e,[`tag`,`--points-at`,`HEAD`])),h=nonEmpty(n.tag)??resolveTag(t,m),g=await readDirty(e);return{origin:c,sha:l,branch:p,tag:h,commit:u,root:s,dirty:g}}function firstLine(e){return e===null?null:nonEmpty(e.split(`
1584
- `)[0])}function unknownCommit(){return{message:``,author:``,email:``,date:new Date().toISOString()}}async function readOrigin(e){let t;try{t=await e([`remote`,`get-url`,`origin`])}catch(e){throw Error(`No "origin" remote found in this repository. Pass --origin "owner/repo" explicitly.`,{cause:e})}let n=parseGitOrigin(t);if(n===null)throw Error(`Cannot derive "owner/repo" from the origin remote "${t}". Pass --origin "owner/repo" explicitly.`);return n}async function readSha(e){let t;try{t=nonEmpty(await e([`rev-parse`,`HEAD`]))}catch(e){throw Error(`Failed to resolve the current commit. ${Gm}`,{cause:e})}if(t===null)throw Error(`Failed to resolve the current commit. ${Gm}`);return t}async function readDirty(e){try{return await e([`status`,`--porcelain`])!==``}catch{return null}}async function readCommit(e,t){try{return parseCommit(await e([`log`,`-1`,`--format=%an%x00%ae%x00%aI%x00%s`]))}catch(e){if(t)return unknownCommit();throw Error(`Failed to read the current commit. ${Gm}`,{cause:e})}}const Km=/^(?:\/|[a-zA-Z]:\/)/,qm={relative:Yt};function toWorkspacePath(e,t,n=qm){let r=n.relative(e,t).replaceAll(`\\`,`/`);if(r===``)return`.`;if(r===`..`||r.startsWith(`../`)||Km.test(r))throw Error(`Project folder "${t}" is outside the git root "${e}", cannot publish it`);return r}function buildPublishPayload({provenance:e,projects:t,assets:n}){let r={},i=new Map;for(let n of t){let t=toWorkspacePath(e.root,n.folder),a=i.get(t);if(a!==void 0)throw Error(`Projects "${a}" and "${n.name}" resolve to the same workspace path "${t}"`);i.set(t,n.name),r[t]=n.data}let a={origin:e.origin,branch:e.branch,tag:e.tag,sha:e.sha,commit:e.commit,projects:r};return n&&Object.keys(n).length>0&&(a.assets=n),a}const Jm=`LIKEC4_PUBLISH_TOKEN`;function resolveToken(e){let t=e?.trim()||An[Jm]?.trim();if(!t)throw Error(`No publish token provided, pass --token or set the ${Jm} environment variable`);return t}function resolveBaseUrl(e){return(e?.trim()||An.LIKEC4_CLOUD_URL?.trim()||`https://likec4.app`).replace(/\/+$/,``)}function humanSize(e){return`${(e/1024).toFixed(1)} KB`}function toPhysicalPath(e){let t=M(e),n=t,r=[];for(;;)try{return Jt(bn(n),...r.reverse())}catch{let e=Gt(n);if(e===n)return t;r.push(Wt(n)),n=e}}function isEmptyModel(e){return Object.values(e.$data.views).every(e=>e.nodes.length===0)}function explainResolvedSymlinks(e,t){if(t.size===0||!(e instanceof Error))return e;let n=[...t].map(([e,t])=>` "${t}" -> "${e}"`);return Error(`${e.message}\nSymlinked paths were resolved to their real location before comparing:\n`+n.join(`
1585
- `),{cause:e})}function selectProjects(e,t){let n=[...new Set(e.projectsManager.all)],r=new Set(e.languageServices.projects().map(e=>e.id)),i=n.filter(e=>e!=="default"||r.has(e)||n.length===1),a=n.filter(e=>!i.includes(e));return a.length>0&&t.debug(`skipping synthetic empty project(s): ${a.join(`, `)}`),i.map(t=>({id:t,folder:e.projectsManager.getProject(t).folderUri.fsPath}))}async function publishHandler(e){try{var t=_usingCtx();let n=createLikeC4Logger(`c4:publish`),r=startTimer(n),i=resolveToken(e.token),s=resolveBaseUrl(e.url),c={};e.origin&&(c.origin=e.origin),e.sha&&(c.sha=e.sha),e.branch&&(c.branch=e.branch),e.tag&&(c.tag=e.tag);let l=new Map,u=M(e.path),f=await readGitProvenance({runner:createGitRunner(u),env:An,overrides:c}),p=toPhysicalPath(f.root||u);switch(n.info(`${S.dim(`origin:`)} ${S.green(f.origin)}`),n.info(`${S.dim(`commit:`)} ${S.green(f.sha)}`),n.info(`${S.dim(`branch:`)} ${f.branch?S.green(f.branch):S.dim(`(none)`)}`),f.tag&&n.info(`${S.dim(`tag:`)} ${S.green(f.tag)}`),f.dirty){case!0:n.warn(S.yellow(`Working tree is DIRTY - publishing anyway. The snapshot is keyed by commit sha, so it will not match the sources you are publishing.`));break;case null:f.root&&n.warn(S.yellow(`Could not determine whether the working tree is clean - if it is not, the snapshot is keyed by a commit sha that does not match the sources you are publishing.`))}f.branch||n.warn(S.yellow(`No branch resolved - the snapshot will not be branch-addressable. Pass --branch to set it explicitly.`)),f.root||n.warn(S.yellow(`No git repository detected - project paths will be relative to ${p}`)),f.commit.author===``&&f.commit.message===``&&n.warn(S.yellow(`No commit metadata available - publishing with an empty commit author, email and message.`));let m=t.a(await x(u,{throwIfInvalid:!e.force,printErrors:!0,graphviz:e.useDotBin?`binary`:`wasm`,watch:!1})),h;if(e.project){let{projectId:t,projectFolder:r}=ensureProject(m,e.project);h=[{id:t,folder:r}],n.info(`${S.dim(`project:`)} ${S.green(t)}`)}else h=selectProjects(m,n),n.info(`${S.dim(`workspace:`)} Found ${h.length} projects`);let g=[];for(let{id:e,folder:t}of h)try{n.info(`Generating layouted model for project ${S.green(e)}`);let r=await m.layoutedModel(e);if(isEmptyModel(r)){n.warn(S.yellow(`Project ${e} is empty, skipping`));continue}let i=toPhysicalPath(t);i!==t&&l.set(i,t),g.push({name:e,folder:i,data:r.$data})}catch(t){n.error(a(t)),n.warn(`Skipping project ${S.red(e)}`)}if(g.length===0)throw Error(`Nothing to publish; all projects are empty or were skipped`);let v=await collectAssets({projects:g,force:e.force,logger:n}),y;try{y=buildPublishPayload({provenance:{...f,root:p},projects:v.projects,assets:v.assets})}catch(e){throw explainResolvedSymlinks(e,l)}let b=JSON.stringify(y),ee=new Uint8Array(tr(b));n.info(`${S.dim(`payload:`)} ${humanSize(Buffer.byteLength(b))} ${S.dim(`→`)} ${humanSize(ee.byteLength)} ${S.dim(`gzipped`)}`);let te=Object.keys(v.assets).length;te>0&&n.info(`${S.dim(`assets:`)} ${te} ${S.dim(`file(s),`)} ${humanSize(v.totalBytes)}`);let ne=`${s}/api/publish`;n.info(`${S.dim(`publishing to`)} ${S.green(ne)}`);let re;try{re=await xi.post(ne,{body:ee,headers:{"X-Publish-Token":i,"Content-Type":`application/json`,"Content-Encoding":`gzip`},retry:{limit:3,retryOnTimeout:!0,methods:[`post`],statusCodes:[429,500,502,503,504]},timeout:12e4}).json()}catch(e){if(e instanceof HTTPError){let t=``;try{t=await e.response.text()}catch{}n.error(S.red(`Publish failed: HTTP ${e.response.status} ${e.response.statusText}`)),t.trim().length>0&&n.error(t),process.exitCode=1;return}throw e}n.info(`${S.dim(`snapshot:`)} ${S.green(re.snapshotId)}`),n.info(`${S.dim(`view at`)} ${S.underline(S.green(re.url))}`),r.stopAndLog(`✓ published in `)}catch(e){t.e=e}finally{await t.d()}}function publishCmd(e){return e.command({command:`publish [path]`,describe:`publish model(s) to LikeC4 Cloud`,builder:e=>e.positional(`path`,B).options({token:{string:!0,desc:`publish token (env: LIKEC4_PUBLISH_TOKEN)`,nargs:1},url:{string:!0,desc:`cloud base url (env: LIKEC4_CLOUD_URL, default https://likec4.app)`,nargs:1},project:{...Gs,desc:`publish a single project by name or path`},origin:{string:!0,desc:`override "owner/repo" (default: derived from git remote origin)`,nargs:1},sha:{string:!0,desc:`override commit sha (default: git HEAD)`,nargs:1},branch:{string:!0,desc:`override branch (default: CI env, then git)`,nargs:1},tag:{string:!0,desc:`override tag (default: CI env, then git tag --points-at HEAD)`,nargs:1},force:{boolean:!0,desc:`publish even if the model has validation errors or an icon file cannot be read`},"use-dot":js}).epilog(`${S.bold(`Notes:`)}
1598
+ `))}async function startStdioMcp(e,t){await startLikeC4MCP({workspacePath:e,mcp:`stdio`,watch:!0,configureLogger:!1,graphviz:t?`binary`:`wasm`})}async function vitePreview(e){let t=await viteConfig({...e,likec4AssetsDir:``,webcomponentPrefix:void 0}),n=await getPorts({port:portNumbers(62001,62010)}),r=e?.open??!1;return await Kn({...t,customLogger:t.customLogger,mode:`production`,preview:{host:e.listen??`127.0.0.1`,allowedHosts:!0,port:n,open:r}})}async function handler$1({path:e,output:t,base:n,listen:r}){printServerUrls(await vitePreview({base:n,languageServices:await x(e,{watch:!1}),outputDir:t,open:!isInsideContainer(),listen:r}))}t(handler$1,`handler`);const previewCmd=e=>e.command({command:`preview [path]`,describe:`Start local server to preview production build`,builder:e=>e.positional(`path`,{type:`string`,desc:`Directory with LikeC4 source files
1599
+ if not specified search in current directory`,normalize:!0}).options({output:{alias:`o`,type:`string`,desc:`output directory from production build`,normalize:!0},base:{type:`string`,desc:`base url the app is being served from`},listen:{alias:`l`,type:`string`,desc:`ip address of the network interface to listen on`}}).coerce([`path`,`output`],P).default(`path`,P(`.`),`.`).default(`listen`,`127.0.0.1`,`localhost`),handler:async e=>{await handler$1(e)}}),Lm=`icon`;function collectFileIcons(e){let t=new Set,visit=e=>{if(Array.isArray(e)){for(let t of e)visit(t);return}if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e)){if(n===Lm&&typeof r==`string`){r.startsWith(`file://`)&&t.add(r);continue}visit(r)}};return visit(e),t}function rewriteFileIcons(e,t){if(t.size===0)return e;let visit=e=>{if(Array.isArray(e)){let t=!1,n=e.map(e=>{let n=visit(e);return t||=n!==e,n});return t?n:e}if(typeof e!=`object`||!e)return e;let n=!1,r={};for(let[i,a]of Object.entries(e)){let e=i===Lm&&typeof a==`string`?t.get(a)??a:visit(a);n||=e!==a,r[i]=e}return n?r:e};return visit(e)}var AssetError=class extends Error{constructor(e,t){super(e,t),this.name=`AssetError`}};function toFilePath(e){try{let t=new URL(e);if(t.protocol===`file:`&&t.hostname!==``&&t.hostname!==`localhost`)throw Error(`unsupported file url host "${t.hostname}"`);return kn(t)}catch(t){throw new AssetError(`Icon "${e}" is not a local file path`,{cause:t})}}async function readAsset(e){let t=toFilePath(e),n;try{n=await It(t)}catch(e){let n=e.code;throw new AssetError(n===`ENOENT`?`Icon file "${t}" does not exist`:`Icon file "${t}" could not be read (${n??`unknown error`})`,{cause:e})}if(n.byteLength>1048576)throw new AssetError(`Icon file "${t}" is ${n.byteLength} bytes, over the 1048576 bytes per-asset limit`);return{path:t,content:n}}async function collectAssets({projects:e,force:t,logger:n}){let r={},i=new Map,a=new Set,s=0,c=0,l=[];for(let u of e){for(let e of collectFileIcons(u.data))if(!(i.has(e)||a.has(e)))try{let{path:t,content:n}=await readAsset(e),a=En(`sha256`).update(n).digest(`hex`);if(!Object.hasOwn(r,a)){if(c>=200)throw new AssetError(`Too many icon files: at most 200 per publish, "${t}" is over the limit`);if(s+n.byteLength>10485760)throw new AssetError(`Icon files exceed the 10485760 bytes total limit, "${t}" is over it`);r[a]={filename:Ht(t),bytes:n.toString(`base64`)},s+=n.byteLength,c++}i.set(e,`asset://${a}`)}catch(r){if(!t)throw r instanceof AssetError?new AssetError(`${r.message}\nReferenced by project "${u.name}". Pass --force to skip it and publish anyway.`,{cause:r.cause}):r;a.add(e),n.warn(S.yellow(`${r instanceof Error?r.message:String(r)}\nReferenced by project "${u.name}" - skipping it, the icon will not render.`))}l.push({...u,data:rewriteFileIcons(u.data,i)})}return{projects:l,assets:r,totalBytes:s}}function createGitRunner(e,t=mn){return async n=>{let{stdout:r}=await t(`git`,n,{cwd:e});return r.trim()}}function nonEmpty(e){if(e==null)return null;let t=e.trim();return t===``?null:t}const Rm=/^[a-z][a-z0-9+.-]*:\/\//i,zm=/^(?:[^@/]+@)?([^@/:]+):(.+)$/,Bm=new Set([`.`,`..`]);function parseGitOrigin(e){let t=e.trim();if(t===``)return null;let n;switch(!0){case Rm.test(t):try{n=new URL(t).pathname}catch{return null}break;default:{let e=zm.exec(t);if(!e)return null;n=e[2]??``}}let r=n.split(`/`).filter(e=>e!==``);if(r.length!==2)return null;let i=r[0],a=r[1].replace(/\.git$/,``);return a===``||Bm.has(i)||Bm.has(a)?null:`${i}/${a}`}function parseCommit(e){let t=e.replace(/\r?\n+$/,``).split(`\0`);if(t.length<4)throw Error(`Unexpected "git log" output: ${JSON.stringify(e)}`);let n=t[0],r=t[1],i=t[2],a=t.slice(3).join(`\0`),s=new Date(i);if(Number.isNaN(s.getTime()))throw Error(`Unexpected commit date from git: ${JSON.stringify(i)}`);return{message:a,author:n,email:r,date:s.toISOString()}}function resolveBranch(e,t){let n=nonEmpty(e.GITHUB_HEAD_REF);if(n!==null)return n;if(e.GITHUB_REF_TYPE===`branch`){let t=nonEmpty(e.GITHUB_REF_NAME);if(t!==null)return t}return nonEmpty(t)}function resolveTag(e,t){if(e.GITHUB_REF_TYPE===`tag`){let t=nonEmpty(e.GITHUB_REF_NAME);if(t!==null)return t}return nonEmpty(t)}const Vm=`Run "likec4 publish" inside a git repository, or pass both --origin and --sha explicitly.`;async function softRun(e,t){try{return nonEmpty(await e(t))}catch{return null}}async function readGitProvenance({runner:e,env:t,overrides:n={}}){let r=nonEmpty(n.origin),i=nonEmpty(n.sha),a=r!==null&&i!==null,s=null;try{s=nonEmpty(await e([`rev-parse`,`--show-toplevel`]))}catch(e){if(!a)throw Error(`Failed to read git repository. ${Vm}`,{cause:e})}if(s===null){if(!a)throw Error(`Failed to resolve the git repository root. ${Vm}`);return{origin:r,sha:i,branch:nonEmpty(n.branch)??resolveBranch(t,null),tag:nonEmpty(n.tag)??resolveTag(t,null),commit:unknownCommit(),root:``,dirty:null}}let c=r??await readOrigin(e),l=i??await readSha(e),u=await readCommit(e,i!==null),f=await softRun(e,[`symbolic-ref`,`--short`,`-q`,`HEAD`]),p=nonEmpty(n.branch)??resolveBranch(t,f),m=firstLine(await softRun(e,[`tag`,`--points-at`,`HEAD`])),h=nonEmpty(n.tag)??resolveTag(t,m),g=await readDirty(e);return{origin:c,sha:l,branch:p,tag:h,commit:u,root:s,dirty:g}}function firstLine(e){return e===null?null:nonEmpty(e.split(`
1600
+ `)[0])}function unknownCommit(){return{message:``,author:``,email:``,date:new Date().toISOString()}}async function readOrigin(e){let t;try{t=await e([`remote`,`get-url`,`origin`])}catch(e){throw Error(`No "origin" remote found in this repository. Pass --origin "owner/repo" explicitly.`,{cause:e})}let n=parseGitOrigin(t);if(n===null)throw Error(`Cannot derive "owner/repo" from the origin remote "${t}". Pass --origin "owner/repo" explicitly.`);return n}async function readSha(e){let t;try{t=nonEmpty(await e([`rev-parse`,`HEAD`]))}catch(e){throw Error(`Failed to resolve the current commit. ${Vm}`,{cause:e})}if(t===null)throw Error(`Failed to resolve the current commit. ${Vm}`);return t}async function readDirty(e){try{return await e([`status`,`--porcelain`])!==``}catch{return null}}async function readCommit(e,t){try{return parseCommit(await e([`log`,`-1`,`--format=%an%x00%ae%x00%aI%x00%s`]))}catch(e){if(t)return unknownCommit();throw Error(`Failed to read the current commit. ${Vm}`,{cause:e})}}const Hm=/^(?:\/|[a-zA-Z]:\/)/,Um={relative:qt};function toWorkspacePath(e,t,n=Um){let r=n.relative(e,t).replaceAll(`\\`,`/`);if(r===``)return`.`;if(r===`..`||r.startsWith(`../`)||Hm.test(r))throw Error(`Project folder "${t}" is outside the git root "${e}", cannot publish it`);return r}function buildPublishPayload({provenance:e,projects:t,assets:n}){let r={},i=new Map;for(let n of t){let t=toWorkspacePath(e.root,n.folder),a=i.get(t);if(a!==void 0)throw Error(`Projects "${a}" and "${n.name}" resolve to the same workspace path "${t}"`);i.set(t,n.name),r[t]=n.data}let a={origin:e.origin,branch:e.branch,tag:e.tag,sha:e.sha,commit:e.commit,projects:r};return n&&Object.keys(n).length>0&&(a.assets=n),a}const Wm=`LIKEC4_PUBLISH_TOKEN`;function resolveToken(e){let t=e?.trim()||jn[Wm]?.trim();if(!t)throw Error(`No publish token provided, pass --token or set the ${Wm} environment variable`);return t}function resolveBaseUrl(e){return(e?.trim()||jn.LIKEC4_CLOUD_URL?.trim()||`https://likec4.app`).replace(/\/+$/,``)}function humanSize(e){return`${(e/1024).toFixed(1)} KB`}function toPhysicalPath(e){let t=P(e),n=t,r=[];for(;;)try{return Kt(xn(n),...r.reverse())}catch{let e=Ut(n);if(e===n)return t;r.push(Ht(n)),n=e}}function isEmptyModel(e){return Object.values(e.$data.views).every(e=>e.nodes.length===0)}function explainResolvedSymlinks(e,t){if(t.size===0||!(e instanceof Error))return e;let n=[...t].map(([e,t])=>` "${t}" -> "${e}"`);return Error(`${e.message}\nSymlinked paths were resolved to their real location before comparing:\n`+n.join(`
1601
+ `),{cause:e})}function selectProjects(e,t){let n=[...new Set(e.projectsManager.all)],r=new Set(e.languageServices.projects().map(e=>e.id)),i=n.filter(e=>e!=="default"||r.has(e)||n.length===1),a=n.filter(e=>!i.includes(e));return a.length>0&&t.debug(`skipping synthetic empty project(s): ${a.join(`, `)}`),i.map(t=>({id:t,folder:e.projectsManager.getProject(t).folderUri.fsPath}))}async function publishHandler(e){try{var t=_usingCtx();let n=createLikeC4Logger(`c4:publish`),r=startTimer(n),i=resolveToken(e.token),s=resolveBaseUrl(e.url),c={};e.origin&&(c.origin=e.origin),e.sha&&(c.sha=e.sha),e.branch&&(c.branch=e.branch),e.tag&&(c.tag=e.tag);let l=new Map,u=P(e.path),f=await readGitProvenance({runner:createGitRunner(u),env:jn,overrides:c}),p=toPhysicalPath(f.root||u);switch(n.info(`${S.dim(`origin:`)} ${S.green(f.origin)}`),n.info(`${S.dim(`commit:`)} ${S.green(f.sha)}`),n.info(`${S.dim(`branch:`)} ${f.branch?S.green(f.branch):S.dim(`(none)`)}`),f.tag&&n.info(`${S.dim(`tag:`)} ${S.green(f.tag)}`),f.dirty){case!0:n.warn(S.yellow(`Working tree is DIRTY - publishing anyway. The snapshot is keyed by commit sha, so it will not match the sources you are publishing.`));break;case null:f.root&&n.warn(S.yellow(`Could not determine whether the working tree is clean - if it is not, the snapshot is keyed by a commit sha that does not match the sources you are publishing.`))}f.branch||n.warn(S.yellow(`No branch resolved - the snapshot will not be branch-addressable. Pass --branch to set it explicitly.`)),f.root||n.warn(S.yellow(`No git repository detected - project paths will be relative to ${p}`)),f.commit.author===``&&f.commit.message===``&&n.warn(S.yellow(`No commit metadata available - publishing with an empty commit author, email and message.`));let m=t.a(await x(u,{throwIfInvalid:!e.force,printErrors:!0,graphviz:e.useDotBin?`binary`:`wasm`,watch:!1})),h;if(e.project){let{projectId:t,projectFolder:r}=ensureProject(m,e.project);h=[{id:t,folder:r}],n.info(`${S.dim(`project:`)} ${S.green(t)}`)}else h=selectProjects(m,n),n.info(`${S.dim(`workspace:`)} Found ${h.length} projects`);let g=[];for(let{id:e,folder:t}of h)try{n.info(`Generating layouted model for project ${S.green(e)}`);let r=await m.layoutedModel(e);if(isEmptyModel(r)){n.warn(S.yellow(`Project ${e} is empty, skipping`));continue}let i=toPhysicalPath(t);i!==t&&l.set(i,t),g.push({name:e,folder:i,data:r.$data})}catch(t){n.error(a(t)),n.warn(`Skipping project ${S.red(e)}`)}if(g.length===0)throw Error(`Nothing to publish; all projects are empty or were skipped`);let v=await collectAssets({projects:g,force:e.force,logger:n}),y;try{y=buildPublishPayload({provenance:{...f,root:p},projects:v.projects,assets:v.assets})}catch(e){throw explainResolvedSymlinks(e,l)}let b=JSON.stringify(y),ee=new Uint8Array(nr(b));n.info(`${S.dim(`payload:`)} ${humanSize(Buffer.byteLength(b))} ${S.dim(`→`)} ${humanSize(ee.byteLength)} ${S.dim(`gzipped`)}`);let te=Object.keys(v.assets).length;te>0&&n.info(`${S.dim(`assets:`)} ${te} ${S.dim(`file(s),`)} ${humanSize(v.totalBytes)}`);let ne=`${s}/api/publish`;n.info(`${S.dim(`publishing to`)} ${S.green(ne)}`);let re;try{re=await xi.post(ne,{body:ee,headers:{"X-Publish-Token":i,"Content-Type":`application/json`,"Content-Encoding":`gzip`},retry:{limit:3,retryOnTimeout:!0,methods:[`post`],statusCodes:[429,500,502,503,504]},timeout:12e4}).json()}catch(e){if(e instanceof HTTPError){let t=``;try{t=await e.response.text()}catch{}n.error(S.red(`Publish failed: HTTP ${e.response.status} ${e.response.statusText}`)),t.trim().length>0&&n.error(t),process.exitCode=1;return}throw e}n.info(`${S.dim(`snapshot:`)} ${S.green(re.snapshotId)}`),n.info(`${S.dim(`view at`)} ${S.underline(S.green(re.url))}`),r.stopAndLog(`✓ published in `)}catch(e){t.e=e}finally{await t.d()}}function publishCmd(e){return e.command({command:`publish [path]`,describe:`publish model(s) to LikeC4 Cloud`,builder:e=>e.positional(`path`,U).options({token:{string:!0,desc:`publish token (env: LIKEC4_PUBLISH_TOKEN)`,nargs:1},url:{string:!0,desc:`cloud base url (env: LIKEC4_CLOUD_URL, default https://likec4.app)`,nargs:1},project:{...Ws,desc:`publish a single project by name or path`},origin:{string:!0,desc:`override "owner/repo" (default: derived from git remote origin)`,nargs:1},sha:{string:!0,desc:`override commit sha (default: git HEAD)`,nargs:1},branch:{string:!0,desc:`override branch (default: CI env, then git)`,nargs:1},tag:{string:!0,desc:`override tag (default: CI env, then git tag --points-at HEAD)`,nargs:1},force:{boolean:!0,desc:`publish even if the model has validation errors or an icon file cannot be read`},"use-dot":W}).epilog(`${S.bold(`Notes:`)}
1586
1602
  ${S.gray(`A snapshot is keyed by commit - publishing the same commit again`)}
1587
1603
  ${S.gray(`OVERWRITES its snapshot. Projects ACCUMULATE into a snapshot,`)}
1588
1604
  ${S.gray(`publishing one project never removes the others.`)}
@@ -1603,7 +1619,7 @@ ${S.bold(`Examples:`)}
1603
1619
  ${S.gray(` env:`)}
1604
1620
  ${S.gray(" LIKEC4_PUBLISH_TOKEN: ${{ secrets.LIKEC4_PUBLISH_TOKEN }}")}
1605
1621
  ${S.gray(`Publish from GitHub Actions (branch and tag come from the workflow env)`)}
1606
- `),handler:async e=>{await publishHandler({path:e.path,token:e.token,url:e.url,project:e.project,origin:e.origin,sha:e.sha,branch:e.branch,tag:e.tag,force:!!e.force,useDotBin:!!e[`use-dot`]})}})}async function handler({path:e,useDotBin:t,webcomponentPrefix:n,title:r,useHashHistory:i,enableWebcomponent:a=!0,enableHMR:s=!0,base:c,listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m}){s&&(process.env.NODE_ENV=`development`);let h=await viteDev({buildWebcomponent:a,hmr:s,base:c,webcomponentPrefix:n,title:r,languageServices:await x(e,{graphviz:t?`binary`:`wasm`,watch:s}),useHashHistory:i,likec4AssetsDir:await Lt(Jt(hn(),`.likec4-assets-`)),listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m});h.config.logger.clearScreen(`info`),printServerUrls(h)}const serveCmd=e=>e.command({command:`start [path]`,aliases:[`serve`,`dev`],describe:`Start local dev server to preview LikeC4 views`,builder:e=>e.positional(`path`,B).option(`base`,Rs).option(`webcomponent-prefix`,Fs).option(`title`,Is).option(`use-hash-history`,Ns).option(`use-dot`,js).option(`listen`,Hs).option(`port`,Us).option(`hmr-port`,Ws).option(`public`,Bs).option(`allowed-host`,Vs).options({"react-hmr":{type:`boolean`,default:!0,describe:`Enable/Disable React HMR`},"build-webcomponent":{type:`boolean`,default:!0,describe:`Enable/Disable Webcomponent build`}}),handler:async e=>{await notifyAvailableUpdate(),setTimeout(showSupportUsMessage,5e3).unref(),await ensureReact(),await handler({path:e.path,useDotBin:e[`use-dot`],base:e.base,webcomponentPrefix:e[`webcomponent-prefix`],title:e.title,useHashHistory:e[`use-hash-history`],listen:e.listen,port:e.port,hmrPort:e[`hmr-port`],enableHMR:e[`react-hmr`],enableWebcomponent:e[`build-webcomponent`],userPublicDir:e.public,allowedHosts:e[`allowed-host`]})}});async function runSyncPlan(e,t,n,r){let i=await planSyncToLeanix(t,n,{idempotent:!0}),a=M(e,`sync-plan.json`);if(await Ut(a,JSON.stringify(i,null,2)),r.info(`${S.dim(`generated`)} ${Yt(process.cwd(),a)}`),i.errors.length>0){let e=`${i.errors.length} plan error(s): ${i.errors.join(`; `)}`;throw r.error(e),Error(e)}}async function runSyncApply(e,t,n,r){let i=await syncToLeanix(t.manifest,t.dryRun,n,{idempotent:!0}),a=M(e,uc.manifest);if(await Ut(a,JSON.stringify(i.manifest,null,2)),r.info(`${S.dim(`generated`)} ${Yt(process.cwd(),a)} (after sync)`),i.errors.length>0){let e=`${i.errors.length} sync error(s): ${i.errors.join(`; `)}`;throw r.error(e),Error(e)}}async function runSyncLeanix(e){let t=createLikeC4Logger(`c4:sync:leanix`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s,dryRun:c,apply:l}=e;try{try{var u=_usingCtx();if(c&&l)throw Error(`Choose either dryRun or apply, not both`);let e=u.a(await x(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${S.dim(`project`)} ${S.green(n)}`);let f=await e.layoutedModel(n);if(f===At.EMPTY)throw t.error(ic),Error(ic);let p=buildBridgeArtifacts(asBridgeModel(f));await writeBridgeArtifacts(i,p,t);let m=createLeanixClientFromEnv();if((c||!l)&&(m?await runSyncPlan(i,p.dryRun,m,t):t.info(`${S.dim(`skip`)} sync-plan (set LEANIX_API_TOKEN to include plan)`)),l){if(!m)throw t.error(ac),Error(ac);await runSyncApply(i,p,m,t)}}catch(e){u.e=e}finally{await u.d()}}finally{n.stopAndLog()}}const Ym=M(process.cwd(),`out`,`bridge`);function isSyncCmdArgs(e){return typeof e!=`object`||!e||!Object.hasOwn(e,`target`)?!1:typeof Reflect.get(e,`target`)==`string`}function syncCmd(e){return e.command({command:`sync <target> [path]`,describe:`Sync bridge artifacts (e.g. LeanIX)`,builder:e=>e.positional(`target`,{type:`string`,choices:[`leanix`],describe:`Target system (leanix)`}).positional(`path`,B).option(`outdir`,{...Ps,default:Ym,desc:`<dir> output directory for bridge artifacts (manifest, leanix-dry-run, report, sync-plan)`}).option(`dry-run`,{type:`boolean`,describe:`Only write artifacts and optional sync-plan; do not call LeanIX API for create/update`}).option(`apply`,{type:`boolean`,describe:`Run live sync to LeanIX (requires LEANIX_API_TOKEN)`}).conflicts(`dry-run`,`apply`).option(`project`,Gs).option(`use-dot`,js).example(`${S.green(`$0 sync leanix --dry-run -o out/bridge`)}`,S.gray(`Write bridge artifacts and optionally sync-plan when LEANIX_API_TOKEN is set`)).example(`${S.green(`$0 sync leanix --apply -o out/bridge`)}`,S.gray(`Write artifacts then run live sync; updates manifest with LeanIX IDs`)),handler:async e=>{if(!isSyncCmdArgs(e)||e.target!==`leanix`)return;let t=e.apply??!1,n=e.dryRun??!t;await runSyncLeanix({path:e.path??`.`,outdir:e.outdir??Ym,project:e.project,useDotBin:e.useDotBin??!1,dryRun:n,apply:t})}})}function matchesFilter(e,t){return t.some(t=>e===t||e.endsWith(`/`+t)||e.endsWith(`\\`+t))}function buildValidateResult({documents:e,errors:t,fileFilter:n}){let r=n?t.filter(e=>matchesFilter(e.file,n)):[...t],i=n?e.filter(e=>matchesFilter(e,n)).length:e.length;return{valid:r.length===0,errors:[...r],stats:{totalFiles:e.length,totalErrors:t.length,filteredFiles:i,filteredErrors:r.length}}}const validateCmd=e=>e.command({command:`validate [path]`,aliases:[],describe:`Validate syntax, semantics and layout drifts`,builder:e=>e.positional(`path`,B).options({project:Gs,file:{alias:`f`,array:!0,string:!0,description:`only report errors from these files (can be specified multiple times)`},layout:{boolean:!0,default:!0,defaultDescription:`enabled`,description:`force layout validation, or disable with --no-layout`},json:{boolean:!0,nargs:0,description:`output as JSON (structured)`}}).showHidden().epilog(`${S.bold(`Examples:`)}
1622
+ `),handler:async e=>{await publishHandler({path:e.path,token:e.token,url:e.url,project:e.project,origin:e.origin,sha:e.sha,branch:e.branch,tag:e.tag,force:!!e.force,useDotBin:!!e[`use-dot`]})}})}async function handler({path:e,useDotBin:t,webcomponentPrefix:n,title:r,useHashHistory:i,enableWebcomponent:a=!0,enableHMR:s=!0,base:c,listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m}){s&&(process.env.NODE_ENV=`development`);let h=await viteDev({buildWebcomponent:a,hmr:s,base:c,webcomponentPrefix:n,title:r,languageServices:await x(e,{graphviz:t?`binary`:`wasm`,watch:s}),useHashHistory:i,likec4AssetsDir:await Ft(Kt(gn(),`.likec4-assets-`)),listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:m});h.config.logger.clearScreen(`info`),printServerUrls(h)}const serveCmd=e=>e.command({command:`start [path]`,aliases:[`serve`,`dev`],describe:`Start local dev server to preview LikeC4 views`,builder:e=>e.positional(`path`,U).option(`base`,Ls).option(`webcomponent-prefix`,Ps).option(`title`,Fs).option(`use-hash-history`,Ms).option(`use-dot`,W).option(`listen`,Vs).option(`port`,Hs).option(`hmr-port`,Us).option(`public`,zs).option(`allowed-host`,Bs).options({"react-hmr":{type:`boolean`,default:!0,describe:`Enable/Disable React HMR`},"build-webcomponent":{type:`boolean`,default:!0,describe:`Enable/Disable Webcomponent build`}}),handler:async e=>{await notifyAvailableUpdate(),setTimeout(showSupportUsMessage,5e3).unref(),await ensureReact(),await handler({path:e.path,useDotBin:e[`use-dot`],base:e.base,webcomponentPrefix:e[`webcomponent-prefix`],title:e.title,useHashHistory:e[`use-hash-history`],listen:e.listen,port:e.port,hmrPort:e[`hmr-port`],enableHMR:e[`react-hmr`],enableWebcomponent:e[`build-webcomponent`],userPublicDir:e.public,allowedHosts:e[`allowed-host`]})}});async function runSyncPlan(e,t,n,r){let i=await planSyncToLeanix(t,n,{idempotent:!0}),a=P(e,`sync-plan.json`);if(await Vt(a,JSON.stringify(i,null,2)),r.info(`${S.dim(`generated`)} ${qt(process.cwd(),a)}`),i.errors.length>0){let e=`${i.errors.length} plan error(s): ${i.errors.join(`; `)}`;throw r.error(e),Error(e)}}async function runSyncApply(e,t,n,r){let i=await syncToLeanix(t.manifest,t.dryRun,n,{idempotent:!0}),a=P(e,lc.manifest);if(await Vt(a,JSON.stringify(i.manifest,null,2)),r.info(`${S.dim(`generated`)} ${qt(process.cwd(),a)} (after sync)`),i.errors.length>0){let e=`${i.errors.length} sync error(s): ${i.errors.join(`; `)}`;throw r.error(e),Error(e)}}async function runSyncLeanix(e){let t=createLikeC4Logger(`c4:sync:leanix`),n=startTimer(t),{path:r,outdir:i,project:a,useDotBin:s,dryRun:c,apply:l}=e;try{try{var u=_usingCtx();if(c&&l)throw Error(`Choose either dryRun or apply, not both`);let e=u.a(await x(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${S.dim(`project`)} ${S.green(n)}`);let f=await e.layoutedModel(n);if(f===Ot.EMPTY)throw t.error(rc),Error(rc);let p=buildBridgeArtifacts(asBridgeModel(f));await writeBridgeArtifacts(i,p,t);let m=createLeanixClientFromEnv();if((c||!l)&&(m?await runSyncPlan(i,p.dryRun,m,t):t.info(`${S.dim(`skip`)} sync-plan (set LEANIX_API_TOKEN to include plan)`)),l){if(!m)throw t.error(ic),Error(ic);await runSyncApply(i,p,m,t)}}catch(e){u.e=e}finally{await u.d()}}finally{n.stopAndLog()}}const Gm=P(process.cwd(),`out`,`bridge`);function isSyncCmdArgs(e){return typeof e!=`object`||!e||!Object.hasOwn(e,`target`)?!1:typeof Reflect.get(e,`target`)==`string`}function syncCmd(e){return e.command({command:`sync <target> [path]`,describe:`Sync bridge artifacts (e.g. LeanIX)`,builder:e=>e.positional(`target`,{type:`string`,choices:[`leanix`],describe:`Target system (leanix)`}).positional(`path`,U).option(`outdir`,{...Ns,default:Gm,desc:`<dir> output directory for bridge artifacts (manifest, leanix-dry-run, report, sync-plan)`}).option(`dry-run`,{type:`boolean`,describe:`Only write artifacts and optional sync-plan; do not call LeanIX API for create/update`}).option(`apply`,{type:`boolean`,describe:`Run live sync to LeanIX (requires LEANIX_API_TOKEN)`}).conflicts(`dry-run`,`apply`).option(`project`,Ws).option(`use-dot`,W).example(`${S.green(`$0 sync leanix --dry-run -o out/bridge`)}`,S.gray(`Write bridge artifacts and optionally sync-plan when LEANIX_API_TOKEN is set`)).example(`${S.green(`$0 sync leanix --apply -o out/bridge`)}`,S.gray(`Write artifacts then run live sync; updates manifest with LeanIX IDs`)),handler:async e=>{if(!isSyncCmdArgs(e)||e.target!==`leanix`)return;let t=e.apply??!1,n=e.dryRun??!t;await runSyncLeanix({path:e.path??`.`,outdir:e.outdir??Gm,project:e.project,useDotBin:e.useDotBin??!1,dryRun:n,apply:t})}})}function matchesFilter(e,t){return t.some(t=>e===t||e.endsWith(`/`+t)||e.endsWith(`\\`+t))}function buildValidateResult({documents:e,errors:t,fileFilter:n}){let r=n?t.filter(e=>matchesFilter(e.file,n)):[...t],i=n?e.filter(e=>matchesFilter(e,n)).length:e.length;return{valid:r.length===0,errors:[...r],stats:{totalFiles:e.length,totalErrors:t.length,filteredFiles:i,filteredErrors:r.length}}}const validateCmd=e=>e.command({command:`validate [path]`,aliases:[],describe:`Validate syntax, semantics and layout drifts`,builder:e=>e.positional(`path`,U).options({project:Ws,file:{alias:`f`,array:!0,string:!0,description:`only report errors from these files (can be specified multiple times)`},layout:{boolean:!0,default:!0,defaultDescription:`enabled`,description:`force layout validation, or disable with --no-layout`},json:{boolean:!0,nargs:0,description:`output as JSON (structured)`}}).showHidden().epilog(`${S.bold(`Examples:`)}
1607
1623
  ${S.green(`$0 validate `)}
1608
1624
  ${S.gray(`Validate all in the current directory`)}
1609
1625
 
@@ -1612,5 +1628,5 @@ ${S.bold(`Examples:`)}
1612
1628
 
1613
1629
  ${S.green(`$0 validate --project my-project /some/where`)}
1614
1630
  ${S.gray(`Validate my-project in /some/where`)}
1615
- `),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:validate`),r=startTimer(n),i=e.json===!0,a=e.layout===!0,s=e.file?.map(e=>M(e))??null,c=t.a(await x(e.path,{watch:!1,printErrors:!i,throwIfInvalid:!1,configureLogger:i?`stderr`:!1})),l=c.getErrors().map(e=>({message:e.message,file:e.sourceFsPath,line:e.line,range:e.range})),u=[];if(a){n.debug(`running layout validation...`);try{let t=await c.diagrams(e.project);for(let n of t)n.drifts&&n.drifts.length>0&&u.push({message:`Layout drift detected on view '${n.id}'`,file:n.sourcePath?M(e.path,n.sourcePath):``,line:0,range:null})}catch(e){u.push({message:`Layout validation failed: ${e instanceof Error?e.message:String(e)}`,file:``,line:0,range:null})}}let f=[...l,...u],p=buildValidateResult({documents:c.documentPaths(),errors:f,fileFilter:s}),{valid:m,errors:h}=p,{totalFiles:g,totalErrors:v}=p.stats;if(process.exitCode=+!m,i){console.log(JSON.stringify(p,null,2));return}for(let e of u)n.error(S.red(e.message)+(e.file?` at `+e.file:``));if(m)n.info(S.green(`✓ Valid`)+S.dim(` (${g} files)`));else{let e=s?`, ${h.length} in filtered files`:``;n.error(S.red(`✗ Invalid`)+S.dim(` (${g} files, ${v} errors${e})`))}r.stopAndLog(`validate `)}catch(e){t.e=e}finally{await t.d()}}});function applyLoggerConfig(e){let t=e??(Mn?`debug`:`info`);f({reset:!0,sinks:{console:i({formatter:S.isColorSupported?oe():c()})},loggers:[{category:`likec4`,sinks:[`console`],lowestLevel:t}]})}async function main(){await ft(Bn(Vn(Fn)),serveCmd,buildCmd,codegenCmd,exportCmd,formatCmd,previewCmd,publishCmd,syncCmd,validateCmd,listIconsCmd,mcpCmd,lsp_default,checkUpdateCmd,e=>e.command({command:`completion`,describe:`Generate completion script`,handler:()=>{e.showCompletionScript()}})).scriptName(`likec4`).usage(`Usage: $0 <command>`).parserConfiguration({"greedy-arrays":!1}).version(sr).alias(`v`,`version`).alias(`h`,`help`).help(`help`).option(`log-level`,Ks).option(`verbose`,qs).option(`color`,{boolean:!0,describe:[`force color output, or disable with --no-color`,`respects 'FORCE_COLOR' and 'NO_COLOR' env variables`].join(`
1616
- `),skipValidation:!0,hidden:!0,global:!0}).group([`log-level`,`verbose`,`color`,`help`,`version`,`show-hidden`],`Globals:`).demandCommand(1,`Please run with valid command`).recommendCommands().showHelpOnFail(!0).showHidden().updateStrings({"Globals:":S.bold(`Globals:`),"Options:":S.bold(`Options:`),"Positionals:":S.bold(`Arguments:`),"Commands:":S.bold(`Commands:`),"Examples:":S.bold(`Examples:`)}).wrap(ut(zn.columns-10,{min:60,max:180})).middleware(e=>{applyLoggerConfig(e.verbose?Js:e.logLevel)}).parseAsync()}function exitWithFailure(e,t){console.error(t==null?a(e):`${t} ${a(e)}`),Ln(1)}main().catch(exitWithFailure),process.on(`unhandledRejection`,e=>{exitWithFailure(e,`Unhandled rejection:`)}),process.on(`uncaughtException`,e=>{console.error(e)});export{};
1631
+ `),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:validate`),r=startTimer(n),i=e.json===!0,a=e.layout===!0,s=e.file?.map(e=>P(e))??null,c=t.a(await x(e.path,{watch:!1,printErrors:!i,throwIfInvalid:!1,configureLogger:i?`stderr`:!1})),l=c.getErrors().map(e=>({message:e.message,file:e.sourceFsPath,line:e.line,range:e.range})),u=[];if(a){n.debug(`running layout validation...`);try{let t=await c.diagrams(e.project);for(let n of t)n.drifts&&n.drifts.length>0&&u.push({message:`Layout drift detected on view '${n.id}'`,file:n.sourcePath?P(e.path,n.sourcePath):``,line:0,range:null})}catch(e){u.push({message:`Layout validation failed: ${e instanceof Error?e.message:String(e)}`,file:``,line:0,range:null})}}let f=[...l,...u],p=buildValidateResult({documents:c.documentPaths(),errors:f,fileFilter:s}),{valid:m,errors:h}=p,{totalFiles:g,totalErrors:v}=p.stats;if(process.exitCode=+!m,i){console.log(JSON.stringify(p,null,2));return}for(let e of u)n.error(S.red(e.message)+(e.file?` at `+e.file:``));if(m)n.info(S.green(`✓ Valid`)+S.dim(` (${g} files)`));else{let e=s?`, ${h.length} in filtered files`:``;n.error(S.red(`✗ Invalid`)+S.dim(` (${g} files, ${v} errors${e})`))}r.stopAndLog(`validate `)}catch(e){t.e=e}finally{await t.d()}}});function applyLoggerConfig(e){let t=e??(Nn?`debug`:`info`);f({reset:!0,sinks:{console:i({formatter:S.isColorSupported?oe():c()})},loggers:[{category:`likec4`,sinks:[`console`],lowestLevel:t}]})}async function main(){await ut(Vn(Hn(In)),serveCmd,buildCmd,codegenCmd,exportCmd,formatCmd,previewCmd,publishCmd,syncCmd,validateCmd,listIconsCmd,mcpCmd,lsp_default,checkUpdateCmd,e=>e.command({command:`completion`,describe:`Generate completion script`,handler:()=>{e.showCompletionScript()}})).scriptName(`likec4`).usage(`Usage: $0 <command>`).parserConfiguration({"greedy-arrays":!1}).version(cr).alias(`v`,`version`).alias(`h`,`help`).help(`help`).option(`log-level`,Gs).option(`verbose`,Ks).option(`color`,{boolean:!0,describe:[`force color output, or disable with --no-color`,`respects 'FORCE_COLOR' and 'NO_COLOR' env variables`].join(`
1632
+ `),skipValidation:!0,hidden:!0,global:!0}).group([`log-level`,`verbose`,`color`,`help`,`version`,`show-hidden`],`Globals:`).demandCommand(1,`Please run with valid command`).recommendCommands().showHelpOnFail(!0).showHidden().updateStrings({"Globals:":S.bold(`Globals:`),"Options:":S.bold(`Options:`),"Positionals:":S.bold(`Arguments:`),"Commands:":S.bold(`Commands:`),"Examples:":S.bold(`Examples:`)}).wrap(st(Bn.columns-10,{min:60,max:180})).middleware(e=>{applyLoggerConfig(e.verbose?qs:e.logLevel)}).parseAsync()}function exitWithFailure(e,t){console.error(t==null?a(e):`${t} ${a(e)}`),Rn(1)}main().catch(exitWithFailure),process.on(`unhandledRejection`,e=>{exitWithFailure(e,`Unhandled rejection:`)}),process.on(`uncaughtException`,e=>{console.error(e)});export{};