likec4 1.60.0 → 1.61.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 (157) hide show
  1. package/README.md +2 -0
  2. package/__app__/codegen/react.mjs +4 -10
  3. package/__app__/codegen/webcomponent.mjs +5 -208
  4. package/__app__/index.html +15 -15
  5. package/__app__/src/aichat/index.mjs +1 -2
  6. package/__app__/src/chunks/AIChat.mjs +292 -117
  7. package/__app__/src/chunks/ErrorComponent.mjs +444 -0
  8. package/__app__/src/chunks/Header.mjs +269 -0
  9. package/__app__/src/chunks/ViewReact.mjs +438 -0
  10. package/__app__/src/chunks/find.mjs +38 -0
  11. package/__app__/src/chunks/hooks.mjs +18 -541
  12. package/__app__/src/chunks/libs/@tabler/icons-react.mjs +340 -0
  13. package/__app__/src/chunks/libs/@tanstack-ai.mjs +11101 -1797
  14. package/__app__/src/chunks/libs/@tanstack.mjs +4563 -3083
  15. package/__app__/src/chunks/libs/fast-equals.mjs +140 -71
  16. package/__app__/src/chunks/{es.mjs → libs/html-to-image.mjs} +16 -22
  17. package/__app__/src/chunks/libs/nanostores.mjs +4 -8
  18. package/__app__/src/chunks/libs/react-resizable-panels.mjs +2792 -0
  19. package/__app__/src/chunks/react.mjs +22 -0
  20. package/__app__/src/chunks/rolldown-runtime.mjs +3 -32
  21. package/__app__/src/chunks/router.mjs +106 -0
  22. package/__app__/src/chunks/scope.mjs +106 -0
  23. package/__app__/src/chunks/searchParams.mjs +29 -0
  24. package/__app__/src/chunks/single-index.mjs +465 -0
  25. package/__app__/src/chunks/styled-system.mjs +1916 -2946
  26. package/__app__/src/chunks/useAsync.mjs +69 -0
  27. package/__app__/src/chunks/useSyncedRef.mjs +16 -0
  28. package/__app__/src/components/ColorSchemeToggle.mjs +124 -0
  29. package/__app__/src/components/CopyToClipboard.mjs +53 -0
  30. package/__app__/src/components/ErrorComponent.mjs +1 -0
  31. package/__app__/src/components/NavigationPanel.mjs +63 -0
  32. package/__app__/src/components/NotFound.mjs +155 -0
  33. package/__app__/src/components/ViewOutlet.mjs +9 -0
  34. package/__app__/src/components/model-diff/CompareModelProvider.mjs +44 -0
  35. package/__app__/src/components/model-diff/ModelDiffPanel.mjs +179 -0
  36. package/__app__/src/components/model-diff/compare-model.mjs +76 -0
  37. package/__app__/src/components/model-diff/state.mjs +45 -0
  38. package/__app__/src/components/search/OverviewSearch.mjs +92 -0
  39. package/__app__/src/components/search/OverviewSearchAdapter.mjs +94 -0
  40. package/__app__/src/components/sidebar/DiagramTree.css.mjs +48 -0
  41. package/__app__/src/components/sidebar/DiagramsTree.mjs +304 -0
  42. package/__app__/src/components/sidebar/Drawer.mjs +178 -0
  43. package/__app__/src/components/sidebar/SidebarBurger.mjs +28 -0
  44. package/__app__/src/components/sidebar/data.mjs +94 -0
  45. package/__app__/src/components/sidebar/state.mjs +16 -0
  46. package/__app__/src/components/view-page/Header.mjs +1 -0
  47. package/__app__/src/components/view-page/SelectProject.mjs +258 -0
  48. package/__app__/src/components/view-page/ShareModal.mjs +111 -0
  49. package/__app__/src/components/view-page/share-modal/AlertLocalhost.mjs +31 -0
  50. package/__app__/src/components/view-page/share-modal/CopyButtonChild.mjs +36 -0
  51. package/__app__/src/components/view-page/share-modal/EmbedPanel.mjs +100 -0
  52. package/__app__/src/components/view-page/share-modal/WebcomponentsPanel.mjs +264 -0
  53. package/__app__/src/components/view-page/state.mjs +17 -0
  54. package/__app__/src/context/LikeC4CustomizationContext.mjs +26 -0
  55. package/__app__/src/context/LikeC4IconRendererContext.mjs +29 -0
  56. package/__app__/src/context/LikeC4ModelContext.mjs +34 -0
  57. package/__app__/src/context/LikeC4ProjectsContext.mjs +40 -0
  58. package/__app__/src/context/ModelDiffsContext.mjs +33 -0
  59. package/__app__/src/context/safeCtx.mjs +14 -0
  60. package/__app__/src/hooks.mjs +1 -0
  61. package/__app__/src/main.mjs +4 -48126
  62. package/__app__/src/pages/EmbedPage.mjs +93 -0
  63. package/__app__/src/pages/ExportPage.mjs +691 -0
  64. package/__app__/src/pages/ProjectsOverview.mjs +23 -0
  65. package/__app__/src/pages/ViewAsD2.mjs +105 -0
  66. package/__app__/src/pages/ViewAsDot.mjs +65 -0
  67. package/__app__/src/pages/ViewAsMmd.mjs +109 -0
  68. package/__app__/src/pages/ViewAsPuml.mjs +105 -0
  69. package/__app__/src/pages/ViewEditor.mjs +220 -0
  70. package/__app__/src/pages/ViewReact.mjs +1 -0
  71. package/__app__/src/pages/export-layout.mjs +95 -0
  72. package/__app__/src/pages/export-page-params.mjs +9 -0
  73. package/__app__/src/pages/styles.css.mjs +23 -0
  74. package/__app__/src/routeTree.gen.mjs +105 -0
  75. package/__app__/src/router.mjs +1 -0
  76. package/__app__/src/routes/__root.mjs +65 -0
  77. package/__app__/src/routes/index.css.mjs +29 -0
  78. package/__app__/src/routes/index.mjs +32 -0
  79. package/__app__/src/routes/project._projectId/-components.mjs +100 -0
  80. package/__app__/src/routes/project._projectId/embed._viewId.mjs +5 -0
  81. package/__app__/src/routes/project._projectId/export._viewId.mjs +24 -0
  82. package/__app__/src/routes/project._projectId/index.mjs +14 -0
  83. package/__app__/src/routes/project._projectId/route.mjs +93 -0
  84. package/__app__/src/routes/project._projectId/view._viewId.d2.mjs +34 -0
  85. package/__app__/src/routes/project._projectId/view._viewId.dot.mjs +41 -0
  86. package/__app__/src/routes/project._projectId/view._viewId.index.mjs +7 -0
  87. package/__app__/src/routes/project._projectId/view._viewId.mjs +23 -0
  88. package/__app__/src/routes/project._projectId/view._viewId.mmd.mjs +39 -0
  89. package/__app__/src/routes/project._projectId/view._viewId.puml.mjs +34 -0
  90. package/__app__/src/routes/projects.mjs +36 -0
  91. package/__app__/src/routes/single-index.mjs +1 -0
  92. package/__app__/src/routes/webcomponent._.mjs +94 -0
  93. package/__app__/src/style.css +1156 -1147
  94. package/config/schema.json +26 -2
  95. package/dist/app/render-view-client.css +1 -1
  96. package/dist/app/render-view-client.js +375 -393
  97. package/dist/chunks/filenames.mjs +26 -20
  98. package/dist/chunks/generate-likec4.mjs +4 -4
  99. package/dist/chunks/index.d.mts +16 -15
  100. package/dist/chunks/index2.d.mts +7041 -3293
  101. package/dist/chunks/libs/@chenglou/pretext.mjs +9 -0
  102. package/dist/chunks/libs/@logtape/logtape.mjs +5 -5
  103. package/dist/chunks/libs/@ts-graphviz/common.d.mts +2 -4
  104. package/dist/chunks/libs/chevrotain.mjs +19 -19
  105. package/dist/chunks/libs/clone.mjs +1 -0
  106. package/dist/chunks/libs/eventemitter3.mjs +1 -1
  107. package/dist/chunks/libs/fast-equals.mjs +1 -0
  108. package/dist/chunks/libs/fontkit.mjs +1 -0
  109. package/dist/chunks/libs/langium.d.mts +80 -2933
  110. package/dist/chunks/libs/langium.mjs +6 -6
  111. package/dist/chunks/libs/pako.mjs +1 -1
  112. package/dist/chunks/libs/pathe.mjs +1 -1
  113. package/dist/chunks/libs/remeda.mjs +1 -1
  114. package/dist/chunks/node.mjs +110 -77
  115. package/dist/chunks/rolldown-runtime.mjs +1 -1
  116. package/dist/chunks/sequence-view.mjs +1 -1
  117. package/dist/chunks/vite-plugin.mjs +183 -164
  118. package/dist/cli/index.mjs +157 -101
  119. package/dist/config/index.d.mts +65 -4
  120. package/dist/config/index.mjs +1 -1
  121. package/dist/generators/likec4.d.mts +16 -64
  122. package/dist/index.d.mts +2 -4
  123. package/dist/model/index.d.mts +0 -10
  124. package/dist/vite-plugin/index.d.mts +83 -61
  125. package/dist/vite-plugin/internal/chunks/rolldown-runtime.mjs +1 -2
  126. package/dist/vite-plugin/internal/index.d.mts +91 -17
  127. package/dist/vite-plugin/internal/index.mjs +156 -110
  128. package/package.json +60 -55
  129. package/react/index.d.mts +3010 -4014
  130. package/react/index.mjs +170 -171
  131. package/react/rolldown-runtime-CfRud99p.js +1 -0
  132. package/skills/likec4-dsl/SKILL.md +71 -25
  133. package/skills/likec4-dsl/evals/evals-public.json +5 -0
  134. package/skills/likec4-dsl/evals/grading-spec.json +15 -1
  135. package/skills/likec4-dsl/references/cli.md +39 -10
  136. package/skills/likec4-dsl/references/configuration.md +5 -5
  137. package/skills/likec4-dsl/references/diffs.md +52 -0
  138. package/skills/likec4-dsl/references/examples.md +2 -2
  139. package/skills/likec4-dsl/references/identifier-validity.md +31 -31
  140. package/skills/likec4-dsl/references/include-predicates-wildcards.md +16 -15
  141. package/skills/likec4-dsl/references/model.md +42 -11
  142. package/skills/likec4-dsl/references/specification.md +11 -7
  143. package/skills/likec4-dsl/references/troubleshooting.md +47 -42
  144. package/skills/likec4-dsl/references/views.md +2 -2
  145. package/vite-plugin-modules.d.ts +126 -51
  146. package/__app__/src/chunks/LikeC4Styles.mjs +0 -4522
  147. package/__app__/src/chunks/ProjectsOverview.mjs +0 -827
  148. package/__app__/src/chunks/libs/@floating-ui.mjs +0 -3286
  149. package/__app__/src/chunks/libs/@mantine.mjs +0 -17731
  150. package/__app__/src/chunks/libs/@xstate/react.mjs +0 -3471
  151. package/__app__/src/chunks/libs/@xyflow/react.mjs +0 -7927
  152. package/__app__/src/chunks/libs/bezier-js.mjs +0 -1593
  153. package/__app__/src/chunks/libs/d3.mjs +0 -4531
  154. package/__app__/src/chunks/libs/framer.mjs +0 -11331
  155. package/__app__/src/chunks/libs/zod.mjs +0 -5404
  156. package/dist/chunks/libs/@chevrotain/types.d.mts +0 -111
  157. package/react/rolldown-runtime-DnkiqaRY.js +0 -1
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
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(`
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 C,u as w,w as T,x as E,y as D}from"../chunks/node.mjs";import{$ as ee,C as te,E as O,F as ne,I as re,Q as ie,T as ae,X as oe,d as se,et as ce,f as le,g as ue,it as de,o as fe,r as pe,t as me,tt as he,u as ge,x as _e}from"../chunks/libs/remeda.mjs";import{a as ve,c as ye,d as be,i as xe,l as Se,n as Ce,o as we,r as Te,s as Ee,t as De}from"../chunks/vite-plugin.mjs";import{t as Oe}from"../chunks/libs/pretty-ms.mjs";import{c as ke,l as Ae,o as je,r as Me,s as Ne}from"../chunks/libs/ufo.mjs";import{n as Pe}from"../chunks/libs/fontkit.mjs";import{n as Fe,t as Ie}from"../chunks/libs/package-manager-detector.mjs";import{C as Le,K as Re,Z as ze,_ as Be,c as Ve,dt as He,g as Ue,h as We,q as Ge,v as Ke,y as qe}from"../chunks/libs/langium.mjs";import{t as Je}from"../chunks/libs/json5.mjs";import{$ as Ye,Q as k,tt as Xe}from"../chunks/generate-likec4.mjs";import{LikeC4Model as Ze}from"../model/index.mjs";import{n as Qe}from"../chunks/sequence-view.mjs";import{t as $e}from"../chunks/libs/which.mjs";import et from"node:module";import*as A from"zod/v4";import tt,{z as j}from"zod/v4";import{isDeepStrictEqual as nt,promisify as rt}from"node:util";import{copyFile as it,cp as at,mkdir as ot,mkdtemp as st,readFile as ct,readdir as ut,realpath as dt,rm as ft,stat as pt,writeFile as M}from"node:fs/promises";import N,{basename as mt,dirname as ht,extname as _t,isAbsolute as vt,join as yt,relative as P,resolve as F,sep as bt}from"node:path";import{DiffId as xt,ProjectId as St}from"@likec4/core/types";import{FqnRef as Ct,GlobalFqn as wt,hasProp as Tt,invariant as I,nonexhaustive as Et}from"@likec4/core";import{ZodOptional as Dt}from"zod";import{collapseUnchanged as Ot,compareNatural as kt,diffLines as At,invariant as jt,isSameHierarchy as Mt,resolveMarkdownRefs as Nt,sortNaturalByFqn as Pt}from"@likec4/core/utils";import L,{copyFileSync as Ft,existsSync as It,readFileSync as Lt,readdirSync as Rt,realpathSync as zt,rmSync as Bt,statSync as Vt,writeFileSync as Ht}from"node:fs";import{isDeploymentElementModel as Ut,isDeploymentNodeModel as Wt,isDeploymentRelationModel as Gt,isElementModel as Kt,isLikeC4ViewModel as qt,isRelationModel as Jt,modelConnection as Yt}from"@likec4/core/model";import Xt from"nano-spawn";import{env as Zt,isCI as Qt,isDevelopment as $t,isTest as en,nodeENV as tn}from"std-env";import{createJiti as nn}from"jiti";import R,{argv as rn,cwd as an,exit as on,hrtime as sn,stdout as cn}from"node:process";import ln from"picomatch";import un from"yargs";import{hideBin as dn}from"yargs/helpers";import fn,{tmpdir as pn}from"node:os";import mn from"node:tty";import{fileURLToPath as hn,pathToFileURL as gn}from"node:url";import{build as _n,createServer as vn,normalizePath as yn,preview as bn}from"vite";import xn from"@vitejs/plugin-react";import{viteSingleFile as Sn}from"vite-plugin-singlefile";import{Buffer as Cn}from"node:buffer";import wn,{createHash as Tn,randomUUID as En}from"node:crypto";import{Readable as Dn}from"node:stream";import On from"node:net";import{setTimeout as kn}from"node:timers/promises";import*as An from"zod/v3";import{ZodFirstPartyTypeKind as z}from"zod/v3";import*as jn from"zod/v4-mini";import{STATUS_CODES as Mn,ServerResponse as Nn,createServer as Pn}from"node:http";import{Http2ServerRequest as Fn,constants as In}from"node:http2";import{gzipSync as Ln}from"node:zlib";var Rn=/* @__PURE__ */ n($e(),1);function graphvizBinPath(){try{return Rn.default.sync(`dot`)}catch(e){return p.error(`Error checking for native Graphviz:`,{error:e}),null}}const zn={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=re(i)?graphvizBinPath():i;if(!re(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=Qe(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},...C(n.enableWatcher),...n.enableManualLayouts&&u,...b(n.graphviz===`binary`?new x:new h)},t?{likec4:{...zn.likec4}}:void 0);return Ve(r.shared),r}function appendView(e,t){e.append(`### `,t.titleOrId,k,k),t.description.nonEmpty&&e.append(Nt(t.description.md,t.$model.resolveMarkdownRef,{escape:!0}),k,k),e.append("```mermaid",k,Te(t).trimEnd(),k,"```",k,k)}function generateMarkdown(e,t={}){let n=new qe;n.append(`# `,e.project.title??e.projectId,k,k),t.description&&n.append(t.description,k,k);for(let t of e.views())t.$view.sourcePath!==void 0&&appendView(n,t);return Ye(n)}function toUnion(e){return ne(e)?`never`:(typeof e==`object`&&!Array.isArray(e)&&(e=te(e)),le(e,pe(),fe(kt),_e(e=>` | ${JSON.stringify(e)}`)).join(`
3
+ `).trimStart())}function elementIdToUnion(e){let t=le(e,me(),ee(e=>!!e&&ae(e.id)),Pt,_e(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(${xe.stringify(e.$data,{space:2,quote:`'`})} as any) as any
55
+ export const likec4model: LikeC4Model<$Aux> = new LikeC4Model(${Je.stringify(e.$data,{space:2,quote:`'`})} as any) as any
56
56
 
57
57
  /* prettier-ignore-end */
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`
58
+ `.trimStart()}function generateViewId(e){return Ke(e,e=>Le`${Je.stringify(e.id)}`,{separator:` | `})}function generateViewsDataTs(e){let t=Array.from(e),n=new qe;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(${xe.stringify(e.$
66
66
  // @ts-nocheck
67
67
 
68
68
  import type { DiagramView } from 'likec4'
69
- `.append(C,C),t.length===0?(n.append(`export {}`,C),Be(n)):(n.appendTemplate`
69
+ `.append(k,k),t.length===0?(n.append(`export {}`,k),Ye(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(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`
72
+ `.indent({indentation:2,indentedChildren(e){e.appendNewLineIf(t.length>1).append(Ke(t,e=>Le`${Je.stringify(e.id)}: (${Je.stringify(e)} as unknown) as DiagramView`,{separator:`,`,appendNewLineIfNotEmpty:!0}))}}).append(`} as const satisfies Record<LikeC4ViewId, DiagramView>`,k,k).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(${xe.stringify(e.$
81
81
  }
82
82
 
83
83
  /* prettier-ignore-end */
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`
84
+ `.append(k),Ye(n))}function generateReactTypes(e,t={}){let{useCorePackage:n=!1}=t;jt(!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,64 +137,69 @@ export {
137
137
  ReactLikeC4
138
138
  }
139
139
  /* prettier-ignore-end */
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
140
+ `.trimStart()}var Bn=`likec4`,Vn=`1.61.0`;const Hn=tt.number().int().min(1).max(65535),Un=tt.strictObject({...be.shape,workspace:tt.string().nonempty().optional(),graphviz:tt.enum([`wasm`,`binary`]).optional(),base:tt.string().nonempty().optional(),publicDir:tt.string().nonempty().optional(),build:tt.strictObject({outDir:tt.string().nonempty().optional(),singleFile:tt.boolean().default(!1),webcomponent:tt.boolean().default(!0)}).prefault({}),server:tt.strictObject({host:tt.string().nonempty().optional(),port:Hn.optional(),hmrPort:Hn.optional(),allowedHosts:tt.array(tt.string().nonempty()).optional()}).prefault({})}),Wn=[`likec4.app.config.ts`,`likec4.app.config.mts`,`likec4.app.config.cts`,`likec4.app.config.js`,`likec4.app.config.mjs`,`likec4.app.config.cjs`];function findAppConfig(e){for(let t of e)for(let e of Wn){let n=F(t,e);if(It(n))return n}}const identity=e=>e,Gn={defineAppConfig:identity};function resolvePaths(e,t){let path=e=>e===void 0?void 0:F(t,e);return{...e,workspace:path(e.workspace),customization:path(e.customization),publicDir:path(e.publicDir),build:{...e.build,outDir:path(e.build.outDir)}}}function parseAppConfig(e,t=`app config`){let n=Un.safeParse(e??{});if(!n.success)throw Error(`Invalid ${t}:\n`+tt.prettifyError(n.error));return n.data}async function loadAppConfig(e){e=F(e);let t=nn(e,{moduleCache:!1,fsCache:!1,virtualModules:{"likec4/config":Gn}}),n;try{n=await t.import(e,{default:!0})}catch(t){throw t instanceof Error&&t.message.includes(e)?t:T(t,`${e}:`)}return resolvePaths(parseAppConfig(n,e),ht(e))}let Kn;function hasDockerEnv(){try{return L.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return L.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return Kn===void 0&&(Kn=hasDockerEnv()||hasDockerCGroup()),Kn}let qn;const hasContainerEnv=()=>{try{return L.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return qn===void 0&&(qn=hasContainerEnv()||isDocker()),qn}function parsePort(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isNaN(t)?void 0:t}function locateAppConfig(e,t,n){if(e.appConfig!==!1){if(typeof e.appConfig==`string`){let t=F(n,e.appConfig);if(!It(t))throw Error(`LikeC4 app config not found: ${t}`);return t}return findAppConfig(pe([...t?[t]:[],n]))}}async function resolveAppConfig(e,{cwd:t=process.cwd(),env:n=process.env}={}){let r=e.path??(n.LIKEC4_WORKSPACE?F(t,n.LIKEC4_WORKSPACE):void 0),i=locateAppConfig(e,r,t),a=i?await loadAppConfig(i):parseAppConfig({}),s=e.useDot??(a.graphviz?a.graphviz===`binary`:isInsideContainer());return{configFile:i,workspace:r??a.workspace??t,graphviz:s?`binary`:`wasm`,title:e.title??a.title,theme:e.theme??a.theme,useHashHistory:e.useHashHistory??a.useHashHistory,webcomponentPrefix:e.webcomponentPrefix??a.webcomponentPrefix,customization:e.customization??a.customization,base:e.base??a.base,publicDir:e.publicDir??a.publicDir,build:{outDir:e.output??a.build.outDir,singleFile:e.outputSingleFile??a.build.singleFile,webcomponent:e.buildWebcomponent??a.build.webcomponent},server:{host:e.listen??a.server.host,port:e.port??parsePort(n.PORT)??a.server.port,hmrPort:e.hmrPort??parsePort(n.HMR_PORT)??a.server.hmrPort,allowedHosts:e.allowedHosts??a.server.allowedHosts}}}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 Jn=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(Jn,``)}const Yn=[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],Xn=[12288,12288,65281,65376,65504,65510],Zn=[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},Qn=19968,[$n,er]=/* #__PURE__ */ findWideFastPathRange(Zn);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(Qn>=i&&Qn<=a)return[i,a];a-i>n-t&&(t=i,n=a)}return[t,n]}const isAmbiguous=e=>e<161||e>1114109?!1:isInRange(Yn,e),isFullwidth=e=>e<12288||e>65510?!1:isInRange(Xn,e),isWide=e=>e>=$n&&e<=er?!0:e<4352||e>262141?!1:isInRange(Zn,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}const tr=new Intl.Segmenter,nr=/[^\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]/v,rr=/\p{Spacing_Mark}/v,ir=/^\p{RGI_Emoji}$/v,ar=/^[\d#*]\u20E3$/,sr=/\p{Extended_Pictographic}/gu;function isDoubleWidthNonRgiEmojiSequence(e){if(e.length>50)return!1;if(ar.test(e))return!0;if(e.includes(`‍`)){let t=e.match(sr);return t!==null&&t.length>=2}return!1}function baseVisible(e){let t=e.search(nr);return t===-1?void 0:e.slice(t)}function isHangulLeadingJamo(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function isHangulVowelJamo(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function isHangulTrailingJamo(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}function isHangulJamo(e){return isHangulLeadingJamo(e)||isHangulVowelJamo(e)||isHangulTrailingJamo(e)}function hangulClusterWidth(e,t){let n=[];for(let t of e)nr.test(t)&&n.push(t.codePointAt(0));if(n.length===0)return;let r=0;for(let e=0;e<n.length;e++){let i=n[e];if(!isHangulJamo(i)){if(r===0)return;for(let i=e;i<n.length;i++)r+=eastAsianWidth(n[i],t);return r}isHangulLeadingJamo(i)&&isHangulVowelJamo(n[e+1])?(r+=2,e+=isHangulTrailingJamo(n[e+2])?2:1):r+=eastAsianWidth(i,t)}return r}function trailingWidth(e,t){let n=0,r=!0;for(let i of e)r?r=!1:(rr.test(i)||i>=`＀`&&i<=`￯`)&&(n+=eastAsianWidth(i.codePointAt(0),t));return n}function stringWidth(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t,i=e;if(!r&&(i.includes(`\x1B`)||i.includes(`›`))&&(i=stripAnsi(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let a=0,s={ambiguousAsWide:!n};for(let{segment:e}of tr.segment(i)){let t=baseVisible(e);if(t===void 0)continue;if(ir.test(e)||isDoubleWidthNonRgiEmojiSequence(e)){a+=2;continue}let n=hangulClusterWidth(t,s);if(n!==void 0){a+=n;continue}let r=t.codePointAt(0);a+=eastAsianWidth(r,s),a+=trailingWidth(t,s)}return a}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: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
- `?(a&&(r+=wrapAnsiHyperlink(``)),i&&n&&(r+=wrapAnsiCode(n))):t===`
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
143
+ `,i)}while(r!==-1);return a+=e.slice(i),a}const cr=/* @__PURE__ */ t((e=0)=>t=>`\u{1B}[${t+e}m`,`wrapAnsi16`),lr=/* @__PURE__ */ t((e=0)=>t=>`\u{1B}[${38+e};5;${t}m`,`wrapAnsi256`),ur=/* @__PURE__ */ t((e=0)=>(t,n,r)=>`\u{1B}[${38+e};2;${t};${n};${r}m`,`wrapAnsi16m`),wrapUnderlineAnsi=e=>`\u{1B}[58;5;${e<90?e-30:e-90+8}m`,B={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:[`4:2`,24],underlineCurly:[`4:3`,24],underlineDotted:[`4:4`,24],underlineDashed:[`4:5`,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]},underlineColor:{underlineBlack:[`58;5;0`,59],underlineRed:[`58;5;1`,59],underlineGreen:[`58;5;2`,59],underlineYellow:[`58;5;3`,59],underlineBlue:[`58;5;4`,59],underlineMagenta:[`58;5;5`,59],underlineCyan:[`58;5;6`,59],underlineWhite:[`58;5;7`,59],underlineBlackBright:[`58;5;8`,59],underlineGray:[`58;5;8`,59],underlineGrey:[`58;5;8`,59],underlineRedBright:[`58;5;9`,59],underlineGreenBright:[`58;5;10`,59],underlineYellowBright:[`58;5;11`,59],underlineBlueBright:[`58;5;12`,59],underlineMagentaBright:[`58;5;13`,59],underlineCyanBright:[`58;5;14`,59],underlineWhiteBright:[`58;5;15`,59]}};Object.keys(B.modifier);const dr=Object.keys(B.color),fr=Object.keys(B.bgColor);Object.keys(B.underlineColor),[...dr,...fr];function assembleStyles$1(){let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(B)){for(let[t,r]of Object.entries(n))B[t]={open:`\u{1B}[${r[0]}m`,close:`\u{1B}[${r[1]}m`},n[t]=B[t],e.set(Number.parseInt(r[0],10),r[1]);Object.defineProperty(B,t,{value:n,enumerable:!1})}return Object.defineProperty(B,"codes",{value:e,enumerable:!1}),B.color.close=`\x1B[39m`,B.bgColor.close=`\x1B[49m`,B.underlineColor.close=`\x1B[59m`,B.color.ansi=cr(),B.color.ansi256=lr(),B.color.ansi16m=ur(),B.bgColor.ansi=cr(10),B.bgColor.ansi256=lr(10),B.bgColor.ansi16m=ur(10),B.underlineColor.ansi=wrapUnderlineAnsi,B.underlineColor.ansi256=lr(20),B.underlineColor.ansi16m=ur(20),Object.defineProperties(B,{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=/[\da-f]{6}|[\da-f]{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=>B.rgbToAnsi256(...B.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)=>B.ansi256ToAnsi(B.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>B.ansi256ToAnsi(B.hexToAnsi256(e)),enumerable:!1}}),B}t(assembleStyles$1,`assembleStyles`);const pr=assembleStyles$1();function hasFlag(e,t=globalThis.Deno?globalThis.Deno.args:R.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:V}=R;let mr;hasFlag(`no-color`)||hasFlag(`no-colors`)||hasFlag(`color=false`)||hasFlag(`color=never`)?mr=0:(hasFlag(`color`)||hasFlag(`colors`)||hasFlag(`color=true`)||hasFlag(`color=always`))&&(mr=1);function hasNumericForceColor(){return/^\d+$/.test(V.FORCE_COLOR)}function envForceColor(){if(`FORCE_COLOR`in V){if(V.FORCE_COLOR===`false`)return 0;if(V.FORCE_COLOR===`true`||V.FORCE_COLOR.length===0)return 1;if(hasNumericForceColor())return Math.min(Number.parseInt(V.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&&(mr=r);let i=n?mr: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(i!==void 0&&hasNumericForceColor())return i;if(`TF_BUILD`in V&&`AGENT_NAME`in V)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(V.TERM===`dumb`)return a;if(R.platform===`win32`){let e=fn.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in V)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in V)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in V)||V.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in V)return+!!/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(V.TEAMCITY_VERSION);if(V.COLORTERM===`truecolor`||V.TERM===`xterm-kitty`||V.TERM===`xterm-ghostty`||V.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in V){let e=Number.parseInt((V.TERM_PROGRAM_VERSION||``).split(`.`,1)[0],10);switch(V.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(?:color)?$/i.test(V.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(V.TERM)||`COLORTERM`in V?1:a}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}const{stdout:hr,stderr:gr}={stdout:createSupportsColor({isTTY:mn.isatty(1)}),stderr:createSupportsColor({isTTY:mn.isatty(2)})},_r=Symbol(`GENERATOR`),vr=Symbol(`STYLER`),yr=Symbol(`IS_EMPTY`),br=Symbol(`LEVEL`),xr=Object.create(null),assertValidLevel=e=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},Sr={enumerable:!0,get(){return this[br]},set(e){assertValidLevel(e),this[br]=e}},applyOptions=(e,t={})=>{t.level!==void 0&&assertValidLevel(t.level);let n=hr?hr.level:0;e[br]=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(pr))xr[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[vr]),this[yr]);return Object.defineProperty(this,e,{value:n}),n}};xr.visible={get(){let e=createBuilder(this,this[vr],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const createModelConverters=(e,t)=>{let n=pr[t];if(e===`rgb`){let ansi=(e,t,r)=>n.ansi(pr.rgbToAnsi(e,t,r)),ansi256=(e,t,r)=>n.ansi256(pr.rgbToAnsi256(e,t,r));return[ansi,ansi,ansi256,n.ansi16m]}if(e===`hex`){let ansi=e=>n.ansi(pr.hexToAnsi(e)),ansi256=e=>n.ansi256(pr.hexToAnsi256(e));return[ansi,ansi,ansi256,e=>n.ansi16m(...pr.hexToRgb(e))]}let ansi=e=>n.ansi(pr.ansi256ToAnsi(e));return[ansi,ansi,n.ansi256,n.ansi256]};for(let e of[`rgb`,`hex`,`ansi256`]){let t=e[0].toUpperCase()+e.slice(1);for(let[n,r]of[[e,`color`],[`bg`+t,`bgColor`],[`underline`+t,`underlineColor`]]){let{close:t}=pr[r],i=createModelConverters(e,r);xr[n]={get(){let styleFunction=function(e,n,r){let a=i[this.level](e,n,r);return createBuilder(this,createStyler(a,t,this[vr]),this[yr])};return Object.defineProperty(this,n,{value:styleFunction}),styleFunction}}}}const Cr=Object.defineProperties(()=>{},{...xr,level:{enumerable:!0,get(){return this[_r].level},set(e){this[_r].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)=>e.length===1?applyStyle(builder,``+e[0]):e.length===2?applyStyle(builder,`${e[0]??``} ${e[1]??``}`):applyStyle(builder,e.join(` `));return Object.setPrototypeOf(builder,Cr),builder[_r]=e[_r]??e,builder[vr]=t,builder[yr]=n,builder},applyStyle=(e,t)=>{if(e[_r][br]<=0||!t)return e[yr]?``:t;let n=e[vr];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,{...xr,level:Sr});const wr=createChalk();createChalk({level:gr?gr.level:0});function widestLine(e){let t=0;for(let n of e.split(`
145
+ `))t=Math.max(t,stringWidth(n));return t}var Tr={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:`→`}};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`,H={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(H.modifier);const Er=Object.keys(H.color),Dr=Object.keys(H.bgColor);[...Er,...Dr];function assembleStyles(){let e=/* @__PURE__ */ new Map;for(let[t,n]of Object.entries(H)){for(let[t,r]of Object.entries(n))H[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=H[t],e.set(r[0],r[1]);Object.defineProperty(H,t,{value:n,enumerable:!1})}return Object.defineProperty(H,"codes",{value:e,enumerable:!1}),H.color.close=`\x1B[39m`,H.bgColor.close=`\x1B[49m`,H.color.ansi=wrapAnsi16(),H.color.ansi256=wrapAnsi256(),H.color.ansi16m=wrapAnsi16m(),H.bgColor.ansi=wrapAnsi16(10),H.bgColor.ansi256=wrapAnsi256(10),H.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(H,{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=>H.rgbToAnsi256(...H.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)=>H.ansi256ToAnsi(H.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>H.ansi256ToAnsi(H.hexToAnsi256(e)),enumerable:!1}}),H}const Or=assembleStyles(),kr=/* @__PURE__ */ new Set([`\x1B`,`›`]),Ar=[...kr].join(``),jr=`(?:\x07|\x1B\\\\)`,Mr=String.raw`[^\u0000-\u001F\u007F-\u009F]*`,Nr=String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${Mr})${jr}`,Pr=`${Mr}${jr}`,Fr=RegExp(`(?:\\[|›)(?:(?<sgr>[0-9;:]*)m|[0-?]*[ -/]*[@-~])|\\](?:${Nr}|${Pr})`,`y`),Ir=new Set(Or.codes.values());Ir.delete(0);const Lr=new Intl.Segmenter,getStringWidth=e=>stringWidth(e,{countAnsiEscapeCodes:!0}),Rr=RegExp(`[${Ar}]`,`g`),zr=RegExp(`[\\n${Ar}]`,`g`),Br=/^[ -~]*$/,wrapAnsiCode=e=>`[${e}m`,wrapAnsiHyperlink=(e,t=``)=>`]8;${t};${e}`,matchAnsiEscape=(e,t)=>{if(kr.has(e[t]))return Fr.lastIndex=t,Fr.exec(e)??void 0},forEachSegment=(e,t,n=()=>{})=>{let r=0,i=0;for(;i<e.length;){Rr.lastIndex=i;let a=Rr.exec(e);if(!a)break;let s=matchAnsiEscape(e,a.index);s?(a.index>r&&t(e.slice(r,a.index)),n(s[0]),i=a.index+s[0].length,r=i):i=a.index+1}r<e.length&&t(e.slice(r))},getWidth=e=>{let t=``;return forEachSegment(e,e=>{t+=e}),getStringWidth(t)},getTokens=e=>{let t=[];return forEachSegment(e,e=>{if(Br.test(e))for(let n of e)t.push({value:n,width:1});else for(let{segment:n}of Lr.segment(e))t.push({value:n,width:getStringWidth(n)})},e=>{t.push({value:e,width:0})}),t},splitWords=e=>{let t={value:``,plainText:``},n=[t];forEachSegment(e,e=>{let r=e.split(` `);t.value+=r[0],t.plainText+=r[0];for(let e=1;e<r.length;e++)t={value:r[e],plainText:r[e]},n.push(t)},e=>{t.value+=e});for(let e of n)e.width=getStringWidth(e.plainText);return n},getColonColorToken=e=>{let t=e.split(`:`),n=Number.parseInt(t[0],10),r=Number.parseInt(t[1],10);if(![38,48,58].includes(n))return;if(r===5&&t.length===3&&/^\d+$/.test(t[2]))return{code:n,open:e,hasArguments:!0};if(r!==2)return;let i=t.length===6?t.slice(3):t.slice(2),a=t.length===6?t[2]:void 0;if(i.length===3&&i.every(e=>/^\d+$/.test(e))&&(a===void 0||/^\d*$/.test(a)))return{code:n,open:e,hasArguments:!0}},getSgrTokens=e=>{let t=e.split(`;`),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.includes(`:`)){let e=getColonColorToken(r);e&&n.push(e);continue}let i=r===``?0:Number.parseInt(r,10);if(Number.isFinite(i)){if(i===38||i===48||i===58){if(e+1>=t.length)break;let r=Number.parseInt(t[e+1],10),a=Number.parseInt(t[e+2],10);if(r===5&&Number.isFinite(a)){n.push({code:i,open:[i,r,a].join(`;`),hasArguments:!0}),e+=2;continue}let s=Number.parseInt(t[e+2],10),c=Number.parseInt(t[e+3],10),l=Number.parseInt(t[e+4],10);if(r===2&&Number.isFinite(s)&&Number.isFinite(c)&&Number.isFinite(l)){n.push({code:i,open:[i,r,s,c,l].join(`;`),hasArguments:!0}),e+=4;continue}break}n.push({code:i,open:String(i),hasArguments:!1})}}return n},removeActiveStyle=(e,t)=>{let n=e.findIndex(e=>e.family===t);n!==-1&&e.splice(n,1)},upsertActiveStyle=(e,t)=>{removeActiveStyle(e,t.family),e.push(t)},removeModifierStylesByClose=(e,t)=>{for(let n=e.length-1;n>=0;n--){let r=e[n];r.family.startsWith(`modifier-`)&&r.close===t&&e.splice(n,1)}},getColorStyle=e=>{let{code:t,open:n,hasArguments:r}=e;if(t>=30&&t<=37||t>=90&&t<=97||t===38&&r)return{family:`foreground`,open:n,close:39};if(t>=40&&t<=47||t>=100&&t<=107||t===48&&r)return{family:`background`,open:n,close:49};if(t===58&&r)return{family:`underlineColor`,open:n,close:59}},applySgrResetCode=(e,t)=>e===0?(t.length=0,!0):e===39?(removeActiveStyle(t,`foreground`),!0):e===49?(removeActiveStyle(t,`background`),!0):e===59?(removeActiveStyle(t,`underlineColor`),!0):Ir.has(e)?(removeModifierStylesByClose(t,e),!0):!1,Vr=/* @__PURE__ */ t((e,t)=>{let{code:n}=e;if(applySgrResetCode(n,t))return;let r=getColorStyle(e);if(r){upsertActiveStyle(t,r);return}let i=Or.codes.get(n);i!==void 0&&i!==0&&upsertActiveStyle(t,{family:`modifier-${n}`,open:e.open,close:i})},`applySgrToken`),applySgrParameters=(e,t)=>{for(let n of getSgrTokens(e))Vr(n,t)},applySgrResets=(e,t)=>{for(let{code:n}of getSgrTokens(e))applySgrResetCode(n,t)},applyLeadingSgrResets=(e,t,n)=>{let r=t;for(;r<e.length;){let t=matchAnsiEscape(e,r);if(!t)break;t.groups.sgr!==void 0&&applySgrResets(t.groups.sgr,n),r+=t[0].length}},getClosingSgrSequence=e=>[...e].reverse().map(e=>wrapAnsiCode(e.close)).join(``),getOpeningSgrSequence=e=>e.map(e=>wrapAnsiCode(e.open)).join(``),wrapWord=(e,t,n,r)=>{let i=getTokens(t),a=r;for(let t=0;t<i.length;t++){let r=i[t];r.width>0&&a>0&&a+r.width>n&&(e.push(``),a=0),e[e.length-1]+=r.value,a+=r.width,a===n&&t<i.length-1&&(e.push(``),a=0)}return!a&&e.at(-1).length>0&&e.length>1&&(e[e.length-2]+=e.pop()),getWidth(e.at(-1))},stringVisibleTrimSpacesRight=e=>{if(!e.includes(` `))return e;let t=[];forEachSegment(e,e=>{t.push({value:e,isEscape:!1})},e=>{t.push({value:e,isEscape:!0})});for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.isEscape)continue;let r=n.value.length;for(;r>0&&n.value[r-1]===` `;)r--;if(n.value=n.value.slice(0,r),getStringWidth(n.value)>0)break}return t.map(e=>e.value).join(``)},expandTabs=e=>{if(!e.includes(` `))return e;let t=0,n=``,r=``,expandPlainText=e=>{let i=e.split(` `);for(let[e,a]of i.entries())if(n+=a,r+=a,e<i.length-1){t+=getStringWidth(r),r=``;let e=8-t%8;n+=` `.repeat(e),t+=e}};return forEachSegment(e,expandPlainText,e=>{n+=e}),n},restoreStylesAcrossRows=e=>{let t=``,n,r=[],i=0,a=0;for(;i<e.length;){zr.lastIndex=i;let s=zr.exec(e);if(!s)break;if(i=s.index,s[0]!==`
146
+ `){let t=matchAnsiEscape(e,i);if(!t){i++;continue}let{groups:a}=t;a.sgr===void 0?a.uri!==void 0&&(n=a.uri.length===0?void 0:{parameters:a.parameters,uri:a.uri}):applySgrParameters(a.sgr,r),i+=t[0].length}else if(t+=e.slice(a,i),i>a&&(n&&(t+=wrapAnsiHyperlink(``)),t+=getClosingSgrSequence(r)),t+=`
147
+ `,i++,a=i,i<e.length&&e[i]!==`
148
+ `){let a=[...r];applyLeadingSgrResets(e,i,a),t+=getOpeningSgrSequence(a),n&&(t+=wrapAnsiHyperlink(n.uri,n.parameters))}}return t+e.slice(a)},exec=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=splitWords(e),i=[``],a=0,s=-1,c=!0;for(let e of r){let r=i.length-1;if(n.trim!==!1&&s!==r){let e=i[r],t=e.trimStart();t.length!==e.length&&(i[r]=t,a=getWidth(t)),t.length>0&&(s=r)}if(c?c=!1:(a>=t&&(n.wordWrap===!1||n.trim===!1)&&(i.push(``),a=0),(a>0||n.trim===!1)&&(i[i.length-1]+=` `,a++)),n.hard&&n.wordWrap!==!1&&e.width>t){let n=t-a,r=1+Math.floor((e.width-n-1)/t);Math.floor((e.width-1)/t)<r&&(i.push(``),a=0),a=wrapWord(i,e.value,t,a)}else{if(a+e.width>t&&a>0&&e.width>0){if(n.wordWrap===!1&&a<t){a=wrapWord(i,e.value,t,a);continue}i.push(``),a=0}a+e.width>t&&n.wordWrap===!1?a=wrapWord(i,e.value,t,a):(i[i.length-1]+=e.value,a+=e.width)}}return n.trim!==!1&&(i=i.map(e=>stringVisibleTrimSpacesRight(e))),restoreStylesAcrossRows(i.join(`
149
+ `))},normalizeText=e=>{let t=``;return forEachSegment(e,e=>{t+=e.normalize()},e=>{t+=e}),t};function wrapAnsi(e,t,n){return normalizeText(String(e)).replaceAll(`\r
150
150
  `,`
151
151
  `).split(`
152
- `).map(e=>exec(e,t,n)).join(`
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
- `),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?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
- `);let c=e.split(`
159
- `);return s+=c.map(e=>a+colorizeBorder(r.left)+colorizeContent(e)+colorizeBorder(r.right)).join(`
160
- `),n.borderStyle!==Nr&&(s+=`
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&&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)}};
152
+ `).map(e=>exec(expandTabs(e),t,n)).join(`
153
+ `)}function isFullwidthCodePoint(e){return Number.isInteger(e)?isFullwidth(e)||isWide(e):!1}const Hr=/* @__PURE__ */ new Set([27,144,152,155,156,157,158,159]),Ur=`\x1B]8;`,Wr=`8;`,Gr=`${Ur};`,Kr=`${Wr};`,qr=`0`.codePointAt(0),Jr=`9`.codePointAt(0),Yr=`;`.codePointAt(0),Xr=`:`.codePointAt(0),Zr=`0`.codePointAt(0),Qr=`?`.codePointAt(0),$r=` `.codePointAt(0),ei=`/`.codePointAt(0),ti=`@`.codePointAt(0),ni=`~`.codePointAt(0),ri=/\p{Emoji_Presentation}/v,ii=new Intl.Segmenter(void 0,{granularity:`grapheme`}),ai=/* @__PURE__ */ new Set;for(let[,e]of Or.codes)ai.add(e);function isSgrParameterCharacter(e){return e>=qr&&e<=Jr||e===Yr||e===Xr}function isCsiParameterCharacter(e){return e>=Zr&&e<=Qr}function isCsiIntermediateCharacter(e){return e>=$r&&e<=ei}function isCsiFinalCharacter(e){return e>=ti&&e<=ni}function isRegionalIndicatorCodePoint(e){return e>=127462&&e<=127487}function createControlParseResult(e,t){return{token:{type:`control`,code:e},endIndex:t}}function isEmojiStyleGrapheme(e){if(ri.test(e))return!0;for(let t of e){let e=t.codePointAt(0);if(e===65039||e===8419)return!0}return!1}function getGraphemeWidth(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(isFullwidthCodePoint(e))return 2;isRegionalIndicatorCodePoint(e)&&t++}return t>=1||isEmojiStyleGrapheme(e)?2:1}function getSgrPrefix(e){return e.startsWith(`›`)?`›`:`\x1B[`}function createSgrCode(e,t){return`${e}${t.join(`;`)}m`}function getSgrFragments(e){let t=[],n=getSgrPrefix(e),r;if(e.startsWith(`\x1B[`))r=e.slice(2,-1);else if(e.startsWith(`›`))r=e.slice(1,-1);else return t;let i=r.length===0?[`0`]:r.split(`;`),a=0;for(;a<i.length;){let e=Number.parseInt(i[a],10);if(Number.isNaN(e)){a++;continue}if(e===0){t.push({type:`reset`}),a++;continue}if(e===38||e===48){let r=Number.parseInt(i[a+1],10);if(r===5&&a+2<i.length){let r=createSgrCode(n,i.slice(a,a+3));t.push({type:`start`,code:r,endCode:Or.color.ansi(e===38?39:49)}),a+=3;continue}if(r===2&&a+4<i.length){let r=createSgrCode(n,i.slice(a,a+5));t.push({type:`start`,code:r,endCode:Or.color.ansi(e===38?39:49)}),a+=5;continue}let s=createSgrCode(n,[i[a]]);t.push({type:`start`,code:s,endCode:Or.color.ansi(e===38?39:49)}),a++;continue}if(ai.has(e)){t.push({type:`end`,endCode:Or.color.ansi(e)}),a++;continue}let r=Or.codes.get(e);if(r!==void 0){let e=createSgrCode(n,[i[a]]);t.push({type:`start`,code:e,endCode:Or.color.ansi(r)}),a++;continue}let s=createSgrCode(n,[i[a]]);t.push({type:`start`,code:s,endCode:Or.reset.open}),a++}return t.length===0&&t.push({type:`reset`}),t}function parseCsiCode(e,t){let n=e.codePointAt(t),r;if(n===27){if(e[t+1]!==`[`)return;r=t+2}else if(n===155)r=t+1;else return;let i=!0;for(let n=r;n<e.length;n++){let r=e.codePointAt(n);if(isCsiFinalCharacter(r)){let r=e.slice(t,n+1);return e[n]!==`m`||!i?createControlParseResult(r,n+1):{token:{type:`sgr`,code:r,fragments:getSgrFragments(r)},endIndex:n+1}}if(isCsiParameterCharacter(r)){isSgrParameterCharacter(r)||(i=!1);continue}if(isCsiIntermediateCharacter(r)){i=!1;continue}let a=n;return createControlParseResult(e.slice(t,a),a)}return createControlParseResult(e.slice(t),e.length)}function parseHyperlinkCode(e,t){let n,r,i=e.codePointAt(t);if(i===27&&e.startsWith(Ur,t))n=Ur,r=Gr;else if(i===157&&e.startsWith(Wr,t))n=Wr,r=Kr;else return;let a=e.indexOf(`;`,t+n.length);if(a===-1)return createControlParseResult(e.slice(t),e.length);for(let n=a+1;n<e.length;n++){let i=e[n];if(i===`\x07`)return{token:{type:`hyperlink`,code:e.slice(t,n+1),action:n===a+1?`close`:`open`,closePrefix:r,terminator:`\x07`},endIndex:n+1};if(i===`\x1B`&&e[n+1]===`\\`)return{token:{type:`hyperlink`,code:e.slice(t,n+2),action:n===a+1?`close`:`open`,closePrefix:r,terminator:`\x1B\\`},endIndex:n+2};if(i===`œ`)return{token:{type:`hyperlink`,code:e.slice(t,n+1),action:n===a+1?`close`:`open`,closePrefix:r,terminator:`œ`},endIndex:n+1}}return createControlParseResult(e.slice(t),e.length)}function parseControlStringCode(e,t){let n=e.codePointAt(t),r,i=!1;switch(n){case 27:switch(e[t+1]){case`]`:r=t+2,i=!0;break;case`P`:case`X`:case`^`:case`_`:r=t+2;break;case`\\`:return createControlParseResult(`\x1B\\`,t+2);default:return}break;case 157:r=t+1,i=!0;break;case 144:case 152:case 158:case 159:r=t+1;break;case 156:return createControlParseResult(`œ`,t+1);default:return}for(let n=r;n<e.length;n++){if(i&&e[n]===`\x07`)return createControlParseResult(e.slice(t,n+1),n+1);if(e[n]===`\x1B`&&e[n+1]===`\\`)return createControlParseResult(e.slice(t,n+2),n+2);if(e[n]===`œ`)return createControlParseResult(e.slice(t,n+1),n+1)}return createControlParseResult(e.slice(t),e.length)}function parseAnsiCode(e,t){let n=e.codePointAt(t);if(n===27||n===157){let n=parseHyperlinkCode(e,t);if(n)return n}return parseControlStringCode(e,t)||parseCsiCode(e,t)}function appendTrailingAnsiTokens(e,t,n){for(;t<e.length;){let r=e.codePointAt(t);if(!Hr.has(r))break;let i=parseAnsiCode(e,t);if(!i)break;n.push(i.token),t=i.endIndex}return t}function parseCharacterTokenWithRawSegmentation(e,t,n){let r=n.containing(t);if(r&&r.index===t)return{token:{type:`character`,value:r.segment,visibleWidth:getGraphemeWidth(r.segment),isGraphemeContinuation:!1},endIndex:t+r.segment.length}}function collectVisibleCharacters(e){let t=[],n=0;for(;n<e.length;){let r=e.codePointAt(n);if(Hr.has(r)){let t=parseAnsiCode(e,n);if(t){n=t.endIndex;continue}}let i=String.fromCodePoint(r);t.push({value:i,visibleWidth:1,isGraphemeContinuation:!1}),n+=i.length}return t}function applyGraphemeMetadata(e){if(e.length===0)return;let t=e.map(({value:e})=>e).join(``),n=[],r=0;for(let t of e)n.push(r),r+=t.value.length;let i=0;for(let r of ii.segment(t)){for(;i<e.length&&n[i]<r.index;)i++;let t=i,a=!0;for(;t<e.length&&n[t]<r.index+r.segment.length;)e[t].visibleWidth=a?getGraphemeWidth(r.segment):0,e[t].isGraphemeContinuation=!a,a=!1,t++;i=t}}function tokenizeAnsiWithVisibleSegmentation(e,{endCharacter:t=1/0}={}){let n=[],r=collectVisibleCharacters(e);applyGraphemeMetadata(r);let i=0,a=0,s=0;for(;i<e.length;){let c=e.codePointAt(i);if(Hr.has(c)){let t=parseAnsiCode(e,i);if(t){n.push(t.token),i=t.endIndex;continue}}let l=String.fromCodePoint(c),u=r[a],f=isFullwidthCodePoint(c)?2:l.length;u&&(f=u.visibleWidth);let p={type:`character`,value:l,visibleWidth:f,isGraphemeContinuation:u?u.isGraphemeContinuation:!1};if(n.push(p),i+=l.length,a++,s+=p.visibleWidth,s>=t){let t=r[a];if(!t||!t.isGraphemeContinuation){i=appendTrailingAnsiTokens(e,i,n);break}}}return n}function areValuesInSameGrapheme(e,t){let n=`${e}${t}`,r=e.length;for(let e of ii.segment(n)){if(e.index===r)return!1;if(e.index>r)return!0}return!0}function hasAnsiSplitContinuationAhead(e,t,n,r){if(!n)return!1;let i=t,a=!1;for(;i<e.length;){let t=e.codePointAt(i);if(Hr.has(t)){let t=parseAnsiCode(e,i);if(t){a=!0,i=t.endIndex;continue}}if(!a)return!1;let s=parseCharacterTokenWithRawSegmentation(e,i,r);return!s||areValuesInSameGrapheme(n,s.token.value)}return!1}function tokenizeAnsi(e,{endCharacter:t=1/0}={}){let n=[],r=ii.segment(e),i=0,a=0,s,c=!1;for(;i<e.length;){let l=e.codePointAt(i);if(Hr.has(l)){let t=parseAnsiCode(e,i);if(t){n.push(t.token),i=t.endIndex,c=!0;continue}}let u=parseCharacterTokenWithRawSegmentation(e,i,r);if(!u||c&&s&&areValuesInSameGrapheme(s,u.token.value))return tokenizeAnsiWithVisibleSegmentation(e,{endCharacter:t});if(n.push(u.token),i=u.endIndex,a+=u.token.visibleWidth,c=!1,s=u.token.value,a>=t){if(hasAnsiSplitContinuationAhead(e,i,s,r))return tokenizeAnsiWithVisibleSegmentation(e,{endCharacter:t});i=appendTrailingAnsiTokens(e,i,n);break}}return n}function applySgrFragments(e,t){for(let n of t)switch(n.type){case`reset`:e.clear();break;case`end`:e.delete(n.endCode);break;case`start`:e.delete(n.endCode),e.set(n.endCode,n.code)}return e}function undoAnsiCodes(e){return[...e.keys()].toReversed().join(``)}function closeHyperlink(e){return`${e.closePrefix}${e.terminator}`}function shouldIncludeSgrAfterEnd(e,t){let n=!1,r=!1;for(let i of e.fragments)i.type===`start`?n=!0:(i.type===`reset`&&t.size>0||i.type===`end`&&t.has(i.endCode))&&(r=!0);return r&&!n}function hasSgrStartFragment(e){return e.fragments.some(e=>e.type===`start`)}function discardPendingHyperlink(e){if(e.activeHyperlink&&!e.activeHyperlinkHasVisibleText&&e.activeHyperlinkOutputIndex!==void 0){let t=e.activeHyperlink.code.length;e.returnValue=e.returnValue.slice(0,e.activeHyperlinkOutputIndex)+e.returnValue.slice(e.activeHyperlinkOutputIndex+t),e.pendingSgrOutputIndex!==void 0&&e.pendingSgrOutputIndex>e.activeHyperlinkOutputIndex&&(e.pendingSgrOutputIndex-=t)}e.activeHyperlink=void 0,e.activeHyperlinkHasVisibleText=!1,e.activeHyperlinkOutputIndex=void 0}function settleActiveHyperlink(e){e.activeHyperlinkHasVisibleText?e.returnValue+=closeHyperlink(e.activeHyperlink):discardPendingHyperlink(e)}function applySgrToken(e){(!e.isPastEnd||shouldIncludeSgrAfterEnd(e.token,e.activeStyles))&&(e.include&&hasSgrStartFragment(e.token)&&e.pendingSgrOutputIndex===void 0&&(e.pendingSgrOutputIndex=e.returnValue.length,e.pendingSgrActiveStyles=new Map(e.activeStyles)),e.activeStyles=applySgrFragments(e.activeStyles,e.token.fragments),e.include&&(e.returnValue+=e.token.code))}function applyHyperlinkToken(e){if(!e.isPastEnd||e.token.action===`close`&&e.activeHyperlink){if(e.token.action===`open`)e.activeHyperlink&&settleActiveHyperlink(e),e.activeHyperlink=e.token,e.activeHyperlinkHasVisibleText=!1,e.activeHyperlinkOutputIndex=void 0,e.include&&(e.activeHyperlinkOutputIndex=e.returnValue.length);else if(e.token.action===`close`){if(e.include&&e.activeHyperlink&&!e.activeHyperlinkHasVisibleText){discardPendingHyperlink(e);return}e.activeHyperlink=void 0,e.activeHyperlinkHasVisibleText=!1,e.activeHyperlinkOutputIndex=void 0}e.include&&(e.returnValue+=e.token.code)}}function applyControlToken(e){!e.isPastEnd&&e.include&&(e.returnValue+=e.token.code)}function applyCharacterToken(e){!e.include&&e.position>=e.start&&!e.token.isGraphemeContinuation&&(e.include=!0,e.returnValue=[...e.activeStyles.values()].join(``),e.activeHyperlink&&(e.activeHyperlinkOutputIndex=e.returnValue.length,e.returnValue+=e.activeHyperlink.code)),e.include&&(e.returnValue+=e.token.value,e.pendingSgrOutputIndex=void 0,e.pendingSgrActiveStyles=void 0,e.activeHyperlink&&(e.activeHyperlinkHasVisibleText=!0)),e.position+=e.token.visibleWidth}const oi={sgr:applySgrToken,hyperlink:applyHyperlinkToken,control:applyControlToken,character:applyCharacterToken};function applyToken(e){oi[e.token.type]?.(e)}function createHasContinuationAheadMap(e){let t=Array.from({length:e.length},()=>!1),n=!1;for(let r=e.length-1;r>=0;r--){let i=e[r];t[r]=n,i.type===`character`&&(n=!!i.isGraphemeContinuation)}return t}function isPastEndBoundary(e,t,n){return n===void 0?!1:t>=n||e.type===`character`&&!e.isGraphemeContinuation&&t+e.visibleWidth>n}function sliceAnsi(e,t,n){let r=tokenizeAnsi(e,{endCharacter:n}),i=createHasContinuationAheadMap(r),a={start:t,token:void 0,isPastEnd:!1,activeStyles:/* @__PURE__ */ new Map,activeHyperlink:void 0,activeHyperlinkHasVisibleText:!1,activeHyperlinkOutputIndex:void 0,pendingSgrOutputIndex:void 0,pendingSgrActiveStyles:void 0,position:0,returnValue:``,include:!1};for(let[e,t]of r.entries()){let r=isPastEndBoundary(t,a.position,n);if(r&&t.type!==`character`&&i[e]&&(r=!1),r&&t.type===`character`&&!t.isGraphemeContinuation){a.activeHyperlink&&!a.activeHyperlinkHasVisibleText&&discardPendingHyperlink(a),a.pendingSgrOutputIndex!==void 0&&(a.returnValue=a.returnValue.slice(0,a.pendingSgrOutputIndex),a.activeStyles=a.pendingSgrActiveStyles,a.pendingSgrOutputIndex=void 0,a.pendingSgrActiveStyles=void 0);break}a.token=t,a.isPastEnd=r,applyToken(a)}return a.include?(a.activeHyperlink&&settleActiveHyperlink(a),a.returnValue+=undoAnsiCodes(a.activeStyles),a.returnValue):``}const si=`none`,ci=/\r\n|[\n\v\f\r]/gv,li=/^(?:\u{1B}\[[0-9:;]*m|\u{1B}\]8;[^\u{0}-\u{1F};\u{7F}]*;[^\u{0}-\u{1F}\u{7F}]*(?:\u{7}|\u{1B}\\))$/v,ui=/(\u{1B}\].*?(?:\u{7}|\u{1B}\\|$)|\u{1B}\[[\u{20}-\u{3F}]*[\u{40}-\u{7E}]|\u{1B}[^\u{7}\u{5B}\u{5D}]?)/gsv,writeControls=e=>{let t=e.split(ui),n=[];for(let[e,r]of t.entries())if(e%2==1)li.test(r)&&n.push(r);else for(let e of r.replaceAll(` `,` `))if(e===`\b`){let e=n.findLastIndex(e=>!e.startsWith(`\x1B`));e!==-1&&n[e]!==`
154
+ `&&n.splice(e,1)}else n.push(e);return n.join(``)},terminalColumns=()=>R.stdout?.columns||R.stderr?.columns||Number(R.env.COLUMNS)||80,terminalRows=()=>R.stdout?.rows||R.stderr?.rows||Number(R.env.LINES),getObject=e=>{let t=typeof e==`number`?{top:e,right:e*3,bottom:e,left:e*3}:{top:0,right:0,bottom:0,left:0,...e};for(let e of[`top`,`right`,`bottom`,`left`]){let n=Number(t[e]);t[e]=Number.isFinite(n)?Math.max(0,Math.floor(n)):0}return t},getBorderWidth=e=>{if(e===si)return 0;let{left:t,right:n}=getBorderChars(e);return stringWidth(t||` `)+stringWidth(n||` `)},getBorderHeight=e=>e===si?0:2,getCornerWidths=e=>{let{topLeft:t,topRight:n,bottomLeft:r,bottomRight:i}=getBorderChars(e);return{top:stringWidth(t)+stringWidth(n),bottom:stringWidth(r)+stringWidth(i)}},sanitizeSize=(e,t,n=1)=>{let r=Number(e);return Number.isFinite(r)&&r>0?Math.max(n,r-t):void 0},wrapLine=(e,t)=>stringWidth(e)>t?wrapAnsi(e,t,{hard:!0}):e,isValidSize=e=>{let t=Number(e);return Number.isFinite(t)&&t>0},alignText=(e,t,n)=>t===`left`?e:e.split(`
155
+ `).map(e=>{let r=Math.max(0,n-stringWidth(e));return` `.repeat(t===`right`?r:Math.floor(r/2))+e}).join(`
156
+ `),getBorderChars=e=>{let t=[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`,`left`,`right`,`top`,`bottom`],n;if(e===si&&(e=Object.fromEntries(t.map(e=>[e,``]))),typeof e==`string`){if(n=Object.hasOwn(Tr,e)?Tr[e]:void 0,!n)throw TypeError(`Invalid border style: ${e}`)}else{e={...e,left:e?.left??e?.vertical,right:e?.right??e?.vertical,top:e?.top??e?.horizontal,bottom: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 Object.fromEntries(t.map(e=>[e,writeControls(n[e].replaceAll(ci,` `)).toWellFormed()]))},makeLabel=(e,t,n)=>{let r=``,i=stringWidth(e);switch(n){case`left`:r=e+sliceAnsi(t,i);break;case`right`:r=sliceAnsi(t,i)+e;break;default:{let n=Math.max(0,stringWidth(t)-i);n%2==1?(t=sliceAnsi(t,Math.floor(n/2)+i),r=sliceAnsi(t,1)+e+t):(t=sliceAnsi(t,n/2+i),r=t+e+t);break}}return r},makeContentText=(e,{padding:t,width:n,textAlignment:r,height:i})=>{let a=n-t.left-t.right,s=e.split(`
157
+ `).map(e=>wrapLine(e,a)).join(`
158
+ `),c=Math.min(a,widestLine(s)),l=alignText(s,r,c),u=0;r===`right`?u=a-c:r===`center`&&(u=Math.floor((a-c)/2));let f=l.split(`
159
+ `).map(e=>` `.repeat(u)+e),p=` `.repeat(t.left),m=` `.repeat(t.right);return f=f.map(e=>{let t=p+e+m;return t+` `.repeat(Math.max(0,n-stringWidth(t)))}),i!==void 0&&f.length>Math.max(0,i-t.top-t.bottom)&&(f=f.slice(0,i-t.top-t.bottom)),t.top>0&&(f=[...Array.from({length:t.top},()=>` `.repeat(n)),...f]),t.bottom>0&&(f=[...f,...Array.from({length:t.bottom},()=>` `.repeat(n))]),i!==void 0&&f.length<i&&(f=[...f,...Array.from({length:i-f.length},()=>` `.repeat(n))]),f.join(`
160
+ `)},fillBar=(e,t)=>{let n=e||` `,r=Math.ceil(Math.max(0,t)/Math.max(1,stringWidth(n)));return sliceAnsi(n.repeat(r),0,Math.max(0,t))},boxContent=(e,t,n)=>{let colorizeBorder=e=>{let t=n.borderColor?getColorFunction(n.borderColor)(e):e,r=t;return n.borderBackgroundColor!==void 0&&(n.borderBackgroundColor===`inherit`?n.backgroundColor&&(r=getBGColorFunction(n.backgroundColor)(t)):r=getBGColorFunction(n.borderBackgroundColor)(t)),n.dimBorder?wr.dim(r):r},colorizeContent=e=>n.backgroundColor?getBGColorFunction(n.backgroundColor)(e):e,colorizeTitle=e=>n.titleColor?getColorFunction(n.titleColor)(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=[],c=n.borderStyle!==si,l=c?r.left||` `:``,u=c?r.right||` `:``,f=t+stringWidth(l)+stringWidth(u),bar=(e,t,n,r,i)=>{let a=Math.max(0,f-stringWidth(t)-stringWidth(n)),s=fillBar(e,a),c=r?makeLabel(r,s,i):s;return sliceAnsi(c+` `.repeat(Math.max(0,a-stringWidth(c))),0,Math.max(0,a))};if(n.borderStyle!==si||n.title){let e=bar(r.top,r.topLeft,r.topRight,n.title?colorizeTitle(n.title):``,n.titleAlignment);s.push(a+colorizeBorder(r.topLeft+e+r.topRight))}let p=e===``?[]:e.split(`
161
+ `);for(let e of p){let n=e+` `.repeat(Math.max(0,t-stringWidth(e)));s.push(a+colorizeBorder(l)+colorizeContent(n)+colorizeBorder(u))}if(n.borderStyle!==si||n.footer){let e=bar(r.bottom,r.bottomLeft,r.bottomRight,n.footer??``,n.footerAlignment);s.push(a+colorizeBorder(r.bottomLeft+e+r.bottomRight))}return`
162
+ `.repeat(n.margin.top)+s.join(`
163
+ `)+`
164
+ `.repeat(n.margin.bottom)},sanitizeOptions=e=>{if(e.fullscreen&&R?.stdout){let t=[terminalColumns(),terminalRows()];typeof e.fullscreen==`function`&&(t=e.fullscreen(...t)),isValidSize(e.width)||(e.width=t[0]),isValidSize(e.height)||(e.height=t[1])}let t=getBorderWidth(e.borderStyle);return e.width=sanitizeSize(e.width,t),e.maxWidth=sanitizeSize(e.maxWidth,t),e.height=sanitizeSize(e.height,getBorderHeight(e.borderStyle),0),e},labelFrame=e=>e===si?0:2,formatLabel=(e,t)=>t===si?e:` ${e} `,fitLabel=(e,t,n,r)=>e&&(e=writeControls(e.replaceAll(ci,` `)).toWellFormed(),e=sliceAnsi(e,0,Math.max(0,t+getBorderWidth(n)-r-labelFrame(n))),e&&formatLabel(e,n)),determineDimensions=(e,t)=>{t=sanitizeOptions(t);let n=t.width!==void 0,r=terminalColumns(),i=getBorderWidth(t.borderStyle),a=getCornerWidths(t.borderStyle),s=Math.max(a.top,a.bottom),c=r-i,l=Math.min(c,t.maxWidth||c),marginWidth=()=>{switch(t.float){case`center`:return 0;case`right`:return t.margin.right;default:return t.margin.left+t.margin.right}},u=n?r-i-(t.float===`left`?t.margin.left:0):c-marginWidth(),f=Math.max(1,l-t.padding.left-t.padding.right),p=widestLine(e.split(`
165
+ `).map(e=>wrapLine(e,f)).join(`
166
+ `)),m=Math.min(p+t.padding.left+t.padding.right,l);if(t.width||=m,(t.margin.left||t.margin.right)&&Math.max(1,t.width)>u){let e=(r-Math.max(1,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))}let h=n?t.width:Math.min(r-i-marginWidth(),l);if(t.title=fitLabel(t.title,h,t.borderStyle,a.top),t.footer=fitLabel(t.footer,h,t.borderStyle,a.bottom),getBorderHeight(t.borderStyle)===0&&t.height!==void 0&&(t.height=Math.max(0,t.height-+!!t.title-!!t.footer)),!n){for(let[e,n]of[[t.title,a.top],[t.footer,a.bottom]])e&&(m=Math.max(m,stringWidth(e)-i+n));t.width=Math.max(1,Math.min(m,r-i-marginWidth()))}return t.width=Math.max(t.width,s-i,1),t.padding.left+t.padding.right>=t.width&&(t.padding.left=0,t.padding.right=0),t.height!==void 0&&t.padding.top+t.padding.bottom>=t.height&&(t.padding.top=0,t.padding.bottom=0),t},di=/* @__PURE__ */ new Set([`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`gray`,`grey`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`]),isHex=e=>/^#(?:[\da-f]{3}){1,2}$/iv.test(e),isColorValid=e=>typeof e==`string`&&(di.has(e)||isHex(e)),getColorFunction=e=>isHex(e)?wr.hex(e):wr[e],getBGColorFunction=e=>isHex(e)?wr.bgHex(e):wr[`bg${e[0].toUpperCase()}${e.slice(1)}`];function boxen$1(e,t){if(e=writeControls(e.replaceAll(ci,`
167
+ `)).toWellFormed(),t={padding:0,dimBorder:!1,float:`left`,...t},t.borderStyle??=`single`,t.textAlignment??=t.align??`left`,t.titleAlignment??=`left`,t.footerAlignment??=`left`,t.borderColor&&!isColorValid(t.borderColor))throw Error(`${t.borderColor} is not a valid borderColor`);if(t.titleColor&&!isColorValid(t.titleColor))throw Error(`${t.titleColor} is not a valid titleColor`);if(t.backgroundColor&&!isColorValid(t.backgroundColor))throw Error(`${t.backgroundColor} is not a valid backgroundColor`);if(`borderBackgroundColor`in t||(t.borderBackgroundColor=`inherit`),t.borderBackgroundColor!==void 0&&t.borderBackgroundColor!==`inherit`&&!isColorValid(t.borderBackgroundColor))throw Error(`${t.borderBackgroundColor} is not a valid borderBackgroundColor`);return t.padding=getObject(t.padding),t.margin=getObject(t.margin),t=determineDimensions(e,t),e=makeContentText(e,t),boxContent(e,Math.max(t.width,widestLine(e)),t)}t(boxen$1,`boxen`);const U=D.getChild(`cli`);function createLikeC4Logger(e){let t=D.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]=sn(e),r=t*1e3+n/1e6;return{ms:r,pretty:Oe(r)}}function startTimer(e){let t=sn();return{stopAndLog(n=`done in `){n=m.green(`${n}${inMillis(t).pretty}`),(e||U).info(n)}}}function boxen(e,t){console.log(boxen$1(e,{padding:1,margin:1,dimBorder:!0,...t}))}const toPath=e=>e instanceof URL?hn(e):e;function findUpSync(e,{cwd:t=R.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=L.statSync(t,{throwIfNoEntry:!1});if(n===`file`&&e?.isFile()||n===`directory`&&e?.isDirectory())return t}catch{}i=N.dirname(i)}}function packageUpSync({cwd:e=R.cwd()}={}){return findUpSync(`package.json`,{cwd:e})}const fi=createLikeC4Logger(`vite`),pi=ht(hn(import.meta.url));function findPkgRoot(){let e=packageUpSync({cwd:pi});if(!e)throw Error(`likec4 package folder not found`);return ht(e)}function viteAppRoot(){let e=findPkgRoot(),t=[F(e,`__app__`),F(pi,`../__app__`),F(pi,`../../__app__`),F(pi,`../../dist/__app__`)],n=ie(t,It);if(!n)throw D.error(`likec4 app root does not exist, tried:\n${t.join(`
168
+ `)}`),Error(`likec4 app root does not exist`);return n}async function mkTempPublicDir(){let e=await st(yt(pn(),`.likec4-public-`));return await M(yt(e,`likec4-views.js`),`// generated by likec4
169
+ `),e}function relativeToCwd(e){return P(an(),e)}async function copyUserPublicDir(e,t){if(!It(e))throw Error(`--public directory does not exist: ${e}`);if(!Vt(e).isDirectory())throw Error(`--public path is not a directory: ${e}`);let n=await ut(e);return await at(e,t,{recursive:!0,errorOnExist:!1}),n}const mi=[`react`,`react-dom`];function viteAliases(){let e=findPkgRoot();return{"likec4/react":F(e,`react/index.mjs`),"likec4/model":F(e,`dist/model/index.mjs`),"likec4/vite-plugin/internal":F(e,`dist/vite-plugin/internal/index.mjs`)}}const viteConfig=async({languageServices:e,likec4AssetsDir:t,...n})=>{let r=n.customLogger??fi,i=viteAppRoot();r.info(`${m.cyan(`likec4 app root`)} ${m.dim(relativeToCwd(i))}`);let a=n.outputDir??F(e.workspace,`dist`);r.info(m.cyan(`outDir`)+` `+m.dim(relativeToCwd(a)));let s=`/`;n.base&&(s=Ae(n.base),!Me(s)&&s!==`./`&&(s=Ne(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:$t,likec4AssetsDir:t,webcomponentPrefix:c,title:l,root:i,languageServices:e,clearScreen:!1,base:s,resolve:{alias:{...viteAliases(),"likec4/previews":t},dedupe:mi},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:[F(i,`index.html`),F(i,`src`,`main.mjs`),F(i,`src`,`fonts.css`),F(i,`src`,`style.css`)],onLog(e,t,n){t.code!==`MODULE_LEVEL_DIRECTIVE`&&n(e,t)}}}},customLogger:r,plugins:[De({languageServices:e.languageServices,webcomponentPrefix:c,title:l,useHashHistory:n.useHashHistory,theme:n.theme,customization:n.customization}),xn(),u?Sn():void 0]}};function viteWebcomponentConfig({languageServices:e,outDir:t,base:n,webcomponentPrefix:r=`likec4`,filename:i=`likec4-views.js`,customization:a}){let s=createLikeC4Logger([`vite`,`webcomponent`]),c=viteAppRoot();return s.info(m.cyan(`outDir`)+` `+m.dim(t)),{root:c,clearScreen:!1,base:n,configFile:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases(),dedupe:mi},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`},rolldownOptions:{onLog(e,t,n){t.code!==`MODULE_LEVEL_DIRECTIVE`&&n(e,t)}}},customLogger:s,plugins:[De({ai:`disabled`,languageServices:e.languageServices,webcomponentPrefix:r,customization:a})]}}const hi=[`favicon.ico`,`robots.txt`];function removeAllButPreserved(e,t){let n=new Set(t);for(let t of Rt(e).filter(e=>!n.has(e)))Bt(F(e,t),{recursive:!0})}const gi={".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=F(e,`index.html`);if(!It(t))return;let n=Lt(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=F(e,a.replace(/^\.?\//,``));if(!It(s))return;let c=`data:${gi[_t(s).toLowerCase()]??`application/octet-stream`};base64,${Lt(s).toString(`base64`)}`,l=r.replace(i,(e,t)=>`href=${t}${c}${t}`);Ht(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 st(yt(pn(),`.likec4-assets-`));let l=await viteConfig({...c,languageServices:r,likec4AssetsDir:i,webcomponentPrefix:t,title:n,outputSingleFile:a}),u=!It(l.build.outDir)||Rt(l.build.outDir).length===0,f=await mkTempPublicDir(),p=s?await copyUserPublicDir(s,f):[];for(let e of hi){let t=F(l.root,e);It(t)&&Ft(t,F(f,e))}let h=r.languageServices.projects();if(h.length===1){let e=await r.viewsService.computedViews(),t=[...(await r.layoutedModel()).views()].map(e=>e.$layouted);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.layoutedModel(e.id)).views()].map(e=>e.$layouted),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,customization:c.customization});await _n(e)}if(await _n({...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=F(l.build.outDir,`index.html`);It(g)&&Ft(g,F(l.build.outDir,`404.html`))}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 _i=(()=>{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})(),vi=typeof globalThis.AbortController==`function`,yi=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,bi=typeof globalThis.ReadableStream==`function`,xi=typeof globalThis.FormData==`function`,Si=[`get`,`post`,`put`,`patch`,`head`,`delete`],Ci={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},wi=2147483647,Ti=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,Ei=Symbol(`stop`);var RetryMarker=class{options;constructor(e){this.options=e}};const retry=e=>new RetryMarker(e),Di={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},Oi={next:!0},ki={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+=Ti,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)})},Ai=/* @__PURE__ */ t(e=>typeof e==`object`&&!!e,`isObject`),validateAndMerge=(...e)=>{for(let t of e)if((!Ai(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(Ai(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(Ai(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&&(!Ai(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):(Ai(n)&&e in t&&(n=deepMerge(t[e],n)),t={...t,[e]:n});Ai(s.hooks)&&(r=mergeHooks(r,s.hooks),t.hooks=r),Ai(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]:yi?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},normalizeRequestMethod=e=>Si.includes(e)?e.toUpperCase():e,ji={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{...ji,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{...ji,...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 ki)&&!(r in Di)&&(!(r in e)||r in Oi)&&(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 Mi=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 ${wi}`);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(!bi)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(Ci))(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}vi&&yi&&(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),_i&&(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&&(xi&&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(!_i)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),wi);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===Ei)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
170
  /*! MIT License © Sindre Sorhus */
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;
171
+ const createInstance=e=>{let ky=(t,n)=>Mi.create(t,validateAndMerge(e,n));for(let t of Si)ky[t]=(n,r)=>Mi.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=Ei,ky.retry=retry,ky},Ni=createInstance();var Pi=/* @__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||
172
+ /* 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}})),Fi=/* @__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):()=>{}})),Ii=/* @__PURE__ */ r(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Pi(),a=Fi();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*$`)})),Li=/* @__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})),Ri=/* @__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}})),zi=/* @__PURE__ */ r(((e,t)=>{let n=Fi(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Pi(),{safeRe:a,t:s}=Ii(),c=Li(),{compareIdentifiers:l}=Ri(),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}}})),Bi=/* @__PURE__ */ r(((e,t)=>{let n=zi(),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})),Vi=/* @__PURE__ */ r(((e,t)=>{let n=Bi(),valid=(e,t)=>{let r=n(e,t);return r?r.version:null};t.exports=valid})),Hi=/* @__PURE__ */ r(((e,t)=>{let n=Bi(),clean=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null};t.exports=clean})),Ui=/* @__PURE__ */ r(((e,t)=>{let n=zi(),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})),Wi=/* @__PURE__ */ r(((e,t)=>{let n=Bi(),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})),Gi=/* @__PURE__ */ r(((e,t)=>{let n=zi(),major=(e,t)=>new n(e,t).major;t.exports=major})),Ki=/* @__PURE__ */ r(((e,t)=>{let n=zi(),minor=(e,t)=>new n(e,t).minor;t.exports=minor})),qi=/* @__PURE__ */ r(((e,t)=>{let n=zi(),patch=(e,t)=>new n(e,t).patch;t.exports=patch})),Ji=/* @__PURE__ */ r(((e,t)=>{let n=Bi(),prerelease=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};t.exports=prerelease})),Yi=/* @__PURE__ */ r(((e,t)=>{let n=zi(),compare=(e,t,r)=>new n(e,r).compare(new n(t,r));t.exports=compare})),Xi=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),rcompare=(e,t,r)=>n(t,e,r);t.exports=rcompare})),Zi=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),compareLoose=(e,t)=>n(e,t,!0);t.exports=compareLoose})),Qi=/* @__PURE__ */ r(((e,t)=>{let n=zi(),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})),$i=/* @__PURE__ */ r(((e,t)=>{let n=Qi(),sort=(e,t)=>e.sort((e,r)=>n(e,r,t));t.exports=sort})),ea=/* @__PURE__ */ r(((e,t)=>{let n=Qi(),rsort=(e,t)=>e.sort((e,r)=>n(r,e,t));t.exports=rsort})),ta=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),gt=(e,t,r)=>n(e,t,r)>0;t.exports=gt})),na=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),lt=(e,t,r)=>n(e,t,r)<0;t.exports=lt})),ra=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),eq=(e,t,r)=>n(e,t,r)===0;t.exports=eq})),ia=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),neq=(e,t,r)=>n(e,t,r)!==0;t.exports=neq})),aa=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),gte=(e,t,r)=>n(e,t,r)>=0;t.exports=gte})),oa=/* @__PURE__ */ r(((e,t)=>{let n=Yi(),lte=(e,t,r)=>n(e,t,r)<=0;t.exports=lte})),sa=/* @__PURE__ */ r(((e,t)=>{let n=ra(),r=ia(),i=ta(),a=aa(),s=na(),c=oa(),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})),ca=/* @__PURE__ */ r(((e,t)=>{let n=zi(),r=Bi(),{safeRe:i,t:a}=Ii(),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})),la=/* @__PURE__ */ r(((e,t)=>{let n=Bi(),r=Pi(),i=zi(),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})),ua=/* @__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})),da=/* @__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(ua()),i=Li(),a=fa(),s=Fi(),c=zi(),{safeRe:l,src:u,t:f,comparatorTrimReplace:p,tildeTrimReplace:m,caretTrimReplace:h}=Ii(),{FLAG_INCLUDE_PRERELEASE:g,FLAG_LOOSE:v}=Pi(),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}})),fa=/* @__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=Li(),{safeRe:i,t:a}=Ii(),s=sa(),c=Fi(),l=zi(),u=da()})),pa=/* @__PURE__ */ r(((e,t)=>{let n=da(),satisfies=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)};t.exports=satisfies})),ma=/* @__PURE__ */ r(((e,t)=>{let n=da(),toComparators=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `));t.exports=toComparators})),ha=/* @__PURE__ */ r(((e,t)=>{let n=zi(),r=da(),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})),ga=/* @__PURE__ */ r(((e,t)=>{let n=zi(),r=da(),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})),_a=/* @__PURE__ */ r(((e,t)=>{let n=zi(),r=da(),i=ta(),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
173
  /* 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}){
174
+ default:throw Error(`Unexpected operation: ${e.operator}`)}}),s&&(!a||i(a,s))&&(a=s)}return a&&e.test(a)?a:null};t.exports=minVersion})),va=/* @__PURE__ */ r(((e,t)=>{let n=da(),validRange=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}};t.exports=validRange})),ya=/* @__PURE__ */ r(((e,t)=>{let n=zi(),r=fa(),{ANY:i}=r,a=da(),s=pa(),c=ta(),l=na(),u=oa(),f=aa(),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})),ba=/* @__PURE__ */ r(((e,t)=>{let n=ya(),gtr=(e,t,r)=>n(e,t,`>`,r);t.exports=gtr})),xa=/* @__PURE__ */ r(((e,t)=>{let n=ya(),ltr=(e,t,r)=>n(e,t,`<`,r);t.exports=ltr})),Sa=/* @__PURE__ */ r(((e,t)=>{let n=da(),intersects=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r));t.exports=intersects})),Ca=/* @__PURE__ */ r(((e,t)=>{let n=pa(),r=Yi();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}})),wa=/* @__PURE__ */ r(((e,t)=>{let n=da(),r=fa(),{ANY:i}=r,a=pa(),s=Yi(),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})),Ta=/* @__PURE__ */ n((/* @__PURE__ */ r(((e,t)=>{let n=Ii(),r=Pi(),i=zi(),a=Ri();t.exports={parse:Bi(),valid:Vi(),clean:Hi(),inc:Ui(),diff:Wi(),major:Gi(),minor:Ki(),patch:qi(),prerelease:Ji(),compare:Yi(),rcompare:Xi(),compareLoose:Zi(),compareBuild:Qi(),sort:$i(),rsort:ea(),gt:ta(),lt:na(),eq:ra(),neq:ia(),gte:aa(),lte:oa(),cmp:sa(),coerce:ca(),truncate:la(),Comparator:fa(),Range:da(),satisfies:pa(),toComparators:ma(),maxSatisfying:ha(),minSatisfying:ga(),minVersion:_a(),validRange:va(),outside:ya(),gtr:ba(),ltr:xa(),intersects:Sa(),simplifyRange:Ca(),subset:wa(),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 Ea=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),Da=Math.max(...[...Ea].map(e=>e.length)),Oa=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<=Oa}return!1}function processSegment(e,t){return!Ea.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=``,i=!1,a=`start`,s=!1,c=0;for(let l of e)if(c++,s)n+=l,s=!1;else if(l===`\\`){if(a===`index`)throw Error(`Invalid character '${l}' in an index at position ${c}`);if(a===`indexEnd`)throw Error(`Invalid character '${l}' after an index at position ${c}`);s=!0,a=a===`start`?`property`:a}else switch(l){case`.`:if(a===`index`)throw Error(`Invalid character '${l}' in an index at position ${c}`);if(a===`indexEnd`){a=`property`;break}if(!processSegment(n,t))return[];n=``,a=`property`;break;case`[`:if(a===`index`)throw Error(`Invalid character '${l}' in an index at position ${c}`);if(a===`indexEnd`){a=`index`;break}if(a===`property`&&n.length<=Da&&Ea.has(n))return[];i=a===`property`,a=`index`;break;case`]`:{if(a===`indexEnd`)throw Error(`Invalid character '${l}' after an index at position ${c}`);if(a!==`index`){a===`start`&&(a=`property`),n+=l;break}if(r===``){n+=`[]`,a=`property`;break}if((n!==``||i)&&!processSegment(n,t))return[];n=``,i=!1;let e=Number.parseInt(r,10),s=e<=Oa&&r===String(e);t.push(s?e:r),r=``,a=`indexEnd`;break}default:if(a===`index`){if(!isDigit(l))throw Error(`Invalid character '${l}' in an index at position ${c}`);r+=l;break}if(a===`indexEnd`)throw Error(`Invalid character '${l}' after an index at position ${c}`);a===`start`&&(a=`property`),n+=l}switch(s&&(n+=`\\`),a){case`property`:if(!processSegment(n,t))return[];break;case`index`:throw Error(`Index was not closed`);case`start`:t.push(``)}return t}Object.freeze([``,` `,`.`,`..`,` .`,`. `,` ..`,`.. `,`../`,`../foo`,`foo/../bar`,`foo/bar`,`foo\\bar`,`foo\0bar`]);function isSafeFilename(e){if(typeof e!=`string`)return!1;let t=e.trim();return t!==``&&t!==`.`&&t!==`..`&&!e.includes(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)}function assertSafeFilename(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);if(!isSafeFilename(e))throw Error(`Unsafe filename: ${JSON.stringify(e)}`)}const ka=fn.homedir(),Aa=fn.tmpdir(),{env:ja}=R,macos=e=>{let t=N.join(ka,`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(Aa,e)}},windows=e=>{let t=ja.APPDATA||N.join(ka,`AppData`,`Roaming`),n=ja.LOCALAPPDATA||N.join(ka,`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(Aa,e)}},linux=e=>{let t=N.basename(ka);return{data:N.join(ja.XDG_DATA_HOME||N.join(ka,`.local`,`share`),e),config:N.join(ja.XDG_CONFIG_HOME||N.join(ka,`.config`),e),cache:N.join(ja.XDG_CACHE_HOME||N.join(ka,`.cache`),e),log:N.join(ja.XDG_STATE_HOME||N.join(ka,`.local`,`state`),e),temp:N.join(Aa,t,e)}};function envPaths(e,{suffix:t=`nodejs`}={}){return assertSafeFilename(e),t&&(e+=`-${t}`),assertSafeFilename(e),R.platform===`darwin`?macos(e):R.platform===`win32`?windows(e):linux(e)}const attemptifyAsync=(e,t)=>{let{onError:n}=t;return function attemptified(...t){return e.apply(void 0,t).catch(n)}},attemptifySync=(e,t)=>{let{onError:n}=t;return function attemptified(...t){try{return e.apply(void 0,t)}catch(e){return n(e)}}},retryifyAsync=(e,t)=>{let{isRetriable:n}=t;return function retryified(t){let{timeout:r}=t,i=t.interval??250,a=Date.now()+r;return function attempt(...t){return e.apply(void 0,t).catch(e=>{if(!n(e)||Date.now()>=a)throw e;let r=Math.round(i*Math.random());return r>0?new Promise(e=>setTimeout(e,r)).then(()=>attempt.apply(void 0,t)):attempt.apply(void 0,t)})}}},retryifySync=(e,t)=>{let{isRetriable:n}=t;return function retryified(t){let{timeout:r}=t,i=Date.now()+r;return function attempt(...t){for(;;)try{return e.apply(void 0,t)}catch(e){if(!n(e)||Date.now()>=i)throw e;continue}}}},Ma={isChangeErrorOk:e=>{if(!Ma.isNodeError(e))return!1;let{code:t}=e;return t===`ENOSYS`||!Fa&&(t===`EINVAL`||t===`EPERM`)},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!Ma.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(!Ma.isNodeError(e)||!Ma.isChangeErrorOk(e))throw e}},Na={onError:Ma.onChangeError},Pa={onError:()=>void 0},Fa=R.getuid?!R.getuid():!1,Ia={isRetriable:Ma.isRetriableError},La={attempt:{chmod:attemptifyAsync(rt(L.chmod),Na),chown:attemptifyAsync(rt(L.chown),Na),close:attemptifyAsync(rt(L.close),Pa),fsync:attemptifyAsync(rt(L.fsync),Pa),mkdir:attemptifyAsync(rt(L.mkdir),Pa),realpath:attemptifyAsync(rt(L.realpath),Pa),stat:attemptifyAsync(rt(L.stat),Pa),unlink:attemptifyAsync(rt(L.unlink),Pa),chmodSync:attemptifySync(L.chmodSync,Na),chownSync:attemptifySync(L.chownSync,Na),closeSync:attemptifySync(L.closeSync,Pa),existsSync:attemptifySync(L.existsSync,Pa),fsyncSync:attemptifySync(L.fsync,Pa),mkdirSync:attemptifySync(L.mkdirSync,Pa),realpathSync:attemptifySync(L.realpathSync,Pa),statSync:attemptifySync(L.statSync,Pa),unlinkSync:attemptifySync(L.unlinkSync,Pa)},retry:{close:retryifyAsync(rt(L.close),Ia),fsync:retryifyAsync(rt(L.fsync),Ia),open:retryifyAsync(rt(L.open),Ia),readFile:retryifyAsync(rt(L.readFile),Ia),rename:retryifyAsync(rt(L.rename),Ia),stat:retryifyAsync(rt(L.stat),Ia),write:retryifyAsync(rt(L.write),Ia),writeFile:retryifyAsync(rt(L.writeFile),Ia),closeSync:retryifySync(L.closeSync,Ia),fsyncSync:retryifySync(L.fsyncSync,Ia),openSync:retryifySync(L.openSync,Ia),readFileSync:retryifySync(L.readFileSync,Ia),renameSync:retryifySync(L.renameSync,Ia),statSync:retryifySync(L.statSync,Ia),writeSync:retryifySync(L.writeSync,Ia),writeFileSync:retryifySync(L.writeFileSync,Ia)}},Ra={},za=R.geteuid?R.geteuid():-1,Ba=R.getegid?R.getegid():-1,Va=!!R.getuid;R.getuid&&R.getuid();const isException=e=>e instanceof Error&&`code`in e,Ha=/* @__PURE__ */ t(e=>typeof e==`string`,`isString`),isUndefined=e=>e===void 0,Ua=R.platform===`linux`,Wa=R.platform===`win32`,Ga=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`];Wa||Ga.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),Ua&&Ga.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&&(Wa&&e!==`SIGINT`&&e!==`SIGTERM`&&e!==`SIGKILL`?R.kill(R.pid,`SIGTERM`):R.kill(R.pid,e))}},this.hook=()=>{R.once(`exit`,()=>this.exit());for(let e of Ga)try{R.once(e,()=>this.exit(e))}catch{}},this.register=e=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}};const Ka=new Interceptor().register,qa={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=qa.truncate(t(e));if(r in qa.store)return qa.get(e,t,n);qa.store[r]=n;let disposer=()=>delete qa.store[r];return[r,disposer]},purge:e=>{qa.store[e]&&(delete qa.store[e],La.attempt.unlink(e))},purgeSync:e=>{qa.store[e]&&(delete qa.store[e],La.attempt.unlinkSync(e))},purgeSyncAll:()=>{for(let e in qa.store)qa.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]}`}};Ka(qa.purgeSyncAll);function writeFileSync$1(e,t,n=Ra){if(Ha(n))return writeFileSync$1(e,t,{encoding:n});let r={timeout:n.timeout??1e3},i=null,a=null,s=null;try{let c=La.attempt.realpathSync(e),l=!!c;e=c||e,[a,i]=qa.get(e,n.tmpCreate||qa.create,n.tmpPurge!==!1);let u=Va&&isUndefined(n.chown),f=isUndefined(n.mode);if(l&&(u||f)){let t=La.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);La.attempt.mkdirSync(t,{mode:511,recursive:!0})}s=La.retry.openSync(r)(a,`w`,n.mode||438),n.tmpCreated&&n.tmpCreated(a),Ha(t)?La.retry.writeSync(r)(s,t,0,n.encoding||`utf8`):isUndefined(t)||La.retry.writeSync(r)(s,t,0,t.length,0),n.fsync!==!1&&(n.fsyncWait===!1?La.attempt.fsync(s):La.retry.fsyncSync(r)(s)),La.retry.closeSync(r)(s),s=null,n.chown&&(n.chown.uid!==za||n.chown.gid!==Ba)&&La.attempt.chownSync(a,n.chown.uid,n.chown.gid),n.mode&&n.mode!==438&&La.attempt.chmodSync(a,n.mode);try{La.retry.renameSync(r)(a,e)}catch(t){if(!isException(t)||t.code!==`ENAMETOOLONG`)throw t;La.retry.renameSync(r)(a,qa.truncate(e))}i(),a=null}finally{s&&La.attempt.closeSync(s),a&&qa.purge(a)}}t(writeFileSync$1,`writeFileSync`);var Ja=/* @__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})),Ya=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Ja();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})),W=/* @__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=Ja(),n=Ya();var r=Ja();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=Ya();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?`
175
+ `:``},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})`}})),G=/* @__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=W(),n=Ja();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})),Xa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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`)}})),Za=/* @__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=W(),n=G(),r=Xa();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
176
  /* 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
177
+ 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])}})),Qa=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Za(),n=W(),r=Xa(),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)}})),$a=/* @__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})),eo=/* @__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})),to=/* @__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=$a(),n=eo(),r=Za(),i=W(),a=G();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
173
178
  || (${l} == "string" && ${a} && ${a} == +${a})`).assign(u,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${l} === "boolean" || ${a} === null
174
179
  || (${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"
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;
180
+ || ${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}}})),no=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();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)}`)}})),ro=/* @__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=W(),n=G(),r=Xa(),i=G();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
181
  /* 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){
182
+ 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})),io=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=Xa(),r=ro(),i=Za();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
183
  /* 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){
184
+ 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})),ao=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();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})),oo=/* @__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`)}})),so=/* @__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=G(),n=Pe(),r=oo(),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})),co=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Qa(),n=to(),r=eo(),i=to(),a=no(),s=io(),c=ao(),l=W(),u=Xa(),f=so(),p=G(),m=Za();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
185
  /* 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){
186
+ 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})),lo=/* @__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})),uo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=so();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})),fo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=lo(),r=Xa(),i=so(),a=G(),s=co();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}})),po=/* @__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}})),mo=/* @__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),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),s=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),u=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),f=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)f[t]=`%`+e[t>>4]+e[t&15]}function percentEncodeNonAscii(e){return e<2048?f[192|e>>6]+f[128|e&63]:e<65536?f[224|e>>12]+f[128|e>>6&63]+f[128|e&63]:f[240|e>>18]+f[128|e>>12&63]+f[128|e>>6&63]+f[128|e&63]}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 p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function isZoneIdentifier(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3)))t+=2;else return!1}return!0}function compressIPv6ZeroRun(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),s=e.slice(t+n).join(`:`);return a+`::`+s}function normalizeIPv6Address(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),s=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;s+=2}else{if(!p(n))return;a[e]=parseInt(n,16).toString(16),s++}}if(t===-1)return s===8?compressIPv6ZeroRun(a):void 0;if(s>=8)return;let c=a.slice(0,n.length);for(let e=s;e<8;e++)c.push(`0`);for(let e=n.length;e<a.length;e++)c.push(a[e]);return compressIPv6ZeroRun(c)}function normalizeIPv6(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(findToken(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!isZoneIdentifier(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=normalizeIPv6Address(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}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 removeDotSegmentsRelative(e){if(e===``||e[0]===`/`)return removeDotSegments(e);let t=e.split(`/`),n=t.length-1,r=[],i=!1;for(let e=0;e<=n;e++){let a=t[e];a===`.`||a===`..`?(a===`..`&&(r.length!==0&&r[r.length-1]!==`..`?r.pop():r.push(`..`)),i=e===n):r.push(a)}return i&&r[r.length-1]!==`..`&&r.push(``),(r.length===0||r[0]===``||r[0].includes(`:`))&&r.unshift(`.`),r.join(`/`)}let v={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},y=/[@/?#:]/g,b=/[@/?#]/g;function reescapeHostDelimiters(e,t){let n=t?b:y;return n.lastIndex=0,e.replace(n,e=>v[e])}function normalizePercentEncoding(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&s(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function normalizePathEncoding(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&s(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=isEscapeSafe(i)?r:f[i];else if(i<55296||i>57343)t+=percentEncodeNonAscii(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=percentEncodeNonAscii(65536+(i-55296<<10)+(r-56320)),n++):t+=percentEncodeNonAscii(65533)}else t+=percentEncodeNonAscii(65533)}}return t}function serializePathEncoding(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),c(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=f[r];else if(r<55296||r>57343)n+=percentEncodeNonAscii(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=percentEncodeNonAscii(65536+(r-55296<<10)+(i-56320)),t++):n+=percentEncodeNonAscii(65533)}else n+=percentEncodeNonAscii(65533)}}return n}function encodeComponent(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=f[t];else if(t<55296||t>57343)n+=percentEncodeNonAscii(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=percentEncodeNonAscii(65536+(t-55296<<10)+(i-56320)),r++):n+=percentEncodeNonAscii(65533)}else n+=percentEncodeNonAscii(65533)}}return n}function encodeUserinfo(e){return encodeComponent(e,u)}function encodeQuery(e){return encodeComponent(e,l)}function encodeFragment(e){return encodeComponent(e,l)}function isEscapeSafe(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function normalizeQueryFragmentEncoding(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));s(i)?t+=i:t+=`%`+e,n+=2;continue}}if(l(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=isEscapeSafe(i)?r:f[i];else if(i<55296||i>57343)t+=percentEncodeNonAscii(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=percentEncodeNonAscii(65536+(i-55296<<10)+(r-56320)),n++):t+=percentEncodeNonAscii(65533)}else t+=percentEncodeNonAscii(65533)}}return t}function escapePreservingEscapes(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function recomposeAuthority(e){let t=[];if(e.userinfo!==void 0&&(t.push(encodeUserinfo(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=normalizeIPv6(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=normalizePercentEncoding(n,!0),e=normalizeIPv6(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:reescapeHostDelimiters(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority,reescapeHostDelimiters,normalizePercentEncoding,normalizePathEncoding,serializePathEncoding,normalizeQueryFragmentEncoding,encodeUserinfo,encodeQuery,encodeFragment,escapePreservingEscapes,removeDotSegments,removeDotSegmentsRelative,isIPv4:r,isUUID:n,normalizeIPv6,stringArrayToHexStripped}})),ho=/* @__PURE__ */ r(((e,t)=>{let{isUUID:n}=mo(),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=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),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&&n[0]===e.path){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}})),go=/* @__PURE__ */ r(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,removeDotSegmentsRelative:i,recomposeAuthority:a,normalizePercentEncoding:s,normalizePathEncoding:c,serializePathEncoding:l,normalizeQueryFragmentEncoding:u,encodeQuery:f,encodeFragment:p,reescapeHostDelimiters:m,isIPv4:h,nonSimpleDomain:g}=mo(),{SCHEMES:v,getSchemeHandler:y}=ho(),b=/^[A-Za-z][A-Za-z0-9+.-]*$/u,x=`URI scheme is malformed.`,S=`URI host is malformed.`,C=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function validateScheme(e){let t=String(e);if(!b.test(t))throw TypeError(x);return t}function normalize(e,t){return typeof e==`string`?e=normalizeString(e,t):typeof e==`object`&&(e=parse(serialize(e,t),t)),e}function resolve(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:s,malformedPercentEncoding:c,malformedSchemeSpecific:l,malformedHost:u,malformedScheme:f}=parseWithStatus(e,i),{parsed:p,malformedAuthorityOrPort:m,malformedPercentEncoding:g,malformedSchemeSpecific:v,malformedHost:b,malformedScheme:x}=parseWithStatus(t,i);if(s||m||c||g||l||v||u||b||f||x)throw Error(a.error||p.error||`URI is malformed.`);let C=resolveComponent(a,p,i,!0),w=y(r&&r.scheme||C.scheme),T=C.host,E=T!==void 0&&T!==``&&(h(T)||n(T).isIPV6);if(hasForbiddenDomainHost(C,r||{},w,E))throw Error(S);canonicalizeHost(C,r||{},w,E);let D=T&&T.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(T);if(C.error&&!D)throw Error(C.error);return i.skipEscape=!0,serialize(C,i)}function resolveComponent(e,t,n,a){let s={};if(a||(e=parse(serialize(e,n),n),t=parse(serialize(t,n),n)),n||={},!n.tolerant&&t.scheme)s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=r(t.path||``),s.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=r(t.path||``),s.query=t.query;else{if(!t.path)s.path=e.path,s.query=t.query===void 0?e.query:t.query;else{if(t.path[0]===`/`)s.path=r(t.path);else{let n=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;s.path=n&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,s.path=e.scheme===void 0&&!n&&s.path[0]!==`/`?i(s.path):r(s.path)}s.query=t.query}s.userinfo=e.userinfo,s.host=e.host,s.port=e.port}s.scheme=e.scheme}return s.fragment=t.fragment,s}function equal(e,t,n){let r=normalizeComparableURI(e,n),i=normalizeComparableURI(t,n);return r!==void 0&&i!==void 0&&r===i}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:``},c=Object.assign({},t),u=[];n.scheme&&=validateScheme(n.scheme);let m=y(c.scheme||n.scheme);m&&m.serialize&&m.serialize(n,c);let h=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,g=(n.scheme===void 0||c.reference===`suffix`)&&!h,v=!c.skipEscape&&g;n.path!==void 0&&(n.path=c.skipEscape?s(n.path):l(n.path,v)),c.reference!==`suffix`&&n.scheme&&(n.scheme=validateScheme(n.scheme),u.push(n.scheme,`:`));let b=a(n);if(b!==void 0&&(c.reference!==`suffix`&&u.push(`//`),u.push(b),n.path&&n.path[0]!==`/`&&u.push(`/`)),n.path!==void 0){let e=n.path;c.absolutePath||m&&m.absolutePath||(e=g&&e[0]!==`/`?i(e):r(e)),g&&(e=l(e,!0)),b===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),u.push(e)}return n.query!==void 0&&u.push(`?`,f(n.query)),n.fragment!==void 0&&u.push(`#`,p(n.fragment)),u.join(``)}let w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,E=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function getParseError(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function hasMalformedPercentEncoding(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function isIPLiteral(e){return e[0]===`[`&&e[e.length-1]===`]`}function hasMalformedComponentPercentEncoding(e){let t=e[4];return hasMalformedPercentEncoding(e[3])||t!==void 0&&!isIPLiteral(t)&&hasMalformedPercentEncoding(t)||hasMalformedPercentEncoding(e[6])||hasMalformedPercentEncoding(e[7])||hasMalformedPercentEncoding(e[8])}function canonicalizeHost(e,t,n,r){if(hasForbiddenDomainHost(e,t,n,r))return e.error=e.error||S,!0;if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!isIPLiteral(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&g(e.host)){let t;try{t=new URL(`http://`+e.host)}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}if(!isHostOnlyURL(t))return e.error=e.error||S,!0;e.host=t.hostname}return!1}function hasForbiddenDomainHost(e,t,n,r){return!!(e.host&&r===!1&&!isIPLiteral(e.host)&&(t.domainHost||n&&n.domainHost)&&C.test(e.host))}function isHostOnlyURL(e){return e.username===``&&e.password===``&&e.port===``&&e.pathname===`/`&&e.search===``&&e.hash===``&&e.hostname!==``}function parseWithStatus(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,l=!1,f=!1,p=!1,g=!1,C=!1,D=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let ee=e.match(T);ee!==null&&ee[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,a=!0);let te=e.match(E);if(te!==null){let e=te[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,a=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,a=!0))}let O=e.match(w);if(O){i.scheme=O[1],i.userinfo=O[3],i.host=O[4],i.port=parseInt(O[5],10),i.path=O[6]||``,i.query=O[7],i.fragment=O[8],i.scheme!==void 0&&(b.test(i.scheme)?i.scheme=i.scheme.toLowerCase():(i.error=i.error||x,C=!0)),l=hasMalformedComponentPercentEncoding(O),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=O[5]);let t=getParseError(i,O);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host){if(h(i.host)===!1){let e=isIPLiteral(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);D=r.isIPV6||r.isIPVFuture===!0,g=t&&(!e||r.error===!0),i.host=D?r.host:r.host.toLowerCase(),g&&(i.error=i.error||S,a=!0)}else D=!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 w=y(r.scheme||i.scheme);if(g||(p=canonicalizeHost(i,r,w,D)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!g){let e=D?i.host:s(i.host,!0);D||(e=s(e.toLowerCase())),i.host=D||r.scheme!==`null`?m(e,D):e}(!w||w&&!w.skipNormalize)&&(i.path&&=c(i.path),i.query&&=u(i.query),i.fragment&&=u(i.fragment)),w&&w.parse&&(w.parse(i,r),w===v.urn&&i.nid===void 0&&(f=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:l,malformedSchemeSpecific:f,malformedHost:p,malformedScheme:C}}function parse(e,t){return parseWithStatus(e,t).parsed}function normalizeString(e,t){return normalizeStringWithStatus(e,t).normalized}function normalizeStringWithStatus(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}=parseWithStatus(e,t);return{normalized:r||i||a||s||c?e:serialize(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}}function normalizeComparableURI(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:serialize(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:l}=normalizeStringWithStatus(n,t);return i||a||s||c||l?void 0:r}let D={SCHEMES:v,normalize,resolve,resolveComponent,equal,serialize,parse};t.exports=D,t.exports.default=D,t.exports.fastUri=D})),_o=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=go();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),vo=/* @__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=co();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();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=lo(),i=uo(),a=$a(),s=fo(),c=W(),l=so(),u=to(),f=G(),p=po(),m=_o(),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
187
  /* 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{
188
+ 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]}}})),yo=/* @__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`)}}})),bo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=uo(),n=ro(),r=W(),i=Xa(),a=fo(),s=G(),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})),xo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=yo(),n=bo();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),So=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),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})`)}}})),Co=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}))`)}}})),wo=/* @__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`})),To=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=wo();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}`)}}})),Eo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=G(),r=W();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})`)}}}})),Do=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),Oo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=W(),r=G();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)}}}})),ko=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),Ao=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Pe();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),jo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=to(),n=W(),r=G(),i=Ao();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)})))}}}})),Mo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Ao();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}`)}}})),No=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Ao();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
189
  /* 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},
190
+ 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}`}}}})),Po=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=So(),n=Co(),r=To(),i=Eo(),a=Do(),s=Oo(),c=ko(),l=jo(),u=Mo(),f=No();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]})),Fo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),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})),Io=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=ro(),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})),Lo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Io();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Ro=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=ro(),i=Fo();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)))}}})),zo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)))}}}})),Bo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=ro();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},
186
191
  missingProperty: ${i},
187
192
  depsCount: ${n},
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;
193
+ 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})),Vo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)}}})),Ho=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=W(),r=Xa(),i=G();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
194
  /* 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;
195
+ 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)}}}})),Uo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=co(),n=ro(),r=G(),i=Ho();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)}}}})),Wo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ro(),n=W(),r=G(),i=G();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())})})}}}})),Go=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`}}})),Ko=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:ro().validateUnion,error:{message:`must match a schema in anyOf`}}})),qo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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
196
  /* 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;
197
+ 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)})})}}}})),Jo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;
193
198
  /* 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;
199
+ 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)})}}})),Yo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),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})),Xo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`)}}})),Zo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Fo(),n=Lo(),r=Io(),i=Ro(),a=zo(),s=Bo(),c=Vo(),l=Ho(),u=Uo(),f=Wo(),p=Go(),m=Ko(),h=qo(),g=Jo(),v=Yo(),y=Xo();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})),Qo=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=W(),n=Xa(),r=fo(),i=bo(),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})),$o=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=W(),n=Xa(),r=bo(),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})),es=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qo(),n=G();e.default={keyword:`$recursiveAnchor`,schemaType:`boolean`,code(e){e.schema?(0,t.dynamicAnchor)(e,``):(0,n.checkStrictMode)(e.it,`$recursiveAnchor: false is ignored`)}}})),ts=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$o();e.default={keyword:`$recursiveRef`,schemaType:`string`,code:e=>(0,t.dynamicRef)(e,e.schema)}})),ns=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qo(),n=$o(),r=es(),i=ts();e.default=[t.default,n.default,r.default,i.default]})),rs=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Bo();e.default={keyword:`dependentRequired`,type:`object`,schemaType:`object`,error:t.error,code:e=>(0,t.validatePropertyDeps)(e)}})),is=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Bo();e.default={keyword:`dependentSchemas`,type:`object`,schemaType:`object`,code:e=>(0,t.validateSchemaDeps)(e)}})),as=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`)}}})),os=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rs(),n=is(),r=as();e.default=[t.default,n.default,r.default]})),ss=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Xa();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
200
  /* 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(`
201
+ 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)}}}})),cs=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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())})}}}})),ls=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ss(),n=cs();e.default=[t.default,n.default]})),us=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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})`}}}}})),ds=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[us().default]})),fs=/* @__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`]})),ps=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xo(),n=Po(),r=Zo(),i=ns(),a=os(),s=ls(),c=ds(),l=fs();e.default=[i.default,t.default,n.default,(0,r.default)(!0),c.default,l.metadataVocabulary,l.contentVocabulary,a.default,s.default]})),ms=/* @__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={}))})),hs=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=ms(),r=fo(),i=uo(),a=G();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}}}}})),gs=/* @__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}}}})),_s=/* @__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`}}}}})),vs=/* @__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`}}}})),ys=/* @__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`}}}})),bs=/* @__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`}}}})),xs=/* @__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`}}}})),Ss=/* @__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}}}})),Cs=/* @__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:[]}}}})),ws=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gs(),n=_s(),r=vs(),i=ys(),a=bs(),s=xs(),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})),Ts=/* @__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=vo(),r=ps(),i=hs(),a=ws(),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=co();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var l=W();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=lo();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var f=uo();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Es=/* @__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}}})),Ds=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xo(),n=Po(),r=Zo(),i=ds(),a=fs();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Os=/* @__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}})),ks=/* @__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=vo(),r=Ds(),i=hs(),a=Os(),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=co();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();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=lo();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=uo();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),As=/* @__PURE__ */ r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=ks(),n=W(),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})),js=/* @__PURE__ */ r(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Es(),r=As(),i=W(),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})),Ms=Ts(),Ns=/* @__PURE__ */ n(js(),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}`,Ps=Object.getOwnPropertyDescriptor(Function.prototype,`toString`),Fs=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",Fs);let{writable:a,enumerable:s,configurable:c}=Ps;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},Is=Object.prototype.toString;function isType(e,t,n){return e?e.constructor===t||Is.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 Ls={utf8:new globalThis.TextDecoder(`utf8`)};function uint8ArrayToString(e,t=`utf8`){return assertUint8ArrayOrArrayBuffer(e),Ls[t]??=new globalThis.TextDecoder(t),Ls[t].decode(e)}new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));const Rs=`aes-256-cbc`,zs=4095,readConfigFileMode=e=>{if(e!=null){if(typeof e==`number`){if(!Number.isInteger(e)||e<0||e>zs)throw TypeError(`The \`configFileMode\` option must be a whole number between 0 and ${zs}, got ${e}`);return e}if(typeof e==`string`&&/^[0-7]+$/.test(e)){let t=Number.parseInt(e,8);if(t>zs)throw TypeError(`The \`configFileMode\` option must be a whole number between 0 and ${zs}, got \`${e}\``);return t}throw TypeError(`The \`configFileMode\` option must be a number or a string of octal digits, got ${typeof e==`string`?`\`${e}\``:typeof e}`)}},assertObjectOption=(e,t)=>{if(t!=null&&typeof t!=`object`)throw TypeError(`The \`${e}\` option must be an object.`)},assertMigrations=e=>{if(e!=null){if(typeof e!=`object`||Array.isArray(e))throw TypeError("The `migrations` option must be an object whose keys are the versions to migrate and whose values are the steps to run.");for(let[t,n]of Object.entries(e))if(typeof n!=`function`)throw TypeError(`The \`migrations\` option must be an object of steps, got ${n===null?`null`:typeof n} for the version \`${t}\`.`)}},Bs=/* @__PURE__ */ new Set([`aes-256-cbc`,`aes-256-gcm`,`aes-256-ctr`]);var DecryptionError=class extends Error{},SchemaViolationError=class extends Error{};const createPlainObject=()=>Object.create(null),copyStore=e=>{let t=Object.getPrototypeOf(e),n=Object.assign(createPlainObject(),e);return t!==null&&Object.setPrototypeOf(n,t),n},omitUndefined=e=>Object.assign(createPlainObject(),Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))),asStore=e=>typeof e!=`object`||!e||Array.isArray(e)?createPlainObject():e,isItem=e=>e!==void 0,storeFromDeserialized=e=>{let t=Object.assign(createPlainObject(),asStore(e));return typeof t.toJSON==`function`&&delete t.toJSON,t};function*storeItems(e){for(let t of Object.keys(e)){let n=e[t];isItem(n)&&(yield[t,n])}}const Vs=/* @__PURE__ */ new Set([`undefined`,`symbol`,`function`]),Hs=1e3,unwritableItem=(e,t,n,r=0)=>{if(r>Hs)return{at:t.join(`.`),type:`deep`,value:e};if(typeof e==`bigint`)return{at:t.join(`.`),type:`bigint`,value:e};if(typeof e==`object`&&e&&holdsKeysOfItsOwn(e)){if(n.has(e))return{at:t.join(`.`),type:`cycle`,value:e};n.add(e);try{for(let[i,a]of Object.entries(e)){let e=unwritableItem(a,[...t,i],n,r+1);if(e!==void 0)return e}}finally{n.delete(e)}}},checkValueType=(e,t,n)=>{let r=typeof t;if(Vs.has(r))throw TypeError(`Setting a value of type \`${r}\` for key \`${e}\` is not allowed as it's not supported by JSON`);if(!n)return;let i=unwritableItem(t,[],/* @__PURE__ */ new Set);i!==void 0&&throwUnwritableType(e,i)},checkWrittenValueTypes=e=>{if(typeof e==`object`&&e)for(let[t,n]of Object.entries(e)){let e=unwritableItem(n,[],/* @__PURE__ */ new Set);e?.type===`deep`&&throwUnwritableType(t,e)}},throwUnwritableType=(e,t)=>{let n=t.at===``?``:` at \`${t.at}\``;throw t.type===`bigint`?TypeError(`Setting a value of type \`bigint\` for key \`${e}\`${n} is not allowed as it's not supported by JSON`):t.type===`deep`?TypeError(`Setting a value for key \`${e}\` is not allowed as a value nested more than \`${Hs}\` levels deep is not one the store can hold`):TypeError(`Setting a value for key \`${e}\`${n} is not allowed as a value that holds itself is not supported by JSON, which refuses one as a circular structure`)},assertStringKey=e=>{if(typeof e!=`string`)throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`)},Us=`__internal__`,Ws=`${Us}.migrations.version`,Gs=`${Us}.migrations.completedRanges`,Ks=`:`.codePointAt(0),qs=Symbol(`missingKey`),atomicWritePath=e=>{if(!L.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink())return e;try{return L.realpathSync(e)}catch{let t=e,n=/* @__PURE__ */ new Set;for(;!n.has(t)&&(n.add(t),L.lstatSync(t,{throwIfNoEntry:!1})?.isSymbolicLink());){let e=L.readlinkSync(t);t=N.resolve(L.realpathSync(N.dirname(t)),e)}return L.existsSync(t)?t:N.join(atomicWritePath(N.dirname(t)),N.basename(t))}},copyStoreValue=(e,t=/* @__PURE__ */ new Map,n=0)=>{if(typeof e!=`object`||!e||n>Hs)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let r=[];r.length=e.length,t.set(e,r);for(let[i,a]of e.entries())i in e&&(r[i]=copyStoreValue(a,t,n+1));return r}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=r===null?createPlainObject():{};t.set(e,i);for(let r of Object.keys(e)){let a=copyStoreValue(e[r],t,n+1);r===`__proto__`?Object.defineProperty(i,r,{value:a,writable:!0,enumerable:!0,configurable:!0}):i[r]=a}return i},freezeStoreValue=(e,t=0,n=/* @__PURE__ */ new Set)=>{if(typeof e!=`object`||!e||t>Hs||n.has(e))return e;let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)return e;n.add(e),Object.freeze(e);for(let r of Object.values(e))freezeStoreValue(r,t+1,n);return e},hasStoreKey=(e,t)=>typeof e!=`object`||!e?!1:Object.prototype.propertyIsEnumerable.call(e,t),ownValue=(e,t)=>{if(typeof e!=`object`||!e)return e;if(!t)return copyStoreValue(e);let n;try{n=JSON.stringify(e)}catch{return copyStoreValue(e)}return n===void 0?copyStoreValue(e):JSON.parse(n)},keyFromInstancePath=e=>e.slice(1).replaceAll(/~([01])/g,(e,t)=>t===`0`?`~`:`/`),keyFromError=({instancePath:e,params:t})=>{let{additionalProperty:n,unevaluatedProperty:r,propertyName:i}=t,a=n??r??i,s=keyFromInstancePath(e);return a===void 0?s:s===``?a:`${s}/${a}`},keyOfPath=e=>e.map(e=>typeof e==`number`?String(e):e.replaceAll(/[\\.[\]]/g,String.raw`\$&`)).join(`.`),keyPathOrReport=e=>{try{let t=parsePath(e);return t.length>0?t:void 0}catch{throw TypeError(`The key \`${e}\` is not a key a value can be written to.`)}},keyPath=e=>{try{return keyPathOrReport(e)}catch{return}},Js=`which is not a key a value can be written to.`,whyKeyIsRefused=e=>{let t=keyPath(e);if(t?.length!==1||String(t[0])!==e)return t===void 0?Js:"which is not a key of its own. Use the `properties` of a key for the keys below the root."},holdsKeysOfItsOwn=e=>typeof e!=`object`||!e?!1:typeof e.toJSON!=`function`,whereWriteIsBlocked=(e,t,n=0)=>{let r=keyPath(t);if(r===void 0)return;let i=e,a=n>0?r[n-1]:void 0;for(let[e,t]of r.entries())if(!(e<n)){if(Array.isArray(i)&&typeof t!=`number`)return a;if(e===r.length-1||!hasStoreKey(i,t))return;if(a=t,i=i[t],!holdsKeysOfItsOwn(i))return a}},copyStoreDeep=e=>{let t=copyStore(e),n=/* @__PURE__ */ new Map;for(let e of Object.keys(t))t[e]=copyStoreValue(t[e],n);return t},Ys=/* @__PURE__ */ new Map,matchesPatternProperty=(e,t)=>{let n=e?.patternProperties;return!n||typeof n!=`object`?!1:Object.keys(n).some(e=>{let n=Ys.get(e);return n||(n=new RegExp(e),Ys.set(e,n)),n.test(t)})},holdsValueRule=(e,t)=>{let{additionalProperties:n,unevaluatedProperties:r}=e??{};return matchesPatternProperty(e,t)||n!==void 0&&n!==!1||r!==void 0&&r!==!1},rangeBranchFor=(e,t)=>{let n=new Ta.default.Range(e).set.map(e=>e.map(String).join(` `));return n.length<2?e:n.find(e=>Ta.default.satisfies(t,e))??e},completedRangeFor=(e,t)=>{let n=rangeBranchFor(e,t);return n===e?e:JSON.stringify([e,n])},orderedDefaults=(e,t)=>{let n=Object.entries(e);if(!t)return n;let r=/* @__PURE__ */ new Map;for(let[e]of n)r.set(e,keyPath(e)?.length??0);return n.toSorted(([e],[t])=>r.get(e)-r.get(t))},isSameFile=(e,t)=>{try{let n=L.lstatSync(e),r=L.lstatSync(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}},movesForward=(e,t)=>t===void 0||isVersionInRangeFormat(t)||Ta.default.gt(e,t),versionToCompare=(e,t)=>isVersionInRangeFormat(e)?Ta.default.minVersion(rangeBranchFor(e,t))?.version??t:e,isVersionInRangeFormat=e=>Ta.default.valid(e)===null,shouldPerformMigration=(e,t,n)=>isVersionInRangeFormat(e)?Ta.default.satisfies(n,e)?t===void 0||Ta.default.gt(n,t)&&!Ta.default.satisfies(t,e):!1:!(t!==void 0&&Ta.default.lte(e,t)||Ta.default.gt(e,n)),isCompletedRange=(e,t,n)=>isVersionInRangeFormat(e)&&n.has(completedRangeFor(e,t)),getOwnProperty=(e,t,n)=>{let r=keyPathOrReport(t);if(r===void 0)return n;let i=e;for(let e of r){if(!hasStoreKey(i,e))return n;i=i[e]}return i===void 0?n:i},setOwnProperty=(e,t,n,r=!1)=>{let i=keyPathOrReport(t);if(i===void 0)return;let a=i.length-1,s=e;for(let[e,c]of i.entries()){if(Array.isArray(s)&&typeof c!=`number`)throw TypeError(`The key \`${t}\` only holds the elements of an array, so \`${c}\` cannot be set on it`);if(e===a){s[c]=n;return}let l=hasStoreKey(s,c)?s[c]:void 0;if(typeof l==`object`&&l){if(!holdsKeysOfItsOwn(l))throw TypeError(`The key \`${t}\` cannot be set, since the value the store holds for it cannot be written through.`);s=l;continue}let u=i[e+1],f=!r&&typeof u==`number`?[]:{};s[c]=f,s=f}},deleteOwnProperty=(e,t)=>{let n=keyPathOrReport(t);if(n===void 0)return;let r=n.length-1,i=e;for(let[e,t]of n.entries()){if(e===r){if(Array.isArray(i)){typeof t==`number`&&i.splice(t,1);return}if(!hasStoreKey(i,t))return;delete i[t];return}let n=hasStoreKey(i,t)?i[t]:void 0;if(typeof n!=`object`||!n)return;i=n}},detachUnwritableBookkeeping=(e,t)=>{let n=e;for(let e of t.slice(0,-1)){let t=n[e];if(typeof t!=`object`||!t)return;if(Array.isArray(t)){delete n[e];return}n=t}};var Conf=class{path;events;#e;#t;#n;#r;#i;#a;#o=createPlainObject();#s;#c=!1;#l=/* @__PURE__ */ new Map;#u;#d;#f;#p=!1;constructor(e={}){let t=this.#H(e);this.#r=t,this.#i=orderedDefaults(t.defaults??{},t.accessPropertiesByDotNotation),this.#U(t),this.#Z(t),this.events=new EventTarget,this.#t=t.encryptionKey,this.#n=t.encryptionAlgorithm??Rs;let n=readConfigFileMode(t.configFileMode);if(n!==void 0){let e=R.umask();if(this.#a=n&~e,!(this.#a&256))throw TypeError(`The \`configFileMode\` option must give the file a mode its owner can read, since a file its owner cannot read is not one the store that wrote it can read back. ${JSON.stringify(t.configFileMode)} leaves the file at mode \`0o${this.#a.toString(8)}\`, which has no owner read bit.`)}this.path=this.#Q(t),this.#te(t),t.watch&&this.#O()}get(e,t){return assertStringKey(e),this.#h(this.#z(),e,t)}set(e,t){if(e===null||typeof e!=`string`&&typeof e!=`object`)throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${e===null?`null`:typeof e}`);if(typeof e!=`object`&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this.#j(e),typeof e==`object`)for(let[t,n]of Object.entries(e))this.#I(t),checkValueType(t,n,this.#R);else this.#I(e),checkValueType(e,t,this.#R);let n=this.#g();if(typeof e==`object`)for(let[t,r]of orderedDefaults(e,this.#r.accessPropertiesByDotNotation))this.#F(n,t,copyStoreValue(r));else this.#F(n,e,copyStoreValue(t));this.#m(n,!0)}has(e){return assertStringKey(e),this.#h(this.#z(),e,qs)!==qs}appendToArray(e,t){assertStringKey(e),checkValueType(e,t,this.#R),this.#j(e),this.#I(e);let n=this.#g(),r=this.#h(n,e,[]);if(!Array.isArray(r))throw TypeError(`The key \`${e}\` is already set to a non-array value`);this.#F(n,e,[...r,copyStoreValue(t)]),this.#m(n,!0)}reset(...e){for(let t of e)assertStringKey(t),this.#I(t);for(let t of e){let e=this.#h(this.#o,t);isItem(e)&&this.set(t,e)}}delete(e){assertStringKey(e),this.#j(e),this.#I(e);let t=this.#g();this.#r.accessPropertiesByDotNotation?deleteOwnProperty(t,e):delete t[e],this.#m(t,!0)}clear(){this.store=createPlainObject()}onDidChange(e,t){if(assertStringKey(e),typeof t!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this.#b(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=`function`)throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this.#b(()=>this.store,e)}get size(){let e=this.#z(),t=0;for(let n of Object.keys(e))isItem(e[n])&&t++;return t}get store(){return this.#z()}set store(e){this.#m(e,!1)}*[Symbol.iterator](){yield*storeItems(this.#z())}_closeWatcher(){for(let e of this.#l.values())e.close();this.#l.clear(),this.#d&&=(L.unwatchFile(this.path,this.#d),void 0),this.#f?.cancel(),this.#f=void 0,this.#s=void 0}#m(e,t){if(this.#w(),e=asStore(e),this.#R&&typeof e.toJSON==`function`){let t=JSON.stringify(e);e=asStore(t===void 0?void 0:JSON.parse(t))}if(!t&&!this.#c&&this.#M(e)&&(e=copyStore(e),this.#v(e)),!t&&!hasStoreKey(e,Us))try{let t=this.#L();hasStoreKey(t,Us)&&(e=copyStore(e),setOwnProperty(e,Us,t[Us]))}catch{}e=this.#Y(e),!this.#c&&this.#e&&(t||(e=copyStoreDeep(e)),this.#C(e)),!t&&this.#R&&checkWrittenValueTypes(e),this.#T(e),this.events.dispatchEvent(new Event(`change`))}#h(e,t,n){if(this.#r.accessPropertiesByDotNotation)return getOwnProperty(e,t,n);let r=e[t];return r===void 0?n:r}#g(e=!0){let t;try{let n=storeFromDeserialized(this.#L());return t=n,e&&!this.#c&&this.#C(n),n}catch(n){if(n?.code===`ENOENT`){if(this.#w(),!e||this.#c)return createPlainObject();let t=this.#Y(createPlainObject());return this.#e?.(t),t}if(this.#r.clearInvalidConfig&&!this.#p&&(n instanceof SchemaViolationError||n instanceof DecryptionError||n?.name===`SyntaxError`))return this.#V(t);throw n}}#_(){let e=this.#g();return this.#v(e),e}#v(e){let t=createPlainObject();for(let n of Object.keys(e))this.#N(n)&&(t[n]=e[n],delete e[n]);return t}#y(e,t,n=!1){let r=this.#n;if(e[16]!==Ks){if(r===`aes-256-cbc`)return uint8ArrayToString(e);throw new DecryptionError(`Failed to decrypt config data.`)}let i=e.slice(0,16),a=e.slice(17),s;if(r===`aes-256-gcm`){let e=a.length-16;if(e<0)throw new DecryptionError(`Failed to decrypt config data.`);s=a.slice(e),a=a.slice(0,e)}let c=n?[i.toString()]:[i,i.toString()];for(let e of c)try{let n=wn.pbkdf2Sync(t,e,1e4,32,`sha512`),c=wn.createDecipheriv(r,n,i);return s&&c.setAuthTag(s),uint8ArrayToString(concatUint8Arrays([c.update(a),c.final()]))}catch{}if(r===`aes-256-cbc`)return uint8ArrayToString(e);throw new DecryptionError(`Failed to decrypt config data.`)}#b(e,t){let n;try{n=e()}catch{}let onChange=()=>{let r;try{r=e()}catch{return}let i=n;nt(r,i)||(n=r,t.call(this,r,i))};return this.events.addEventListener(`change`,onChange),()=>{this.events.removeEventListener(`change`,onChange)}}#x=e=>{let t=e.replace(/^\uFEFF/,``);try{return JSON.parse(t)}catch{throw SyntaxError(`The config file \`${this.path}\` is not valid JSON.`)}};#S=e=>JSON.stringify(e,void 0,` `);#C(e){if(!this.#e)return;let t=this.#v(e),n=this.#e(e),{errors:r}=this.#e;if(Object.assign(e,t),!n&&r)throw new SchemaViolationError(`Config schema violation: `+r.map(e=>`\`${keyFromError(e)}\` ${e.message??``}`).join(`; `))}#w(){L.mkdirSync(N.dirname(this.path),{recursive:!0})}#T(e){this.#s=void 0;let t=this.#S(e);if(typeof t!=`string`&&!(t instanceof Uint8Array))throw TypeError(`The \`serialize\` option must return a string or a \`Uint8Array\`, got ${t===null?`null`:typeof t}`);let n=t,r=this.#t;if(r){let e=wn.randomBytes(16),t=wn.pbkdf2Sync(r,e,1e4,32,`sha512`),i=wn.createCipheriv(this.#n,t,e),a=concatUint8Arrays([i.update(n),i.final()]),s=[e,Uint8Array.of(Ks),a];this.#n===`aes-256-gcm`&&s.push(i.getAuthTag()),n=concatUint8Arrays(s)}this.#E(n,this.#a),this.#r.watch&&(this.#u=n)}#E(e,t){if(R.env.SNAP)this.#D(e,t);else try{writeFileSync$1(atomicWritePath(this.path),e,{mode:t})}catch(n){if(n?.code!==`EXDEV`)throw n;this.#D(e,t)}}#D(e,t){L.mkdirSync(N.dirname(atomicWritePath(this.path)),{recursive:!0});let n=L.statSync(this.path,{throwIfNoEntry:!1})?.mode,r=n!==void 0&&!(n&128);r&&L.chmodSync(this.path,n|128);let i=!1;try{L.writeFileSync(this.path,e,{mode:t}),i=!0}finally{L.existsSync(this.path)&&(i&&t!==void 0?L.chmodSync(this.path,t):r&&L.chmodSync(this.path,n))}}#O(){this.#w(),L.existsSync(this.path)||this.#T(createPlainObject());let reportChange=()=>{this.#s=void 0;let e=this.#u;this.#u=void 0,e!==void 0&&this.#B(e)||this.events.dispatchEvent(new Event(`change`))};R.platform===`win32`||R.platform===`darwin`?(this.#f=debounceFunction(reportChange,{wait:100}),this.#k(atomicWritePath(this.path)),this.#k(this.path)):(this.#f=debounceFunction(reportChange,{wait:1e3}),this.#d=()=>{this.#f?.()},L.watchFile(this.path,{persistent:!1,interval:500},this.#d))}#k(e){if(this.#l.has(e))return;let t=N.dirname(e),n=Cn.from(N.basename(e));L.mkdirSync(t,{recursive:!0}),this.#l.set(e,L.watch(t,{persistent:!1,encoding:`buffer`},(r,i)=>{(!i||i.equals(n)||isSameFile(N.join(t,i.toString(`utf8`)),e))&&this.#f?.()}))}#A(e,t,n,r){let i=getOwnProperty(r,Ws),a=getOwnProperty(r,Gs),s=new Set(Array.isArray(a)?a.filter(e=>typeof e==`string`):[]),c=i===void 0||isVersionInRangeFormat(i)?void 0:i,l=Object.keys(e).filter(e=>shouldPerformMigration(e,c,t)&&!isCompletedRange(e,t,s)).map(e=>({version:e,toVersion:versionToCompare(e,t)})).sort((e,t)=>Ta.default.compare(e.toVersion,t.toVersion)),u=l.map(({toVersion:e})=>e),f=c??`0.0.0`,p=r;for(let{version:r,toVersion:i}of l){let a;try{n&&n(this,{fromVersion:f,toVersion:i,finalVersion:t,versions:[...u]});let c=e[r];if(c?.(this),f=i,isVersionInRangeFormat(r))s.add(completedRangeFor(r,t)),a=this.#P(Gs,[...s],this.#g());else{let e=this.#g(),t=getOwnProperty(e,Ws);a=movesForward(r,t)?this.#P(Ws,r,e):e}p=a}catch(e){this.#m(p,!0);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}`)}}let m=l.length>0?this.#g():r;movesForward(t,getOwnProperty(m,Ws))&&this.#P(Ws,t,m)}#j(e){if(this.#M(e))throw TypeError(`Please don't use the ${Us} key, as it's used to manage this module internal operations.`)}#M(e){return typeof e==`string`?this.#N(e):!e||typeof e!=`object`?!1:Object.keys(e).some(e=>this.#N(e))}#N(e){if(!this.#r.accessPropertiesByDotNotation||!e.includes(`.`)&&!e.includes(`[`)&&!e.includes(`]`)&&!e.includes(`\\`))return e===Us;let t=keyPath(e);if(t===void 0)return!1;let[n]=t;return n===Us||keyPath(String(n))?.[0]===Us}#P(e,t,n){return detachUnwritableBookkeeping(n,parsePath(e)),setOwnProperty(n,e,t),this.#m(n,!0),n}#F(e,t,n){this.#r.accessPropertiesByDotNotation?setOwnProperty(e,t,n):e[t]=n}#I(e){this.#r.accessPropertiesByDotNotation&&keyPathOrReport(e)}#L(){let e=this.#t;if(!e)return this.#x(L.readFileSync(this.path,`utf8`));let t=L.readFileSync(this.path),n=this.#y(t,e);try{return this.#x(n)}catch(n){try{return this.#x(this.#y(t,e,!0))}catch{if(this.#n===`aes-256-cbc`)try{return this.#x(uint8ArrayToString(t))}catch{}throw n}}}get#R(){return!this.#r.serialize}#z(){return this.#r.cache?(this.#s??=freezeStoreValue(this.#_()),this.#s):this.#_()}#B(e){try{let t=L.readFileSync(this.path);return t.length===Cn.byteLength(e)&&t.equals(Cn.from(e))}catch{return!1}}#V(e){let t=this.#Y(createPlainObject());this.#c?this.#e?.(t):this.#C(t);let n=e?.[Us];if(n!==void 0&&(t[Us]=n),!this.#c){this.#w(),this.#p=!0;try{return this.#T(t),this.events.dispatchEvent(new Event(`change`)),this.#g()}finally{this.#p=!1}}return t}#H(e){let t=omitUndefined(e),n={...t,configName:t.configName??`config`,fileExtension:t.fileExtension??`json`,projectSuffix:t.projectSuffix??`nodejs`,clearInvalidConfig:t.clearInvalidConfig??!1,accessPropertiesByDotNotation:t.accessPropertiesByDotNotation??!0};if(n.defaults!==void 0&&n.defaults!==null){let e=Object.entries(omitUndefined(n.defaults));for(let[t,r]of e)checkValueType(t,r,!n.serialize);n.defaults=Object.fromEntries(e.map(([e,t])=>[e,ownValue(t,!n.serialize)]))}if(n.encryptionAlgorithm??=Rs,!Bs.has(n.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...Bs].join(`, `)}`);if(`encryptionKey`in n&&n.encryptionKey!==null&&!n.encryptionKey)throw TypeError("The `encryptionKey` option must not be empty, since an empty key leaves the store in plain text.");if(assertMigrations(n.migrations),!n.cwd){if(!n.projectName)throw Error("Please specify the `projectName` option.");n.cwd=envPaths(n.projectName,{suffix:n.projectSuffix}).config}return n}#U(e){if(assertObjectOption(`schema`,e.schema),assertObjectOption(`rootSchema`,e.rootSchema),assertObjectOption(`ajvOptions`,e.ajvOptions),!(e.schema??e.ajvOptions??e.rootSchema)){this.#J(e);return}if(e.rootSchema&&`properties`in e.rootSchema)throw TypeError("The `rootSchema` option must not contain a `properties` key. Use the `schema` option for properties.");let t=e.rootSchema?.type;if(t!==void 0&&!(Array.isArray(t)?t:[t]).includes(`object`))throw TypeError(`The \`rootSchema\` option must not name a \`type\` other than \`object\`, since a store is always an object, got \`${JSON.stringify(t)}\`.`);let n=omitUndefined(e.ajvOptions??{}),r=Ns.default.default,i=new Ms.Ajv2020({allErrors:!0,useDefaults:!0,...n});r(i),this.#K(e.schema,``,n.useDefaults!==!1),this.#J(e),this.#K(e.schema,``,n.useDefaults!==!1);let a={...e.rootSchema,type:`object`,properties:this.#G(e.schema)};this.#e=i.compile(a)}#W(e,t,n,r){for(let[i,a]of n.entries()){let s=String(a);if(t[s]===void 0){if(holdsValueRule(e,s))return;t[s]=!0}let c=t[s];if(i===n.length-1){c!==!1&&(t[s]=c===!0?{default:r}:{...c,default:r});return}if(typeof c!=`object`||!c)return;if(c.default!==void 0){let e=keyOfPath(n.slice(0,i+1));c={...c,default:ownValue(this.#h(this.#o,e),this.#R)},t[s]=c}let l=typeof c.properties==`object`&&c.properties!==null&&!Array.isArray(c.properties)?c.properties:void 0,{additionalProperties:u,unevaluatedProperties:f}=c;if(l===void 0&&u!==!1&&f!==!1)return;let p=Object.assign(createPlainObject(),l);e={...c,properties:p},t[s]=e,t=p}}#G(e){if(!this.#r.defaults)return e??void 0;let t=omitUndefined(e??{});for(let[e,n]of this.#i){let r=this.#r.accessPropertiesByDotNotation?keyPath(e):[e];if(r===void 0)continue;if(this.#r.accessPropertiesByDotNotation&&r.length>1){this.#W(this.#r.rootSchema,t,r,n);continue}let i=this.#r.accessPropertiesByDotNotation?String(r[0]):e;if(t[i]===!1||t[i]===void 0&&holdsValueRule(this.#r.rootSchema,i))continue;let a=t[i];t[i]=a===!0||a===void 0?{default:n}:{...a,default:n}}return t}#K(e,t,n){let r=t===``?qs:this.#h(this.#o,t,qs),i=Object.entries(e??{});for(let[e,a]of i){if(!a||typeof a!=`object`)continue;let i=t===``?e:`${t}.${keyOfPath([e])}`;if(t===``&&this.#N(e))throw TypeError(`The \`schema\` option must not contain the key \`${i}\`, which is the one this module keeps its bookkeeping under.`);if(this.#r.accessPropertiesByDotNotation){let n=t===``?whyKeyIsRefused(e):keyPath(i)===void 0?Js:void 0;if(n!==void 0)throw TypeError(`The \`schema\` option must not contain the key \`${i}\`, ${n}`)}let{default:s,properties:c}=a;Object.hasOwn(a,`default`)&&s!==void 0&&this.#r.ajvOptions?.useDefaults!==!1&&(checkValueType(i,s,this.#R),n&&this.#q(i,s));let l=this.#h(this.#o,i,qs),u=l===qs||typeof l==`object`&&!!l;if(this.#r.accessPropertiesByDotNotation&&typeof c==`object`&&c&&!Array.isArray(c)){let e=n&&u&&(r===qs||l!==qs);this.#K(c,i,e)}}}#q(e,t){this.#h(this.#o,e,qs)===qs&&(this.#r.accessPropertiesByDotNotation?whereWriteIsBlocked(this.#o,e)===void 0&&setOwnProperty(this.#o,e,ownValue(t,this.#R),!0):this.#o[e]=ownValue(t,this.#R))}#J(e){if(e.defaults){if(this.#j(e.defaults),this.#r.accessPropertiesByDotNotation)for(let[e,t]of this.#i){if(keyPath(e)===void 0)throw TypeError(`The \`defaults\` option cannot hold the key \`${e}\`, ${Js}`);whereWriteIsBlocked(this.#o,e)===void 0&&setOwnProperty(this.#o,e,ownValue(t,this.#R))}else Object.assign(this.#o,Object.fromEntries(this.#i.map(([e,t])=>[e,ownValue(t,this.#R)])))}}#Y(e){let t=this.#r.accessPropertiesByDotNotation,n;for(let[r,i]of this.#i){if(!(t?getOwnProperty(e,r,qs)===qs:!hasStoreKey(e,r)||e[r]===void 0))continue;let a=n??e;if(t){if(whereWriteIsBlocked(a,r)!==void 0||(n??=copyStoreDeep(e),!this.#X(n,r)))continue;setOwnProperty(n,r,ownValue(i,this.#R))}else n??=copyStore(e),Object.defineProperty(n,r,{value:ownValue(i,this.#R),writable:!0,enumerable:!0,configurable:!0})}return n??e}#X(e,t){if(this.#c)return!0;let n=keyPath(t)??[];for(let[r,i]of n.entries()){if(r===0)continue;let i=keyOfPath(n.slice(0,r));if(getOwnProperty(e,i,qs)!==qs)continue;let a=getOwnProperty(this.#o,i,qs);if(a===qs)continue;let s=ownValue(a,this.#R);return typeof s!=`object`||!s||whereWriteIsBlocked(s,t,r)!==void 0?!1:(setOwnProperty(e,i,s),!0)}return!0}#Z(e){e.serialize&&(this.#S=e.serialize),e.deserialize&&(this.#x=e.deserialize)}#Q(e){let t=N.resolve(e.cwd),n=typeof e.fileExtension==`string`?e.fileExtension.replace(/^\.+/,``):``,r=n===``?``:`.${n}`,i=`${e.configName??`config`}${r}`,a=N.resolve(t,i);if(i.includes(`\0`))throw TypeError(`The \`configName\` and \`fileExtension\` options must not hold a NUL byte, got \`${i.replaceAll(`\0`,String.raw`\0`)}\`.`);let s=N.relative(t,a);if(s===``||s===`..`||s.startsWith(`..${N.sep}`)||N.isAbsolute(s))throw TypeError(`The \`configName\` and \`fileExtension\` options must name a file inside \`cwd\`, got \`${i}\`, which resolves to \`${a}\`.`);return a}#$(){try{return L.readFileSync(this.path)}catch{return L.existsSync(this.path)?void 0:`absent`}}#ee(e){e===`absent`?L.rmSync(atomicWritePath(this.path),{force:!0}):e!==void 0&&this.#E(e,void 0)}#te(e){let t=e.migrations?this.#$():void 0;this.#ne(e);let n=this.#g(!1),r=this.#Y(copyStoreValue(n));try{this.#C(r)}catch(n){if(!e.clearInvalidConfig||!(n instanceof SchemaViolationError))throw this.#ee(t),n;try{let e=this.#Y(createPlainObject());this.#C(e),this.store=e}catch(e){throw this.#ee(t),e}return}nt(n,r)||(this.store=n)}#ne(e){let{migrations:t,projectVersion:n}=e;if(t){if(!n)throw Error("Please specify the `projectVersion` option.");if(Ta.default.valid(n)===null)throw Error(`The \`projectVersion\` option must be a valid semantic version, got \`${n}\``);this.#c=!0;try{let r=!L.existsSync(this.path),i=this.#g(),a=this.#Y(i);if(r){this.#P(Ws,n,a);return}nt(i,a)||this.#T(a),this.#A(t,n,e.beforeEachMigration,a)}finally{this.#c=!1}}}};const Xs={name:Bn,version:Vn},Zs=ue(()=>{try{return new Conf({projectName:Bn,clearInvalidConfig:!0,watch:!1})}catch(e){U.debug(`Failed to create config store`,{error:e});return}}),Qs=`check-update`;async function notifyAvailableUpdate(){if(Qt||en||tn===Qs||isInsideContainer())return;let e=Zs();if(!e)return;let t=e.get(`lastUpdateCheck`),n=e.get(`latestVersion`);if(ne(n)||ne(t)||t+864e5<Date.now())try{Xt(`likec4`,[`check-update`],{stdio:`ignore`,timeout:5e3,preferLocal:!0,detached:!0,env:{NODE_ENV:Qs}}).catch(()=>{})}catch{}else n&&(0,Ta.gt)(n,Xs.version)&&boxen([`Update available: `,m.dim(Xs.version),m.reset(` → `),m.green(n)].join(``))}async function checkAvailableUpdate(e=!0){try{let t=Zs();t?.set({lastUpdateCheck:Date.now()});let n=await fetchLatestVersion();if(I(n,`No version found in latest npm`),t?.set({lastUpdateCheck:Date.now(),latestVersion:n}),(0,Ta.gt)(n,Xs.version)){boxen([`Update available: `,m.dim(Xs.version),m.reset(` → `),m.green(n)].join(``));return}e&&boxen(m.dim(`Up to date: `)+` `+m.green(Xs.version))}catch(e){U.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!!et.createRequire(import.meta.url).resolve(e)}catch(e){return U.debug(i(e)),!1}}async function ensureReact(){if(isInstalled(`react`)&&isInstalled(`react-dom`)){U.debug(`react already installed`);return}U.warn(`react not installed`);let e=await Ie();e||(U.error`Package manager not detected, please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));let t=Fe(e.agent,`add`,[`react`,`react-dom`]);t||(U.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1));try{await Xt(t.command,t.args,{stdio:`inherit`})}catch(e){U.debug(i(e)),U.error`Please install dependencies manually: ${`react`} ${`react-dom`}`,process.exit(1)}}async function ensurePlaywright(){if(isInstalled(`playwright`)){U.debug(`playwright already installed`);return}U.warn(`playwright not installed`);let e=await Ie();e||(U.error`Package manager not detected, please install dependencies manually: ${`playwright`}`,process.exit(1));let t=Fe(e.agent,`add`,[`playwright`]);t||(U.error`Please install dependencies manually: ${`playwright`}`,process.exit(1));try{await Xt(t.command,t.args,{preferLocal:!0,stdio:`inherit`})}catch(e){U.debug(i(e)),U.error`Please install dependencies manually: ${`playwright`}`,process.exit(1)}}const K={type:`string`,desc:`<directory> with LikeC4 sources (default is current directory or 'LIKEC4_WORKSPACE' env)`,normalize:!0,default:Zt.LIKEC4_WORKSPACE||`.`,coerce:F};function withoutDefault(e){let{default:t,...n}=e;return t===void 0?n:{...n,defaultDescription:JSON.stringify(t)}}const $s={string:!0,desc:`path to the app config (default is likec4.app.config.{ts,js,..} in the workspace or the current directory), --no-app-config to ignore it`},ec={string:!0,desc:"file with UI customizations, default-exports `defineCustomComponents` from likec4/react",normalize:!0,nargs:1,coerce:F},q={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()},tc={boolean:!0,type:`boolean`,desc:"use `@likec4/core` package in types",default:!1},nc={boolean:!0,type:`boolean`,desc:`use hash history for navigation, e.g. "/#/view" instead of "/view"`},rc={alias:[`o`,`output`],string:!0,desc:`output directory`,normalize:!0,nargs:1,coerce:F},ic={alias:`w`,string:!0,desc:`prefix for Webcomponents, e.g "c4" generates <c4-view ../>`,default:`likec4`,nargs:1},ac={alias:`t`,string:!0,desc:`base title of the app pages (default is "LikeC4")`,default:`LikeC4`,nargs:1},oc={choices:[`light`,`dark`],desc:`default color scheme for the built website (default: auto, follows system preference)`,nargs:1},sc={alias:[`base-url`],string:!0,desc:`base url the app is being served from, e.g. "/" or "/pages/"`,nargs:1},cc={boolean:!0,desc:`outputs a single self-contained HTML file with all required resources inlined`},lc={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:F},uc={array:!0,string:!0,desc:`hostname allowed to respond to (Vite server.allowedHosts); can be repeated. Defaults to allowing all hosts.`,requiresArg:!0},dc={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},fc={number:!0,desc:`port number for the dev server (default is 5173, or PORT environment variable)`,nargs:1},pc={number:!0,desc:`port number for the HMR WebSocket server (default is auto-discovered from 24678-24690, or HMR_PORT environment variable)`,nargs:1},mc={alias:`p`,string:!0,desc:`select LikeC4 project by name (e.g. "my-project") or by path`,nargs:1},hc={hidden:!0,nargs:1,desc:`force log level`,choices:[`trace`,`debug`,`info`,`warning`,`error`],conflicts:[`verbose`]},gc={boolean:!0,desc:`verbose logging`,conflicts:[`log-level`]},_c=$t?`trace`:`debug`,vc=6e4,yc=vc*60*24*7;function showSupportUsMessage(){if(!(Qt||en))try{let e=Date.now(),t=Zs();if(!t)return;let n=t.get(`lastSupportUsMessage`);if(!n){t.set(`lastSupportUsMessage`,e-yc+5*vc);return}if(n+yc>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(`
202
+ `))}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`,withoutDefault(K)).option(`app-config`,$s).option(`output`,{alias:`o`,type:`string`,desc:`output directory for production build`,normalize:!0,coerce:F}).option(`base`,sc).option(`use-hash-history`,nc).option(`use-dot`,withoutDefault(q)).option(`webcomponent-prefix`,withoutDefault(ic)).option(`build-webcomponent`,{type:`boolean`,defaultDescription:`true`,describe:`enable/disable webcomponent build`}).option(`title`,withoutDefault(ac)).option(`customization`,ec).option(`output-single-file`,cc).option(`public`,lc).option(`theme`,oc).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();await notifyAvailableUpdate(),await ensureReact();let n=createLikeC4Logger(`c4:build`),r=await resolveAppConfig({appConfig:e[`app-config`],path:e.path,useDot:e[`use-dot`],base:e.base,title:e.title,theme:e.theme,useHashHistory:e[`use-hash-history`],webcomponentPrefix:e[`webcomponent-prefix`],customization:e.customization,publicDir:e.public,output:e.output,outputSingleFile:e[`output-single-file`],buildWebcomponent:e[`build-webcomponent`]});r.configFile&&n.info(`${m.cyan(`app config`)} ${m.dim(relativeToCwd(r.configFile))}`);let i=t.a(await S(r.workspace,{graphviz:r.graphviz,watch:!1})),a=r.build.outDir??F(i.workspace,`dist`),s=F(a,`assets`);await viteBuild({base:r.base,useHashHistory:r.build.singleFile||r.useHashHistory,customLogger:n,webcomponentPrefix:r.webcomponentPrefix,buildWebcomponent:r.build.webcomponent,title:r.title,theme:r.theme,customization:r.customization,languageServices:i,likec4AssetsDir:s,outputDir:a,outputSingleFile:r.build.singleFile,userPublicDir:r.publicDir}),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=F(t);if(n===e.workspace)return e.languageServices.projectsManager.ensureProjectId();if(It(n)&&Vt(n).isDirectory()){U.debug`Project path exists: ${n}`;let t=Ge.file(n.endsWith(bt)?n:n+bt),r=e.languageServices.projects().find(e=>e.folder.fsPath===t.fsPath);if(r)return U.debug`Found project ${r.id} at path: ${n}`,r.id;U.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 bc=U.getChild(`generator`);async function customHandler({name:e,path:t,useDotBin:n,project:r}){try{var i=_usingCtx();let a=startTimer(bc),s=i.a(await S(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:c,config:l}=ensureProject(s,r);r&&bc.info(`${m.dim(`project`)} ${m.green(c)}`);let u=l.generators?.[e];if(!u)throw bc.error(m.red(`generator ${e} does not exist in project config`)),Error(`generator ${e} does not exist in project config`);bc.info(`${m.dim(`generator`)} ${m.green(e)}`),await runCustomGenerator({likec4:s,model:await s.layoutedModel(c),generator:u,logger:bc.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 Kt(e):t=i.locate({element:e.id,projectId:c});break;case qt(e):t=i.locate({view:e.id,projectId:c});break;case Ut(e):t=i.locate({deployment:e.id,projectId:c});break;case Jt(e):case Gt(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=Ge.parse(t.uri);return{range:t.range,document:n,relativePath:Re.relative(s.folder,n),folder:Re.dirname(n).fsPath,filename:Re.basename(n)}},write:async({path:e,content:t})=>{let n;n=Array.isArray(e)?F(s.folder.fsPath,...e):Ge.isUri(e)?e.fsPath:F(s.folder.fsPath,`${e}`);let i=ht(n);a.has(i)||(It(i)||(r.debug(`${m.dim(`create directory`)} ${i}`),await ot(i,{recursive:!0})),a.add(i)),r.debug(`${m.dim(`write`)} ${n}`),await M(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?yt(...n):`.`}async function singleFileCodegenAction(e,t,n){t??=F(e.workspace,`likec4.generated.ts`),_t(t)!==`.ts`&&(t+=`.ts`),await ot(ht(t),{recursive:!0});let r=generateViewsDataTs([...(await e.layoutedModel()).views()].map(e=>e.$layouted));await M(t,r),n.info(`${m.dim(`generated`)} ${P(process.cwd(),t)}`)}async function dotCodegenAction(e,t,n){await ot(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=me(i.$data.views),s=0;for(let c of a)try{let a=await e.viewsService.layouter.dot({view:c,styles:i.$styles}),l=F(t,relativeOutputDir(c.sourcePath));r.has(l)||(await ot(l,{recursive:!0}),r.add(l));let u=F(l,c.id+`.dot`);await M(u,a),n.info(`${m.dim(`generated`)} ${P(process.cwd(),u)}`),s++}catch(e){U.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 ot(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=ye;break;case`mermaid`:i=`.mmd`,a=Te;break;case`plantuml`:i=`.puml`,a=Ce;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=F(n,relativeOutputDir(t.sourcePath));s.has(c)||(await ot(c,{recursive:!0}),s.add(c));let u=F(c,t.id+i),f=a(e);await M(u,f),r.info(`${m.dim(`generated`)} ${P(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 xc=ht(hn(import.meta.url));function readVersion(){try{let e=JSON.parse(Lt(yt(xc,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}try{let e=JSON.parse(Lt(yt(xc,`..`,`..`,`package.json`),`utf8`));if(e.version)return e.version}catch{}return`0.1.0`}const Sc=readVersion(),Cc=`leanix`,wc=/* @__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(!wc.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 Ec={manifestVersion:`1.0`,bridgeVersion:Sc,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={...Ec,...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(`
198
203
  query FindFactSheet($name: String!, $type: String!) {
199
204
  allFactSheets(filter: { name: $name, factSheetType: $type }) {
200
205
  edges { node { id name type } }
@@ -224,7 +229,7 @@ if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f insta
224
229
  relation { id }
225
230
  }
226
231
  }
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=`
232
+ `,{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,[Cc]:{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?.[Cc];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,[Cc]:{relationId:n,...c.external?.[Cc]}}});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=`
228
233
  query AllFactSheets($first: Int!, $after: String, $filter: FilterInput) {
229
234
  allFactSheets(first: $first, after: $after, filter: $filter) {
230
235
  edges {
@@ -258,26 +263,26 @@ if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f insta
258
263
  }
259
264
  }
260
265
  }
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(`
266
+ `,{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?.[Cc],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 Dc=`No project or empty model`,Oc=`LEANIX_API_TOKEN is required for likec4 sync leanix --apply`,kc=`default`,Ac=`manifest.json`,jc=`leanix-dry-run.json`,Mc=`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:kc}),n=toLeanixInventoryDryRun(e,{mappingProfile:kc});return{manifest:t,dryRun:n,report:buildBridgeReport(t,n)}}async function writeBridgeArtifacts(e,t,n,r=process.cwd()){await ot(e,{recursive:!0});let i=F(e,Ac),a=F(e,jc),s=F(e,Mc);await M(i,JSON.stringify(t.manifest,null,2)),await M(a,JSON.stringify(t.dryRun,null,2)),await M(s,JSON.stringify(t.report,null,2)),n.info(`${m.dim(`generated`)} ${P(r,i)}`),n.info(`${m.dim(`generated`)} ${P(r,a)}`),n.info(`${m.dim(`generated`)} ${P(r,s)}`)}const Nc={manifest:Ac,dryRun:jc,report:Mc};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===Ze.EMPTY)throw t.error(Dc),Error(Dc);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 ot(r,{recursive:!0});let s=F(r,`leanix-inventory-snapshot.json`);await M(s,JSON.stringify(a,null,2)),t.info(`${m.dim(`generated`)} ${P(process.cwd(),s)}`),t.info(`${m.dim(`snapshot`)} ${a.factSheets.length} fact sheets, ${a.relations.length} relations`)}finally{n.stopAndLog()}}const Pc=`manifest.json`,Fc=`leanix-inventory-snapshot.json`;async function readManifestAndSnapshot(e){let t=F(e,Pc),n=F(e,Fc),[r,i]=await Promise.all([ct(t,`utf-8`),ct(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===Ze.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 ${Pc} or ${Fc} from ${i}: ${n}`),e}let c;try{c=await loadDryRunFromWorkspace(r,a,s)}catch(e){let n=e instanceof Error?e.message:String(e);if(a!=null&&a!==``)throw t.error(`Failed to load workspace for dryRun enrichment: ${n}`),e;t.warn(`Could not load workspace for dryRun enrichment; proceeding without it: ${n}`),c=void 0}let l=reconcileInventoryWithManifest(n,e,{...c==null?{}:{dryRun:c}}),u=F(i,`reconciliation-report.json`);await M(u,JSON.stringify(l,null,2)),t.info(`${m.dim(`generated`)} ${P(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=F(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-model.ts`);if(r&&(g=vt(r)?r:F(r),It(r)&&(await pt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let v=mt(g);c.info(`${m.dim(`filename`)} ${v}`);let y=_t(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=ht(g);c.info(`${m.dim(`outdir`)} ${b}`),await ot(b,{recursive:!0}),await M(g,generateLikeC4Model(h,{useCorePackage:n}),{encoding:`utf-8`}),l.stopAndLog(),boxen(Xe(`
262
267
  ${m.dim(`Source generated:`)}
263
- ${E(tn(),g)}
268
+ ${P(an(),g)}
264
269
 
265
270
  ${m.dim(`How to use:`)}
266
271
  ${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(`
272
+ `).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`,customization:r}){let i=createLikeC4Logger([`vite`,`react`]),a=viteAppRoot();return i.info(`${m.cyan(`likec4 app root`)} ${m.dim(relativeToCwd(a))}`),i.info(m.cyan(`outDir`)+` `+m.dim(relativeToCwd(t))),{customLogger:i,root:a,configFile:!1,clearScreen:!1,publicDir:!1,mode:`production`,resolve:{alias:viteAliases(),dedupe:mi},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(\/.*)?$/,/^react-dom(\/.*)?$/]}},plugins:[De({ai:`disabled`,languageServices:e.languageServices,customization:r})]}}async function reactHandler({path:e,useDotBin:t,useCorePackage:n,outfile:r,project:i,customization:a}){try{var s=_usingCtx();await ensureReact();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(`react`)}`);let h=await u.layoutedModel(f),g=[...h.views()].map(e=>e.$layouted);if(g.length===0)throw process.exitCode=1,Error(`no views found`);g.forEach(e=>{e.drifts&&e.drifts.length>0?c.info(m.yellow(`layout drift detected, view:`)+` `+m.red(e.id)):e.hasLayoutDrift&&c.warn(m.yellow(`drift detected, manual layout can not be applied, view:`)+` `+m.red(e.id))});let v=F(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-views.js`);if(r&&(v=vt(r)?r:F(r),It(r)&&(await pt(r)).isDirectory()))throw Error(`output file is a directory: ${r}`);let y=ht(v);c.info(`${m.dim(`outdir`)} ${y}`);let b=mt(v);c.info(`${m.dim(`filename`)} ${b}`);let x=_t(b).toLocaleLowerCase();if(![`.js`,`.mjs`,`.jsx`].includes(x))throw c.error(`output file ${r} has extension "${x}"`),Error(`output file ${r} must be a .js, .jsx or .mjs`);let C=await viteReactConfig({languageServices:u,outDir:y,filename:b,customization:a});await _n({...C,logLevel:`warn`});let w=F(y,mt(v,x)+(x===`.mjs`?`.d.mts`:`.d.ts`));await M(w,generateReactTypes(h,{useCorePackage:n})),l.stopAndLog(),boxen(Xe(`
268
273
  ${m.dim(`Sources generated:`)}
269
- ${E(tn(),h)}
270
- ${E(tn(),ee)}
274
+ ${P(an(),v)}
275
+ ${P(an(),w)}
271
276
 
272
277
  ${m.dim(`How to use:`)}
273
278
  ${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(`
279
+ `),{padding:1,borderColor:`green`,borderStyle:`round`})}catch(e){s.e=e}finally{await s.d()}}async function webcomponentHandler({project:e,path:t,useDotBin:n,webcomponentPrefix:r=`likec4`,outfile:i,customization:a}){try{var s=_usingCtx();await ensureReact();let c=createLikeC4Logger(`c4:codegen`),l=startTimer(c),u=s.a(await S(t,{graphviz:n?`binary`:`wasm`,watch:!1})),{projectId:f,projectFolder:p}=ensureProject(u,e);e&&c.info(`${m.dim(`project`)} ${m.green(f)}`),c.info(`${m.dim(`format`)} ${m.green(`webcomponent`)}`);let h=[...(await u.layoutedModel(f)).views()].map(e=>e.$layouted);if(!he(h,1))throw c.warn(`no views found`),process.exitCode=1,Error(`no views found`);h.forEach(e=>{e.hasLayoutDrift&&c.warn(m.yellow(`drift detected, manual layout can not be applied, view:`)+` `+m.red(e.id))});let g=F(u.projectsManager.hasMultipleProjects()?p:u.workspace,`likec4-views.js`);if(i&&(g=vt(i)?i:F(i),It(i)&&(await pt(i)).isDirectory()))throw Error(`output file is a directory: ${i}`);c.debug(`${m.dim(`outfilepath`)} ${g}`);let v=mt(g);c.debug(`${m.dim(`filename`)} ${v}`);let y=_t(v).toLocaleLowerCase();if(y!==`.js`&&y!==`.mjs`)throw c.warn(`output file ${i} has extension "${y}"`),Error(`output file ${i} must be a .js or .mjs`);let b=await mkTempPublicDir();c.debug(`${m.dim(`created temp public`)} ${b}`);let x=viteWebcomponentConfig({languageServices:u,outDir:b,filename:v,webcomponentPrefix:r,base:`/`,customization:a});c.debug(`${m.dim(`vite build webcomponent`)}`),await _n({...x,logLevel:`warn`});let C=F(b,v);if(!It(C))throw Error(`output file not found: ${C}`);await ot(ht(g),{recursive:!0}),await it(C,g),c.info(`${m.dim(`generated`)} ${g}`),c.debug(`${m.dim(`remove temp public`)}`),await ft(b,{recursive:!0,force:!0}),l.stopAndLog(),boxen(Xe(`
275
280
  ${m.dim(`Webcomponents generated to:`)}
276
- ${E(tn(),h)}
281
+ ${P(an(),g)}
277
282
 
278
283
  ${m.dim(`Setup and usage instructions:`)}
279
284
  ${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:`)}
285
+ `))}catch(e){s.e=e}finally{await s.d()}}function logAppConfig(e){e&&U.info(`${m.cyan(`app config`)} ${m.dim(relativeToCwd(e))}`)}const codegenCmd=e=>e.command({command:`gen <command> [path]`,aliases:[`generate`,`codegen`],describe:`Generate various artifacts from LikeC4 sources`,builder:e=>e.positional(`path`,withoutDefault(K)).command(`react [path]`,`generate react component to render likec4 view`,e=>e.positional(`path`,withoutDefault(K)).option(`app-config`,$s).option(`customization`,ec).option(`project`,mc).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.jsx, .mjs or .js)`,normalize:!0,coerce:F}).option(`use-dot`,withoutDefault(q)).option(`use-core-package`,tc),async e=>{let t=await resolveAppConfig({appConfig:e[`app-config`],path:e.path,useDot:e[`use-dot`],customization:e.customization});logAppConfig(t.configFile),await reactHandler({project:e.project,useDotBin:t.graphviz===`binary`,path:t.workspace,outfile:e.outfile,useCorePackage:e.useCorePackage,customization:t.customization}),showSupportUsMessage()}).command({command:`webcomponent [path]`,aliases:[`wc`,`webcomp`],describe:`generate js with webcomponents`,builder:e=>e.positional(`path`,withoutDefault(K)).option(`app-config`,$s).option(`customization`,ec).option(`project`,mc).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.mjs or .js)`,normalize:!0,coerce:F}).option(`webcomponent-prefix`,withoutDefault(ic)).option(`use-dot`,withoutDefault(q)),handler:async e=>{let t=await resolveAppConfig({appConfig:e[`app-config`],path:e.path,useDot:e[`use-dot`],webcomponentPrefix:e[`webcomponent-prefix`],customization:e.customization});logAppConfig(t.configFile),await webcomponentHandler({project:e.project,useDotBin:t.graphviz===`binary`,path:t.workspace,outfile:e.outfile,webcomponentPrefix:t.webcomponentPrefix,customization:t.customization}),showSupportUsMessage()}}).command({command:`model [path]`,aliases:[`ts`],describe:`generate LikeC4Model (.ts)`,builder:e=>e.positional(`path`,K).option(`project`,mc).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> path to output file (.ts)`,normalize:!0,coerce:F}).option(`skip-layout`,{type:`boolean`,desc:`Skip layout (produce compute-only model, faster)`}).option(`use-dot`,q).option(`use-core-package`,tc),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`,K).option(`outfile`,{alias:[`o`,`output`],type:`string`,desc:`<file> output .ts file`,normalize:!0,coerce:F}).option(`use-dot`,q),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`,K).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`,K).option(`outdir`,{...rc,desc:`<dir> output directory for manifest.json, leanix-dry-run.json, report.json`}).option(`project`,mc).option(`use-dot`,q).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??F(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`,{...rc,default:F(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??F(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`,K).option(`outdir`,{...rc,default:F(process.cwd(),`out`,`bridge`),desc:`<dir> directory with manifest.json and leanix-inventory-snapshot.json`}).option(`project`,mc).option(`use-dot`,q).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??F(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`,K).option(`outdir`,rc).option(`use-dot`,q),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`,K).option(`outdir`,rc).option(`use-dot`,q),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`,K).option(`outdir`,rc).option(`use-dot`,q),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`,K).option(`outdir`,rc).option(`use-dot`,q),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`,K).option(`project`,mc).option(`use-dot`,q),handler:async e=>{await customHandler({name:`custom`,path:e.path,project:e.project,useDotBin:e.useDotBin})}}).epilog(`${m.bold(`Examples:`)}
281
286
  likec4 gen react -o dist/likec4-views.mjs ./src/likec4
282
287
  likec4 gen model -o likec4-model.ts
283
288
  likec4 gen leanix dry-run -o out/bridge
@@ -288,9 +293,12 @@ if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f insta
288
293
  likec4 gen mmd --outdir assets/
289
294
  likec4 gen plantuml --outdir assets/
290
295
  likec4 gen dot -o out .
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=`
296
+ `),handler:async e=>{await customHandler({name:e.command,path:e.path??K.coerce(K.default),project:e.project,useDotBin:e.useDotBin})}});function projectsToSearch(e,t){return t?[ensureProject(e,t).projectId]:[...e.projects()]}async function findProject(e,t,n){let r=[];for(let t of e)await n(t)&&r.push(t);let[i,...a]=r;return i&&a.length===0?{projectId:i}:{error:i?`${t} exists in projects ${r.join(`, `)}, select one with --project`:`${t} not found`}}function displayPath(e){return P(process.cwd(),hn(e))}function displayLocation(e,t){return`${displayPath(e)}:${t.start.line+1}:${t.start.character+1}`}function printPreview(e){let t=[m.bold(`${e.label} (dry run)`)];e.documents.length===0&&t.push(`No changes`),e.overlaps.length>0&&t.push(``,m.yellow(`Overlaps with other diffs (apply needs --accept-overlaps once their owners agreed):`),...e.overlaps.map(e=>` ${e}`));for(let n of e.documents){t.push(``,m.bold(`--- ${displayPath(n.uri)}`));for(let e of Ot(At(n.before,n.after),2))switch(e.type){case`skipped`:t.push(m.dim(`@@ ${e.count} unchanged line(s) @@`));break;case`added`:t.push(m.green(`+ ${e.line}`));break;case`removed`:t.push(m.red(`- ${e.line}`));break;default:t.push(` ${e.line}`)}}process.stdout.write(t.join(`
297
+ `)+`
298
+ `)}function reportEditResult(e,t,n){if(!n.applied)e.error(`${t} failed: ${n.error??`nothing changed`}`),process.exitCode=1;else if(n.remaining.length===0)e.info(`${m.green(t)}: done, no errors left`);else{e.warn(`${t}: done, ${n.remaining.length} error(s) left to fix manually`);for(let t of n.remaining){let n=t.diffId?`diff ${t.diffId}: `:``;e.warn(` ${displayLocation(t.uri,t.range)} ${n}${t.message}`)}process.exitCode=1}}function describeDiff(e,t){let{added:n,removed:r,modified:i}=e;return[`${t?`${m.dim(`${e.projectId}:`)} `:``}${m.bold(e.id)}${e.title?` ${m.dim(e.title)}`:``}`,` adds ${n.elements} element(s) and ${n.relations} relation(s), removes ${r.elements} element(s) and ${r.relations} relation(s), modifies ${i.elements} element(s)`,` changes ${e.views.length} view(s)${e.views.length>0?`: ${e.views.map(e=>e.id).join(`, `)}`:``}`]}async function applyDiff(e,t){try{var n=_usingCtx();let r=createLikeC4Logger(`c4:diff:${e}`),i=n.a(await S(t.path,{watch:!1}));i.hasErrors()&&r.warn(`The workspace has errors, the result may need manual fixes`);let a={type:`apply-diff`,diffId:xt(t.diff),action:e,acceptOverlaps:t.acceptOverlaps},s=await findProject(projectsToSearch(i,t.project),`Diff ${t.diff}`,async e=>!!(await i.parsedModel(e)).$data.diffs?.[a.diffId]);if(`error`in s){r.error(s.error),process.exitCode=1;return}let{projectId:c}=s;if(t.dryRun){let e=await i.modelEdits.preview(a,c);if(`error`in e){r.error(e.error),process.exitCode=1;return}printPreview(e);return}let l=await i.modelEdits.apply(a,{projectId:c});reportEditResult(r,`${e===`apply`?`Apply`:`Discard`} diff ${t.diff}`,l)}catch(e){n.e=e}finally{await n.d()}}const diffActionArgs=e=>e.positional(`diff`,{type:`string`,demandOption:!0,desc:`diff name`}).positional(`path`,K).option(`project`,mc).option(`dry-run`,{type:`boolean`,default:!1,desc:`print the changes without writing files`}),diffCmd=e=>e.command({command:`diff`,describe:`List, apply or discard model diffs`,builder:e=>e.command({command:`list [path]`,describe:`List model diffs and the views they change`,builder:e=>e.positional(`path`,K).option(`project`,mc).option(`json`,{type:`boolean`,default:!1,desc:`print as JSON`}),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:diff:list`),r=t.a(await S(e.path,{watch:!1,...e.json&&{printErrors:!1,configureLogger:`stderr`}})),i=projectsToSearch(r,e.project),a=[];for(let e of i)a.push(...(await r.modelDiffs.list(e)).map(t=>({projectId:e,...t})));if(e.json){process.stdout.write(JSON.stringify(a,null,2)+`
299
+ `);return}if(a.length===0){n.info(`No diffs found`);return}for(let e of a.flatMap(e=>describeDiff(e,i.length>1)))n.info(e)}catch(e){t.e=e}finally{await t.d()}}}).command({command:`apply <diff> [path]`,describe:`Apply the diff to the model (removes "remove" entries with their references, merges "add" blocks into the model)`,builder:e=>diffActionArgs(e).option(`accept-overlaps`,{type:`boolean`,default:!1,desc:`apply although the diff overlaps with other diffs (their owners agreed)`}),handler:e=>applyDiff(`apply`,e)}).command({command:`discard <diff> [path]`,describe:`Delete the diff without changing the model`,builder:diffActionArgs,handler:e=>applyDiff(`discard`,e)}).demandCommand(1,`Please choose: list, apply or discard`),handler:()=>{}}),Ic=/* @__PURE__ */ new Set([`node_modules`,`.git`]);function isSourceFile(e){return e.endsWith(`.c4`)||e.endsWith(`.likec4`)}function joinNonEmptyFiles(e,t=`
292
300
 
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:`)}
301
+ `){return e.filter(e=>e.trim()!==``).join(t)}const Lc=`No project or empty model`,Rc=`No views could be exported`;function getDrawioEpilog(){return`${m.bold(`Examples:`)}
294
302
  ${m.green(`$0 export drawio`)}
