likec4 1.59.4 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/__app__/codegen/react.mjs +6 -6
  2. package/__app__/codegen/webcomponent.mjs +147 -69
  3. package/__app__/src/aichat/index.mjs +10 -5
  4. package/__app__/src/chunks/AIChat.mjs +1134 -693
  5. package/__app__/src/chunks/LikeC4Styles.mjs +3995 -1779
  6. package/__app__/src/chunks/ProjectsOverview.mjs +624 -334
  7. package/__app__/src/chunks/es.mjs +515 -335
  8. package/__app__/src/chunks/hooks.mjs +578 -369
  9. package/__app__/src/chunks/libs/@floating-ui.mjs +2720 -1966
  10. package/__app__/src/chunks/libs/@mantine.mjs +13920 -10057
  11. package/__app__/src/chunks/libs/@tanstack-ai.mjs +2266 -1146
  12. package/__app__/src/chunks/libs/@tanstack.mjs +3152 -1926
  13. package/__app__/src/chunks/libs/@xstate/react.mjs +2924 -1468
  14. package/__app__/src/chunks/libs/@xyflow/react.mjs +6627 -4067
  15. package/__app__/src/chunks/libs/bezier-js.mjs +1312 -726
  16. package/__app__/src/chunks/libs/d3.mjs +3219 -1505
  17. package/__app__/src/chunks/libs/fast-equals.mjs +434 -210
  18. package/__app__/src/chunks/libs/framer.mjs +9251 -3846
  19. package/__app__/src/chunks/libs/nanostores.mjs +174 -0
  20. package/__app__/src/chunks/libs/zod.mjs +4591 -2363
  21. package/__app__/src/chunks/rolldown-runtime.mjs +39 -23
  22. package/__app__/src/chunks/styled-system.mjs +2279 -1951
  23. package/__app__/src/fonts.css +112 -1
  24. package/__app__/src/main.mjs +40817 -21840
  25. package/__app__/src/style.css +18488 -1
  26. package/config/schema.json +122 -97
  27. package/dist/app/render-view-client.css +1 -1
  28. package/dist/app/render-view-client.js +508 -334
  29. package/dist/chunks/enableServer.mjs +1 -1
  30. package/dist/chunks/filenames.mjs +11 -9
  31. package/dist/chunks/generate-likec4.mjs +5 -0
  32. package/dist/chunks/index.d.mts +243 -183
  33. package/dist/chunks/index2.d.mts +2865 -1977
  34. package/dist/chunks/libs/@chevrotain/gast.mjs +27 -1
  35. package/dist/chunks/libs/@chevrotain/regexp-to-ast.mjs +81 -9
  36. package/dist/chunks/libs/@chevrotain/types.d.mts +4 -1
  37. package/dist/chunks/libs/@logtape/logtape.mjs +5 -4
  38. package/dist/chunks/libs/@lume/kiwi.mjs +1 -1
  39. package/dist/chunks/libs/@ts-graphviz/core.mjs +1 -1
  40. package/dist/chunks/libs/birpc.mjs +1 -1
  41. package/dist/chunks/libs/chevrotain-allstar.mjs +2 -2
  42. package/dist/chunks/libs/chevrotain.mjs +87 -35
  43. package/dist/chunks/libs/eventemitter3.mjs +1 -1
  44. package/dist/chunks/libs/json5.mjs +4 -4
  45. package/dist/chunks/libs/langium.d.mts +9038 -6193
  46. package/dist/chunks/libs/langium.mjs +16 -24
  47. package/dist/chunks/libs/merge-error-cause.mjs +1 -1
  48. package/dist/chunks/libs/p-limit.mjs +1 -0
  49. package/dist/chunks/libs/p-queue.mjs +1 -1
  50. package/dist/chunks/libs/package-manager-detector.mjs +1 -1
  51. package/dist/chunks/libs/pako.mjs +1 -1
  52. package/dist/chunks/libs/pretty-ms.mjs +1 -1
  53. package/dist/chunks/libs/remeda.mjs +1 -1
  54. package/dist/chunks/libs/ufo.mjs +1 -1
  55. package/dist/chunks/libs/unstorage.mjs +1 -1
  56. package/dist/chunks/libs/which.mjs +1 -1
  57. package/dist/chunks/node.mjs +59 -58
  58. package/dist/chunks/rolldown-runtime.mjs +1 -1
  59. package/dist/chunks/sequence-view.mjs +1 -1
  60. package/dist/chunks/vite-plugin.mjs +45 -45
  61. package/dist/cli/index.mjs +207 -1315
  62. package/dist/config/index.d.mts +2 -2
  63. package/dist/generators/likec4.d.mts +6578 -0
  64. package/dist/generators/likec4.mjs +1 -0
  65. package/dist/model/index.d.mts +4 -1
  66. package/dist/vite-plugin/index.d.mts +4 -1
  67. package/dist/vite-plugin/index.mjs +1 -1
  68. package/dist/vite-plugin/internal/chunks/rolldown-runtime.mjs +9 -0
  69. package/dist/vite-plugin/internal/index.d.mts +6 -5
  70. package/dist/vite-plugin/internal/index.mjs +83 -30
  71. package/generators/likec4/package.json +4 -0
  72. package/package.json +113 -106
  73. package/react/index.d.mts +8500 -26659
  74. package/react/index.mjs +534 -63936
  75. package/react/rolldown-runtime-DnkiqaRY.js +1 -0
  76. package/skills/likec4-dsl/SKILL.md +428 -0
  77. package/skills/likec4-dsl/evals/evals-public.json +202 -0
  78. package/skills/likec4-dsl/evals/grading-spec.json +589 -0
  79. package/skills/likec4-dsl/references/bridge-leanix-drawio.md +42 -0
  80. package/skills/likec4-dsl/references/cli.md +139 -0
  81. package/skills/likec4-dsl/references/configuration.md +266 -0
  82. package/skills/likec4-dsl/references/deployment.md +160 -0
  83. package/skills/likec4-dsl/references/dynamic-views.md +455 -0
  84. package/skills/likec4-dsl/references/examples.md +370 -0
  85. package/skills/likec4-dsl/references/identifier-validity.md +90 -0
  86. package/skills/likec4-dsl/references/include-predicates-wildcards.md +179 -0
  87. package/skills/likec4-dsl/references/model.md +151 -0
  88. package/skills/likec4-dsl/references/predicates.md +123 -0
  89. package/skills/likec4-dsl/references/relationships-bidirectional.md +176 -0
  90. package/skills/likec4-dsl/references/specification.md +75 -0
  91. package/skills/likec4-dsl/references/style-tokens-colors.md +150 -0
  92. package/skills/likec4-dsl/references/troubleshooting.md +96 -0
  93. package/skills/likec4-dsl/references/views.md +329 -0
  94. package/dist/chunks/libs/picomatch.mjs +0 -1
  95. package/dist/chunks/libs/zod.d.mts +0 -3840
  96. package/dist/chunks/libs/zod.mjs +0 -65
@@ -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 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(`
2
+ import{a as e,i as t,s as n,t as r}from"../chunks/rolldown-runtime.mjs";import{C as i,S as a,_ as s,a as c,b as l,c as u,d as f,f as p,g as m,h,l as g,m as v,n as y,o as b,p as x,r as S,s as ee,u as te,x as ne,y as re}from"../chunks/node.mjs";import{n as ie}from"../chunks/sequence-view.mjs";import{H as ae,K as oe,V as se,b as ce,f as le,g as ue,h as de,m as fe,p as pe,rt as me,s as he}from"../chunks/libs/langium.mjs";import{c as ge,l as _e,o as ve,r as ye,s as be}from"../chunks/libs/ufo.mjs";import{t as xe}from"../chunks/libs/json5.mjs";import{$ as Se,J as Ce,N as we,P as Te,S as Ee,T as De,X as Oe,Z as ke,b as Ae,d as je,h as Me,o as Ne,r as Pe,rt as Fe,t as Ie,tt as Le,u as Re,w as ze}from"../chunks/libs/remeda.mjs";import{$ as Be,Q as C,tt as Ve}from"../chunks/generate-likec4.mjs";import{t as He}from"../chunks/libs/which.mjs";import{t as Ue}from"../chunks/libs/pretty-ms.mjs";import{a as We,c as Ge,i as Ke,l as qe,n as Je,o as Ye,r as Xe,s as Ze,t as Qe}from"../chunks/vite-plugin.mjs";import{n as $e,t as et}from"../chunks/libs/package-manager-detector.mjs";import{LikeC4Model as tt}from"../model/index.mjs";import nt from"node:module";import{isDeepStrictEqual as rt,promisify as it}from"node:util";import{copyFile as at,cp as ot,mkdir as st,mkdtemp as ct,readFile as ut,readdir as dt,realpath as ft,rm as pt,stat as mt,writeFile as w}from"node:fs/promises";import T,{basename as ht,dirname as _t,extname as vt,isAbsolute as yt,join as bt,relative as E,resolve as D,sep as xt}from"node:path";import*as O from"zod/v4";import{z as k}from"zod/v4";import{ProjectId as St}from"@likec4/core/types";import{FqnRef as Ct,GlobalFqn as wt,hasProp as Tt,invariant as A,nonexhaustive as Et}from"@likec4/core";import{ZodOptional as Dt}from"zod";import{compareNatural as Ot,ifilter as kt,invariant as At,isSameHierarchy as jt,sortNaturalByFqn as Mt}from"@likec4/core/utils";import{isDeploymentElementModel as Nt,isDeploymentNodeModel as Pt,isDeploymentRelationModel as Ft,isElementModel as It,isLikeC4ViewModel as Lt,isRelationModel as Rt,modelConnection as zt}from"@likec4/core/model";import Bt from"nano-spawn";import j,{copyFileSync as Vt,existsSync as Ht,readFileSync as Ut,readdirSync as Wt,realpathSync as Gt,rmSync as Kt,statSync as qt,writeFileSync as Jt}from"node:fs";import{env as Yt,isCI as Xt,isDevelopment as Zt,isTest as Qt,nodeENV as $t}from"std-env";import M,{argv as en,cwd as tn,exit as nn,hrtime as rn,stdout as an}from"node:process";import on from"picomatch";import sn from"yargs";import{hideBin as cn}from"yargs/helpers";import ln,{tmpdir as un}from"node:os";import dn from"node:tty";import{build as fn,createServer as pn,preview as mn}from"vite";import{viteSingleFile as hn}from"vite-plugin-singlefile";import{fileURLToPath as gn,pathToFileURL as _n}from"node:url";import vn,{createHash as yn,randomUUID as bn}from"node:crypto";import xn from"node:assert";import Sn from"@vitejs/plugin-react";import Cn from"node:net";import{setTimeout as wn}from"node:timers/promises";import*as Tn from"zod/v3";import{ZodFirstPartyTypeKind as N}from"zod/v3";import*as En from"zod/v4-mini";import{STATUS_CODES as Dn,ServerResponse as On,createServer as kn}from"node:http";import{Http2ServerRequest as An,constants as jn}from"node:http2";import{Readable as Mn}from"node:stream";import{gzipSync as Nn}from"node:zlib";var Pn=/* @__PURE__ */ n(He(),1);function graphvizBinPath(){try{return Pn.default.sync(`dot`)}catch(e){return p.error(`Error checking for native Graphviz:`,{error:e}),null}}const Fn={likec4:{Layouter(e){p.debug(`Creating ConfigurableLayouter`);let t=e.likec4.Graphviz,n=new v({graphviz:t});return e.shared.workspace.ConfigurationProvider.onConfigurationSectionUpdate(t=>{if(p.debug(`Configuration update: {update}`,{update:t}),t.section!==e.LanguageMetaData.languageId)p.debug(`Ignoring configuration update as it is not for ${e.LanguageMetaData.languageId}`);else try{let{mode:r,path:i}=t.configuration.graphviz??{mode:`wasm`,path:``};if(r!==`wasm`){let t=Te(i)?graphvizBinPath():i;if(!Te(t)){n.changePort(new x(t)),p.info`use graphviz binary: ${t}`;return}p.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 h),p.info(`use graphviz wasm`)}catch(e){p.error(`Failed to update configuration`,{error:e})}}),n}}};function startLanguageServer(e){let t=e?.connection,n=ie(e,{enableWatcher:!0,enableManualLayouts:!0,graphviz:`wasm`,configureLogger:!1});n.configureLogger!==!1&&(n.configureLogger===`stderr`?f({lspConnection:t,enableTelemetry:!1,useStdErr:!0}):n.configureLogger===`console`&&f({lspConnection:t})),t?p.info(`Starting LikeC4 language server`):p.warn(`Starting LikeC4 language server (headless - no LSP connection)`);let r=c({...t&&{connection:t},...ee(n.enableWatcher),...n.enableManualLayouts&&u,...b(n.graphviz===`binary`?new x:new h)},t?{likec4:{...Fn.likec4}}:void 0);return he(r.shared),r}function appendView(e,t){e.append(`### `,t.titleOrId,C,C),t.description.nonEmpty&&e.append(t.description.md,C,C),e.append("```mermaid",C,Xe(t).trimEnd(),C,"```",C,C)}function generateMarkdown(e,t={}){let n=new ue;n.append(`# `,e.project.title??e.projectId,C,C),t.description&&n.append(t.description,C,C);for(let t of e.views())t.$view.sourcePath!==void 0&&appendView(n,t);return Be(n)}function toUnion(e){return we(e)?`never`:(typeof e==`object`&&!Array.isArray(e)&&(e=Ee(e)),Le(e,Pe(),Ne(Ot),Ae(e=>` | ${JSON.stringify(e)}`)).join(`
3
+ `).trimStart())}function elementIdToUnion(e){let t=Le(e,Ie(),ke(e=>!!e&&ze(e.id)),Mt,Ae(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
 
@@ -52,10 +52,10 @@ export type $MetadataKey = $Aux['MetadataKey']
52
52
  import { LikeC4Model } from '${r?`@likec4/core`:`likec4`}/model'
53
53
  ${n}
54
54
 
55
- export const likec4model: LikeC4Model<$Aux> = new LikeC4Model(${be.stringify(e.$data,{space:2,quote:`'`})} as any) as any
55
+ export const likec4model: LikeC4Model<$Aux> = new LikeC4Model(${xe.stringify(e.$data,{space:2,quote:`'`})} as any) as any
56
56
 
57
57
  /* prettier-ignore-end */
58
- `.trimStart()}function generateViewId(e){return pe(e,e=>ue`${be.stringify(e.id)}`,{separator:` | `})}function generateViewsDataTs(e){let t=Array.from(e),n=new fe;return n.appendTemplate`
58
+ `.trimStart()}function generateViewId(e){return de(e,e=>ce`${xe.stringify(e.id)}`,{separator:` | `})}function generateViewsDataTs(e){let t=Array.from(e),n=new ue;return n.appendTemplate`
59
59
  /******************************************************************************
60
60
  * This file was generated
61
61
  * DO NOT EDIT MANUALLY!
@@ -66,10 +66,10 @@ export const likec4model: LikeC4Model<$Aux> = new LikeC4Model(${be.stringify(e.$
66
66
  // @ts-nocheck
67
67
 
68
68
  import type { DiagramView } from 'likec4'
69
- `.append(g,g),t.length===0?(n.append(`export {}`,g),l(n)):(n.appendTemplate`
69
+ `.append(C,C),t.length===0?(n.append(`export {}`,C),Be(n)):(n.appendTemplate`
70
70
  export type LikeC4ViewId = ${generateViewId(t)};
71
71
  export const LikeC4Views = {
72
- `.indent({indentation:2,indentedChildren(e){e.appendNewLineIf(t.length>1).append(pe(t,e=>ue`${be.stringify(e.id)}: (${be.stringify(e)} as unknown) as DiagramView`,{separator:`,`,appendNewLineIfNotEmpty:!0}))}}).append(`} as const satisfies Record<LikeC4ViewId, DiagramView>`,g,g).appendTemplate`
72
+ `.indent({indentation:2,indentedChildren(e){e.appendNewLineIf(t.length>1).append(de(t,e=>ce`${xe.stringify(e.id)}: (${xe.stringify(e)} as unknown) as DiagramView`,{separator:`,`,appendNewLineIfNotEmpty:!0}))}}).append(`} as const satisfies Record<LikeC4ViewId, DiagramView>`,C,C).appendTemplate`
73
73
  export type LikeC4Views = typeof LikeC4Views
74
74
 
75
75
  export function isLikeC4ViewId(value: unknown): value is LikeC4ViewId {
@@ -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;rn(!e.isParsed(),`can not generate react types for parsed model`);let r=generateAux(e,t);return`
84
+ `.append(C),Be(n))}function generateReactTypes(e,t={}){let{useCorePackage:n=!1}=t;At(!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,41 +137,64 @@ export {
137
137
  ReactLikeC4
138
138
  }
139
139
  /* prettier-ignore-end */
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
140
+ `.trimStart()}var In=`likec4`,Ln=`1.60.0`;function ansiRegex({onlyFirst:e=!1}={}){return RegExp(`(?:(?:\\u001B\\]|\\u009D)[^\\u0007\\u001B\\u009C\\u009D]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const Rn=ansiRegex();function stripAnsi(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes(`\x1B`)&&!e.includes(`›`)?e:e.replace(Rn,``)}const zn=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Bn=[12288,12288,65281,65376,65504,65510],Vn=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101594,101631,101664,101760,101874,101888,102801,102816,102866,110576,110579,110581,110587,110589,110590,110592,110888,110898,110898,110928,110930,110933,110933,110948,110952,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127406,127406,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128729,128732,128735,128747,128748,128756,128764,128986,128986,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129734,129736,129736,129740,129757,129759,129771,129775,129786,131072,196605,196608,262141],isInRange=(e,t)=>{let n=0,r=Math.floor(e.length/2)-1;for(;n<=r;){let i=Math.floor((n+r)/2),a=i*2;if(t<e[a])r=i-1;else if(t>e[a+1])n=i+1;else return!0}return!1},Hn=19968,[Un,Wn]=/* #__PURE__ */ findWideFastPathRange(Vn);function findWideFastPathRange(e){let t=e[0],n=e[1];for(let r=0;r<e.length;r+=2){let i=e[r],a=e[r+1];if(Hn>=i&&Hn<=a)return[i,a];a-i>n-t&&(t=i,n=a)}return[t,n]}const isAmbiguous=e=>e<161||e>1114109?!1:isInRange(zn,e),isFullwidth=e=>e<12288||e>65510?!1:isInRange(Bn,e),isWide=e=>e>=Un&&e<=Wn?!0:e<4352||e>262141?!1:isInRange(Vn,e);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 Gn=/* @__PURE__ */ 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 Kn=new Intl.Segmenter,qn=/^\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 Kn.segment(e)){let e=t.codePointAt(0);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||qn.test(t)||(Gn().test(t)?i+=2:i+=eastAsianWidth(e,a))}return i}const Jn=/* @__PURE__ */ t((e=0)=>t=>`\u001B[${t+e}m`,`wrapAnsi16`),Yn=/* @__PURE__ */ t((e=0)=>t=>`\u001B[${38+e};5;${t}m`,`wrapAnsi256`),Xn=/* @__PURE__ */ t((e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,`wrapAnsi16m`),P={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(P.modifier);const Zn=Object.keys(P.color),Qn=Object.keys(P.bgColor);[...Zn,...Qn];function assembleStyles$1(){let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(P)){for(let[t,r]of Object.entries(n))P[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=P[t],e.set(r[0],r[1]);Object.defineProperty(P,t,{value:n,enumerable:!1})}return Object.defineProperty(P,"codes",{value:e,enumerable:!1}),P.color.close=`\x1B[39m`,P.bgColor.close=`\x1B[49m`,P.color.ansi=Jn(),P.color.ansi256=Yn(),P.color.ansi16m=Xn(),P.bgColor.ansi=Jn(10),P.bgColor.ansi256=Yn(10),P.bgColor.ansi16m=Xn(10),Object.defineProperties(P,{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=>P.rgbToAnsi256(...P.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)=>P.ansi256ToAnsi(P.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>P.ansi256ToAnsi(P.hexToAnsi256(e)),enumerable:!1}}),P}t(assembleStyles$1,`assembleStyles`);const $n=assembleStyles$1();function hasFlag(e,t=globalThis.Deno?globalThis.Deno.args:M.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:F}=M;let er;hasFlag(`no-color`)||hasFlag(`no-colors`)||hasFlag(`color=false`)||hasFlag(`color=never`)?er=0:(hasFlag(`color`)||hasFlag(`colors`)||hasFlag(`color=true`)||hasFlag(`color=always`))&&(er=1);function envForceColor(){if(`FORCE_COLOR`in F)return F.FORCE_COLOR===`true`?1:F.FORCE_COLOR===`false`?0:F.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(F.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&&(er=r);let i=n?er: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 F&&`AGENT_NAME`in F)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(F.TERM===`dumb`)return a;if(M.platform===`win32`){let e=ln.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in F)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in F)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in F)||F.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in F)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(F.TEAMCITY_VERSION);if(F.COLORTERM===`truecolor`||F.TERM===`xterm-kitty`||F.TERM===`xterm-ghostty`||F.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in F){let e=Number.parseInt((F.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(F.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(F.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(F.TERM)||`COLORTERM`in F?1:a}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}const tr={stdout:createSupportsColor({isTTY:dn.isatty(1)}),stderr:createSupportsColor({isTTY:dn.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(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
- `);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
- `))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`,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
- `),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]===`
143
+ `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:nr,stderr:rr}=tr,ir=Symbol(`GENERATOR`),ar=Symbol(`STYLER`),sr=Symbol(`IS_EMPTY`),cr=[`ansi`,`ansi`,`ansi256`,`ansi16m`],lr=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=nr?nr.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($n))lr[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[ar]),this[sr]);return Object.defineProperty(this,e,{value:n}),n}};lr.visible={get(){let e=createBuilder(this,this[ar],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const getModelAnsi=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?$n[n].ansi16m(...r):t===`ansi256`?$n[n].ansi256($n.rgbToAnsi256(...r)):$n[n].ansi($n.rgbToAnsi(...r)):e===`hex`?getModelAnsi(`rgb`,t,n,...$n.hexToRgb(...r)):$n[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){lr[e]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,cr[t],`color`,...n),$n.color.close,this[ar]);return createBuilder(this,r,this[sr])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);lr[t]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,cr[t],`bgColor`,...n),$n.bgColor.close,this[ar]);return createBuilder(this,r,this[sr])}}}}const ur=Object.defineProperties(()=>{},{...lr,level:{enumerable:!0,get(){return this[ir].level},set(e){this[ir].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,ur),builder[ir]=e,builder[ar]=t,builder[sr]=n,builder},applyStyle=(e,t)=>{if(e.level<=0||!t)return e[sr]?``:t;let n=e[ar];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
+ `);return a!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,i,r,a)),r+t+i};Object.defineProperties(createChalk.prototype,lr);const dr=createChalk();createChalk({level:rr?rr.level:0});function widestLine(e){let t=0;for(let n of e.split(`
145
+ `))t=Math.max(t,stringWidth(n));return t}var fr=/* @__PURE__ */ 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:`→`}}})),pr=/* @__PURE__ */ n((/* @__PURE__ */ r(((e,t)=>{let n=fr();t.exports=n,t.exports.default=n})))(),1);const mr=/[\p{Lu}]/u,hr=/[\p{Ll}]/u,gr=/^[\p{Lu}](?![\p{Lu}])/gu,_r=/([\p{Alpha}\p{N}_]|$)/u,vr=/[_.\- ]+/,yr=RegExp(`^`+vr.source),br=new RegExp(vr.source+_r.source,`gu`),xr=RegExp(`\\d+`+_r.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&&hr.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)=>(gr.lastIndex=0,e.replaceAll(gr,e=>t(e))),postProcess=(e,t)=>(br.lastIndex=0,xr.lastIndex=0,e.replaceAll(xr,(n,r,i)=>[`_`,`-`].includes(e.charAt(i+n.length))?n:t(n)).replaceAll(br,(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?vr.test(e)?``:t.pascalCase?r(e):n(e):(e!==n(e)&&(e=preserveCamelCase(e,n,r,t.preserveConsecutiveUppercase)),e=e.replace(yr,``),e=t.preserveConsecutiveUppercase?preserveConsecutiveUppercase(e,n):n(e),t.pascalCase&&(e=r(e.charAt(0))+e.slice(1)),postProcess(e,r))}var Sr=/* @__PURE__ */ 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`)}})),Cr=/* @__PURE__ */ r(((e,t)=>{let n=Sr();t.exports=e=>typeof e==`string`?e.replace(n(),``):e})),wr=/* @__PURE__ */ 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})),Tr=/* @__PURE__ */ 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}})),Er=/* @__PURE__ */ r(((e,t)=>{let n=Cr(),r=wr(),i=Tr(),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})),Dr=/* @__PURE__ */ n((/* @__PURE__ */ r(((e,t)=>{let n=Er();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 Or=Object.keys(I.color),kr=Object.keys(I.bgColor);[...Or,...kr];function assembleStyles(){let e=/* @__PURE__ */ 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 Ar=assembleStyles(),jr=/* @__PURE__ */ new Set([`\x1B`,`›`]),Mr=`]8;;`,wrapAnsiCode=e=>`${jr.values().next().value}[${e}m`,wrapAnsiHyperlink=e=>`${jr.values().next().value}${Mr}${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);s+l<=n?e[e.length-1]+=c:(e.push(c),s=0),jr.has(c)&&(i=!0,a=r.slice(t+1,t+1+4).join(``)===Mr),i?a?c===`\x07`&&(i=!1,a=!1):c===`m`&&(i=!1):(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)}else{if(e+s[r]>t&&e>0&&s[r]>0){if(n.wordWrap===!1&&e<t){wrapWord(c,i,t);continue}c.push(``)}e+s[r]>t&&n.wordWrap===!1?wrapWord(c,i,t):c[c.length-1]+=i}}n.trim!==!1&&(c=c.map(e=>stringVisibleTrimSpacesRight(e)));let l=c.join(`
147
+ `),u=[...l],f=0;for(let[e,t]of u.entries()){if(r+=t,jr.has(t)){let{groups:e}=RegExp(`(?:\\[(?<code>\\d+)m|\\${Mr}(?<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=Ar.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}=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
- `),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(`
153
+ `)}const Nr=`none`,terminalColumns=()=>{let{env:e,stdout:t,stderr:n}=M;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===Nr?0:2,getBorderChars=e=>{let t=[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`,`left`,`right`,`top`,`bottom`],n;if(e===Nr){e={};for(let n of t)e[n]=``}if(typeof e==`string`){if(n=pr.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,Dr.default)(e,{align:r});let a=e.split(`
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,Dr.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
- `)},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+=`
157
- `.repeat(n.margin.top)),(n.borderStyle!==Zr||n.title)&&(s+=colorizeBorder(a+r.topLeft+(n.title?makeTitle(n.title,r.top.repeat(t),n.titleAlignment):r.top.repeat(t))+r.topRight)+`
156
+ `)},boxContent=(e,t,n)=>{let colorizeBorder=e=>{let t=n.borderColor?getColorFunction(n.borderColor)(e):e;return n.dimBorder?dr.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+=`
157
+ `.repeat(n.margin.top)),(n.borderStyle!==Nr||n.title)&&(s+=colorizeBorder(a+r.topLeft+(n.title?makeTitle(n.title,r.top.repeat(t),n.titleAlignment):r.top.repeat(t))+r.topRight)+`
158
158
  `);let c=e.split(`
159
159
  `);return s+=c.map(e=>a+colorizeBorder(r.left)+colorizeContent(e)+colorizeBorder(r.right)).join(`
160
- `),n.borderStyle!==Zr&&(s+=`
160
+ `),n.borderStyle!==Nr&&(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&&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)}};
162
+ `.repeat(n.margin.bottom)),s},sanitizeOptions=e=>{if(e.fullscreen&&M?.stdout){let t=[M.stdout.columns,M.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===Nr?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`&&(dr[e]??isHex(e)),getColorFunction=e=>isHex(e)?dr.hex(e):dr[e],getBGColorFunction=e=>isHex(e)?dr.bgHex(e):dr[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 L=re.getChild(`cli`);function createLikeC4Logger(e){let t=re.getChild(e);return{info(e){t.info(e)},debug(e,...n){n.length===0?t.debug(e):t.debug(e,{args:n})},warn(e){e instanceof Error?t.warn(`${m.red(e.name+` `+e.message)}`,{msg:e}):typeof e==`string`?t.warn(e):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(`${m.red(r.name+` `+r.message)}`,{error:r});return}t.error(m.red(e),{error:r})}else typeof e==`string`?t.error(m.red(e)):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:Ue(r)}}function startTimer(e){let t=rn();return{stopAndLog(n=`done in `){n=m.green(`${n}${inMillis(t).pretty}`),(e||L).info(n)}}}function boxen(e,t){console.log(boxen$1(e,{padding:1,margin:1,dimBorder:!0,...t}))}const toPath=e=>e instanceof URL?gn(e):e;function findUpSync(e,{cwd:t=M.cwd(),type:n=`file`,stopAt:r}={}){let i=T.resolve(toPath(t)??``),{root:a}=T.parse(i);for(r=T.resolve(i,toPath(r)??a);i&&i!==r&&i!==a;){let t=T.isAbsolute(e)?e:T.join(i,e);try{let e=j.statSync(t,{throwIfNoEntry:!1});if(n===`file`&&e?.isFile()||n===`directory`&&e?.isDirectory())return t}catch{}i=T.dirname(i)}}function packageUpSync({cwd:e=M.cwd()}={}){return findUpSync(`package.json`,{cwd:e})}const Pr=createLikeC4Logger(`vite`),Fr=_t(gn(import.meta.url));function findPkgRoot(){let e=packageUpSync({cwd:Fr});if(!e)throw Error(`likec4 package folder not found`);return _t(e)}function viteAppRoot(){let e=findPkgRoot(),t=[D(e,`__app__`),D(Fr,`../__app__`),D(Fr,`../../__app__`),D(Fr,`../../dist/__app__`)],n=Oe(t,Ht);if(!n)throw re.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 ct(bt(un(),`.likec4-public-`));return await w(bt(e,`likec4-views.js`),`// generated by likec4
164
+ `),e}function relativeToCwd(e){return E(tn(),e)}async function copyUserPublicDir(e,t){if(!Ht(e))throw Error(`--public directory does not exist: ${e}`);if(!qt(e).isDirectory())throw Error(`--public path is not a directory: ${e}`);let n=await dt(e);return await ot(e,t,{recursive:!0,errorOnExist:!1}),n}function viteAliases(){let e=findPkgRoot();return{"likec4/react":D(e,`react/index.mjs`),"likec4/model":D(e,`dist/model/index.mjs`),"likec4/vite-plugin/internal":D(e,`dist/vite-plugin/internal/index.mjs`)}}const viteConfig=async({languageServices:e,likec4AssetsDir:t,...n})=>{let r=n.customLogger??Pr,i=viteAppRoot();r.info(`${m.cyan(`likec4 app root`)} ${m.dim(relativeToCwd(i))}`);let a=n.outputDir??D(e.workspace,`dist`);r.info(m.cyan(`outDir`)+` `+m.dim(relativeToCwd(a)));let s=`/`;n.base&&(s=_e(n.base),!ye(s)&&s!==`./`&&(s=be(s))),s!==`/`&&r.info(`${m.green(`app base url`)} ${m.dim(s)}`);let c=n.webcomponentPrefix??`likec4`,l=n.title??`LikeC4`,u=n.outputSingleFile??!1;return{isDev:Zt,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:[D(i,`index.html`),D(i,`src`,`main.mjs`),D(i,`src`,`fonts.css`),D(i,`src`,`style.css`)]}}},customLogger:r,plugins:[Qe({languageServices:e.languageServices,appConfig:{webcomponentPrefix:c,pageTitle:l,useHashHistory:n.useHashHistory,theme:n.theme}}),u?hn():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(m.cyan(`outDir`)+` `+m.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:[Qe({ai:`disabled`,languageServices:e.languageServices,appConfig:{webcomponentPrefix:r}})]}}const Ir=[`favicon.ico`,`robots.txt`];function removeAllButPreserved(e,t){let n=new Set(t);for(let t of Wt(e).filter(e=>!n.has(e)))Kt(D(e,t),{recursive:!0})}const Lr={".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=D(e,`index.html`);if(!Ht(t))return;let n=Ut(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=D(e,a.replace(/^\.?\//,``));if(!Ht(s))return;let c=`data:${Lr[vt(s).toLowerCase()]??`application/octet-stream`};base64,${Ut(s).toString(`base64`)}`,l=r.replace(i,(e,t)=>`href=${t}${c}${t}`);Jt(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 ct(bt(un(),`.likec4-assets-`));let l=await viteConfig({...c,languageServices:r,likec4AssetsDir:i,webcomponentPrefix:t,title:n,outputSingleFile:a}),u=!Ht(l.build.outDir)||Wt(l.build.outDir).length===0,f=await mkTempPublicDir(),p=s?await copyUserPublicDir(s,f):[];for(let e of Ir){let t=D(l.root,e);Ht(t)&&Vt(t,D(f,e))}let h=r.languageServices.projects();if(h.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(`${m.dim(`workspace:`)} ${m.green(`✓ all views layouted`)}`):l.customLogger.warn(`${m.dim(`workspace:`)} ${m.yellow(`✗ layouted ${t.length} of ${e.length} views`)}`),t.forEach(e=>{(e.hasLayoutDrift||e.drifts&&e.drifts.length>0)&&l.customLogger.warn(m.dim(`view`)+` `+m.red(e.id)+` `+m.yellow(`is out of date, layout drift detected`))});let n=h[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(m.dim(`landingPage:`)+` `+m.yellow(`no views match the configured filter`))}}else for(let e of h){let t=await r.viewsService.computedViews(e.id);t.length===0?l.customLogger.warn(`${m.dim(`project:`)} ${e.id} ${m.yellow(`✗ no views found`)}`):l.customLogger.info(`${m.dim(`project:`)} ${e.id} ${m.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(`${m.dim(`project:`)} ${e.id} ${m.yellow(`landingPage: no views match the configured filter`)}`)}}if(e&&!a){let e=viteWebcomponentConfig({webcomponentPrefix:t,languageServices:r,outDir:f,base:l.base});await fn(e)}if(await fn({...l,publicDir:f}),a){if(!u){l.customLogger.warn(m.yellow(`outDir was not empty, skipping cleanup`));return}inlineSingleFileFavicon(l.build.outDir),removeAllButPreserved(l.build.outDir,[`index.html`,...p])}let g=D(l.build.outDir,`index.html`);Ht(g)&&Vt(g,D(l.build.outDir,`404.html`))}let Rr;function hasDockerEnv(){try{return j.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return j.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return Rr===void 0&&(Rr=hasDockerEnv()||hasDockerCGroup()),Rr}let zr;const hasContainerEnv=()=>{try{return j.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return zr===void 0&&(zr=hasContainerEnv()||isDocker()),zr}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 Br=(()=>{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})(),Vr=typeof globalThis.AbortController==`function`,Hr=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,Ur=typeof globalThis.ReadableStream==`function`,Wr=typeof globalThis.FormData==`function`,Gr=[`get`,`post`,`put`,`patch`,`head`,`delete`],Kr={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},qr=2147483647,Jr=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,Yr=Symbol(`stop`);var RetryMarker=class{options;constructor(e){this.options=e}};const retry=e=>new RetryMarker(e),Xr={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},Zr={next:!0},Qr={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+=Jr,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)})},$r=/* @__PURE__ */ t(e=>typeof e==`object`&&!!e,`isObject`),validateAndMerge=(...e)=>{for(let t of e)if((!$r(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($r(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($r(s)){for(let[e,n]of Object.entries(s))if(e===`signal`&&n instanceof globalThis.AbortSignal)a.push(n);else if(e===`context`){if(n!=null&&(!$r(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}}}else e===`searchParams`?i=n==null?void 0:i===void 0?n:appendSearchParameters(i,n):($r(n)&&e in t&&(n=deepMerge(t[e],n)),t={...t,[e]:n});$r(s.hooks)&&(r=mergeHooks(r,s.hooks),t.hooks=r),$r(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]:Hr?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},normalizeRequestMethod=e=>Gr.includes(e)?e.toUpperCase():e,ei={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{...ei,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{...ei,...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 Qr)&&!(r in Xr)&&(!(r in e)||r in Zr)&&(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 ti=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 ${qr}`);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(!Ur)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(Kr))(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}Vr&&Hr&&(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),Br&&(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&&(Wr&&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(!Br)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),qr);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===Yr)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=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
166
+ const createInstance=e=>{let ky=(t,n)=>ti.create(t,validateAndMerge(e,n));for(let t of Gr)ky[t]=(n,r)=>ti.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=Yr,ky.retry=retry,ky},ni=createInstance();var ri=/* @__PURE__ */ r(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||
167
+ /* istanbul ignore next */9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),ii=/* @__PURE__ */ 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):()=>{}})),ai=/* @__PURE__ */ r(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=ri(),a=ii();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*$`)})),oi=/* @__PURE__ */ r(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({}),parseOptions=e=>e?typeof e==`object`?e:n:r;t.exports=parseOptions})),si=/* @__PURE__ */ 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}})),R=/* @__PURE__ */ r(((e,t)=>{let n=ii(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=ri(),{safeRe:a,t:s}=ai(),c=oi(),{compareIdentifiers:l}=si(),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}}})),ci=/* @__PURE__ */ r(((e,t)=>{let n=R(),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})),li=/* @__PURE__ */ r(((e,t)=>{let n=ci(),valid=(e,t)=>{let r=n(e,t);return r?r.version:null};t.exports=valid})),ui=/* @__PURE__ */ r(((e,t)=>{let n=ci(),clean=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null};t.exports=clean})),di=/* @__PURE__ */ r(((e,t)=>{let n=R(),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})),fi=/* @__PURE__ */ r(((e,t)=>{let n=ci(),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})),pi=/* @__PURE__ */ r(((e,t)=>{let n=R(),major=(e,t)=>new n(e,t).major;t.exports=major})),mi=/* @__PURE__ */ r(((e,t)=>{let n=R(),minor=(e,t)=>new n(e,t).minor;t.exports=minor})),hi=/* @__PURE__ */ r(((e,t)=>{let n=R(),patch=(e,t)=>new n(e,t).patch;t.exports=patch})),gi=/* @__PURE__ */ r(((e,t)=>{let n=ci(),prerelease=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};t.exports=prerelease})),_i=/* @__PURE__ */ r(((e,t)=>{let n=R(),compare=(e,t,r)=>new n(e,r).compare(new n(t,r));t.exports=compare})),vi=/* @__PURE__ */ r(((e,t)=>{let n=_i(),rcompare=(e,t,r)=>n(t,e,r);t.exports=rcompare})),yi=/* @__PURE__ */ r(((e,t)=>{let n=_i(),compareLoose=(e,t)=>n(e,t,!0);t.exports=compareLoose})),bi=/* @__PURE__ */ r(((e,t)=>{let n=R(),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})),xi=/* @__PURE__ */ r(((e,t)=>{let n=bi(),sort=(e,t)=>e.sort((e,r)=>n(e,r,t));t.exports=sort})),Si=/* @__PURE__ */ r(((e,t)=>{let n=bi(),rsort=(e,t)=>e.sort((e,r)=>n(r,e,t));t.exports=rsort})),Ci=/* @__PURE__ */ r(((e,t)=>{let n=_i(),gt=(e,t,r)=>n(e,t,r)>0;t.exports=gt})),wi=/* @__PURE__ */ r(((e,t)=>{let n=_i(),lt=(e,t,r)=>n(e,t,r)<0;t.exports=lt})),Ti=/* @__PURE__ */ r(((e,t)=>{let n=_i(),eq=(e,t,r)=>n(e,t,r)===0;t.exports=eq})),Ei=/* @__PURE__ */ r(((e,t)=>{let n=_i(),neq=(e,t,r)=>n(e,t,r)!==0;t.exports=neq})),Di=/* @__PURE__ */ r(((e,t)=>{let n=_i(),gte=(e,t,r)=>n(e,t,r)>=0;t.exports=gte})),Oi=/* @__PURE__ */ r(((e,t)=>{let n=_i(),lte=(e,t,r)=>n(e,t,r)<=0;t.exports=lte})),ki=/* @__PURE__ */ r(((e,t)=>{let n=Ti(),r=Ei(),i=Ci(),a=Di(),s=wi(),c=Oi(),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})),Ai=/* @__PURE__ */ r(((e,t)=>{let n=R(),r=ci(),{safeRe:i,t:a}=ai(),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})),ji=/* @__PURE__ */ r(((e,t)=>{let n=ci(),r=ri(),i=R(),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})),Mi=/* @__PURE__ */ r(((e,t)=>{var LRUCache=class{constructor(){this.max=1e3,this.map=/* @__PURE__ */ 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})),Ni=/* @__PURE__ */ 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=/* @__PURE__ */ new Map,x=u.map(e=>new a(e,this.options));for(let e of x){if(isNullSet(e))return[e];b.set(e.value,e)}b.size>1&&b.has(``)&&b.delete(``);let S=[...b.values()];return r.set(t,S),S}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(Mi()),i=oi(),a=Pi(),s=ii(),c=R(),{safeRe:l,src:u,t:f,comparatorTrimReplace:p,tildeTrimReplace:m,caretTrimReplace:h}=ai(),{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:v}=ri(),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}})),Pi=/* @__PURE__ */ 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=oi(),{safeRe:i,t:a}=ai(),s=ki(),c=ii(),l=R(),u=Ni()})),Fi=/* @__PURE__ */ r(((e,t)=>{let n=Ni(),satisfies=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)};t.exports=satisfies})),Ii=/* @__PURE__ */ r(((e,t)=>{let n=Ni(),toComparators=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `));t.exports=toComparators})),Li=/* @__PURE__ */ r(((e,t)=>{let n=R(),r=Ni(),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})),Ri=/* @__PURE__ */ r(((e,t)=>{let n=R(),r=Ni(),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})),zi=/* @__PURE__ */ r(((e,t)=>{let n=R(),r=Ni(),i=Ci(),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;
168
+ /* istanbul ignore next */
169
+ default:throw Error(`Unexpected operation: ${e.operator}`)}}),s&&(!a||i(a,s))&&(a=s)}return a&&e.test(a)?a:null};t.exports=minVersion})),Bi=/* @__PURE__ */ r(((e,t)=>{let n=Ni(),validRange=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}};t.exports=validRange})),Vi=/* @__PURE__ */ r(((e,t)=>{let n=R(),r=Pi(),{ANY:i}=r,a=Ni(),s=Fi(),c=Ci(),l=wi(),u=Oi(),f=Di(),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})),Hi=/* @__PURE__ */ r(((e,t)=>{let n=Vi(),gtr=(e,t,r)=>n(e,t,`>`,r);t.exports=gtr})),Ui=/* @__PURE__ */ r(((e,t)=>{let n=Vi(),ltr=(e,t,r)=>n(e,t,`<`,r);t.exports=ltr})),Wi=/* @__PURE__ */ r(((e,t)=>{let n=Ni(),intersects=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r));t.exports=intersects})),Gi=/* @__PURE__ */ r(((e,t)=>{let n=Fi(),r=_i();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}})),Ki=/* @__PURE__ */ r(((e,t)=>{let n=Ni(),r=Pi(),{ANY:i}=r,a=Fi(),s=_i(),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=/* @__PURE__ */ 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})),qi=/* @__PURE__ */ n((/* @__PURE__ */ r(((e,t)=>{let n=ai(),r=ri(),i=R(),a=si();t.exports={parse:ci(),valid:li(),clean:ui(),inc:di(),diff:fi(),major:pi(),minor:mi(),patch:hi(),prerelease:gi(),compare:_i(),rcompare:vi(),compareLoose:yi(),compareBuild:bi(),sort:xi(),rsort:Si(),gt:Ci(),lt:wi(),eq:Ti(),neq:Ei(),gte:Di(),lte:Oi(),cmp:ki(),coerce:Ai(),truncate:ji(),Comparator:Pi(),Range:Ni(),satisfies:Fi(),toComparators:Ii(),maxSatisfying:Li(),minSatisfying:Ri(),minVersion:zi(),validRange:Bi(),outside:Vi(),gtr:Hi(),ltr:Ui(),intersects:Wi(),simplifyRange:Gi(),subset:Ki(),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`)},Ji=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),Yi=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<=Yi}return!1}function processSegment(e,t){return!Ji.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;else 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}else 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<=Yi&&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(Ji.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 Xi=ln.homedir(),Zi=ln.tmpdir(),{env:Qi}=M,macos=e=>{let t=T.join(Xi,`Library`);return{data:T.join(t,`Application Support`,e),config:T.join(t,`Preferences`,e),cache:T.join(t,`Caches`,e),log:T.join(t,`Logs`,e),temp:T.join(Zi,e)}},windows=e=>{let t=Qi.APPDATA||T.join(Xi,`AppData`,`Roaming`),n=Qi.LOCALAPPDATA||T.join(Xi,`AppData`,`Local`);return{data:T.join(n,e,`Data`),config:T.join(t,e,`Config`),cache:T.join(n,e,`Cache`),log:T.join(n,e,`Log`),temp:T.join(Zi,e)}},linux=e=>{let t=T.basename(Xi);return{data:T.join(Qi.XDG_DATA_HOME||T.join(Xi,`.local`,`share`),e),config:T.join(Qi.XDG_CONFIG_HOME||T.join(Xi,`.config`),e),cache:T.join(Qi.XDG_CACHE_HOME||T.join(Xi,`.cache`),e),log:T.join(Qi.XDG_STATE_HOME||T.join(Xi,`.local`,`state`),e),temp:T.join(Zi,t,e)}};function envPaths(e,{suffix:t=`nodejs`}={}){if(typeof e!=`string`)throw TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),M.platform===`darwin`?macos(e):M.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)}},$i=M.getuid?!M.getuid():!1,NOOP=()=>void 0,z={isChangeErrorOk:e=>{if(!z.isNodeError(e))return!1;let{code:t}=e;return t===`ENOSYS`||!$i&&(t===`EINVAL`||t===`EPERM`)},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!z.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(!z.isNodeError(e)||!z.isChangeErrorOk(e))throw e}};var RetryfyQueue=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=1e4,this.queueActive=/* @__PURE__ */ new Set,this.queueWaiting=/* @__PURE__ */ 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()}}}}},ea=new RetryfyQueue;const retryifyAsync=(e,t)=>function retrified(n){return function attempt(...r){return ea.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}}},B={attempt:{chmod:attemptifyAsync(it(j.chmod),z.onChangeError),chown:attemptifyAsync(it(j.chown),z.onChangeError),close:attemptifyAsync(it(j.close),NOOP),fsync:attemptifyAsync(it(j.fsync),NOOP),mkdir:attemptifyAsync(it(j.mkdir),NOOP),realpath:attemptifyAsync(it(j.realpath),NOOP),stat:attemptifyAsync(it(j.stat),NOOP),unlink:attemptifyAsync(it(j.unlink),NOOP),chmodSync:attemptifySync(j.chmodSync,z.onChangeError),chownSync:attemptifySync(j.chownSync,z.onChangeError),closeSync:attemptifySync(j.closeSync,NOOP),existsSync:attemptifySync(j.existsSync,NOOP),fsyncSync:attemptifySync(j.fsync,NOOP),mkdirSync:attemptifySync(j.mkdirSync,NOOP),realpathSync:attemptifySync(j.realpathSync,NOOP),statSync:attemptifySync(j.statSync,NOOP),unlinkSync:attemptifySync(j.unlinkSync,NOOP)},retry:{close:retryifyAsync(it(j.close),z.isRetriableError),fsync:retryifyAsync(it(j.fsync),z.isRetriableError),open:retryifyAsync(it(j.open),z.isRetriableError),readFile:retryifyAsync(it(j.readFile),z.isRetriableError),rename:retryifyAsync(it(j.rename),z.isRetriableError),stat:retryifyAsync(it(j.stat),z.isRetriableError),write:retryifyAsync(it(j.write),z.isRetriableError),writeFile:retryifyAsync(it(j.writeFile),z.isRetriableError),closeSync:retryifySync(j.closeSync,z.isRetriableError),fsyncSync:retryifySync(j.fsyncSync,z.isRetriableError),openSync:retryifySync(j.openSync,z.isRetriableError),readFileSync:retryifySync(j.readFileSync,z.isRetriableError),renameSync:retryifySync(j.renameSync,z.isRetriableError),statSync:retryifySync(j.statSync,z.isRetriableError),writeSync:retryifySync(j.writeSync,z.isRetriableError),writeFileSync:retryifySync(j.writeFileSync,z.isRetriableError)}},ta={},na=ln.userInfo().uid,ra=ln.userInfo().gid,ia=!!M.getuid;M.getuid&&M.getuid();const isException=e=>e instanceof Error&&`code`in e,aa=/* @__PURE__ */ t(e=>typeof e==`string`,`isString`),isUndefined=e=>e===void 0,oa=M.platform===`linux`,sa=M.platform===`win32`,ca=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`];sa||ca.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),oa&&ca.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`);var Interceptor=class{constructor(){this.callbacks=/* @__PURE__ */ new Set,this.exited=!1,this.exit=e=>{if(!this.exited){this.exited=!0;for(let e of this.callbacks)e();e&&(sa&&e!==`SIGINT`&&e!==`SIGTERM`&&e!==`SIGKILL`?M.kill(M.pid,`SIGTERM`):M.kill(M.pid,e))}},this.hook=()=>{M.once(`exit`,()=>this.exit());for(let e of ca)try{M.once(e,()=>this.exit(e))}catch{}},this.register=e=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}};const la=new Interceptor().register,V={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=V.truncate(t(e));if(r in V.store)return V.get(e,t,n);V.store[r]=n;let disposer=()=>delete V.store[r];return[r,disposer]},purge:e=>{V.store[e]&&(delete V.store[e],B.attempt.unlink(e))},purgeSync:e=>{V.store[e]&&(delete V.store[e],B.attempt.unlinkSync(e))},purgeSyncAll:()=>{for(let e in V.store)V.purgeSync(e)},truncate:e=>{let t=T.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]}`}};la(V.purgeSyncAll);function writeFileSync$1(e,t,n=ta){if(aa(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=B.attempt.realpathSync(e),l=!!c;e=c||e,[a,i]=V.get(e,n.tmpCreate||V.create,n.tmpPurge!==!1);let u=ia&&isUndefined(n.chown),f=isUndefined(n.mode);if(l&&(u||f)){let t=B.attempt.statSync(e);t&&(n={...n},u&&(n.chown={uid:t.uid,gid:t.gid}),f&&(n.mode=t.mode))}if(!l){let t=T.dirname(e);B.attempt.mkdirSync(t,{mode:511,recursive:!0})}s=B.retry.openSync(r)(a,`w`,n.mode||438),n.tmpCreated&&n.tmpCreated(a),aa(t)?B.retry.writeSync(r)(s,t,0,n.encoding||`utf8`):isUndefined(t)||B.retry.writeSync(r)(s,t,0,t.length,0),n.fsync!==!1&&(n.fsyncWait===!1?B.attempt.fsync(s):B.retry.fsyncSync(r)(s)),B.retry.closeSync(r)(s),s=null,n.chown&&(n.chown.uid!==na||n.chown.gid!==ra)&&B.attempt.chownSync(a,n.chown.uid,n.chown.gid),n.mode&&n.mode!==438&&B.attempt.chmodSync(a,n.mode);try{B.retry.renameSync(r)(a,e)}catch(t){if(!isException(t)||t.code!==`ENAMETOOLONG`)throw t;B.retry.renameSync(r)(a,V.truncate(e))}i(),a=null}finally{s&&B.attempt.closeSync(s),a&&V.purge(a)}}t(writeFileSync$1,`writeFileSync`);var ua=/* @__PURE__ */ 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})),da=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=ua();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]=/* @__PURE__ */ 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]||/* @__PURE__ */ 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})),H=/* @__PURE__ */ 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=ua(),n=da();var r=ua();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=da();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?`
170
+ `:``},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]=/* @__PURE__ */ 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){return e instanceof t.Name?replaceName(e):canOptimize(e)?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),[])):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})`}})),U=/* @__PURE__ */ 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=H(),n=ua();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})),fa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();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`)}})),pa=/* @__PURE__ */ 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=H(),n=U(),r=fa();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}){
171
+ /* istanbul ignore if */
172
+ 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])}})),ma=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=pa(),n=H(),r=fa(),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)}})),ha=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=/* @__PURE__ */ 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})),ga=/* @__PURE__ */ 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})),_a=/* @__PURE__ */ 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=ha(),n=ga(),r=pa(),i=H(),a=U();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=/* @__PURE__ */ 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
173
  || (${l} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${l} === "boolean" || ${a} === null
169
174
  || (${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=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},
175
+ || ${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}}})),va=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=H(),n=U();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)}`)}})),ya=/* @__PURE__ */ 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=H(),n=U(),r=fa(),i=U();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;
176
+ /* istanbul ignore if */
177
+ 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})),ba=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=H(),n=fa(),r=ya(),i=pa();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){
178
+ /* istanbul ignore if */
179
+ 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})),xa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=H(),n=U();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=/* @__PURE__ */ 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})),Sa=/* @__PURE__ */ 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}})),Ca=/* @__PURE__ */ 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`)}})),wa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=U(),n=Sa(),r=Ca(),i=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ 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/* @__PURE__ */ Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=getSchemaRefs})),Ta=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=ma(),n=_a(),r=ga(),i=_a(),a=va(),s=ba(),c=xa(),l=H(),u=fa(),f=wa(),p=U(),m=pa();function validateFunctionCode(e){isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))?topSchemaObjCode(e):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){isSchemaObj(e)&&(checkKeywords(e),schemaCxtHasRules(e))?subSchemaObjCode(e,n):(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){t.length&&(e.dataTypes.length?(t.forEach(t=>{includesType(e.dataTypes,t)||strictTypesError(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),narrowSchemaTypes(e,t)):e.dataTypes=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){e===void 0?(this.error(),this.allErrors||this.gen.if(!1)):(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){t?(this.setParams(t),this._error(e,n),this.setParams({})):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){
180
+ /* istanbul ignore if */
181
+ 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})),Ea=/* @__PURE__ */ 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})),Da=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wa();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})),Oa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=H(),n=Ea(),r=fa(),i=wa(),a=U(),s=Ta();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:/* @__PURE__ */ 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=/* @__PURE__ */ 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}})),ka=/* @__PURE__ */ 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}})),Aa=/* @__PURE__ */ 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(`:`)}else 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}})),ja=/* @__PURE__ */ r(((e,t)=>{let{isUUID:n}=Aa(),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}})),Ma=/* @__PURE__ */ r(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:s,nonSimpleDomain:c}=Aa(),{SCHEMES:l,getSchemeHandler:u}=ja();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})),Na=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ma();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Pa=/* @__PURE__ */ 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=Ta();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=H();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=Ea(),i=Da(),a=ha(),s=Oa(),c=H(),l=wa(),u=_a(),f=U(),p=ka(),m=Na(),defaultRegExp=(e,t)=>new RegExp(e,t);defaultRegExp.code=`new RegExp`;let h=[`removeAdditional`,`useDefaults`,`coerceTypes`],g=/* @__PURE__ */ 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=/* @__PURE__ */ new Set,this._loading={},this._cache=/* @__PURE__ */ 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){
182
+ /* istanbul ignore if */
183
+ 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);else{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 x=/^[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(!x.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 S={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function schemaOrData(e){return{anyOf:[e,S]}}})),Fa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),Ia=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Da(),n=ya(),r=H(),i=fa(),a=Oa(),s=U(),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);return h instanceof a.SchemaEnv?callValidate(h):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})),La=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Fa(),n=Ia();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Ra=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),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})`)}}})),za=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();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}))`)}}})),Ba=/* @__PURE__ */ 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`})),Va=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),r=Ba();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}`)}}})),Ha=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ya(),n=U(),r=H();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})`)}}}})),Ua=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();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}`)}}})),Wa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ya(),n=H(),r=U();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)}}}})),Ga=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();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}`)}}})),Ka=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Sa();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),qa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_a(),n=H(),r=U(),i=Ka();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)})))}}}})),Ja=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),r=Ka();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}`)}}})),Ya=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),r=Ka();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{
184
+ /* istanbul ignore if */
185
+ 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}`}}}})),Xa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ra(),n=za(),r=Va(),i=Ha(),a=Ua(),s=Wa(),c=Ga(),l=qa(),u=Ja(),f=Ya();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]})),Za=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=H(),n=U(),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;Array.isArray(i)?validateAdditionalItems(e,i):(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`)}};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})),Qa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=H(),n=U(),r=ya(),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})),$a=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qa();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),eo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),r=ya(),i=Za();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)))}}})),to=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U();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)))}}}})),no=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=H(),n=U(),r=ya();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
186
  missingProperty: ${i},
172
187
  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=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(`
188
+ 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})),ro=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U();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)}}})),io=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ya(),n=H(),r=fa(),i=U();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;
189
+ /* istanbul ignore if */
190
+ 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);else if(s===!1)e.setParams({additionalProperty:t}),e.error(),p||a.break();else 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)}}}})),ao=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ta(),n=ya(),r=U(),i=io();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)}}}})),oo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ya(),n=H(),r=U(),i=U();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())})})}}}})),so=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=U();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`}}})),co=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:ya().validateUnion,error:{message:`must match a schema in anyOf`}}})),lo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U();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;
191
+ /* istanbul ignore if */
192
+ 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)})})}}}})),uo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=U();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;
193
+ /* istanbul ignore if */
194
+ 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)})}}})),fo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),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})),po=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=U();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`)}}})),mo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Za(),n=$a(),r=Qa(),i=eo(),a=to(),s=no(),c=ro(),l=io(),u=ao(),f=oo(),p=so(),m=co(),h=lo(),g=uo(),v=fo(),y=po();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})),ho=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=H(),n=fa(),r=Oa(),i=Ia(),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})),go=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=H(),n=fa(),r=Ia(),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})),_o=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ho(),n=U();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),vo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=go();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),yo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ho(),n=go(),r=_o(),i=vo();e.default=[t.default,n.default,r.default,i.default]})),bo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=no();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),xo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=no();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),So=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=U();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`)}}})),Co=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bo(),n=xo(),r=So();e.default=[t.default,n.default,r.default]})),wo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U(),r=fa();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;
195
+ /* istanbul ignore if */
196
+ 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();else 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)}}}})),To=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=U();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())})}}}})),Eo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wo(),n=To();e.default=[t.default,n.default]})),Do=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H();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})`}}}}})),Oo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Do().default]})),ko=/* @__PURE__ */ 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`]})),Ao=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=La(),n=Xa(),r=mo(),i=yo(),a=Co(),s=Eo(),c=Oo(),l=ko();e.default=[i.default,t.default,n.default,(0,r.default)(!0),c.default,l.metadataVocabulary,l.contentVocabulary,a.default,s.default]})),jo=/* @__PURE__ */ 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={}))})),Mo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=H(),n=jo(),r=Oa(),i=Da(),a=U();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}}}}})),No=/* @__PURE__ */ 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}}}})),Po=/* @__PURE__ */ 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`}}}}})),Fo=/* @__PURE__ */ 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`}}}})),Io=/* @__PURE__ */ 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`}}}})),Lo=/* @__PURE__ */ 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`}}}})),Ro=/* @__PURE__ */ 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`}}}})),zo=/* @__PURE__ */ 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}}}})),Bo=/* @__PURE__ */ 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:[]}}}})),Vo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=No(),n=Po(),r=Fo(),i=Io(),a=Lo(),s=Ro(),c=zo(),l=Bo(),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})),Ho=/* @__PURE__ */ 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=Pa(),r=Ao(),i=Mo(),a=Vo(),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=Ta();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=H();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=Ea();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var f=Da();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Uo=/* @__PURE__ */ 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=(/* @__PURE__ */ new Date(`2020-01-01T`+e)).valueOf(),r=(/* @__PURE__ */ 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}}})),Wo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=La(),n=Xa(),r=mo(),i=Oo(),a=ko();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Go=/* @__PURE__ */ 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}})),Ko=/* @__PURE__ */ 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=Pa(),r=Wo(),i=Mo(),a=Go(),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=Ta();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=H();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=Ea();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Da();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),qo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Ko(),n=H(),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})),Jo=/* @__PURE__ */ r(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Uo(),r=qo(),i=H(),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})),Yo=Ho(),Xo=/* @__PURE__ */ n(Jo(),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}`,Zo=Object.getOwnPropertyDescriptor(Function.prototype,`toString`),Qo=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",Qo);let{writable:a,enumerable:s,configurable:c}=Zo;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},$o=Object.prototype.toString;function isType(e,t,n){return e?e.constructor===t||$o.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/* @__PURE__ */ 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 es={utf8:new globalThis.TextDecoder(`utf8`)};function uint8ArrayToString(e,t=`utf8`){return assertUint8ArrayOrArrayBuffer(e),es[t]??=new globalThis.TextDecoder(t),es[t].decode(e)}function assertString(e){if(typeof e!=`string`)throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}const ts=new globalThis.TextEncoder;function stringToUint8Array(e){return assertString(e),ts.encode(e)}Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));const ns=`aes-256-cbc`,rs=/* @__PURE__ */ new Set([`aes-256-cbc`,`aes-256-gcm`,`aes-256-ctr`]),isSupportedEncryptionAlgorithm=e=>typeof e==`string`&&rs.has(e),createPlainObject=()=>Object.create(null),isExist=e=>e!==void 0,checkValueType=(e,t)=>{let n=/* @__PURE__ */ 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`)},is=`__internal__`,as=`${is}.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??ns,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 ${is} 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=j.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,is))try{let t=j.readFileSync(this.path,this.#t?null:`utf8`),n=this._decryptData(t),r=this._deserialize(n);hasProperty(r,is)&&setProperty(e,is,getProperty(r,is))}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&&=(j.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=vn.pbkdf2Sync(t,e,1e4,32,`sha512`),c=vn.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;rt(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();rt(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(){j.mkdirSync(T.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e),n=this.#t;if(n){let e=vn.randomBytes(16),r=vn.pbkdf2Sync(n,e,1e4,32,`sha512`),i=vn.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(M.env.SNAP)j.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`){j.writeFileSync(this.path,t,{mode:this.#r.configFileMode});return}throw e}}_watch(){if(this._ensureDirectory(),j.existsSync(this.path)||this._write(createPlainObject()),M.platform===`win32`||M.platform===`darwin`){this.#c??=debounceFunction(()=>{this.events.dispatchEvent(new Event(`change`))},{wait:100});let e=T.dirname(this.path),t=T.basename(this.path);this.#o=j.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}),j.watchFile(this.path,{persistent:!1},(e,t)=>{typeof this.#c==`function`&&this.#c()}),this.#s=!0}_migrate(e,t,n){let r=this._get(as,`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(as,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)||!qi.default.eq(r,t))&&this._set(as,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===is||e.startsWith(`${is}.`)}_isVersionInRangeFormat(e){return qi.default.clean(e)===null}_shouldPerformMigration(e,t,n){return this._isVersionInRangeFormat(e)?t!==`0.0.0`&&qi.default.satisfies(t,e)?!1:qi.default.satisfies(n,e):!(qi.default.lte(e,t)||qi.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??=ns,!isSupportedEncryptionAlgorithm(t.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...rs].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=Xo.default.default,n=new Yo.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 T.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{xn.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{xn.deepEqual(r,i)}catch{this._write(i)}this._migrate(t,n,e.beforeEachMigration)}finally{this.#a=!1}}}};const os={name:In,version:Ln},ss=Me(()=>{try{return new Conf({projectName:In,clearInvalidConfig:!0,watch:!1})}catch(e){L.debug(`Failed to create config store`,{error:e});return}}),cs=`check-update`;async function notifyAvailableUpdate(){if(Xt||Qt||$t===cs||isInsideContainer())return;let e=ss();if(!e)return;let t=e.get(`lastUpdateCheck`),n=e.get(`latestVersion`);if(we(n)||we(t)||t+864e5<Date.now())try{Bt(`likec4`,[`check-update`],{stdio:`ignore`,timeout:5e3,preferLocal:!0,detached:!0,env:{NODE_ENV:cs}}).catch(()=>{})}catch{}else n&&(0,qi.gt)(n,os.version)&&boxen([`Update available: `,m.dim(os.version),m.reset(` → `),m.green(n)].join(``))}async function checkAvailableUpdate(e=!0){try{let t=ss();t?.set({lastUpdateCheck:Date.now()});let n=await fetchLatestVersion();if(A(n,`No version found in latest npm`),t?.set({lastUpdateCheck:Date.now(),latestVersion:n}),(0,qi.gt)(n,os.version)){boxen([`Update available: `,m.dim(os.version),m.reset(` → `),m.green(n)].join(``));return}e&&boxen(m.dim(`Up to date: `)+` `+m.green(os.version))}catch(e){L.warning(i(e))}}async function fetchLatestVersion(){return(await ni(`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!!nt.createRequire(import.meta.url).resolve(e)}catch(e){return L.debug(i(e)),!1}}async function ensureReact(){if(isInstalled(`react`)&&isInstalled(`react-dom`)){L.debug(`react already installed`);return}L.warn(`react not installed`);let e=await et();e||(L.error`Package manager not detected, please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));let t=$e(e.agent,`add`,[`react`,`react-dom`]);t||(L.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));try{await Bt(t.command,t.args,{stdio:`inherit`})}catch(e){L.debug(i(e)),L.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1)}}async function ensurePlaywright(){if(isInstalled(`playwright`)){L.debug(`playwright already installed`);return}L.warn(`playwright not installed`);let e=await et();e||(L.error`Package manager not detected, please install dependencies manually: ${`playwright`}`,process.exit(1));let t=$e(e.agent,`add`,[`playwright`]);t||(L.error`Please install dependencies manually: ${`playwright`}`,process.exit(1));try{await Bt(t.command,t.args,{preferLocal:!0,stdio:`inherit`})}catch(e){L.debug(i(e)),L.error`Please install dependencies manually: ${`playwright`}`,process.exit(1)}}const W={type:`string`,desc:`<directory> with LikeC4 sources (default is current directory or 'LIKEC4_WORKSPACE' env)`,normalize:!0,default:Yt.LIKEC4_WORKSPACE||`.`,coerce:D},G={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()},ls={boolean:!0,type:`boolean`,desc:"use `@likec4/core` package in types",default:!1},us={boolean:!0,type:`boolean`,desc:`use hash history for navigation, e.g. "/#/view" instead of "/view"`},ds={alias:[`o`,`output`],string:!0,desc:`output directory`,normalize:!0,nargs:1,coerce:D},fs={alias:`w`,string:!0,desc:`prefix for Webcomponents, e.g "c4" generates <c4-view ../>`,default:`likec4`,nargs:1},ps={alias:`t`,string:!0,desc:`base title of the app pages (default is "LikeC4")`,default:`LikeC4`,nargs:1},ms={choices:[`light`,`dark`],desc:`default color scheme for the built website (default: auto, follows system preference)`,nargs:1},hs={alias:[`base-url`],string:!0,desc:`base url the app is being served from, e.g. "/" or "/pages/"`,nargs:1},gs={boolean:!0,desc:`outputs a single self-contained HTML file with all required resources inlined`},_s={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:D},vs={array:!0,string:!0,desc:`hostname allowed to respond to (Vite server.allowedHosts); can be repeated. Defaults to allowing all hosts.`,requiresArg:!0},ys={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},bs={number:!0,desc:`port number for the dev server (default is 5173, or PORT environment variable)`,nargs:1},xs={number:!0,desc:`port number for the HMR WebSocket server (default is auto-discovered from 24678-24690, or HMR_PORT environment variable)`,nargs:1},Ss={alias:`p`,string:!0,desc:`select LikeC4 project by name (e.g. "my-project") or by path`,nargs:1},Cs={hidden:!0,nargs:1,desc:`force log level`,choices:[`trace`,`debug`,`info`,`warning`,`error`],conflicts:[`verbose`]},ws={boolean:!0,desc:`verbose logging`,conflicts:[`log-level`]},Ts=Zt?`trace`:`debug`,Es=6e4,Ds=Es*60*24*7;function showSupportUsMessage(){if(!(Xt||Qt))try{let e=Date.now(),t=ss();if(!t)return;let n=t.get(`lastSupportUsMessage`);if(!n){t.set(`lastSupportUsMessage`,e-Ds+5*Es);return}if(n+Ds>e)return;t.set(`lastSupportUsMessage`,e),boxen([m.dim(`If you are working in a commercial environment`),m.dim(`consider supporting the project`),``,m.dim(`How to get more?`)+` `+m.underline(`https://likec4.dev/sponsor/`)].join(`
197
+ `))}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`,W).option(`output`,{alias:`o`,type:`string`,desc:`output directory for production build`,normalize:!0,coerce:D}).option(`base`,hs).option(`use-hash-history`,us).option(`use-dot`,G).option(`webcomponent-prefix`,fs).option(`build-webcomponent`,{type:`boolean`,default:!0,describe:`enable/disable webcomponent build`}).option(`title`,ps).option(`output-single-file`,gs).option(`public`,_s).option(`theme`,ms).example(`${m.green(`$0 build -o ./build ./src`)}`,m.gray(`Search for likec4 files in 'src' and output static site to 'build'`)).example(`${m.green(`$0 build --theme dark -o ./build ./src`)}`,m.gray(`Build with dark color scheme as default`)).example(`${m.green(`$0 build --public ./assets -o ./build ./src`)}`,m.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 S(e.path,{graphviz:e[`use-dot`]?`binary`:`wasm`,watch:!1})),a=e.output??D(i.workspace,`dist`),s=D(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=D(t);if(n===e.workspace)return e.languageServices.projectsManager.ensureProjectId();if(Ht(n)&&qt(n).isDirectory()){L.debug`Project path exists: ${n}`;let t=ae.file(n.endsWith(xt)?n:n+xt),r=e.languageServices.projects().find(e=>e.folder.fsPath===t.fsPath);if(r)return L.debug`Found project ${r.id} at path: ${n}`,r.id;L.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 Os=L.getChild(`generator`);async function customHandler({name:e,path:t,useDotBin:n,project:r}){try{var i=_usingCtx();let a=startTimer(Os),s=i.a(await S(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:c,config:l}=ensureProject(s,r);r&&Os.info(`${m.dim(`project`)} ${m.green(c)}`);let u=l.generators?.[e];if(!u)throw Os.error(m.red(`generator ${e} does not exist in project config`)),Error(`generator ${e} does not exist in project config`);Os.info(`${m.dim(`generator`)} ${m.green(e)}`),await runCustomGenerator({likec4:s,model:await s.layoutedModel(c),generator:u,logger:Os.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=/* @__PURE__ */ new Set,s=i.project(t.project.id),c=t.project.id;r.debug(`${m.dim(`running for project:`)} ${m.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 It(e):t=i.locate({element:e.id,projectId:c});break;case Lt(e):t=i.locate({view:e.id,projectId:c});break;case Nt(e):t=i.locate({deployment:e.id,projectId:c});break;case Rt(e):case Ft(e):t=i.locate({relation:e.id,projectId:c});break;default:Et(e)}if(!t)throw r.error(`Cannot locate ${e.id}`,{target:e}),Error(`Cannot locate ${e.id}`);let n=ae.parse(t.uri);return{range:t.range,document:n,relativePath:se.relative(s.folder,n),folder:se.dirname(n).fsPath,filename:se.basename(n)}},write:async({path:e,content:t})=>{let n;n=Array.isArray(e)?D(s.folder.fsPath,...e):ae.isUri(e)?e.fsPath:D(s.folder.fsPath,`${e}`);let i=_t(n);a.has(i)||(Ht(i)||(r.debug(`${m.dim(`create directory`)} ${i}`),await st(i,{recursive:!0})),a.add(i)),r.debug(`${m.dim(`write`)} ${n}`),await w(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?bt(...n):`.`}async function singleFileCodegenAction(e,t,n){t??=D(e.workspace,`likec4.generated.ts`),vt(t)!==`.ts`&&(t+=`.ts`),await st(_t(t),{recursive:!0});let r=generateViewsDataTs([...await e.diagrams()]);await w(t,r),n.info(`${m.dim(`generated`)} ${E(process.cwd(),t)}`)}async function dotCodegenAction(e,t,n){await st(t,{recursive:!0}),n.info(`${m.dim(`format`)} ${m.green(`dot`)}`),n.info(`${m.dim(`outdir`)} ${t}`);let r=/* @__PURE__ */ new Set,i=await e.computedModel(),a=Ie(i.$data.views),s=0;for(let c of a)try{let a=await e.viewsService.layouter.dot({view:c,styles:i.$styles}),l=D(t,relativeOutputDir(c.sourcePath));r.has(l)||(await st(l,{recursive:!0}),r.add(l));let u=D(l,c.id+`.dot`);await w(u,a),n.info(`${m.dim(`generated`)} ${E(process.cwd(),u)}`),s++}catch(e){L.error(`error while generating ${c.id}`,{error:e})}s>0&&n.info(`${m.dim(`total`)} ${s} files`)}async function multipleFilesCodegenAction(e,t,n,r){await st(n,{recursive:!0}),r.info(`${m.dim(`format`)} ${m.green(t)}`),r.info(`${m.dim(`outdir`)} ${n}`);let i,a;switch(t){case`d2`:i=`.d2`,a=Ge;break;case`mermaid`:i=`.mmd`,a=Xe;break;case`plantuml`:i=`.puml`,a=Je;break;default:Et(t)}let s=/* @__PURE__ */ new Set,c=await e.layoutedModel(),l=0;for(let e of c.views()){let t=e.$view;try{let c=D(n,relativeOutputDir(t.sourcePath));s.has(c)||(await st(c,{recursive:!0}),s.add(c));let u=D(c,t.id+i),f=a(e);await w(u,f),r.info(`${m.dim(`generated`)} ${E(process.cwd(),u)}`),l++}catch(e){r.error(`error while generating ${t.id}`,{error:e})}}l>0&&r.info(`${m.dim(`total`)} ${l} files`)}async function legacyHandler({path:e,useDotBin:t,...n}){let r=createLikeC4Logger(`c4:codegen`),i=startTimer(r),a=await S(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:Et(n)}i.stopAndLog()}const ks=_t(gn(import.meta.url));function readVersion(){try{let e=JSON.parse(Ut(bt(ks,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}try{let e=JSON.parse(Ut(bt(ks,`..`,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}return`0.1.0`}const As=readVersion(),js=`leanix`,Ms=/* @__PURE__ */ 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(!Ms.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 Ns={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:{...Ns.factSheetTypes},relationTypes:{...Ns.relationTypes},metadataToFields:{...Ns.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 Ps={manifestVersion:`1.0`,bridgeVersion:As,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={...Ps,...t,generatedAt:t.generatedAt??(/* @__PURE__ */ 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??(/* @__PURE__ */ 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
198
  query FindFactSheet($name: String!, $type: String!) {
176
199
  allFactSheets(filter: { name: $name, factSheetType: $type }) {
177
200
  edges { node { id name type } }
@@ -201,7 +224,7 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
201
224
  relation { id }
202
225
  }
203
226
  }
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=`
227
+ `,{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,[js]:{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=/* @__PURE__ */ 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?.[js];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,[js]:{relationId:n,...c.external?.[js]}}});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??(/* @__PURE__ */ 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??(/* @__PURE__ */ 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
228
  query AllFactSheets($first: Int!, $after: String, $filter: FilterInput) {
206
229
  allFactSheets(first: $first, after: $after, filter: $filter) {
207
230
  edges {
@@ -235,26 +258,26 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
235
258
  }
236
259
  }
237
260
  }
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
- ${S.dim(`Source generated:`)}
240
- ${qt(Ln(),h)}
241
-
242
- ${S.dim(`How to use:`)}
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:[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
- ${S.dim(`Sources generated:`)}
246
- ${qt(Ln(),m)}
247
- ${qt(Ln(),ee)}
248
-
249
- ${S.dim(`How to use:`)}
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(!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
- ${S.dim(`Webcomponents generated to:`)}
253
- ${qt(Ln(),m)}
254
-
255
- ${S.dim(`Setup and usage instructions:`)}
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`,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:`)}
261
+ `,{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?.[js],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??(/* @__PURE__ */ new Date()).toISOString(),i=n.dryRun,a=[],s=[],c=[],l=new Map(e.factSheets.map(e=>[e.id,e])),u=/* @__PURE__ */ new Map,f=/* @__PURE__ */ 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=/* @__PURE__ */ 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 Fs=`No project or empty model`,Is=`LEANIX_API_TOKEN is required for likec4 sync leanix --apply`,Ls=`default`,Rs=`manifest.json`,zs=`leanix-dry-run.json`,Bs=`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:Ls}),n=toLeanixInventoryDryRun(e,{mappingProfile:Ls});return{manifest:t,dryRun:n,report:buildBridgeReport(t,n)}}async function writeBridgeArtifacts(e,t,n,r=process.cwd()){await st(e,{recursive:!0});let i=D(e,Rs),a=D(e,zs),s=D(e,Bs);await w(i,JSON.stringify(t.manifest,null,2)),await w(a,JSON.stringify(t.dryRun,null,2)),await w(s,JSON.stringify(t.report,null,2)),n.info(`${m.dim(`generated`)} ${E(r,i)}`),n.info(`${m.dim(`generated`)} ${E(r,a)}`),n.info(`${m.dim(`generated`)} ${E(r,s)}`)}const Vs={manifest:Rs,dryRun:zs,report:Bs};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 S(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${m.dim(`project`)} ${m.green(n)}`);let l=await e.layoutedModel(n);if(l===tt.EMPTY)throw t.error(Fs),Error(Fs);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 st(r,{recursive:!0});let s=D(r,`leanix-inventory-snapshot.json`);await w(s,JSON.stringify(a,null,2)),t.info(`${m.dim(`generated`)} ${E(process.cwd(),s)}`),t.info(`${m.dim(`snapshot`)} ${a.factSheets.length} fact sheets, ${a.relations.length} relations`)}finally{n.stopAndLog()}}const Hs=`manifest.json`,Us=`leanix-inventory-snapshot.json`;async function readManifestAndSnapshot(e){let t=D(e,Hs),n=D(e,Us),[r,i]=await Promise.all([ut(t,`utf-8`),ut(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 S(e,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:a}=ensureProject(i,t),s=await i.layoutedModel(a);return s===tt.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 ${Hs} or ${Us} 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=D(i,`reconciliation-report.json`);await w(u,JSON.stringify(l,null,2)),t.info(`${m.dim(`generated`)} ${E(process.cwd(),u)}`),t.info(`${m.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 S(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:f,projectFolder:p}=ensureProject(u,i);i&&c.info(`${m.dim(`project`)} ${m.green(f)}`),c.info(`${m.dim(`format`)} ${m.green(`model`)} ${a?m.cyan(`(compute only)`):``}`);let h;if(a)h=await u.computedModel(f);else{h=await u.layoutedModel(f);for(let e of h.views())e.hasLayoutDrifts&&c.warn(m.yellow(`layout drift detected, view:`)+` `+m.red(e.id))}let g=D(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-model.ts`);if(r&&(g=yt(r)?r:D(r),Ht(r)&&(await mt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let v=ht(g);c.info(`${m.dim(`filename`)} ${v}`);let y=vt(v).toLocaleLowerCase();if(![`.ts`,`.mts`,`.cts`].includes(y))throw c.error(`output file ${r} has extension "${y}"`),Error(`output file ${r} must be a .ts, .mts or .cts file`);let b=_t(g);c.info(`${m.dim(`outdir`)} ${b}`),await st(b,{recursive:!0}),await w(g,generateLikeC4Model(h,{useCorePackage:n}),{encoding:`utf-8`}),l.stopAndLog(),boxen(Ve(`
262
+ ${m.dim(`Source generated:`)}
263
+ ${E(tn(),g)}
264
+
265
+ ${m.dim(`How to use:`)}
266
+ ${m.underline(`https://likec4.dev/tooling/code-generation/model/`)}
267
+ `).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(`${m.cyan(`likec4 app root`)} ${m.dim(relativeToCwd(i))}`),r.info(m.cyan(`outDir`)+` `+m.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(\/.*)?$/,/@likec4\/core.*/]}},plugins:[Qe({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 S(e,{graphviz:t?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,i);i&&s.info(`${m.dim(`project`)} ${m.green(u)}`),s.info(`${m.dim(`format`)} ${m.green(`react`)}`);let p=await l.diagrams(u);if(p.length===0)throw process.exitCode=1,Error(`no views found`);p.forEach(e=>{e.drifts&&e.drifts.length>0?s.info(m.yellow(`layout drift detected, view:`)+` `+m.red(e.id)):e.hasLayoutDrift&&s.warn(m.yellow(`drift detected, manual layout can not be applied, view:`)+` `+m.red(e.id))});let h=D(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(r&&(h=yt(r)?r:D(r),Ht(r)&&(await mt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let g=_t(h);s.info(`${m.dim(`outdir`)} ${g}`);let v=ht(h);s.info(`${m.dim(`filename`)} ${v}`);let y=vt(v).toLocaleLowerCase();if(![`.js`,`.mjs`,`.jsx`].includes(y))throw s.error(`output file ${r} has extension "${y}"`),Error(`output file ${r} must be a .js, .jsx or .mjs`);let b=await viteReactConfig({languageServices:l,outDir:g,filename:v});await fn({...b,logLevel:`warn`});let x=await l.layoutedModel(u),ee=D(g,ht(h,y)+(y===`.mjs`?`.d.mts`:`.d.ts`));await w(ee,generateReactTypes(x,{useCorePackage:n})),c.stopAndLog(),boxen(Ve(`
268
+ ${m.dim(`Sources generated:`)}
269
+ ${E(tn(),h)}
270
+ ${E(tn(),ee)}
271
+
272
+ ${m.dim(`How to use:`)}
273
+ ${m.underline(`https://likec4.dev/tooling/code-generation/react/`)}
274
+ `),{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 S(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:u,projectFolder:f}=ensureProject(l,e);e&&s.info(`${m.dim(`project`)} ${m.green(u)}`),s.info(`${m.dim(`format`)} ${m.green(`webcomponent`)}`);let p=await l.diagrams(u);if(!Se(p,1))throw s.warn(`no views found`),process.exitCode=1,Error(`no views found`);p.forEach(e=>{e.hasLayoutDrift&&s.warn(m.yellow(`drift detected, manual layout can not be applied, view:`)+` `+m.red(e.id))});let h=D(l.projectsManager.hasMultipleProjects()?f:l.workspace,`likec4-views.js`);if(i&&(h=yt(i)?i:D(i),Ht(i)&&(await mt(i)).isDirectory()))throw Error(`output file is a directory: ${i}`);s.debug(`${m.dim(`outfilepath`)} ${h}`);let g=ht(h);s.debug(`${m.dim(`filename`)} ${g}`);let v=vt(g).toLocaleLowerCase();if(v!==`.js`&&v!==`.mjs`)throw s.warn(`output file ${i} has extension "${v}"`),Error(`output file ${i} must be a .js or .mjs`);let y=await mkTempPublicDir();s.debug(`${m.dim(`created temp public`)} ${y}`);let b=viteWebcomponentConfig({languageServices:l,outDir:y,filename:g,webcomponentPrefix:r,base:`/`});s.debug(`${m.dim(`vite build webcomponent`)}`),await fn({...b,logLevel:`warn`});let x=D(y,g);if(!Ht(x))throw Error(`output file not found: ${x}`);await st(_t(h),{recursive:!0}),await at(x,h),s.info(`${m.dim(`generated`)} ${h}`),s.debug(`${m.dim(`remove temp public`)}`),await pt(y,{recursive:!0,force:!0}),c.stopAndLog(),boxen(Ve(`
275
+ ${m.dim(`Webcomponents generated to:`)}
276
+ ${E(tn(),h)}
277
+
278
+ ${m.dim(`Setup and usage instructions:`)}
279
+ ${m.blue(`https://likec4.dev/tooling/code-generation/webcomponent/`)}
280
+ `))}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`,W).command(`react [path]`,`generate react component to render likec4 view`,e=>e.positional(`path`,W).option(`project`,Ss).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.jsx, .mjs or .js)`,normalize:!0,coerce:D}).option(`use-dot`,G).option(`use-core-package`,ls),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`,W).option(`project`,Ss).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.mjs or .js)`,normalize:!0,coerce:D}).option(`webcomponent-prefix`,fs).option(`use-dot`,G),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`,W).option(`project`,Ss).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.ts)`,normalize:!0,coerce:D}).option(`skip-layout`,{type:`boolean`,desc:`Skip layout (produce compute-only model, faster)`}).option(`use-dot`,G).option(`use-core-package`,ls),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`,W).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> output .ts file`,normalize:!0,coerce:D}).option(`use-dot`,G),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`,W).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`,W).option(`outdir`,{...ds,desc:`<dir> output directory for manifest.json, leanix-dry-run.json, report.json`}).option(`project`,Ss).option(`use-dot`,G).example(`${m.green(`$0 gen leanix dry-run -o out/bridge`)}`,m.gray(`Write bridge artifacts to out/bridge`)),async e=>{await leanixDryRunHandler({path:e.path,outdir:e.outdir??D(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`,{...ds,default:D(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(`${m.green(`$0 gen leanix inventory -o out/bridge`)}`,m.gray(`Requires LEANIX_API_TOKEN`)),async e=>{await leanixInventorySnapshotHandler({outdir:e.outdir??D(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`,W).option(`outdir`,{...ds,default:D(process.cwd(),`out`,`bridge`),desc:`<dir> directory with manifest.json and leanix-inventory-snapshot.json`}).option(`project`,Ss).option(`use-dot`,G).example(`${m.green(`$0 gen leanix reconcile -o out/bridge`)}`,m.gray(`Reads manifest + snapshot from outdir; optional workspace for name+type matching`)),async e=>{await leanixReconcileHandler({path:e.path,outdir:e.outdir??D(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`,W).option(`outdir`,ds).option(`use-dot`,G),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`,W).option(`outdir`,ds).option(`use-dot`,G),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`,W).option(`outdir`,ds).option(`use-dot`,G),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`,W).option(`outdir`,ds).option(`use-dot`,G),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`,W).option(`project`,Ss).option(`use-dot`,G),handler:async e=>{await customHandler({name:`custom`,path:e.path,project:e.project,useDotBin:e.useDotBin})}}).epilog(`${m.bold(`Examples:`)}
258
281
  likec4 gen react -o dist/likec4-views.mjs ./src/likec4
259
282
  likec4 gen model -o likec4-model.ts
260
283
  likec4 gen leanix dry-run -o out/bridge
@@ -265,87 +288,88 @@ const createInstance=e=>{let ky=(t,n)=>bi.create(t,validateAndMerge(e,n));for(le
265
288
  likec4 gen mmd --outdir assets/
266
289
  likec4 gen plantuml --outdir assets/
267
290
  likec4 gen dot -o out .
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
-
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
- ${S.green(`$0 export drawio`)}
272
- ${S.gray(`Export each view to a separate .drawio file`)}
273
-
274
- ${S.green(`$0 export drawio --all-in-one -o ./diagrams src/`)}
275
- ${S.gray(`Export all views as tabs in one .drawio file`)}
276
-
277
- ${S.green(`$0 export drawio --roundtrip -o ./out`)}
278
- ${S.gray(`Re-apply layout/waypoints from comment blocks (e.g. after import from DrawIO)`)}
279
-
280
- ${S.green(`$0 export drawio --uncompressed -o ./out`)}
281
- ${S.gray(`Export with raw XML (no compression) for draw.io desktop compatibility`)}
282
-
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 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
- `+``.padEnd(9,` `)),e.resolvedUrls.network.length?S.dim(`Network: `)+e.resolvedUrls.network.join(`
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
- `+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&&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
- 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
- ${S.green(`$0 export png`)}
293
- ${S.gray(`Search for likec4 files in current directory and output PNG next to sources`)}
294
-
295
- ${S.green(`$0 export png --theme dark -o ./png src/likec4`)}
296
- ${S.gray(`Search for likec4 files in src/likec4 and output PNG with dark theme to png folder`)}
297
-
298
- ${S.green(`$0 export png -f "team1*" -f "team2*" --flat -o ./png src/likec4`)}
299
- ${S.gray(`Export views matching team1* or team2* only`)}
300
-
301
- ${S.green(`$0 export png -f "use-case*" --sequence src/likec4`)}
302
- ${S.gray(`Export views matching use-case* using sequence layout`)}
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
- 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
- ${S.green(`$0 export jpg`)}
306
- ${S.gray(`Search for likec4 files in current directory and output JPEG next to sources`)}
307
-
308
- ${S.green(`$0 export jpg --theme dark -o ./jpg src/likec4`)}
309
- ${S.gray(`Search for likec4 files in src/likec4 and output JPEG with dark theme to jpg folder`)}
310
-
311
- ${S.green(`$0 export jpg --quality 90 -o ./jpg src/likec4`)}
312
- ${S.gray(`Export JPEG with 90% quality`)}
313
-
314
- ${S.green(`$0 export jpg -f "team1*" -f "team2*" --flat -o ./jpg src/likec4`)}
315
- ${S.gray(`Export views matching team1* or team2* only`)}
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
- ${S.green(`$0 export json --skip-layout`)}
318
- ${S.gray(`Search for likec4 files in current directory and output JSON to likec4.json (no layout)`)}
319
-
320
- ${S.green(`$0 export json --pretty -o ./generated/likec4.json src/likec4 `)}
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 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
- ${S.green(`$0 export markdown`)}
324
- ${S.gray(`Render every project to README.md in its own project folder`)}
325
-
326
- ${S.green(`$0 export markdown -p my-project src/likec4`)}
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=>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
-
331
- ${S.green(`$0 lsp --stdio `)}
332
- ${S.gray(`Start LSP with stdio transport`)}
333
-
334
- ${S.green(`$0 lsp --node-ipc --watch --no-manual-layouts --no-color `)}
335
- ${S.gray(`Start LSP with node-ipc transport and watcher, disabled manual layouts and disabled color`)}
336
-
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
291
+ `),handler:async e=>{await customHandler({name:e.command,path:e.path,project:e.project,useDotBin:e.useDotBin})}}),Ws=/* @__PURE__ */ new Set([`node_modules`,`.git`]);function isSourceFile(e){return e.endsWith(`.c4`)||e.endsWith(`.likec4`)}function joinNonEmptyFiles(e,t=`
292
+
293
+ `){return e.filter(e=>e.trim()!==``).join(t)}const Gs=`No project or empty model`,Ks=`No views could be exported`;function getDrawioEpilog(){return`${m.bold(`Examples:`)}
294
+ ${m.green(`$0 export drawio`)}
295
+ ${m.gray(`Export each view to a separate .drawio file`)}
296
+
297
+ ${m.green(`$0 export drawio --all-in-one -o ./diagrams src/`)}
298
+ ${m.gray(`Export all views as tabs in one .drawio file`)}
299
+
300
+ ${m.green(`$0 export drawio --roundtrip -o ./out`)}
301
+ ${m.gray(`Re-apply layout/waypoints from comment blocks (e.g. after import from DrawIO)`)}
302
+
303
+ ${m.green(`$0 export drawio --uncompressed -o ./out`)}
304
+ ${m.gray(`Export with raw XML (no compression) for draw.io desktop compatibility`)}
305
+
306
+ ${m.green(`$0 export drawio --profile leanix -o ./out`)}
307
+ ${m.gray(`Export with bridge-managed metadata (likec4Id, likec4ViewId, etc.) for LeanIX interoperability`)}`}function toError(e){return e instanceof Error?e:Error(i(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=/* @__PURE__ */ new Set;async function walk(e,i){if(i>=50)return;let a=await ft(e).catch(()=>null);if(a==null||r.has(a))return;r.add(a);let s=await dt(e,{withFileTypes:!0}).catch(n=>(t?.debug&&t.debug(`${m.dim(`Roundtrip:`)} readdir failed`,{dir:e,err:n}),[]));for(let r of s){let a=bt(e,r.name);switch(!0){case r.isDirectory():Ws.has(r.name)||await walk(a,i+1);break;case r.isSymbolicLink():if((await mt(a).catch(()=>null))?.isFile()&&isSourceFile(r.name)){let e=await ut(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${m.dim(`Roundtrip:`)} readFile failed`,{file:a,err:e}),``));e&&n.push(e)}break;case r.isFile()&&isSourceFile(r.name):{let e=await ut(a,`utf-8`).catch(e=>(t?.debug&&t.debug(`${m.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(D(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 Ke(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=Ye(t,u),p=D(n,Ze);await w(p,f),l.info(`${m.dim(`generated`)} ${E(process.cwd(),p)} (${t.length} tab(s))`)}async function writeViewToFile(e,t,n,r){let i=String(e.$view.id);try{let a=We(e,t[i]),s=D(n,i+`.drawio`);return await st(_t(s),{recursive:!0}),await w(s,a),r.info(`${m.dim(`generated`)} ${E(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 S(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===tt.EMPTY)throw t.error(Gs),Error(Gs);let c=[...s.views()];if(c.length===0)throw t.error(`No views to export`),Error(Ks);await st(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(Ks),Error(Ks);t.info(`${m.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`,W).option(`outdir`,{alias:`o`,type:`string`,desc:`<dir> output directory for .drawio files`,normalize:!0,coerce:D}).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:Ss,"use-dot":G}).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 Ce(e.resolvedUrls.network)??Ce(e.resolvedUrls.local)}function printServerUrls(e){if(!e.resolvedUrls)throw Error(`Vite server is not ready, no resolvedUrls`);boxen([m.green(`LikeC4 served at:`),``,m.dim(`Local: `)+e.resolvedUrls.local.join(`
308
+ `+``.padEnd(9,` `)),e.resolvedUrls.network.length?m.dim(`Network: `)+e.resolvedUrls.network.join(`
309
+ `+``.padEnd(9,` `)):void 0].filter(e=>De(e)).join(`
310
+ `))}var Locked=class extends Error{constructor(e){super(`${e} is locked`)}};const qs={old:/* @__PURE__ */ new Set,young:/* @__PURE__ */ new Set},Js=/* @__PURE__ */ new Set,Ys=1024,Xs=65535;let Zs;const getLocalHosts=()=>{let e=ln.networkInterfaces(),t=/* @__PURE__ */ 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=Cn.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=>qs.old.has(e)||qs.young.has(e)||Js.has(e),portCheckSequence=function*(e){e&&(yield*e),yield 0};async function getPorts(e){let t,n=/* @__PURE__ */ 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??{};Zs===void 0&&(Zs=setTimeout(()=>{Zs=void 0,qs.old=qs.young,qs.young=/* @__PURE__ */ new Set},15e3),Zs.unref&&Zs.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?Js.add(t):qs.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<Ys||e>Xs)throw RangeError(`'from' must be between ${Ys} and ${Xs}`);if(t<Ys||t>Xs)throw RangeError(`'to' must be between ${Ys} and ${Xs}`);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(Yt.HMR_PORT){let e=Number.parseInt(Yt.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:a,likec4AssetsDir:s,openBrowser:c,listen:l,port:u,hmrPort:f,userPublicDir:p,allowedHosts:h,...g}){s??=await ct(bt(un(),`.likec4-assets-`));let{isDev:v,...y}=await viteConfig({...g,languageServices:a,likec4AssetsDir:s,webcomponentPrefix:n,title:r}),b=y.customLogger;u??=Yt.PORT?parseInt(Yt.PORT,10):void 0,u||=await getPorts({port:[5173,5174,...portNumbers(61e3,61010),...portNumbers(62002,62010)]});let x=await mkTempPublicDir();p&&await copyUserPublicDir(p,x);let S=l??(isInsideContainer()?`0.0.0.0`:`localhost`),ee=await resolveHmrPort(f,t);if(t&&ee!==void 0){let e=f?` (explicit)`:Yt.HMR_PORT?` (env)`:` (auto-discovered)`;b.info(`Enabling HMR: localhost:${ee}${e}`),y.plugins=[Sn(),...y.plugins],isInsideContainer()&&b.info(m.yellow(`ensure port ${ee} is published from container`))}else t||b.info(`Disabling HMR`);let te=await pn({...y,define:t?{...y.define,"process.env.NODE_ENV":`"development"`}:y.define,mode:t?`development`:y.mode,publicDir:x,optimizeDeps:{holdUntilCrawlEnd:!1,ignoreOutdatedRequests:!0,include:[`react`,`react-dom`,`react/compiler-runtime`,`react/jsx-runtime`,`react-dom/client`,`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:S,allowedHosts:h&&h.length>0?h:!0,port:u,hmr:t&&{overlay:!0,...ee===void 0?{}:{port:ee}},fs:{strict:!1},open:c??(!v&&!isInsideContainer())}});if(await te.listen(),e){let e=viteWebcomponentConfig({webcomponentPrefix:n,languageServices:a,outDir:x,base:y.base});b.info(`Building webcomponent`),await fn({...e,logLevel:`warn`}).catch(e=>{b.warn(i(e)),b.warn(`webcomponent build failed, ignoring error and continue`)})}else b.info(`Skip webcomponent build`);return te}function createExportViewUrl({viewId:e,padding:t,theme:n,dynamicVariant:r,format:i=`png`,notation:a=!1,description:s=!1}){return ge(`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:h=!1}){let g,v=t.map(e=>({view:e,attempt:1})),y=[],b;for(;b=v.shift();){let{view:t,attempt:x}=b,S=`export/${encodeURIComponent(t.id)}/`;try{if(x>1){g&&=(g.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),void 0);let e=Fe(x*200,{min:200,max:1e3});r.info(m.cyan(S)+m.dim(` attempt ${x} of ${a} after ${e}ms`)),await wn(e)}else t.hasLayoutDrift&&r.warn(m.yellow(`Drift detected, manual layout can not be applied, view may be invalid: `)+m.red(t.id));let v=`.`;c===`relative`&&(v=t.sourcePath??`.`,v=v.includes(`/`)?v.slice(0,v.lastIndexOf(`/`)):`.`);let b=u===`jpeg`?`.jpg`:`.png`,ee=D(n,v,`${t.id}${b}`);g??=await e.newPage();let te=t.bounds;s===`sequence`&&t._type===`dynamic`&&(te=t.sequenceLayout.bounds),await g.setViewportSize({width:te.width+40+20,height:te.height+40+20}),await g.goto(createExportViewUrl({viewId:t.id,padding:20,theme:l,dynamicVariant:s,format:u,notation:p,description:h})),r.info(m.cyan(S)+m.dim(` -> ${E(n,ee)}`)),await g.waitForSelector(`.react-flow.initialized`);let ne=g.getByTestId(`export-page`),re=await ne.boundingBox();if(re){let e=Math.ceil(re.width),t=Math.ceil(re.height),n=g.viewportSize();(!n||e>n.width||t>n.height)&&await g.setViewportSize({width:e,height:t})}t.nodes.some(e=>ze(e.icon)&&e.icon.toLowerCase().startsWith(`http`))&&await waitAllImages(g,i),await ne.screenshot({animations:`disabled`,path:ee,type:u===`jpeg`?`jpeg`:`png`,...u===`jpeg`?{quality:f??80,omitBackground:!1}:{omitBackground:!0}}),y.push({view:t,path:ee})}catch(e){g?.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),r.error(m.red(`failed `+S+`
311
+ `+e)),x<a&&(v.push({view:t,attempt:x+1}),r.info(m.dim(`retry ${S}`))),g=void 0}}return y}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}),void 0,{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:h=!1,description:g=!1}){e.info(`${m.dim(`output`)} ${a}`),e.info(`${m.dim(`base url`)} ${t}\n`);let{chromium:v}=await import(`playwright`),y=v.executablePath();e.info(m.cyan(`Start chromium`)+` `+m.dim(y));let b=await v.launch({chromiumSandbox:l,headless:!0});e.info(m.cyan(`Color scheme: `)+n+`
312
+ `);let x=await b.newContext({deviceScaleFactor:2,colorScheme:n,baseURL:t,bypassCSP:!0,ignoreHTTPSErrors:!0,isMobile:!1});x.setDefaultNavigationTimeout(r),x.setDefaultTimeout(r);try{return await takeScreenshot({browserContext:x,views:i,output:a,outputType:s,logger:e,maxAttempts:c,dynamicVariant:u?`sequence`:`diagram`,timeout:r,theme:n,format:f,quality:p,notation:h,description:g})}finally{e.info(m.cyan(`close chromium`)),await x.close(),await b.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:h=3,filter:g,sequence:v=!1,chromiumSandbox:y=!1,format:b=`png`,quality:x,notation:ee=!1,description:te=!1}=e,ne=n.a(await S(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(m.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(m.dim(`---------`)),t.info(`${m.dim(`project:`)} ${e.id}`),t.info(`${m.dim(`folder:`)} ${e.folder.fsPath}`));let n=await ne.diagrams(e.id);if(g&&Se(g,1)&&Se(n,1)){let e=on(g);t.info(`${m.cyan(`filter`)} ${m.dim(JSON.stringify(g))}`),n=n.filter(n=>e(n.id)?(t.info(`${m.green(`include`)} ${n.id} ✅`),!0):(t.info(`${m.gray(`skip`)} ${m.dim(n.id)}`),!1))}if(!Se(n,1)){t.warn(`no views found`);continue}let r=oe.length>1?_e(ve(ae,`project`,e.id)):ae,i=oe.length>1?ve(re,e.id):re,c=rn(),u=await exportViewsToPNG({logger:t,serverUrl:r,theme:s,timeoutMs:p,views:n,output:i,outputType:l,maxAttempts:h,sequence:v,chromiumSandbox:y,format:b,quality:x,notation:ee,description:te}),{pretty:S}=inMillis(c);if(u.length>0&&t.info(m.green(`exported ${u.length} views in ${S}`)+`
313
+ `),u.length!==n.length&&(f&&u.length>0?t.info(m.dim(`ignore`)+` `+m.red(`failed ${n.length-u.length} out of ${n.length} views`)):t.error(m.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(m.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`,W).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:D},project:Ss,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":G,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
314
+ 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(`${m.bold(`Examples:`)}
315
+ ${m.green(`$0 export png`)}
316
+ ${m.gray(`Search for likec4 files in current directory and output PNG next to sources`)}
317
+
318
+ ${m.green(`$0 export png --theme dark -o ./png src/likec4`)}
319
+ ${m.gray(`Search for likec4 files in src/likec4 and output PNG with dark theme to png folder`)}
320
+
321
+ ${m.green(`$0 export png -f "team1*" -f "team2*" --flat -o ./png src/likec4`)}
322
+ ${m.gray(`Export views matching team1* or team2* only`)}
323
+
324
+ ${m.green(`$0 export png -f "use-case*" --sequence src/likec4`)}
325
+ ${m.gray(`Export views matching use-case* using sequence layout`)}
326
+ `),handler:async e=>{A(e.timeout>=1,`timeout must be >= 1`),A(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`,W).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:D},project:Ss,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":G,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
327
+ 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(`${m.bold(`Examples:`)}
328
+ ${m.green(`$0 export jpg`)}
329
+ ${m.gray(`Search for likec4 files in current directory and output JPEG next to sources`)}
330
+
331
+ ${m.green(`$0 export jpg --theme dark -o ./jpg src/likec4`)}
332
+ ${m.gray(`Search for likec4 files in src/likec4 and output JPEG with dark theme to jpg folder`)}
333
+
334
+ ${m.green(`$0 export jpg --quality 90 -o ./jpg src/likec4`)}
335
+ ${m.gray(`Export JPEG with 90% quality`)}
336
+
337
+ ${m.green(`$0 export jpg -f "team1*" -f "team2*" --flat -o ./jpg src/likec4`)}
338
+ ${m.gray(`Export views matching team1* or team2* only`)}
339
+ `),handler:async e=>{A(e.quality>=1&&e.quality<=100,`quality must be between 1 and 100`),A(e.timeout>=1,`timeout must be >= 1`),A(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 Qs=`project not found`,$s=`No projects found`;async function runExportJson(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await S(e.path,{graphviz:e.useDot?`binary`:`wasm`,watch:!1})),a=[...i.projectsManager.all];if(e.project){if(a=a.filter(t=>t===e.project),!Se(a,1))throw t.error(`${Qs}: ${e.project}`),Error(`${Qs}: ${e.project}`)}else{if(!Se(a,1))throw t.error($s),Error($s);t.info(`${m.dim(`workspace:`)} Found ${a.length} projects`)}let s=[];for(let n of a){let r;e.skipLayout?(t.info(`Generate model for project ${m.green(n)} ${m.dim(`(skip layout)`)}`),r=await i.computedModel(n)):(t.info(`Generating layouted model for project ${m.green(n)}`),r=await i.layoutedModel(n)),r===tt.EMPTY?t.warn(m.yellow(`Project ${n} is empty, skipping`)):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;vt(c).toLowerCase()!==`.json`&&(c+=`.json`),await st(_t(c),{recursive:!0});let l=s.length===1?s[0]:s,u=e.pretty?JSON.stringify(l,void 0,2):JSON.stringify(l);await w(c,u);let f=c.startsWith(e.path)?E(e.path,c):c;t.info(`${m.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`,W).option(`outfile`,{alias:`o`,type:`string`,desc:`<file> output .json file`,default:`likec4.json`,normalize:!0,coerce:D}).options({project:Ss,"use-dot":G,"skip-layout":{type:`boolean`,desc:`skip layout (produce compute-only model, faster)`},pretty:{type:`boolean`,desc:`indented JSON output`}}).epilog(`${m.bold(`Examples:`)}
340
+ ${m.green(`$0 export json --skip-layout`)}
341
+ ${m.gray(`Search for likec4 files in current directory and output JSON to likec4.json (no layout)`)}
342
+
343
+ ${m.green(`$0 export json --pretty -o ./generated/likec4.json src/likec4 `)}
344
+ ${m.gray(`Search for likec4 files in src/likec4 and output JSON to generated/likec4.json`)}
345
+ `),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 ec=`project not found`,tc=`<!-- 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 ut(e,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!0;throw e}return n.startsWith(tc)}async function runExportMarkdown(e,t){try{var n=_usingCtx();let r=startTimer(t),i=n.a(await S(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(`${ec}: ${e.project}`),Error(`${ec}: ${e.project}`)}else t.info(`${m.dim(`workspace:`)} Found ${a.length} projects`);let s=0;for(let n of a){let r=await i.layoutedModel(n.id);if(r===tt.EMPTY||!hasAuthoredViews(r)){t.warn(m.yellow(`Project ${n.id} has no views, skipping`));continue}let a=bt(n.folder.fsPath,`README.md`);if(!await canWrite(a,!!e.force)){t.warn(m.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 w(a,`${tc}\n\n${l}`),s++,t.info(`${m.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`,W).options({project:Ss,"use-dot":G,force:{type:`boolean`,desc:`overwrite an existing README.md even if it was not generated by this command`}}).epilog(`${m.bold(`Examples:`)}
346
+ ${m.green(`$0 export markdown`)}
347
+ ${m.gray(`Render every project to README.md in its own project folder`)}
348
+
349
+ ${m.green(`$0 export markdown -p my-project src/likec4`)}
350
+ ${m.gray(`Render only my-project to its README.md under src/likec4`)}
351
+ `),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=>Le(e.usage(`${m.bold(`Usage:`)} $0 export <format> [path]`),pngCmd,jpgCmd,jsonCmd,drawioCmd,markdownCmd).updateStrings({"Commands:":m.bold(`Formats:`)}),handler:()=>void 0}),formatCmd=e=>e.command({command:`format [path]`,aliases:[`fmt`],describe:`Format LikeC4 source files`,builder:e=>e.positional(`path`,W).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=>D(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 S(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=>_n(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(` ${gn(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=E(u,e);return t.startsWith(`..`)?e:t};if(c){let e=c.filter(e=>!l.has(e));for(let t of e)n.warn(`${m.yellow(`skipped`)} ${displayPath(gn(t))} (not found in workspace)`)}let f=0,p=0,h=[];for(let[e,t]of l){let r=gn(e),a=displayPath(r),s;try{s=await ut(r,`utf-8`)}catch(e){n.error(`Failed to read ${a}: ${e}`),p++;continue}if(s===t)n.debug(`${m.dim(`unchanged`)} ${a}`);else if(f++,h.push(a),i)n.info(`${m.yellow(`needs formatting`)} ${a}`);else try{await w(r,t,`utf-8`),n.info(`${m.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${h.map(e=>` ${e}`).join(`
352
+ `)}`),process.exitCode=1;return}n.info(m.green(`All ${l.size} file(s) are formatted`))}else f>0?n.info(`${m.green(String(f))} of ${l.size} file(s) formatted`):n.info(m.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:g,description:`Filter icons by group`}),handler:e=>{let t=e.group?[e.group]:g;switch(!0){case e.format===`json`:{let e=Object.fromEntries(t.map(e=>[e,te[e]]));console.log(JSON.stringify(e,null,2));break}default:for(let e of t)for(let t of te[e])console.log(`${e}:${t}`)}}});var nc=/* @__PURE__ */ r((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||(function(){var ownKeys=function(e){return ownKeys=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},ownKeys(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=ownKeys(e),a=0;a<i.length;a++)i[a]!=="default"&&n(t,e,i[a]);return r(t,e),t}})();Object.defineProperty(t,"__esModule",{value:!0}),t.FileSystem=void 0,t.uriToFilePath=uriToFilePath,t.resolve=resolve,t.resolveGlobalNodePath=resolveGlobalNodePath,t.resolveGlobalYarnPath=resolveGlobalYarnPath,t.resolveModulePath=resolveModulePath;let a=i(e(`node:url`)),s=i(e(`node:path`)),c=i(e(`node:fs`)),l=e(`node:child_process`);function uriToFilePath(e){let t=a.parse(e);if(t.protocol!==`file:`||!t.path)return;let n=t.path.split(`/`);for(let e=0,t=n.length;e<t;e++)n[e]=decodeURIComponent(n[e]);if(process.platform===`win32`&&n.length>1){let e=n[0],t=n[1];e.length===0&&t.length>1&&t[1]===`:`&&n.shift()}return s.normalize(n.join(`/`))}function isWindows(){return process.platform===`win32`}function resolve(e,t,n,r){let i=`NODE_PATH`,a=[`var p = process;`,`p.on('message',function(m){`,`if(m.c==='e'){`,`p.exit(0);`,`}`,`else if(m.c==='rs'){`,`try{`,`var r=require.resolve(m.a);`,`p.send({c:'r',s:true,r:r});`,`}`,`catch(err){`,`p.send({c:'r',s:false});`,`}`,`}`,`});`].join(``);return new Promise((u,f)=>{let p=process.env,m=Object.create(null);Object.keys(p).forEach(e=>m[e]=p[e]),t&&c.existsSync(t)&&(m[i]?m[i]=t+s.delimiter+m[i]:m[i]=t,r&&r(`NODE_PATH value is: ${m[i]}`)),m.ELECTRON_RUN_AS_NODE=`1`;try{let t=(0,l.fork)(``,[],{cwd:n,env:m,execArgv:[`-e`,a]});if(t.pid===void 0){f(/* @__PURE__ */ Error(`Starting process to resolve node module ${e} failed`));return}t.on(`error`,e=>{f(e)}),t.on(`message`,n=>{n.c===`r`&&(t.send({c:`e`}),n.s?u(n.r):f(/* @__PURE__ */ Error(`Failed to resolve module: ${e}`)))});let r={c:`rs`,a:e};t.send(r)}catch(e){f(e)}})}function resolveGlobalNodePath(e){let t=`npm`,n=Object.create(null);Object.keys(process.env).forEach(e=>n[e]=process.env[e]),n.NO_UPDATE_NOTIFIER=`true`;let r={encoding:`utf8`,env:n};isWindows()&&(t=`npm.cmd`,r.shell=!0);let handler=()=>{};try{process.on(`SIGPIPE`,handler);let n=(0,l.spawnSync)(t,[`config`,`get`,`prefix`],r).stdout;if(!n){e&&e(`'npm config get prefix' didn't return a value.`);return}let i=n.trim();return e&&e(`'npm config get prefix' value is: ${i}`),i.length>0?isWindows()?s.join(i,`node_modules`):s.join(i,`lib`,`node_modules`):void 0}catch{return}finally{process.removeListener(`SIGPIPE`,handler)}}function resolveGlobalYarnPath(e){let t=`yarn`,n={encoding:`utf8`};isWindows()&&(t=`yarn.cmd`,n.shell=!0);let handler=()=>{};try{process.on(`SIGPIPE`,handler);let r=(0,l.spawnSync)(t,[`global`,`dir`,`--json`],n),i=r.stdout;if(!i){e&&(e(`'yarn global dir' didn't return a value.`),r.stderr&&e(r.stderr));return}let a=i.trim().split(/\r?\n/);for(let e of a)try{let t=JSON.parse(e);if(t.type===`log`)return s.join(t.data,`node_modules`)}catch{}return}catch{return}finally{process.removeListener(`SIGPIPE`,handler)}}var u;(function(e){let t;function isCaseSensitive(){return t===void 0&&(t=process.platform===`win32`?!1:!c.existsSync(__filename.toUpperCase())||!c.existsSync(__filename.toLowerCase())),t}e.isCaseSensitive=isCaseSensitive;function isParent(e,t){return isCaseSensitive()?s.normalize(t).indexOf(s.normalize(e))===0:s.normalize(t).toLowerCase().indexOf(s.normalize(e).toLowerCase())===0}e.isParent=isParent})(u||(t.FileSystem=u={}));function resolveModulePath(e,t,n,r){return n?(s.isAbsolute(n)||(n=s.join(e,n)),resolve(t,n,n,r).then(e=>u.isParent(n,e)?e:Promise.reject(/* @__PURE__ */ Error(`Failed to load ${t} from node path location.`))).then(void 0,n=>resolve(t,resolveGlobalNodePath(r),e,r))):resolve(t,resolveGlobalNodePath(r),e,r)}})),rc=/* @__PURE__ */ r((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:util`),r=me();var i=class MessageBuffer extends r.AbstractMessageBuffer{static emptyBuffer=Buffer.allocUnsafe(0);constructor(e=`utf-8`){super(e)}emptyBuffer(){return MessageBuffer.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(e,t){return e instanceof Buffer?e.toString(t):new n.TextDecoder(t).decode(e)}asNative(e,t){return t===void 0?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}},ReadableStreamWrapper=class{stream;constructor(e){this.stream=e}onClose(e){return this.stream.on(`close`,e),r.Disposable.create(()=>this.stream.off(`close`,e))}onError(e){return this.stream.on(`error`,e),r.Disposable.create(()=>this.stream.off(`error`,e))}onEnd(e){return this.stream.on(`end`,e),r.Disposable.create(()=>this.stream.off(`end`,e))}onData(e){return this.stream.on(`data`,e),r.Disposable.create(()=>this.stream.off(`data`,e))}},WritableStreamWrapper=class{stream;constructor(e){this.stream=e}onClose(e){return this.stream.on(`close`,e),r.Disposable.create(()=>this.stream.off(`close`,e))}onError(e){return this.stream.on(`error`,e),r.Disposable.create(()=>this.stream.off(`error`,e))}onEnd(e){return this.stream.on(`end`,e),r.Disposable.create(()=>this.stream.off(`end`,e))}write(e,t){return new Promise((n,r)=>{let callback=e=>{e==null?n():r(e)};typeof e==`string`?this.stream.write(e,t,callback):this.stream.write(e,callback)})}end(){this.stream.end()}};let a=Object.freeze({messageBuffer:Object.freeze({create:e=>new i(e)}),applicationJson:Object.freeze({encoder:Object.freeze({name:`application/json`,encode:(e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(e){return Promise.reject(e)}}}),decoder:Object.freeze({name:`application/json`,decode:(e,t)=>{try{return e instanceof Buffer?Promise.resolve(JSON.parse(e.toString(t.charset))):Promise.resolve(JSON.parse(new n.TextDecoder(t.charset).decode(e)))}catch(e){return Promise.reject(e)}}})}),stream:Object.freeze({asReadableStream:e=>new ReadableStreamWrapper(e),asWritableStream:e=>new WritableStreamWrapper(e)}),console,timer:Object.freeze({setTimeout(e,t,...n){let r=setTimeout(e,t,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(e,...t){let n=setImmediate(e,...t);return{dispose:()=>clearImmediate(n)}},setInterval(e,t,...n){let r=setInterval(e,t,...n);return{dispose:()=>clearInterval(r)}}})});function RIL(){return a}(function(e){function install(){r.RAL.install(a)}e.install=install})(RIL||={}),t.default=RIL})),ic=/* @__PURE__ */ r((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||(function(){var ownKeys=function(e){return ownKeys=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},ownKeys(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=ownKeys(e),a=0;a<i.length;a++)i[a]!=="default"&&n(t,e,i[a]);return r(t,e),t}})(),a=t&&t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)},s=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.StreamMessageWriter=t.StreamMessageReader=t.SocketMessageWriter=t.SocketMessageReader=t.PortMessageWriter=t.PortMessageReader=t.IPCMessageWriter=t.IPCMessageReader=void 0,t.generateRandomPipeName=generateRandomPipeName,t.createClientPipeTransport=createClientPipeTransport,t.createServerPipeTransport=createServerPipeTransport,t.createClientSocketTransport=createClientSocketTransport,t.createServerSocketTransport=createServerSocketTransport,t.createMessageConnection=createMessageConnection;let c=s(rc());c.default.install();let l=i(e(`node:path`)),u=i(e(`node:os`)),f=i(e(`node:fs`)),p=e(`node:crypto`),m=e(`node:net`),h=me();a(me(),t);var IPCMessageReader=class extends h.AbstractMessageReader{process;constructor(e){super(),this.process=e;let t=this.process;t.on(`error`,e=>this.fireError(e)),t.on(`close`,()=>this.fireClose())}listen(e){return this.process.on(`message`,e),h.Disposable.create(()=>this.process.off(`message`,e))}};t.IPCMessageReader=IPCMessageReader;var IPCMessageWriter=class extends h.AbstractMessageWriter{process;errorCount;constructor(e){super(),this.process=e,this.errorCount=0;let t=this.process;t.on(`error`,e=>this.fireError(e)),t.on(`close`,()=>this.fireClose)}write(e){try{return typeof this.process.send==`function`&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};t.IPCMessageWriter=IPCMessageWriter;var PortMessageReader=class extends h.AbstractMessageReader{onData;constructor(e){super(),this.onData=new h.Emitter,e.on(`close`,()=>this.fireClose),e.on(`error`,e=>this.fireError(e)),e.on(`message`,e=>{this.onData.fire(e)})}listen(e){return this.onData.event(e)}};t.PortMessageReader=PortMessageReader;var PortMessageWriter=class extends h.AbstractMessageWriter{port;errorCount;constructor(e){super(),this.port=e,this.errorCount=0,e.on(`close`,()=>this.fireClose()),e.on(`error`,e=>this.fireError(e))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};t.PortMessageWriter=PortMessageWriter;var SocketMessageReader=class extends h.ReadableStreamMessageReader{constructor(e,t=`utf-8`){super((0,c.default)().stream.asReadableStream(e),t)}};t.SocketMessageReader=SocketMessageReader;var SocketMessageWriter=class extends h.WriteableStreamMessageWriter{socket;constructor(e,t){super((0,c.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};t.SocketMessageWriter=SocketMessageWriter;var StreamMessageReader=class extends h.ReadableStreamMessageReader{constructor(e,t){super((0,c.default)().stream.asReadableStream(e),t)}};t.StreamMessageReader=StreamMessageReader;var StreamMessageWriter=class extends h.WriteableStreamMessageWriter{constructor(e,t){super((0,c.default)().stream.asWritableStream(e),t)}};t.StreamMessageWriter=StreamMessageWriter;let g=process.env.XDG_RUNTIME_DIR,v=/* @__PURE__ */ new Map([[`linux`,107],[`darwin`,102]]);function generateRandomPipeName(){if(process.platform===`win32`)return`\\\\.\\pipe\\lsp-${(0,p.randomBytes)(16).toString(`hex`)}-sock`;let e=32,t=f.realpathSync(g??u.tmpdir()),n=v.get(process.platform);if(n!==void 0&&(e=Math.min(n-t.length-10,e)),e<16)throw Error(`Unable to generate a random pipe name with ${e} characters.`);let r=(0,p.randomBytes)(Math.floor(e/2)).toString(`hex`);return l.join(t,`lsp-${r}.sock`)}function createClientPipeTransport(e,t=`utf-8`){let n,r=new Promise((e,t)=>{n=e});return new Promise((i,a)=>{let s=(0,m.createServer)(e=>{s.close(),n([new SocketMessageReader(e,t),new SocketMessageWriter(e,t)])});s.on(`error`,a),s.listen(e,()=>{s.removeListener(`error`,a),i({onConnected:()=>r})})})}function createServerPipeTransport(e,t=`utf-8`){let n=(0,m.createConnection)(e);return[new SocketMessageReader(n,t),new SocketMessageWriter(n,t)]}function createClientSocketTransport(e,t=`utf-8`){let n,r=new Promise((e,t)=>{n=e});return new Promise((i,a)=>{let s=(0,m.createServer)(e=>{s.close(),n([new SocketMessageReader(e,t),new SocketMessageWriter(e,t)])});s.on(`error`,a),s.listen(e,`127.0.0.1`,()=>{s.removeListener(`error`,a);let e=s.address();if(e===null||typeof e==`string`){a(/* @__PURE__ */ Error(`Unexpected server address: ${e}`));return}let t=e.port;i({port:()=>t,onConnected:()=>r})})})}function createServerSocketTransport(e,t=`utf-8`){let n=(0,m.createConnection)(e,`127.0.0.1`);return[new SocketMessageReader(n,t),new SocketMessageWriter(n,t)]}function isReadableStream(e){let t=e;return t.read!==void 0&&t.addListener!==void 0}function isWritableStream(e){let t=e;return t.write!==void 0&&t.addListener!==void 0}function createMessageConnection(e,t,n,r){n||=h.NullLogger;let i=isReadableStream(e)?new StreamMessageReader(e):e,a=isWritableStream(t)?new StreamMessageWriter(t):t;return h.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,h.createMessageConnection)(i,a,n,r)}})),ac=/* @__PURE__ */ r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createProtocolConnection=createProtocolConnection;let r=ic();n(ic(),e),n(oe(),e);function createProtocolConnection(e,t,n,i){return(0,r.createMessageConnection)(e,t,n,i)}})),oc=(/* @__PURE__ */ r((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||(function(){var ownKeys=function(e){return ownKeys=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},ownKeys(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=ownKeys(e),a=0;a<i.length;a++)i[a]!=="default"&&n(t,e,i[a]);return r(t,e),t}})(),a=t&&t.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0,t.createConnection=createConnection;let s=e(`node:util`),c=i(fe()),l=pe(),u=i(nc()),f=ac();a(ac(),t),a(le(),t);var p;(function(e){e.uriToFilePath=u.uriToFilePath,e.resolveGlobalNodePath=u.resolveGlobalNodePath,e.resolveGlobalYarnPath=u.resolveGlobalYarnPath,e.resolve=u.resolve,e.resolveModulePath=u.resolveModulePath})(p||(t.Files=p={}));let m=!1,h;function setupExitTimer(){let e=`--clientProcessId`;function runTimer(e){try{let t=parseInt(e);isNaN(t)||(h=setInterval(()=>{try{process.kill(t,0)}catch{process.exit(+!m)}},3e3))}catch{}}for(let t=2;t<process.argv.length;t++){let n=process.argv[t];if(n===e&&t+1<process.argv.length){runTimer(process.argv[t+1]);return}{let t=n.split(`=`);t[0]===e&&runTimer(t[1])}}}setupExitTimer();let g={initialize:e=>{let t=e.processId;c.number(t)&&h===void 0&&setInterval(()=>{try{process.kill(t,0)}catch{process.exit(+!m)}},3e3)},get shutdownReceived(){return m},set shutdownReceived(e){m=e},exit:e=>{process.exit(e)}};function createConnection(e,t,n,r){let i,a,s,c;return e!==void 0&&e.__brand===`features`&&(i=e,e=t,t=n,n=r),f.ConnectionStrategy.is(e)||f.ConnectionOptions.is(e)?c=e:(a=e,s=t,c=n),_createConnection(a,s,c,i)}function _createConnection(e,t,n,r){let i=!1;if(!e&&!t&&process.argv.length>2){let n,r,a=process.argv.slice(2);for(let s=0;s<a.length;s++){let c=a[s];if(c===`--node-ipc`){e=new f.IPCMessageReader(process),t=new f.IPCMessageWriter(process);break}if(c===`--stdio`){i=!0,e=process.stdin,t=process.stdout;break}if(c===`--socket`){n=parseInt(a[s+1]);break}if(c===`--pipe`){r=a[s+1];break}{let e=c.split(`=`);if(e[0]===`--socket`){n=parseInt(e[1]);break}if(e[0]===`--pipe`){r=e[1];break}}}if(n){let r=(0,f.createServerSocketTransport)(n);e=r[0],t=r[1]}else if(r){let n=(0,f.createServerPipeTransport)(r);e=n[0],t=n[1]}}let a=`Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'`;if(!e)throw Error(`Connection input stream is not set. `+a);if(!t)throw Error(`Connection output stream is not set. `+a);if(c.func(e.read)&&c.func(e.on)){let t=e;t.on(`end`,()=>{process.exit(+!m)}),t.on(`close`,()=>{process.exit(+!m)})}let connectionFactory=r=>{let a=(0,f.createProtocolConnection)(e,t,r,n);return i&&patchConsole(r),a};return(0,l.createConnection)(connectionFactory,g,r)}function patchConsole(e){function serialize(e){return e.map(e=>typeof e==`string`?e:(0,s.inspect)(e)).join(` `)}let t=/* @__PURE__ */ new Map;console.assert=function assert(t,...n){if(!t){if(n.length===0)e.error(`Assertion failed`);else{let[t,...r]=n;e.error(`Assertion failed: ${t} ${serialize(r)}`)}}},console.count=function count(n=`default`){let r=String(n),i=t.get(r)??0;i+=1,t.set(r,i),e.log(`${r}: ${r}`)},console.countReset=function countReset(e){e===void 0?t.clear():t.delete(String(e))},console.debug=function debug(...t){e.log(serialize(t))},console.dir=function dir(t,n){e.log((0,s.inspect)(t,n))},console.log=function log(...t){e.log(serialize(t))},console.error=function error(...t){e.error(serialize(t))},console.trace=function trace(...t){let n=(/* @__PURE__ */ Error()).stack.replace(/(.+\n){2}/,``),r=`Trace`;t.length!==0&&(r+=`: ${serialize(t)}`),e.log(`${r}\n${n}`)},console.warn=function warn(...t){e.warn(serialize(t))},console.info=function info(...t){e.info(serialize(t))}}})))();function lsp_default(e){return e.command({command:`lsp`,aliases:[],describe:`Start LSP server`,builder:e=>e.usage(`${m.bold(`Usage:`)} $0 lsp`).option(`log-level`,Cs).option(`verbose`,ws).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`,G).showHidden().epilog(`${m.bold(`Examples:`)}
353
+
354
+ ${m.green(`$0 lsp --stdio `)}
355
+ ${m.gray(`Start LSP with stdio transport`)}
356
+
357
+ ${m.green(`$0 lsp --node-ipc --watch --no-manual-layouts --no-color `)}
358
+ ${m.gray(`Start LSP with node-ipc transport and watcher, disabled manual layouts and disabled color`)}
359
+
360
+ `),handler:e=>{let t;if(e.nodeIpc||e.stdio||e.socket||e.pipe)t=(0,oc.createConnection)(oc.ProposedFeatures.all);else throw Error(`No transport specified`);f({lspConnection:t,useStdErr:e.stdio===!0,colors:m.isColorSupported,enableTelemetry:e.telemetry,logLevel:e.verbose?Ts: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;uc.add(onLeave);try{let a=r?r.run(e,i):i();return n||(t=void 0),await a}finally{uc.delete(onLeave)}}}}function createNamespace(e={}){let t={};return{get(n,r={}){return t[n]||(t[n]=createContext({...e,...r})),t[n]}}}const sc=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof global<`u`?global:typeof window<`u`?window:{},cc=`__unctx__`;sc[cc]||(sc[cc]=createNamespace());const lc=`__unctx_async_handlers__`,uc=sc[lc]||(sc[lc]=/* @__PURE__ */ new Set),dc=createContext(),fc=createContext();function useLanguageServices(){return fc.use()}function setMcpServerCtx(e){return e?dc.set(e,!0):dc.unset(),e}function setLanguageServicesCtx(e){return e?fc.set(e,!0):fc.unset(),e}const pc=`2025-11-25`,mc=[pc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],hc=`io.modelcontextprotocol/related-task`,K=O.custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),gc=O.union([O.string(),O.number().int()]),_c=O.string();O.looseObject({ttl:O.number().optional(),pollInterval:O.number().optional()});const vc=O.object({ttl:O.number().optional()}),yc=O.object({taskId:O.string()}),bc=O.looseObject({progressToken:gc.optional(),[hc]:yc.optional()}),xc=O.object({_meta:bc.optional()}),Sc=xc.extend({task:vc.optional()}),isTaskAugmentedRequestParams=e=>Sc.safeParse(e).success,q=O.object({method:O.string(),params:xc.loose().optional()}),Cc=O.object({_meta:bc.optional()}),wc=O.object({method:O.string(),params:Cc.loose().optional()}),J=O.looseObject({_meta:bc.optional()}),Tc=O.union([O.string(),O.number().int()]),Ec=O.object({jsonrpc:O.literal(`2.0`),id:Tc,...q.shape}).strict(),isJSONRPCRequest=e=>Ec.safeParse(e).success,Dc=O.object({jsonrpc:O.literal(`2.0`),...wc.shape}).strict(),isJSONRPCNotification=e=>Dc.safeParse(e).success,Oc=O.object({jsonrpc:O.literal(`2.0`),id:Tc,result:J}).strict(),isJSONRPCResultResponse=e=>Oc.safeParse(e).success;var Y;(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`})(Y||={});const kc=O.object({jsonrpc:O.literal(`2.0`),id:Tc.optional(),error:O.object({code:O.number().int(),message:O.string(),data:O.unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>kc.safeParse(e).success,Ac=O.union([Ec,Dc,Oc,kc]);O.union([Oc,kc]);const jc=J.strict(),Mc=Cc.extend({requestId:Tc.optional(),reason:O.string().optional()}),Nc=wc.extend({method:O.literal(`notifications/cancelled`),params:Mc}),Pc=O.object({src:O.string(),mimeType:O.string().optional(),sizes:O.array(O.string()).optional(),theme:O.enum([`light`,`dark`]).optional()}),Fc=O.object({icons:O.array(Pc).optional()}),Ic=O.object({name:O.string(),title:O.string().optional()}),Lc=Ic.extend({...Ic.shape,...Fc.shape,version:O.string(),websiteUrl:O.string().optional(),description:O.string().optional()}),Rc=O.intersection(O.object({applyDefaults:O.boolean().optional()}),O.record(O.string(),O.unknown())),zc=O.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,O.intersection(O.object({form:Rc.optional(),url:K.optional()}),O.record(O.string(),O.unknown()).optional())),Bc=O.looseObject({list:K.optional(),cancel:K.optional(),requests:O.looseObject({sampling:O.looseObject({createMessage:K.optional()}).optional(),elicitation:O.looseObject({create:K.optional()}).optional()}).optional()}),Vc=O.looseObject({list:K.optional(),cancel:K.optional(),requests:O.looseObject({tools:O.looseObject({call:K.optional()}).optional()}).optional()}),Hc=O.object({experimental:O.record(O.string(),K).optional(),sampling:O.object({context:K.optional(),tools:K.optional()}).optional(),elicitation:zc.optional(),roots:O.object({listChanged:O.boolean().optional()}).optional(),tasks:Bc.optional(),extensions:O.record(O.string(),K).optional()}),Uc=xc.extend({protocolVersion:O.string(),capabilities:Hc,clientInfo:Lc}),Wc=q.extend({method:O.literal(`initialize`),params:Uc}),isInitializeRequest=e=>Wc.safeParse(e).success,Gc=O.object({experimental:O.record(O.string(),K).optional(),logging:K.optional(),completions:K.optional(),prompts:O.object({listChanged:O.boolean().optional()}).optional(),resources:O.object({subscribe:O.boolean().optional(),listChanged:O.boolean().optional()}).optional(),tools:O.object({listChanged:O.boolean().optional()}).optional(),tasks:Vc.optional(),extensions:O.record(O.string(),K).optional()}),Kc=J.extend({protocolVersion:O.string(),capabilities:Gc,serverInfo:Lc,instructions:O.string().optional()}),qc=wc.extend({method:O.literal(`notifications/initialized`),params:Cc.optional()}),Jc=q.extend({method:O.literal(`ping`),params:xc.optional()}),Yc=O.object({progress:O.number(),total:O.optional(O.number()),message:O.optional(O.string())}),Xc=O.object({...Cc.shape,...Yc.shape,progressToken:gc}),Zc=wc.extend({method:O.literal(`notifications/progress`),params:Xc}),Qc=xc.extend({cursor:_c.optional()}),$c=q.extend({params:Qc.optional()}),el=J.extend({nextCursor:_c.optional()}),tl=O.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),nl=O.object({taskId:O.string(),status:tl,ttl:O.union([O.number(),O.null()]),createdAt:O.string(),lastUpdatedAt:O.string(),pollInterval:O.optional(O.number()),statusMessage:O.optional(O.string())}),rl=J.extend({task:nl}),il=Cc.merge(nl),al=wc.extend({method:O.literal(`notifications/tasks/status`),params:il}),ol=q.extend({method:O.literal(`tasks/get`),params:xc.extend({taskId:O.string()})}),sl=J.merge(nl),cl=q.extend({method:O.literal(`tasks/result`),params:xc.extend({taskId:O.string()})});J.loose();const ll=$c.extend({method:O.literal(`tasks/list`)}),ul=el.extend({tasks:O.array(nl)}),dl=q.extend({method:O.literal(`tasks/cancel`),params:xc.extend({taskId:O.string()})}),fl=J.merge(nl),pl=O.object({uri:O.string(),mimeType:O.optional(O.string()),_meta:O.record(O.string(),O.unknown()).optional()}),ml=pl.extend({text:O.string()}),hl=O.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),gl=pl.extend({blob:hl}),_l=O.enum([`user`,`assistant`]),vl=O.object({audience:O.array(_l).optional(),priority:O.number().min(0).max(1).optional(),lastModified:O.iso.datetime({offset:!0}).optional()}),yl=O.object({...Ic.shape,...Fc.shape,uri:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),size:O.optional(O.number()),annotations:vl.optional(),_meta:O.optional(O.looseObject({}))}),bl=O.object({...Ic.shape,...Fc.shape,uriTemplate:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),annotations:vl.optional(),_meta:O.optional(O.looseObject({}))}),xl=$c.extend({method:O.literal(`resources/list`)}),Sl=el.extend({resources:O.array(yl)}),Cl=$c.extend({method:O.literal(`resources/templates/list`)}),wl=el.extend({resourceTemplates:O.array(bl)}),Tl=xc.extend({uri:O.string()}),El=Tl,Dl=q.extend({method:O.literal(`resources/read`),params:El}),Ol=J.extend({contents:O.array(O.union([ml,gl]))}),kl=wc.extend({method:O.literal(`notifications/resources/list_changed`),params:Cc.optional()}),Al=Tl,jl=q.extend({method:O.literal(`resources/subscribe`),params:Al}),Ml=Tl,Nl=q.extend({method:O.literal(`resources/unsubscribe`),params:Ml}),Pl=Cc.extend({uri:O.string()}),Fl=wc.extend({method:O.literal(`notifications/resources/updated`),params:Pl}),Il=O.object({name:O.string(),description:O.optional(O.string()),required:O.optional(O.boolean())}),Ll=O.object({...Ic.shape,...Fc.shape,description:O.optional(O.string()),arguments:O.optional(O.array(Il)),_meta:O.optional(O.looseObject({}))}),Rl=$c.extend({method:O.literal(`prompts/list`)}),zl=el.extend({prompts:O.array(Ll)}),Bl=xc.extend({name:O.string(),arguments:O.record(O.string(),O.string()).optional()}),Vl=q.extend({method:O.literal(`prompts/get`),params:Bl}),Hl=O.object({type:O.literal(`text`),text:O.string(),annotations:vl.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Ul=O.object({type:O.literal(`image`),data:hl,mimeType:O.string(),annotations:vl.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Wl=O.object({type:O.literal(`audio`),data:hl,mimeType:O.string(),annotations:vl.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Gl=O.object({type:O.literal(`tool_use`),name:O.string(),id:O.string(),input:O.record(O.string(),O.unknown()),_meta:O.record(O.string(),O.unknown()).optional()}),Kl=O.object({type:O.literal(`resource`),resource:O.union([ml,gl]),annotations:vl.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),ql=yl.extend({type:O.literal(`resource_link`)}),Jl=O.union([Hl,Ul,Wl,ql,Kl]),Yl=O.object({role:_l,content:Jl}),Xl=J.extend({description:O.string().optional(),messages:O.array(Yl)}),Zl=wc.extend({method:O.literal(`notifications/prompts/list_changed`),params:Cc.optional()}),Ql=O.object({title:O.string().optional(),readOnlyHint:O.boolean().optional(),destructiveHint:O.boolean().optional(),idempotentHint:O.boolean().optional(),openWorldHint:O.boolean().optional()}),$l=O.object({taskSupport:O.enum([`required`,`optional`,`forbidden`]).optional()}),eu=O.object({...Ic.shape,...Fc.shape,description:O.string().optional(),inputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),K).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()),outputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),K).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()).optional(),annotations:Ql.optional(),execution:$l.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),tu=$c.extend({method:O.literal(`tools/list`)}),nu=el.extend({tools:O.array(eu)}),ru=J.extend({content:O.array(Jl).default([]),structuredContent:O.record(O.string(),O.unknown()).optional(),isError:O.boolean().optional()});ru.or(J.extend({toolResult:O.unknown()}));const iu=Sc.extend({name:O.string(),arguments:O.record(O.string(),O.unknown()).optional()}),au=q.extend({method:O.literal(`tools/call`),params:iu}),ou=wc.extend({method:O.literal(`notifications/tools/list_changed`),params:Cc.optional()});O.object({autoRefresh:O.boolean().default(!0),debounceMs:O.number().int().nonnegative().default(300)});const su=O.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),cu=xc.extend({level:su}),lu=q.extend({method:O.literal(`logging/setLevel`),params:cu}),uu=Cc.extend({level:su,logger:O.string().optional(),data:O.unknown()}),du=wc.extend({method:O.literal(`notifications/message`),params:uu}),fu=O.object({name:O.string().optional()}),pu=O.object({hints:O.array(fu).optional(),costPriority:O.number().min(0).max(1).optional(),speedPriority:O.number().min(0).max(1).optional(),intelligencePriority:O.number().min(0).max(1).optional()}),mu=O.object({mode:O.enum([`auto`,`required`,`none`]).optional()}),hu=O.object({type:O.literal(`tool_result`),toolUseId:O.string().describe(`The unique identifier for the corresponding tool call.`),content:O.array(Jl).default([]),structuredContent:O.object({}).loose().optional(),isError:O.boolean().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),gu=O.discriminatedUnion(`type`,[Hl,Ul,Wl]),_u=O.discriminatedUnion(`type`,[Hl,Ul,Wl,Gl,hu]),vu=O.object({role:_l,content:O.union([_u,O.array(_u)]),_meta:O.record(O.string(),O.unknown()).optional()}),yu=Sc.extend({messages:O.array(vu),modelPreferences:pu.optional(),systemPrompt:O.string().optional(),includeContext:O.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:O.number().optional(),maxTokens:O.number().int(),stopSequences:O.array(O.string()).optional(),metadata:K.optional(),tools:O.array(eu).optional(),toolChoice:mu.optional()}),bu=q.extend({method:O.literal(`sampling/createMessage`),params:yu}),xu=J.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(O.string())),role:_l,content:gu}),Su=J.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(O.string())),role:_l,content:O.union([_u,O.array(_u)])}),Cu=O.object({type:O.literal(`boolean`),title:O.string().optional(),description:O.string().optional(),default:O.boolean().optional()}),wu=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),minLength:O.number().optional(),maxLength:O.number().optional(),format:O.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:O.string().optional()}),Tu=O.object({type:O.enum([`number`,`integer`]),title:O.string().optional(),description:O.string().optional(),minimum:O.number().optional(),maximum:O.number().optional(),default:O.number().optional()}),Eu=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),default:O.string().optional()}),Du=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),oneOf:O.array(O.object({const:O.string(),title:O.string()})),default:O.string().optional()}),Ou=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),enumNames:O.array(O.string()).optional(),default:O.string().optional()}),ku=O.union([Eu,Du]),Au=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({type:O.literal(`string`),enum:O.array(O.string())}),default:O.array(O.string()).optional()}),ju=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({anyOf:O.array(O.object({const:O.string(),title:O.string()}))}),default:O.array(O.string()).optional()}),Mu=O.union([Au,ju]),Nu=O.union([Ou,ku,Mu]),Pu=O.union([Nu,Cu,wu,Tu]),Fu=Sc.extend({mode:O.literal(`form`).optional(),message:O.string(),requestedSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),Pu),required:O.array(O.string()).optional()})}),Iu=Sc.extend({mode:O.literal(`url`),message:O.string(),elicitationId:O.string(),url:O.string().url()}),Lu=O.union([Fu,Iu]),Ru=q.extend({method:O.literal(`elicitation/create`),params:Lu}),zu=Cc.extend({elicitationId:O.string()}),Bu=wc.extend({method:O.literal(`notifications/elicitation/complete`),params:zu}),Vu=J.extend({action:O.enum([`accept`,`decline`,`cancel`]),content:O.preprocess(e=>e===null?void 0:e,O.record(O.string(),O.union([O.string(),O.number(),O.boolean(),O.array(O.string())])).optional())}),Hu=O.object({type:O.literal(`ref/resource`),uri:O.string()}),Uu=O.object({type:O.literal(`ref/prompt`),name:O.string()}),Wu=xc.extend({ref:O.union([Uu,Hu]),argument:O.object({name:O.string(),value:O.string()}),context:O.object({arguments:O.record(O.string(),O.string()).optional()}).optional()}),Gu=q.extend({method:O.literal(`completion/complete`),params:Wu});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 Ku=J.extend({completion:O.looseObject({values:O.array(O.string()).max(100),total:O.optional(O.number().int()),hasMore:O.optional(O.boolean())})}),qu=O.object({uri:O.string().startsWith(`file://`),name:O.string().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Ju=q.extend({method:O.literal(`roots/list`),params:xc.optional()}),Yu=J.extend({roots:O.array(qu)}),Xu=wc.extend({method:O.literal(`notifications/roots/list_changed`),params:Cc.optional()});O.union([Jc,Wc,Gu,lu,Vl,Rl,xl,Cl,Dl,jl,Nl,au,tu,ol,cl,ll,dl]),O.union([Nc,Zc,qc,Xu,al]),O.union([jc,xu,Su,Vu,Yu,sl,ul,rl]),O.union([Jc,bu,Ru,Ju,ol,cl,ll,dl]),O.union([Nc,Zc,du,Fl,kl,ou,Zl,al,Bu]),O.union([jc,Kc,Ku,Xl,zl,Sl,wl,Ol,ru,nu,sl,ul,rl]);var X=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===Y.UrlElicitationRequired&&n){let e=n;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,t)}return new McpError(e,t,n)}},UrlElicitationRequiredError=class extends X{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Y.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ReadBuffer=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
361
+ `);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 Ac.parse(JSON.parse(e))}function serializeMessage(e){return JSON.stringify(e)+`
362
+ `}var StdioServerTransport=class{constructor(e=M.stdin,t=M.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new ReadBuffer({maxBufferSize:n?.maxBufferSize})}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 Z=re.getChild(`mcp`);function mcpToolSchema(e){return k.object(e).meta({$schema:`https://json-schema.org/draft/2020-12/schema`})}function likec4Tool(e){return t=>n=>{let{name:r,description:a,inputSchema:s,outputSchema:c,...l}=e,u=c!==void 0&&!we(c),f={description:a?.trim()??``,...l,...s===void 0?{}:{inputSchema:mcpToolSchema(s)},...c===void 0?{}:{outputSchema:mcpToolSchema(c)}};return n.registerTool(r,f,async(...e)=>{let n=useLanguageServices();Z.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}:Tt(r,`content`)?r:{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return Z.error(`Tool ${r} failed`,{err:e}),{content:[{type:`text`,text:i(e)}],isError:!0}}}),n}}function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return En.object({});let n=t.every(isZ4Schema),r=t.every(e=>!isZ4Schema(e));if(n)return En.object(e);if(r)return Tn.object(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?En.safeParse(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await En.safeParseAsync(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 getDotPath(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${getDotPath(e.path)}`:e.message).join(`
363
+ `);if(`message`in e&&typeof e.message==`string`)return e.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 Zu=Symbol(`Let zodToJsonSchema decide on which parser to use`),Qu={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`?{...Qu,name:e}:{...Qu,...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!==N.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 $u;const ed={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:()=>($u===void 0&&($u=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),$u),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,ed.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,ed.cuid,r.message,t);break;case`cuid2`:addPattern(n,ed.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,ed.base64url,r.message,t);break;case`jwt`:addPattern(n,ed.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&addPattern(n,ed.ipv4Cidr,r.message,t),r.version!==`v4`&&addPattern(n,ed.ipv6Cidr,r.message,t);break;case`emoji`:addPattern(n,ed.emoji(),r.message,t);break;case`ulid`:addPattern(n,ed.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,ed.base64,r.message,t)}break;case`nanoid`:addPattern(n,ed.nanoid,r.message,t)}return n}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const td=/* @__PURE__ */ new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let n=0;n<e.length;n++)td.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;else{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
364
  ]))`;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===$.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.
365
+ ]))`;continue}}n.s&&r[e]===`.`?i+=s?`${r[e]}\r\n`:`[${r[e]}\r\n]`:(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===N.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===N.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=parseStringDef(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===N.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===N.ZodBranded&&e.keyType._def.type._def.typeName===N.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 nd={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 nd&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=nd[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:nd[e.innerType._def.typeName],nullable:!0}:{type:[nd[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 N.ZodString:return parseStringDef(e,n);case N.ZodNumber:return parseNumberDef(e,n);case N.ZodObject:return parseObjectDef(e,n);case N.ZodBigInt:return parseBigintDef(e,n);case N.ZodBoolean:return parseBooleanDef();case N.ZodDate:return parseDateDef(e,n);case N.ZodUndefined:return parseUndefinedDef(n);case N.ZodNull:return parseNullDef(n);case N.ZodArray:return parseArrayDef(e,n);case N.ZodUnion:case N.ZodDiscriminatedUnion:return parseUnionDef(e,n);case N.ZodIntersection:return parseIntersectionDef(e,n);case N.ZodTuple:return parseTupleDef(e,n);case N.ZodRecord:return parseRecordDef(e,n);case N.ZodLiteral:return parseLiteralDef(e,n);case N.ZodEnum:return parseEnumDef(e);case N.ZodNativeEnum:return parseNativeEnumDef(e);case N.ZodNullable:return parseNullableDef(e,n);case N.ZodOptional:return parseOptionalDef(e,n);case N.ZodMap:return parseMapDef(e,n);case N.ZodSet:return parseSetDef(e,n);case N.ZodLazy:return()=>e.getter()._def;case N.ZodPromise:return parsePromiseDef(e,n);case N.ZodNaN:case N.ZodNever:return parseNeverDef(n);case N.ZodEffects:return parseEffectsDef(e,n);case N.ZodAny:return parseAnyDef(n);case N.ZodUnknown:return parseUnknownDef(n);case N.ZodDefault:return parseDefaultDef(e,n);case N.ZodBranded:return parseBrandedDef(e,n);case N.ZodReadonly:return parseReadonlyDef(e,n);case N.ZodCatch:return parseCatchDef(e,n);case N.ZodPipeline:return parsePipelineDef(e,n);case N.ZodFunction:case N.ZodVoid:case N.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!==Zu)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)?En.toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??`input`}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function getMethodLiteral(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let 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=/* @__PURE__ */ new Map,this._requestHandlerAbortControllers=/* @__PURE__ */ new Map,this._notificationHandlers=/* @__PURE__ */ new Map,this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers=/* @__PURE__ */ new Map,this._timeoutInfo=/* @__PURE__ */ new Map,this._pendingDebouncedNotifications=/* @__PURE__ */ new Set,this._taskProgressTokens=/* @__PURE__ */ new Map,this._requestResolvers=/* @__PURE__ */ new Map,this.setNotificationHandler(Nc,e=>{this._oncancel(e)}),this.setNotificationHandler(Zc,e=>{this._onprogress(e)}),this.setRequestHandler(Jc,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 X(Y.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(cl,async(e,t)=>{let handleTaskResult=async()=>{let n=e.params.taskId;if(!await this._taskStore.getTask(n,t.sessionId))throw new X(Y.InvalidParams,`Task not found: ${n}`);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 X(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(/* @__PURE__ */ Error(`${t} handler missing for request ${n}`))}}else await this._transport?.send(e.message,{relatedRequestId:t.requestId})}let r=await this._taskStore.getTask(n,t.sessionId);if(!r)throw new X(Y.InvalidParams,`Task not found: ${n}`);if(!isTerminal(r.status))return await this._waitForTaskUpdate(n,t.signal,t.sessionId),await handleTaskResult();if(isTerminal(r.status)){let e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n,t.sessionId),{...e,_meta:{...e._meta,[hc]:{taskId:n}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ll,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 X(Y.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(dl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new X(Y.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(n.status))throw new X(Y.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,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new X(Y.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof X?e:new X(Y.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),X.fromError(Y.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(/* @__PURE__ */ Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=/* @__PURE__ */ 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=X.fromError(Y.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(/* @__PURE__ */ 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?.[hc]?.taskId,a=r?.sessionId,s=this._taskStore,c=!0,l;if(i&&s&&this._taskMessageQueue&&a!==void 0&&(c=!1,l=(async()=>{if(!await s.getTask(i,a))throw new X(Y.InvalidParams,`Task not found: ${i}`);c=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Y.MethodNotFound,message:`Method not found`}};if(i&&l){let e={type:`error`,message:t,timestamp:Date.now()};l.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let f=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,p=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,m={signal:u.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(u.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(u.signal.aborted)throw new X(Y.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let s=a.relatedTask?.taskId??i;return s&&p&&await p.updateTaskStatus(s,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:p,taskRequestedTtl:f?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(l??Promise.resolve()).then(()=>{if(l&&u.signal.aborted)throw new X(Y.ConnectionClosed,`Request was cancelled`);f&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,m)).then(async t=>{if(u.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(u.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Y.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===u&&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(/* @__PURE__ */ 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 X(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(/* @__PURE__ */ 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(X.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 X?e:new X(Y.InternalError,String(e))}}return}let i;try{let r=await this.request(e,rl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new X(Y.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 X(Y.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new X(Y.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 X?e:new X(Y.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(/* @__PURE__ */ 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||{},[hc]: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(/* @__PURE__ */ Error(`Failed to send cancellation: ${e}`))),u(e instanceof X?e:new X(Y.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(X.fromError(Y.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(/* @__PURE__ */ 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},sl,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},ul,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},fl,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||{},[hc]: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||{},[hc]: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||{},[hc]: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??this._transport?.sessionId,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 X(Y.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(/* @__PURE__ */ Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new X(Y.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new X(Y.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 X(Y.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=al.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 X(Y.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(a.status))throw new X(Y.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=al.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 rd=/* @__PURE__ */ n(Ko(),1);function createDefaultAjvInstance(){let e=new rd.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Xo.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},xu,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},Vu,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=/* @__PURE__ */ new Map,this.LOG_LEVEL_SEVERITY=new Map(su.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(Wc,e=>this._oninitialize(e)),this.setNotificationHandler(qc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(lu,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=su.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=getLiteralValue(n);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(au,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new X(Y.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=safeParse(rl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new X(Y.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=safeParse(ru,a);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new X(Y.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:pc,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`},jc)}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},Su,t):this.request({method:`sampling/createMessage`,params:e},xu,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},Vu,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},Vu,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new X(Y.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof X?e:new X(Y.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},Yu,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 id=Symbol.for(`mcp.completable`);function completable(e,t){return Object.defineProperty(e,id,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function isCompletable(e){return!!e&&typeof e==`object`&&id in e}function getCompleter(e){return e[id]?.complete}var ad;(function(e){e.Completable=`McpCompletable`})(ad||={});const od=1e6,sd=1e6,cd=1e4;var ld=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,od,`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>cd)throw Error(`Template contains too many expressions (max ${cd})`);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,sd,`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,sd,`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,sd,`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,od,`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 ud=/^[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`),!ud.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)}};function toolInputElementCount(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function resolveMaxToolInputElements(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var 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),this._maxToolInputElements=resolveMaxToolInputElements(t?.maxToolInputElements)}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(tu)),this.server.assertCanSetRequestHandler(getMethodValue(au)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(tu,()=>({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`}):dd})(),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(au,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new X(Y.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new X(Y.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 X(Y.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new X(Y.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 X&&e.code===Y.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(this._maxToolInputElements!==void 0&&toolInputElementCount(t,this._maxToolInputElements)>this._maxToolInputElements)throw new X(Y.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);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 X(Y.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 X(Y.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 X(Y.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 X(Y.InternalError,`Task ${c} not found during polling`);l=e}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(Gu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Gu,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 X(Y.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new X(Y.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new X(Y.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return fd;let r=getObjectShape(n.argsSchema)?.[e.params.argument.name];if(!isCompletable(r))return fd;let i=getCompleter(r);return i?createCompletionResult(await i(e.params.argument.value,e.params.context)):fd}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 fd;throw new X(Y.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)):fd}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(xl)),this.server.assertCanSetRequestHandler(getMethodValue(Cl)),this.server.assertCanSetRequestHandler(getMethodValue(Dl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(xl,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(Cl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Dl,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new X(Y.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 X(Y.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(Rl)),this.server.assertCanSetRequestHandler(getMethodValue(Vl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Rl,()=>({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(Vl,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new X(Y.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new X(Y.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 X(Y.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 Dt?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 ld(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};const dd={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 fd={completion:{values:[],hasMore:!1}};var pd=`1.60.0`;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(Tn.string().describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(Re(`id`))),viewId:completable(Tn.string().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(Re(`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(`
366
+ `)}}]})),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(Re(`id`));let n=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(n)).map(Re(`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}(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)});var md=k.union([k.literal(`light`),k.literal(`dark`)]).describe(`Color theme preference for the host environment.`),hd=k.union([k.literal(`inline`),k.literal(`fullscreen`),k.literal(`pip`)]).describe(`Display mode for UI presentation.`),gd=k.union([k.literal(`--color-background-primary`),k.literal(`--color-background-secondary`),k.literal(`--color-background-tertiary`),k.literal(`--color-background-inverse`),k.literal(`--color-background-ghost`),k.literal(`--color-background-info`),k.literal(`--color-background-danger`),k.literal(`--color-background-success`),k.literal(`--color-background-warning`),k.literal(`--color-background-disabled`),k.literal(`--color-text-primary`),k.literal(`--color-text-secondary`),k.literal(`--color-text-tertiary`),k.literal(`--color-text-inverse`),k.literal(`--color-text-ghost`),k.literal(`--color-text-info`),k.literal(`--color-text-danger`),k.literal(`--color-text-success`),k.literal(`--color-text-warning`),k.literal(`--color-text-disabled`),k.literal(`--color-border-primary`),k.literal(`--color-border-secondary`),k.literal(`--color-border-tertiary`),k.literal(`--color-border-inverse`),k.literal(`--color-border-ghost`),k.literal(`--color-border-info`),k.literal(`--color-border-danger`),k.literal(`--color-border-success`),k.literal(`--color-border-warning`),k.literal(`--color-border-disabled`),k.literal(`--color-ring-primary`),k.literal(`--color-ring-secondary`),k.literal(`--color-ring-inverse`),k.literal(`--color-ring-info`),k.literal(`--color-ring-danger`),k.literal(`--color-ring-success`),k.literal(`--color-ring-warning`),k.literal(`--font-sans`),k.literal(`--font-mono`),k.literal(`--font-weight-normal`),k.literal(`--font-weight-medium`),k.literal(`--font-weight-semibold`),k.literal(`--font-weight-bold`),k.literal(`--font-text-xs-size`),k.literal(`--font-text-sm-size`),k.literal(`--font-text-md-size`),k.literal(`--font-text-lg-size`),k.literal(`--font-heading-xs-size`),k.literal(`--font-heading-sm-size`),k.literal(`--font-heading-md-size`),k.literal(`--font-heading-lg-size`),k.literal(`--font-heading-xl-size`),k.literal(`--font-heading-2xl-size`),k.literal(`--font-heading-3xl-size`),k.literal(`--font-text-xs-line-height`),k.literal(`--font-text-sm-line-height`),k.literal(`--font-text-md-line-height`),k.literal(`--font-text-lg-line-height`),k.literal(`--font-heading-xs-line-height`),k.literal(`--font-heading-sm-line-height`),k.literal(`--font-heading-md-line-height`),k.literal(`--font-heading-lg-line-height`),k.literal(`--font-heading-xl-line-height`),k.literal(`--font-heading-2xl-line-height`),k.literal(`--font-heading-3xl-line-height`),k.literal(`--border-radius-xs`),k.literal(`--border-radius-sm`),k.literal(`--border-radius-md`),k.literal(`--border-radius-lg`),k.literal(`--border-radius-xl`),k.literal(`--border-radius-full`),k.literal(`--border-width-regular`),k.literal(`--shadow-hairline`),k.literal(`--shadow-sm`),k.literal(`--shadow-md`),k.literal(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),_d=k.record(gd.describe(`Style variables for theming MCP apps.
343
367
 
344
368
  Individual style keys are optional - hosts may provide any subset of these values.
345
369
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
346
370
 
347
371
  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([E(),Ge()]).describe(`Style variables for theming MCP apps.
372
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),k.union([k.string(),k.undefined()]).describe(`Style variables for theming MCP apps.
349
373
 
350
374
  Individual style keys are optional - hosts may provide any subset of these values.
351
375
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -357,18 +381,18 @@ Individual style keys are optional - hosts may provide any subset of these value
357
381
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
358
382
 
359
383
  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.`);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).
384
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);k.object({method:k.literal(`ui/open-link`),params:k.object({url:k.string().describe(`URL to open in the host's browser`)})}),k.object({isError:k.boolean().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),k.object({isError:k.boolean().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),k.object({isError:k.boolean().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),k.object({method:k.literal(`ui/notifications/sandbox-proxy-ready`),params:k.object({})});var vd=k.object({connectDomains:k.array(k.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
361
385
 
362
386
  - Maps to CSP \`connect-src\` directive
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.
387
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:k.array(k.string()).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:k.array(k.string()).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:k.array(k.string()).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'`)")}),yd=k.object({camera:k.object({}).optional().describe(`Request camera access.
364
388
 
365
- Maps to Permission Policy \`camera\` feature.`),microphone:O({}).optional().describe(`Request microphone access.
389
+ Maps to Permission Policy \`camera\` feature.`),microphone:k.object({}).optional().describe(`Request microphone access.
366
390
 
367
- Maps to Permission Policy \`microphone\` feature.`),geolocation:O({}).optional().describe(`Request geolocation access.
391
+ Maps to Permission Policy \`microphone\` feature.`),geolocation:k.object({}).optional().describe(`Request geolocation access.
368
392
 
369
- Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:O({}).optional().describe(`Request clipboard write access.
393
+ Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:k.object({}).optional().describe(`Request clipboard write access.
370
394
 
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.
395
+ Maps to Permission Policy \`clipboard-write\` feature.`)});k.object({method:k.literal(`ui/notifications/size-changed`),params:k.object({width:k.number().optional().describe(`New width in pixels.`),height:k.number().optional().describe(`New height in pixels.`)})}),k.object({method:k.literal(`ui/notifications/tool-input`),params:k.object({arguments:k.record(k.string(),k.unknown().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),k.object({method:k.literal(`ui/notifications/tool-input-partial`),params:k.object({arguments:k.record(k.string(),k.unknown().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),k.object({method:k.literal(`ui/notifications/tool-cancelled`),params:k.object({reason:k.string().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var bd=k.object({fonts:k.string().optional()}),xd=k.object({variables:_d.optional().describe(`CSS variables for theming the app.`),css:bd.optional().describe(`CSS blocks that apps can inject.`)});k.object({method:k.literal(`ui/resource-teardown`),params:k.object({})}),k.record(k.string(),k.unknown());var Sd=k.object({text:k.object({}).optional().describe(`Host supports text content blocks.`),image:k.object({}).optional().describe(`Host supports image content blocks.`),audio:k.object({}).optional().describe(`Host supports audio content blocks.`),resource:k.object({}).optional().describe(`Host supports resource content blocks.`),resourceLink:k.object({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:k.object({}).optional().describe(`Host supports structured content.`)});k.object({method:k.literal(`ui/notifications/request-teardown`),params:k.object({}).optional()});var Cd=k.object({experimental:k.record(k.string(),k.record(k.string(),k.any()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:k.object({}).optional().describe(`Host supports opening external URLs.`),downloadFile:k.object({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:k.object({listChanged:k.boolean().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:k.object({listChanged:k.boolean().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:k.object({}).optional().describe(`Host accepts log messages.`),sandbox:k.object({permissions:yd.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:vd.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Sd.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Sd.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:k.object({tools:k.object({}).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.")}),wd=k.object({experimental:k.record(k.string(),k.record(k.string(),k.any()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:k.object({listChanged:k.boolean().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:k.array(hd).optional().describe(`Display modes the app supports.`)});k.object({method:k.literal(`ui/notifications/initialized`),params:k.object({}).optional()}),k.object({csp:vd.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:yd.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:k.string().optional().describe(`Dedicated origin for view sandbox.
372
396
 
373
397
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
374
398
 
@@ -376,26 +400,16 @@ Useful when views need stable, dedicated origins for OAuth callbacks, CORS polic
376
400
  - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
377
401
  - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
378
402
 
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.
403
+ If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:k.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
380
404
 
381
405
  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
406
 
383
407
  - \`true\`: request visible border + background
384
408
  - \`false\`: request no visible border + background
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"]
409
+ - omitted: host decides border`)}),k.object({method:k.literal(`ui/request-display-mode`),params:k.object({mode:hd.describe(`The display mode being requested.`)})}),k.object({mode:hd.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough();var Td=k.union([k.literal(`model`),k.literal(`app`)]).describe(`Tool visibility scope - who can access the tool.`);k.object({resourceUri:k.string().optional(),visibility:k.array(Td).optional().describe(`Who can access this tool. Default: ["model", "app"]
386
410
  - "model": Tool visible to and callable by the agent
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
-
390
- Request:
391
- - viewId: string — view id (name)
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.
397
-
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>
411
+ - "app": Tool callable by the app from this server only`),csp:k.never().optional(),permissions:k.never().optional()}),k.object({mimeTypes:k.array(k.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),k.object({method:k.literal(`ui/download-file`),params:k.object({contents:k.array(k.union([Kl,ql])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),k.object({method:k.literal(`ui/message`),params:k.object({role:k.literal(`user`).describe(`Message role, currently only "user" is supported.`),content:k.array(Jl).describe(`Message content blocks (text, image, etc.).`)})}),k.object({method:k.literal(`ui/notifications/sandbox-resource-ready`),params:k.object({html:k.string().describe(`HTML content to load into the inner iframe.`),sandbox:k.string().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:vd.optional().describe(`CSP configuration from resource metadata.`),permissions:yd.optional().describe(`Sandbox permissions from resource metadata.`)})}),k.object({method:k.literal(`ui/notifications/tool-result`),params:ru.describe(`Standard MCP tool execution result.`)});var Ed=k.object({toolInfo:k.object({id:Tc.optional().describe(`JSON-RPC id of the tools/call request.`),tool:eu.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:md.optional().describe(`Current color theme preference.`),styles:xd.optional().describe(`Style configuration for theming the app.`),displayMode:hd.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:k.array(hd).optional().describe(`Display modes the host supports.`),containerDimensions:k.union([k.object({height:k.number().describe(`Fixed container height in pixels.`)}),k.object({maxHeight:k.union([k.number(),k.undefined()]).optional().describe(`Maximum container height in pixels.`)})]).and(k.union([k.object({width:k.number().describe(`Fixed container width in pixels.`)}),k.object({maxWidth:k.union([k.number(),k.undefined()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
412
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:k.string().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:k.string().optional().describe(`User's timezone in IANA format.`),userAgent:k.string().optional().describe(`Host application identifier.`),platform:k.union([k.literal(`web`),k.literal(`desktop`),k.literal(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:k.object({touch:k.boolean().optional().describe(`Whether the device supports touch input.`),hover:k.boolean().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:k.object({top:k.number().describe(`Top safe area inset in pixels.`),right:k.number().describe(`Right safe area inset in pixels.`),bottom:k.number().describe(`Bottom safe area inset in pixels.`),left:k.number().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();k.object({method:k.literal(`ui/notifications/host-context-changed`),params:Ed.describe(`Partial context update containing only changed fields.`)}),k.object({method:k.literal(`ui/update-model-context`),params:k.object({content:k.array(Jl).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:k.record(k.string(),k.unknown().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),k.object({method:k.literal(`ui/initialize`),params:k.object({appInfo:Lc.describe(`App identification (name and version).`),appCapabilities:wd.describe(`Features and capabilities this app provides.`),protocolVersion:k.string().describe(`Protocol version this app supports.`)})}),k.object({protocolVersion:k.string().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Lc.describe(`Host application identification and version.`),hostCapabilities:Cd.describe(`Features and capabilities provided by the host.`),hostContext:Ed.describe(`Rich context about the host environment.`)}).passthrough();var Dd=`ui/resourceUri`,Od=`text/html;profile=mcp-app`;function K3(e,t,n,r){let i=n._meta,a=i.ui,s=i[Dd],c=i;return a?.resourceUri&&!s?c={...i,[Dd]: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:Od,...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=gn(e);if(Ht(t))return Ut(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 kd=O.object({name:O.string().describe(`Project identifier`),title:O.string().optional().describe(`Human-readable project title`),contactPerson:O.string().optional().describe(`Maintainer contact information`),metadata:O.record(O.string(),O.unknown()).optional().describe(`Custom project metadata as key-value pairs`),extends:O.union([O.string(),O.array(O.string())]).optional().describe(`Style inheritance paths`),exclude:O.array(O.string()).optional().describe(`File exclusion patterns`),include:O.object({paths:O.array(O.string()).describe(`Include paths`),maxDepth:O.number().describe(`Maximum directory depth`),fileThreshold:O.number().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:O.object({outDir:O.string().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:O.object({hasTheme:O.boolean().describe(`Whether theme customization is defined`),hasDefaults:O.boolean().describe(`Whether default style values are defined`),hasCustomCss:O.boolean().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 Ad=O.object({id:O.string().describe(`Element id (FQN)`),name:O.string().describe(`Element name`),kind:O.string().describe(`Element kind`),title:O.string(),tags:O.array(O.string()),metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])),includedInViews:O.array(O.object({id:O.string().describe(`View id`),title:O.string().describe(`View title`),type:O.enum([`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);A(s,`Element "${t}" not found`);let c=/* @__PURE__ */ 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 jd=O.object({path:O.string().describe(`Path to the file`),range:O.object({start:O.object({line:O.number(),character:O.number()}),end:O.object({line:O.number(),character:O.number()})}).describe(`Range in the file`)}).nullable(),Md=O.array(O.object({title:O.string().nullable().describe(`Optional link title`),url:O.string().describe(`Link URL`),relative:O.string().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 Q=O.string().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),Nd=O.array(O.object({id:O.string().describe(`View id`),title:O.string().describe(`View title`),type:O.enum([`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:ae.parse(r.uri).fsPath,range:r.range}:null}catch(e){return Z.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=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ 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),Ct.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(wt(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(Ut(ae.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 Pd=`ui://likec4/render-view.html`,Fd=O.object({size:O.enum([`compact`,`standard`,`large`]).default(`standard`).describe(`Initial canvas size hint`),fitView:O.boolean().default(!0).describe(`Fit the diagram into the canvas initially`),initialZoom:O.number().min(.05).max(3).optional().describe(`Initial zoom level; overrides fitView`)}).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. Use it when the user wants to *see* a view; use "read-view" when only the view's structure (nodes/edges) is needed.`,inputSchema:mcpToolSchema({viewId:O.string().describe(`View id (name)`),project:Q,fullModel:O.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`),render:Fd}),outputSchema:mcpToolSchema({id:O.string(),title:O.string(),project:O.string(),view:O.record(O.string(),O.unknown()).describe(`Layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:O.record(O.string(),O.unknown()).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:Fd}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:Pd}}},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>
399
413
  <html>
400
414
  <head>
401
415
  <meta charset="utf-8" />
@@ -409,1132 +423,10 @@ Use this when the user wants to *see* a view. Use "read-view" instead when only
409
423
  <div id="root"></div>
410
424
  <script>${e}<\/script>
411
425
  </body>
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+`
413
-
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:`
415
- Read details of multiple elements in a single call, reducing round-trips.
416
- Returns a compact summary for each element including metadata, description, technology, shape, children, relationship counts, links and source location.
417
-
418
- Request:
419
- - ids: string[] — array of element ids (FQNs) to read (max 50)
420
- - project: string (optional) — project id. Defaults to "default" if omitted.
421
-
422
- Response (JSON object):
423
- - elements: Array of element details, each with:
424
- - id: string — element id (FQN)
425
- - name: string — element name
426
- - kind: string — element kind
427
- - title: string — human-readable title
428
- - description: string|null — optional description
429
- - technology: string|null — optional technology
430
- - tags: string[] — assigned tags
431
- - metadata: Record<string, string | string[]> — element metadata
432
- - shape: string — rendered shape
433
- - color: string — rendered color
434
- - children: string[] — direct child element ids
435
- - incomingCount: number — number of incoming relationships
436
- - outgoingCount: number — number of outgoing relationships
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
440
- - notFound: string[] — ids that were not found in the project
441
-
442
- View (object) fields:
443
- - id: string — view identifier
444
- - title: string — view title
445
- - type: "element" | "deployment" | "dynamic"
446
-
447
- Notes:
448
- - Read-only, idempotent, no side effects.
449
- - Safe to call repeatedly.
450
- - Maximum 50 element ids per call.
451
- - Elements not found are listed in notFound array (not an error).
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.
455
-
456
- Example response:
457
- {
458
- "elements": [
459
- {
460
- "id": "shop.frontend",
461
- "name": "frontend",
462
- "kind": "container",
463
- "title": "Frontend",
464
- "description": "User-facing web app",
465
- "technology": "React",
466
- "tags": ["public"],
467
- "metadata": { "owner": "web-team" },
468
- "shape": "browser",
469
- "color": "#2F80ED",
470
- "children": ["shop.frontend.auth"],
471
- "incomingCount": 2,
472
- "outgoingCount": 3,
473
- "includedInViews": [
474
- { "id": "system-overview", "title": "System Overview", "type": "element" }
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
- }
483
- }
484
- ],
485
- "notFound": []
486
- }
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:`
488
- Compare two elements side-by-side, showing differences in properties, tags, metadata, and relationships.
489
-
490
- Request:
491
- - element1Id: string — first element id (FQN)
492
- - element2Id: string — second element id (FQN)
493
- - project: string (optional) — project id. Defaults to "default" if omitted.
494
-
495
- Response (JSON object):
496
- - element1: object — snapshot of first element (id, kind, title, description, technology, shape, color)
497
- - element2: object — snapshot of second element
498
- - propertyDiffs: Array of { property, element1Value, element2Value } — properties that differ
499
- - tags: object
500
- - onlyInElement1: string[] — tags only in element1
501
- - onlyInElement2: string[] — tags only in element2
502
- - common: string[] — tags in both
503
- - metadata: object
504
- - onlyInElement1: Record — metadata keys only in element1
505
- - onlyInElement2: Record — metadata keys only in element2
506
- - different: Array of { key, element1Value, element2Value } — keys present in both but with different values
507
- - common: Record — metadata keys with identical values in both
508
- - relationships: object — relationship count comparison
509
- - incomingOnlyElement1/incomingOnlyElement2/incomingShared
510
- - outgoingOnlyElement1/outgoingOnlyElement2/outgoingShared
511
-
512
- Notes:
513
- - Read-only, idempotent, no side effects.
514
- - Safe to call repeatedly.
515
- - Both elements must exist in the same project.
516
- - Useful for comparing similar nodes to understand why they have different configurations.
517
-
518
- Example response:
519
- {
520
- "element1": { "id": "planner.nodeA", "kind": "cgf-node", "title": "nodeA", ... },
521
- "element2": { "id": "planner.nodeB", "kind": "cgf-node", "title": "nodeB", ... },
522
- "propertyDiffs": [
523
- { "property": "title", "element1Value": "nodeA :dwNodeTypeA", "element2Value": "nodeB :dwNodeTypeB" }
524
- ],
525
- "tags": {
526
- "onlyInElement1": ["target_asil_qm"],
527
- "onlyInElement2": ["target_asil_asil_b"],
528
- "common": ["is_in_dag", "process_camera_master"]
529
- },
530
- "metadata": {
531
- "onlyInElement1": {},
532
- "onlyInElement2": {},
533
- "different": [
534
- { "key": "target_asil", "element1Value": "QM", "element2Value": "ASIL-B" }
535
- ],
536
- "common": { "host": "machine0" }
537
- },
538
- "relationships": {
539
- "incomingOnlyElement1": 2,
540
- "incomingOnlyElement2": 1,
541
- "incomingShared": 3,
542
- "outgoingOnlyElement1": 0,
543
- "outgoingOnlyElement2": 1,
544
- "outgoingShared": 2
545
- }
546
- }
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:`
548
- Discover all paths (chains of relationships) between two elements, supporting multi-hop traversal.
549
-
550
- Request:
551
- - sourceId: string — source element FQN
552
- - targetId: string — target element FQN
553
- - maxDepth: number (optional, default: 3, max: 5) — maximum path length (number of hops)
554
- - includeIndirect: boolean (optional, default: false) — include indirect (implied) relationships through nested elements
555
- - project: string (optional) — project id. Defaults to "default" if omitted.
556
-
557
- Algorithm:
558
- - Uses breadth-first search (BFS) to find all paths
559
- - Prevents cycles with visited set per path
560
- - Paths are sorted by length (shortest first)
561
- - Limited to 100 paths to avoid overwhelming responses
562
-
563
- Response (JSON object):
564
- - paths: Array of path objects, each with:
565
- - length: number — number of hops in the path
566
- - steps: Array<Step> — ordered sequence of relationships
567
-
568
- Step (object) fields:
569
- - source: string — source element FQN
570
- - target: string — target element FQN
571
- - relationship: object
572
- - kind: string|null — relationship kind
573
- - title: string|null — relationship title
574
- - description: string|null — relationship description
575
- - technology: string|null — relationship technology
576
- - tags: string[] — relationship tags
577
-
578
- Notes:
579
- - Read-only, idempotent, no side effects.
580
- - Safe to call repeatedly.
581
- - Returns empty paths array if no paths exist.
582
- - Rejects if source equals target.
583
- - includeIndirect=false (default): only follows direct relationships on each element.
584
- includeIndirect=true: also follows implied relationships through nested elements.
585
- - maxDepth is capped at 5 to prevent excessive computation.
586
- - Paths are discovered iteratively and sorted by length.
587
-
588
- Example response:
589
- {
590
- "paths": [
591
- {
592
- "length": 1,
593
- "steps": [
594
- {
595
- "source": "shop.frontend",
596
- "target": "shop.backend",
597
- "relationship": {
598
- "kind": "uses",
599
- "title": "Calls API",
600
- "description": null,
601
- "technology": "HTTPS",
602
- "tags": []
603
- }
604
- }
605
- ]
606
- },
607
- {
608
- "length": 2,
609
- "steps": [
610
- {
611
- "source": "shop.frontend",
612
- "target": "shop.cache",
613
- "relationship": {
614
- "kind": "uses",
615
- "title": "Reads from",
616
- "description": null,
617
- "technology": "Redis",
618
- "tags": []
619
- }
620
- },
621
- {
622
- "source": "shop.cache",
623
- "target": "shop.backend",
624
- "relationship": {
625
- "kind": "syncs-with",
626
- "title": "Updates",
627
- "description": null,
628
- "technology": null,
629
- "tags": []
630
- }
631
- }
632
- ]
633
- }
634
- ]
635
- }
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:`
637
- Find relationships between two LikeC4 elements within a project.
638
-
639
- What it does:
640
- - Finds both direct relationships (element1 ↔ element2) and indirect ones that arise via containment (e.g. via nested elements).
641
- - Returns rich metadata for each relationship and where it appears in views.
642
-
643
- Inputs:
644
- - element1: string — Element ID (FQN)
645
- - element2: string — Element ID (FQN)
646
- - project: string (optional, defaults to "default") — Project id
647
-
648
- Output:
649
- - found: Relationship[]
650
-
651
- Relationship (object) fields:
652
- - type: "direct" | "indirect" — direct is between the specified endpoints; indirect is via nested elements
653
- - source: Endpoint
654
- - target: Endpoint
655
- - kind: string|null — relationship kind from the model
656
- - title: string|null — relationship title if provided
657
- - description: string|null — relationship description text
658
- - technology: string|null — relationship technology
659
- - tags: string[] — relationship tags
660
- - includedInViews: View[] — views where this relationship appears
661
- - sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null
662
-
663
- Endpoint (object) fields:
664
- - id: string — Element ID (FQN)
665
- - title: string — element title
666
- - kind: string — element kind
667
-
668
- View (object) fields:
669
- - id: string — view identifier
670
- - title: string — view title
671
- - type: "element" | "deployment" | "dynamic"
672
-
673
- Notes:
674
- - Read-only, idempotent; does not mutate the model. May trigger UI navigation in supporting clients.
675
- - The order of results is not guaranteed.
676
-
677
- Example:
678
- Request:
679
- {
680
- "element1": "shop.frontend",
681
- "element2": "shop.backend",
682
- "project": "default"
683
- }
684
-
685
- Response:
686
- {
687
- "found": [
688
- {
689
- "type": "direct",
690
- "source": { "id": "shop.frontend", "title": "Frontend", "kind": "component" },
691
- "target": { "id": "shop.backend", "title": "Backend", "kind": "component" },
692
- "kind": "sync",
693
- "title": "Calls",
694
- "description": "Frontend calls Backend",
695
- "technology": "HTTP",
696
- "tags": ["public"],
697
- "includedInViews": [
698
- { "id": "system-overview", "title": "System Overview", "type": "element" }
699
- ],
700
- "sourceLocation": {
701
- "path": "/abs/path/project/model.c4",
702
- "range": { "start": { "line": 12, "character": 0 }, "end": { "line": 14, "character": 0 } }
703
- }
704
- }
705
- ]
706
- }
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:`
708
- List LikeC4 projects discoverable in the current workspace.
709
-
710
- Request:
711
- - No input parameters.
712
-
713
- Response (JSON object):
714
- - projects: Project[]
715
-
716
- Project (object) fields:
717
- - id: string — stable project identifier
718
- - title: string — human-readable project title
719
- - folder: string — absolute path to the project root
720
- - sources: string[] — absolute file paths of related documents
721
-
722
- Notes:
723
- - Read-only, idempotent, no side effects.
724
- - Safe to call repeatedly.
725
-
726
- Example response:
727
- {
728
- "projects": [
729
- {
730
- "id": "docs",
731
- "title": "Documentation",
732
- "folder": "/abs/path/to/workspace/docs",
733
- "sources": [
734
- "/abs/path/to/workspace/docs/model/contexts.likec4",
735
- "/abs/path/to/workspace/docs/model/relations.likec4"
736
- ]
737
- }
738
- ]
739
- }
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(`
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.
742
-
743
- Request:
744
- - dsl: string — a single \`view <id> ... { ... }\` definition. It must reference elements that already exist in the target project.
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.
747
-
748
- Behavior:
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.
750
- - The view is rendered as a draft alongside the project's real elements.
751
-
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.
753
-
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:`
755
- Search elements and deployment nodes by metadata key-value pairs with flexible matching modes.
756
-
757
- Request:
758
- - key: string — metadata key to filter by
759
- - value: string (optional) — metadata value to match (ignored for 'exists' mode)
760
- - matchMode: "exact" | "contains" | "exists" (optional, default: "exact")
761
- - project: string (optional) — project id. Defaults to "default" if omitted.
762
-
763
- Match Modes:
764
- - exact: Value must match exactly (case-sensitive)
765
- Example: key="owner", value="platform-team" matches only exact "platform-team"
766
- - contains: Value contains the search string (case-insensitive)
767
- Example: key="technology", value="aws" matches "AWS Lambda", "aws-s3", etc.
768
- - exists: Element has the key (value parameter is ignored)
769
- Example: key="owner" returns all elements with any "owner" metadata
770
-
771
- Response (JSON object):
772
- - results: Array of matching elements/deployment-nodes, each with:
773
- - id: string — element/node id (FQN)
774
- - name: string — element/node name
775
- - kind: string — element/node kind
776
- - title: string — human-readable title
777
- - tags: string[] — assigned tags
778
- - metadata: Record<string, string | string[]> — all element metadata
779
- - matchedValue: string — the metadata value that matched (for reference)
780
- - includedInViews: View[] — views that include this element
781
-
782
- View (object) fields:
783
- - id: string — view identifier
784
- - title: string — view title
785
- - type: "element" | "deployment" | "dynamic"
786
-
787
- Notes:
788
- - Read-only, idempotent, no side effects.
789
- - Safe to call repeatedly.
790
- - Handles both string and array metadata values.
791
- - For array values, matches if any element in the array matches.
792
- - Returns empty array if no matches found.
793
- - Limited to 50 results to avoid overwhelming responses.
794
- - Case-sensitive for exact mode, case-insensitive for contains mode.
795
-
796
- Example response:
797
- {
798
- "results": [
799
- {
800
- "id": "shop.frontend",
801
- "name": "frontend",
802
- "kind": "container",
803
- "title": "Frontend",
804
- "tags": ["public"],
805
- "metadata": {
806
- "owner": "platform-team",
807
- "tier": "critical"
808
- },
809
- "matchedValue": "platform-team",
810
- "includedInViews": [
811
- {
812
- "id": "system-overview",
813
- "title": "System Overview",
814
- "type": "element"
815
- }
816
- ]
817
- }
818
- ]
819
- }
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:`
821
- Search elements by tag patterns using prefix or substring matching.
822
- Useful for tag taxonomies with structured naming conventions (e.g., "schedule_*", "*_asil_*").
823
-
824
- Request:
825
- - pattern: string — tag pattern to match
826
- - matchMode: "prefix" | "contains" | "suffix" (optional, default: "prefix")
827
- - prefix: matches tags starting with the pattern (e.g., "target_asil" matches "target_asil_qm", "target_asil_asil_b")
828
- - contains: matches tags containing the pattern anywhere (e.g., "asil" matches "target_asil_qm", "unit_asil_b")
829
- - suffix: matches tags ending with the pattern (e.g., "_tbc" matches "target_asil_qm__tbc")
830
- - project: string (optional) — project id. Defaults to "default" if omitted.
831
-
832
- Response (JSON object):
833
- - results: Array of matching elements, each with:
834
- - id: string — element id (FQN)
835
- - name: string — element name
836
- - kind: string — element kind
837
- - title: string — human-readable title
838
- - tags: string[] — all assigned tags
839
- - metadata: Record<string, string | string[]> — element metadata
840
- - matchedTags: string[] — the specific tags that matched the pattern
841
- - includedInViews: View[] — views that include this element
842
- - truncated: boolean — true if results were truncated due to exceeding the 50-result limit
843
- - matchedTagValues: string[] — all unique tag values that matched the pattern across all elements
844
-
845
- View (object) fields:
846
- - id: string — view identifier
847
- - title: string — view title
848
- - type: "element" | "deployment" | "dynamic"
849
-
850
- Notes:
851
- - Read-only, idempotent, no side effects.
852
- - Safe to call repeatedly.
853
- - Pattern matching is case-insensitive.
854
- - Returns empty array if no matches found.
855
- - Limited to 50 results.
856
- - matchedTagValues provides a summary of all distinct matching tag values found.
857
-
858
- Example response:
859
- {
860
- "results": [
861
- {
862
- "id": "top.planner.behaviorNode",
863
- "name": "behaviorNode",
864
- "kind": "cgf-node",
865
- "title": "behaviorNode :dwBehaviorPlannerNode",
866
- "tags": ["is_in_dag", "target_asil_qm", "process_camera_master"],
867
- "metadata": {},
868
- "matchedTags": ["target_asil_qm"],
869
- "includedInViews": []
870
- }
871
- ],
872
- "truncated": false,
873
- "matchedTagValues": ["target_asil_qm", "target_asil_asil_b", "target_asil_qm__tbc"]
874
- }
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:`
876
- Advanced tag filtering with boolean logic (AND, OR, NOT).
877
-
878
- Request:
879
- - allOf: string[] (optional) — element must have ALL these tags (AND logic)
880
- - anyOf: string[] (optional) — element must have ANY of these tags (OR logic)
881
- - noneOf: string[] (optional) — element must have NONE of these tags (NOT logic)
882
- - project: string (optional) — project id. Defaults to "default" if omitted.
883
-
884
- Boolean Logic:
885
- - All three conditions are combined with AND logic
886
- - At least one condition must be specified
887
- - Tags are case-sensitive
888
-
889
- Example Queries:
890
- - Public APIs: {"allOf": ["public", "api"]}
891
- - Deprecated or legacy: {"anyOf": ["deprecated", "legacy"]}
892
- - Public but not deprecated: {"allOf": ["public"], "noneOf": ["deprecated"]}
893
- - Critical services not in migration: {"allOf": ["critical", "service"], "noneOf": ["migration", "deprecated"]}
894
-
895
- Response (JSON object):
896
- - results: Array of matching elements/deployment-nodes, each with:
897
- - id: string — element/node id (FQN)
898
- - name: string — element/node name
899
- - kind: string — element/node kind
900
- - title: string — human-readable title
901
- - tags: string[] — assigned tags (for reference)
902
- - metadata: Record<string, string | string[]> — element metadata
903
- - includedInViews: View[] — views that include this element
904
-
905
- View (object) fields:
906
- - id: string — view identifier
907
- - title: string — view title
908
- - type: "element" | "deployment" | "dynamic"
909
-
910
- Notes:
911
- - Read-only, idempotent, no side effects.
912
- - Safe to call repeatedly.
913
- - Returns empty array if no matches found.
914
- - Limited to 50 results to avoid overwhelming responses.
915
- - Conflicting conditions (e.g., allOf and noneOf with same tag) will return no results.
916
-
917
- Example response:
918
- {
919
- "results": [
920
- {
921
- "id": "shop.api",
922
- "name": "api",
923
- "kind": "container",
924
- "title": "API Gateway",
925
- "tags": ["public", "api", "critical"],
926
- "metadata": {
927
- "owner": "platform-team"
928
- },
929
- "includedInViews": [
930
- {
931
- "id": "system-overview",
932
- "title": "System Overview",
933
- "type": "element"
934
- }
935
- ]
936
- }
937
- ]
938
- }
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:`
940
- Query element hierarchy and relationships in the architecture graph.
941
-
942
- Request:
943
- - elementId: string — element id (FQN) to query
944
- - queryType: "ancestors" | "descendants" | "siblings" | "children" | "parent" | "incomers" | "outgoers"
945
- - includeIndirect: boolean (optional, default: true) — for incomers/outgoers, include indirect relationships (through nested elements)
946
- - project: string (optional) — project id. Defaults to "default" if omitted.
947
-
948
- Query Types:
949
- - ancestors: Returns all parent elements up to the root (hierarchical)
950
- Example: shop.frontend.auth.service returns [shop.frontend.auth, shop.frontend, shop]
951
- - descendants: Returns all child elements recursively (hierarchical)
952
- Example: shop.frontend returns all nested elements like shop.frontend.auth, shop.frontend.auth.service
953
- - siblings: Returns elements at the same hierarchy level with the same parent
954
- Example: shop.frontend returns [shop.backend, shop.database] if they're siblings
955
- - children: Returns direct child elements only (not recursive)
956
- Example: shop returns [shop.frontend, shop.backend] but not shop.frontend.auth
957
- - parent: Returns the direct parent element
958
- Example: shop.frontend.auth returns shop.frontend
959
- - incomers: Returns elements that have outgoing relationships to this element (single hop, not recursive).
960
- For recursive upstream traversal, use query-incomers-graph instead.
961
- includeIndirect=true: Includes relationships to nested children
962
- Example: Elements that depend on this element
963
- - outgoers: Returns elements that receive incoming relationships from this element (single hop, not recursive).
964
- For recursive downstream traversal, use query-outgoers-graph instead.
965
- includeIndirect=true: Includes relationships from nested children
966
- Example: Elements this element depends on
967
-
968
- Response (JSON object):
969
- - results: Array of elements (max 100), each with:
970
- - id: string — element id (FQN)
971
- - name: string — element name
972
- - kind: string — element kind
973
- - title: string — human-readable title
974
- - tags: string[] — assigned tags
975
- - metadata: Record<string, string> — element metadata
976
- - includedInViews: View[] — views that include this element
977
- - truncated: boolean — true if results were truncated due to exceeding maximum limit (100)
978
-
979
- View (object) fields:
980
- - id: string — view identifier
981
- - title: string — view title
982
- - type: "element" | "deployment" | "dynamic"
983
-
984
- Notes:
985
- - Read-only, idempotent, no side effects.
986
- - Safe to call repeatedly.
987
- - For parent query on root element, returns empty array.
988
- - For hierarchical queries (ancestors, descendants, siblings, children), includeIndirect is ignored.
989
-
990
- Example response:
991
- {
992
- "results": [
993
- {
994
- "id": "shop.frontend",
995
- "name": "frontend",
996
- "kind": "container",
997
- "title": "Frontend",
998
- "tags": ["public"],
999
- "metadata": { "owner": "web-team" },
1000
- "includedInViews": [
1001
- {
1002
- "id": "system-overview",
1003
- "title": "System Overview",
1004
- "type": "element"
1005
- }
1006
- ]
1007
- }
1008
- ],
1009
- "truncated": false
1010
- }
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:`
1012
- Query the complete graph of all elements that provide input to the target element (recursive incomers/producers).
426
+ </html>`}function renderViewResource(e){return N3(e,`Render View UI`,Pd,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:Pd,mimeType:Od,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(O.string().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(Re(`id`))),viewId:completable(O.string().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(Re(`id`))})}),outputSchema:mcpToolSchema({reasoning:O.string().describe(`Reasoning behind the layout changes`),snapshotUri:O.string().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 qe(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+`
1013
427
 
1014
- This tool performs a breadth-first traversal to discover all upstream dependencies - elements that directly or
1015
- indirectly provide input to the target element. It returns the complete subgraph in a single response,
1016
- making it much more efficient than repeated individual queries.
1017
-
1018
- Request:
1019
- - elementId: string — target element id (FQN) to start from
1020
- - includeIndirect: boolean (optional, default: true) — include relationships through nested elements
1021
- - maxDepth: number (optional, default: 10, max: 50) — maximum traversal depth to prevent infinite recursion
1022
- - maxNodes: number (optional, default: 200, max: 2000) — maximum number of nodes to return
1023
- - project: string (optional) — project id. Defaults to "default" if omitted.
1024
-
1025
- Response Structure:
1026
- {
1027
- "target": "element.id",
1028
- "totalNodes": number,
1029
- "maxDepth": number,
1030
- "truncated": boolean,
1031
- "nodes": {
1032
- "element.id": {
1033
- "id": "element.id",
1034
- "name": "name",
1035
- "kind": "kind",
1036
- "title": "title",
1037
- "tags": ["tag1", "tag2"],
1038
- "metadata": {},
1039
- "includedInViews": [...],
1040
- "incomers": [
1041
- {
1042
- "elementId": "id1",
1043
- "relationshipLabel": "uses",
1044
- "technology": "REST"
1045
- }
1046
- ],
1047
- "depth": number
1048
- }
1049
- }
1050
- }
1051
-
1052
- Use Cases:
1053
- - Find all producers/dependencies for an element
1054
- - Trace data lineage upstream
1055
- - Identify root causes and dependencies
1056
- - Build complete dependency trees
1057
- - Answer "what feeds into this?" questions
1058
-
1059
- Notes:
1060
- - Read-only, idempotent, no side effects
1061
- - Cycle detection prevents infinite loops
1062
- - Result size limited to maxNodes to prevent huge responses
1063
- - If truncated=true, increase maxNodes or reduce maxDepth to get more specific results
1064
-
1065
- Example:
1066
- For a database element, this returns all services, APIs, and components that write to it,
1067
- plus all their dependencies, recursively up to maxDepth levels.
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:`
1069
- Query the complete graph of all elements that receive output from the target element (recursive outgoers/consumers).
1070
-
1071
- This tool performs a breadth-first traversal to discover all downstream dependencies - elements that directly or
1072
- indirectly consume output from the target element. It returns the complete subgraph in a single response,
1073
- making it much more efficient than repeated individual queries.
1074
-
1075
- Request:
1076
- - elementId: string — target element id (FQN) to start from
1077
- - includeIndirect: boolean (optional, default: true) — include relationships through nested elements
1078
- - maxDepth: number (optional, default: 10, max: 50) — maximum traversal depth to prevent infinite recursion
1079
- - maxNodes: number (optional, default: 200, max: 2000) — maximum number of nodes to return
1080
- - project: string (optional) — project id. Defaults to "default" if omitted.
1081
-
1082
- Response Structure:
1083
- {
1084
- "target": "element.id",
1085
- "totalNodes": number,
1086
- "maxDepth": number,
1087
- "truncated": boolean,
1088
- "nodes": {
1089
- "element.id": {
1090
- "id": "element.id",
1091
- "name": "name",
1092
- "kind": "kind",
1093
- "title": "title",
1094
- "tags": ["tag1", "tag2"],
1095
- "metadata": {},
1096
- "includedInViews": [...],
1097
- "outgoers": [
1098
- {
1099
- "elementId": "id1",
1100
- "relationshipLabel": "sends data to",
1101
- "technology": "Kafka"
1102
- }
1103
- ],
1104
- "depth": number
1105
- }
1106
- }
1107
- }
1108
-
1109
- Use Cases:
1110
- - Find all consumers/dependents of an element
1111
- - Trace data lineage downstream
1112
- - Assess impact of changes (blast radius)
1113
- - Build complete consumer trees
1114
- - Answer "what depends on this?" questions
1115
-
1116
- Notes:
1117
- - Read-only, idempotent, no side effects
1118
- - Cycle detection prevents infinite loops
1119
- - Result size limited to maxNodes to prevent huge responses
1120
- - If truncated=true, increase maxNodes or reduce maxDepth to get more specific results
1121
-
1122
- Example:
1123
- For an API service, this returns all clients, services, and systems that consume its output,
1124
- plus all their consumers, recursively up to maxDepth levels.
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:`
1126
- Read details about a deployment node or a deployed instance in a LikeC4 project.
1127
-
1128
- What it does:
1129
- - Returns metadata about a deployment entity (node or instance), including kind, tags, color/shape, children, which views include it, and its source location.
1130
-
1131
- Inputs:
1132
- - id: string — Deployment id (FQN)
1133
- - project: string (optional, defaults to "default") — Project id
1134
-
1135
- Output fields:
1136
- - type: "deployment-node" | "deployed-instance"
1137
- - id: string — Deployment id (FQN)
1138
- - kind: string — Deployment node kind, or element kind for deployed instances
1139
- - name: string — Name of the deployment entity
1140
- - title: string — Title of the deployment entity
1141
- - description: string|null — Description text
1142
- - technology: string|null — Technology info, if any
1143
- - tags: string[] — Tags assigned to this entity
1144
- - project: string — Project id
1145
- - metadata: Record<string, string>
1146
- - links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this deployment entity
1147
- - shape: string — Rendered shape
1148
- - color: string — Rendered color
1149
- - children: string[] — Child deployment ids (empty for instances)
1150
- - includedInViews: View[] — Views that include this entity
1151
- - instanceof: { id: string, title: string, kind: string } | null — If type is "deployed-instance", the referenced element
1152
- - sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null
1153
-
1154
- View (object) fields:
1155
- - id: string — view identifier
1156
- - title: string — view title
1157
- - type: "element" | "deployment" | "dynamic"
1158
-
1159
- Notes:
1160
- - Read-only, idempotent; does not mutate the model.
1161
-
1162
- Example request:
1163
- { "id": "k8s.cluster.frontend", "project": "default" }
1164
-
1165
- Example response (deployed instance):
1166
- {
1167
- "type": "deployed-instance",
1168
- "id": "k8s.cluster.frontend",
1169
- "kind": "k8s.pod",
1170
- "name": "frontend",
1171
- "title": "Frontend Pod",
1172
- "description": null,
1173
- "technology": "Kubernetes",
1174
- "tags": ["prod"],
1175
- "project": "default",
1176
- "metadata": {},
1177
- "links": [],
1178
- "shape": "rectangle",
1179
- "color": "#2F80ED",
1180
- "children": [],
1181
- "includedInViews": [
1182
- { "id": "runtime-overview", "title": "Runtime Overview", "type": "deployment" }
1183
- ],
1184
- "instanceof": { "id": "shop.frontend", "title": "Frontend", "kind": "component" },
1185
- "sourceLocation": {
1186
- "path": "/abs/path/project/model.c4",
1187
- "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
1188
- }
1189
- }
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:`
1191
- Read detailed information about a LikeC4 element.
1192
-
1193
- Request:
1194
- - id: string — element id (FQN)
1195
- - project: string (optional) — project id. Defaults to "default" if omitted.
1196
-
1197
- Response (JSON object):
1198
- - id: string — element id (FQN)
1199
- - name: string — element name
1200
- - kind: string — element kind
1201
- - title: string — human-readable title
1202
- - description: string|null — optional description
1203
- - technology: string|null — optional technology
1204
- - tags: string[] — assigned tags
1205
- - project: string — project id this element belongs to
1206
- - metadata: Record<string, string> — element metadata
1207
- - links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this element
1208
- - shape: string — rendered shape
1209
- - color: string — rendered color
1210
- - children: string[] — ids (FQNs) of direct child elements
1211
- - defaultView: string|null — default view name if set
1212
- - includedInViews: View[] — views that include this element
1213
- - relationships: object — relationships of this element (direct and indirect)
1214
- - incoming: Array<{ source: { id: string, title: string, kind: string }, kind: string|null, target: string, title: string|null, description: string|null, technology: string|null, tags: string[] }>
1215
- - outgoing: Array<{ source: string, target: { id: string, title: string, kind: string }, kind: string|null, title: string|null, description: string|null, technology: string|null, tags: string[] }>
1216
- - deployedInstances: string[] — deployed instance ids (Deployment FQNs)
1217
- - sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
1218
-
1219
- View (object) fields:
1220
- - id: string — view identifier
1221
- - title: string — view title
1222
- - type: "element" | "deployment" | "dynamic"
1223
-
1224
- Notes:
1225
- - Read-only, idempotent, no side effects.
1226
- - Safe to call repeatedly.
1227
-
1228
- Example response:
1229
- {
1230
- "id": "shop.frontend",
1231
- "name": "frontend",
1232
- "kind": "container",
1233
- "title": "Frontend",
1234
- "description": "User-facing web app",
1235
- "technology": "React",
1236
- "tags": ["public"],
1237
- "project": "default",
1238
- "metadata": { "owner": "web" },
1239
- "links": [
1240
- {
1241
- "title": "Documentation",
1242
- "url": "https://docs.example.com/frontend",
1243
- "relative": null
1244
- }
1245
- ],
1246
- "shape": "rounded-rectangle",
1247
- "color": "#2F80ED",
1248
- "children": ["shop.frontend.auth"],
1249
- "defaultView": "frontend-overview",
1250
- "includedInViews": [
1251
- {
1252
- "id": "frontend-overview",
1253
- "title": "Frontend Overview",
1254
- "type": "element"
1255
- }
1256
- ],
1257
- "relationships": {
1258
- "incoming": [
1259
- {
1260
- "source": { "id": "shop.api", "title": "API", "kind": "container" },
1261
- "kind": "uses",
1262
- "target": "shop.frontend",
1263
- "title": "Calls",
1264
- "description": null,
1265
- "technology": "HTTPS",
1266
- "tags": []
1267
- }
1268
- ],
1269
- "outgoing": []
1270
- },
1271
- "deployedInstances": ["k8s.cluster.frontend"],
1272
- "sourceLocation": {
1273
- "path": "/abs/path/project/model.c4",
1274
- "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
1275
- }
1276
- }
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:`
1278
- Request:
1279
- - project: string (optional) — project id. Defaults to "default" if omitted.
1280
-
1281
- Response (JSON object):
1282
- - title: string — human-readable project title
1283
- - folder: string — absolute path to the project root
1284
- - sources: string[] — absolute file paths of model documents
1285
- - config: object — project configuration
1286
- - name: string — project identifier
1287
- - title?: string — human-readable title
1288
- - contactPerson?: string — maintainer contact
1289
- - metadata?: object — custom project metadata as key-value pairs
1290
- - extends?: string | string[] — style inheritance paths
1291
- - exclude?: string[] — file exclusion patterns
1292
- - include?: object — include configuration (paths, maxDepth, fileThreshold)
1293
- - manualLayouts?: object — manual layouts config (outDir)
1294
- - styles?: object — simplified styles (hasTheme, hasDefaults, hasCustomCss)
1295
- - specification: object
1296
- - elementKinds: string[] — all element kinds
1297
- - relationshipKinds: string[] — all relationship kinds
1298
- - deploymentKinds: string[] — all deployment kinds
1299
- - tags: string[] — all tags
1300
- - metadataKeys: string[] — used metadata keys
1301
- - elements: Element[] — list of elements
1302
- - deployments: Deployment[] — list of deployment entities
1303
- - views: View[] — list of views defined in the model
1304
-
1305
- Element (object) fields:
1306
- - id: string — element id (FQN)
1307
- - kind: string — element kind
1308
- - title: string — element title
1309
- - tags: string[] — element tags
1310
-
1311
- Deployment (object) fields:
1312
- - type = "deployment-node": { id: string, kind: string, title: string, tags: string[] }
1313
- - type = "deployed-instance": { id: string, title: string, tags: string[], referencedElementId: string }
1314
-
1315
- View (object) fields:
1316
- - id: string — view identifier
1317
- - title: string — view title
1318
- - type: "element" | "deployment" | "dynamic"
1319
-
1320
- Notes:
1321
- - Read-only, idempotent, no side effects.
1322
- - Safe to call repeatedly.
1323
-
1324
- Example response:
1325
- {
1326
- "title": "Cloud Boutique",
1327
- "folder": "/abs/path/to/workspace/examples/cloud-system",
1328
- "sources": [
1329
- "/abs/path/to/workspace/examples/cloud-system/model.c4"
1330
- ],
1331
- "config": {
1332
- "name": "cloud-boutique",
1333
- "title": "Cloud Boutique",
1334
- "contactPerson": "admin@example.com"
1335
- },
1336
- "specification": {
1337
- "elementKinds": ["system", "container", "component"],
1338
- "relationshipKinds": ["uses", "depends-on"],
1339
- "deploymentKinds": ["node", "cluster"],
1340
- "tags": ["public", "internal"],
1341
- "metadataKeys": ["owner", "tier"]
1342
- },
1343
- "elements": [
1344
- {
1345
- "id": "shop.frontend",
1346
- "kind": "component",
1347
- "title": "Frontend",
1348
- "tags": ["public"]
1349
- }
1350
- ],
1351
- "deployments": [
1352
- {
1353
- "type": "deployment-node",
1354
- "id": "k8s.shop.frontend",
1355
- "kind": "cluster",
1356
- "title": "Frontend",
1357
- "tags": []
1358
- }
1359
- ],
1360
- "views": [
1361
- {
1362
- "id": "system-overview",
1363
- "title": "System Overview",
1364
- "type": "element"
1365
- }
1366
- ]
1367
- }
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:`
1369
- Read detailed information about a LikeC4 view.
1370
-
1371
- Request:
1372
- - viewId: string — view id (name)
1373
- - project: string (optional) — project id. Defaults to "default" if omitted.
1374
-
1375
- Response (JSON object):
1376
- - id: string — view id
1377
- - type: "element" | "deployment" | "dynamic" — view type
1378
- - title: string — view title (falls back to id if not set)
1379
- - description: string|null — optional description
1380
- - tags: string[] — view tags
1381
- - project: string — project id this view belongs to
1382
- - nodes: Node[] — nodes included in the view
1383
- - edges: Edge[] — relationships between nodes
1384
- - sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
1385
-
1386
- Node (discriminated union by "type"):
1387
- - type = "element": { id: string, elementId: string, kind: string, title: string, description: string|null, technology: string|null, children: string[], shape: string, color: string, tags: string[] }
1388
- - type = "deployment-node": { id: string, deploymentId: string, kind: string, title: string, description: string|null, technology: string|null, children: string[], shape: string, color: string, tags: string[] }
1389
- - type = "deployed-instance": { id: string, deploymentId: string, title: string, description: string|null, technology: string|null, referencedElement: { id: string, kind: string, title: string }, shape: string, color: string, tags: string[] }
1390
-
1391
- Edge object:
1392
- - { source: string, target: string, label: string|null, description: string|null, technology: string|null, tags: string[] }
1393
-
1394
- Notes:
1395
- - Read-only, idempotent, no side effects.
1396
-
1397
- Example response:
1398
- {
1399
- "id": "system-overview",
1400
- "type": "element",
1401
- "title": "System Overview",
1402
- "description": null,
1403
- "tags": [],
1404
- "project": "default",
1405
- "nodes": [
1406
- { "type": "logical", "id": "n1", "elementId": "shop.frontend", "kind": "container", "title": "Frontend", "description": null, "technology": "React", "children": [], "shape": "rounded-rectangle", "color": "#2F80ED", "tags": [] }
1407
- ],
1408
- "edges": [
1409
- { "source": "n1", "target": "n2", "label": "calls", "description": null, "technology": "HTTPS", "tags": [] }
1410
- ],
1411
- "sourceLocation": {
1412
- "path": "/abs/path/project/model.c4",
1413
- "range": { "start": { "line": 10, "character": 0 }, "end": { "line": 30, "character": 0 } }
1414
- }
1415
- }
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:`
1417
- Search LikeC4 elements and deployment nodes across all projects.
1418
-
1419
- Query syntax (case-insensitive):
1420
- - kind:<value> filters by kind
1421
- - shape:<value> filters by shape
1422
- - meta:<key> filters by having metadata with the given key
1423
- - #<value> matches assigned tags
1424
- - <value> matches id (FQN) or title
1425
-
1426
- Request:
1427
- - search: string — at least 2 characters
1428
-
1429
- Response (JSON object):
1430
- - total: number - total number of results
1431
- - found: Result[] - returns top 20 results
1432
-
1433
- Result (discriminated union by "type"):
1434
- - type = "element": { id: string, name: string, kind: string, title: string, technology: string|null, shape: string, project: string, includedInViews: View[], tags: string[], metadata: Record<string, string> }
1435
- - type = "deployment-node": { id: string, name: string, kind: string, title: string, technology: string|null, shape: string, project: string, includedInViews: View[], tags: string[], metadata: Record<string, string> }
1436
-
1437
- View (object) fields:
1438
- - id: string — view identifier
1439
- - title: string — view title
1440
- - type: "element" | "deployment" | "dynamic"
1441
-
1442
- Notes:
1443
- - Read-only, idempotent.
1444
- - Use results as input to other tools (e.g., read-element, read-view).
1445
-
1446
- Example response:
1447
- {
1448
- "total": 1,
1449
- "found": [
1450
- {
1451
- "type": "logical",
1452
- "project": "default",
1453
- "id": "shop.frontend",
1454
- "name": "frontend",
1455
- "kind": "container",
1456
- "title": "Frontend",
1457
- "technology": "React",
1458
- "shape": "rectangle",
1459
- "includedInViews": [
1460
- {
1461
- "id": "system-overview",
1462
- "title": "System Overview",
1463
- "type": "element"
1464
- }
1465
- ],
1466
- "tags": ["public"],
1467
- "metadata": {}
1468
- }
1469
- ]
1470
- }
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:`
1472
- Get a compact, table-friendly summary of all descendants of a parent element.
1473
- Returns each descendant with its depth, metadata, tags, and relationship counts in a single call.
1474
- Much more efficient than calling read-element for each descendant individually.
1475
-
1476
- Request:
1477
- - elementId: string — parent element id (FQN) whose descendants to summarize
1478
- - maxDepth: number (optional, default: 10, max: 20) — maximum depth of descendants to include
1479
- - metadataKeys: string[] (optional) — if provided, only include these metadata keys in the response (reduces response size)
1480
- - project: string (optional) — project id. Defaults to "default" if omitted.
1481
-
1482
- Response (JSON object):
1483
- - root: object — the root element summary
1484
- - id: string — element id
1485
- - kind: string — element kind
1486
- - title: string — element title
1487
- - childCount: number — number of direct children
1488
- - descendants: Array of descendant summaries, each with:
1489
- - id: string — element id (FQN)
1490
- - name: string — element name
1491
- - kind: string — element kind
1492
- - title: string — human-readable title
1493
- - depth: number — depth relative to root (1 = direct child)
1494
- - tags: string[] — assigned tags
1495
- - metadata: Record<string, string | string[]> — element metadata (filtered by metadataKeys if provided)
1496
- - childCount: number — number of direct children
1497
- - incomingCount: number — number of incoming relationships
1498
- - outgoingCount: number — number of outgoing relationships
1499
- - totalDescendants: number — total number of descendants (may differ from array length if truncated)
1500
- - truncated: boolean — true if results were truncated due to exceeding the 200-result limit
1501
- - truncatedByDepth: boolean — true if deeper descendants exist beyond maxDepth
1502
-
1503
- Notes:
1504
- - Read-only, idempotent, no side effects.
1505
- - Safe to call repeatedly.
1506
- - Limited to 200 descendants in the response.
1507
- - Use metadataKeys to reduce response size when you only need specific metadata.
1508
- - Descendants are returned in breadth-first order (closest to root first).
1509
- - depth=1 means direct child, depth=2 means grandchild, etc.
1510
-
1511
- Example response:
1512
- {
1513
- "root": {
1514
- "id": "top.planner",
1515
- "kind": "subsystem",
1516
- "title": "Planner Subsystem",
1517
- "childCount": 5
1518
- },
1519
- "descendants": [
1520
- {
1521
- "id": "top.planner.nodeA",
1522
- "name": "nodeA",
1523
- "kind": "cgf-node",
1524
- "title": "nodeA :dwNodeTypeA",
1525
- "depth": 1,
1526
- "tags": ["is_in_dag", "target_asil_qm"],
1527
- "metadata": { "target_asil": "QM", "safety_info_unit_asil": "QM" },
1528
- "childCount": 0,
1529
- "incomingCount": 3,
1530
- "outgoingCount": 2
1531
- }
1532
- ],
1533
- "totalDescendants": 5,
1534
- "truncated": false,
1535
- "truncatedByDepth": false
1536
- }
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.
428
+ `+n}}]}},O.object({content:O.object({type:O.literal(`text`),text:O.string()})}));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 Id=Ad.extend({description:O.string().nullable().describe(`Element description`),technology:O.string().nullable().describe(`Element technology`),shape:O.string().describe(`Rendered shape`),color:O.string().describe(`Rendered color`),children:O.array(O.string()).describe(`Direct child element ids`),incomingCount:O.number().describe(`Number of incoming relationships`),outgoingCount:O.number().describe(`Number of outgoing relationships`),links:Md,sourceLocation:jd}),Ld=likec4Tool({name:`batch-read-elements`,description:`Read summaries of up to 50 elements in one call: properties, metadata, children, relationship counts, the views that include them, links and source location. Ids not found are listed in notFound instead of failing the call. Use read-element only when you also need relationships, deployedInstances, defaultView or project.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:O.array(O.string()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:Q},outputSchema:{elements:O.array(Id),notFound:O.array(O.string()).describe(`Element ids that were not found`)}})(async(e,t)=>{A(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);t?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})}):s.push(e)}return{elements:a,notFound:s}}),Rd=O.object({id:O.string(),kind:O.string(),title:O.string(),description:O.string().nullable(),technology:O.string().nullable(),shape:O.string(),color:O.string()}),zd=O.object({element1:Rd,element2:Rd,propertyDiffs:O.array(O.object({property:O.string().describe(`Property name`),element1Value:O.string().nullable().describe(`Value in element1`),element2Value:O.string().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:O.object({onlyInElement1:O.array(O.string()).describe(`Tags present only in element1`),onlyInElement2:O.array(O.string()).describe(`Tags present only in element2`),common:O.array(O.string()).describe(`Tags present in both elements`)}),metadata:O.object({onlyInElement1:O.record(O.string(),O.union([O.string(),O.array(O.string())])).describe(`Metadata keys only in element1`),onlyInElement2:O.record(O.string(),O.union([O.string(),O.array(O.string())])).describe(`Metadata keys only in element2`),different:O.array(O.object({key:O.string(),element1Value:O.union([O.string(),O.array(O.string())]),element2Value:O.union([O.string(),O.array(O.string())])})).describe(`Metadata keys present in both but with different values`),common:O.record(O.string(),O.union([O.string(),O.array(O.string())])).describe(`Metadata keys with identical values in both`)}),relationships:O.object({incomingOnlyElement1:O.number().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:O.number().describe(`Count of unique source elements sending to element2 only`),incomingShared:O.number().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:O.number().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:O.number().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:O.number().describe(`Count of unique target elements receiving from both`)})}),Bd=likec4Tool({name:`element-diff`,description:`Compare two elements of the same project: properties that differ, tags and metadata on each side or shared, and incoming and outgoing relationship counts on each side or shared. Useful for seeing why two similar elements differ.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:O.string().describe(`First element id (FQN)`),element2Id:O.string().describe(`Second element id (FQN)`),project:Q},outputSchema:zd.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);A(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);A(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=/* @__PURE__ */ new Set([...Object.keys(h),...Object.keys(g)]),y={},b={},x=[],S={};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)?S[e]=t:x.push({key:e,element1Value:t,element2Value:n}))}let ee=new Set([...i.incoming()].map(e=>e.source.id)),te=new Set([...a.incoming()].map(e=>e.source.id)),ne=new Set([...i.outgoing()].map(e=>e.target.id)),re=new Set([...a.outgoing()].map(e=>e.target.id)),ie=0,ae=0,oe=0;for(let e of ee)te.has(e)?ie++:ae++;for(let e of te)ee.has(e)||oe++;let se=0,ce=0,le=0;for(let e of ne)re.has(e)?se++:ce++;for(let e of re)ne.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:x,common:S},relationships:{incomingOnlyElement1:ae,incomingOnlyElement2:oe,incomingShared:ie,outgoingOnlyElement1:ce,outgoingOnlyElement2:le,outgoingShared:se}}}),Vd=likec4Tool({name:`find-relationship-paths`,description:`Find chains of relationships from a source element to a target element, shortest first, up to maxDepth hops and at most 100 paths. Follows direct relationships only, unless includeIndirect adds implied relationships through nested elements. Source and target must differ; no connection returns an empty list.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:O.string().describe(`Source element FQN`),targetId:O.string().describe(`Target element FQN`),maxDepth:O.number().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:O.boolean().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:Q},outputSchema:{paths:O.array(O.object({length:O.number().describe(`Number of hops in the path`),steps:O.array(O.object({source:O.string().describe(`Source element FQN`),target:O.string().describe(`Target element FQN`),relationship:O.object({kind:O.string().nullable().describe(`Relationship kind`),title:O.string().nullable().describe(`Relationship title`),description:O.string().nullable().describe(`Relationship description`),technology:O.string().nullable().describe(`Relationship technology`),tags:O.array(O.string()).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);A(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);A(a,`Target element "${t.targetId}" not found in project "${n}"`),A(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:/* @__PURE__ */ 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:/* @__PURE__ */ new Set([...e.visited,t])})}}return u.sort((e,t)=>e.length-t.length),{paths:u}}),Hd=O.object({id:O.string(),title:O.string(),kind:O.string()}),Ud=O.object({type:O.enum([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:Hd,target:Hd,kind:O.string().nullable().describe(`Relationship kind`),title:O.string().nullable().describe(`Relationship title`),description:O.string().nullable().describe(`Relationship description`),technology:O.string().nullable().describe(`Relationship technology`),tags:O.array(O.string()).describe(`Relationship tags`),includedInViews:Nd.describe(`Views that include this relationship`),sourceLocation:jd}),Wd=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`Find the relationships between two elements: direct ones between them, and indirect ones through their nested elements. Each comes with kind, title, technology, tags, the views it appears in and source location. Result order is not guaranteed. For multi-hop chains, use find-relationship-paths.`,inputSchema:{element1:O.string().describe(`Element ID (FQN)`),element2:O.string().describe(`Element ID (FQN)`),project:Q},outputSchema:{found:O.array(Ud)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(jt(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);At(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);At(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=zt.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}}),Gd=likec4Tool({name:`list-projects`,description:`List the LikeC4 projects in the workspace. Pass a project's id as the "project" argument of other tools.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:O.array(O.object({id:O.string(),title:O.string(),folder:O.string(),sources:O.array(O.string())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))})),Kd=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=Kd.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(E(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(`
429
+ `)}function previewViewTool(e){return K3(e,`preview-view`,{title:`Preview View`,description:'Renders a draft view from DSL against an existing project\'s real elements, without saving anything. The DSL must be a single element view, `view <id> ... { ... }`, with a new id: an existing id is rejected (use "render-view" for saved views), and a dynamic or deployment view fails with a generic "could not find a `view <id>`" error. Custom theme and style extensions are not applied. Use it to iterate on a view before creating it for real.',inputSchema:mcpToolSchema({dsl:O.string().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:Q,fullModel:O.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`)}),outputSchema:mcpToolSchema({id:O.string(),title:O.string(),project:O.string(),view:O.record(O.string(),O.unknown()),model:O.record(O.string(),O.unknown())}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:Pd}}},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=`${bn()}.c4`;s[c]=wrapAsViewsBlock(e.dsl);let l=t.a(await y(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(St(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 qd=O.enum([`exact`,`contains`,`exists`]),Jd=likec4Tool({name:`query-by-metadata`,description:`Find elements and deployment nodes by metadata. matchMode "exact" (default) compares the value case-sensitively, "contains" matches a substring case-insensitively, and "exists" matches any element with the key and ignores value. An array value matches if any item matches. At most 50 results.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:O.string().describe(`Metadata key to filter by`),value:O.string().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:qd.optional().default(`exact`).describe(`Matching mode`),project:Q},outputSchema:{results:O.array(Ad.extend({matchedValue:O.string().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}}),Yd=likec4Tool({name:`query-by-tag-pattern`,description:`Find elements whose tags match a pattern, for structured tag naming such as "team_*". matchMode is "prefix" (default), "contains" or "suffix", case-insensitive. Returns the matching tags per element and every distinct matching tag. At most 50 results. For exact tags with boolean logic, use query-by-tags.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:O.string().min(1).describe(`Tag pattern to match`),matchMode:O.enum([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:Q},outputSchema:{results:O.array(Ad.extend({matchedTags:O.array(O.string()).describe(`Tags that matched the pattern`)})),truncated:O.boolean().describe(`True if results were truncated`),matchedTagValues:O.array(O.string()).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=/* @__PURE__ */ 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(!Pt(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))}}),Xd=likec4Tool({name:`query-by-tags`,description:`Find elements and deployment nodes by tags with boolean logic: allOf (AND), anyOf (OR) and noneOf (NOT), combined with AND. At least one condition is required, and tags are case-sensitive. At most 50 results. For partial tag names, use query-by-tag-pattern.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:O.array(O.string()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:O.array(O.string()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:O.array(O.string()).optional().describe(`Element must have NONE of these tags (NOT)`),project:Q},outputSchema:{results:O.array(Ad),truncated:O.boolean().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{A(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}Pt(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),Zd=O.enum([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),Qd=likec4Tool({name:`query-graph`,description:`One-step graph query around an element. Hierarchy: ancestors (up to the root), descendants (recursive), siblings, children, parent (empty for a root element); includeIndirect is ignored for these. Relationships: incomers and outgoers, single hop; includeIndirect (default true) adds relationships of nested children. For recursive traversal, use query-incomers-graph or query-outgoers-graph. At most 100 results.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:O.string().describe(`Element id (FQN) to query`),queryType:Zd.describe(`Type of graph query`),includeIndirect:O.boolean().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:Q},outputSchema:{results:O.array(Ad),truncated:O.boolean().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);A(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}}),$d=O.object({elementId:O.string().describe(`ID of the incoming element`),relationshipLabel:O.string().optional().describe(`Label on the relationship`),technology:O.string().optional().describe(`Technology specified on the relationship`)}),ef=likec4Tool({name:`query-incomers-graph`,description:`Recursive upstream traversal: every element that feeds into the target, directly or transitively, returned as one graph with each node's depth and incomers. Answers "what feeds into this?" in one call instead of repeated query-graph calls. Stops at maxDepth or maxNodes; if truncated is true, raise maxNodes or lower maxDepth.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:O.string().describe(`Target element id (FQN) to query incomers for`),includeIndirect:O.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:O.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:O.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Q},outputSchema:{target:O.string().describe(`Target element id`),totalNodes:O.number().describe(`Total number of nodes in the graph`),maxDepth:O.number().describe(`Maximum depth reached`),truncated:O.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:O.record(O.string(),Ad.extend({incomers:O.array($d).describe(`Incoming relationships with details`),depth:O.number().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);A(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}}),tf=O.object({elementId:O.string().describe(`ID of the outgoing element`),relationshipLabel:O.string().optional().describe(`Label on the relationship`),technology:O.string().optional().describe(`Technology specified on the relationship`)}),nf=likec4Tool({name:`query-outgoers-graph`,description:`Recursive downstream traversal: every element that consumes output from the target, directly or transitively, returned as one graph with each node's depth and outgoers. Answers "what depends on this?" (blast radius) in one call instead of repeated query-graph calls. Stops at maxDepth or maxNodes; if truncated is true, raise maxNodes or lower maxDepth.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:O.string().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:O.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:O.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:O.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Q},outputSchema:{target:O.string().describe(`Target element id`),totalNodes:O.number().describe(`Total number of nodes in the graph`),maxDepth:O.number().describe(`Maximum depth reached`),truncated:O.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:O.record(O.string(),Ad.extend({outgoers:O.array(tf).describe(`Outgoing relationships with details`),depth:O.number().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);A(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}}),rf=likec4Tool({name:`read-deployment`,description:`Read one deployment node or deployed instance: kind, tags, metadata, links, children (empty for an instance), the views that include it, the element a deployed instance instantiates, and source location.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:O.string().describe(`Deployment id (FQN)`),project:Q},outputSchema:{type:O.enum([`deployment-node`,`deployed-instance`]),id:O.string().describe(`Deployment id (FQN)`),kind:O.string().describe(`Deployment node kind, or element kind for deployed instances`),name:O.string(),title:O.string(),description:O.string().nullable(),technology:O.string().nullable(),tags:O.array(O.string()),project:O.string(),metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])),links:Md.describe(`External links associated with this deployment entity`),shape:O.string(),color:O.string(),children:O.array(O.string()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:Nd.describe(`Views that include this deployment node`),instanceof:O.object({id:O.string().describe(`Element ID (FQN)`),title:O.string(),kind:O.string()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:jd}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);A(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})}}),af=likec4Tool({name:`read-element`,description:`Read one element in full: properties, metadata, links, children, the views that include it, its direct and indirect incoming and outgoing relationships, deployed instances and source location. For many elements, use batch-read-elements.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:O.string().describe(`Element id (FQN)`),project:Q},outputSchema:{id:O.string().describe(`Element id (FQN)`),kind:O.string().describe(`Element kind`),name:O.string().describe(`Element name`),title:O.string(),description:O.string().nullable(),technology:O.string().nullable(),tags:O.array(O.string()),project:O.string(),metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])),links:Md,shape:O.string(),color:O.string(),children:O.array(O.string()).describe(`Children of this element (Array of FQNs)`),defaultView:O.string().nullable().describe(`Name of the default view of this element`),includedInViews:Nd.describe(`Views that include this element`),relationships:O.object({incoming:O.array(O.object({source:O.object({id:O.string(),title:O.string(),kind:O.string()}).describe(`Source element of this relationship`),kind:O.string().nullable().describe(`Relationship kind`),target:O.string().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:O.string().nullable().describe(`Relationship title`),description:O.string().nullable().describe(`Relationship description`),technology:O.string().nullable().describe(`Relationship technology`),tags:O.array(O.string()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:O.array(O.object({source:O.string().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:O.object({id:O.string(),title:O.string(),kind:O.string()}).describe(`Target element of this relationship`),kind:O.string().nullable().describe(`Relationship kind`),title:O.string().nullable().describe(`Relationship title`),description:O.string().nullable().describe(`Relationship description`),technology:O.string().nullable().describe(`Relationship technology`),tags:O.array(O.string()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:O.array(O.string()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:jd}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.id);A(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})}}),of=likec4Tool({name:`read-project-summary`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read project summary`},description:`Overview of a LikeC4 project: its configuration, its specification (element, relationship and deployment kinds, tags, metadata keys), and every element, deployment entity and view with id, kind, title and tags. Use it to orient in a project before reading individual elements or views.`,inputSchema:{project:Q},outputSchema:{title:O.string(),folder:O.string(),sources:O.array(O.string()),config:kd.describe(`Project configuration`),specification:O.object({elementKinds:O.array(O.string()),relationshipKinds:O.array(O.string()),deploymentKinds:O.array(O.string()),tags:O.array(O.string()),metadataKeys:O.array(O.string())}),elements:O.array(O.object({id:O.string(),kind:O.string(),title:O.string(),tags:O.array(O.string())})).describe(`List of elements in the project`),deployments:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`deployment-node`),id:O.string().describe(`Node ID`),kind:O.string().describe(`Deployment node kind`),title:O.string().describe(`Node title`),tags:O.array(O.string())}),O.object({type:O.literal(`deployed-instance`),id:O.string().describe(`Node ID`),title:O.string().describe(`Node title`),tags:O.array(O.string()),referencedElementId:O.string().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:O.array(O.object({id:O.string(),title:O.string(),type:O.enum([`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:Ee(i.specification.elements),relationshipKinds:Ee(i.specification.relationships),deploymentKinds:Ee(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,sf=O.discriminatedUnion(`type`,[O.object({type:O.literal(`element`),id:O.string().describe(`Node ID`),elementId:O.string().describe(`Element ID (FQN)`),kind:O.string().describe(`Element kind`),title:O.string().describe(`Node title`),description:O.string().nullable(),technology:O.string().nullable(),children:O.array(O.string()).describe(`Children nodes, array of node IDs`),shape:O.string().describe(`Rendered shape`),color:O.string().describe(`Rendered color`),tags:O.array(O.string())}),O.object({type:O.literal(`deployment-node`),id:O.string().describe(`Node ID`),deploymentId:O.string().describe(`Deployment entity ID (FQN)`),kind:O.string().describe(`Deployment kind`),title:O.string().describe(`Node title`),description:O.string().nullable(),technology:O.string().nullable(),children:O.array(O.string()).describe(`Children nodes, array of node IDs`),shape:O.string().describe(`Rendered shape`),color:O.string().describe(`Rendered color`),tags:O.array(O.string())}),O.object({type:O.literal(`deployed-instance`),id:O.string().describe(`Node ID`),deploymentId:O.string().describe(`Deployment entity ID (FQN)`),title:O.string().describe(`Node title`),description:O.string().nullable(),technology:O.string().nullable(),referencedElement:O.object({id:O.string().describe(`Element ID (FQN)`),kind:O.string().describe(`Element kind`),title:O.string().describe(`Element title`)}),shape:O.string().describe(`Rendered shape`),color:O.string().describe(`Rendered color`),tags:O.array(O.string())})]),cf=likec4Tool({name:`read-view`,description:`Read a view's structure: its nodes (elements, deployment nodes or deployed instances) and the edges between them, with source location. A view without a title returns its id as the title. Use render-view to show the diagram to the user.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:O.string().describe(`View id (name)`),project:Q},outputSchema:{id:O.string(),type:O.enum([`element`,`deployment`,`dynamic`]).describe(`View type`),title:O.string(),description:O.string().nullable(),tags:O.array(O.string()),project:O.string(),nodes:O.array(sf),edges:O.array(O.object({source:O.string().describe(`Source node`),target:O.string().describe(`Target node`),label:O.string().nullable(),description:O.string().nullable(),technology:O.string().nullable(),tags:O.array(O.string())})).describe(`Edge represents relationship between nodes`),sourceLocation:jd}})(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})}}),lf=O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`element`),project:O.string().describe(`Project ID`),id:O.string().describe(`Element ID (FQN)`),name:O.string().describe(`Element name`),kind:O.string(),title:O.string(),technology:O.string().nullable(),shape:O.string(),includedInViews:Nd,metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])),tags:O.array(O.string())}),O.object({type:O.literal(`deployment-node`),project:O.string().describe(`Project ID`),id:O.string().describe(`Deployment ID (FQN)`),name:O.string().describe(`Deployment name`),kind:O.string(),title:O.string(),technology:O.string().nullable(),shape:O.string(),includedInViews:Nd,metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])),tags:O.array(O.string())})])),uf=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`Search elements and deployment nodes across all projects by id, title, kind, shape, tag or metadata key. Returns the total number of matches and the first 20. Pass the ids found to read-element or other tools.`,inputSchema:{search:O.string().min(2,`Search must be at least 2 characters long`).describe(`Case-insensitive. "kind:<value>" or "shape:<value>" matches a kind or shape exactly, "meta:<key>" elements with that metadata key, "#<value>" tags containing the value; anything else matches id (FQN) or title.`)},outputSchema:{total:O.number(),found:lf}})(async(e,t)=>{let n=e.projects(),r=[],i=t.search.toLowerCase(),predicate;i.startsWith(`kind:`)?(i=i.slice(5),Z.debug(`search by kind: {search}`,{search:i}),predicate=e=>e.kind.toLowerCase()===i):i.startsWith(`shape:`)?(i=i.slice(6),Z.debug(`search by shape: {search}`,{search:i}),predicate=e=>e.shape.toLowerCase()===i):i.startsWith(`meta:`)?(i=i.slice(5),Z.debug(`search by metadata: {search}`,{search:i}),predicate=e=>!!e.getMetadata(i)):i.startsWith(`#`)?(i=i.slice(1),Z.debug(`search by tag: {search}`,{search:i}),predicate=e=>e.tags.some(e=>e.toLowerCase().includes(i))):(Z.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 kt(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 kt(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){Z.error(`Error searching in project ${t.id}:`,{error:e})}return{total:r.length,found:r.slice(0,20)}}),df=O.object({id:O.string().describe(`Element id (FQN)`),name:O.string().describe(`Element name`),kind:O.string().describe(`Element kind`),title:O.string().describe(`Human-readable title`),depth:O.number().describe(`Depth relative to the root element (1 = direct child)`),tags:O.array(O.string()).describe(`Assigned tags`),metadata:O.record(O.string(),O.union([O.string(),O.array(O.string())])).describe(`Element metadata`),childCount:O.number().describe(`Number of direct children`),incomingCount:O.number().describe(`Number of incoming relationships`),outgoingCount:O.number().describe(`Number of outgoing relationships`)}),ff=likec4Tool({name:`subgraph-summary`,description:`Summarize all descendants of an element in one call, breadth-first, each with depth (1 = direct child), tags, metadata, and child and relationship counts. At most 200 descendants; truncated and truncatedByDepth say what was cut. Pass metadataKeys to return only those keys. Cheaper than read-element per descendant.`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:O.string().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:O.number().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:O.array(O.string()).optional().describe(`If provided, only include these metadata keys in the response`),project:Q},outputSchema:{root:O.object({id:O.string(),kind:O.string(),title:O.string(),childCount:O.number()}),descendants:O.array(df),totalDescendants:O.number().describe(`Total number of descendants found`),truncated:O.boolean().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:O.boolean().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);A(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:pd},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
1538
430
 
1539
431
  Conventions:
1540
432
  - All tools are read-only and idempotent.
@@ -1569,21 +461,21 @@ Instructions:
1569
461
  - If response returns "sourceLocation", provide link to this location in the editor
1570
462
 
1571
463
  Full documentation: https://likec4.dev/llms-full.txt
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(`
464
+ `,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{re.error(i(e))},Le(t,setMcpServerCtx,Gd,of,af,rf,cf,uf,Wd,Vd,je(Qd,ef,nf,Jd,Xd,Yd),je(Ld,Bd,ff),je(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),je(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){Z.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}Z.info(`LikeC4 MCP Server running on stdio`)}}async stop(){if(this.transport)try{Z.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 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})}};const pf=Symbol(),bufferToFormData=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),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=await e.arrayBuffer(),i=bufferToFormData(r,n.get(`Content-Type`)||``);isRawRequest(e)||(e.bodyCache.formData=i);let a=await i;return a?convertFormDataToBodyData(a,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}const 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(`.`,34);a.length>33&&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++>=1e4&&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),r=splitPath(n);return replaceGroupMarks(r,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},mf={},getPattern=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return mf[r]||(n[2]?mf[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:mf[r]=[e,n[1],!0]),mf[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,gf),_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},hf=_getQueryParam,getQueryParams=(e,t)=>_getQueryParam(e,t,!0),gf=decodeURIComponent;var 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 hf(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[pf](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};const _f={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},setDefaultContentType=(e,t)=>({"Content-Type":e,...t}),createResponseInstance=(e,t)=>new Response(e,t);var 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??=/* @__PURE__ */ 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)}}}let i=typeof t==`number`?t:t?.status??this.#r;return createResponseInstance(e,{status:i,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(`text/plain; charset=UTF-8`,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,_f.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))};const 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}},vf=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],yf=`Can not add a route since the matcher is already built.`;var UnsupportedPathError=class extends Error{};const 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)};var bf=class Hono{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...vf,`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.__COMPOSED_HANDLER=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))})}};const createNullObject=()=>Object.create(null),xf=[];function match(e,t){let n=this.buildAllMatchers(),match=((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[[],xf];let s=a.indexOf(``,1);return[r[1][s],a]});return this.match=match,match(e,t)}const Sf=`[^/]+`,Cf=`(?:|/.*)`,wf=Symbol(),Tf=/* @__PURE__ */ 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 Ef=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?[``,``,`.*`]:[``,``,Sf]:null:s===`/*`?[``,``,Cf]: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&&Tf.has(t)))throw wf;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 wf}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 wf;l=a.#n[s]=new Node}a=l}if(a.#e!==void 0)throw wf;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}`:Tf.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 Ef;#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]}};let Df=createNullObject();function buildWildcardRegExp(e){return Df[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Cf:e===`*`?`.*`:`/:${Sf}`)}$`)}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===wf?new UnsupportedPathError(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(yf);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,Df=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];s?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())]):i[t]=[n.map(([e])=>[e,createNullObject()]),xf]}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(yf);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]}};const Of=createNullObject();let kf=0;var Af=class Node{#e=[];#t=createNullObject();#n=[];#r;#i=Of;insert(e,t,n){let r=this,i=splitRoutingPath(t),a=/* @__PURE__ */ 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:++kf}})}#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=Of;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===Of?{}:{...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 Af;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 bf{constructor(e={}){super(e),this.router=e.router??new SmartRouter({routers:[new RegExpRouter,new TrieRouter]})}};const 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 cors(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})}},$=O.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:O.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),O.NEVER}).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`});O.looseObject({resource:O.string().url(),authorization_servers:O.array($).optional(),jwks_uri:O.string().url().optional(),scopes_supported:O.array(O.string()).optional(),bearer_methods_supported:O.array(O.string()).optional(),resource_signing_alg_values_supported:O.array(O.string()).optional(),resource_name:O.string().optional(),resource_documentation:O.string().optional(),resource_policy_uri:O.string().url().optional(),resource_tos_uri:O.string().url().optional(),tls_client_certificate_bound_access_tokens:O.boolean().optional(),authorization_details_types_supported:O.array(O.string()).optional(),dpop_signing_alg_values_supported:O.array(O.string()).optional(),dpop_bound_access_tokens_required:O.boolean().optional()});const jf=O.looseObject({issuer:O.string(),authorization_endpoint:$,token_endpoint:$,registration_endpoint:$.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),service_documentation:$.optional(),revocation_endpoint:$.optional(),revocation_endpoint_auth_methods_supported:O.array(O.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),introspection_endpoint:O.string().optional(),introspection_endpoint_auth_methods_supported:O.array(O.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),code_challenge_methods_supported:O.array(O.string()).optional(),client_id_metadata_document_supported:O.boolean().optional()}),Mf=O.looseObject({issuer:O.string(),authorization_endpoint:$,token_endpoint:$,userinfo_endpoint:$.optional(),jwks_uri:$,registration_endpoint:$.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),acr_values_supported:O.array(O.string()).optional(),subject_types_supported:O.array(O.string()),id_token_signing_alg_values_supported:O.array(O.string()),id_token_encryption_alg_values_supported:O.array(O.string()).optional(),id_token_encryption_enc_values_supported:O.array(O.string()).optional(),userinfo_signing_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_enc_values_supported:O.array(O.string()).optional(),request_object_signing_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_enc_values_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),display_values_supported:O.array(O.string()).optional(),claim_types_supported:O.array(O.string()).optional(),claims_supported:O.array(O.string()).optional(),service_documentation:O.string().optional(),claims_locales_supported:O.array(O.string()).optional(),ui_locales_supported:O.array(O.string()).optional(),claims_parameter_supported:O.boolean().optional(),request_parameter_supported:O.boolean().optional(),request_uri_parameter_supported:O.boolean().optional(),require_request_uri_registration:O.boolean().optional(),op_policy_uri:$.optional(),op_tos_uri:$.optional(),client_id_metadata_document_supported:O.boolean().optional()});O.object({...Mf.shape,...jf.pick({code_challenge_methods_supported:!0}).shape}),O.object({access_token:O.string(),id_token:O.string().optional(),token_type:O.string(),expires_in:O.coerce.number().optional(),scope:O.string().optional(),refresh_token:O.string().optional(),issuer:O.string().optional().catch(void 0)}).strip(),O.object({error:O.string(),error_description:O.string().optional(),error_uri:O.string().optional()});const Nf=$.optional().or(O.literal(``).transform(()=>void 0)),Pf=O.object({redirect_uris:O.array($),token_endpoint_auth_method:O.string().optional(),grant_types:O.array(O.string()).optional(),response_types:O.array(O.string()).optional(),client_name:O.string().optional(),client_uri:$.optional(),logo_uri:Nf,scope:O.string().optional(),contacts:O.array(O.string()).optional(),tos_uri:Nf,policy_uri:O.string().optional(),jwks_uri:$.optional(),jwks:O.any().optional(),software_id:O.string().optional(),software_version:O.string().optional(),software_statement:O.string().optional()}).strip(),Ff=O.object({client_id:O.string(),client_secret:O.string().optional(),client_id_issued_at:O.number().optional(),client_secret_expires_at:O.number().optional(),issuer:O.string().optional().catch(void 0)}).strip();Pf.merge(Ff),O.object({error:O.string(),error_description:O.string().optional()}).strip(),O.object({token:O.string(),token_type_hint:O.string().optional()}).strip(),globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto),O.object({client_id:O.string(),redirect_uri:O.string().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),O.object({response_type:O.literal(`code`),code_challenge:O.string(),code_challenge_method:O.literal(`S256`),scope:O.string().optional(),state:O.string().optional(),resource:O.url().optional()}),O.object({grant_type:O.string()}),O.object({code:O.string(),code_verifier:O.string(),redirect_uri:O.string().optional(),resource:O.url().optional()}),O.object({refresh_token:O.string(),scope:O.string().optional(),resource:O.url().optional()}),O.object({client_id:O.string(),client_secret:O.string().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+`
465
+ `),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,_f.Stringify,!1,{})).split(/\r\n|\r|\n/).map(e=>`data: ${e}`).join(`
1574
466
  `);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(`
1575
467
  `)+`
1576
468
 
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
469
+ `;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)}},Lf=/* @__PURE__ */ 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()}),Lf.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=/* @__PURE__ */ new Map;#u=/* @__PURE__ */ new Map;#d=/* @__PURE__ */ 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?.(/* @__PURE__ */ 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:Y.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:Y.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:Y.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=>Ac.parse(e)):[Ac.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:Y.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:Y.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:Y.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:Y.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:Y.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:Y.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:Y.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:Y.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:Y.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=/* @__PURE__ */ new Map,this.#r=/* @__PURE__ */ 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 Rf=/* @__PURE__ */ 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`]),zf=/^[!#$%&'*+\-.^_`|~\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)},Bf=/[\0\r\n]/,Vf=globalThis.Headers,materializeHeaders=(e,t=Vf)=>{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 An&&(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(!zf.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof An?void 0:this.#e.headers;if(!t||Rf.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 Bf.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(Bf.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,Vf.prototype);const newHeadersFromIncoming=e=>globalThis.Headers===Vf?new RequestHeaders(e):materializeHeaders(e.rawHeaders,globalThis.Headers),Hf=/^\/[!#$&-;=?-\[\]_a-z~]*$/,Uf=/\/\.\.?(?:[/?#]|$)/,Wf=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,buildUrl=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!Wf.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!Hf.test(n)||Uf.test(n)?new URL(r).href:r},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),Gf=global.Request;var Request$1=class extends Gf{constructor(e,t){if(typeof e==`object`&&Xf in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[sp]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[Xf]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const Kf=Symbol(`wrapBodyStream`),qf=/* @__PURE__ */ new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),isByteExactEncoding=e=>e===null||qf.has(e),Jf=Symbol(`bodyBufferedBeforeDisconnect`),Yf=Symbol(`bodyBufferedLengthBeforeDisconnect`),toBufferChunk=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),isRecoverableDisconnectedIncoming=e=>!(e instanceof An)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&isByteExactEncoding(e.readableEncoding),recordBodyBufferedBeforeDisconnect=e=>{if(e.readableDidRead||!isRecoverableDisconnectedIncoming(e))return;let t=e;t[Yf]??=e.readableLength},readBodyBufferedBeforeDisconnect=(e,t)=>{if(e.readableDidRead&&!t||!isRecoverableDisconnectedIncoming(e))return;let n=e;if(n[Jf]!==void 0)return n[Jf];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[Yf]!==void 0&&e.readableLength!==n[Yf])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[Jf]=r,r},enqueueBufferedBody=(e,t)=>{t instanceof Error?e.error(t):(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[Kf]){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||=Mn.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?Mn.toWeb(r):new ReadableStream({start(t){enqueueBufferedBody(t,e)}})}}return new Request$1(t,a)},Xf=Symbol(`getRequestCache`),Zf=Symbol(`requestCache`),Qf=Symbol(`incomingKey`),$f=Symbol(`urlKey`),ep=Symbol(`methodKey`),tp=Symbol(`headersKey`),np=Symbol(`abortControllerKey`),rp=Symbol(`getAbortController`),ip=Symbol(`abortRequest`),ap=Symbol(`bodyBuffer`),op=Symbol(`bodyReadPromise`),sp=Symbol(`bodyConsumedDirectly`),cp=Symbol(`bodyLockReader`),lp=Symbol(`abortReason`),newBodyUnusableError=()=>/* @__PURE__ */ TypeError(`Body is unusable`),rejectBodyUnusable=()=>Promise.reject(newBodyUnusableError()),up=new TextDecoder,consumeBodyDirectOnce=e=>{if(e[sp])return rejectBodyUnusable();e[sp]=!0},toArrayBuffer=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),contentType=e=>(e[tp]||=newHeadersFromIncoming(e[Qf])).get(`content-type`)||``,dp=/^[!#$%&'*+\-.^_`|~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(!dp.test(e))return/* @__PURE__ */ TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return/* @__PURE__ */ TypeError(`'${e}' HTTP method is unsupported.`)},readBodyWithFastPath=(e,t,n)=>{if(e[sp])return rejectBodyUnusable();let r=e.method;if(r===`GET`||r===`HEAD`)return e[Xf]()[t]();let i=validateDirectReadMethod(r);if(i)return Promise.reject(i);if(e[Zf]&&r!==`TRACE`)return e[Zf][t]();let a=consumeBodyDirectOnce(e);if(a)return a;let s=readRawBodyIfAvailable(e);if(s){let t=Promise.resolve(n(s,e));return e[ap]=void 0,t}return readBodyDirect(e).then(t=>{let r=n(t,e);return e[ap]=void 0,r})},readRawBodyIfAvailable=e=>{let t=e[Qf];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},normalizeAbortError=(e,t)=>{if(t.errored)return t.errored;let n=e[lp];return n===void 0?/* @__PURE__ */ Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},readBodyDirect=e=>{if(e[ap])return Promise.resolve(e[ap]);if(e[op])return e[op];let t=e[Qf];if(t.readableDidRead)return rejectBodyUnusable();let n=readBodyBufferedBeforeDisconnect(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[ap]=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[ap]=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[ap]=t,n(t)})},onError=e=>{recoverCompleteBodyAfterDisconnect(e)||finish(()=>{r(e)})},onClose=()=>{t.readableEnded?onEnd():recoverCompleteBodyAfterDisconnect()||finish(()=>{r(normalizeAbortError(e,t))})},cleanup=()=>{t.off(`data`,onData),t.off(`end`,onEnd),t.off(`error`,onError),t.off(`close`,onClose),e[op]=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[op]=r,r},fp={get method(){return this[ep]},get url(){return this[$f]},get headers(){return this[tp]||=newHeadersFromIncoming(this[Qf])},[ip](e){this[lp]===void 0&&(this[lp]=e);let t=this[np];t&&!t.signal.aborted&&t.abort(e)},[rp](){return this[np]||=new AbortController,this[lp]!==void 0&&!this[np].signal.aborted&&this[np].abort(this[lp]),this[np]},[Xf](){let e=this[rp]();if(this[Zf])return this[Zf];let t=this.method;if(this[sp]&&t!==`GET`&&t!==`HEAD`){this[ap]=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[$f],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[Zf]=r}return this[Zf]=newRequestFromIncoming(this.method,this[$f],this.headers,this[Qf],e)},get body(){if(!this[sp])return this[Xf]().body;let e=this[Xf]();return!this[cp]&&e.body&&(this[cp]=e.body.getReader()),e.body},get bodyUsed(){return this[sp]?!0:this[Zf]?this[Zf].bodyUsed:!1}};Object.defineProperty(fp,"signal",{get(){return this[rp]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(fp,e,{get(){return this[Xf]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(fp,e,{value:function(){if(this[sp]){if(e===`clone`)throw newBodyUnusableError();return rejectBodyUnusable()}return this[Xf]()[e]()}})}),Object.defineProperty(fp,"text",{value:function(){return readBodyWithFastPath(this,`text`,e=>up.decode(e))}}),Object.defineProperty(fp,"arrayBuffer",{value:function(){return readBodyWithFastPath(this,`arrayBuffer`,e=>toArrayBuffer(e))}}),Object.defineProperty(fp,"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(fp,"json",{value:function(){return this[sp]?rejectBodyUnusable():this.text().then(JSON.parse)}}),Object.defineProperty(fp,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[Zf]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(fp,Request$1.prototype);const newRequest=(e,t)=>{let n=Object.create(fp);n[Qf]=e,n[ep]=normalizeIncomingMethod(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof An)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{n[$f]=new URL(r).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof An?e.authority:e.headers.host)||t;if(!i)throw new RequestError(`Missing host header`);let a;if(e instanceof An){if(a=e.scheme,a!==`http`&&a!==`https`)throw new RequestError(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[$f]=buildUrl(a,i,r)}catch(e){throw e instanceof RequestError?e:new RequestError(`Invalid URL`,{cause:e})}return n},pp=`text/plain; charset=UTF-8`,mp=Symbol(`responseCache`),hp=Symbol(`getResponseCache`),gp=Symbol(`cache`),_p=global.Response;var vp=class Response$1{#e;#t;[hp](){let e=this[gp],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[gp],this[mp]||=new _p(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 _p){let e=t[mp];if(e){this.#t=e,this[hp]();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[gp]=[t?.status||200,e??null,n||t?.headers])}get headers(){let e=this[gp];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":pp}))),e[2]):this[hp]().headers}get status(){return this[gp]?.[0]??this[hp]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(vp.prototype,e,{get(){return this[hp]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(vp.prototype,e,{value:function(){return this[hp]()[e]()}})}),Object.defineProperty(vp.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[mp]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(vp,_p),Object.setPrototypeOf(vp.prototype,_p.prototype);const yp=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,parseRedirectUrl=e=>e instanceof URL?e.href:yp.test(e)?e:new URL(e).href,bp=/* @__PURE__ */ new Set([301,302,303,307,308]);Object.defineProperty(vp,"redirect",{value:function redirect(e,t=302){if(!bp.has(t))throw RangeError(`Invalid status code`);return new vp(null,{status:t,headers:{location:parseRedirectUrl(e)}})},writable:!0,configurable:!0}),Object.defineProperty(vp,"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 vp(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.`);if(!t.destroyed)return 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},xp=Symbol(`outgoingEnded`),Sp=Symbol(`incomingDraining`),drainIncoming=e=>{let t=e;if(e.destroyed||t[Sp])return;if(t[Sp]=!0,e instanceof An){try{e.stream?.close?.(jn.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[ip](t.errored.toString())):n.writableFinished||(recordBodyBufferedBeforeDisconnect(t),e[ip](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{drainIncoming(t)})})},isImmediateCacheableResponse=e=>{if(!(gp in e))return!1;let t=e[gp][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 instanceof On&&(t._contentLength=null),t.writeHead(500,{"Content-Type":`text/plain`})),t.end(`Error: ${n.message}`),t.destroy(n))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},trySetContentLength=(e,t,n)=>{let r=e;return r._contentLength===null&&r._hasBody&&r.useChunkedEncodingByDefault&&!r._removedContLen&&t>=200&&t!==204&&t!==304&&!e.hasHeader(`content-length`)&&!e.hasHeader(`transfer-encoding`)&&!e.hasHeader(`trailer`)?(r._contentLength=n,!0):!1},writeDefaultHeaders=(e,t,n)=>{trySetContentLength(e,t,n)?e.writeHead(t,{"Content-Type":pp}):e.writeHead(t,{"Content-Type":pp,"Content-Length":n})},responseViaCache=async(e,t)=>{let[n,r,i]=e[gp];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(writeDefaultHeaders(t,n,Buffer.byteLength(r)),t.end(r)):r instanceof Uint8Array?(writeDefaultHeaders(t,n,r.byteLength),t.end(r)):r instanceof Blob?(writeDefaultHeaders(t,n,r.size),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":pp}),flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[xp]?.();return}let a=!1,s=!1,c=!0;if(i instanceof Headers)a=i.has(`content-length`),i=buildOutgoingHttpHeaders(i,r===null?void 0:pp);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=buildOutgoingHttpHeaders(e,r===null?void 0:pp)}else{s=!0;for(let e in i){if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}(e.length===17&&e.toLowerCase()===`transfer-encoding`||e.length===7&&e.toLowerCase()===`trailer`)&&(c=!1)}}if(!a){let e;typeof r==`string`?e=Buffer.byteLength(r):r instanceof Uint8Array?e=r.byteLength:r instanceof Blob&&(e=r.size),e!==void 0&&(!s||!c||!trySetContentLength(t,n,e))&&(s&&(i={...i}),i[`Content-Length`]=e)}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[xp]?.()},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(gp in e)return responseViaCache(e,t);let r=buildOutgoingHttpHeaders(e.headers,e.body===null?void 0:pp);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[xp]?.()},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:vp})),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[Kf]=!0,r instanceof An&&(i[xp]=()=>{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 Cp=Symbol(`CONNECTION_SYMBOL_KEY`),wp=Symbol(`WAIT_FOR_WEBSOCKET_SYMBOL`),Tp=/* @__PURE__ */ 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)=>{Tp.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()} ${Dn[t]??``}\r\n${r.join(`\r
1578
470
  `)}\r\n\r
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:`)}
1580
- ${S.green(`$0 mcp`)}
1581
- ${S.gray(`Start MCP with default stdio transport`)}
1582
- ${S.green(`$0 mcp --http ./src`)}
1583
- ${S.gray(`Start MCP with streamable http transport on port 33335 at ./src folder`)}
1584
- ${S.green(`$0 mcp -p 1234`)}
1585
- ${S.gray(`Start MCP with streamable http transport on port 1234`)}
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:`),`
471
+ `)},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=/* @__PURE__ */ 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(/* @__PURE__ */ 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,[wp]: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[Cp]){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||kn)(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=>(Z.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)=>(Z.error(i(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()}Z.info(`Starting MCP server on port {port}`,{port:e}),this._port=e,this.server=await startServer({factory:()=>createMCPServer(this.services),port:e}),Z.info(`MCP server ready at http://0.0.0.0:{port}/mcp`,{port:e})}stop(){let e=this.server;return e?(Z.info(`Stopping MCP server`),this.server=void 0,setMcpServerCtx(void 0),new Promise(t=>{e.close(e=>{e?Z.error(`Failed to stop MCP server`,{err:e}):Z.info(`MCP server stopped`),t()})})):(Z.info(`MCP server is not running, nothing to stop`),Promise.resolve())}};async function initLikeC4MCP(e){let t=ie(e,{workspacePath:`.`,mcp:`stdio`,graphviz:`wasm`,watch:!0,throwIfInvalid:!1,configureLogger:!0});t.configureLogger&&(f({useStdErr:t.mcp===`stdio`,colors:m.isColorSupported&&t.mcp!==`stdio`,logLevel:Zt?`debug`:`info`}),process.on(`uncaughtException`,e=>{Z.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{Z.error(`unhandledRejection`,{err:e})}));let n=D(t.workspacePath);Z.info`Loading LikeC4 from workspace: ${n}`;let r=await S(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=>{Z.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){Z.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(`${m.bold(`Usage:`)} $0 mcp [path]`).positional(`path`,W).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`,G).option(`log-level`,Cs).option(`verbose`,ws).showHidden().epilog(`${m.bold(`Examples:`)}
472
+ ${m.green(`$0 mcp`)}
473
+ ${m.gray(`Start MCP with default stdio transport`)}
474
+ ${m.green(`$0 mcp --http ./src`)}
475
+ ${m.gray(`Start MCP with streamable http transport on port 33335 at ./src folder`)}
476
+ ${m.green(`$0 mcp -p 1234`)}
477
+ ${m.gray(`Start MCP with streamable http transport on port 1234`)}
478
+ `),handler:async e=>{e.http||e.port?(f({colors:m.isColorSupported,logLevel:e.verbose?Ts:e.logLevel}),await startHttpMcp(e.path,e.useDot,e.port)):(f({useStdErr:!0,colors:!1,logLevel:e.verbose?Ts: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([m.green(`LikeC4 MCP served at:`),`
1587
479
  {
1588
480
  "mcpServers": {
1589
481
  "likec4": {
@@ -1592,41 +484,41 @@ ${S.green(`$0 mcp -p 1234`)}
1592
484
  }
1593
485
  }
1594
486
 
1595
- ${S.dim(`Documentation:`)}
1596
- ${S.underline(`https://likec4.dev/tooling/mcp/#using-extension`)}
487
+ ${m.dim(`Documentation:`)}
488
+ ${m.underline(`https://likec4.dev/tooling/mcp/#using-extension`)}
1597
489
  `].join(`
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:`)}
1602
- ${S.gray(`A snapshot is keyed by commit - publishing the same commit again`)}
1603
- ${S.gray(`OVERWRITES its snapshot. Projects ACCUMULATE into a snapshot,`)}
1604
- ${S.gray(`publishing one project never removes the others.`)}
1605
-
1606
- ${S.bold(`Examples:`)}
1607
- ${S.green(`$0 publish --token=<token>`)}
1608
- ${S.gray(`Publish all projects from the current directory`)}
1609
-
1610
- ${S.green(`$0 publish -p my-project ./src/likec4`)}
1611
- ${S.gray(`Publish a single project into the snapshot of the current commit`)}
1612
-
1613
- ${S.green(`$0 publish --origin acme/architecture --sha $GIT_SHA`)}
1614
- ${S.gray(`Publish without a git repository (both flags are required then)`)}
1615
-
1616
- ${S.gray(`# .github/workflows/likec4.yml`)}
1617
- ${S.gray(`- uses: actions/checkout@v6`)}
1618
- ${S.gray(`- run: npx likec4 publish`)}
1619
- ${S.gray(` env:`)}
1620
- ${S.gray(" LIKEC4_PUBLISH_TOKEN: ${{ secrets.LIKEC4_PUBLISH_TOKEN }}")}
1621
- ${S.gray(`Publish from GitHub Actions (branch and tag come from the workflow env)`)}
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:`)}
1623
- ${S.green(`$0 validate `)}
1624
- ${S.gray(`Validate all in the current directory`)}
1625
-
1626
- ${S.green(`$0 validate --no-layout --json -f ./src/model.c4 -f ./src/deployment.c4 `)}
1627
- ${S.gray([`Validate all`,`ignore layout drifts`,`report only errors from these files`,`output as JSON`].join(`, `))}
1628
-
1629
- ${S.green(`$0 validate --project my-project /some/where`)}
1630
- ${S.gray(`Validate my-project in /some/where`)}
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{};
490
+ `))}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 mn({...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 S(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
491
+ 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`],D).default(`path`,D(`.`),`.`).default(`listen`,`127.0.0.1`,`localhost`),handler:async e=>{await handler$1(e)}}),Ep=`icon`;function collectFileIcons(e){let t=/* @__PURE__ */ new Set,visit=e=>{if(Array.isArray(e))for(let t of e)visit(t);else if(typeof e==`object`&&e)for(let[n,r]of Object.entries(e))n===Ep&&typeof r==`string`?r.startsWith(`file://`)&&t.add(r):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===Ep&&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 gn(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 ut(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=/* @__PURE__ */ new Map,a=/* @__PURE__ */ 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=yn(`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(m.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=Bt){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 Dp=/^[a-z][a-z0-9+.-]*:\/\//i,Op=/^(?:[^@/]+@)?([^@/:]+):(.+)$/,kp=/* @__PURE__ */ new Set([`.`,`..`]);function parseGitOrigin(e){let t=e.trim();if(t===``)return null;let n;switch(!0){case Dp.test(t):try{n=new URL(t).pathname}catch{return null}break;default:{let e=Op.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===``||kp.has(i)||kp.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 Ap=`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. ${Ap}`,{cause:e})}if(s===null){if(!a)throw Error(`Failed to resolve the git repository root. ${Ap}`);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(`
492
+ `)[0])}function unknownCommit(){return{message:``,author:``,email:``,date:(/* @__PURE__ */ 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. ${Ap}`,{cause:e})}if(t===null)throw Error(`Failed to resolve the current commit. ${Ap}`);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. ${Ap}`,{cause:e})}}const jp=/^(?:\/|[a-zA-Z]:\/)/,Mp={relative:E};function toWorkspacePath(e,t,n=Mp){let r=n.relative(e,t).replaceAll(`\\`,`/`);if(r===``)return`.`;if(r===`..`||r.startsWith(`../`)||jp.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=/* @__PURE__ */ 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 Np=`LIKEC4_PUBLISH_TOKEN`;function resolveToken(e){let t=e?.trim()||Yt[Np]?.trim();if(!t)throw Error(`No publish token provided, pass --token or set the ${Np} environment variable`);return t}function resolveBaseUrl(e){return(e?.trim()||Yt.LIKEC4_CLOUD_URL?.trim()||`https://likec4.app`).replace(/\/+$/,``)}function humanSize(e){return`${(e/1024).toFixed(1)} KB`}function toPhysicalPath(e){let t=D(e),n=t,r=[];for(;;)try{return bt(Gt(n),...r.reverse())}catch{let e=_t(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(`
493
+ `),{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),a=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=/* @__PURE__ */ new Map,u=D(e.path),f=await readGitProvenance({runner:createGitRunner(u),env:Yt,overrides:c}),p=toPhysicalPath(f.root||u);switch(n.info(`${m.dim(`origin:`)} ${m.green(f.origin)}`),n.info(`${m.dim(`commit:`)} ${m.green(f.sha)}`),n.info(`${m.dim(`branch:`)} ${f.branch?m.green(f.branch):m.dim(`(none)`)}`),f.tag&&n.info(`${m.dim(`tag:`)} ${m.green(f.tag)}`),f.dirty){case!0:n.warn(m.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(m.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(m.yellow(`No branch resolved - the snapshot will not be branch-addressable. Pass --branch to set it explicitly.`)),f.root||n.warn(m.yellow(`No git repository detected - project paths will be relative to ${p}`)),f.commit.author===``&&f.commit.message===``&&n.warn(m.yellow(`No commit metadata available - publishing with an empty commit author, email and message.`));let h=t.a(await S(u,{throwIfInvalid:!e.force,printErrors:!0,graphviz:e.useDotBin?`binary`:`wasm`,watch:!1})),g;if(e.project){let{projectId:t,projectFolder:r}=ensureProject(h,e.project);g=[{id:t,folder:r}],n.info(`${m.dim(`project:`)} ${m.green(t)}`)}else g=selectProjects(h,n),n.info(`${m.dim(`workspace:`)} Found ${g.length} projects`);let v=[];for(let{id:e,folder:t}of g)try{n.info(`Generating layouted model for project ${m.green(e)}`);let r=await h.layoutedModel(e);if(isEmptyModel(r)){n.warn(m.yellow(`Project ${e} is empty, skipping`));continue}let i=toPhysicalPath(t);i!==t&&l.set(i,t),v.push({name:e,folder:i,data:r.$data})}catch(t){n.error(i(t)),n.warn(`Skipping project ${m.red(e)}`)}if(v.length===0)throw Error(`Nothing to publish; all projects are empty or were skipped`);let y=await collectAssets({projects:v,force:e.force,logger:n}),b;try{b=buildPublishPayload({provenance:{...f,root:p},projects:y.projects,assets:y.assets})}catch(e){throw explainResolvedSymlinks(e,l)}let x=JSON.stringify(b),ee=new Uint8Array(Nn(x));n.info(`${m.dim(`payload:`)} ${humanSize(Buffer.byteLength(x))} ${m.dim(`→`)} ${humanSize(ee.byteLength)} ${m.dim(`gzipped`)}`);let te=Object.keys(y.assets).length;te>0&&n.info(`${m.dim(`assets:`)} ${te} ${m.dim(`file(s),`)} ${humanSize(y.totalBytes)}`);let ne=`${s}/api/publish`;n.info(`${m.dim(`publishing to`)} ${m.green(ne)}`);let re;try{re=await ni.post(ne,{body:ee,headers:{"X-Publish-Token":a,"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(m.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(`${m.dim(`snapshot:`)} ${m.green(re.snapshotId)}`),n.info(`${m.dim(`view at`)} ${m.underline(m.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`,W).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:{...Ss,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":G}).epilog(`${m.bold(`Notes:`)}
494
+ ${m.gray(`A snapshot is keyed by commit - publishing the same commit again`)}
495
+ ${m.gray(`OVERWRITES its snapshot. Projects ACCUMULATE into a snapshot,`)}
496
+ ${m.gray(`publishing one project never removes the others.`)}
497
+
498
+ ${m.bold(`Examples:`)}
499
+ ${m.green(`$0 publish --token=<token>`)}
500
+ ${m.gray(`Publish all projects from the current directory`)}
501
+
502
+ ${m.green(`$0 publish -p my-project ./src/likec4`)}
503
+ ${m.gray(`Publish a single project into the snapshot of the current commit`)}
504
+
505
+ ${m.green(`$0 publish --origin acme/architecture --sha $GIT_SHA`)}
506
+ ${m.gray(`Publish without a git repository (both flags are required then)`)}
507
+
508
+ ${m.gray(`# .github/workflows/likec4.yml`)}
509
+ ${m.gray(`- uses: actions/checkout@v6`)}
510
+ ${m.gray(`- run: npx likec4 publish`)}
511
+ ${m.gray(` env:`)}
512
+ ${m.gray(" LIKEC4_PUBLISH_TOKEN: ${{ secrets.LIKEC4_PUBLISH_TOKEN }}")}
513
+ ${m.gray(`Publish from GitHub Actions (branch and tag come from the workflow env)`)}
514
+ `),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 S(e,{graphviz:t?`binary`:`wasm`,watch:s}),useHashHistory:i,likec4AssetsDir:await ct(bt(un(),`.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`,W).option(`base`,hs).option(`webcomponent-prefix`,fs).option(`title`,ps).option(`use-hash-history`,us).option(`use-dot`,G).option(`listen`,ys).option(`port`,bs).option(`hmr-port`,xs).option(`public`,_s).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=D(e,`sync-plan.json`);if(await w(a,JSON.stringify(i,null,2)),r.info(`${m.dim(`generated`)} ${E(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=D(e,Vs.manifest);if(await w(a,JSON.stringify(i.manifest,null,2)),r.info(`${m.dim(`generated`)} ${E(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 S(r,{graphviz:s?`binary`:`wasm`,watch:!1})),{projectId:n}=ensureProject(e,a);a&&t.info(`${m.dim(`project`)} ${m.green(n)}`);let f=await e.layoutedModel(n);if(f===tt.EMPTY)throw t.error(Fs),Error(Fs);let p=buildBridgeArtifacts(asBridgeModel(f));await writeBridgeArtifacts(i,p,t);let h=createLeanixClientFromEnv();if((c||!l)&&(h?await runSyncPlan(i,p.dryRun,h,t):t.info(`${m.dim(`skip`)} sync-plan (set LEANIX_API_TOKEN to include plan)`)),l){if(!h)throw t.error(Is),Error(Is);await runSyncApply(i,p,h,t)}}catch(e){u.e=e}finally{await u.d()}}finally{n.stopAndLog()}}const Pp=D(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`,W).option(`outdir`,{...ds,default:Pp,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`,Ss).option(`use-dot`,G).example(`${m.green(`$0 sync leanix --dry-run -o out/bridge`)}`,m.gray(`Write bridge artifacts and optionally sync-plan when LEANIX_API_TOKEN is set`)).example(`${m.green(`$0 sync leanix --apply -o out/bridge`)}`,m.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??Pp,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`,W).options({project:Ss,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(`${m.bold(`Examples:`)}
515
+ ${m.green(`$0 validate `)}
516
+ ${m.gray(`Validate all in the current directory`)}
517
+
518
+ ${m.green(`$0 validate --no-layout --json -f ./src/model.c4 -f ./src/deployment.c4 `)}
519
+ ${m.gray([`Validate all`,`ignore layout drifts`,`report only errors from these files`,`output as JSON`].join(`, `))}
520
+
521
+ ${m.green(`$0 validate --project my-project /some/where`)}
522
+ ${m.gray(`Validate my-project in /some/where`)}
523
+ `),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=>D(e))??null,c=t.a(await S(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?D(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:h,errors:g}=p,{totalFiles:v,totalErrors:y}=p.stats;if(process.exitCode=+!h,i){console.log(JSON.stringify(p,null,2));return}for(let e of u)n.error(m.red(e.message)+(e.file?` at `+e.file:``));if(h)n.info(m.green(`✓ Valid`)+m.dim(` (${v} files)`));else{let e=s?`, ${g.length} in filtered files`:``;n.error(m.red(`✗ Invalid`)+m.dim(` (${v} files, ${y} errors${e})`))}r.stopAndLog(`validate `)}catch(e){t.e=e}finally{await t.d()}}});function applyLoggerConfig(e){let t=e??(Zt?`debug`:`info`);s({reset:!0,sinks:{console:l({formatter:m.isColorSupported?ne():a()})},loggers:[{category:`likec4`,sinks:[`console`],lowestLevel:t}]})}async function main(){await Le(sn(cn(en)),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(Ln).alias(`v`,`version`).alias(`h`,`help`).help(`help`).option(`log-level`,Cs).option(`verbose`,ws).option(`color`,{boolean:!0,describe:[`force color output, or disable with --no-color`,`respects 'FORCE_COLOR' and 'NO_COLOR' env variables`].join(`
524
+ `),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:":m.bold(`Globals:`),"Options:":m.bold(`Options:`),"Positionals:":m.bold(`Arguments:`),"Commands:":m.bold(`Commands:`),"Examples:":m.bold(`Examples:`)}).wrap(Fe(an.columns-10,{min:60,max:180})).middleware(e=>{applyLoggerConfig(e.verbose?Ts:e.logLevel)}).parseAsync()}function exitWithFailure(e,t){console.error(t==null?i(e):`${t} ${i(e)}`),nn(1)}main().catch(exitWithFailure),process.on(`unhandledRejection`,e=>{exitWithFailure(e,`Unhandled rejection:`)}),process.on(`uncaughtException`,e=>{console.error(e)});export{};