295
303
  ${m.gray(`Export each view to a separate .drawio file`)}
296
304
 
@@ -304,13 +312,13 @@ if(!c)throw Error(`ajv implementation error`);let{allErrors:u,props:f}=l;f insta
304
312
  ${m.gray(`Export with raw XML (no compression) for draw.io desktop compatibility`)}
305
313
 
306
314
  ${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(`
315
+ ${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 dt(e).catch(()=>null);if(a==null||r.has(a))return;r.add(a);let s=await ut(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=yt(e,r.name);switch(!0){case r.isDirectory():Ic.has(r.name)||await walk(a,i+1);break;case r.isSymbolicLink():if((await pt(a).catch(()=>null))?.isFile()&&isSourceFile(r.name)){let e=await ct(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 ct(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(F(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 xe(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=we(t,u),p=F(n,Ee);await M(p,f),l.info(`${m.dim(`generated`)} ${P(process.cwd(),p)} (${t.length} tab(s))`)}async function writeViewToFile(e,t,n,r){let i=String(e.$view.id);try{let a=ve(e,t[i]),s=F(n,i+`.drawio`);return await ot(ht(s),{recursive:!0}),await M(s,a),r.info(`${m.dim(`generated`)} ${P(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===Ze.EMPTY)throw t.error(Lc),Error(Lc);let c=[...s.views()];if(c.length===0)throw t.error(`No views to export`),Error(Rc);await ot(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(Rc),Error(Rc);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`,K).option(`outdir`,{alias:`o`,type:`string`,desc:`<dir> output directory for .drawio files`,normalize:!0,coerce:F}).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:mc,"use-dot":q}).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 oe(e.resolvedUrls.network)??oe(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
316
  `+``.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
317
+ `+``.padEnd(9,` `)):void 0].filter(e=>O(e)).join(`
318
+ `))}var Locked=class extends Error{constructor(e){super(`${e} is locked`)}};const zc={old:/* @__PURE__ */ new Set,young:/* @__PURE__ */ new Set},Bc=/* @__PURE__ */ new Set,Vc=1024,Hc=65535;let Uc;const getLocalHosts=()=>{let e=fn.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=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=>zc.old.has(e)||zc.young.has(e)||Bc.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??{};Uc===void 0&&(Uc=setTimeout(()=>{Uc=void 0,zc.old=zc.young,zc.young=/* @__PURE__ */ new Set},15e3),Uc.unref&&Uc.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?Bc.add(t):zc.young.add(t),t}catch(e){if(![`EADDRINUSE`,`EACCES`].includes(e.code)&&!(e instanceof Locked))throw e}throw Error(`No available ports found`)}function portNumbers(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))throw TypeError("`from` and `to` must be integer numbers");if(e<Vc||e>Hc)throw RangeError(`'from' must be between ${Vc} and ${Hc}`);if(t<Vc||t>Hc)throw RangeError(`'to' must be between ${Vc} and ${Hc}`);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(Zt.HMR_PORT){let e=Number.parseInt(Zt.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 st(yt(pn(),`.likec4-assets-`));let{isDev:v,...y}=await viteConfig({...g,languageServices:a,likec4AssetsDir:s,webcomponentPrefix:n,title:r}),b=y.customLogger;u??=Zt.PORT?parseInt(Zt.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`),C=await resolveHmrPort(f,t);if(t&&C!==void 0){let e=f?` (explicit)`:Zt.HMR_PORT?` (env)`:` (auto-discovered)`;b.info(`Enabling HMR: localhost:${C}${e}`),isInsideContainer()&&b.info(m.yellow(`ensure port ${C} is published from container`))}else t||b.info(`Disabling HMR`);let w=await vn({...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/jsx-dev-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,...C===void 0?{}:{port:C}},fs:{strict:!1},open:c??(!v&&!isInsideContainer())}});if(await w.listen(),e){let e=viteWebcomponentConfig({webcomponentPrefix:n,languageServices:a,outDir:x,base:y.base,customization:g.customization});b.info(`Building webcomponent`),await _n({...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 w}function createExportViewUrl({viewId:e,padding:t,theme:n,dynamicVariant:r,format:i=`png`,notation:a=!1,description:s=!1}){return ke(`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=de(x*200,{min:200,max:1e3});r.info(m.cyan(S)+m.dim(` attempt ${x} of ${a} after ${e}ms`)),await kn(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`,C=F(n,v,`${t.id}${b}`);g??=await e.newPage();let w=t.bounds;s===`sequence`&&t._type===`dynamic`&&(w=t.sequenceLayout.bounds),await g.setViewportSize({width:w.width+40+20,height:w.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(` -> ${P(n,C)}`)),await g.waitForSelector(`.react-flow.initialized`);let T=g.getByTestId(`export-page`),E=await T.boundingBox();if(E){let e=Math.ceil(E.width),t=Math.ceil(E.height),n=g.viewportSize();(!n||e>n.width||t>n.height)&&await g.setViewportSize({width:e,height:t})}t.nodes.some(e=>ae(e.icon)&&e.icon.toLowerCase().startsWith(`http`))&&await waitAllImages(g,i),await T.screenshot({animations:`disabled`,path:C,type:u===`jpeg`?`jpeg`:`png`,...u===`jpeg`?{quality:f??80,omitBackground:!1}:{omitBackground:!0}}),y.push({view:t,path:C})}catch(e){g?.close({runBeforeUnload:!0}).catch(e=>r.error(`failed to close page: ${e}`)),r.error(m.red(`failed `+S+`
319
+ `+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 resolveImageExportConfig(e,t){let n=await resolveAppConfig({appConfig:e[`app-config`],path:e.path,useDot:e[`use-dot`],customization:e.customization});return n.configFile&&t.info(`${m.cyan(`app config`)} ${m.dim(relativeToCwd(n.configFile))}`),{path:n.workspace,useDotBin:n.graphviz===`binary`,customization:n.customization}}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+`
320
+ `);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:C=!1,description:w=!1,customization:T}=e,E=n.a(await S(r,{graphviz:i?`binary`:`wasm`,watch:!1})),D=c??E.workspace,ee,te=u,O=[...E.languageServices.projects()];if(a&&!O.some(e=>e.id===a))throw t.error(`project not found: ${a}`),Error(`project not found: ${a}`);try{if(!te&&(t.info(m.cyan(`start preview server`)),ee=await viteDev({languageServices:E,buildWebcomponent:!1,openBrowser:!1,hmr:!1,customization:T}),te=resolveServerUrl(ee),!te))throw t.error(`Vite server is not ready, no resolvedUrls`),Error(`Vite server is not ready, no resolvedUrls`);for(let e of O){if(a&&e.id!==a)continue;O.length>1&&(t.info(m.dim(`---------`)),t.info(`${m.dim(`project:`)} ${e.id}`),t.info(`${m.dim(`folder:`)} ${e.folder.fsPath}`));let n=[...(await E.layoutedModel(e.id)).views()].map(e=>e.$layouted);if(g&&he(g,1)&&he(n,1)){let e=ln(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(!he(n,1)){t.warn(`no views found`);continue}let r=O.length>1?Ae(je(te,`project`,e.id)):te,i=O.length>1?je(D,e.id):D,c=sn(),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:C,description:w}),{pretty:S}=inMillis(c);if(u.length>0&&t.info(m.green(`exported ${u.length} views in ${S}`)+`
321
+ `),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{ee&&(t.info(m.cyan(`stop server`)),await ee.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`,withoutDefault(K)).options({"app-config":$s,customization:ec,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:F},project:mc,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":withoutDefault(q),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
322
  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
323
  ${m.green(`$0 export png`)}
316
324
  ${m.gray(`Search for likec4 files in current directory and output PNG next to sources`)}
@@ -323,7 +331,7 @@ multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`cont
323
331
 
324
332
  ${m.green(`$0 export png -f "use-case*" --sequence src/likec4`)}
325
333
  ${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
334
+ `),handler:async e=>{I(e.timeout>=1,`timeout must be >= 1`),I(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await pngHandler({...await resolveImageExportConfig(e,createLikeC4Logger(`c4:export`)),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`,withoutDefault(K)).options({"app-config":$s,customization:ec,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:F},project:mc,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":withoutDefault(q),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
335
  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
336
  ${m.green(`$0 export jpg`)}
329
337
  ${m.gray(`Search for likec4 files in current directory and output JPEG next to sources`)}
@@ -336,20 +344,20 @@ multiple patterns are combined with OR`},ignore:{boolean:!0,alias:`i`,desc:`cont
336
344
 
337
345
  ${m.green(`$0 export jpg -f "team1*" -f "team2*" --flat -o ./jpg src/likec4`)}
338
346
  ${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:`)}
347
+ `),handler:async e=>{I(e.quality>=1&&e.quality<=100,`quality must be between 1 and 100`),I(e.timeout>=1,`timeout must be >= 1`),I(e[`max-attempts`]>=1,`max-attempts must be >= 1`),await ensureReact(),await ensurePlaywright();let t=e.theme??(e.dark?`dark`:`light`);await jpgHandler({...await resolveImageExportConfig(e,createLikeC4Logger(`c4:export`)),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 Wc=`project not found`,Gc=`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),!he(a,1))throw t.error(`${Wc}: ${e.project}`),Error(`${Wc}: ${e.project}`)}else{if(!he(a,1))throw t.error(Gc),Error(Gc);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===Ze.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;_t(c).toLowerCase()!==`.json`&&(c+=`.json`),await ot(ht(c),{recursive:!0});let l=s.length===1?s[0]:s,u=e.pretty?JSON.stringify(l,void 0,2):JSON.stringify(l);await M(c,u);let f=c.startsWith(e.path)?P(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`,K).option(`outfile`,{alias:`o`,type:`string`,desc:`<file> output .json file`,default:`likec4.json`,normalize:!0,coerce:F}).options({project:mc,"use-dot":q,"skip-layout":{type:`boolean`,desc:`skip layout (produce compute-only model, faster)`},pretty:{type:`boolean`,desc:`indented JSON output`}}).epilog(`${m.bold(`Examples:`)}
340
348
  ${m.green(`$0 export json --skip-layout`)}
341
349
  ${m.gray(`Search for likec4 files in current directory and output JSON to likec4.json (no layout)`)}
342
350
 
343
351
  ${m.green(`$0 export json --pretty -o ./generated/likec4.json src/likec4 `)}
344
352
  ${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:`)}
353
+ `),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 Kc=`project not found`,qc=`<!-- 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 ct(e,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!0;throw e}return n.startsWith(qc)}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(`${Kc}: ${e.project}`),Error(`${Kc}: ${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===Ze.EMPTY||!hasAuthoredViews(r)){t.warn(m.yellow(`Project ${n.id} has no views, skipping`));continue}let a=yt(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 M(a,`${qc}\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`,K).options({project:mc,"use-dot":q,force:{type:`boolean`,desc:`overwrite an existing README.md even if it was not generated by this command`}}).epilog(`${m.bold(`Examples:`)}
346
354
  ${m.green(`$0 export markdown`)}
347
355
  ${m.gray(`Render every project to README.md in its own project folder`)}
348
356
 
349
357
  ${m.green(`$0 export markdown -p my-project src/likec4`)}
350
358
  ${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:`)}
359
+ `),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`,K).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=>F(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=>gn(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(` ${hn(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=P(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(hn(t))} (not found in workspace)`)}let f=0,p=0,h=[];for(let[e,t]of l){let r=hn(e),a=displayPath(r),s;try{s=await ct(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 M(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(`
360
+ `)}`),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,w[e]]));console.log(JSON.stringify(e,null,2));break}default:for(let e of t)for(let t of w[e])console.log(`${e}:${t}`)}}});var Jc=/* @__PURE__ */ r(((t,n,r)=>{var i=r&&r.__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]})),a=r&&r.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),s=r&&r.__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 n=ownKeys(e),r=0;r<n.length;r++)n[r]!=="default"&&i(t,e,n[r]);return a(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 c=s(e(`node:url`)),l=s(e(`node:path`)),u=s(e(`node:fs`)),f=e(`node:child_process`);function uriToFilePath(e){let t=c.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 l.normalize(n.join(`/`))}function isWindows(){return process.platform===`win32`}function resolve(e,t,n,r){let i=`NODE_PATH`;return new Promise((a,s)=>{let c=process.env,p=Object.create(null);Object.keys(c).forEach(e=>p[e]=c[e]),t&&u.existsSync(t)&&(p[i]?p[i]=t+l.delimiter+p[i]:p[i]=t,r&&r(`NODE_PATH value is: ${p[i]}`)),p.ELECTRON_RUN_AS_NODE=`1`;try{let t=(0,f.fork)(``,[],{cwd:n,env:p,execArgv:[`-e`,`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});}}});`]});if(t.pid===void 0){s(/* @__PURE__ */ Error(`Starting process to resolve node module ${e} failed`));return}t.on(`error`,e=>{s(e)}),t.on(`message`,n=>{n.c===`r`&&(t.send({c:`e`}),n.s?a(n.r):s(/* @__PURE__ */ Error(`Failed to resolve module: ${e}`)))});let r={c:`rs`,a:e};t.send(r)}catch(e){s(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,f.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()?l.join(i,`node_modules`):l.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,f.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 l.join(t.data,`node_modules`)}catch{}return}catch{return}finally{process.removeListener(`SIGPIPE`,handler)}}var p;(function(e){let t;function isCaseSensitive(){return t===void 0&&(t=process.platform===`win32`?!1:!u.existsSync(__filename.toUpperCase())||!u.existsSync(__filename.toLowerCase())),t}e.isCaseSensitive=isCaseSensitive;function isParent(e,t){return isCaseSensitive()?l.normalize(t).indexOf(l.normalize(e))===0:l.normalize(t).toLowerCase().indexOf(l.normalize(e).toLowerCase())===0}e.isParent=isParent})(p||(t.FileSystem=p={}));function resolveModulePath(e,t,n,r){return n?(l.isAbsolute(n)||(n=l.join(e,n)),resolve(t,n,n,r).then(e=>p.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)}})),Yc=/* @__PURE__ */ r((t=>{Object.defineProperty(t,"__esModule",{value:!0});let n=e(`node:util`),r=He();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})),Xc=/* @__PURE__ */ r(((t,n,r)=>{var i=r&&r.__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]})),a=r&&r.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),s=r&&r.__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 n=ownKeys(e),r=0;r<n.length;r++)n[r]!=="default"&&i(t,e,n[r]);return a(t,e),t}})(),c=r&&r.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&i(t,e,n)},l=r&&r.__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 u=l(Yc());u.default.install();let f=s(e(`node:path`)),p=s(e(`node:os`)),m=s(e(`node:fs`)),h=e(`node:crypto`),g=e(`node:net`),v=He();c(He(),t);var IPCMessageReader=class extends v.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),v.Disposable.create(()=>this.process.off(`message`,e))}};t.IPCMessageReader=IPCMessageReader;var IPCMessageWriter=class extends v.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 v.AbstractMessageReader{onData;constructor(e){super(),this.onData=new v.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 v.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 v.ReadableStreamMessageReader{constructor(e,t=`utf-8`){super((0,u.default)().stream.asReadableStream(e),t)}};t.SocketMessageReader=SocketMessageReader;var SocketMessageWriter=class extends v.WriteableStreamMessageWriter{socket;constructor(e,t){super((0,u.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};t.SocketMessageWriter=SocketMessageWriter;var StreamMessageReader=class extends v.ReadableStreamMessageReader{constructor(e,t){super((0,u.default)().stream.asReadableStream(e),t)}};t.StreamMessageReader=StreamMessageReader;var StreamMessageWriter=class extends v.WriteableStreamMessageWriter{constructor(e,t){super((0,u.default)().stream.asWritableStream(e),t)}};t.StreamMessageWriter=StreamMessageWriter;let y=process.env.XDG_RUNTIME_DIR,b=/* @__PURE__ */ new Map([[`linux`,107],[`darwin`,102]]);function generateRandomPipeName(){if(process.platform===`win32`)return`\\\\.\\pipe\\lsp-${(0,h.randomBytes)(16).toString(`hex`)}-sock`;let e=32,t=m.realpathSync(y??p.tmpdir()),n=b.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,h.randomBytes)(Math.floor(e/2)).toString(`hex`);return f.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,g.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,g.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,g.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,g.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||=v.NullLogger;let i=isReadableStream(e)?new StreamMessageReader(e):e,a=isWritableStream(t)?new StreamMessageWriter(t):t;return v.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,v.createMessageConnection)(i,a,n,r)}})),Zc=/* @__PURE__ */ r(((e,t,n)=>{var r=n&&n.__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]})),i=n&&n.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&r(t,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.createProtocolConnection=createProtocolConnection;let a=Xc();i(Xc(),e),i(ze(),e);function createProtocolConnection(e,t,n,r){return(0,a.createMessageConnection)(e,t,n,r)}})),Qc=(/* @__PURE__ */ r(((t,n,r)=>{var i=r&&r.__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]})),a=r&&r.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),s=r&&r.__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 n=ownKeys(e),r=0;r<n.length;r++)n[r]!=="default"&&i(t,e,n[r]);return a(t,e),t}})(),c=r&&r.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0,t.createConnection=createConnection;let l=e(`node:util`),u=s(Be()),f=Ue(),p=s(Jc()),m=Zc();c(Zc(),t),c(We(),t);var h;(function(e){e.uriToFilePath=p.uriToFilePath,e.resolveGlobalNodePath=p.resolveGlobalNodePath,e.resolveGlobalYarnPath=p.resolveGlobalYarnPath,e.resolve=p.resolve,e.resolveModulePath=p.resolveModulePath})(h||(t.Files=h={}));let g=!1,v;function setupExitTimer(){let e=`--clientProcessId`;function runTimer(e){try{let t=parseInt(e);isNaN(t)||(v=setInterval(()=>{try{process.kill(t,0)}catch{process.exit(+!g)}},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 y={initialize:e=>{let t=e.processId;u.number(t)&&v===void 0&&setInterval(()=>{try{process.kill(t,0)}catch{process.exit(+!g)}},3e3)},get shutdownReceived(){return g},set shutdownReceived(e){g=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),m.ConnectionStrategy.is(e)||m.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 m.IPCMessageReader(process),t=new m.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,m.createServerSocketTransport)(n);e=r[0],t=r[1]}else if(r){let n=(0,m.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(u.func(e.read)&&u.func(e.on)){let t=e;t.on(`end`,()=>{process.exit(+!g)}),t.on(`close`,()=>{process.exit(+!g)})}let connectionFactory=r=>{let a=(0,m.createProtocolConnection)(e,t,r,n);return i&&patchConsole(r),a};return(0,f.createConnection)(connectionFactory,y,r)}function patchConsole(e){function serialize(e){return e.map(e=>typeof e==`string`?e:(0,l.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,l.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`,hc).option(`verbose`,gc).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`,q).showHidden().epilog(`${m.bold(`Examples:`)}
353
361
 
354
362
  ${m.green(`$0 lsp --stdio `)}
355
363
  ${m.gray(`Start LSP with stdio transport`)}
@@ -357,19 +365,19 @@ ${m.gray(`Start LSP with stdio transport`)}
357
365
  ${m.green(`$0 lsp --node-ipc --watch --no-manual-layouts --no-color `)}
358
366
  ${m.gray(`Start LSP with node-ipc transport and watcher, disabled manual layouts and disabled color`)}
359
367
 
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
368
+ `),handler:e=>{let t;if(e.nodeIpc||e.stdio||e.socket||e.pipe)t=(0,Qc.createConnection)(Qc.ProposedFeatures.all);else throw Error(`No transport specified`);f({lspConnection:t,useStdErr:e.stdio===!0,colors:m.isColorSupported,enableTelemetry:e.telemetry,logLevel:e.verbose?_c: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;nl.add(onLeave);try{let a=r?r.run(e,i):i();return n||(t=void 0),await a}finally{nl.delete(onLeave)}}}}function createNamespace(e={}){let t={};return{get(n,r={}){return t[n]||(t[n]=createContext({...e,...r})),t[n]}}}const $c=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof global<`u`?global:typeof window<`u`?window:{},el=`__unctx__`;$c[el]||($c[el]=createNamespace());const tl=`__unctx_async_handlers__`,nl=$c[tl]||($c[tl]=/* @__PURE__ */ new Set),rl=createContext(),il=createContext();function useLanguageServices(){return il.use()}function setMcpServerCtx(e){return e?rl.set(e,!0):rl.unset(),e}function setLanguageServicesCtx(e){return e?il.set(e,!0):il.unset(),e}const al=`2025-11-25`,ol=[al,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],sl=`io.modelcontextprotocol/related-task`,J=A.custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),cl=A.union([A.string(),A.number().int()]),ll=A.string();A.looseObject({ttl:A.number().optional(),pollInterval:A.number().optional()});const ul=A.object({ttl:A.number().optional()}),dl=A.object({taskId:A.string()}),fl=A.looseObject({progressToken:cl.optional(),[sl]:dl.optional()}),pl=A.object({_meta:fl.optional()}),ml=pl.extend({task:ul.optional()}),isTaskAugmentedRequestParams=e=>ml.safeParse(e).success,hl=A.object({method:A.string(),params:pl.loose().optional()}),gl=A.object({_meta:fl.optional()}),_l=A.object({method:A.string(),params:gl.loose().optional()}),vl=A.looseObject({_meta:fl.optional()}),yl=A.union([A.string(),A.number().int()]),bl=A.object({jsonrpc:A.literal(`2.0`),id:yl,...hl.shape}).strict(),isJSONRPCRequest=e=>bl.safeParse(e).success,xl=A.object({jsonrpc:A.literal(`2.0`),..._l.shape}).strict(),isJSONRPCNotification=e=>xl.safeParse(e).success,Sl=A.object({jsonrpc:A.literal(`2.0`),id:yl,result:vl}).strict(),isJSONRPCResultResponse=e=>Sl.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 Cl=A.object({jsonrpc:A.literal(`2.0`),id:yl.optional(),error:A.object({code:A.number().int(),message:A.string(),data:A.unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>Cl.safeParse(e).success,wl=A.union([bl,xl,Sl,Cl]);A.union([Sl,Cl]);const Tl=vl.strict(),El=gl.extend({requestId:yl.optional(),reason:A.string().optional()}),Dl=_l.extend({method:A.literal(`notifications/cancelled`),params:El}),Ol=A.object({src:A.string(),mimeType:A.string().optional(),sizes:A.array(A.string()).optional(),theme:A.enum([`light`,`dark`]).optional()}),kl=A.object({icons:A.array(Ol).optional()}),Al=A.object({name:A.string(),title:A.string().optional()}),jl=Al.extend({...Al.shape,...kl.shape,version:A.string(),websiteUrl:A.string().optional(),description:A.string().optional()}),Ml=A.intersection(A.object({applyDefaults:A.boolean().optional()}),A.record(A.string(),A.unknown())),Nl=A.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,A.intersection(A.object({form:Ml.optional(),url:J.optional()}),A.record(A.string(),A.unknown()).optional())),Pl=A.looseObject({list:J.optional(),cancel:J.optional(),requests:A.looseObject({sampling:A.looseObject({createMessage:J.optional()}).optional(),elicitation:A.looseObject({create:J.optional()}).optional()}).optional()}),Fl=A.looseObject({list:J.optional(),cancel:J.optional(),requests:A.looseObject({tools:A.looseObject({call:J.optional()}).optional()}).optional()}),Il=A.object({experimental:A.record(A.string(),J).optional(),sampling:A.object({context:J.optional(),tools:J.optional()}).optional(),elicitation:Nl.optional(),roots:A.object({listChanged:A.boolean().optional()}).optional(),tasks:Pl.optional(),extensions:A.record(A.string(),J).optional()}),Ll=pl.extend({protocolVersion:A.string(),capabilities:Il,clientInfo:jl}),Rl=hl.extend({method:A.literal(`initialize`),params:Ll}),isInitializeRequest=e=>Rl.safeParse(e).success,zl=A.object({experimental:A.record(A.string(),J).optional(),logging:J.optional(),completions:J.optional(),prompts:A.object({listChanged:A.boolean().optional()}).optional(),resources:A.object({subscribe:A.boolean().optional(),listChanged:A.boolean().optional()}).optional(),tools:A.object({listChanged:A.boolean().optional()}).optional(),tasks:Fl.optional(),extensions:A.record(A.string(),J).optional()}),Bl=vl.extend({protocolVersion:A.string(),capabilities:zl,serverInfo:jl,instructions:A.string().optional()}),Vl=_l.extend({method:A.literal(`notifications/initialized`),params:gl.optional()}),Hl=hl.extend({method:A.literal(`ping`),params:pl.optional()}),Ul=A.object({progress:A.number(),total:A.optional(A.number()),message:A.optional(A.string())}),Wl=A.object({...gl.shape,...Ul.shape,progressToken:cl}),Gl=_l.extend({method:A.literal(`notifications/progress`),params:Wl}),Kl=pl.extend({cursor:ll.optional()}),ql=hl.extend({params:Kl.optional()}),Jl=vl.extend({nextCursor:ll.optional()}),Yl=A.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xl=A.object({taskId:A.string(),status:Yl,ttl:A.union([A.number(),A.null()]),createdAt:A.string(),lastUpdatedAt:A.string(),pollInterval:A.optional(A.number()),statusMessage:A.optional(A.string())}),Zl=vl.extend({task:Xl}),Ql=gl.merge(Xl),$l=_l.extend({method:A.literal(`notifications/tasks/status`),params:Ql}),eu=hl.extend({method:A.literal(`tasks/get`),params:pl.extend({taskId:A.string()})}),tu=vl.merge(Xl),nu=hl.extend({method:A.literal(`tasks/result`),params:pl.extend({taskId:A.string()})});vl.loose();const ru=ql.extend({method:A.literal(`tasks/list`)}),iu=Jl.extend({tasks:A.array(Xl)}),au=hl.extend({method:A.literal(`tasks/cancel`),params:pl.extend({taskId:A.string()})}),ou=vl.merge(Xl),su=A.object({uri:A.string(),mimeType:A.optional(A.string()),_meta:A.record(A.string(),A.unknown()).optional()}),cu=su.extend({text:A.string()}),lu=A.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),uu=su.extend({blob:lu}),du=A.enum([`user`,`assistant`]),fu=A.object({audience:A.array(du).optional(),priority:A.number().min(0).max(1).optional(),lastModified:A.iso.datetime({offset:!0}).optional()}),pu=A.object({...Al.shape,...kl.shape,uri:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),size:A.optional(A.number()),annotations:fu.optional(),_meta:A.optional(A.looseObject({}))}),mu=A.object({...Al.shape,...kl.shape,uriTemplate:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),annotations:fu.optional(),_meta:A.optional(A.looseObject({}))}),hu=ql.extend({method:A.literal(`resources/list`)}),gu=Jl.extend({resources:A.array(pu)}),_u=ql.extend({method:A.literal(`resources/templates/list`)}),vu=Jl.extend({resourceTemplates:A.array(mu)}),yu=pl.extend({uri:A.string()}),bu=yu,xu=hl.extend({method:A.literal(`resources/read`),params:bu}),Su=vl.extend({contents:A.array(A.union([cu,uu]))}),Cu=_l.extend({method:A.literal(`notifications/resources/list_changed`),params:gl.optional()}),wu=yu,Tu=hl.extend({method:A.literal(`resources/subscribe`),params:wu}),Eu=yu,Du=hl.extend({method:A.literal(`resources/unsubscribe`),params:Eu}),Ou=gl.extend({uri:A.string()}),ku=_l.extend({method:A.literal(`notifications/resources/updated`),params:Ou}),Au=A.object({name:A.string(),description:A.optional(A.string()),required:A.optional(A.boolean())}),ju=A.object({...Al.shape,...kl.shape,description:A.optional(A.string()),arguments:A.optional(A.array(Au)),_meta:A.optional(A.looseObject({}))}),Mu=ql.extend({method:A.literal(`prompts/list`)}),Nu=Jl.extend({prompts:A.array(ju)}),Pu=pl.extend({name:A.string(),arguments:A.record(A.string(),A.string()).optional()}),Fu=hl.extend({method:A.literal(`prompts/get`),params:Pu}),Iu=A.object({type:A.literal(`text`),text:A.string(),annotations:fu.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),Lu=A.object({type:A.literal(`image`),data:lu,mimeType:A.string(),annotations:fu.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),Ru=A.object({type:A.literal(`audio`),data:lu,mimeType:A.string(),annotations:fu.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),zu=A.object({type:A.literal(`tool_use`),name:A.string(),id:A.string(),input:A.record(A.string(),A.unknown()),_meta:A.record(A.string(),A.unknown()).optional()}),Bu=A.object({type:A.literal(`resource`),resource:A.union([cu,uu]),annotations:fu.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),Vu=pu.extend({type:A.literal(`resource_link`)}),Hu=A.union([Iu,Lu,Ru,Vu,Bu]),Uu=A.object({role:du,content:Hu}),Wu=vl.extend({description:A.string().optional(),messages:A.array(Uu)}),Gu=_l.extend({method:A.literal(`notifications/prompts/list_changed`),params:gl.optional()}),Ku=A.object({title:A.string().optional(),readOnlyHint:A.boolean().optional(),destructiveHint:A.boolean().optional(),idempotentHint:A.boolean().optional(),openWorldHint:A.boolean().optional()}),qu=A.object({taskSupport:A.enum([`required`,`optional`,`forbidden`]).optional()}),Ju=A.object({...Al.shape,...kl.shape,description:A.string().optional(),inputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),J).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()),outputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),J).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()).optional(),annotations:Ku.optional(),execution:qu.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),Yu=ql.extend({method:A.literal(`tools/list`)}),Xu=Jl.extend({tools:A.array(Ju)}),Zu=vl.extend({content:A.array(Hu).default([]),structuredContent:A.record(A.string(),A.unknown()).optional(),isError:A.boolean().optional()});Zu.or(vl.extend({toolResult:A.unknown()}));const Qu=ml.extend({name:A.string(),arguments:A.record(A.string(),A.unknown()).optional()}),$u=hl.extend({method:A.literal(`tools/call`),params:Qu}),ed=_l.extend({method:A.literal(`notifications/tools/list_changed`),params:gl.optional()});A.object({autoRefresh:A.boolean().default(!0),debounceMs:A.number().int().nonnegative().default(300)});const td=A.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),nd=pl.extend({level:td}),rd=hl.extend({method:A.literal(`logging/setLevel`),params:nd}),id=gl.extend({level:td,logger:A.string().optional(),data:A.unknown()}),ad=_l.extend({method:A.literal(`notifications/message`),params:id}),od=A.object({name:A.string().optional()}),sd=A.object({hints:A.array(od).optional(),costPriority:A.number().min(0).max(1).optional(),speedPriority:A.number().min(0).max(1).optional(),intelligencePriority:A.number().min(0).max(1).optional()}),cd=A.object({mode:A.enum([`auto`,`required`,`none`]).optional()}),ld=A.object({type:A.literal(`tool_result`),toolUseId:A.string().describe(`The unique identifier for the corresponding tool call.`),content:A.array(Hu).default([]),structuredContent:A.object({}).loose().optional(),isError:A.boolean().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),ud=A.discriminatedUnion(`type`,[Iu,Lu,Ru]),dd=A.discriminatedUnion(`type`,[Iu,Lu,Ru,zu,ld]),fd=A.object({role:du,content:A.union([dd,A.array(dd)]),_meta:A.record(A.string(),A.unknown()).optional()}),pd=ml.extend({messages:A.array(fd),modelPreferences:sd.optional(),systemPrompt:A.string().optional(),includeContext:A.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:A.number().optional(),maxTokens:A.number().int(),stopSequences:A.array(A.string()).optional(),metadata:J.optional(),tools:A.array(Ju).optional(),toolChoice:cd.optional()}),md=hl.extend({method:A.literal(`sampling/createMessage`),params:pd}),hd=vl.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(A.string())),role:du,content:ud}),gd=vl.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A.string())),role:du,content:A.union([dd,A.array(dd)])}),_d=A.object({type:A.literal(`boolean`),title:A.string().optional(),description:A.string().optional(),default:A.boolean().optional()}),vd=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),minLength:A.number().optional(),maxLength:A.number().optional(),format:A.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:A.string().optional()}),yd=A.object({type:A.enum([`number`,`integer`]),title:A.string().optional(),description:A.string().optional(),minimum:A.number().optional(),maximum:A.number().optional(),default:A.number().optional()}),bd=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),default:A.string().optional()}),xd=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),oneOf:A.array(A.object({const:A.string(),title:A.string()})),default:A.string().optional()}),Sd=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),enumNames:A.array(A.string()).optional(),default:A.string().optional()}),Cd=A.union([bd,xd]),wd=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({type:A.literal(`string`),enum:A.array(A.string())}),default:A.array(A.string()).optional()}),Td=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({anyOf:A.array(A.object({const:A.string(),title:A.string()}))}),default:A.array(A.string()).optional()}),Ed=A.union([wd,Td]),Dd=A.union([Sd,Cd,Ed]),Od=A.union([Dd,_d,vd,yd]),kd=ml.extend({mode:A.literal(`form`).optional(),message:A.string(),requestedSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),Od),required:A.array(A.string()).optional()})}),Ad=ml.extend({mode:A.literal(`url`),message:A.string(),elicitationId:A.string(),url:A.string().url()}),jd=A.union([kd,Ad]),Md=hl.extend({method:A.literal(`elicitation/create`),params:jd}),Nd=gl.extend({elicitationId:A.string()}),Pd=_l.extend({method:A.literal(`notifications/elicitation/complete`),params:Nd}),Fd=vl.extend({action:A.enum([`accept`,`decline`,`cancel`]),content:A.preprocess(e=>e===null?void 0:e,A.record(A.string(),A.union([A.string(),A.number(),A.boolean(),A.array(A.string())])).optional())}),Id=A.object({type:A.literal(`ref/resource`),uri:A.string()}),Ld=A.object({type:A.literal(`ref/prompt`),name:A.string()}),Rd=pl.extend({ref:A.union([Ld,Id]),argument:A.object({name:A.string(),value:A.string()}),context:A.object({arguments:A.record(A.string(),A.string()).optional()}).optional()}),zd=hl.extend({method:A.literal(`completion/complete`),params:Rd});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 Bd=vl.extend({completion:A.looseObject({values:A.array(A.string()).max(100),total:A.optional(A.number().int()),hasMore:A.optional(A.boolean())})}),Vd=A.object({uri:A.string().startsWith(`file://`),name:A.string().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),Hd=hl.extend({method:A.literal(`roots/list`),params:pl.optional()}),Ud=vl.extend({roots:A.array(Vd)}),Wd=_l.extend({method:A.literal(`notifications/roots/list_changed`),params:gl.optional()});A.union([Hl,Rl,zd,rd,Fu,Mu,hu,_u,xu,Tu,Du,$u,Yu,eu,nu,ru,au]),A.union([Dl,Gl,Vl,Wd,$l]),A.union([Tl,hd,gd,Fd,Ud,tu,iu,Zl]),A.union([Hl,md,Md,Hd,eu,nu,ru,au]),A.union([Dl,Gl,ad,ku,Cu,ed,Gu,$l,Pd]),A.union([Tl,Bl,Bd,Wu,Nu,gu,vu,Su,Zu,Xu,tu,iu,Zl]);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(`
369
+ `);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 wl.parse(JSON.parse(e))}function serializeMessage(e){return JSON.stringify(e)+`
370
+ `}var StdioServerTransport=class{constructor(e=R.stdin,t=R.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=D.getChild(`mcp`);function mcpToolSchema(e){return j.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&&!ne(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 jn.object({});let n=t.every(isZ4Schema),r=t.every(e=>!isZ4Schema(e));if(n)return jn.object(e);if(r)return An.object(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?jn.safeParse(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await jn.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(`
371
+ `);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 Gd=Symbol(`Let zodToJsonSchema decide on which parser to use`),Kd={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`?{...Kd,name:e}:{...Kd,...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!==z.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 qd;const Jd={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:()=>(qd===void 0&&(qd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),qd),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,Jd.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,Jd.cuid,r.message,t);break;case`cuid2`:addPattern(n,Jd.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,Jd.base64url,r.message,t);break;case`jwt`:addPattern(n,Jd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&addPattern(n,Jd.ipv4Cidr,r.message,t),r.version!==`v4`&&addPattern(n,Jd.ipv6Cidr,r.message,t);break;case`emoji`:addPattern(n,Jd.emoji(),r.message,t);break;case`ulid`:addPattern(n,Jd.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,Jd.base64,r.message,t)}break;case`nanoid`:addPattern(n,Jd.nanoid,r.message,t)}return n}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const Yd=/* @__PURE__ */ new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let n=0;n<e.length;n++)Yd.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
364
372
  ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
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.
373
+ ]))`;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===z.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===z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=parseStringDef(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===z.ZodBranded&&e.keyType._def.type._def.typeName===z.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 Xd={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 Xd&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Xd[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:Xd[e.innerType._def.typeName],nullable:!0}:{type:[Xd[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 z.ZodString:return parseStringDef(e,n);case z.ZodNumber:return parseNumberDef(e,n);case z.ZodObject:return parseObjectDef(e,n);case z.ZodBigInt:return parseBigintDef(e,n);case z.ZodBoolean:return parseBooleanDef();case z.ZodDate:return parseDateDef(e,n);case z.ZodUndefined:return parseUndefinedDef(n);case z.ZodNull:return parseNullDef(n);case z.ZodArray:return parseArrayDef(e,n);case z.ZodUnion:case z.ZodDiscriminatedUnion:return parseUnionDef(e,n);case z.ZodIntersection:return parseIntersectionDef(e,n);case z.ZodTuple:return parseTupleDef(e,n);case z.ZodRecord:return parseRecordDef(e,n);case z.ZodLiteral:return parseLiteralDef(e,n);case z.ZodEnum:return parseEnumDef(e);case z.ZodNativeEnum:return parseNativeEnumDef(e);case z.ZodNullable:return parseNullableDef(e,n);case z.ZodOptional:return parseOptionalDef(e,n);case z.ZodMap:return parseMapDef(e,n);case z.ZodSet:return parseSetDef(e,n);case z.ZodLazy:return()=>e.getter()._def;case z.ZodPromise:return parsePromiseDef(e,n);case z.ZodNaN:case z.ZodNever:return parseNeverDef(n);case z.ZodEffects:return parseEffectsDef(e,n);case z.ZodAny:return parseAnyDef(n);case z.ZodUnknown:return parseUnknownDef(n);case z.ZodDefault:return parseDefaultDef(e,n);case z.ZodBranded:return parseBrandedDef(e,n);case z.ZodReadonly:return parseReadonlyDef(e,n);case z.ZodCatch:return parseCatchDef(e,n);case z.ZodPipeline:return parsePipelineDef(e,n);case z.ZodFunction:case z.ZodVoid:case z.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!==Gd)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)?jn.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(Dl,e=>{this._oncancel(e)}),this.setNotificationHandler(Gl,e=>{this._onprogress(e)}),this.setRequestHandler(Hl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(eu,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(nu,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,[sl]:{taskId:n}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ru,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(au,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?.[sl]?.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,Zl,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||{},[sl]: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},tu,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},iu,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},ou,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||{},[sl]: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||{},[sl]: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||{},[sl]: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=$l.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=$l.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 Zd=/* @__PURE__ */ n(ks(),1);function createDefaultAjvInstance(){let e=new Zd.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ns.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},hd,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},Fd,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(td.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(Rl,e=>this._oninitialize(e)),this.setNotificationHandler(Vl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(rd,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=td.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($u,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(Zl,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(Zu,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:ol.includes(t)?t:al,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`},Tl)}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},gd,t):this.request({method:`sampling/createMessage`,params:e},hd,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},Fd,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},Fd,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},Ud,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 Qd=Symbol.for(`mcp.completable`);function completable(e,t){return Object.defineProperty(e,Qd,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function isCompletable(e){return!!e&&typeof e==`object`&&Qd in e}function getCompleter(e){return e[Qd]?.complete}var $d;(function(e){e.Completable=`McpCompletable`})($d||={});const ef=1e6,tf=1e6,nf=1e4;var rf=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,ef,`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>nf)throw Error(`Template contains too many expressions (max ${nf})`);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,tf,`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,tf,`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,tf,`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,ef,`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 af=/^[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`),!af.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),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}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(Yu)),this.server.assertCanSetRequestHandler(getMethodValue($u)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Yu,()=>({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`}):of})(),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($u,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(zd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zd,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 sf;let r=getObjectShape(n.argsSchema)?.[e.params.argument.name];if(!isCompletable(r))return sf;let i=getCompleter(r);return i?createCompletionResult(await i(e.params.argument.value,e.params.context)):sf}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 sf;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)):sf}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(hu)),this.server.assertCanSetRequestHandler(getMethodValue(_u)),this.server.assertCanSetRequestHandler(getMethodValue(xu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(hu,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(_u,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(xu,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(Mu)),this.server.assertCanSetRequestHandler(getMethodValue(Fu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Mu,()=>({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(Fu,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 rf(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};const of={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 sf={completion:{values:[],hasMore:!1}};var cf=`1.61.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(An.string().describe(`Project id (optional, will use "default" if not specified)`),e=>t.projects().filter(t=>t.id.startsWith(e)).map(ge(`id`))),viewId:completable(An.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(ge(`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(`
374
+ `)}}]})),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(ge(`id`));let n=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(n)).map(ge(`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 lf=j.union([j.literal(`light`),j.literal(`dark`)]).describe(`Color theme preference for the host environment.`),uf=j.union([j.literal(`inline`),j.literal(`fullscreen`),j.literal(`pip`)]).describe(`Display mode for UI presentation.`),df=j.union([j.literal(`--color-background-primary`),j.literal(`--color-background-secondary`),j.literal(`--color-background-tertiary`),j.literal(`--color-background-inverse`),j.literal(`--color-background-ghost`),j.literal(`--color-background-info`),j.literal(`--color-background-danger`),j.literal(`--color-background-success`),j.literal(`--color-background-warning`),j.literal(`--color-background-disabled`),j.literal(`--color-text-primary`),j.literal(`--color-text-secondary`),j.literal(`--color-text-tertiary`),j.literal(`--color-text-inverse`),j.literal(`--color-text-ghost`),j.literal(`--color-text-info`),j.literal(`--color-text-danger`),j.literal(`--color-text-success`),j.literal(`--color-text-warning`),j.literal(`--color-text-disabled`),j.literal(`--color-border-primary`),j.literal(`--color-border-secondary`),j.literal(`--color-border-tertiary`),j.literal(`--color-border-inverse`),j.literal(`--color-border-ghost`),j.literal(`--color-border-info`),j.literal(`--color-border-danger`),j.literal(`--color-border-success`),j.literal(`--color-border-warning`),j.literal(`--color-border-disabled`),j.literal(`--color-ring-primary`),j.literal(`--color-ring-secondary`),j.literal(`--color-ring-inverse`),j.literal(`--color-ring-info`),j.literal(`--color-ring-danger`),j.literal(`--color-ring-success`),j.literal(`--color-ring-warning`),j.literal(`--font-sans`),j.literal(`--font-mono`),j.literal(`--font-weight-normal`),j.literal(`--font-weight-medium`),j.literal(`--font-weight-semibold`),j.literal(`--font-weight-bold`),j.literal(`--font-text-xs-size`),j.literal(`--font-text-sm-size`),j.literal(`--font-text-md-size`),j.literal(`--font-text-lg-size`),j.literal(`--font-heading-xs-size`),j.literal(`--font-heading-sm-size`),j.literal(`--font-heading-md-size`),j.literal(`--font-heading-lg-size`),j.literal(`--font-heading-xl-size`),j.literal(`--font-heading-2xl-size`),j.literal(`--font-heading-3xl-size`),j.literal(`--font-text-xs-line-height`),j.literal(`--font-text-sm-line-height`),j.literal(`--font-text-md-line-height`),j.literal(`--font-text-lg-line-height`),j.literal(`--font-heading-xs-line-height`),j.literal(`--font-heading-sm-line-height`),j.literal(`--font-heading-md-line-height`),j.literal(`--font-heading-lg-line-height`),j.literal(`--font-heading-xl-line-height`),j.literal(`--font-heading-2xl-line-height`),j.literal(`--font-heading-3xl-line-height`),j.literal(`--border-radius-xs`),j.literal(`--border-radius-sm`),j.literal(`--border-radius-md`),j.literal(`--border-radius-lg`),j.literal(`--border-radius-xl`),j.literal(`--border-radius-full`),j.literal(`--border-width-regular`),j.literal(`--shadow-hairline`),j.literal(`--shadow-sm`),j.literal(`--shadow-md`),j.literal(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),ff=j.record(df.describe(`Style variables for theming MCP apps.
367
375
 
368
376
  Individual style keys are optional - hosts may provide any subset of these values.
369
377
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
370
378
 
371
379
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
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.
380
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),j.union([j.string(),j.undefined()]).describe(`Style variables for theming MCP apps.
373
381
 
374
382
  Individual style keys are optional - hosts may provide any subset of these values.
375
383
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -381,18 +389,18 @@ Individual style keys are optional - hosts may provide any subset of these value
381
389
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
382
390
 
383
391
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
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).
392
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);j.object({method:j.literal(`ui/open-link`),params:j.object({url:j.string().describe(`URL to open in the host's browser`)})}),j.object({isError:j.boolean().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),j.object({isError:j.boolean().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),j.object({isError:j.boolean().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),j.object({method:j.literal(`ui/notifications/sandbox-proxy-ready`),params:j.object({})});var pf=j.object({connectDomains:j.array(j.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
385
393
 
386
394
  - Maps to CSP \`connect-src\` directive
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.
395
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:j.array(j.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:j.array(j.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:j.array(j.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'`)")}),mf=j.object({camera:j.object({}).optional().describe(`Request camera access.
388
396
 
389
- Maps to Permission Policy \`camera\` feature.`),microphone:k.object({}).optional().describe(`Request microphone access.
397
+ Maps to Permission Policy \`camera\` feature.`),microphone:j.object({}).optional().describe(`Request microphone access.
390
398
 
391
- Maps to Permission Policy \`microphone\` feature.`),geolocation:k.object({}).optional().describe(`Request geolocation access.
399
+ Maps to Permission Policy \`microphone\` feature.`),geolocation:j.object({}).optional().describe(`Request geolocation access.
392
400
 
393
- Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:k.object({}).optional().describe(`Request clipboard write access.
401
+ Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:j.object({}).optional().describe(`Request clipboard write access.
394
402
 
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.
403
+ Maps to Permission Policy \`clipboard-write\` feature.`)});j.object({method:j.literal(`ui/notifications/size-changed`),params:j.object({width:j.number().optional().describe(`New width in pixels.`),height:j.number().optional().describe(`New height in pixels.`)})}),j.object({method:j.literal(`ui/notifications/tool-input`),params:j.object({arguments:j.record(j.string(),j.unknown().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),j.object({method:j.literal(`ui/notifications/tool-input-partial`),params:j.object({arguments:j.record(j.string(),j.unknown().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),j.object({method:j.literal(`ui/notifications/tool-cancelled`),params:j.object({reason:j.string().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var hf=j.object({fonts:j.string().optional()}),gf=j.object({variables:ff.optional().describe(`CSS variables for theming the app.`),css:hf.optional().describe(`CSS blocks that apps can inject.`)});j.object({method:j.literal(`ui/resource-teardown`),params:j.object({})}),j.record(j.string(),j.unknown());var _f=j.object({text:j.object({}).optional().describe(`Host supports text content blocks.`),image:j.object({}).optional().describe(`Host supports image content blocks.`),audio:j.object({}).optional().describe(`Host supports audio content blocks.`),resource:j.object({}).optional().describe(`Host supports resource content blocks.`),resourceLink:j.object({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:j.object({}).optional().describe(`Host supports structured content.`)});j.object({method:j.literal(`ui/notifications/request-teardown`),params:j.object({}).optional()});var vf=j.object({experimental:j.record(j.string(),j.record(j.string(),j.any()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:j.object({}).optional().describe(`Host supports opening external URLs.`),downloadFile:j.object({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:j.object({listChanged:j.boolean().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:j.object({listChanged:j.boolean().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:j.object({}).optional().describe(`Host accepts log messages.`),sandbox:j.object({permissions:mf.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:pf.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:_f.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:_f.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:j.object({tools:j.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.")}),yf=j.object({experimental:j.record(j.string(),j.record(j.string(),j.any()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:j.object({listChanged:j.boolean().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:j.array(uf).optional().describe(`Display modes the app supports.`)});j.object({method:j.literal(`ui/notifications/initialized`),params:j.object({}).optional()}),j.object({csp:pf.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:mf.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:j.string().optional().describe(`Dedicated origin for view sandbox.
396
404
 
397
405
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
398
406
 
@@ -400,16 +408,16 @@ Useful when views need stable, dedicated origins for OAuth callbacks, CORS polic
400
408
  - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
401
409
  - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
402
410
 
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.
411
+ If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:j.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
404
412
 
405
413
  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.
406
414
 
407
415
  - \`true\`: request visible border + background
408
416
  - \`false\`: request no visible border + background
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"]
417
+ - omitted: host decides border`)}),j.object({method:j.literal(`ui/request-display-mode`),params:j.object({mode:uf.describe(`The display mode being requested.`)})}),j.object({mode:uf.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough();var bf=j.union([j.literal(`model`),j.literal(`app`)]).describe(`Tool visibility scope - who can access the tool.`);j.object({resourceUri:j.string().optional(),visibility:j.array(bf).optional().describe(`Who can access this tool. Default: ["model", "app"]
410
418
  - "model": Tool visible to and callable by the agent
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>
419
+ - "app": Tool callable by the app from this server only`),csp:j.never().optional(),permissions:j.never().optional()}),j.object({mimeTypes:j.array(j.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),j.object({method:j.literal(`ui/download-file`),params:j.object({contents:j.array(j.union([Bu,Vu])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),j.object({method:j.literal(`ui/message`),params:j.object({role:j.literal(`user`).describe(`Message role, currently only "user" is supported.`),content:j.array(Hu).describe(`Message content blocks (text, image, etc.).`)})}),j.object({method:j.literal(`ui/notifications/sandbox-resource-ready`),params:j.object({html:j.string().describe(`HTML content to load into the inner iframe.`),sandbox:j.string().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:pf.optional().describe(`CSP configuration from resource metadata.`),permissions:mf.optional().describe(`Sandbox permissions from resource metadata.`)})}),j.object({method:j.literal(`ui/notifications/tool-result`),params:Zu.describe(`Standard MCP tool execution result.`)});var xf=j.object({toolInfo:j.object({id:yl.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Ju.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:lf.optional().describe(`Current color theme preference.`),styles:gf.optional().describe(`Style configuration for theming the app.`),displayMode:uf.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:j.array(uf).optional().describe(`Display modes the host supports.`),containerDimensions:j.union([j.object({height:j.number().describe(`Fixed container height in pixels.`)}),j.object({maxHeight:j.union([j.number(),j.undefined()]).optional().describe(`Maximum container height in pixels.`)})]).and(j.union([j.object({width:j.number().describe(`Fixed container width in pixels.`)}),j.object({maxWidth:j.union([j.number(),j.undefined()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
420
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j.string().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j.string().optional().describe(`User's timezone in IANA format.`),userAgent:j.string().optional().describe(`Host application identifier.`),platform:j.union([j.literal(`web`),j.literal(`desktop`),j.literal(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:j.object({touch:j.boolean().optional().describe(`Whether the device supports touch input.`),hover:j.boolean().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:j.object({top:j.number().describe(`Top safe area inset in pixels.`),right:j.number().describe(`Right safe area inset in pixels.`),bottom:j.number().describe(`Bottom safe area inset in pixels.`),left:j.number().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();j.object({method:j.literal(`ui/notifications/host-context-changed`),params:xf.describe(`Partial context update containing only changed fields.`)}),j.object({method:j.literal(`ui/update-model-context`),params:j.object({content:j.array(Hu).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:j.record(j.string(),j.unknown().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),j.object({method:j.literal(`ui/initialize`),params:j.object({appInfo:jl.describe(`App identification (name and version).`),appCapabilities:yf.describe(`Features and capabilities this app provides.`),protocolVersion:j.string().describe(`Protocol version this app supports.`)})}),j.object({protocolVersion:j.string().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:jl.describe(`Host application identification and version.`),hostCapabilities:vf.describe(`Features and capabilities provided by the host.`),hostContext:xf.describe(`Rich context about the host environment.`)}).passthrough();var Sf=`ui/resourceUri`,Cf=`text/html;profile=mcp-app`;function K3(e,t,n,r){let i=n._meta,a=i.ui,s=i[Sf],c=i;return a?.resourceUri&&!s?c={...i,[Sf]: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:Cf,...r},i)}function readDistAsset(e){let t=[new URL(`./${e}`,import.meta.url),new URL(`../dist/${e}`,import.meta.url),new URL(`../../dist/${e}`,import.meta.url)];for(let e of t){let t=hn(e);if(It(t))return Lt(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 wf=A.object({name:A.string().describe(`Project identifier`),title:A.string().optional().describe(`Human-readable project title`),contactPerson:A.string().optional().describe(`Maintainer contact information`),metadata:A.record(A.string(),A.unknown()).optional().describe(`Custom project metadata as key-value pairs`),extends:A.union([A.string(),A.array(A.string())]).optional().describe(`Style inheritance paths`),exclude:A.array(A.string()).optional().describe(`File exclusion patterns`),include:A.object({paths:A.array(A.string()).describe(`Include paths`),maxDepth:A.number().describe(`Maximum directory depth`),fileThreshold:A.number().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:A.object({outDir:A.string().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:A.object({hasTheme:A.boolean().describe(`Whether theme customization is defined`),hasDefaults:A.boolean().describe(`Whether default style values are defined`),hasCustomCss:A.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 Tf=A.object({id:A.string().describe(`Element id (FQN)`),name:A.string().describe(`Element name`),kind:A.string().describe(`Element kind`),title:A.string(),tags:A.array(A.string()),metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])),includedInViews:A.array(A.object({id:A.string().describe(`View id`),title:A.string().describe(`View title`),type:A.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);I(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 Ef=A.object({path:A.string().describe(`Path to the file`),range:A.object({start:A.object({line:A.number(),character:A.number()}),end:A.object({line:A.number(),character:A.number()})}).describe(`Range in the file`)}).nullable(),Df=A.array(A.object({title:A.string().nullable().describe(`Optional link title`),url:A.string().describe(`Link URL`),relative:A.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=A.string().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),Of=A.array(A.object({id:A.string().describe(`View id`),title:A.string().describe(`View title`),type:A.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:Ge.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(Lt(Ge.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 kf=`ui://likec4/render-view.html`,Af=A.object({size:A.enum([`compact`,`standard`,`large`]).default(`standard`).describe(`Initial canvas size hint`),fitView:A.boolean().default(!0).describe(`Fit the diagram into the canvas initially`),initialZoom:A.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:A.string().describe(`View id (name)`),project:Q,fullModel:A.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`),render:Af}),outputSchema:mcpToolSchema({id:A.string(),title:A.string(),project:A.string(),view:A.record(A.string(),A.unknown()).describe(`Layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:A.record(A.string(),A.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:Af}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:kf}}},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>
413
421
  <html>
414
422
  <head>
415
423
  <meta charset="utf-8" />
@@ -423,10 +431,53 @@ container holding the app. Specify either width or maxWidth, and either height o
423
431
  <div id="root"></div>
424
432
  <script>${e}<\/script>
425
433
  </body>
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+`
427
-
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.
434
+ </html>`}function renderViewResource(e){return N3(e,`Render View UI`,kf,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:kf,mimeType:Cf,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(A.string().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(ge(`id`))),viewId:completable(A.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(ge(`id`))})}),outputSchema:mcpToolSchema({reasoning:A.string().describe(`Reasoning behind the layout changes`),snapshotUri:A.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 Se(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+`
435
+
436
+ `+n}}]}},A.object({content:A.object({type:A.literal(`text`),text:A.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 jf=Tf.extend({description:A.string().nullable().describe(`Element description`),technology:A.string().nullable().describe(`Element technology`),shape:A.string().describe(`Rendered shape`),color:A.string().describe(`Rendered color`),children:A.array(A.string()).describe(`Direct child element ids`),incomingCount:A.number().describe(`Number of incoming relationships`),outgoingCount:A.number().describe(`Number of outgoing relationships`),links:Df,sourceLocation:Ef}),Mf=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:A.array(A.string()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:Q},outputSchema:{elements:A.array(jf),notFound:A.array(A.string()).describe(`Element ids that were not found`)}})(async(e,t)=>{I(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}}),Nf=A.object({id:A.string(),kind:A.string(),title:A.string(),description:A.string().nullable(),technology:A.string().nullable(),shape:A.string(),color:A.string()}),Pf=A.object({element1:Nf,element2:Nf,propertyDiffs:A.array(A.object({property:A.string().describe(`Property name`),element1Value:A.string().nullable().describe(`Value in element1`),element2Value:A.string().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:A.object({onlyInElement1:A.array(A.string()).describe(`Tags present only in element1`),onlyInElement2:A.array(A.string()).describe(`Tags present only in element2`),common:A.array(A.string()).describe(`Tags present in both elements`)}),metadata:A.object({onlyInElement1:A.record(A.string(),A.union([A.string(),A.array(A.string())])).describe(`Metadata keys only in element1`),onlyInElement2:A.record(A.string(),A.union([A.string(),A.array(A.string())])).describe(`Metadata keys only in element2`),different:A.array(A.object({key:A.string(),element1Value:A.union([A.string(),A.array(A.string())]),element2Value:A.union([A.string(),A.array(A.string())])})).describe(`Metadata keys present in both but with different values`),common:A.record(A.string(),A.union([A.string(),A.array(A.string())])).describe(`Metadata keys with identical values in both`)}),relationships:A.object({incomingOnlyElement1:A.number().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:A.number().describe(`Count of unique source elements sending to element2 only`),incomingShared:A.number().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:A.number().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:A.number().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:A.number().describe(`Count of unique target elements receiving from both`)})}),Ff=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:A.string().describe(`First element id (FQN)`),element2Id:A.string().describe(`Second element id (FQN)`),project:Q},outputSchema:Pf.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);I(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);I(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 C=new Set([...i.incoming()].map(e=>e.source.id)),w=new Set([...a.incoming()].map(e=>e.source.id)),T=new Set([...i.outgoing()].map(e=>e.target.id)),E=new Set([...a.outgoing()].map(e=>e.target.id)),D=0,ee=0,te=0;for(let e of C)w.has(e)?D++:ee++;for(let e of w)C.has(e)||te++;let O=0,ne=0,re=0;for(let e of T)E.has(e)?O++:ne++;for(let e of E)T.has(e)||re++;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:ee,incomingOnlyElement2:te,incomingShared:D,outgoingOnlyElement1:ne,outgoingOnlyElement2:re,outgoingShared:O}}}),Lf=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:A.string().describe(`Source element FQN`),targetId:A.string().describe(`Target element FQN`),maxDepth:A.number().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:A.boolean().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:Q},outputSchema:{paths:A.array(A.object({length:A.number().describe(`Number of hops in the path`),steps:A.array(A.object({source:A.string().describe(`Source element FQN`),target:A.string().describe(`Target element FQN`),relationship:A.object({kind:A.string().nullable().describe(`Relationship kind`),title:A.string().nullable().describe(`Relationship title`),description:A.string().nullable().describe(`Relationship description`),technology:A.string().nullable().describe(`Relationship technology`),tags:A.array(A.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);I(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);I(a,`Target element "${t.targetId}" not found in project "${n}"`),I(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}}),Rf=A.object({id:A.string(),title:A.string(),kind:A.string()}),zf=A.object({type:A.enum([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:Rf,target:Rf,kind:A.string().nullable().describe(`Relationship kind`),title:A.string().nullable().describe(`Relationship title`),description:A.string().nullable().describe(`Relationship description`),technology:A.string().nullable().describe(`Relationship technology`),tags:A.array(A.string()).describe(`Relationship tags`),includedInViews:Of.describe(`Views that include this relationship`),sourceLocation:Ef}),Bf=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:A.string().describe(`Element ID (FQN)`),element2:A.string().describe(`Element ID (FQN)`),project:Q},outputSchema:{found:A.array(zf)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(Mt(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);jt(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);jt(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=Yt.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}}),Vf=A.object({added:A.number(),removed:A.number(),modified:A.number()}),Hf=likec4Tool({name:`list-diffs`,description:`
437
+ List model diffs (named change sets, "diff" blocks) and the views each diff changes.
438
+
439
+ Request:
440
+ - project: string (optional) — project id. Defaults to "default" if omitted.
441
+
442
+ Response (JSON object):
443
+ - diffs: Array of
444
+ - id: string — diff name
445
+ - title: string|null
446
+ - description: string|null
447
+ - added: { elements: number, relations: number }
448
+ - removed: { elements: number, relations: number }
449
+ - modified: { elements: number }
450
+ - views: Array<{ id, title, nodes: { added, removed, modified }, edges: { added, removed, modified } }> — views changed by the diff
451
+
452
+ Notes:
453
+ - Read-only, idempotent, no side effects.
454
+ - A diff describes a future state of the model; the model itself stays unchanged until the diff is applied.
455
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List model diffs`},inputSchema:{project:Q},outputSchema:{diffs:A.array(A.object({id:A.string(),title:A.string().nullable(),description:A.string().nullable(),added:A.object({elements:A.number(),relations:A.number()}),removed:A.object({elements:A.number(),relations:A.number()}),modified:A.object({elements:A.number()}),views:A.array(A.object({id:A.string(),title:A.string().nullable(),nodes:Vf,edges:Vf}))}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.modelDiffs.list(n),i=r.some(e=>e.description&&`md`in e.description)?await e.computedModel(n):null;return{diffs:r.map(e=>({...e,description:e.description?`md`in e.description?Nt(e.description.md,i?.resolveMarkdownRef):e.description.txt:null}))}}),Uf=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:A.array(A.object({id:A.string(),title:A.string(),folder:A.string(),sources:A.array(A.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)}))})),Wf=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=Wf.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(bt).join(`/`)}function toVirtualSourcePath(e,t,n){let r=toPortablePath(P(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(`
456
+ `)}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:A.string().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:Q,fullModel:A.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`)}),outputSchema:mcpToolSchema({id:A.string(),title:A.string(),project:A.string(),view:A.record(A.string(),A.unknown()),model:A.record(A.string(),A.unknown())}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:kf}}},async e=>{try{var t=_usingCtx();let n=useLanguageServices(),r=n.projectsManager.ensureProjectId(e.project),i=extractViewId(e.dsl);if(!i)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let a=n.project(r);if((await n.computedModel(r))?.findView(i))return toolError(`View "${i}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let s={};for(let[e,t]of a.documents.entries()){let r=toVirtualSourcePath(a.folder.fsPath,t.fsPath,`seed-${e}.c4`);s[r]=n.documentText(t.toString())??``}let c=`${En()}.c4`;s[c]=wrapAsViewsBlock(e.dsl);let l=t.a(await 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 Gf=A.enum([`exact`,`contains`,`exists`]),Kf=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:A.string().describe(`Metadata key to filter by`),value:A.string().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:Gf.optional().default(`exact`).describe(`Matching mode`),project:Q},outputSchema:{results:A.array(Tf.extend({matchedValue:A.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}}),qf=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:A.string().min(1).describe(`Tag pattern to match`),matchMode:A.enum([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:Q},outputSchema:{results:A.array(Tf.extend({matchedTags:A.array(A.string()).describe(`Tags that matched the pattern`)})),truncated:A.boolean().describe(`True if results were truncated`),matchedTagValues:A.array(A.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(!Wt(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))}}),Jf=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:A.array(A.string()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:A.array(A.string()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:A.array(A.string()).optional().describe(`Element must have NONE of these tags (NOT)`),project:Q},outputSchema:{results:A.array(Tf),truncated:A.boolean().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{I(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}Wt(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),Yf=A.enum([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),Xf=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:A.string().describe(`Element id (FQN) to query`),queryType:Yf.describe(`Type of graph query`),includeIndirect:A.boolean().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:Q},outputSchema:{results:A.array(Tf),truncated:A.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);I(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}}),Zf=A.object({elementId:A.string().describe(`ID of the incoming element`),relationshipLabel:A.string().optional().describe(`Label on the relationship`),technology:A.string().optional().describe(`Technology specified on the relationship`)}),Qf=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:A.string().describe(`Target element id (FQN) to query incomers for`),includeIndirect:A.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:A.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:A.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Q},outputSchema:{target:A.string().describe(`Target element id`),totalNodes:A.number().describe(`Total number of nodes in the graph`),maxDepth:A.number().describe(`Maximum depth reached`),truncated:A.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:A.record(A.string(),Tf.extend({incomers:A.array(Zf).describe(`Incoming relationships with details`),depth:A.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);I(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}}),$f=A.object({elementId:A.string().describe(`ID of the outgoing element`),relationshipLabel:A.string().optional().describe(`Label on the relationship`),technology:A.string().optional().describe(`Technology specified on the relationship`)}),ep=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:A.string().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:A.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:A.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:A.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:Q},outputSchema:{target:A.string().describe(`Target element id`),totalNodes:A.number().describe(`Total number of nodes in the graph`),maxDepth:A.number().describe(`Maximum depth reached`),truncated:A.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:A.record(A.string(),Tf.extend({outgoers:A.array($f).describe(`Outgoing relationships with details`),depth:A.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);I(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}}),tp=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:A.string().describe(`Deployment id (FQN)`),project:Q},outputSchema:{type:A.enum([`deployment-node`,`deployed-instance`]),id:A.string().describe(`Deployment id (FQN)`),kind:A.string().describe(`Deployment node kind, or element kind for deployed instances`),name:A.string(),title:A.string(),description:A.string().nullable(),technology:A.string().nullable(),tags:A.array(A.string()),project:A.string(),metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])),links:Df.describe(`External links associated with this deployment entity`),shape:A.string(),color:A.string(),children:A.array(A.string()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:Of.describe(`Views that include this deployment node`),instanceof:A.object({id:A.string().describe(`Element ID (FQN)`),title:A.string(),kind:A.string()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:Ef}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);I(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})}}),np=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:A.string().describe(`Element id (FQN)`),project:Q},outputSchema:{id:A.string().describe(`Element id (FQN)`),kind:A.string().describe(`Element kind`),name:A.string().describe(`Element name`),title:A.string(),description:A.string().nullable(),technology:A.string().nullable(),tags:A.array(A.string()),project:A.string(),metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])),links:Df,shape:A.string(),color:A.string(),children:A.array(A.string()).describe(`Children of this element (Array of FQNs)`),defaultView:A.string().nullable().describe(`Name of the default view of this element`),includedInViews:Of.describe(`Views that include this element`),relationships:A.object({incoming:A.array(A.object({source:A.object({id:A.string(),title:A.string(),kind:A.string()}).describe(`Source element of this relationship`),kind:A.string().nullable().describe(`Relationship kind`),target:A.string().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:A.string().nullable().describe(`Relationship title`),description:A.string().nullable().describe(`Relationship description`),technology:A.string().nullable().describe(`Relationship technology`),tags:A.array(A.string()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:A.array(A.object({source:A.string().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:A.object({id:A.string(),title:A.string(),kind:A.string()}).describe(`Target element of this relationship`),kind:A.string().nullable().describe(`Relationship kind`),title:A.string().nullable().describe(`Relationship title`),description:A.string().nullable().describe(`Relationship description`),technology:A.string().nullable().describe(`Relationship technology`),tags:A.array(A.string()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:A.array(A.string()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:Ef}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.id);I(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})}}),rp=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:A.string(),folder:A.string(),sources:A.array(A.string()),config:wf.describe(`Project configuration`),specification:A.object({elementKinds:A.array(A.string()),relationshipKinds:A.array(A.string()),deploymentKinds:A.array(A.string()),tags:A.array(A.string()),metadataKeys:A.array(A.string())}),elements:A.array(A.object({id:A.string(),kind:A.string(),title:A.string(),tags:A.array(A.string())})).describe(`List of elements in the project`),deployments:A.array(A.discriminatedUnion(`type`,[A.object({type:A.literal(`deployment-node`),id:A.string().describe(`Node ID`),kind:A.string().describe(`Deployment node kind`),title:A.string().describe(`Node title`),tags:A.array(A.string())}),A.object({type:A.literal(`deployed-instance`),id:A.string().describe(`Node ID`),title:A.string().describe(`Node title`),tags:A.array(A.string()),referencedElementId:A.string().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:A.array(A.object({id:A.string(),title:A.string(),type:A.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:te(i.specification.elements),relationshipKinds:te(i.specification.relationships),deploymentKinds:te(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,ip=A.discriminatedUnion(`type`,[A.object({type:A.literal(`element`),id:A.string().describe(`Node ID`),elementId:A.string().describe(`Element ID (FQN)`),kind:A.string().describe(`Element kind`),title:A.string().describe(`Node title`),description:A.string().nullable(),technology:A.string().nullable(),children:A.array(A.string()).describe(`Children nodes, array of node IDs`),shape:A.string().describe(`Rendered shape`),color:A.string().describe(`Rendered color`),tags:A.array(A.string())}),A.object({type:A.literal(`deployment-node`),id:A.string().describe(`Node ID`),deploymentId:A.string().describe(`Deployment entity ID (FQN)`),kind:A.string().describe(`Deployment kind`),title:A.string().describe(`Node title`),description:A.string().nullable(),technology:A.string().nullable(),children:A.array(A.string()).describe(`Children nodes, array of node IDs`),shape:A.string().describe(`Rendered shape`),color:A.string().describe(`Rendered color`),tags:A.array(A.string())}),A.object({type:A.literal(`deployed-instance`),id:A.string().describe(`Node ID`),deploymentId:A.string().describe(`Deployment entity ID (FQN)`),title:A.string().describe(`Node title`),description:A.string().nullable(),technology:A.string().nullable(),referencedElement:A.object({id:A.string().describe(`Element ID (FQN)`),kind:A.string().describe(`Element kind`),title:A.string().describe(`Element title`)}),shape:A.string().describe(`Rendered shape`),color:A.string().describe(`Rendered color`),tags:A.array(A.string())})]),ap=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:A.string().describe(`View id (name)`),project:Q},outputSchema:{id:A.string(),type:A.enum([`element`,`deployment`,`dynamic`]).describe(`View type`),title:A.string(),description:A.string().nullable(),tags:A.array(A.string()),project:A.string(),nodes:A.array(ip),edges:A.array(A.object({source:A.string().describe(`Source node`),target:A.string().describe(`Target node`),label:A.string().nullable(),description:A.string().nullable(),technology:A.string().nullable(),tags:A.array(A.string())})).describe(`Edge represents relationship between nodes`),sourceLocation:Ef}})(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})}}),op=likec4Tool({name:`removal-impact`,description:`
457
+ Report what removing an element from the model takes with it (safe delete dry run, blast radius).
458
+
459
+ Request:
460
+ - id: string — element id (FQN)
461
+ - project: string (optional) — project id. Defaults to "default" if omitted.
462
+
463
+ Response (JSON object):
464
+ - elements: string[] — removed elements: the element and its descendants (FQNs)
465
+ - relationships: number — relationships with a removed element as source or target
466
+ - deployedInstances: string[] — deployed instances of removed elements
467
+ - emptyDeploymentNodes: string[] — deployment nodes left without deployed instances
468
+ - affectedViews: string[] — views that show a removed element or relationship
469
+ - scopedViews: string[] — views scoped to a removed element
470
+ - orphans: string[] — elements left without relationships (suggested for removal, not removed automatically)
471
+ - references: Array<{ kind, resolution, text, path, line }> — source references to removed elements
472
+ - kind: where the reference is (relation, extend-element, deployed-instance, view-predicate, view-scope, dynamic-step, diff, ...)
473
+ - resolution: "removed" (removed together with the element), "optional" (removed only on request), "manual" (fix manually)
474
+ - text: source text of the node with the reference
475
+ - path, line: location (line is 1-based)
476
+
477
+ Notes:
478
+ - Read-only, idempotent, no side effects. Nothing is removed.
479
+ - Use before refactoring to understand the impact of removing an element.
480
+ `,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Removal impact`},inputSchema:{id:A.string().describe(`Element id (FQN)`),project:Q},outputSchema:{elements:A.array(A.string()),relationships:A.number(),deployedInstances:A.array(A.string()),emptyDeploymentNodes:A.array(A.string()),affectedViews:A.array(A.string()),scopedViews:A.array(A.string()),orphans:A.array(A.string()),references:A.array(A.object({kind:A.string(),resolution:A.enum([`removed`,`optional`,`manual`]),text:A.string(),path:A.string(),line:A.number()}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.removalImpact.analyze([t.id],n);I(r,`Element "${t.id}" not found in project "${n}"`);let{impact:i}=r;return{elements:[...i.elements],relationships:i.relations.length,deployedInstances:[...i.deployedInstances],emptyDeploymentNodes:[...i.emptyDeploymentNodes],affectedViews:[...i.affectedViews],scopedViews:[...i.scopedViews],orphans:[...i.orphans],references:r.references.map(e=>({kind:e.kind,resolution:e.resolution,text:e.text,path:Ge.parse(e.location.uri).fsPath,line:e.location.range.start.line+1}))}});function isArray(e){return Array.isArray?Array.isArray(e):getTag(e)===`[object Array]`}function baseToString(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function toString(e){return e==null?``:baseToString(e)}function isString$1(e){return typeof e==`string`}t(isString$1,`isString`);function isNumber(e){return typeof e==`number`}function isBoolean(e){return e===!0||e===!1||isObjectLike(e)&&getTag(e)==`[object Boolean]`}function isObject(e){return typeof e==`object`}function isObjectLike(e){return isObject(e)&&e!==null}function isDefined(e){return e!=null}function isBlank(e){return!e.trim().length}function getTag(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}const sp=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY=e=>`Invalid value for key ${e}`,PATTERN_LENGTH_TOO_LARGE=e=>`Pattern length exceeds max of ${e}.`,MISSING_KEY_PROPERTY=e=>`Missing ${e} property in key`,INVALID_KEY_WEIGHT_VALUE=e=>`Property 'weight' in key '${e}' must be a positive integer`,cp=Object.prototype.hasOwnProperty;var KeyStore=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=createKey(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function createKey(e){let t=null,n=null,r=null,i=1,a=null;if(isString$1(e)||isArray(e))r=e,t=createKeyPath(e),n=createKeyId(e);else{if(!cp.call(e,`name`))throw Error(MISSING_KEY_PROPERTY(`name`));let s=e.name;if(r=s,cp.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(INVALID_KEY_WEIGHT_VALUE(createKeyId(s)));t=createKeyPath(s),n=createKeyId(s),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function createKeyPath(e){return isArray(e)?e:e.split(`.`)}function createKeyId(e){return isArray(e)?e.join(`.`):e}function get(e,t){let n=[],r=!1,deepGet=(e,t,i,a)=>{if(isDefined(e)){if(!t[i])n.push(a===void 0?e:{v:e,i:a});else{let s=e[t[i]];if(!isDefined(s))return;if(i===t.length-1&&(isString$1(s)||isNumber(s)||isBoolean(s)||typeof s==`bigint`))n.push(a===void 0?toString(s):{v:toString(s),i:a});else if(isArray(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)deepGet(s[e],t,i+1,e)}else t.length&&deepGet(s,t,i+1,a)}}};return deepGet(e,isString$1(t)?t.split(`.`):t,0),r?n:n[0]}const lp={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},up={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},dp={location:0,threshold:.6,distance:100},fp={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:get,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},$=Object.freeze({...up,...lp,...dp,...fp});function isWordSeparator(e){return e>=9&&e<=13||e===32||e===160}function norm(e=1,t=3){let n=/* @__PURE__ */ new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)isWordSeparator(t.charCodeAt(e))?a=!1:a||=(i++,!0);if(i===0&&(i=1),n.has(i))return n.get(i);let s=Math.round(r/i**(.5*e))/r;return n.set(i,s),s},clear(){n.clear()}}}var FuseIndex=class{constructor({getFn:e=$.getFn,fieldNormWeight:t=$.fieldNormWeight}={}){this.norm=norm(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(isString$1(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(sp);if(isString$1(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(sp);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=/* @__PURE__ */ new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!isDefined(e)||isBlank(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(isDefined(i)){if(isArray(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(isDefined(n)){if(isString$1(n)){if(!isBlank(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(isDefined(n.v)){let t=isString$1(n.v)?n.v:toString(n.v);if(!isBlank(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(isString$1(i)&&!isBlank(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function createIndex(e,t,{getFn:n=$.getFn,fieldNormWeight:r=$.fieldNormWeight}={}){let i=new FuseIndex({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(createKey)),i.setSources(t),i.create(),i}function parseIndex(e,{getFn:t=$.getFn,fieldNormWeight:n=$.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new FuseIndex({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function convertMaskToIndices(e=[],t=$.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let s=e.length;a<s;a+=1){let s=e[a];s&&r===-1?r=a:!s&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function search(e,t,n,{location:r=$.location,distance:i=$.distance,threshold:a=$.threshold,findAllMatches:s=$.findAllMatches,minMatchCharLength:c=$.minMatchCharLength,includeMatches:l=$.includeMatches,ignoreLocation:u=$.ignoreLocation}={}){if(t.length>32)throw Error(PATTERN_LENGTH_TOO_LARGE(32));let f=t.length,p=e.length,m=Math.max(0,Math.min(r,p)),h=a,g=m,calcScore=(e,t)=>{let n=e/f;if(u)return n;let r=Math.abs(m-t);return i?n+r/i:r?1:n},v=c>1||l,y=v?Array(p):[],b;for(;(b=e.indexOf(t,g))>-1;){let e=calcScore(0,b);if(h=Math.min(e,h),g=b+f,v){let e=0;for(;e<f;)y[b+e]=1,e+=1}}g=-1;let x=[],S=1,C=0,w=f+p,T=1<<f-1;for(let t=0;t<f;t+=1){let r=0,i=w;for(;r<i;)calcScore(t,m+i)<=h?r=i:w=i,i=Math.floor((w-r)/2+r);w=i;let a=Math.max(1,m-i+1),c=s?p:Math.min(m+i,p)+f,l=Array(c+2);l[c+1]=(1<<t)-1;for(let r=c;r>=a;--r){let i=r-1,s=n[e[i]];if(l[r]=(l[r+1]<<1|1)&s,t&&(l[r]|=(x[r+1]|x[r])<<1|1|x[r+1]),l[r]&T&&(S=calcScore(t,i),S<=h)){if(h=S,g=i,C=t,g<=m)break;a=Math.max(1,2*m-g)}}if(calcScore(t+1,m)>h)break;x=l}if(v&&g>=0){let t=Math.min(p-1,g+f-1+C);for(let r=g;r<=t;r+=1)n[e[r]]&&(y[r]=1)}let E={isMatch:g>=0,score:Math.max(.001,S)};if(v){let e=convertMaskToIndices(y,c);e.length?l&&(E.indices=e):E.isMatch=!1}return E}function createPatternAlphabet(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function mergeIndices(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}const pp={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},mp=RegExp(`[`+Object.keys(pp).join(``)+`]`,`g`),hp=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFD`).replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,``).replace(mp,e=>pp[e]):e=>e;var BitapSearch=class{constructor(e,{location:t=$.location,threshold:n=$.threshold,distance:r=$.distance,includeMatches:i=$.includeMatches,findAllMatches:a=$.findAllMatches,minMatchCharLength:s=$.minMatchCharLength,isCaseSensitive:c=$.isCaseSensitive,ignoreDiacritics:l=$.ignoreDiacritics,ignoreLocation:u=$.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:s,isCaseSensitive:c,ignoreDiacritics:l,ignoreLocation:u},e=c?e:e.toLowerCase(),e=l?hp(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let addChunk=(e,t)=>{this.chunks.push({pattern:e,alphabet:createPatternAlphabet(e),startIndex:t})},f=this.pattern.length;if(f>32){let e=0,t=f%32,n=f-t;for(;e<n;)addChunk(this.pattern.substr(e,32),e),e+=32;if(t){let e=f-32;addChunk(this.pattern.substr(e),e)}}else addChunk(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?hp(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:s,findAllMatches:c,minMatchCharLength:l,ignoreLocation:u}=this.options,f=[],p=0,m=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:h})=>{let{isMatch:g,score:v,indices:y}=search(e,t,n,{location:i+h,distance:a,threshold:s,findAllMatches:c,minMatchCharLength:l,includeMatches:r,ignoreLocation:u});g&&(m=!0),p+=v,g&&y&&f.push(...y)});let h={isMatch:m,score:m?p/this.chunks.length:1};return m&&r&&(h.indices=mergeIndices(f)),h}};const gp=/* @__PURE__ */ new Set([`fuzzy`,`include`]);function isInverse(e){return e.startsWith(`inverse`)}const _p=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let s=!!i.length;return{isMatch:s,score:+!s,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new BitapSearch(e,{location:t.location??$.location,threshold:t.threshold??$.threshold,distance:t.distance??$.distance,includeMatches:t.includeMatches??$.includeMatches,findAllMatches:t.findAllMatches??$.findAllMatches,minMatchCharLength:t.minMatchCharLength??$.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??$.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??$.ignoreDiacritics,ignoreLocation:t.ignoreLocation??$.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],vp=_p.length;function tokenize(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function getMatch(e,t){let n=e.match(t);return n?n[1]:null}function parseQuery(e,t={}){return e.replace(/\\\|/g,`\0`).split(`|`).map(e=>{let n=tokenize(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,s=-1;for(;!a&&++s<vp;){let e=_p[s],n=getMatch(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(s=-1;++s<vp;){let e=_p[s],n=getMatch(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var ExtendedSearch=class{constructor(e,{isCaseSensitive:t=$.isCaseSensitive,ignoreDiacritics:n=$.ignoreDiacritics,includeMatches:r=$.includeMatches,minMatchCharLength:i=$.minMatchCharLength,ignoreLocation:a=$.ignoreLocation,findAllMatches:s=$.findAllMatches,location:c=$.location,threshold:l=$.threshold,distance:u=$.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:s,ignoreLocation:a,location:c,threshold:l,distance:u},e=t?e:e.toLowerCase(),e=n?hp(e):e,this.pattern=e,this.query=parseQuery(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?hp(e):e;let a=0,s=[],c=0,l=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];s.length=0,a=0,l=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:u,indices:f,score:p}=r.search(e);if(u)a+=1,c+=p,isInverse(r.type)&&(l=!0),n&&(gp.has(r.type)?s.push(...f):s.push(f));else{c=0,a=0,s.length=0,l=!1;break}}if(a){let e={isMatch:!0,score:c/a};return l&&(e.hasInverse=!0),n&&(e.indices=mergeIndices(s)),e}}return{isMatch:!1,score:1}}};const yp=[];function register(...e){yp.push(...e)}function createSearcher(e,t){for(let n=0,r=yp.length;n<r;n+=1){let r=yp[n];if(r.condition(e,t))return new r(e,t)}return new BitapSearch(e,t)}const bp={AND:`$and`,OR:`$or`},xp={PATH:`$path`,PATTERN:`$val`},isExpression=e=>!!(e[bp.AND]||e[bp.OR]),isPath=e=>!!e[xp.PATH],isLeaf=e=>!isArray(e)&&isObject(e)&&!isExpression(e),convertToExplicit=e=>({[bp.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function parse(e,t,{auto:n=!0}={}){let next=e=>{if(isString$1(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=createSearcher(e,t)),r}let r=Object.keys(e),i=isPath(e);if(!i&&r.length>1&&!isExpression(e))return next(convertToExplicit(e));if(isLeaf(e)){let a=i?e[xp.PATH]:r[0],s=i?e[xp.PATTERN]:e[a];if(!isString$1(s))throw Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(a));let c={keyId:createKeyId(a),pattern:s};return n&&(c.searcher=createSearcher(s,t)),c}let a={children:[],operator:r[0]};return r.forEach(t=>{let n=e[t];isArray(n)&&n.forEach(e=>{a.children.push(next(e))})}),a};return isExpression(e)||(e=convertToExplicit(e)),next(e)}function computeScoreSingle(e,{ignoreFieldNorm:t=$.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function computeScore(e,{ignoreFieldNorm:t=$.ignoreFieldNorm}){e.forEach(e=>{e.score=computeScoreSingle(e.matches,{ignoreFieldNorm:t})})}var MaxHeap=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function formatMatches(e){let t=[];return e.matches.forEach(e=>{if(!isDefined(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function format(e,t,{includeMatches:n=$.includeMatches,includeScore:r=$.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=formatMatches(e)),r&&(a.score=e.score),a})}const Sp=/[\p{L}\p{M}\p{N}_]+/gu,Cp=/* @__PURE__ */ new WeakSet;function warnNonGlobal(e){Cp.has(e)||(Cp.add(e),console.warn(`[Fuse] tokenize regex ${e} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function resolveTokenize(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||warnNonGlobal(e),t=>t.match(e)||[]):e=>e.match(Sp)||[]}function createAnalyzer({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=resolveTokenize(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=hp(n)),r(n)}}}var TokenSearch=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=createAnalyzer({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new BitapSearch(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,s=this.combineAll&&!this.useMask?/* @__PURE__ */ new Set:null;for(let c=0;c<this.termSearchers.length;c++){let l=this.termSearchers[c].searchIn(e),u=this.idfWeights[c];r+=u,l.isMatch&&(i++,n+=u*(1-l.score),l.indices&&t.push(...l.indices),this.combineAll&&(this.useMask?a|=1<<c:s.add(c)))}if(i===0)return{isMatch:!1,score:1};let c=r>0?1-n/r:0,l={isMatch:!0,score:Math.max(.001,c)};return this.options.includeMatches&&t.length&&(l.indices=mergeIndices(t)),this.combineAll&&(this.useMask?l.matchedMask=a:l.matchedTerms=s,l.termCount=this.numTerms),l}};function addField(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),s=e.docTermFieldHits.get(n);s||(s=/* @__PURE__ */ new Map,e.docTermFieldHits.set(n,s));for(let t of a)s.set(t,(s.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function ingestRecord(e,t,n,r){let{i,v:a,$:s}=t;if(a!==void 0)addField(e,a,i,r);else if(s)for(let t=0;t<n;t++){let n=s[t];if(n){if(Array.isArray(n))for(let t of n)addField(e,t.v,i,r);else addField(e,n.v,i,r)}}}function buildInvertedIndex(e,t,n){let r={fieldCount:0,df:/* @__PURE__ */ new Map,docFieldCount:/* @__PURE__ */ new Map,docTermFieldHits:/* @__PURE__ */ new Map};for(let i of e)ingestRecord(r,i,t,n);return r}function addToInvertedIndex(e,t,n,r){ingestRecord(e,t,n,r)}function removeFromInvertedIndex(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function removeAndShiftInvertedIndex(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)removeFromInvertedIndex(e,t);let shift=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},r=n[0],i=/* @__PURE__ */ new Map;for(let[t,n]of e.docFieldCount)i.set(t>r?shift(t):t,n);e.docFieldCount=i;let a=/* @__PURE__ */ new Map;for(let[t,n]of e.docTermFieldHits)a.set(t>r?shift(t):t,n);e.docTermFieldHits=a}var Fuse=class{constructor(e,t,n){this.options={...$,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new KeyStore(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=createSearcher(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof FuseIndex))throw Error(`Incorrect 'index' type`);if(this._myIndex=t||createIndex(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=createAnalyzer({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=buildInvertedIndex(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!isDefined(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=createAnalyzer({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});addToInvertedIndex(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&removeAndShiftInvertedIndex(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(sp);this._invertedIndex&&removeAndShiftInvertedIndex(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:s,ignoreFieldNorm:c}=this.options;if(isString$1(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return isNumber(n)&&n>-1&&(e=e.slice(0,n)),e}let l=a&&isNumber(n)&&n>0&&isString$1(e),u=s,stable=(e,t)=>u(e,t)||e.idx-t.idx,f;if(l){let t=new MaxHeap(n,stable);isString$1(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:c}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:c}),f=t.extractSorted()}else f=isString$1(e)?isString$1(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),computeScore(f,{ignoreFieldNorm:c}),a&&f.sort(isString$1(e)?stable:u),isNumber(n)&&n>-1&&(f=f.slice(0,n));return format(f,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,s=t?null:[];return a.forEach(({v:e,i:a,n:c})=>{if(!isDefined(e))return;let l=r.searchIn(e);if(l.isMatch){let r={score:l.score,value:e,norm:c,indices:l.indices};i&&(r.matchedMask=l.matchedMask,r.matchedTerms=l.matchedTerms,r.termCount=l.termCount);let u=[r];if(!i||this._coversAllTokens(u)){let r={item:e,idx:a,matches:u};t?(r.score=computeScoreSingle(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}}),s}_searchLogical(e){let t=parse(e,this.options),n=this._normalizedKeys(),evaluate=(e,t,r)=>{if(!(`children`in e)){let{keyId:i,searcher:a}=e,s;return i===null?(s=[],n.forEach((e,n)=>{s.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):s=this._findMatches({key:this._keyStore.get(i),value:this._myIndex.getValueForItemAtKeyId(t,i),searcher:a}),s&&s.length?[{idx:r,item:t,matches:s}]:[]}let{children:i,operator:a}=e,s=[];for(let e=0,n=i.length;e<n;e+=1){let n=i[e],c=evaluate(n,t,r);if(c.length)s.push(...c);else if(a===bp.AND)return[]}return s},r=this._myIndex.records,i=/* @__PURE__ */ new Map,a=[];return r.forEach(({$:e,i:n})=>{if(isDefined(e)){let r=evaluate(t,e,n);r.length&&(i.has(n)||(i.set(n,{idx:n,item:e,matches:[]}),a.push(i.get(n))),r.forEach(({matches:e})=>{i.get(n).matches.push(...e)}))}}),a}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,s=this._normalizedKeys(),c=t?null:[];return a.forEach(({$:e,i:a})=>{if(!isDefined(e))return;let l=[],u=!1,f=!1;if(s.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(l.push(...i),i[0].hasInverse&&(f=!0)):u=!0}),!(f&&u)&&l.length&&(!i||this._coversAllTokens(l))){let r={idx:a,item:e,matches:l};t?(r.score=computeScoreSingle(r.matches,{ignoreFieldNorm:n}),t.insert(r)):c.push(r)}}),c}_findMatches({key:e,value:t,searcher:n}){if(!isDefined(t))return[];let r=[];if(isArray(t))t.forEach(({v:t,i,n:a})=>{if(!isDefined(t))return;let s=n.searchIn(t);if(s.isMatch){let n={score:s.score,key:e,value:t,idx:i,norm:a,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(n.matchedMask=s.matchedMask,n.matchedTerms=s.matchedTerms,n.termCount=s.termCount),r.push(n)}});else{let{v:i,n:a}=t,s=n.searchIn(i);if(s.isMatch){let t={score:s.score,key:e,value:i,norm:a,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(t.matchedMask=s.matchedMask,t.matchedTerms=s.matchedTerms,t.termCount=s.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};Fuse.version=`7.5.0`,Fuse.createIndex=createIndex,Fuse.parseIndex=parseIndex,Fuse.config=$,Fuse.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`);return createSearcher(e,{...$,...n}).searchIn(t)},Fuse.parseQuery=parse,register(ExtendedSearch),register(TokenSearch),Fuse.use=function(...e){e.forEach(e=>register(e))};var wp=Fuse;const linkPathSegments=e=>(URL.canParse(e)?new URL(e).pathname:e).split(`/`).filter(Boolean).slice(1).map(e=>e.replace(/\.git$/,``)),Tp=[`name`,`title`,`id`,`description`,`links`],toQuery=e=>({$and:e.split(/\s+/).filter(Boolean).flatMap(e=>{switch(!0){case e.startsWith(`kind:`):return[{kind:`=${e.slice(5)}`}];case e.startsWith(`shape:`):return[{shape:`=${e.slice(6)}`}];case e.startsWith(`meta:`):return[{meta:`=${e.slice(5)}`}];case e.startsWith(`#`):return[{tags:`'${e.slice(1)}`}];default:return(e.match(/[\p{L}\p{M}\p{N}_]+/gu)??[]).map(e=>({$or:Tp.map(t=>({[t]:e}))}))}})}),Ep=A.array(A.discriminatedUnion(`type`,[A.object({type:A.literal(`element`),project:A.string().describe(`Project ID`),id:A.string().describe(`Element ID (FQN)`),name:A.string().describe(`Element name`),kind:A.string(),title:A.string(),description:A.string().nullable(),technology:A.string().nullable(),shape:A.string(),includedInViews:Of,metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])),tags:A.array(A.string())}),A.object({type:A.literal(`deployment-node`),project:A.string().describe(`Project ID`),id:A.string().describe(`Deployment ID (FQN)`),name:A.string().describe(`Deployment name`),kind:A.string(),title:A.string(),description:A.string().nullable(),technology:A.string().nullable(),shape:A.string(),includedInViews:Of,metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])),tags:A.array(A.string())})])),Dp=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`Search elements and deployment nodes across all projects by id, title, description, link, kind, shape, tag or metadata key. Returns the total number of matches and the first 20, ranked by relevance for plain-text searches. Pass the ids found to read-element or other tools.`,inputSchema:{search:A.string().min(2,`Search must be at least 2 characters long`).describe(`Case-insensitive, space-separated words that must all match. "kind:<value>" or "shape:<value>" matches a kind or shape exactly, "meta:<key>" elements with that metadata key, "#<value>" tags containing the value; any other word fuzzy-matches name, title, id (FQN), description or a link path segment except the first. Example: "kind:container #public checkout".`)},outputSchema:{total:A.number(),found:Ep}})(async(e,t)=>{let n=[];for(let t of e.projects())try{let r=await e.computedModel(t.id);for(let e of r.elements())e.imported||n.push({type:`element`,project:t.id,el:e});for(let e of r.deployment.nodes())n.push({type:`deployment-node`,project:t.id,el:e})}catch(e){Z.error(`Error searching in project ${t.id}:`,{error:e})}let r=new wp(n,{useExtendedSearch:!0,ignoreLocation:!0,threshold:.2,keys:[{name:`name`,weight:8,getFn:e=>e.el.name},{name:`title`,weight:4,getFn:e=>e.el.title},{name:`id`,weight:3,getFn:e=>e.el.id},{name:`description`,weight:1,getFn:e=>e.el.description.text??``},{name:`links`,weight:1,getFn:e=>e.el.links.flatMap(e=>linkPathSegments(e.url))},{name:`kind`,getFn:e=>e.el.kind},{name:`shape`,getFn:e=>e.el.shape},{name:`tags`,getFn:e=>[...e.el.tags]},{name:`meta`,getFn:e=>Object.keys(e.el.getMetadata())}]}),i=toQuery(t.search);Z.debug(`search: {query}`,{query:i});let a=r.search(i).map(e=>e.item);return{total:a.length,found:a.slice(0,20).map(toResult)}});function toResult({type:e,project:t,el:n}){return{type:e,project:t,id:n.id,name:n.name,kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,shape:n.shape,tags:[...n.tags],metadata:n.getMetadata(),includedInViews:includedInViews(n.views())}}const Op=A.object({id:A.string().describe(`Element id (FQN)`),name:A.string().describe(`Element name`),kind:A.string().describe(`Element kind`),title:A.string().describe(`Human-readable title`),depth:A.number().describe(`Depth relative to the root element (1 = direct child)`),tags:A.array(A.string()).describe(`Assigned tags`),metadata:A.record(A.string(),A.union([A.string(),A.array(A.string())])).describe(`Element metadata`),childCount:A.number().describe(`Number of direct children`),incomingCount:A.number().describe(`Number of incoming relationships`),outgoingCount:A.number().describe(`Number of outgoing relationships`)}),kp=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:A.string().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:A.number().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:A.array(A.string()).optional().describe(`If provided, only include these metadata keys in the response`),project:Q},outputSchema:{root:A.object({id:A.string(),kind:A.string(),title:A.string(),childCount:A.number()}),descendants:A.array(Op),totalDescendants:A.number().describe(`Total number of descendants found`),truncated:A.boolean().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:A.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);I(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:cf},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
430
481
 
431
482
  Conventions:
432
483
  - All tools are read-only and idempotent.
@@ -452,6 +503,8 @@ Available tools:
452
503
  - query-by-tag-pattern — Search elements by tag prefix/contains/suffix patterns. Input: { pattern, matchMode?, project? }.
453
504
  - element-diff — Compare two elements side-by-side showing differences in properties, tags, metadata, and relationships. Input: { element1Id, element2Id, project? }.
454
505
  - subgraph-summary — Compact summary of all descendants of a parent element with metadata, tags, and relationship counts. Input: { elementId, maxDepth?, metadataKeys?, project? }.
506
+ - removal-impact — What removing an element takes with it (safe delete dry run): relationships, deployed instances, affected views, orphans and source references. Input: { id, project? }.
507
+ - list-diffs — Model diffs (planned changes) with their added/removed/modified counts and the views they change. Input: { project? }.
455
508
 
456
509
  Instructions:
457
510
  - Identify the project first
@@ -461,21 +514,21 @@ Instructions:
461
514
  - If response returns "sourceLocation", provide link to this location in the editor
462
515
 
463
516
  Full documentation: https://likec4.dev/llms-full.txt
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(`
517
+ `,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{D.error(i(e))},le(t,setMcpServerCtx,Uf,rp,np,tp,ap,Dp,Bf,Lf,se(Xf,Qf,ep,Kf,Jf,qf),se(Mf,Ff,kp,op,Hf),se(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),se(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 Ap=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},jp={},getPattern=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return jp[r]||(n[2]?jp[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:jp[r]=[e,n[1],!0]),jp[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},stripPathPrefix=(e,t,n)=>{e.at(-1)===`/`&&t.at(-1)!==`/`&&(e=e.slice(0,-1));let r=0;for(let i=t.indexOf(`/`);i!==-1&&i<n;i=t.indexOf(`/`,i+1))if(r=e.indexOf(`/`,r+1),r===-1)return`/`;return e.slice(r)||`/`},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,Np),_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),r=n;if(r===-1)return;for(e.startsWith(t,r+1)||(r=e.indexOf(`&${t}`,r+1));r!==-1;){let i=e.charCodeAt(r+t.length+1);if(i===61||i===38||isNaN(i)){if(r>n&&/(?:^|&)[^=&]*[%+]/.test(e.slice(n+1,r)))break;if(i===61){let n=r+t.length+2,i=e.indexOf(`&`,n);return _decodeURI(e.slice(n,i===-1?void 0:i))}return``}r=e.indexOf(`&${t}`,r+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},Mp=_getQueryParam,getQueryParams=(e,t)=>_getQueryParam(e,t,!0),Np=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 Mp(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[Ap](){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 Pp={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.bodyUsed&&(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,Pp.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}},Fp=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],Ip=`Can not add a route since the matcher is already built.`;var UnsupportedPathError=class extends Error{};const getPathPrefixLength=(e,t,n)=>{if(!/[:*]/.test(t))return t.length;let r=e.req.path,i=e.req[Ap],a=/* @__PURE__ */ new Set,s=0;for(let c of splitRoutingPath(t)){let t=getPattern(c);if(t&&t!==`*`){let e=t[1];if(a.has(e))throw Error(`mount(): Duplicate path parameter "${e}" in "${n}".`);a.add(e)}if(t&&t!==`*`&&t[2]!==!0){let n=i.length===2?i[1][i[0][e.req.routeIndex][1][t[1]]]:i[0][e.req.routeIndex][1][t[1]];s+=n.length+1}else if(t||c.endsWith(`*`)){let e=r.indexOf(`/`,s+1);s=e===-1?r.length:e}else s+=c.length+1}return s},createMountedRequest=(e,t,n)=>{if(/[^/]\*$/.test(n))throw Error(`mount(): Wildcard must follow "/" in "${n}".`);let r=new URL(e.req.raw.url);return r.pathname=stripPathPrefix(r.pathname,e.req.path,getPathPrefixLength(e,t,n)),new Request(r,e.req.raw)},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 Lp=class Hono{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...Fp,`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]},s=mergePath(this._basePath,e),defaultReplaceRequest=e=>createMountedRequest(e,s.replace(/\/$/,``),mergePath(s,`*`)),handler=async(e,n)=>{let i=await t(r?r(e.req.raw):defaultReplaceRequest(e),...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),Rp=[];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[[],Rp];let s=a.indexOf(``,1);return[r[1][s],a]});return this.match=match,match(e,t)}const zp=Symbol(),Bp=/* @__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 Vp=class Node{#e;#t;#n=createNullObject();insert(e,t,n,r,i){let a=this;for(let t=0,s=e.length;t<s;t++){let c=e[t],l=c.length===1?c===`*`?t===s-1?[``,``,`[^]*`]:[``,``,`[^/]+`]:null:c===`/*`?[``,``,`(?:|/[^]*)`]:c.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(l){let e=l[1],t=l[2]||`[^/]+`;if(e&&l[2]&&(new RegExp(t).test(``)||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))||t.length===1&&Bp.has(t)))throw zp;if(i.push(t),u=a.#n[t],!u){if(t!==`[^]*`&&t!==`(?:|/[^]*)`){for(let e in a.#n)if((t.length>1||e.length>1)&&e!==`[^]*`&&e!==`(?:|/[^]*)`)throw zp}u=a.#n[t]=new Node}e!==``&&(u.#t??=r.varIndex++,n.push([e,u.#t]))}else if(i.push(c),u=a.#n[c],!u){for(let e in a.#n)if(e.length>1&&e!==`[^]*`&&e!==`(?:|/[^]*)`)throw zp;u=a.#n[c]=new Node}a=u}if(a.#e!==void 0)throw zp;a.#e=t}buildRegExpStr(){let e=Object.keys(this.#n).sort(compareKey).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Bp.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Trie=class{#e={varIndex:0};#t=new Vp;#n=0;paths=createNullObject();insert(e,t){let n=[];if(t){this.#t.insert(e.split(``),-1,[],this.#e,n),this.paths[e]=[-1,[],n];return}let r=[],i=[],a=e;for(let e=0;;){let t=!1;if(a=a.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,n=>{let r=`@\\${e}`;return i[e]=[r,n],e++,t=!0,r}),!t)break}let s=a.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=s.length-1;n>=0;n--)if(s[n].indexOf(t)!==-1){s[n]=s[n].replace(t,i[e][1]);break}}this.#t.insert(s,this.#n,r,this.#e,n),this.paths[e]=[this.#n++,r,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]}};function endsWithWildcard(e){let t=e[e.length-1];return t===`[^]*`||t===`(?:|/[^]*)`}function covers(e,t){let n=e.length-1;for(let r=0;r<n;r++)if(e[r]!==t[r])return!1;return e[n]===`[^]*`||t.length===n||t[n]===`/`}var RegExpRouter=class{name=`RegExpRouter`;#e;#t;constructor(){this.#e={ALL:[]},this.#t={ALL:new Trie}}#n(e,t){try{this.#t[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===zp?new UnsupportedPathError(t):e}}add(e,t,n){let r=this.#e;if(!r)throw Error(Ip);let i=this.#t;if(!r[e]){i[e]=new Trie,r[e]=[...r.ALL];for(let t in i.ALL.paths)this.#n(e,t)}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e],s=checkOptionalParameter(t)||[t];for(let e of s)for(let t of a)i[t].paths[e]||this.#n(t,e),r[t].push([n,e])}match=match;buildAllMatchers(){let e=createNullObject();for(let t of Object.keys(this.#e))e[t]=this.#r(t);return this.#e=this.#t=void 0,e}#r(e){let t=this.#e[e],n=this.#t[e],r=createNullObject(),i=[],[a,s,c]=n.buildRegExp(),l=createNullObject(),u=t.map(([e,t],r)=>((l[t]??=[]).push(r),[e,n.paths[t][1].reduceRight((e,[t,n])=>(e[t]=c[n],e),createNullObject())])),f=Object.keys(l).filter(e=>endsWithWildcard(n.paths[e][2]));for(let e in n.paths){let[t,,s]=n.paths[e],c=[...l[e]];for(let t of f)t!==e&&covers(n.paths[t][2],s)&&c.push(...l[t]);let p=c.sort((e,t)=>e-t).map(e=>u[e]);if(t===-1){let t=Math.max(-1,...p.flatMap(([,e])=>Object.values(e)));r[e]=[p,t===-1?Rp:e.match(a).slice(0,t+1)]}else i[t]=p}return[a,s.map(e=>i[e]),r]}},SmartRouter=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(Ip);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 Hp=createNullObject();let Up=0;var Wp=class Node{#e=[];#t=createNullObject();#n=[];#r;#i=Hp;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:++Up}})}#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=Hp;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===Hp?{}:{...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){Object.hasOwn(g,v)||(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))&&(Object.hasOwn(g,v)||(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 Wp;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 Lp{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})}},Gp=A.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:A.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),A.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`});A.looseObject({resource:A.string().url(),authorization_servers:A.array(Gp).optional(),jwks_uri:A.string().url().optional(),scopes_supported:A.array(A.string()).optional(),bearer_methods_supported:A.array(A.string()).optional(),resource_signing_alg_values_supported:A.array(A.string()).optional(),resource_name:A.string().optional(),resource_documentation:A.string().optional(),resource_policy_uri:A.string().url().optional(),resource_tos_uri:A.string().url().optional(),tls_client_certificate_bound_access_tokens:A.boolean().optional(),authorization_details_types_supported:A.array(A.string()).optional(),dpop_signing_alg_values_supported:A.array(A.string()).optional(),dpop_bound_access_tokens_required:A.boolean().optional()});const Kp=A.looseObject({issuer:A.string(),authorization_endpoint:Gp,token_endpoint:Gp,registration_endpoint:Gp.optional(),scopes_supported:A.array(A.string()).optional(),response_types_supported:A.array(A.string()),response_modes_supported:A.array(A.string()).optional(),grant_types_supported:A.array(A.string()).optional(),token_endpoint_auth_methods_supported:A.array(A.string()).optional(),token_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),service_documentation:Gp.optional(),revocation_endpoint:Gp.optional(),revocation_endpoint_auth_methods_supported:A.array(A.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),introspection_endpoint:A.string().optional(),introspection_endpoint_auth_methods_supported:A.array(A.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),code_challenge_methods_supported:A.array(A.string()).optional(),client_id_metadata_document_supported:A.boolean().optional()}),qp=A.looseObject({issuer:A.string(),authorization_endpoint:Gp,token_endpoint:Gp,userinfo_endpoint:Gp.optional(),jwks_uri:Gp,registration_endpoint:Gp.optional(),scopes_supported:A.array(A.string()).optional(),response_types_supported:A.array(A.string()),response_modes_supported:A.array(A.string()).optional(),grant_types_supported:A.array(A.string()).optional(),acr_values_supported:A.array(A.string()).optional(),subject_types_supported:A.array(A.string()),id_token_signing_alg_values_supported:A.array(A.string()),id_token_encryption_alg_values_supported:A.array(A.string()).optional(),id_token_encryption_enc_values_supported:A.array(A.string()).optional(),userinfo_signing_alg_values_supported:A.array(A.string()).optional(),userinfo_encryption_alg_values_supported:A.array(A.string()).optional(),userinfo_encryption_enc_values_supported:A.array(A.string()).optional(),request_object_signing_alg_values_supported:A.array(A.string()).optional(),request_object_encryption_alg_values_supported:A.array(A.string()).optional(),request_object_encryption_enc_values_supported:A.array(A.string()).optional(),token_endpoint_auth_methods_supported:A.array(A.string()).optional(),token_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),display_values_supported:A.array(A.string()).optional(),claim_types_supported:A.array(A.string()).optional(),claims_supported:A.array(A.string()).optional(),service_documentation:A.string().optional(),claims_locales_supported:A.array(A.string()).optional(),ui_locales_supported:A.array(A.string()).optional(),claims_parameter_supported:A.boolean().optional(),request_parameter_supported:A.boolean().optional(),request_uri_parameter_supported:A.boolean().optional(),require_request_uri_registration:A.boolean().optional(),op_policy_uri:Gp.optional(),op_tos_uri:Gp.optional(),client_id_metadata_document_supported:A.boolean().optional()});A.object({...qp.shape,...Kp.pick({code_challenge_methods_supported:!0}).shape}),A.object({access_token:A.string(),id_token:A.string().optional(),token_type:A.string(),expires_in:A.coerce.number().optional(),scope:A.string().optional(),refresh_token:A.string().optional(),issuer:A.string().optional().catch(void 0)}).strip(),A.object({error:A.string(),error_description:A.string().optional(),error_uri:A.string().optional()});const Jp=Gp.optional().or(A.literal(``).transform(()=>void 0)),Yp=A.object({redirect_uris:A.array(Gp),token_endpoint_auth_method:A.string().optional(),grant_types:A.array(A.string()).optional(),response_types:A.array(A.string()).optional(),client_name:A.string().optional(),client_uri:Gp.optional(),logo_uri:Jp,scope:A.string().optional(),contacts:A.array(A.string()).optional(),tos_uri:Jp,policy_uri:A.string().optional(),jwks_uri:Gp.optional(),jwks:A.any().optional(),software_id:A.string().optional(),software_version:A.string().optional(),software_statement:A.string().optional()}).strip(),Xp=A.object({client_id:A.string(),client_secret:A.string().optional(),client_id_issued_at:A.number().optional(),client_secret_expires_at:A.number().optional(),issuer:A.string().optional().catch(void 0)}).strip();Yp.merge(Xp),A.object({error:A.string(),error_description:A.string().optional()}).strip(),A.object({token:A.string(),token_type_hint:A.string().optional()}).strip(),globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto),A.object({client_id:A.string(),redirect_uri:A.string().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),A.object({response_type:A.literal(`code`),code_challenge:A.string(),code_challenge_method:A.literal(`S256`),scope:A.string().optional(),state:A.string().optional(),resource:A.url().optional()}),A.object({grant_type:A.string()}),A.object({code:A.string(),code_verifier:A.string(),redirect_uri:A.string().optional(),resource:A.url().optional()}),A.object({refresh_token:A.string(),scope:A.string().optional(),resource:A.url().optional()}),A.object({client_id:A.string(),client_secret:A.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+`
518
+ `),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,Pp.Stringify,!1,{})).split(/\r\n|\r|\n/).map(e=>`data: ${e}`).join(`
466
519
  `);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(`
467
520
  `)+`
468
521
 
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
522
+ `;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)}},Zp=/* @__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()}),Zp.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=>wl.parse(e)):[wl.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(t.includes(`, `))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=`2025-03-26`,n=e.req.header(`mcp-protocol-version`);if(n){let e=n.split(`,`).map(e=>e.trim());t=e[e.length-1]}if(!ol.includes(t))throw new HTTPException(400,{res:Response.json({jsonrpc:`2.0`,error:{code:Y.ConnectionClosed,message:`Bad Request: Unsupported protocol version (supported versions: ${ol.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)){if(!i){this.#u.delete(n);return}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(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 Qp=/* @__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`]),$p=/^[!#$%&'*+\-.^_`|~\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)},em=/[\0\r\n]/,tm=globalThis.Headers,materializeHeaders=(e,t=tm)=>{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 Fn&&(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(!$p.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof Fn?void 0:this.#e.headers;if(!t||Qp.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 em.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(em.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,tm.prototype);const newHeadersFromIncoming=e=>globalThis.Headers===tm?new RequestHeaders(e):materializeHeaders(e.rawHeaders,globalThis.Headers),nm=/^\/[!#$&-;=?-\[\]_a-z~]*$/,rm=/\/\.\.?(?:[/?#]|$)/,im=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,validateRequestTarget=e=>{let t=e.indexOf(`\\`);if(t!==-1){let n=e.indexOf(`?`);if(n===-1||t<n)throw new RequestError(`Backslash in request path`)}},buildUrl=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!im.test(t)){validateRequestTarget(n);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!nm.test(n)||rm.test(n)?(validateRequestTarget(n),new URL(r).href):r},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),am=global.Request;var Request$1=class extends am{constructor(e,t){if(typeof e==`object`&&um in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[xm]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[um]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const om=Symbol(`wrapBodyStream`),sm=/* @__PURE__ */ new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),isByteExactEncoding=e=>e===null||sm.has(e),cm=Symbol(`bodyBufferedBeforeDisconnect`),lm=Symbol(`bodyBufferedLengthBeforeDisconnect`),toBufferChunk=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),isRecoverableDisconnectedIncoming=e=>!(e instanceof Fn)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&isByteExactEncoding(e.readableEncoding),recordBodyBufferedBeforeDisconnect=e=>{if(e.readableDidRead||!isRecoverableDisconnectedIncoming(e))return;let t=e;t[lm]??=e.readableLength},readBodyBufferedBeforeDisconnect=(e,t)=>{if(e.readableDidRead&&!t||!isRecoverableDisconnectedIncoming(e))return;let n=e;if(n[cm]!==void 0)return n[cm];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[lm]!==void 0&&e.readableLength!==n[lm])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[cm]=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[om]){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||=Dn.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?Dn.toWeb(r):new ReadableStream({start(t){enqueueBufferedBody(t,e)}})}}return new Request$1(t,a)},um=Symbol(`getRequestCache`),dm=Symbol(`requestCache`),fm=Symbol(`incomingKey`),pm=Symbol(`urlKey`),mm=Symbol(`methodKey`),hm=Symbol(`headersKey`),gm=Symbol(`abortControllerKey`),_m=Symbol(`getAbortController`),vm=Symbol(`abortRequest`),ym=Symbol(`bodyBuffer`),bm=Symbol(`bodyReadPromise`),xm=Symbol(`bodyConsumedDirectly`),Sm=Symbol(`bodyLockReader`),Cm=Symbol(`abortReason`),newBodyUnusableError=()=>/* @__PURE__ */ TypeError(`Body is unusable`),rejectBodyUnusable=()=>Promise.reject(newBodyUnusableError()),wm=new TextDecoder,consumeBodyDirectOnce=e=>{if(e[xm])return rejectBodyUnusable();e[xm]=!0},toArrayBuffer=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),contentType=e=>(e[hm]||=newHeadersFromIncoming(e[fm])).get(`content-type`)||``,Tm=/^[!#$%&'*+\-.^_`|~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(!Tm.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[xm])return rejectBodyUnusable();let r=e.method;if(r===`GET`||r===`HEAD`)return e[um]()[t]();let i=validateDirectReadMethod(r);if(i)return Promise.reject(i);if(e[dm]&&r!==`TRACE`)return e[dm][t]();let a=consumeBodyDirectOnce(e);if(a)return a;let s=readRawBodyIfAvailable(e);if(s){let t=Promise.resolve(n(s,e));return e[ym]=void 0,t}return readBodyDirect(e).then(t=>{let r=n(t,e);return e[ym]=void 0,r})},readRawBodyIfAvailable=e=>{let t=e[fm];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},normalizeAbortError=(e,t)=>{if(t.errored)return t.errored;let n=e[Cm];return n===void 0?/* @__PURE__ */ Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},readBodyDirect=e=>{if(e[ym])return Promise.resolve(e[ym]);if(e[bm])return e[bm];let t=e[fm];if(t.readableDidRead)return rejectBodyUnusable();let n=readBodyBufferedBeforeDisconnect(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[ym]=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[ym]=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[ym]=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[bm]=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[bm]=r,r},Em={get method(){return this[mm]},get url(){return this[pm]},get headers(){return this[hm]||=newHeadersFromIncoming(this[fm])},[vm](e){this[Cm]===void 0&&(this[Cm]=e);let t=this[gm];t&&!t.signal.aborted&&t.abort(e)},[_m](){return this[gm]||=new AbortController,this[Cm]!==void 0&&!this[gm].signal.aborted&&this[gm].abort(this[Cm]),this[gm]},[um](){let e=this[_m]();if(this[dm])return this[dm];let t=this.method;if(this[xm]&&t!==`GET`&&t!==`HEAD`){this[ym]=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[pm],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[dm]=r}return this[dm]=newRequestFromIncoming(this.method,this[pm],this.headers,this[fm],e)},get body(){if(!this[xm])return this[um]().body;let e=this[um]();return!this[Sm]&&e.body&&(this[Sm]=e.body.getReader()),e.body},get bodyUsed(){return this[xm]?!0:this[dm]?this[dm].bodyUsed:!1}};Object.defineProperty(Em,"signal",{get(){return this[_m]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(Em,e,{get(){return this[um]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(Em,e,{value:function(){if(this[xm]){if(e===`clone`)throw newBodyUnusableError();return rejectBodyUnusable()}return this[um]()[e]()}})}),Object.defineProperty(Em,"text",{value:function(){return readBodyWithFastPath(this,`text`,e=>wm.decode(e))}}),Object.defineProperty(Em,"arrayBuffer",{value:function(){return readBodyWithFastPath(this,`arrayBuffer`,e=>toArrayBuffer(e))}}),Object.defineProperty(Em,"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(Em,"json",{value:function(){return this[xm]?rejectBodyUnusable():this.text().then(JSON.parse)}}),Object.defineProperty(Em,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[dm]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Em,Request$1.prototype);const newRequest=(e,t)=>{let n=Object.create(Em);n[fm]=e,n[mm]=normalizeIncomingMethod(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof Fn)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{validateRequestTarget(r),n[pm]=new URL(r).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof Fn?e.authority:e.headers.host)||t;if(!i)throw new RequestError(`Missing host header`);let a;if(e instanceof Fn){if(a=e.scheme,a!==`http`&&a!==`https`)throw new RequestError(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[pm]=buildUrl(a,i,r)}catch(e){throw e instanceof RequestError?e:new RequestError(`Invalid URL`,{cause:e})}return n},Dm=`text/plain; charset=UTF-8`,Om=Symbol(`responseCache`),km=Symbol(`getResponseCache`),Am=Symbol(`cache`),jm=global.Response;var Mm=class Response$1{#e;#t;[km](){let e=this[Am],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Am],this[Om]||=new jm(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 jm){let e=t[Om];if(e){this.#t=e,this[km]();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[Am]=[t?.status||200,e??null,n||t?.headers])}get headers(){let e=this[Am];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Dm}))),e[2]):this[km]().headers}get status(){return this[Am]?.[0]??this[km]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Mm.prototype,e,{get(){return this[km]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Mm.prototype,e,{value:function(){return this[km]()[e]()}})}),Object.defineProperty(Mm.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[Om]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Mm,jm),Object.setPrototypeOf(Mm.prototype,jm.prototype);const Nm=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,parseRedirectUrl=e=>e instanceof URL?e.href:Nm.test(e)?e:new URL(e).href,Pm=/* @__PURE__ */ new Set([301,302,303,307,308]);Object.defineProperty(Mm,"redirect",{value:function redirect(e,t=302){if(!Pm.has(t))throw RangeError(`Invalid status code`);return new Mm(null,{status:t,headers:{location:parseRedirectUrl(e)}})},writable:!0,configurable:!0}),Object.defineProperty(Mm,"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 Mm(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},Fm=Symbol(`outgoingEnded`),Im=Symbol(`incomingDraining`),drainIncoming=e=>{let t=e;if(e.destroyed||t[Im])return;if(t[Im]=!0,e instanceof Fn){try{e.stream?.close?.(In.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[vm](t.errored.toString())):(!n.writableFinished||t instanceof Fn&&t.aborted)&&(recordBodyBufferedBeforeDisconnect(t),e[vm](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{drainIncoming(t)})})},isImmediateCacheableResponse=e=>{if(!(Am in e))return!1;let t=e[Am][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 Nn&&(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":Dm}):e.writeHead(t,{"Content-Type":Dm,"Content-Length":n})},responseViaCache=async(e,t)=>{let[n,r,i]=e[Am];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":Dm}),flushHeaders(t),await writeFromReadableStream(r,t)?.catch(e=>handleResponseError(e,t))),t[Fm]?.();return}let a=!1,s=!1,c=!0;if(i instanceof Headers)a=i.has(`content-length`),i=buildOutgoingHttpHeaders(i,r===null?void 0:Dm);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=buildOutgoingHttpHeaders(e,r===null?void 0:Dm)}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[Fm]?.()},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(Am in e)return responseViaCache(e,t);let r=buildOutgoingHttpHeaders(e.headers,e.body===null?void 0:Dm);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[Fm]?.()},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:Mm})),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[om]=!0,r instanceof Fn&&(i[Fm]=()=>{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 Lm=Symbol(`CONNECTION_SYMBOL_KEY`),Rm=Symbol(`WAIT_FOR_WEBSOCKET_SYMBOL`),zm=/* @__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)=>{zm.has(n.toLowerCase())||e.push(`${n}: ${t}`)})},rejectUpgradeRequest=(e,t,n)=>{if(e.destroyed)return;let r=[`Connection: close`,`Content-Length: 0`];appendResponseHeaders(r,n),e.end(`HTTP/1.1 ${t.toString()} ${Mn[t]??``}\r\n${r.join(`\r
470
523
  `)}\r\n\r
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:`)}
524
+ `)},createUpgradeRequest=e=>{let t=e.socket.encrypted?`https`:`http`,n=e.url??`/`,r;n[0]!==`/`&&(n.startsWith(`http://`)||n.startsWith(`https://`))?(validateRequestTarget(n),r=new URL(n).href):r=buildUrl(t,e.headers.host??`localhost`,n);let i=new Headers;for(let t in e.headers){let n=e.headers[t];n&&i.append(t,Array.isArray(n)?n[0]:n)}return new Request(r,{headers:i})},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 ignoreSocketError=()=>{},reclaimWaiterOnClose=()=>rejectWaiter(e);a.on(`error`,ignoreSocketError),a.once(`close`,reclaimWaiterOnClose);let c={incoming:e,outgoing:void 0,wss:r,[Rm]:waitForWebSocket},l=400,u;try{let t=await n(createUpgradeRequest(e),c);t instanceof Response&&(l=t.status,u=t.headers)}catch(e){t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,e instanceof RequestError?400:500);return}if(a.destroyed){rejectWaiter(e);return}let f=i.get(e);if(!f||f.connectionSymbol!==c[Lm]){rejectWaiter(e),t.listenerCount(`upgrade`)===1&&rejectUpgradeRequest(a,l,u);return}let addResponseHeaders=e=>{appendResponseHeaders(e,u)};r.on(`headers`,addResponseHeaders);try{r.handleUpgrade(e,a,s,t=>{a.off(`close`,reclaimWaiterOnClose),a.off(`error`,ignoreSocketError),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||Pn)(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=Qe(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:$t?`debug`:`info`}),process.on(`uncaughtException`,e=>{Z.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{Z.error(`unhandledRejection`,{err:e})}));let n=F(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`,K).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`,q).option(`log-level`,hc).option(`verbose`,gc).showHidden().epilog(`${m.bold(`Examples:`)}
472
525
  ${m.green(`$0 mcp`)}
473
526
  ${m.gray(`Start MCP with default stdio transport`)}
474
527
  ${m.green(`$0 mcp --http ./src`)}
475
528
  ${m.gray(`Start MCP with streamable http transport on port 33335 at ./src folder`)}
476
529
  ${m.green(`$0 mcp -p 1234`)}
477
530
  ${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:`),`
531
+ `),handler:async e=>{e.http||e.port?(f({colors:m.isColorSupported,logLevel:e.verbose?_c:e.logLevel}),await startHttpMcp(e.path,e.useDot,e.port)):(f({useStdErr:!0,colors:!1,logLevel:e.verbose?_c: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:`),`
479
532
  {
480
533
  "mcpServers": {
481
534
  "likec4": {
@@ -487,10 +540,9 @@ ${m.green(`$0 mcp -p 1234`)}
487
540
  ${m.dim(`Documentation:`)}
488
541
  ${m.underline(`https://likec4.dev/tooling/mcp/#using-extension`)}
489
542
  `].join(`
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:`)}
543
+ `))}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 bn({...t,customLogger:t.customLogger,mode:`production`,preview:{host:e.listen??`127.0.0.1`,allowedHosts:!0,port:n,open:r}})}async function handler$1({appConfig:e,path:t,output:n,base:r,listen:i}){let a=await resolveAppConfig({appConfig:e,path:t,output:n,base:r});a.configFile&&createLikeC4Logger(`c4:preview`).info(`${m.cyan(`app config`)} ${m.dim(relativeToCwd(a.configFile))}`);let s=await S(a.workspace,{watch:!1});printServerUrls(await vitePreview({base:a.base,languageServices:s,outputDir:a.build.outDir,open:!isInsideContainer(),listen:i}))}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`,withoutDefault(K)).option(`app-config`,$s).option(`output`,{alias:`o`,type:`string`,desc:`output directory from production build`,normalize:!0,coerce:F}).option(`base`,sc).option(`listen`,{alias:`l`,type:`string`,desc:`ip address of the network interface to listen on`,default:`127.0.0.1`,defaultDescription:`localhost`}),handler:async e=>{await handler$1({appConfig:e[`app-config`],path:e.path,output:e.output,base:e.base,listen:e.listen})}}),Bm=`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===Bm&&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===Bm&&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 hn(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 ct(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=Tn(`sha256`).update(n).digest(`hex`);if(!Object.hasOwn(r,a)){if(c>=200)throw new AssetError(`Too many icon files: at most 200 per publish, "${t}" is over the limit`);if(s+n.byteLength>10485760)throw new AssetError(`Icon files exceed the 10485760 bytes total limit, "${t}" is over it`);r[a]={filename:mt(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=Xt){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 Vm=/^[a-z][a-z0-9+.-]*:\/\//i,Hm=/^(?:[^@/]+@)?([^@/:]+):(.+)$/,Um=/* @__PURE__ */ new Set([`.`,`..`]);function parseGitOrigin(e){let t=e.trim();if(t===``)return null;let n;switch(!0){case Vm.test(t):try{n=new URL(t).pathname}catch{return null}break;default:{let e=Hm.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===``||Um.has(i)||Um.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 Wm=`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. ${Wm}`,{cause:e})}if(s===null){if(!a)throw Error(`Failed to resolve the git repository root. ${Wm}`);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(`
544
+ `)[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. ${Wm}`,{cause:e})}if(t===null)throw Error(`Failed to resolve the current commit. ${Wm}`);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. ${Wm}`,{cause:e})}}const Gm=/^(?:\/|[a-zA-Z]:\/)/,Km={relative:P};function toWorkspacePath(e,t,n=Km){let r=n.relative(e,t).replaceAll(`\\`,`/`);if(r===``)return`.`;if(r===`..`||r.startsWith(`../`)||Gm.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 qm=`LIKEC4_PUBLISH_TOKEN`;function resolveToken(e){let t=e?.trim()||Zt[qm]?.trim();if(!t)throw Error(`No publish token provided, pass --token or set the ${qm} environment variable`);return t}function resolveBaseUrl(e){return(e?.trim()||Zt.LIKEC4_CLOUD_URL?.trim()||`https://likec4.app`).replace(/\/+$/,``)}function humanSize(e){return`${(e/1024).toFixed(1)} KB`}function toPhysicalPath(e){let t=F(e),n=t,r=[];for(;;)try{return yt(zt(n),...r.reverse())}catch{let e=ht(n);if(e===n)return t;r.push(mt(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(`
545
+ `),{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=F(e.path),f=await readGitProvenance({runner:createGitRunner(u),env:Zt,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),C=new Uint8Array(Ln(x));n.info(`${m.dim(`payload:`)} ${humanSize(Buffer.byteLength(x))} ${m.dim(`→`)} ${humanSize(C.byteLength)} ${m.dim(`gzipped`)}`);let w=Object.keys(y.assets).length;w>0&&n.info(`${m.dim(`assets:`)} ${w} ${m.dim(`file(s),`)} ${humanSize(y.totalBytes)}`);let T=`${s}/api/publish`;n.info(`${m.dim(`publishing to`)} ${m.green(T)}`);let E;try{E=await Ni.post(T,{body:C,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(E.snapshotId)}`),n.info(`${m.dim(`view at`)} ${m.underline(m.green(E.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`,K).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:{...mc,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":q}).epilog(`${m.bold(`Notes:`)}
494
546
  ${m.gray(`A snapshot is keyed by commit - publishing the same commit again`)}
495
547
  ${m.gray(`OVERWRITES its snapshot. Projects ACCUMULATE into a snapshot,`)}
496
548
  ${m.gray(`publishing one project never removes the others.`)}
@@ -511,14 +563,18 @@ ${m.bold(`Examples:`)}
511
563
  ${m.gray(` env:`)}
512
564
  ${m.gray(" LIKEC4_PUBLISH_TOKEN: ${{ secrets.LIKEC4_PUBLISH_TOKEN }}")}
513
565
  ${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:`)}
566
+ `),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`]})}})}const Jm={removed:`Removed together with the element`,optional:`Removed only with --scoped-views or --dynamic-steps`,manual:`Fix manually`};function describeReport(e){let{impact:t,references:n}=e,r=[`${m.bold(`Removes`)} ${t.elements.length} element(s), ${t.relations.length} relation(s), ${t.deployedInstances.length} deployed instance(s)`,`${m.bold(`Changes`)} ${t.affectedViews.length} view(s)${t.scopedViews.length>0?`, ${t.scopedViews.length} view(s) are scoped to it`:``}`];t.orphans.length>0&&r.push(`${m.yellow(`Orphans`)} (use --orphans to remove): ${t.orphans.join(`, `)}`),t.emptyDeploymentNodes.length>0&&r.push(`${m.yellow(`Empty deployment nodes`)}: ${t.emptyDeploymentNodes.join(`, `)}`);for(let[e,t]of ce(Jm)){let i=n.filter(t=>t.resolution===e);if(i.length!==0){r.push(`${m.bold(t)} (${i.length}):`);for(let e of i)r.push(` ${m.dim(displayLocation(e.location.uri,e.location.range))} ${e.text}`)}}return r}const safeDeleteCmd=e=>e.command({command:`safe-delete <element> [path]`,describe:`Remove an element and everything that references it (use --dry-run to see the impact)`,builder:e=>e.positional(`element`,{type:`string`,demandOption:!0,desc:`element FQN, e.g. cloud.backend`}).positional(`path`,K).options({project:mc,"dry-run":{type:`boolean`,default:!1,desc:`only report what the removal takes with it`},orphans:{type:`boolean`,default:!1,desc:`also remove elements left without relationships`},"scoped-views":{type:`boolean`,default:!1,desc:`also remove views scoped to removed elements`},"dynamic-steps":{type:`boolean`,default:!1,desc:`also remove dynamic view steps`},json:{type:`boolean`,default:!1,desc:`print the dry-run report as JSON`}}),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:safe-delete`),r=t.a(await S(e.path,{watch:!1,...e.json&&{printErrors:!1,configureLogger:`stderr`}})),i=await findProject(projectsToSearch(r,e.project),`Element ${e.element}`,async t=>!!(await r.parsedModel(t)).findElement(e.element));if(`error`in i){n.error(i.error),process.exitCode=1;return}let{projectId:a}=i;if(e.dryRun){let t=await r.removalImpact.analyze([e.element],a);if(!t){n.error(`Element not found: ${e.element}`),process.exitCode=1;return}if(e.json){process.stdout.write(JSON.stringify(t,null,2)+`
567
+ `);return}for(let e of describeReport(t))n.info(e);return}let s=await r.modelEdits.apply({type:`safe-delete`,targets:[e.element],options:{includeOrphans:e.orphans,includeScopedViews:e.scopedViews,includeDynamicSteps:e.dynamicSteps}},{projectId:a});reportEditResult(n,`Safe delete ${e.element}`,s)}catch(e){t.e=e}finally{await t.d()}}});async function handler({path:e,useDotBin:t,webcomponentPrefix:n,title:r,theme:i,customization:a,appConfigFile:s,useHashHistory:c,enableWebcomponent:l=!0,enableHMR:u=!0,base:f,listen:p,port:h,hmrPort:g,userPublicDir:v,allowedHosts:y}){u&&(process.env.NODE_ENV=`development`);let b=await viteDev({buildWebcomponent:l,hmr:u,base:f,webcomponentPrefix:n,title:r,theme:i,customization:a,languageServices:await S(e,{graphviz:t?`binary`:`wasm`,watch:u}),useHashHistory:c,likec4AssetsDir:await st(yt(pn(),`.likec4-assets-`)),listen:p,port:h,hmrPort:g,userPublicDir:v,allowedHosts:y});if(b.config.logger.clearScreen(`info`),printServerUrls(b),s){let e=yn(s);b.watcher.add(s),b.watcher.on(`change`,t=>{yn(t)===e&&b.config.logger.warn(m.yellow(`${relativeToCwd(s)} changed, restart to apply`))})}}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`,withoutDefault(K)).option(`app-config`,$s).option(`base`,sc).option(`webcomponent-prefix`,withoutDefault(ic)).option(`title`,withoutDefault(ac)).option(`theme`,oc).option(`customization`,ec).option(`use-hash-history`,nc).option(`use-dot`,withoutDefault(q)).option(`listen`,withoutDefault(dc)).option(`port`,fc).option(`hmr-port`,pc).option(`public`,lc).option(`allowed-host`,uc).options({"react-hmr":{type:`boolean`,default:!0,describe:`Enable/Disable React HMR`},"build-webcomponent":{type:`boolean`,defaultDescription:`true`,describe:`Enable/Disable Webcomponent build`}}),handler:async e=>{await notifyAvailableUpdate(),setTimeout(showSupportUsMessage,5e3).unref(),await ensureReact();let t=await resolveAppConfig({appConfig:e[`app-config`],path:e.path,useDot:e[`use-dot`],base:e.base,title:e.title,theme:e.theme,useHashHistory:e[`use-hash-history`],webcomponentPrefix:e[`webcomponent-prefix`],customization:e.customization,publicDir:e.public,buildWebcomponent:e[`build-webcomponent`],listen:e.listen,port:e.port,hmrPort:e[`hmr-port`],allowedHosts:e[`allowed-host`]});t.configFile&&createLikeC4Logger(`c4:start`).info(`${m.cyan(`app config`)} ${m.dim(relativeToCwd(t.configFile))}`),await handler({path:t.workspace,useDotBin:t.graphviz===`binary`,base:t.base,webcomponentPrefix:t.webcomponentPrefix,title:t.title,theme:t.theme,customization:t.customization,appConfigFile:t.configFile,useHashHistory:t.useHashHistory,listen:t.server.host,port:t.server.port,hmrPort:t.server.hmrPort,enableHMR:e[`react-hmr`],enableWebcomponent:t.build.webcomponent,userPublicDir:t.publicDir,allowedHosts:t.server.allowedHosts})}});async function runSyncPlan(e,t,n,r){let i=await planSyncToLeanix(t,n,{idempotent:!0}),a=F(e,`sync-plan.json`);if(await M(a,JSON.stringify(i,null,2)),r.info(`${m.dim(`generated`)} ${P(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=F(e,Nc.manifest);if(await M(a,JSON.stringify(i.manifest,null,2)),r.info(`${m.dim(`generated`)} ${P(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===Ze.EMPTY)throw t.error(Dc),Error(Dc);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(Oc),Error(Oc);await runSyncApply(i,p,h,t)}}catch(e){u.e=e}finally{await u.d()}}finally{n.stopAndLog()}}const Ym=F(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`,K).option(`outdir`,{...rc,default:Ym,desc:`<dir> output directory for bridge artifacts (manifest, leanix-dry-run, report, sync-plan)`}).option(`dry-run`,{type:`boolean`,describe:`Only write artifacts and optional sync-plan; do not call LeanIX API for create/update`}).option(`apply`,{type:`boolean`,describe:`Run live sync to LeanIX (requires LEANIX_API_TOKEN)`}).conflicts(`dry-run`,`apply`).option(`project`,mc).option(`use-dot`,q).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??Ym,project:e.project,useDotBin:e.useDotBin??!1,dryRun:n,apply:t})}})}function matchesFilter(e,t){return t.some(t=>e===t||e.endsWith(`/`+t)||e.endsWith(`\\`+t))}function parseMaxWarnings(e){if(e!==void 0){if(!Number.isInteger(e)||e<0)throw Error(`--max-warnings must be a non-negative integer, got ${e}`);return e}}function buildValidateResult({documents:e,errors:t,warnings:n=[],fileFilter:r,maxWarnings:i=null}){let a=r?t.filter(e=>matchesFilter(e.file,r)):[...t],s=r?n.filter(e=>matchesFilter(e.file,r)):[...n],c=r?e.filter(e=>matchesFilter(e,r)).length:e.length,l=i!==null&&s.length>i;return{valid:a.length===0&&!l,errors:a,warnings:s,maxWarnings:i,stats:{totalFiles:e.length,totalErrors:t.length,totalWarnings:n.length,filteredFiles:c,filteredErrors:a.length,filteredWarnings:s.length}}}const toDiagnosticItem=e=>({message:e.message,file:e.sourceFsPath,line:e.line,range:e.range});function formatDiagnostic(e){let t=e.range?`:${e.range.start.line+1}:${e.range.start.character+1}`:``;return`${e.file}${t} ${e.message}`}async function runValidate(e,t,n,r=console.log){let i=t.file?.map(e=>F(e))??null,a=[];if(t.layout){n.debug(`running layout validation...`);let r=t.project?[t.project]:e.projects();for(let n of r)try{let r=await e.layoutedModel(n),i=e.projectsManager.getProject(r.projectId)?.folderUri.fsPath??t.path;for(let e of r.views()){let t=e.$layouted;t.drifts&&t.drifts.length>0&&a.push({message:`Layout drift detected on view '${t.id}'`,file:t.sourcePath?F(i,t.sourcePath):``,line:0,range:null})}}catch(e){a.push({message:`Layout validation failed: ${e instanceof Error?e.message:String(e)}`,file:``,line:0,range:null})}}let s=buildValidateResult({documents:e.documentPaths(),errors:[...e.getErrors().map(toDiagnosticItem),...a],warnings:e.getWarnings().map(toDiagnosticItem),fileFilter:i,maxWarnings:t.maxWarnings??null});if(t.json)return r(JSON.stringify(s,null,2)),s;for(let e of a)n.error(m.red(e.message)+(e.file?` at `+e.file:``));for(let e of s.warnings)n.warn(m.yellow(`Warning `)+formatDiagnostic(e));let{totalFiles:c,totalErrors:l,filteredErrors:u,filteredWarnings:f}=s.stats,p=f>0?`, ${f} warnings`:``,h=s.maxWarnings!==null&&f>s.maxWarnings?` (max ${s.maxWarnings})`:``;if(s.valid)n.info(m.green(`✓ Valid`)+m.dim(` (${c} files${p})`));else{let e=i?`, ${u} in filtered files`:``;n.error(m.red(`✗ Invalid`)+m.dim(` (${c} files, ${l} errors${e}${p}${h})`))}return s}const validateCmd=e=>e.command({command:`validate [path]`,aliases:[],describe:`Validate syntax, semantics and layout drifts`,builder:e=>e.positional(`path`,K).options({project:mc,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)`},"max-warnings":{number:!0,nargs:1,defaultDescription:`unlimited`,description:`fail validation when there are more warnings than this number (0 fails on any warning)`,coerce:parseMaxWarnings}}).showHidden().epilog(`${m.bold(`Examples:`)}
515
568
  ${m.green(`$0 validate `)}
516
569
  ${m.gray(`Validate all in the current directory`)}
517
570
 
518
571
  ${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(`, `))}
572
+ ${m.gray(`Validate all, ignore layout drifts, report only errors from these files, output as JSON`)}
573
+
574
+ ${m.green(`$0 validate --max-warnings 0`)}
575
+ ${m.gray(`Validate all, fail on any warning`)}
520
576
 
521
577
  ${m.green(`$0 validate --project my-project /some/where`)}
522
578
  ${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{};
579
+ `),handler:async e=>{try{var t=_usingCtx();let n=createLikeC4Logger(`c4:validate`),r=startTimer(n),i=e.json===!0,a=await runValidate(t.a(await S(e.path,{watch:!1,printErrors:!i,throwIfInvalid:!1,configureLogger:i?`stderr`:!1})),{path:e.path,project:e.project,file:e.file,layout:e.layout===!0,json:i,maxWarnings:e.maxWarnings},n);process.exitCode=+!a.valid,i||r.stopAndLog(`validate `)}catch(e){t.e=e}finally{await t.d()}}});function applyLoggerConfig(e){let t=e??($t?`debug`:`info`);s({reset:!0,sinks:{console:l({formatter:m.isColorSupported?E():a()})},loggers:[{category:`likec4`,sinks:[`console`],lowestLevel:t}]})}async function main(){await le(un(dn(rn)),serveCmd,buildCmd,codegenCmd,exportCmd,formatCmd,previewCmd,publishCmd,syncCmd,validateCmd,e=>safeDeleteCmd(diffCmd(e)),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(Vn).alias(`v`,`version`).alias(`h`,`help`).help(`help`).option(`log-level`,hc).option(`verbose`,gc).option(`color`,{boolean:!0,describe:`force color output, or disable with --no-color
580
+ respects 'FORCE_COLOR' and 'NO_COLOR' env variables`,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(de(cn.columns-10,{min:60,max:180})).middleware(e=>{applyLoggerConfig(e.verbose?_c:e.logLevel)}).parseAsync()}function exitWithFailure(e,t){console.error(t==null?i(e):`${t} ${i(e)}`),on(1)}main().catch(exitWithFailure),process.on(`unhandledRejection`,e=>{exitWithFailure(e,`Unhandled rejection:`)}),process.on(`uncaughtException`,e=>{console.error(e)});export{};