@likec4/mcp 1.59.4 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/app/render-view-client.css +1 -1
  2. package/dist/app/render-view-client.js +508 -334
  3. package/dist/chunks/libs/@chevrotain/gast.mjs +27 -0
  4. package/dist/chunks/libs/@chevrotain/regexp-to-ast.mjs +81 -0
  5. package/dist/chunks/libs/@logtape/logtape.mjs +6 -0
  6. package/dist/chunks/libs/@lume/kiwi.mjs +1 -0
  7. package/dist/chunks/libs/@radix-ui/colors.mjs +1 -0
  8. package/dist/chunks/libs/@ts-graphviz/ast.mjs +3 -0
  9. package/dist/chunks/libs/@ts-graphviz/core.mjs +1 -0
  10. package/dist/chunks/libs/@ungap/structured-clone.mjs +3 -0
  11. package/dist/chunks/libs/character-entities.mjs +2 -0
  12. package/dist/chunks/libs/chevrotain-allstar.mjs +2 -0
  13. package/dist/chunks/libs/chevrotain.mjs +110 -0
  14. package/dist/chunks/libs/chroma-js.mjs +15 -0
  15. package/dist/chunks/libs/eventemitter3.mjs +1 -0
  16. package/dist/chunks/libs/graphology-dag.mjs +1 -0
  17. package/dist/chunks/libs/graphology.mjs +1 -0
  18. package/dist/chunks/libs/hast-util-sanitize.mjs +1 -0
  19. package/dist/chunks/libs/hast-util-to-html.mjs +9 -0
  20. package/dist/chunks/libs/hastscript.mjs +1 -0
  21. package/dist/chunks/libs/immer.mjs +1 -0
  22. package/dist/chunks/libs/json5.mjs +14 -0
  23. package/dist/chunks/libs/khroma.mjs +1 -0
  24. package/dist/chunks/libs/langium.mjs +17 -0
  25. package/dist/chunks/libs/markdown-table.mjs +2 -0
  26. package/dist/chunks/libs/mdast-util-find-and-replace.mjs +1 -0
  27. package/dist/chunks/libs/mdast-util-from-markdown.mjs +9 -0
  28. package/dist/chunks/libs/mdast-util-gfm.mjs +15 -0
  29. package/dist/chunks/libs/mdast-util-to-hast.mjs +11 -0
  30. package/dist/chunks/libs/merge-error-cause.mjs +2 -0
  31. package/dist/chunks/libs/micromark-extension-gfm.mjs +5 -0
  32. package/dist/chunks/libs/mnemonist.mjs +1 -0
  33. package/dist/chunks/libs/nano-spawn.mjs +3 -0
  34. package/dist/chunks/libs/ohash.mjs +1 -0
  35. package/dist/chunks/libs/p-limit.mjs +1 -0
  36. package/dist/chunks/libs/p-queue.mjs +1 -0
  37. package/dist/chunks/libs/parse-entities.mjs +1 -0
  38. package/dist/chunks/libs/pathe.mjs +1 -0
  39. package/dist/chunks/libs/pretty-ms.mjs +1 -0
  40. package/dist/chunks/libs/refractor.mjs +5 -0
  41. package/dist/chunks/libs/rehype-prism-plus.mjs +4 -0
  42. package/dist/chunks/libs/remark-github-blockquote-alert.mjs +3 -0
  43. package/dist/chunks/libs/remark-rehype.mjs +1 -0
  44. package/dist/chunks/libs/remeda.mjs +1 -0
  45. package/dist/chunks/libs/ufo.mjs +1 -0
  46. package/dist/chunks/libs/unified.mjs +1 -0
  47. package/dist/chunks/libs/unstorage.mjs +1 -0
  48. package/dist/chunks/libs/which.mjs +1 -0
  49. package/dist/chunks/rolldown-runtime.mjs +1 -0
  50. package/dist/chunks/src.mjs +320 -1118
  51. package/dist/cli.mjs +5 -1
  52. package/dist/index.mjs +1 -1
  53. package/package.json +60 -56
@@ -0,0 +1,17 @@
1
+ import{i as e,r as t}from"../rolldown-runtime.mjs";import{n,t as r}from"./@chevrotain/regexp-to-ast.mjs";import{a as i,l as a,n as o,o as s,r as c,t as l,u}from"./chevrotain.mjs";import{t as d}from"./chevrotain-allstar.mjs";import*as f from"node:fs";import{CompletionItemKind as p,CompletionList as m,DidChangeWatchedFilesNotification as ee,Disposable as h,DocumentHighlight as te,Emitter as g,FileChangeType as ne,FoldingRange as re,FoldingRangeKind as ie,Location as ae,LocationLink as oe,Position as se,SemanticTokenModifiers as _,SemanticTokenTypes as v,SemanticTokensBuilder as ce,SymbolKind as le,TextDocumentSyncKind as ue}from"vscode-languageserver";import{URI as de,URI as y,Utils as fe}from"vscode-uri";import{CancellationToken as b,CancellationTokenSource as pe,DidChangeConfigurationNotification as me,Emitter as he,Emitter as ge,LSPErrorCodes as _e,ResponseError as ve,TextDocumentSyncKind as ye}from"vscode-languageserver-protocol";import{TextDocument as be}from"vscode-languageserver-textdocument";import{Position as x,Range as S,TextEdit as xe}from"vscode-languageserver-types";function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.$type==`string`}function isReference(e){return typeof e==`object`&&!!e&&typeof e.$refText==`string`&&`ref`in e}function isMultiReference(e){return typeof e==`object`&&!!e&&typeof e.$refText==`string`&&`items`in e}function isAstNodeDescription(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.type==`string`&&typeof e.path==`string`}function isLinkingError(e){return typeof e==`object`&&!!e&&typeof e.info==`object`&&typeof e.message==`string`}var AbstractAstReflection=class{constructor(){this.subtypes={},this.allSubtypes={}}getAllTypes(){return Object.keys(this.types)}getReferenceType(e){let t=this.types[e.container.$type];if(!t)throw Error(`Type ${e.container.$type||`undefined`} not found.`);let n=t.properties[e.property]?.referenceType;if(!n)throw Error(`Property ${e.property||`undefined`} of type ${e.container.$type} is not a reference.`);return n}getTypeMetaData(e){return this.types[e]||{name:e,properties:{},superTypes:[]}}isInstance(e,t){return isAstNode(e)&&this.isSubtype(e.$type,t)}isSubtype(e,t){if(e===t)return!0;let n=this.subtypes[e];n||=this.subtypes[e]={};let r=n[t];if(r!==void 0)return r;{let r=this.types[e],i=r?r.superTypes.some(e=>this.isSubtype(e,t)):!1;return n[t]=i,i}}getAllSubTypes(e){let t=this.allSubtypes[e];if(t)return t;{let t=this.getAllTypes(),n=[];for(let r of t)this.isSubtype(r,e)&&n.push(r);return this.allSubtypes[e]=n,n}}isComplete(e){let t=this.getTypeMetaData(e.$type);for(let n of Object.keys(t.properties)){let r=t.properties[n];if(!r.optional&&e[r.name]==null)return!1}return!0}};function isCompositeCstNode(e){return typeof e==`object`&&!!e&&Array.isArray(e.content)}function isLeafCstNode(e){return typeof e==`object`&&!!e&&typeof e.tokenType==`object`}function isRootCstNode(e){return isCompositeCstNode(e)&&typeof e.fullText==`string`}const C={$type:`AbstractElement`,cardinality:`cardinality`};function isAbstractElement(e){return U.isInstance(e,C.$type)}const Se={$type:`AbstractParserRule`};function isAbstractParserRule(e){return U.isInstance(e,Se.$type)}const Ce={$type:`AbstractRule`},w={$type:`AbstractType`},T={$type:`Action`,cardinality:`cardinality`,feature:`feature`,inferredType:`inferredType`,operator:`operator`,type:`type`};function isAction(e){return U.isInstance(e,T.$type)}const we={$type:`Alternatives`,cardinality:`cardinality`,elements:`elements`};function isAlternatives(e){return U.isInstance(e,we.$type)}const Te={$type:`ArrayLiteral`,elements:`elements`},Ee={$type:`ArrayType`,elementType:`elementType`};function isArrayType(e){return U.isInstance(e,Ee.$type)}const E={$type:`Assignment`,cardinality:`cardinality`,feature:`feature`,operator:`operator`,predicate:`predicate`,terminal:`terminal`};function isAssignment(e){return U.isInstance(e,E.$type)}const De={$type:`BooleanLiteral`,true:`true`};function isBooleanLiteral(e){return U.isInstance(e,De.$type)}const D={$type:`CharacterRange`,cardinality:`cardinality`,left:`left`,lookahead:`lookahead`,parenthesized:`parenthesized`,right:`right`};function isCharacterRange(e){return U.isInstance(e,D.$type)}const O={$type:`Condition`},Oe={$type:`Conjunction`,left:`left`,right:`right`};function isConjunction(e){return U.isInstance(e,Oe.$type)}const k={$type:`CrossReference`,cardinality:`cardinality`,deprecatedSyntax:`deprecatedSyntax`,isMulti:`isMulti`,terminal:`terminal`,type:`type`};function isCrossReference(e){return U.isInstance(e,k.$type)}const ke={$type:`Disjunction`,left:`left`,right:`right`};function isDisjunction(e){return U.isInstance(e,ke.$type)}const Ae={$type:`EndOfFile`,cardinality:`cardinality`};function isEndOfFile(e){return U.isInstance(e,Ae.$type)}const A={$type:`Grammar`,imports:`imports`,interfaces:`interfaces`,isDeclared:`isDeclared`,name:`name`,rules:`rules`,types:`types`},je={$type:`GrammarImport`,path:`path`},j={$type:`Group`,cardinality:`cardinality`,elements:`elements`,guardCondition:`guardCondition`,predicate:`predicate`};function isGroup(e){return U.isInstance(e,j.$type)}const Me={$type:`InferredType`,name:`name`};function isInferredType(e){return U.isInstance(e,Me.$type)}const M={$type:`InfixRule`,call:`call`,dataType:`dataType`,inferredType:`inferredType`,name:`name`,operators:`operators`,parameters:`parameters`,returnType:`returnType`};function isInfixRule(e){return U.isInstance(e,M.$type)}const Ne={$type:`InfixRuleOperatorList`,associativity:`associativity`,operators:`operators`},Pe={$type:`InfixRuleOperators`,precedences:`precedences`},Fe={$type:`Interface`,attributes:`attributes`,name:`name`,superTypes:`superTypes`};function isInterface(e){return U.isInstance(e,Fe.$type)}const Ie={$type:`Keyword`,cardinality:`cardinality`,predicate:`predicate`,value:`value`};function isKeyword(e){return U.isInstance(e,Ie.$type)}const Le={$type:`NamedArgument`,calledByName:`calledByName`,parameter:`parameter`,value:`value`},N={$type:`NegatedToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,terminal:`terminal`};function isNegatedToken(e){return U.isInstance(e,N.$type)}const Re={$type:`Negation`,value:`value`};function isNegation(e){return U.isInstance(e,Re.$type)}const ze={$type:`NumberLiteral`,value:`value`},Be={$type:`Parameter`,name:`name`},Ve={$type:`ParameterReference`,parameter:`parameter`};function isParameterReference(e){return U.isInstance(e,Ve.$type)}const P={$type:`ParserRule`,dataType:`dataType`,definition:`definition`,entry:`entry`,fragment:`fragment`,inferredType:`inferredType`,name:`name`,parameters:`parameters`,returnType:`returnType`};function isParserRule(e){return U.isInstance(e,P.$type)}const He={$type:`ReferenceType`,isMulti:`isMulti`,referenceType:`referenceType`};function isReferenceType(e){return U.isInstance(e,He.$type)}const F={$type:`RegexToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,regex:`regex`};function isRegexToken(e){return U.isInstance(e,F.$type)}const Ue={$type:`ReturnType`,name:`name`};function isReturnType(e){return U.isInstance(e,Ue.$type)}const I={$type:`RuleCall`,arguments:`arguments`,cardinality:`cardinality`,predicate:`predicate`,rule:`rule`};function isRuleCall(e){return U.isInstance(e,I.$type)}const We={$type:`SimpleType`,primitiveType:`primitiveType`,stringType:`stringType`,typeRef:`typeRef`};function isSimpleType(e){return U.isInstance(e,We.$type)}const Ge={$type:`StringLiteral`,value:`value`},L={$type:`TerminalAlternatives`,cardinality:`cardinality`,elements:`elements`,lookahead:`lookahead`,parenthesized:`parenthesized`};function isTerminalAlternatives(e){return U.isInstance(e,L.$type)}const R={$type:`TerminalElement`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`},z={$type:`TerminalGroup`,cardinality:`cardinality`,elements:`elements`,lookahead:`lookahead`,parenthesized:`parenthesized`};function isTerminalGroup(e){return U.isInstance(e,z.$type)}const B={$type:`TerminalRule`,definition:`definition`,fragment:`fragment`,hidden:`hidden`,name:`name`,type:`type`};function isTerminalRule(e){return U.isInstance(e,B.$type)}const V={$type:`TerminalRuleCall`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,rule:`rule`};function isTerminalRuleCall(e){return U.isInstance(e,V.$type)}const Ke={$type:`Type`,name:`name`,type:`type`};function isType(e){return U.isInstance(e,Ke.$type)}const qe={$type:`TypeAttribute`,defaultValue:`defaultValue`,isOptional:`isOptional`,name:`name`,type:`type`},Je={$type:`TypeDefinition`},Ye={$type:`UnionType`,types:`types`};function isUnionType(e){return U.isInstance(e,Ye.$type)}const Xe={$type:`UnorderedGroup`,cardinality:`cardinality`,elements:`elements`};function isUnorderedGroup(e){return U.isInstance(e,Xe.$type)}const H={$type:`UntilToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,terminal:`terminal`};function isUntilToken(e){return U.isInstance(e,H.$type)}const Ze={$type:`ValueLiteral`},Qe={$type:`Wildcard`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`};function isWildcard(e){return U.isInstance(e,Qe.$type)}var LangiumGrammarAstReflection=class extends AbstractAstReflection{constructor(){super(...arguments),this.types={AbstractElement:{name:C.$type,properties:{cardinality:{name:C.cardinality,optional:!0}},superTypes:[]},AbstractParserRule:{name:Se.$type,properties:{},superTypes:[Ce.$type,w.$type]},AbstractRule:{name:Ce.$type,properties:{},superTypes:[]},AbstractType:{name:w.$type,properties:{},superTypes:[]},Action:{name:T.$type,properties:{cardinality:{name:T.cardinality,optional:!0},feature:{name:T.feature,optional:!0},inferredType:{name:T.inferredType,optional:!0},operator:{name:T.operator,optional:!0},type:{name:T.type,referenceType:w.$type,optional:!0}},superTypes:[C.$type]},Alternatives:{name:we.$type,properties:{cardinality:{name:we.cardinality,optional:!0},elements:{name:we.elements,defaultValue:[]}},superTypes:[C.$type]},ArrayLiteral:{name:Te.$type,properties:{elements:{name:Te.elements,defaultValue:[]}},superTypes:[Ze.$type]},ArrayType:{name:Ee.$type,properties:{elementType:{name:Ee.elementType}},superTypes:[Je.$type]},Assignment:{name:E.$type,properties:{cardinality:{name:E.cardinality,optional:!0},feature:{name:E.feature},operator:{name:E.operator},predicate:{name:E.predicate,optional:!0},terminal:{name:E.terminal}},superTypes:[C.$type]},BooleanLiteral:{name:De.$type,properties:{true:{name:De.true,defaultValue:!1}},superTypes:[O.$type,Ze.$type]},CharacterRange:{name:D.$type,properties:{cardinality:{name:D.cardinality,optional:!0},left:{name:D.left},lookahead:{name:D.lookahead,optional:!0},parenthesized:{name:D.parenthesized,defaultValue:!1,optional:!0},right:{name:D.right,optional:!0}},superTypes:[R.$type]},Condition:{name:O.$type,properties:{},superTypes:[]},Conjunction:{name:Oe.$type,properties:{left:{name:Oe.left},right:{name:Oe.right}},superTypes:[O.$type]},CrossReference:{name:k.$type,properties:{cardinality:{name:k.cardinality,optional:!0},deprecatedSyntax:{name:k.deprecatedSyntax,defaultValue:!1},isMulti:{name:k.isMulti,defaultValue:!1},terminal:{name:k.terminal,optional:!0},type:{name:k.type,referenceType:w.$type}},superTypes:[C.$type]},Disjunction:{name:ke.$type,properties:{left:{name:ke.left},right:{name:ke.right}},superTypes:[O.$type]},EndOfFile:{name:Ae.$type,properties:{cardinality:{name:Ae.cardinality,optional:!0}},superTypes:[C.$type]},Grammar:{name:A.$type,properties:{imports:{name:A.imports,defaultValue:[]},interfaces:{name:A.interfaces,defaultValue:[]},isDeclared:{name:A.isDeclared,defaultValue:!1},name:{name:A.name,optional:!0},rules:{name:A.rules,defaultValue:[]},types:{name:A.types,defaultValue:[]}},superTypes:[]},GrammarImport:{name:je.$type,properties:{path:{name:je.path}},superTypes:[]},Group:{name:j.$type,properties:{cardinality:{name:j.cardinality,optional:!0},elements:{name:j.elements,defaultValue:[]},guardCondition:{name:j.guardCondition,optional:!0},predicate:{name:j.predicate,optional:!0}},superTypes:[C.$type]},InferredType:{name:Me.$type,properties:{name:{name:Me.name}},superTypes:[w.$type]},InfixRule:{name:M.$type,properties:{call:{name:M.call},dataType:{name:M.dataType,optional:!0},inferredType:{name:M.inferredType,optional:!0},name:{name:M.name},operators:{name:M.operators},parameters:{name:M.parameters,defaultValue:[]},returnType:{name:M.returnType,referenceType:w.$type,optional:!0}},superTypes:[Se.$type]},InfixRuleOperatorList:{name:Ne.$type,properties:{associativity:{name:Ne.associativity,optional:!0},operators:{name:Ne.operators,defaultValue:[]}},superTypes:[]},InfixRuleOperators:{name:Pe.$type,properties:{precedences:{name:Pe.precedences,defaultValue:[]}},superTypes:[]},Interface:{name:Fe.$type,properties:{attributes:{name:Fe.attributes,defaultValue:[]},name:{name:Fe.name},superTypes:{name:Fe.superTypes,defaultValue:[],referenceType:w.$type}},superTypes:[w.$type]},Keyword:{name:Ie.$type,properties:{cardinality:{name:Ie.cardinality,optional:!0},predicate:{name:Ie.predicate,optional:!0},value:{name:Ie.value}},superTypes:[C.$type]},NamedArgument:{name:Le.$type,properties:{calledByName:{name:Le.calledByName,defaultValue:!1},parameter:{name:Le.parameter,referenceType:Be.$type,optional:!0},value:{name:Le.value}},superTypes:[]},NegatedToken:{name:N.$type,properties:{cardinality:{name:N.cardinality,optional:!0},lookahead:{name:N.lookahead,optional:!0},parenthesized:{name:N.parenthesized,defaultValue:!1,optional:!0},terminal:{name:N.terminal}},superTypes:[R.$type]},Negation:{name:Re.$type,properties:{value:{name:Re.value}},superTypes:[O.$type]},NumberLiteral:{name:ze.$type,properties:{value:{name:ze.value}},superTypes:[Ze.$type]},Parameter:{name:Be.$type,properties:{name:{name:Be.name}},superTypes:[]},ParameterReference:{name:Ve.$type,properties:{parameter:{name:Ve.parameter,referenceType:Be.$type}},superTypes:[O.$type]},ParserRule:{name:P.$type,properties:{dataType:{name:P.dataType,optional:!0},definition:{name:P.definition},entry:{name:P.entry,defaultValue:!1},fragment:{name:P.fragment,defaultValue:!1},inferredType:{name:P.inferredType,optional:!0},name:{name:P.name},parameters:{name:P.parameters,defaultValue:[]},returnType:{name:P.returnType,referenceType:w.$type,optional:!0}},superTypes:[Se.$type]},ReferenceType:{name:He.$type,properties:{isMulti:{name:He.isMulti,defaultValue:!1},referenceType:{name:He.referenceType}},superTypes:[Je.$type]},RegexToken:{name:F.$type,properties:{cardinality:{name:F.cardinality,optional:!0},lookahead:{name:F.lookahead,optional:!0},parenthesized:{name:F.parenthesized,defaultValue:!1,optional:!0},regex:{name:F.regex}},superTypes:[R.$type]},ReturnType:{name:Ue.$type,properties:{name:{name:Ue.name}},superTypes:[]},RuleCall:{name:I.$type,properties:{arguments:{name:I.arguments,defaultValue:[]},cardinality:{name:I.cardinality,optional:!0},predicate:{name:I.predicate,optional:!0},rule:{name:I.rule,referenceType:Ce.$type}},superTypes:[C.$type]},SimpleType:{name:We.$type,properties:{primitiveType:{name:We.primitiveType,optional:!0},stringType:{name:We.stringType,optional:!0},typeRef:{name:We.typeRef,referenceType:w.$type,optional:!0}},superTypes:[Je.$type]},StringLiteral:{name:Ge.$type,properties:{value:{name:Ge.value}},superTypes:[Ze.$type]},TerminalAlternatives:{name:L.$type,properties:{cardinality:{name:L.cardinality,optional:!0},elements:{name:L.elements,defaultValue:[]},lookahead:{name:L.lookahead,optional:!0},parenthesized:{name:L.parenthesized,defaultValue:!1,optional:!0}},superTypes:[R.$type]},TerminalElement:{name:R.$type,properties:{cardinality:{name:R.cardinality,optional:!0},lookahead:{name:R.lookahead,optional:!0},parenthesized:{name:R.parenthesized,defaultValue:!1,optional:!0}},superTypes:[C.$type]},TerminalGroup:{name:z.$type,properties:{cardinality:{name:z.cardinality,optional:!0},elements:{name:z.elements,defaultValue:[]},lookahead:{name:z.lookahead,optional:!0},parenthesized:{name:z.parenthesized,defaultValue:!1,optional:!0}},superTypes:[R.$type]},TerminalRule:{name:B.$type,properties:{definition:{name:B.definition},fragment:{name:B.fragment,defaultValue:!1},hidden:{name:B.hidden,defaultValue:!1},name:{name:B.name},type:{name:B.type,optional:!0}},superTypes:[Ce.$type]},TerminalRuleCall:{name:V.$type,properties:{cardinality:{name:V.cardinality,optional:!0},lookahead:{name:V.lookahead,optional:!0},parenthesized:{name:V.parenthesized,defaultValue:!1,optional:!0},rule:{name:V.rule,referenceType:B.$type}},superTypes:[R.$type]},Type:{name:Ke.$type,properties:{name:{name:Ke.name},type:{name:Ke.type}},superTypes:[w.$type]},TypeAttribute:{name:qe.$type,properties:{defaultValue:{name:qe.defaultValue,optional:!0},isOptional:{name:qe.isOptional,defaultValue:!1},name:{name:qe.name},type:{name:qe.type}},superTypes:[]},TypeDefinition:{name:Je.$type,properties:{},superTypes:[]},UnionType:{name:Ye.$type,properties:{types:{name:Ye.types,defaultValue:[]}},superTypes:[Je.$type]},UnorderedGroup:{name:Xe.$type,properties:{cardinality:{name:Xe.cardinality,optional:!0},elements:{name:Xe.elements,defaultValue:[]}},superTypes:[C.$type]},UntilToken:{name:H.$type,properties:{cardinality:{name:H.cardinality,optional:!0},lookahead:{name:H.lookahead,optional:!0},parenthesized:{name:H.parenthesized,defaultValue:!1,optional:!0},terminal:{name:H.terminal}},superTypes:[R.$type]},ValueLiteral:{name:Ze.$type,properties:{},superTypes:[]},Wildcard:{name:Qe.$type,properties:{cardinality:{name:Qe.cardinality,optional:!0},lookahead:{name:Qe.lookahead,optional:!0},parenthesized:{name:Qe.parenthesized,defaultValue:!1,optional:!0}},superTypes:[R.$type]}}}};const U=new LangiumGrammarAstReflection;var W=class StreamImpl{constructor(e,t){this.startFn=e,this.nextFn=t}iterator(){let e={state:this.startFn(),next:()=>this.nextFn(e.state),[Symbol.iterator]:()=>e};return e}[Symbol.iterator](){return this.iterator()}isEmpty(){return!!this.iterator().next().done}count(){let e=this.iterator(),t=0,n=e.next();for(;!n.done;)t++,n=e.next();return t}toArray(){let e=[],t=this.iterator(),n;do n=t.next(),n.value!==void 0&&e.push(n.value);while(!n.done);return e}toSet(){return new Set(this)}toMap(e,t){let n=this.map(n=>[e?e(n):n,t?t(n):n]);return new Map(n)}toString(){return this.join()}concat(e){return new StreamImpl(()=>({first:this.startFn(),firstDone:!1,iterator:e[Symbol.iterator]()}),e=>{let t;if(!e.firstDone){do if(t=this.nextFn(e.first),!t.done)return t;while(!t.done);e.firstDone=!0}do if(t=e.iterator.next(),!t.done)return t;while(!t.done);return K})}join(e=`,`){let t=this.iterator(),n=``,r,i=!1;do r=t.next(),r.done||(i&&(n+=e),n+=toString$1(r.value)),i=!0;while(!r.done);return n}indexOf(e,t=0){let n=this.iterator(),r=0,i=n.next();for(;!i.done;){if(r>=t&&i.value===e)return r;i=n.next(),r++}return-1}every(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(!e(n.value))return!1;n=t.next()}return!0}some(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return!0;n=t.next()}return!1}forEach(e){let t=this.iterator(),n=0,r=t.next();for(;!r.done;)e(r.value,n),r=t.next(),n++}map(e){return new StreamImpl(this.startFn,t=>{let{done:n,value:r}=this.nextFn(t);return n?K:{done:!1,value:e(r)}})}filter(e){return new StreamImpl(this.startFn,t=>{let n;do if(n=this.nextFn(t),!n.done&&e(n.value))return n;while(!n.done);return K})}nonNullable(){return this.filter(e=>e!=null)}reduce(e,t){let n=this.iterator(),r=t,i=n.next();for(;!i.done;)r=r===void 0?i.value:e(r,i.value),i=n.next();return r}reduceRight(e,t){return this.recursiveReduce(this.iterator(),e,t)}recursiveReduce(e,t,n){let r=e.next();if(r.done)return n;let i=this.recursiveReduce(e,t,n);return i===void 0?r.value:t(i,r.value)}find(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return n.value;n=t.next()}}findIndex(e){let t=this.iterator(),n=0,r=t.next();for(;!r.done;){if(e(r.value))return n;r=t.next(),n++}return-1}includes(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(n.value===e)return!0;n=t.next()}return!1}flatMap(e){return new StreamImpl(()=>({this:this.startFn()}),t=>{do{if(t.iterator){let e=t.iterator.next();if(e.done)t.iterator=void 0;else return e}let{done:n,value:r}=this.nextFn(t.this);if(!n){let n=e(r);if(isIterable(n))t.iterator=n[Symbol.iterator]();else return{done:!1,value:n}}}while(t.iterator);return K})}flat(e){if(e===void 0&&(e=1),e<=0)return this;let t=e>1?this.flat(e-1):this;return new StreamImpl(()=>({this:t.startFn()}),e=>{do{if(e.iterator){let t=e.iterator.next();if(t.done)e.iterator=void 0;else return t}let{done:n,value:r}=t.nextFn(e.this);if(!n){if(isIterable(r))e.iterator=r[Symbol.iterator]();else return{done:!1,value:r}}}while(e.iterator);return K})}head(){let e=this.iterator().next();if(!e.done)return e.value}tail(e=1){return new StreamImpl(()=>{let t=this.startFn();for(let n=0;n<e;n++)if(this.nextFn(t).done)return t;return t},this.nextFn)}limit(e){return new StreamImpl(()=>({size:0,state:this.startFn()}),t=>(t.size++,t.size>e?K:this.nextFn(t.state)))}distinct(e){return new StreamImpl(()=>({set:/* @__PURE__ */ new Set,internalState:this.startFn()}),t=>{let n;do if(n=this.nextFn(t.internalState),!n.done){let r=e?e(n.value):n.value;if(!t.set.has(r))return t.set.add(r),n}while(!n.done);return K})}exclude(e,t){let n=/* @__PURE__ */ new Set;for(let r of e){let e=t?t(r):r;n.add(e)}return this.filter(e=>{let r=t?t(e):e;return!n.has(r)})}};function toString$1(e){return typeof e==`string`?e:e===void 0?`undefined`:typeof e.toString==`function`?e.toString():Object.prototype.toString.call(e)}e(toString$1,`toString`);function isIterable(e){return!!e&&typeof e[Symbol.iterator]==`function`}const G=new W(()=>void 0,()=>K),K=Object.freeze({done:!0,value:void 0});function stream(...e){if(e.length===1){let t=e[0];if(t instanceof W)return t;if(isIterable(t))return new W(()=>t[Symbol.iterator](),e=>e.next());if(typeof t.length==`number`)return new W(()=>({index:0}),e=>e.index<t.length?{done:!1,value:t[e.index++]}:K)}return e.length>1?new W(()=>({collIndex:0,arrIndex:0}),t=>{do{if(t.iterator){let e=t.iterator.next();if(!e.done)return e;t.iterator=void 0}if(t.array){if(t.arrIndex<t.array.length)return{done:!1,value:t.array[t.arrIndex++]};t.array=void 0,t.arrIndex=0}if(t.collIndex<e.length){let n=e[t.collIndex++];isIterable(n)?t.iterator=n[Symbol.iterator]():n&&typeof n.length==`number`&&(t.array=n)}}while(t.iterator||t.array||t.collIndex<e.length);return K}):G}var TreeStreamImpl=class extends W{constructor(e,t,n){super(()=>({iterators:n?.includeRoot?[[e][Symbol.iterator]()]:[t(e)[Symbol.iterator]()],pruned:!1}),e=>{for(e.pruned&&=(e.iterators.pop(),!1);e.iterators.length>0;){let n=e.iterators[e.iterators.length-1].next();if(n.done)e.iterators.pop();else return e.iterators.push(t(n.value)[Symbol.iterator]()),n}return K})}iterator(){let e={state:this.startFn(),next:()=>this.nextFn(e.state),prune:()=>{e.state.pruned=!0},[Symbol.iterator]:()=>e};return e}},$e;(function(e){function sum(e){return e.reduce((e,t)=>e+t,0)}e.sum=sum;function product(e){return e.reduce((e,t)=>e*t,0)}e.product=product;function min(e){return e.reduce((e,t)=>Math.min(e,t))}e.min=min;function max(e){return e.reduce((e,t)=>Math.max(e,t))}e.max=max})($e||={});var et=/* @__PURE__ */ t({DefaultNameRegexp:()=>tt,RangeComparison:()=>q,compareRange:()=>compareRange,findCommentNode:()=>findCommentNode,findDeclarationNodeAtOffset:()=>findDeclarationNodeAtOffset,findLeafNodeAtOffset:()=>findLeafNodeAtOffset,findLeafNodeBeforeOffset:()=>findLeafNodeBeforeOffset,flattenCst:()=>flattenCst,getDatatypeNode:()=>getDatatypeNode,getInteriorNodes:()=>getInteriorNodes,getNextNode:()=>getNextNode,getPreviousNode:()=>getPreviousNode,getStartlineNode:()=>getStartlineNode,inRange:()=>inRange,isChildNode:()=>isChildNode,isCommentNode:()=>isCommentNode,isValidTokenRange:()=>isValidTokenRange,streamCst:()=>streamCst,toDocumentSegment:()=>toDocumentSegment,tokenToRange:()=>tokenToRange});function getDatatypeNode(e){let t=e,n=!1;for(;t;){let e=getContainerOfType(t.grammarSource,isParserRule);if(e&&e.dataType)t=t.container,n=!0;else if(n)return t;else return}}function streamCst(e){return new TreeStreamImpl(e,e=>isCompositeCstNode(e)?e.content:[],{includeRoot:!0})}function flattenCst(e){return streamCst(e).filter(isLeafCstNode)}function isChildNode(e,t){for(;e.container;)if(e=e.container,e===t)return!0;return!1}function tokenToRange(e){return{start:{line:e.startLine-1,character:e.startColumn-1},end:{line:e.endLine-1,character:e.endColumn}}}function isValidTokenRange(e){let{startOffset:t,endOffset:n}=e;return typeof t==`number`&&Number.isFinite(t)&&t>=0&&typeof n==`number`&&Number.isFinite(n)&&n>=t}function toDocumentSegment(e){if(!e)return;let{offset:t,end:n,range:r}=e;return{range:r,offset:t,end:n,length:n-t}}var q;(function(e){e[e.Before=0]=`Before`,e[e.After=1]=`After`,e[e.OverlapFront=2]=`OverlapFront`,e[e.OverlapBack=3]=`OverlapBack`,e[e.Inside=4]=`Inside`,e[e.Outside=5]=`Outside`})(q||={});function compareRange(e,t){if(e.end.line<t.start.line||e.end.line===t.start.line&&e.end.character<=t.start.character)return q.Before;if(e.start.line>t.end.line||e.start.line===t.end.line&&e.start.character>=t.end.character)return q.After;let n=e.start.line>t.start.line||e.start.line===t.start.line&&e.start.character>=t.start.character,r=e.end.line<t.end.line||e.end.line===t.end.line&&e.end.character<=t.end.character;return n&&r?q.Inside:n?q.OverlapBack:r?q.OverlapFront:q.Outside}function inRange(e,t){return compareRange(e,t)>q.After}const tt=/^[\w\p{L}]$/u;function findDeclarationNodeAtOffset(e,t,n=tt){if(e){if(t>0){let r=t>=e.offset&&t<e.end?e.root.fullText.charAt(t):``;n.test(r)||t--}return findLeafNodeAtOffset(e,t)}}function findCommentNode(e,t){if(e){let n=getPreviousNode(e,!0);if(n&&isCommentNode(n,t))return n;if(isRootCstNode(e)){let n=e.content.findIndex(e=>!e.hidden);for(let r=n-1;r>=0;r--){let n=e.content[r];if(isCommentNode(n,t))return n}}}}function isCommentNode(e,t){return isLeafCstNode(e)&&t.includes(e.tokenType.name)}function findLeafNodeAtOffset(e,t){if(isLeafCstNode(e))return e;if(isCompositeCstNode(e)){let n=binarySearch(e,t,!1);if(n)return findLeafNodeAtOffset(n,t)}}function findLeafNodeBeforeOffset(e,t){if(isLeafCstNode(e))return e;if(isCompositeCstNode(e)){let n=binarySearch(e,t,!0);if(n)return findLeafNodeBeforeOffset(n,t)}}function binarySearch(e,t,n){let r=0,i=e.content.length-1,a;for(;r<=i;){let o=Math.floor((r+i)/2),s=e.content[o];if(s.offset<=t&&s.end>t)return s;s.end<=t?(a=n?s:void 0,r=o+1):i=o-1}return a}function getPreviousNode(e,t=!0){for(;e.container;){let n=e.container,r=n.content.indexOf(e);for(;r>0;){r--;let e=n.content[r];if(t||!e.hidden)return e}e=n}}function getNextNode(e,t=!0){for(;e.container;){let n=e.container,r=n.content.indexOf(e),i=n.content.length-1;for(;r<i;){r++;let e=n.content[r];if(t||!e.hidden)return e}e=n}}function getStartlineNode(e){if(e.range.start.character===0)return e;let t=e.range.start.line,n=e,r;for(;e.container;){let i=e.container,a=r??i.content.indexOf(e);if(a===0?(e=i,r=void 0):(r=a-1,e=i.content[r]),e.range.start.line!==t)break;n=e}return n}function getInteriorNodes(e,t){let n=getCommonParent(e,t);return n?n.parent.content.slice(n.a+1,n.b):[]}function getCommonParent(e,t){let n=getParentChain(e),r=getParentChain(t),i;for(let e=0;e<n.length&&e<r.length;e++){let t=n[e],a=r[e];if(t.parent===a.parent)i={parent:t.parent,a:t.index,b:a.index};else break}return i}function getParentChain(e){let t=[];for(;e.container;){let n=e.container,r=n.content.indexOf(e);t.push({parent:n,index:r}),e=n}return t.reverse()}var nt=/* @__PURE__ */ t({assignMandatoryProperties:()=>assignMandatoryProperties,copyAstNode:()=>copyAstNode,findRootNode:()=>findRootNode,getContainerOfType:()=>getContainerOfType,getDocument:()=>getDocument,getReferenceNodes:()=>getReferenceNodes,hasContainerOfType:()=>hasContainerOfType,linkContentToContainer:()=>linkContentToContainer,streamAllContents:()=>streamAllContents,streamAst:()=>streamAst,streamContents:()=>streamContents,streamReferences:()=>streamReferences});function linkContentToContainer(e,t={}){for(let[n,r]of Object.entries(e))n.startsWith(`$`)||(Array.isArray(r)?r.forEach((r,i)=>{isAstNode(r)&&(r.$container=e,r.$containerProperty=n,r.$containerIndex=i,t.deep&&linkContentToContainer(r,t))}):isAstNode(r)&&(r.$container=e,r.$containerProperty=n,t.deep&&linkContentToContainer(r,t)))}function getContainerOfType(e,t){let n=e;for(;n;){if(t(n))return n;n=n.$container}}function hasContainerOfType(e,t){let n=e;for(;n;){if(t(n))return!0;n=n.$container}return!1}function getDocument(e){let t=findRootNode(e).$document;if(!t)throw Error(`AST node has no document.`);return t}function findRootNode(e){for(;e.$container;)e=e.$container;return e}function getReferenceNodes(e){return isReference(e)?e.ref?[e.ref]:[]:isMultiReference(e)?e.items.map(e=>e.ref):[]}function streamContents(e,t){if(!e)throw Error(`Node must be an AstNode.`);let n=t?.range;return new W(()=>({keys:Object.keys(e),keyIndex:0,arrayIndex:0}),t=>{for(;t.keyIndex<t.keys.length;){let r=t.keys[t.keyIndex];if(!r.startsWith(`$`)){let i=e[r];if(isAstNode(i)){if(t.keyIndex++,isAstNodeInRange(i,n))return{done:!1,value:i}}else if(Array.isArray(i)){for(;t.arrayIndex<i.length;){let e=i[t.arrayIndex++];if(isAstNode(e)&&isAstNodeInRange(e,n))return{done:!1,value:e}}t.arrayIndex=0}}t.keyIndex++}return K})}function streamAllContents(e,t){if(!e)throw Error(`Root node must be an AstNode.`);return new TreeStreamImpl(e,e=>streamContents(e,t))}function streamAst(e,t){if(!e)throw Error(`Root node must be an AstNode.`);return t?.range&&!isAstNodeInRange(e,t.range)?new TreeStreamImpl(e,()=>[]):new TreeStreamImpl(e,e=>streamContents(e,t),{includeRoot:!0})}function isAstNodeInRange(e,t){if(!t)return!0;let n=e.$cstNode?.range;return n?inRange(n,t):!1}function streamReferences(e){return new W(()=>({keys:Object.keys(e),keyIndex:0,arrayIndex:0}),t=>{for(;t.keyIndex<t.keys.length;){let n=t.keys[t.keyIndex];if(!n.startsWith(`$`)){let r=e[n];if(isReference(r)||isMultiReference(r))return t.keyIndex++,{done:!1,value:{reference:r,container:e,property:n}};if(Array.isArray(r)){for(;t.arrayIndex<r.length;){let i=t.arrayIndex++,a=r[i];if(isReference(a)||isMultiReference(a))return{done:!1,value:{reference:a,container:e,property:n,index:i}}}t.arrayIndex=0}}t.keyIndex++}return K})}function assignMandatoryProperties(e,t){let n=e.getTypeMetaData(t.$type),r=t;for(let e of Object.values(n.properties))e.defaultValue!==void 0&&r[e.name]===void 0&&(r[e.name]=copyDefaultValue(e.defaultValue))}function copyDefaultValue(e){return Array.isArray(e)?[...e.map(copyDefaultValue)]:e}function copyAstNode(e,t,n){let r={$type:e.$type};n&&(n.set(e,r),n.set(r,e));for(let[i,a]of Object.entries(e))if(!i.startsWith(`$`)){if(isAstNode(a))r[i]=copyAstNode(a,t,n);else if(isReference(a))r[i]=t(r,i,a.$refNode,a.$refText,a);else if(Array.isArray(a)){let e=[];for(let o of a)isAstNode(o)?e.push(copyAstNode(o,t,n)):isReference(o)?e.push(t(r,i,o.$refNode,o.$refText,o)):e.push(o);r[i]=e}else r[i]=a}return linkContentToContainer(r,{deep:!0}),r}var ErrorWithLocation=class extends Error{constructor(e,t){let n=typeof t==`string`?t:t();super(e?`${n} at ${e.range.start.line}:${e.range.start.character}`:n)}};function assertUnreachable(e,t=`Error: Got unexpected value.`){throw Error(typeof t==`string`?t:t())}const rt=/\r?\n/gm,it=new n;var TerminalRegExpVisitor=class extends r{constructor(){super(...arguments),this.isStarting=!0,this.endRegexpStack=[],this.multiline=!1}get endRegex(){return this.endRegexpStack.join(``)}reset(e){this.multiline=!1,this.regex=e,this.startRegexp=``,this.isStarting=!0,this.endRegexpStack=[]}visitGroup(e){e.quantifier&&(this.isStarting=!1,this.endRegexpStack=[])}visitCharacter(e){let t=String.fromCharCode(e.value);if(!this.multiline&&t===`
2
+ `&&(this.multiline=!0),e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let e=escapeRegExp(t);this.endRegexpStack.push(e),this.isStarting&&(this.startRegexp+=e)}}visitSet(e){if(!this.multiline){let t=this.regex.substring(e.loc.begin,e.loc.end),n=new RegExp(t);this.multiline=!!`
3
+ `.match(n)}if(e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let t=this.regex.substring(e.loc.begin,e.loc.end);this.endRegexpStack.push(t),this.isStarting&&(this.startRegexp+=t)}}visitChildren(e){e.type===`Group`&&e.quantifier||super.visitChildren(e)}};const at=new TerminalRegExpVisitor;function isMultilineComment(e){try{return typeof e==`string`&&(e=new RegExp(e)),e=e.toString(),at.reset(e),at.visit(it.pattern(e)),at.multiline}catch{return!1}}const ot=`\f
4
+ \r \v \xA0            \u2028\u2029   `.split(``);function isWhitespace(e){let t=typeof e==`string`?new RegExp(e):e;return ot.some(e=>t.test(e))}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function partialMatches(e,t){let n=partialRegExp(e),r=t.match(n);return!!r&&r[0].length>0}function partialRegExp(e){typeof e==`string`&&(e=new RegExp(e));let t=e,n=e.source,r=0;function process(){let e=``,i;function appendRaw(t){e+=n.substr(r,t),r+=t}function appendOptional(t){e+=`(?:`+n.substr(r,t)+`|$)`,r+=t}for(;r<n.length;)switch(n[r]){case`\\`:switch(n[r+1]){case`c`:appendOptional(3);break;case`x`:appendOptional(4);break;case`u`:t.unicode?n[r+2]===`{`?appendOptional(n.indexOf(`}`,r)-r+1):appendOptional(6):appendOptional(2);break;case`p`:case`P`:t.unicode?appendOptional(n.indexOf(`}`,r)-r+1):appendOptional(2);break;case`k`:appendOptional(n.indexOf(`>`,r)-r+1);break;default:appendOptional(2)}break;case`[`:i=/\[(?:\\.|.)*?\]/g,i.lastIndex=r,i=i.exec(n)||[],appendOptional(i[0].length);break;case`|`:case`^`:case`$`:case`*`:case`+`:case`?`:appendRaw(1);break;case`{`:i=/\{\d+,?\d*\}/g,i.lastIndex=r,i=i.exec(n),i?appendRaw(i[0].length):appendOptional(1);break;case`(`:if(n[r+1]===`?`)switch(n[r+2]){case`:`:e+=`(?:`,r+=3,e+=process()+`|$)`;break;case`=`:e+=`(?=`,r+=3,e+=process()+`)`;break;case`!`:i=r,r+=3,process(),e+=n.substr(i,r-i);break;case`<`:switch(n[r+3]){case`=`:case`!`:i=r,r+=4,process(),e+=n.substr(i,r-i);break;default:appendRaw(n.indexOf(`>`,r)-r+1),e+=process()+`|$)`}}else appendRaw(1),e+=process()+`|$)`;break;case`)`:return++r,e;default:appendOptional(1)}return e}return new RegExp(process(),e.flags)}var st=/* @__PURE__ */ t({findAssignment:()=>findAssignment,findNameAssignment:()=>findNameAssignment,findNodeForKeyword:()=>findNodeForKeyword,findNodeForProperty:()=>findNodeForProperty,findNodesForKeyword:()=>findNodesForKeyword,findNodesForKeywordInternal:()=>findNodesForKeywordInternal,findNodesForProperty:()=>findNodesForProperty,getActionAtElement:()=>getActionAtElement,getActionType:()=>getActionType,getAllReachableRules:()=>getAllReachableRules,getAllRulesUsedForCrossReferences:()=>getAllRulesUsedForCrossReferences,getCrossReferenceTerminal:()=>getCrossReferenceTerminal,getEntryRule:()=>getEntryRule,getExplicitRuleType:()=>getExplicitRuleType,getHiddenRules:()=>getHiddenRules,getRuleType:()=>getRuleType,getRuleTypeName:()=>getRuleTypeName,getTypeName:()=>getTypeName,isArrayCardinality:()=>isArrayCardinality,isArrayOperator:()=>isArrayOperator,isCommentTerminal:()=>isCommentTerminal,isDataType:()=>isDataType,isDataTypeRule:()=>isDataTypeRule,isOptionalCardinality:()=>isOptionalCardinality,terminalRegex:()=>terminalRegex});function getEntryRule(e){return e.rules.find(e=>isParserRule(e)&&e.entry)}function getHiddenRules(e){return e.rules.filter(e=>isTerminalRule(e)&&e.hidden)}function getAllReachableRules(e,t){let n=/* @__PURE__ */ new Set,r=getEntryRule(e);if(!r)return new Set(e.rules);let i=[r].concat(getHiddenRules(e));for(let e of i)ruleDfs(e,n,t);let a=/* @__PURE__ */ new Set;for(let t of e.rules)(n.has(t.name)||isTerminalRule(t)&&t.hidden)&&a.add(t);return a}function ruleDfs(e,t,n){t.add(e.name),streamAllContents(e).forEach(e=>{if(isRuleCall(e)||n&&isTerminalRuleCall(e)){let r=e.rule.ref;r&&!t.has(r.name)&&ruleDfs(r,t,n)}})}function getAllRulesUsedForCrossReferences(e){let t=/* @__PURE__ */ new Set;return streamAllContents(e).forEach(e=>{isCrossReference(e)&&(isParserRule(e.type.ref)&&t.add(e.type.ref),isInferredType(e.type.ref)&&isParserRule(e.type.ref.$container)&&t.add(e.type.ref.$container))}),t}function getCrossReferenceTerminal(e){if(e.terminal)return e.terminal;if(e.type.ref)return findNameAssignment(e.type.ref)?.terminal}function isCommentTerminal(e){return e.hidden&&!isWhitespace(terminalRegex(e))}function findNodesForProperty(e,t){return!e||!t?[]:findNodesForPropertyInternal(e,t,e.astNode,!0)}function findNodeForProperty(e,t,n){if(!e||!t)return;let r=findNodesForPropertyInternal(e,t,e.astNode,!0);if(r.length!==0)return n=n===void 0?0:Math.max(0,Math.min(n,r.length-1)),r[n]}function findNodesForPropertyInternal(e,t,n,r){if(!r){let n=getContainerOfType(e.grammarSource,isAssignment);if(n&&n.feature===t)return[e]}return isCompositeCstNode(e)&&e.astNode===n?e.content.flatMap(e=>findNodesForPropertyInternal(e,t,n,!1)):[]}function findNodesForKeyword(e,t){return e?findNodesForKeywordInternal(e,t,e?.astNode):[]}function findNodeForKeyword(e,t,n){if(!e)return;let r=findNodesForKeywordInternal(e,t,e?.astNode);if(r.length!==0)return n=n===void 0?0:Math.max(0,Math.min(n,r.length-1)),r[n]}function findNodesForKeywordInternal(e,t,n){if(e.astNode!==n)return[];if(isKeyword(e.grammarSource)&&e.grammarSource.value===t)return[e];let r=streamCst(e).iterator(),i,a=[];do if(i=r.next(),!i.done){let e=i.value;e.astNode===n?isKeyword(e.grammarSource)&&e.grammarSource.value===t&&a.push(e):r.prune()}while(!i.done);return a}function findAssignment(e){let t=e.astNode;for(;t===e.container?.astNode;){let t=getContainerOfType(e.grammarSource,isAssignment);if(t)return t;e=e.container}}function findNameAssignment(e){let t=e;return isInferredType(t)&&(isAction(t.$container)?t=t.$container.$container:isAbstractParserRule(t.$container)?t=t.$container:assertUnreachable(t.$container)),findNameAssignmentInternal(e,t,/* @__PURE__ */ new Map)}function findNameAssignmentInternal(e,t,n){function go(t,r){let i;return getContainerOfType(t,isAssignment)||(i=findNameAssignmentInternal(r,r,n)),n.set(e,i),i}if(n.has(e))return n.get(e);n.set(e,void 0);for(let r of streamAllContents(t))if(isAssignment(r)&&r.feature.toLowerCase()===`name`)return n.set(e,r),r;else if(isRuleCall(r)&&isParserRule(r.rule.ref))return go(r,r.rule.ref);else if(isSimpleType(r)&&r.typeRef?.ref)return go(r,r.typeRef.ref)}function getActionAtElement(e){let t=e.$container;if(isGroup(t)){let n=t.elements,r=n.indexOf(e);for(let e=r-1;e>=0;e--){let t=n[e];if(isAction(t))return t;{let t=streamAllContents(n[e]).find(isAction);if(t)return t}}}if(isAbstractElement(t))return getActionAtElement(t)}function isOptionalCardinality(e,t){return e===`?`||e===`*`||isGroup(t)&&!!t.guardCondition}function isArrayCardinality(e){return e===`*`||e===`+`}function isArrayOperator(e){return e===`+=`}function isDataTypeRule(e){return isDataTypeRuleInternal(e,/* @__PURE__ */ new Set)}function isDataTypeRuleInternal(e,t){if(t.has(e))return!0;t.add(e);for(let n of streamAllContents(e))if(isRuleCall(n)){if(!n.rule.ref||isParserRule(n.rule.ref)&&!isDataTypeRuleInternal(n.rule.ref,t)||isInfixRule(n.rule.ref))return!1}else if(isAssignment(n))return!1;else if(isAction(n))return!1;return!!e.definition}function isDataType(e){return isDataTypeInternal(e.type,/* @__PURE__ */ new Set)}function isDataTypeInternal(e,t){if(t.has(e))return!0;if(t.add(e),isArrayType(e)||isReferenceType(e))return!1;if(isUnionType(e))return e.types.every(e=>isDataTypeInternal(e,t));if(isSimpleType(e)){if(e.primitiveType!==void 0||e.stringType!==void 0)return!0;if(e.typeRef!==void 0){let n=e.typeRef.ref;return isType(n)?isDataTypeInternal(n.type,t):!1}return!1}return!1}function getExplicitRuleType(e){if(!isTerminalRule(e)){if(e.inferredType)return e.inferredType.name;if(e.dataType)return e.dataType;if(e.returnType){let t=e.returnType.ref;if(t)return t.name}}}function getTypeName(e){if(isAbstractParserRule(e))return isParserRule(e)&&isDataTypeRule(e)?e.name:getExplicitRuleType(e)??e.name;if(isInterface(e)||isType(e)||isReturnType(e))return e.name;if(isAction(e)){let t=getActionType(e);if(t)return t}else if(isInferredType(e))return e.name;throw Error(`Cannot get name of Unknown Type`)}function getActionType(e){if(e.inferredType)return e.inferredType.name;if(e.type?.ref)return getTypeName(e.type.ref)}function getRuleTypeName(e){return isTerminalRule(e)?e.type?.name??`string`:isParserRule(e)&&isDataTypeRule(e)?e.name:getExplicitRuleType(e)??e.name}function getRuleType(e){return isTerminalRule(e)?e.type?.name??`string`:getExplicitRuleType(e)??e.name}function terminalRegex(e){let t={s:!1,i:!1,u:!1},n=abstractElementToRegex(e.definition,t),r=Object.entries(t).filter(([,e])=>e).map(([e])=>e).join(``);return new RegExp(n,r)}const ct=`[\\s\\S]`;function abstractElementToRegex(e,t){if(isTerminalAlternatives(e))return terminalAlternativesToRegex(e);if(isTerminalGroup(e))return terminalGroupToRegex(e);if(isCharacterRange(e))return characterRangeToRegex(e);if(isTerminalRuleCall(e)){let t=e.rule.ref;if(!t)throw Error(`Missing rule reference.`);return withCardinality(abstractElementToRegex(t.definition),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}if(isNegatedToken(e))return negateTokenToRegex(e);if(isUntilToken(e))return untilTokenToRegex(e);if(isRegexToken(e)){let n=e.regex.lastIndexOf(`/`),r=e.regex.substring(1,n),i=e.regex.substring(n+1);return t&&(t.i=i.includes(`i`),t.s=i.includes(`s`),t.u=i.includes(`u`)),withCardinality(r,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}if(isWildcard(e))return withCardinality(ct,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized});throw Error(`Invalid terminal element: ${e?.$type}, ${e?.$cstNode?.text}`)}function terminalAlternativesToRegex(e){return withCardinality(e.elements.map(e=>abstractElementToRegex(e)).join(`|`),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}function terminalGroupToRegex(e){return withCardinality(e.elements.map(e=>abstractElementToRegex(e)).join(``),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}function untilTokenToRegex(e){return withCardinality(`${ct}*?${abstractElementToRegex(e.terminal)}`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}function negateTokenToRegex(e){return withCardinality(`(?!${abstractElementToRegex(e.terminal)})${ct}*?`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}function characterRangeToRegex(e){return e.right?withCardinality(`[${keywordToRegex(e.left)}-${keywordToRegex(e.right)}]`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1}):withCardinality(keywordToRegex(e.left),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}function keywordToRegex(e){return escapeRegExp(e.value)}function withCardinality(e,t){return(t.parenthesized||t.lookahead||t.wrap!==!1)&&(e=`(${t.lookahead??(t.parenthesized?``:`?:`)}${e})`),t.cardinality?`${e}${t.cardinality}`:e}function findNextFeatures(e,t){let n={stacks:e,tokens:t};return interpretTokens(n),n.stacks.flat().forEach(e=>{e.property=void 0}),findNextFeatureStacks(n.stacks).map(e=>e[e.length-1])}function findNextFeaturesInternal(e){let t=[];if(e.length===0)return t;let n=e[e.length-1],{group:r,child:i}=findGroupAndChild(n.feature);if(isArrayCardinality(i.cardinality)){let e=findFirstFeaturesInternal({feature:i,type:n.type,property:n.property});t.push(...e)}let a=-1;r&&(a=r.elements.indexOf(i));let o=e.slice(0,-1);if(r){let e=a+1,{stacks:i,end:s}=findNextFeaturesInGroup({feature:r,type:n.type},e);for(let e of i)t.push([...o,...e]);s&&(a=r.elements.length-1)}else{let e=getAbstractElementParent(i);e?t.push(...findNextFeaturesInternal([...o,{feature:e}])):t.push(...findNextFeaturesInternal(o))}return r&&a===r.elements.length-1&&t.push(...findNextFeaturesInternal([...o,{feature:r}])),t}function findFirstFeatures(e){return findFirstFeaturesInternal({feature:e})}function findFirstFeaturesInternal(e){let{feature:t,type:n}=e;if(isGroup(t))return findNextFeaturesInGroup(e,0).stacks;if(isAlternatives(t)||isUnorderedGroup(t))return t.elements.flatMap(t=>findFirstFeaturesInternal({feature:t,type:n,property:e.property}));if(isAssignment(t))return findFirstFeaturesInternal({feature:t.terminal,type:n,property:e.property??t.feature});if(isAction(t))return findNextFeaturesInternal([{feature:t,type:getTypeName(t),property:e.property??t.feature}]);if(isRuleCall(t)&&isParserRule(t.rule.ref)){let n=t.rule.ref,r=findFirstFeaturesInternal({feature:n.definition,type:n.fragment||n.dataType?void 0:getExplicitRuleType(n)??n.name,property:e.property});for(let t of r)t.unshift(e);return r}if(isRuleCall(t)&&isInfixRule(t.rule.ref)){let n=t.rule.ref,r=n.call.rule.ref;if(!isParserRule(r))return console.error(`Failed to resolve reference to `+n.call.rule.$refText),[];let i=findFirstFeaturesInternal({feature:r.definition,type:getExplicitRuleType(r)??r.name,property:`parts`});for(let t of i)t.unshift(e);return i}return[[e]]}function findNextFeaturesInGroup(e,t){let n=[],r;for(;t<e.feature.elements.length;){let i=e.feature.elements[t];r={feature:i,type:e.type};let a=findFirstFeaturesInternal(r);if(n.push(...a),isElementOptional(i,/* @__PURE__ */ new Map))t++;else break}return{stacks:n,end:t>=e.feature.elements.length}}function isElementOptional(e,t){let n=t.get(e);if(n!==void 0)return n;if(t.set(e,!1),isOptionalCardinality(e.cardinality,e))return t.set(e,!0),!0;if(isGroup(e)){for(let n of e.elements)if(!isElementOptional(n,t))return t.set(e,!1),!1;return t.set(e,!0),!0}if(isAlternatives(e)||isUnorderedGroup(e)){for(let n of e.elements)if(isElementOptional(n,t))return t.set(e,!0),!0;return t.set(e,!1),!1}if(isRuleCall(e)&&isParserRule(e.rule.ref)){let n=e.rule.ref,r=isElementOptional(n.definition,t);return t.set(e,r),r}return!1}function interpretTokens(e){for(let t of e.tokens)e.stacks=findNextFeatureStacks(e.stacks,t)}function findNextFeatureStacks(e,t){let n=[];for(let r of e)n.push(...interpretStackToken(r,t));return n}function interpretStackToken(e,t){return findNextFeaturesInternal(e).filter(e=>!t||featureMatches(e[e.length-1].feature,t))}function findGroupAndChild(e){let t,n=e;for(;n.$container;)if(isGroup(n.$container)){t=n.$container;break}else if(isAbstractElement(n.$container))n=n.$container;else break;return t?{group:t,child:n}:{group:void 0,child:getContainerOfType(e,isAssignment)??e}}function getAbstractElementParent(e){let t=e.$container,n=getContainerOfType(t,isAssignment);if(n)return getAbstractElementParent(n);if(t&&isAbstractElement(t))return t}function featureMatches(e,t){if(isKeyword(e))return e.value===t.tokenType.name;if(isRuleCall(e))return ruleMatches(e.rule.ref,t);if(isCrossReference(e)){let n=getCrossReferenceTerminal(e);if(n)return featureMatches(n,t)}return!1}function ruleMatches(e,t){return isParserRule(e)?findFirstFeatures(e.definition).some(e=>featureMatches(e[e.length-1].feature,t)):isTerminalRule(e)?terminalRegex(e).test(t.image):!1}function mergeCompletionProviderOptions(e){let t=Array.from(new Set(e.flatMap(e=>e?.triggerCharacters??[]))),n=Array.from(new Set(e.flatMap(e=>e?.allCommitCharacters??[])));return{triggerCharacters:t.length>0?t:void 0,allCommitCharacters:n.length>0?n:void 0}}var DefaultCompletionProvider=class{constructor(e){this.scopeProvider=e.references.ScopeProvider,this.grammar=e.Grammar,this.completionParser=e.parser.CompletionParser,this.nameProvider=e.references.NameProvider,this.lexer=e.parser.Lexer,this.nodeKindProvider=e.shared.lsp.NodeKindProvider,this.fuzzyMatcher=e.shared.lsp.FuzzyMatcher,this.grammarConfig=e.parser.GrammarConfig,this.astReflection=e.shared.AstReflection,this.documentationProvider=e.documentation.DocumentationProvider,e.shared.lsp.LanguageServer.onInitialize(e=>{this.initialize(e)})}initialize(e){this.clientCapabilities=e.capabilities.textDocument?.completion}async getCompletion(e,t,n){let r=[],i=this.buildContexts(e,t.position),acceptor=(e,t)=>{let n=this.fillCompletionItem(e,t);n&&r.push(n)},distinctionFunction=e=>isKeyword(e.feature)?e.feature.value:e.feature,a=[];for(let e of i)if(await Promise.all(stream(e.features).distinct(distinctionFunction).exclude(a).map(t=>this.completionFor(e,t,acceptor))),a.push(...e.features),!this.continueCompletion(r))break;return m.create(this.deduplicateItems(r),!0)}deduplicateItems(e){return stream(e).distinct(e=>`${e.kind}_${e.label}_${e.detail}`).toArray()}findFeaturesAt(e,t){let n=e.getText({start:se.create(0,0),end:e.positionAt(t)}),r=this.completionParser.parse(n),i=r.tokens;if(r.tokenIndex===0){let e=getEntryRule(this.grammar);return findNextFeatures([[this.buildSyntheticEntryRuleCall(e)]],i)}let a=[...i].splice(r.tokenIndex);return findNextFeatures([r.elementStack.map(e=>({feature:e}))],a)}buildSyntheticEntryRuleCall(e){let t={$type:`Group`,$container:void 0,elements:[]},n={feature:t},r={$type:`RuleCall`,$container:void 0,rule:{ref:e,$refText:e.name},arguments:[]},i={$type:`Group`,$container:void 0,elements:[t,r]};return t.$container=i,r.$container=i,n}*buildContexts(e,t){let n=e.parseResult.value.$cstNode;if(!n)return;let r=e.textDocument,i=r.getText(),a=r.offsetAt(t),o={document:e,textDocument:r,offset:a,position:t},s=this.findDataTypeRuleStart(n,a);if(s){let[e,t]=s,i=findLeafNodeBeforeOffset(n,e)?.astNode;yield{...o,node:i,tokenOffset:e,tokenEndOffset:t,features:this.findFeaturesAt(r,e)}}let{nextTokenStart:c,nextTokenEnd:l,previousTokenStart:u,previousTokenEnd:d}=this.backtrackToAnyToken(i,a),f=c;a<=c&&u!==void 0&&(f=u);let p=findLeafNodeBeforeOffset(n,f)?.astNode,m=!0;if(u!==void 0&&d!==void 0&&d===a&&(yield{...o,node:p,tokenOffset:u,tokenEndOffset:d,features:this.findFeaturesAt(r,u)},m=this.performNextTokenCompletion(e,i.substring(u,d),u,d),m&&(yield{...o,node:p,tokenOffset:d,tokenEndOffset:d,features:this.findFeaturesAt(r,d)})),p)m&&(yield{...o,node:p,tokenOffset:c,tokenEndOffset:l,features:this.findFeaturesAt(r,c)});else{let e=getEntryRule(this.grammar);if(!e)throw Error(`Missing entry parser rule`);yield{...o,tokenOffset:c,tokenEndOffset:l,features:findFirstFeatures(e.definition).map(e=>e[e.length-1])}}}performNextTokenCompletion(e,t,n,r){return/\P{L}$/u.test(t)}findDataTypeRuleStart(e,t){let n=findDeclarationNodeAtOffset(e,t,this.grammarConfig.nameRegexp);if(!n)return;let r=getDatatypeNode(n);if(r)return[r.offset,r.end]}continueCompletion(e){return e.length===0}backtrackToAnyToken(e,t){let n=this.lexer.tokenize(e).tokens;if(n.length===0)return{nextTokenStart:t,nextTokenEnd:t};let r;for(let e of n){if(e.startOffset>=t)return{nextTokenStart:t,nextTokenEnd:t,previousTokenStart:r?r.startOffset:void 0,previousTokenEnd:r?r.endOffset+1:void 0};if(e.endOffset>=t)return{nextTokenStart:e.startOffset,nextTokenEnd:e.endOffset+1,previousTokenStart:r?r.startOffset:void 0,previousTokenEnd:r?r.endOffset+1:void 0};r=e}return{nextTokenStart:t,nextTokenEnd:t,previousTokenStart:r?r.startOffset:void 0,previousTokenEnd:r?r.endOffset+1:void 0}}completionFor(e,t,n){if(isKeyword(t.feature))return this.completionForKeyword(e,t.feature,n);if(isCrossReference(t.feature)&&e.node)return this.completionForCrossReference(e,t,n)}completionForCrossReference(e,t,n){let r=getContainerOfType(t.feature,isAssignment),i=e.node;if(r&&i){t.type&&(i={$type:t.type,$container:i,$containerProperty:t.property},assignMandatoryProperties(this.astReflection,i));let a;a=t.feature.isMulti?{$refText:``,items:[]}:{$refText:``,ref:void 0};let o={reference:a,container:i,property:r.feature};try{for(let t of this.getReferenceCandidates(o,e))n(e,this.createReferenceCompletionItem(t,o,e))}catch(e){console.error(e)}}}getReferenceCandidates(e,t){return this.scopeProvider.getScope(e).getAllElements()}createReferenceCompletionItem(e,t,n){return{nodeDescription:e,kind:this.nodeKindProvider.getCompletionItemKind(e),documentation:this.getReferenceDocumentation(e),detail:e.type,sortText:`0`}}getReferenceDocumentation(e){if(!e.node)return;let t=this.documentationProvider.getDocumentation(e.node);if(t)return{kind:`markdown`,value:t}}completionForKeyword(e,t,n){this.filterKeyword(e,t)&&n(e,{label:t.value,kind:this.getKeywordCompletionItemKind(t),detail:`Keyword`,sortText:`1`})}getKeywordCompletionItemKind(e){return p.Keyword}filterKeyword(e,t){return/\p{L}/u.test(t.value)}fillCompletionItem(e,t){let n;if(typeof t.label==`string`)n=t.label;else if(`node`in t){let e=this.nameProvider.getName(t.node);if(!e)return;n=e}else if(`nodeDescription`in t)n=t.nodeDescription.name;else return;let r;r=typeof t.textEdit?.newText==`string`?t.textEdit.newText:typeof t.insertText==`string`?t.insertText:n;let i=t.textEdit??this.buildCompletionTextEdit(e,n,r);if(i)return{additionalTextEdits:t.additionalTextEdits,command:t.command,commitCharacters:t.commitCharacters,data:t.data,detail:t.detail,documentation:t.documentation,filterText:t.filterText,insertText:t.insertText,insertTextFormat:t.insertTextFormat,insertTextMode:t.insertTextMode,kind:t.kind,labelDetails:t.labelDetails,preselect:t.preselect,sortText:t.sortText,tags:t.tags,textEditText:t.textEditText,textEdit:i,label:n}}buildCompletionTextEdit(e,t,n){return this.clientCapabilities?.completionItem?.insertReplaceSupport?this.buildCompletionTextEditWithInsertReplace(e,t,n):this.buildCompletionTextEditWithoutInsertReplace(e,t,n)}buildCompletionTextEditWithInsertReplace(e,t,n){let r=e.textDocument.positionAt(e.tokenOffset),i=e.position,a=e.textDocument.getText({start:r,end:i});if(this.fuzzyMatcher.match(a,t)){let t=e.textDocument.positionAt(e.tokenEndOffset);return{newText:n,insert:{start:r,end:i},replace:{start:r,end:t}}}}buildCompletionTextEditWithoutInsertReplace(e,t,n){let r=e.textDocument.getText().substring(e.tokenOffset,e.offset);if(this.fuzzyMatcher.match(r,t))return{newText:n,range:{start:e.textDocument.positionAt(e.tokenOffset),end:e.position}}}},J;(function(e){e.basename=fe.basename,e.dirname=fe.dirname,e.extname=fe.extname,e.joinPath=fe.joinPath,e.resolvePath=fe.resolvePath;let t=typeof process==`object`&&process?.platform===`win32`;function equals(e,t){return e?.toString()===t?.toString()}e.equals=equals;function relative(e,n){let r=typeof e==`string`?y.parse(e).path:e.path,i=typeof n==`string`?y.parse(n).path:n.path,a=r.split(`/`).filter(e=>e.length>0),o=i.split(`/`).filter(e=>e.length>0);if(t){let e=/^[A-Z]:$/;if(a[0]&&e.test(a[0])&&(a[0]=a[0].toLowerCase()),o[0]&&e.test(o[0])&&(o[0]=o[0].toLowerCase()),a[0]!==o[0])return i.substring(1)}let s=0;for(;s<a.length&&a[s]===o[s];s++);return`../`.repeat(a.length-s)+o.slice(s).join(`/`)}e.relative=relative;function normalize(e){return y.parse(e.toString()).toString()}e.normalize=normalize;function contains(e,t){let n=typeof e==`string`?y.parse(e):e,r=typeof t==`string`?y.parse(t):t;if(n.scheme!==r.scheme)return!1;let i=n.path,a=r.path;return a.charAt(a.length-1)===`/`&&(a=a.slice(0,-1)),i.charAt(i.length-1)===`/`&&(i=i.slice(0,-1)),a===i?!0:a.length<i.length||a.charAt(i.length)!==`/`?!1:a.startsWith(i)}e.contains=contains})(J||={});var UriTrie=class{constructor(){this.root={name:``,children:/* @__PURE__ */ new Map}}normalizeUri(e){return J.normalize(e)}clear(){this.root.children.clear()}insert(e,t){let n=this.getNode(this.normalizeUri(e),!0);n.element=t}delete(e){let t=this.getNode(this.normalizeUri(e),!1);t?.parent&&t.parent.children.delete(t.name)}has(e){return this.getNode(this.normalizeUri(e),!1)?.element!==void 0}hasNode(e){return this.getNode(this.normalizeUri(e),!1)!==void 0}find(e){return this.getNode(this.normalizeUri(e),!1)?.element}findNode(e){let t=this.normalizeUri(e),n=this.getNode(t,!1);if(n)return{name:n.name,uri:J.joinPath(y.parse(t),n.name).toString(),element:n.element}}findChildren(e){let t=this.normalizeUri(e),n=this.getNode(t,!1);return n?Array.from(n.children.values()).map(e=>({name:e.name,uri:J.joinPath(y.parse(t),e.name).toString(),element:e.element})):[]}all(){return this.collectValues(this.root)}findAll(e){let t=this.getNode(this.normalizeUri(e),!1);return t?this.collectValues(t):[]}getNode(e,t){let n=e.split(`/`);e.charAt(e.length-1)===`/`&&n.pop();let r=this.root;for(let e of n){let n=r.children.get(e);if(!n){if(t)n={name:e,children:/* @__PURE__ */ new Map,parent:r},r.children.set(e,n);else return}r=n}return r}collectValues(e){let t=[];e.element&&t.push(e.element);for(let n of e.children.values())t.push(...this.collectValues(n));return t}},DefaultDefinitionProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}getDefinition(e,t,n){let r=e.parseResult.value;if(r.$cstNode){let n=r.$cstNode,i=findDeclarationNodeAtOffset(n,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(i)return this.collectLocationLinks(i,t)}}collectLocationLinks(e,t){let n=this.findLinks(e);if(n.length>0)return n.map(e=>oe.create(e.targetDocument.textDocument.uri,(e.target.astNode.$cstNode??e.target).range,e.target.range,e.source.range))}findLinks(e){let t=getDatatypeNode(e)??e,n=this.references.findDeclarationNodes(e),r=[];for(let e of n){let i=getDocument(e.astNode);n&&i&&r.push({source:t,target:e,targetDocument:i})}return r}};function createGrammarConfig(e){let t=[],n=e.Grammar;for(let e of n.rules)isTerminalRule(e)&&isCommentTerminal(e)&&isMultilineComment(terminalRegex(e))&&t.push(e.name);return{multilineCommentRules:t,nameRegexp:tt}}var CstNodeBuilder=class{constructor(){this.nodeStack=[]}get current(){return this.nodeStack[this.nodeStack.length-1]??this.rootNode}buildRootNode(e){return this.rootNode=new RootCstNodeImpl(e),this.nodeStack=[this.rootNode],this.rootNode}buildCompositeNode(e){let t=new CompositeCstNodeImpl;return t.grammarSource=e,this.appendChild(this.current,t),this.nodeStack.push(t),t}buildLeafNode(e,t){let n=this.createLeafNode(e,!t);return t&&(n.grammarSource=t),this.appendChild(this.current,n),n}createLeafNode(e,t){return new LeafCstNodeImpl(e.startOffset,e.image.length,e.startLine-1,e.startColumn-1,e.endLine-1,e.endColumn,e.tokenType,t)}appendChild(e,t){t.container=e,e.content.push(t)}appendChildren(e,t){for(let n of t)n.container=e;e.content.length===0?e.content=t.slice():e.content.push(...t)}insertChildren(e,t,n){for(let t of n)t.container=e;e.content.splice(t,0,...n)}removeNode(e){let t=e.container;if(t){let n=t.content.indexOf(e);n>=0&&t.content.splice(n,1)}}addHiddenNodes(e){let t=[];for(let n of e)t.push(this.createLeafNode(n,!0));let n=this.current,r=!1;if(n.content.length>0)this.appendChildren(n,t);else{for(;n.container;){let e=n.container.content.indexOf(n);if(e>0){this.insertChildren(n.container,e,t),r=!0;break}n=n.container}r||this.insertChildren(this.rootNode,0,t)}}construct(e){e.$cstNode=this.current;let t=this.nodeStack.pop();t&&(t.content.length===0?this.removeNode(t):t.content=t.content.slice())}},AbstractCstNode=class{constructor(){this.container=void 0,this.grammarSource=void 0}get root(){let e=this;for(;e.container;)e=e.container;return e}get text(){return this.root.fullText.substring(this.offset,this.end)}},LeafCstNodeImpl=class extends AbstractCstNode{get offset(){return this._offset}get length(){return this._length}get end(){return this._offset+this._length}get hidden(){return this._hidden}get tokenType(){return this._tokenType}get astNode(){let e=this.container;if(!e)throw Error(`This node has no associated AST element`);return e.astNode}get range(){return{start:{line:this._startLine,character:this._startColumn},end:{line:this._endLine,character:this._endColumn}}}constructor(e,t,n,r,i,a,o,s=!1){super(),this._hidden=s,this._offset=toSmi(e),this._length=toSmi(t),this._startLine=toSmi(n),this._startColumn=toSmi(r),this._endLine=toSmi(i),this._endColumn=toSmi(a),this._tokenType=o}};function toSmi(e){return e|0}var CompositeCstNodeImpl=class extends AbstractCstNode{constructor(){super(...arguments),this.content=[],this._astNode=void 0,this._rangeCache=void 0}get astNode(){let e=this;for(;e;){if(e._astNode)return e._astNode;e=e.container}throw Error(`This node has no associated AST element`)}set astNode(e){this._astNode=e}get hidden(){return!1}get offset(){return this.firstNonHiddenNode?.offset??0}get length(){return this.end-this.offset}get end(){return this.lastNonHiddenNode?.end??0}get range(){let e=this._rangeCache;if(e===void 0){let t=this.firstNonHiddenNode,n=this.lastNonHiddenNode;if(t&&n){let{range:r}=t,{range:i}=n;this._rangeCache=e={start:r.start,end:i.end.line<r.start.line?r.start:i.end}}else return{start:{line:0,character:0},end:{line:0,character:0}}}return e}get firstNonHiddenNode(){for(let e of this.content)if(!e.hidden)return e;return this.content[0]}get lastNonHiddenNode(){for(let e=this.content.length-1;e>=0;e--){let t=this.content[e];if(!t.hidden)return t}return this.content[this.content.length-1]}},RootCstNodeImpl=class extends CompositeCstNodeImpl{get text(){return this._text.substring(this.offset,this.end)}get fullText(){return this._text}constructor(e){super(),this._text=``,this._text=e??``}};const lt=Symbol(`Datatype`);function isDataTypeNode(e){return e.$type===lt}const withRuleSuffix=e=>e.endsWith(`​`)?e:e+`​`;var AbstractLangiumParser=class{constructor(e,t){this._unorderedGroups=/* @__PURE__ */ new Map,this.allRules=/* @__PURE__ */ new Map,this.lexer=e.parser.Lexer;let n=this.lexer.definition,r=e.LanguageMetaData.mode===`production`;this.wrapper=e.shared.profilers.LangiumProfiler?.isActive(`parsing`)?new ProfilerWrapper(n,{...e.parser.ParserConfig,skipValidations:r,errorMessageProvider:e.parser.ParserErrorMessageProvider},t,e.shared.profilers.LangiumProfiler.createTask(`parsing`,e.LanguageMetaData.languageId)):new ChevrotainWrapper(n,{...e.parser.ParserConfig,skipValidations:r,errorMessageProvider:e.parser.ParserErrorMessageProvider},t)}alternatives(e,t){this.wrapper.wrapOr(e,t)}optional(e,t){this.wrapper.wrapOption(e,t)}many(e,t){this.wrapper.wrapMany(e,t)}atLeastOne(e,t){this.wrapper.wrapAtLeastOne(e,t)}getRule(e){return this.allRules.get(e)}isRecording(){return this.wrapper.IS_RECORDING}get unorderedGroups(){return this._unorderedGroups}getRuleStack(){return this.wrapper.RULE_STACK}finalize(){this.wrapper.wrapSelfAnalysis()}},LangiumParser=class extends AbstractLangiumParser{get current(){return this.stack[this.stack.length-1]}constructor(e){super(e,!1),this.nodeBuilder=new CstNodeBuilder,this.stack=[],this.assignmentMap=/* @__PURE__ */ new Map,this.operatorPrecedence=/* @__PURE__ */ new Map,this.linker=e.references.Linker,this.converter=e.parser.ValueConverter,this.astReflection=e.shared.AstReflection}rule(e,t){let n=this.computeRuleType(e),r;isInfixRule(e)&&(r=e.name,this.registerPrecedenceMap(e));let i=this.wrapper.DEFINE_RULE(withRuleSuffix(e.name),this.startImplementation(n,r,t).bind(this));return this.allRules.set(e.name,i),isParserRule(e)&&e.entry&&(this.mainRule=i),i}registerPrecedenceMap(e){let t=e.name,n=/* @__PURE__ */ new Map;for(let t=0;t<e.operators.precedences.length;t++){let r=e.operators.precedences[t];for(let e of r.operators)n.set(e.value,{precedence:t,rightAssoc:r.associativity===`right`})}this.operatorPrecedence.set(t,n)}computeRuleType(e){if(isInfixRule(e))return getTypeName(e);if(!e.fragment)return isDataTypeRule(e)?lt:getTypeName(e)}parse(e,t={}){this.nodeBuilder.buildRootNode(e);let n=this.lexerResult=this.lexer.tokenize(e);this.wrapper.input=n.tokens;let r=t.rule?this.allRules.get(t.rule):this.mainRule;if(!r)throw Error(t.rule?`No rule found with name '${t.rule}'`:`No main rule available.`);let i=this.doParse(r);return this.nodeBuilder.addHiddenNodes(n.hidden),this.unorderedGroups.clear(),this.lexerResult=void 0,linkContentToContainer(i,{deep:!0}),{value:i,lexerErrors:n.errors,lexerReport:n.report,parserErrors:this.wrapper.errors}}doParse(e){let t=this.wrapper.rule(e);if(this.stack.length>0&&(t=this.construct()),t===void 0)throw Error(`No result from parser`);if(this.stack.length>0)throw Error(`Parser stack is not empty after parsing`);return this.linkCstNode(t),t}linkCstNode(e){isAstNode(e)&&e.$cstNode&&(e.$cstNode.astNode=e)}startImplementation(e,t,n){return r=>{let i=!this.isRecording()&&e!==void 0;if(i){let n={$type:e};this.stack.push(n),e===lt?n.value=``:t!==void 0&&(n.$infixName=t)}return n(r),i?this.construct():void 0}}extractHiddenTokens(e){let t=this.lexerResult.hidden;if(!t.length)return[];let n=e.startOffset;for(let e=0;e<t.length;e++)if(t[e].startOffset>n)return t.splice(0,e);return t.splice(0,t.length)}consume(e,t,n){let r=this.wrapper.wrapConsume(e,t);if(!this.isRecording()&&this.isValidToken(r)){let e=this.extractHiddenTokens(r);this.nodeBuilder.addHiddenNodes(e);let t=this.nodeBuilder.buildLeafNode(r,n),{assignment:i,crossRef:a}=this.getAssignment(n),o=this.current;if(i){let e=isKeyword(n)?r.image:this.converter.convert(r.image,t);this.assign(i.operator,i.feature,e,t,a)}else if(isDataTypeNode(o)){let e=r.image;isKeyword(n)||(e=this.converter.convert(e,t).toString()),o.value+=e}}}isValidToken(e){return!e.isInsertedInRecovery&&isValidTokenRange(e)}subrule(e,t,n,r,i){let a;!this.isRecording()&&!n&&(a=this.nodeBuilder.buildCompositeNode(r));let o;try{o=this.wrapper.wrapSubrule(e,t,i)}finally{this.isRecording()||(o===void 0&&!n&&(o=this.construct()),o!==void 0&&a&&a.length>0&&this.performSubruleAssignment(o,r,a))}}performSubruleAssignment(e,t,n){let{assignment:r,crossRef:i}=this.getAssignment(t);if(r)this.assign(r.operator,r.feature,e,n,i);else if(!r){let t=this.current;if(isDataTypeNode(t))t.value+=e.toString();else if(typeof e==`object`&&e){let n=this.assignWithoutOverride(e,t);this.stack.pop(),this.stack.push(n)}}}action(e,t){if(!this.isRecording()){let n=this.current;if(t.feature&&t.operator){n=this.construct(),this.nodeBuilder.removeNode(n.$cstNode);let r=this.nodeBuilder.buildCompositeNode(t);this.nodeBuilder.appendChild(r,n.$cstNode);let i={$type:e};this.stack.push(i),this.assign(t.operator,t.feature,n,n.$cstNode)}else n.$type=e}}construct(){if(this.isRecording())return;let e=this.stack.pop();return this.nodeBuilder.construct(e),`$infixName`in e?this.constructInfix(e,this.operatorPrecedence.get(e.$infixName)):isDataTypeNode(e)?this.converter.convert(e.value,e.$cstNode):(assignMandatoryProperties(this.astReflection,e),e)}constructInfix(e,t){let n=e.parts;if(!Array.isArray(n)||n.length===0)return;let r=e.operators;if(!Array.isArray(r)||n.length<2)return n[0];let i=0,a=-1;for(let e=0;e<r.length;e++){let n=r[e],o=t.get(n)??{precedence:1/0,rightAssoc:!1};o.precedence>a?(a=o.precedence,i=e):o.precedence===a&&(o.rightAssoc||(i=e))}let o=r.slice(0,i),s=r.slice(i+1),c=n.slice(0,i+1),l=n.slice(i+1),u={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:c,operators:o},d={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:l,operators:s},f=this.constructInfix(u,t),p=this.constructInfix(d,t);return{$type:e.$type,$cstNode:e.$cstNode,left:f,operator:r[i],right:p}}getAssignment(e){if(!this.assignmentMap.has(e)){let t=getContainerOfType(e,isAssignment);this.assignmentMap.set(e,{assignment:t,crossRef:t&&isCrossReference(t.terminal)?t.terminal.isMulti?`multi`:`single`:void 0})}return this.assignmentMap.get(e)}assign(e,t,n,r,i){let a=this.current,o;switch(o=i===`single`&&typeof n==`string`?this.linker.buildReference(a,t,r,n):i===`multi`&&typeof n==`string`?this.linker.buildMultiReference(a,t,r,n):n,this.linkCstNode(o),e){case`=`:a[t]=o;break;case`?=`:a[t]=!0;break;case`+=`:Array.isArray(a[t])||(a[t]=[]),a[t].push(o)}}assignWithoutOverride(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];t===void 0?e[n]=r:Array.isArray(t)&&Array.isArray(r)&&(r.push(...t),e[n]=r)}return e.$cstNode=void 0,e}get definitionErrors(){return this.wrapper.definitionErrors}},AbstractParserErrorMessageProvider=class{buildMismatchTokenMessage(e){return i.buildMismatchTokenMessage(e)}buildNotAllInputParsedMessage(e){return i.buildNotAllInputParsedMessage(e)}buildNoViableAltMessage(e){return i.buildNoViableAltMessage(e)}buildEarlyExitMessage(e){return i.buildEarlyExitMessage(e)}},LangiumParserErrorMessageProvider=class extends AbstractParserErrorMessageProvider{buildMismatchTokenMessage({expected:e,actual:t}){return`Expecting ${e.LABEL?"`"+e.LABEL+"`":e.name.endsWith(`:KW`)?`keyword '${e.name.substring(0,e.name.length-3)}'`:`token of type '${e.name}'`} but found \`${t.image}\`.`}buildNotAllInputParsedMessage({firstRedundant:e}){return`Expecting end of file but found \`${e.image}\`.`}},LangiumCompletionParser=class extends AbstractLangiumParser{constructor(e){super(e,!0),this.tokens=[],this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}action(){}construct(){}parse(e){this.resetState();let t=this.lexer.tokenize(e,{mode:`partial`});return this.tokens=t.tokens,this.wrapper.input=[...this.tokens],this.mainRule.call(this.wrapper,{}),this.unorderedGroups.clear(),{tokens:this.tokens,elementStack:[...this.lastElementStack],tokenIndex:this.nextTokenIndex}}rule(e,t){let n=this.wrapper.DEFINE_RULE(withRuleSuffix(e.name),this.startImplementation(t).bind(this));return this.allRules.set(e.name,n),e.entry&&(this.mainRule=n),n}resetState(){this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}startImplementation(e){return t=>{let n=this.keepStackSize();try{e(t)}finally{this.resetStackSize(n)}}}removeUnexpectedElements(){this.elementStack.splice(this.stackSize)}keepStackSize(){let e=this.elementStack.length;return this.stackSize=e,e}resetStackSize(e){this.removeUnexpectedElements(),this.stackSize=e}consume(e,t,n){this.wrapper.wrapConsume(e,t),this.isRecording()||(this.lastElementStack=[...this.elementStack,n],this.nextTokenIndex=this.currIdx+1)}subrule(e,t,n,r,i){this.before(r),this.wrapper.wrapSubrule(e,t,i),this.after(r)}before(e){this.isRecording()||this.elementStack.push(e)}after(e){if(!this.isRecording()){let t=this.elementStack.lastIndexOf(e);t>=0&&this.elementStack.splice(t)}}get currIdx(){return this.wrapper.currIdx}};const ut={recoveryEnabled:!0,nodeLocationTracking:`full`,skipValidations:!0,errorMessageProvider:new LangiumParserErrorMessageProvider};var ChevrotainWrapper=class extends o{constructor(e,t,n){let r=t&&`maxLookahead`in t;super(e,{...ut,lookaheadStrategy:r?new c({maxLookahead:t.maxLookahead}):new d({logging:t.skipValidations?()=>{}:void 0,incomplete:n}),...t})}get IS_RECORDING(){return this.RECORDING_PHASE}DEFINE_RULE(e,t,n){return this.RULE(e,t,n)}wrapSelfAnalysis(){this.performSelfAnalysis()}wrapConsume(e,t){return this.consume(e,t,void 0)}wrapSubrule(e,t,n){return this.subrule(e,t,{ARGS:[n]})}wrapOr(e,t){this.or(e,t)}wrapOption(e,t){this.option(e,t)}wrapMany(e,t){this.many(e,t)}wrapAtLeastOne(e,t){this.atLeastOne(e,t)}rule(e){return e.call(this,{})}},ProfilerWrapper=class extends ChevrotainWrapper{constructor(e,t,n,r){super(e,t,n),this.task=r}rule(e){this.task.start(),this.task.startSubTask(this.ruleName(e));try{return super.rule(e)}finally{this.task.stopSubTask(this.ruleName(e)),this.task.stop()}}ruleName(e){return e.ruleName}subrule(e,t,n){this.task.startSubTask(this.ruleName(t));try{return super.subrule(e,t,n)}finally{this.task.stopSubTask(this.ruleName(t))}}};function createParser(e,t,n){return buildRules({parser:t,tokens:n,ruleNames:/* @__PURE__ */ new Map},e),t}function buildRules(e,t){let n=getAllReachableRules(t,!1),r=stream(t.rules).filter(isParserRule).filter(e=>n.has(e));for(let t of r){let n={...e,consume:1,optional:1,subrule:1,many:1,or:1};e.parser.rule(t,buildElement(n,t.definition))}let i=stream(t.rules).filter(isInfixRule).filter(e=>n.has(e));for(let t of i)e.parser.rule(t,buildInfixRule(e,t))}function buildInfixRule(e,t){let n=t.call.rule.ref;if(!n)throw Error(`Could not resolve reference to infix operator rule: `+t.call.rule.$refText);if(isTerminalRule(n))throw Error(`Cannot use terminal rule in infix expression`);let r=t.operators.precedences.flatMap(e=>e.operators),i={$type:`Group`,elements:[]},a={$container:i,$type:`Assignment`,feature:`parts`,operator:`+=`,terminal:t.call},o={$container:i,$type:`Group`,elements:[],cardinality:`*`};i.elements.push(a,o);let s={$container:o,$type:`Assignment`,feature:`operators`,operator:`+=`,terminal:{$type:`Alternatives`,elements:r}},c={...a,$container:o};o.elements.push(s,c);let l=r.map(t=>e.tokens[t.value]).map((t,n)=>({ALT:()=>e.parser.consume(n,t,s)})),u;return t=>{u??=getRule(e,n),e.parser.subrule(0,u,!1,a,t),e.parser.many(0,{DEF:()=>{e.parser.alternatives(0,l),e.parser.subrule(1,u,!1,c,t)}})}}function buildElement(e,t,n=!1){let method;if(isKeyword(t))method=buildKeyword(e,t);else if(isAction(t))method=buildAction(e,t);else if(isAssignment(t))method=buildElement(e,t.terminal);else if(isCrossReference(t))method=buildCrossReference(e,t);else if(isRuleCall(t))method=buildRuleCall(e,t);else if(isAlternatives(t))method=buildAlternatives(e,t);else if(isUnorderedGroup(t))method=buildUnorderedGroup(e,t);else if(isGroup(t))method=buildGroup(e,t);else if(isEndOfFile(t)){let n=e.consume++;method=()=>e.parser.consume(n,s,t)}else throw new ErrorWithLocation(t.$cstNode,`Unexpected element type: ${t.$type}`);return wrap(e,n?void 0:getGuardCondition(t),method,t.cardinality)}function buildAction(e,t){let n=getTypeName(t);return()=>e.parser.action(n,t)}function buildRuleCall(e,t){let n=t.rule.ref;if(isAbstractParserRule(n)){let r=e.subrule++,i=isParserRule(n)&&n.fragment,a=t.arguments.length>0?buildRuleCallPredicate(n,t.arguments):()=>({}),o;return s=>{o??=getRule(e,n),e.parser.subrule(r,o,i,t,a(s))}}if(isTerminalRule(n)){let r=e.consume++,i=getToken(e,n.name);return()=>e.parser.consume(r,i,t)}if(n)assertUnreachable(n);else throw new ErrorWithLocation(t.$cstNode,`Undefined rule: ${t.rule.$refText}`)}function buildRuleCallPredicate(e,t){if(t.some(e=>e.calledByName)){let e=t.map(e=>({parameterName:e.parameter?.ref?.name,predicate:buildPredicate(e.value)}));return t=>{let n={};for(let{parameterName:r,predicate:i}of e)r&&(n[r]=i(t));return n}}{let n=t.map(e=>buildPredicate(e.value));return t=>{let r={};for(let i=0;i<n.length;i++)if(i<e.parameters.length){let a=e.parameters[i].name,o=n[i];r[a]=o(t)}return r}}}function buildPredicate(e){if(isDisjunction(e)){let t=buildPredicate(e.left),n=buildPredicate(e.right);return e=>t(e)||n(e)}if(isConjunction(e)){let t=buildPredicate(e.left),n=buildPredicate(e.right);return e=>t(e)&&n(e)}if(isNegation(e)){let t=buildPredicate(e.value);return e=>!t(e)}if(isParameterReference(e)){let t=e.parameter.ref.name;return e=>e!==void 0&&e[t]===!0}if(isBooleanLiteral(e)){let t=!!e.true;return()=>t}assertUnreachable(e)}function buildAlternatives(e,t){if(t.elements.length===1)return buildElement(e,t.elements[0]);{let n=[];for(let r of t.elements){let t={ALT:buildElement(e,r,!0)},i=getGuardCondition(r);i&&(t.GATE=buildPredicate(i)),n.push(t)}let r=e.or++;return t=>e.parser.alternatives(r,n.map(e=>{let n={ALT:()=>e.ALT(t)},r=e.GATE;return r&&(n.GATE=()=>r(t)),n}))}}function buildUnorderedGroup(e,t){if(t.elements.length===1)return buildElement(e,t.elements[0]);let n=[];for(let r of t.elements){let t={ALT:buildElement(e,r,!0)},i=getGuardCondition(r);i&&(t.GATE=buildPredicate(i)),n.push(t)}let r=e.or++,idFunc=(e,t)=>`uGroup_${e}_${t.getRuleStack().join(`-`)}`,alternatives=t=>e.parser.alternatives(r,n.map((n,i)=>{let a={ALT:()=>!0},o=e.parser;a.ALT=()=>{if(n.ALT(t),!o.isRecording()){let e=idFunc(r,o);o.unorderedGroups.get(e)||o.unorderedGroups.set(e,[]);let t=o.unorderedGroups.get(e);t?.[i]===void 0&&(t[i]=!0)}};let s=n.GATE;return a.GATE=s?()=>s(t):()=>!o.unorderedGroups.get(idFunc(r,o))?.[i],a})),i=wrap(e,getGuardCondition(t),alternatives,`*`);return t=>{i(t),e.parser.isRecording()||e.parser.unorderedGroups.delete(idFunc(r,e.parser))}}function buildGroup(e,t){let n=t.elements.map(t=>buildElement(e,t));return e=>n.forEach(t=>t(e))}function getGuardCondition(e){if(isGroup(e))return e.guardCondition}function buildCrossReference(e,t,n=t.terminal){if(!n){if(!t.type.ref)throw Error(`Could not resolve reference to type: `+t.type.$refText);let n=findNameAssignment(t.type.ref)?.terminal;if(!n)throw Error(`Could not find name assignment for type: `+getTypeName(t.type.ref));return buildCrossReference(e,t,n)}if(isRuleCall(n)&&isParserRule(n.rule.ref)){let r=n.rule.ref,i=e.subrule++,a;return n=>{a??=getRule(e,r),e.parser.subrule(i,a,!1,t,n)}}if(isRuleCall(n)&&isTerminalRule(n.rule.ref)){let r=e.consume++,i=getToken(e,n.rule.ref.name);return()=>e.parser.consume(r,i,t)}if(isKeyword(n)){let r=e.consume++,i=getToken(e,n.value);return()=>e.parser.consume(r,i,t)}throw Error(`Could not build cross reference parser`)}function buildKeyword(e,t){let n=e.consume++,r=e.tokens[t.value];if(!r)throw Error(`Could not find token for keyword: `+t.value);return()=>e.parser.consume(n,r,t)}function wrap(e,t,n,r){let i=t&&buildPredicate(t);if(!r){if(i){let t=e.or++;return r=>e.parser.alternatives(t,[{ALT:()=>n(r),GATE:()=>i(r)},{ALT:l(),GATE:()=>!i(r)}])}return n}if(r===`*`){let t=e.many++;return r=>e.parser.many(t,{DEF:()=>n(r),GATE:i?()=>i(r):void 0})}if(r===`+`){let t=e.many++;if(i){let r=e.or++;return a=>e.parser.alternatives(r,[{ALT:()=>e.parser.atLeastOne(t,{DEF:()=>n(a)}),GATE:()=>i(a)},{ALT:l(),GATE:()=>!i(a)}])}return r=>e.parser.atLeastOne(t,{DEF:()=>n(r)})}if(r===`?`){let t=e.optional++;return r=>e.parser.optional(t,{DEF:()=>n(r),GATE:i?()=>i(r):void 0})}assertUnreachable(r)}function getRule(e,t){let n=getRuleName(e,t),r=e.parser.getRule(n);if(!r)throw Error(`Rule "${n}" not found."`);return r}function getRuleName(e,t){if(isAbstractParserRule(t))return t.name;if(e.ruleNames.has(t))return e.ruleNames.get(t);{let n=t,r=n.$container,i=t.$type;for(;!isParserRule(r);)(isGroup(r)||isAlternatives(r)||isUnorderedGroup(r))&&(i=r.elements.indexOf(n).toString()+`:`+i),n=r,r=r.$container;return i=r.name+`:`+i,e.ruleNames.set(t,i),i}}function getToken(e,t){let n=e.tokens[t];if(!n)throw Error(`Token "${t}" not found."`);return n}function createCompletionParser(e){let t=e.Grammar,n=e.parser.Lexer,r=new LangiumCompletionParser(e);return createParser(t,r,n.definition),r.finalize(),r}function createLangiumParser(e){let t=prepareLangiumParser(e);return t.finalize(),t}function prepareLangiumParser(e){let t=e.Grammar,n=e.parser.Lexer;return createParser(t,new LangiumParser(e),n.definition)}var DefaultTokenBuilder=class{constructor(){this.diagnostics=[]}buildTokens(e,t){let n=stream(getAllReachableRules(e,!1)),r=this.buildTerminalTokens(n),i=this.buildKeywordTokens(n,r,t);return i.push(...r),i}flushLexingReport(e){return{diagnostics:this.popDiagnostics()}}popDiagnostics(){let e=[...this.diagnostics];return this.diagnostics=[],e}buildTerminalTokens(e){return e.filter(isTerminalRule).filter(e=>!e.fragment).map(e=>this.buildTerminalToken(e)).toArray()}buildTerminalToken(e){let t=terminalRegex(e),n=this.requiresCustomPattern(t)?this.regexPatternFunction(t):t,r={name:e.name,PATTERN:n};return typeof n==`function`&&(r.LINE_BREAKS=!0),e.hidden&&(r.GROUP=isWhitespace(t)?a.SKIPPED:`hidden`),r}requiresCustomPattern(e){return!!(e.flags.includes(`u`)||e.flags.includes(`s`))}regexPatternFunction(e){let t=new RegExp(e,e.flags+`y`);return(e,n)=>(t.lastIndex=n,t.exec(e))}buildKeywordTokens(e,t,n){return e.filter(isAbstractParserRule).flatMap(e=>streamAllContents(e).filter(isKeyword)).distinct(e=>e.value).toArray().sort((e,t)=>t.value.length-e.value.length).map(e=>this.buildKeywordToken(e,t,!!n?.caseInsensitive))}buildKeywordToken(e,t,n){let r=this.buildKeywordPattern(e,n),i={name:e.value,PATTERN:r,LONGER_ALT:this.findLongerAlt(e,t)};return typeof r==`function`&&(i.LINE_BREAKS=!0),i}buildKeywordPattern(e,t){return t?new RegExp(escapeRegExp(e.value),`i`):e.value}findLongerAlt(e,t){return t.reduce((t,n)=>{let r=n?.PATTERN;return r?.source&&partialMatches(`^`+r.source+`$`,e.value)&&t.push(n),t},[])}},DefaultValueConverter=class{convert(e,t){let n=t.grammarSource;if(isCrossReference(n)&&(n=getCrossReferenceTerminal(n)),isRuleCall(n)){let r=n.rule.ref;if(!r)throw Error(`This cst node was not parsed by a rule.`);return this.runConverter(r,e,t)}return e}runConverter(e,t,n){switch(e.name.toUpperCase()){case`INT`:return Y.convertInt(t);case`STRING`:return Y.convertString(t);case`ID`:return Y.convertID(t)}switch(getRuleType(e)?.toLowerCase()){case`number`:return Y.convertNumber(t);case`boolean`:return Y.convertBoolean(t);case`bigint`:return Y.convertBigint(t);case`date`:return Y.convertDate(t);default:return t}}},Y;(function(e){function convertString(e){let t=``;for(let n=1;n<e.length-1;n++){let r=e.charAt(n);if(r===`\\`){let r=e.charAt(++n);t+=convertEscapeCharacter(r)}else t+=r}return t}e.convertString=convertString;function convertEscapeCharacter(e){switch(e){case`b`:return`\b`;case`f`:return`\f`;case`n`:return`
5
+ `;case`r`:return`\r`;case`t`:return` `;case`v`:return`\v`;case`0`:return`\0`;default:return e}}function convertID(e){return e.charAt(0)===`^`?e.substring(1):e}e.convertID=convertID;function convertInt(e){return parseInt(e)}e.convertInt=convertInt;function convertBigint(e){return BigInt(e)}e.convertBigint=convertBigint;function convertDate(e){return new Date(e)}e.convertDate=convertDate;function convertNumber(e){return Number(e)}e.convertNumber=convertNumber;function convertBoolean(e){return e.toLowerCase()===`true`}e.convertBoolean=convertBoolean})(Y||={});function delayNextTick(){return new Promise(e=>{typeof setImmediate>`u`?setTimeout(e,0):setImmediate(e)})}let dt=0;function startCancelableOperation(){return dt=performance.now(),new pe}const ft=Symbol(`OperationCancelled`);function isOperationCancelled(e){return e===ft}async function interruptAndCheck(e){if(e===b.None)return;let t=performance.now();if(t-dt>=10&&(dt=t,await delayNextTick(),dt=performance.now()),e.isCancellationRequested)throw ft}var Deferred=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>(e(t),this),this.reject=e=>(t(e),this)})}},X;(function(e){e[e.Changed=0]=`Changed`,e[e.Parsed=1]=`Parsed`,e[e.IndexedContent=2]=`IndexedContent`,e[e.ComputedScopes=3]=`ComputedScopes`,e[e.Linked=4]=`Linked`,e[e.IndexedReferences=5]=`IndexedReferences`,e[e.Validated=6]=`Validated`})(X||={});var DefaultLangiumDocumentFactory=class{constructor(e){this.serviceRegistry=e.ServiceRegistry,this.textDocuments=e.workspace.TextDocuments,this.fileSystemProvider=e.workspace.FileSystemProvider}async fromUri(e,t=b.None){let n=await this.getInitialText(e,t);return this.createAsync(e,n,t)}async getInitialText(e,t){return this.fileSystemProvider.readFile(e)}fromTextDocument(e,t,n){return t??=y.parse(e.uri),b.is(n)?this.createAsync(t,e,n):this.create(t,e,n)}fromString(e,t,n){return b.is(n)?this.createAsync(t,e,n):this.create(t,e,n)}fromModel(e,t){return this.create(t,{$model:e})}create(e,t,n){if(typeof t==`string`){let r=this.parse(e,t,n);return this.createLangiumDocument(r,e,void 0,t)}if(`$model`in t){let n={value:t.$model,parserErrors:[],lexerErrors:[]};return this.createLangiumDocument(n,e)}{let r=this.parse(e,t.getText(),n);return this.createLangiumDocument(r,e,t)}}async createAsync(e,t,n){if(typeof t==`string`){let r=await this.parseAsync(e,t,n);return this.createLangiumDocument(r,e,void 0,t)}{let r=await this.parseAsync(e,t.getText(),n);return this.createLangiumDocument(r,e,t)}}createLangiumDocument(e,t,n,r){let i;if(n)i={parseResult:e,uri:t,state:X.Parsed,references:[],textDocument:n};else{let n=this.createTextDocumentGetter(t,r);i={parseResult:e,uri:t,state:X.Parsed,references:[],get textDocument(){return n()}}}return e.value.$document=i,i}async update(e,t){let n=e.parseResult.value.$cstNode?.root.fullText,r=this.textDocuments?.get(e.uri.toString()),i=await this.getUpdatedText(e,r,t);if(r)Object.defineProperty(e,"textDocument",{value:r});else{let t=this.createTextDocumentGetter(e.uri,i);Object.defineProperty(e,"textDocument",{get:t})}return n!==i&&(e.parseResult=await this.parseAsync(e.uri,i,t),e.parseResult.value.$document=e),e.state=X.Parsed,e}async getUpdatedText(e,t,n){return t?t.getText():await this.fileSystemProvider.readFile(e.uri)}parse(e,t,n){return this.serviceRegistry.getServices(e).parser.LangiumParser.parse(t,n)}parseAsync(e,t,n){return this.serviceRegistry.getServices(e).parser.AsyncParser.parse(t,n)}createTextDocumentGetter(e,t){let n=this.serviceRegistry,r;return()=>r??=be.create(e.toString(),n.getServices(e).LanguageMetaData.languageId,0,t??``)}},DefaultLangiumDocuments=class{constructor(e){this.documentTrie=new UriTrie,this.services=e,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.documentBuilder=()=>e.workspace.DocumentBuilder}get all(){return stream(this.documentTrie.all())}addDocument(e){let t=e.uri.toString();if(this.documentTrie.has(t))throw Error(`A document with the URI '${t}' is already present.`);this.documentTrie.insert(t,e)}getDocument(e){let t=e.toString();return this.documentTrie.find(t)}getDocuments(e){let t=e.toString();return this.documentTrie.findAll(t)}async getOrCreateDocument(e,t){let n=this.getDocument(e);return n||(n=await this.langiumDocumentFactory.fromUri(e,t),this.addDocument(n),n)}createDocument(e,t,n){if(n)return this.langiumDocumentFactory.fromString(t,e,n).then(e=>(this.addDocument(e),e));{let n=this.langiumDocumentFactory.fromString(t,e);return this.addDocument(n),n}}hasDocument(e){return this.documentTrie.has(e.toString())}invalidateDocument(e){let t=e.toString(),n=this.documentTrie.find(t);return n&&this.documentBuilder().resetToState(n,X.Changed),n}deleteDocument(e){let t=e.toString(),n=this.documentTrie.find(t);return n&&(n.state=X.Changed,this.documentTrie.delete(t)),n}deleteDocuments(e){let t=e.toString(),n=this.documentTrie.findAll(t);for(let e of n)e.state=X.Changed;return this.documentTrie.delete(t),n}};const pt=Symbol(`RefResolving`);var DefaultReferenceImpl=class{constructor(e,t,n,r,i){this.resolver=e,this.node=t,this.property=n,this._ref=void 0,this.$refNode=r,this.$refText=i}get ref(){return this.resolver.resolveReference(this,this.node,this.property)}get $nodeDescription(){return this._nodeDescription}get error(){return isLinkingError(this._ref)?this._ref:void 0}},DefaultMultiReferenceImpl=class{constructor(e,t,n,r,i){this.resolver=e,this.node=t,this.property=n,this._items=void 0,this.$refNode=r,this.$refText=i}get items(){return this.resolver.resolveMultiReference(this,this.node,this.property)}get error(){return this._linkingError}},DefaultLinker=class{constructor(e){this.reflection=e.shared.AstReflection,this.langiumDocuments=()=>e.shared.workspace.LangiumDocuments,this.scopeProvider=e.references.ScopeProvider,this.astNodeLocator=e.workspace.AstNodeLocator,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId,this.referenceResolver={resolveReference:this.resolveReference.bind(this),resolveMultiReference:this.resolveMultiReference.bind(this)}}async link(e,t=b.None){if(this.profiler?.isActive(`linking`)){let n=this.profiler.createTask(`linking`,this.languageId);n.start();try{for(let r of streamAst(e.parseResult.value))await interruptAndCheck(t),streamReferences(r).forEach(t=>{let i=`${r.$type}:${t.property}`;n.startSubTask(i);try{this.doLink(t,e)}finally{n.stopSubTask(i)}})}finally{n.stop()}}else for(let n of streamAst(e.parseResult.value))await interruptAndCheck(t),streamReferences(n).forEach(t=>this.doLink(t,e))}doLink(e,t){let n=e.reference;if(`_ref`in n&&n._ref===void 0){n._ref=pt;try{let t=this.getCandidate(e);isLinkingError(t)?n._ref=t:(n._nodeDescription=t,n._ref=this.loadAstNode(t)??this.createLinkingError(e,t))}catch(t){console.error(`An error occurred while resolving reference to '${n.$refText}':`,t);let r=t.message??String(t);n._ref={info:e,message:`An error occurred while resolving reference to '${n.$refText}': ${r}`}}t.references.push(n)}else if(`_items`in n&&n._items===void 0){n._items=pt;try{let t=this.getCandidates(e),r=[];if(isLinkingError(t))n._linkingError=t;else for(let e of t){let t=this.loadAstNode(e);t&&r.push({ref:t,$nodeDescription:e})}n._items=r}catch(t){n._linkingError={info:e,message:`An error occurred while resolving reference to '${n.$refText}': ${t}`},n._items=[]}t.references.push(n)}}unlink(e){for(let t of e.references)`_ref`in t?(t._ref=void 0,delete t._nodeDescription):`_items`in t&&(t._items=void 0,delete t._linkingError);e.references=[]}getCandidate(e){return this.scopeProvider.getScope(e).getElement(e.reference.$refText)??this.createLinkingError(e)}getCandidates(e){let t=this.scopeProvider.getScope(e).getElements(e.reference.$refText).distinct(e=>`${e.documentUri}#${e.path}`).toArray();return t.length>0?t:this.createLinkingError(e)}buildReference(e,t,n,r){return new DefaultReferenceImpl(this.referenceResolver,e,t,n,r)}buildMultiReference(e,t,n,r){return new DefaultMultiReferenceImpl(this.referenceResolver,e,t,n,r)}resolveReference(e,t,n){if(isAstNode(e._ref))return e._ref;if(isAstNodeDescription(e._nodeDescription))e._ref=this.loadAstNode(e._nodeDescription)??this.createLinkingError({reference:e,container:t,property:n},e._nodeDescription);else if(e._ref===void 0){e._ref=pt;let r=findRootNode(t).$document,i=this.getLinkedNode({reference:e,container:t,property:n});if(i.error&&r&&r.state<X.ComputedScopes){e._ref=void 0;return}e._ref=i.node??i.error,e._nodeDescription=i.descr,r?.references.push(e)}else e._ref===pt&&this.throwCyclicReferenceError(t,n,e.$refText);return isAstNode(e._ref)?e._ref:void 0}resolveMultiReference(e,t,n){if(Array.isArray(e._items))return e._items;if(e._items===void 0){e._items=pt;let r=findRootNode(t).$document,i=this.getCandidates({reference:e,container:t,property:n}),a=[];if(isLinkingError(i))e._linkingError=i;else{for(let e of i){let t=this.loadAstNode(e);t&&a.push({ref:t,$nodeDescription:e})}a.length===0&&(e._linkingError=this.createLinkingError({reference:e,container:t,property:n}))}e._items=a,r?.references.push(e)}else e._items===pt&&this.throwCyclicReferenceError(t,n,e.$refText);return Array.isArray(e._items)?e._items:[]}throwCyclicReferenceError(e,t,n){throw Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(e)}/${t} (symbol '${n}')`)}getLinkedNode(e){try{let t=this.getCandidate(e);if(isLinkingError(t))return{error:t};let n=this.loadAstNode(t);return n?{node:n,descr:t}:{descr:t,error:this.createLinkingError(e,t)}}catch(t){console.error(`An error occurred while resolving reference to '${e.reference.$refText}':`,t);let n=t.message??String(t);return{error:{info:e,message:`An error occurred while resolving reference to '${e.reference.$refText}': ${n}`}}}}loadAstNode(e){if(e.node)return e.node;let t=this.langiumDocuments().getDocument(e.documentUri);if(t)return this.astNodeLocator.getAstNode(t.parseResult.value,e.path)}createLinkingError(e,t){let n=findRootNode(e.container).$document;return n&&n.state<X.ComputedScopes&&console.warn(`Attempted reference resolution before document reached ComputedScopes state (${n.uri}).`),{info:e,message:`Could not resolve reference to ${this.reflection.getReferenceType(e)} named '${e.reference.$refText}'.`,targetDescription:t}}};function isNamed(e){return typeof e.name==`string`}var DefaultNameProvider=class{getName(e){if(isNamed(e))return e.name}getNameNode(e){return findNodeForProperty(e.$cstNode,`name`)}},DefaultReferences=class{constructor(e){this.nameProvider=e.references.NameProvider,this.index=e.shared.workspace.IndexManager,this.nodeLocator=e.workspace.AstNodeLocator,this.documents=e.shared.workspace.LangiumDocuments,this.hasMultiReference=streamAst(e.Grammar).some(e=>isCrossReference(e)&&e.isMulti)}findDeclarations(e){if(e){let t=findAssignment(e),n=e.astNode;if(t&&n){let r=n[t.feature];if(isReference(r)||isMultiReference(r))return getReferenceNodes(r);if(Array.isArray(r)){for(let t of r)if((isReference(t)||isMultiReference(t))&&t.$refNode&&t.$refNode.offset<=e.offset&&t.$refNode.end>=e.end)return getReferenceNodes(t)}}if(n){let t=this.nameProvider.getNameNode(n);if(t&&(t===e||isChildNode(e,t)))return this.getSelfNodes(n)}}return[]}getSelfNodes(e){if(this.hasMultiReference){let t=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e)),n=this.getNodeFromReferenceDescription(t.head());if(n){for(let t of streamReferences(n))if(isMultiReference(t.reference)&&t.reference.items.some(t=>t.ref===e))return t.reference.items.map(e=>e.ref)}return[e]}return[e]}getNodeFromReferenceDescription(e){if(!e)return;let t=this.documents.getDocument(e.sourceUri);if(t)return this.nodeLocator.getAstNode(t.parseResult.value,e.sourcePath)}findDeclarationNodes(e){let t=this.findDeclarations(e),n=[];for(let e of t){let t=this.nameProvider.getNameNode(e)??e.$cstNode;t&&n.push(t)}return n}findReferences(e,t){let n=[];t.includeDeclaration&&n.push(...this.getSelfReferences(e));let r=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e));return t.documentUri&&(r=r.filter(e=>J.equals(e.sourceUri,t.documentUri))),n.push(...r),stream(n)}getSelfReferences(e){let t=this.getSelfNodes(e),n=[];for(let e of t){let t=this.nameProvider.getNameNode(e);if(t){let r=getDocument(e),i=this.nodeLocator.getAstNodePath(e);n.push({sourceUri:r.uri,sourcePath:i,targetUri:r.uri,targetPath:i,segment:toDocumentSegment(t),local:!0})}}return n}},MultiMap=class{constructor(e){if(this.map=/* @__PURE__ */ new Map,e)for(let[t,n]of e)this.add(t,n)}get size(){return $e.sum(stream(this.map.values()).map(e=>e.length))}clear(){this.map.clear()}delete(e,t){if(t===void 0)return this.map.delete(e);{let n=this.map.get(e);if(n){let r=n.indexOf(t);if(r>=0)return n.length===1?this.map.delete(e):n.splice(r,1),!0}return!1}}get(e){return this.map.get(e)??[]}getStream(e){let t=this.map.get(e);return t?stream(t):G}has(e,t){if(t===void 0)return this.map.has(e);{let n=this.map.get(e);return n?n.indexOf(t)>=0:!1}}add(e,t){return this.map.has(e)?this.map.get(e).push(t):this.map.set(e,[t]),this}addAll(e,t){return this.map.has(e)?this.map.get(e).push(...t):this.map.set(e,Array.from(t)),this}forEach(e){this.map.forEach((t,n)=>t.forEach(t=>e(t,n,this)))}[Symbol.iterator](){return this.entries().iterator()}entries(){return stream(this.map.entries()).flatMap(([e,t])=>t.map(t=>[e,t]))}keys(){return stream(this.map.keys())}values(){return stream(this.map.values()).flat()}entriesGroupedByKey(){return stream(this.map.entries())}},BiMap=class{get size(){return this.map.size}constructor(e){if(this.map=/* @__PURE__ */ new Map,this.inverse=/* @__PURE__ */ new Map,e)for(let[t,n]of e)this.set(t,n)}clear(){this.map.clear(),this.inverse.clear()}set(e,t){return this.map.set(e,t),this.inverse.set(t,e),this}get(e){return this.map.get(e)}getKey(e){return this.inverse.get(e)}delete(e){let t=this.map.get(e);return t!==void 0&&(this.map.delete(e),this.inverse.delete(t),!0)}},DefaultScopeComputation=class{constructor(e){this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider}async collectExportedSymbols(e,t=b.None){return this.collectExportedSymbolsForNode(e.parseResult.value,e,void 0,t)}async collectExportedSymbolsForNode(e,t,n=streamContents,r=b.None){let i=[];this.addExportedSymbol(e,i,t);for(let a of n(e))await interruptAndCheck(r),this.addExportedSymbol(a,i,t);return i}addExportedSymbol(e,t,n){let r=this.nameProvider.getName(e);r&&t.push(this.descriptions.createDescription(e,r,n))}async collectLocalSymbols(e,t=b.None){let n=e.parseResult.value,r=new MultiMap;for(let i of streamAllContents(n))await interruptAndCheck(t),this.addLocalSymbol(i,e,r);return r}addLocalSymbol(e,t,n){let r=e.$container;if(r){let i=this.nameProvider.getName(e);i&&n.add(r,this.descriptions.createDescription(e,i,t))}}},StreamScope=class{constructor(e,t,n){this.elements=e,this.outerScope=t,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0}getAllElements(){return this.outerScope?this.elements.concat(this.outerScope.getAllElements()):this.elements}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.caseInsensitive?this.elements.find(e=>e.name.toLowerCase()===t):this.elements.find(t=>t.name===e);if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.caseInsensitive?this.elements.filter(e=>e.name.toLowerCase()===t):this.elements.filter(t=>t.name===e);return(this.concatOuterScope||n.isEmpty())&&this.outerScope?n.concat(this.outerScope.getElements(e)):n}},MapScope=class{constructor(e,t,n){this.elements=/* @__PURE__ */ new Map,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0;for(let t of e){let e=this.caseInsensitive?t.name.toLowerCase():t.name;this.elements.set(e,t)}this.outerScope=t}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t);if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t),r=n?[n]:[];return(this.concatOuterScope||r.length===0)&&this.outerScope?stream(r).concat(this.outerScope.getElements(e)):stream(r)}getAllElements(){let e=stream(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},MultiMapScope=class{constructor(e,t,n){this.elements=new MultiMap,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0;for(let t of e){let e=this.caseInsensitive?t.name.toLowerCase():t.name;this.elements.add(e,t)}this.outerScope=t}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t)[0];if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t);return(this.concatOuterScope||n.length===0)&&this.outerScope?stream(n).concat(this.outerScope.getElements(e)):stream(n)}getAllElements(){let e=stream(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}};const mt={getElement(){},getElements(){return G},getAllElements(){return G}};var DisposableCache=class{constructor(){this.toDispose=[],this.isDisposed=!1}onDispose(e){this.toDispose.push(e)}dispose(){this.throwIfDisposed(),this.clear(),this.isDisposed=!0,this.toDispose.forEach(e=>e.dispose())}throwIfDisposed(){if(this.isDisposed)throw Error(`This cache has already been disposed`)}},SimpleCache=class extends DisposableCache{constructor(){super(...arguments),this.cache=/* @__PURE__ */ new Map}has(e){return this.throwIfDisposed(),this.cache.has(e)}set(e,t){this.throwIfDisposed(),this.cache.set(e,t)}get(e,t){if(this.throwIfDisposed(),this.cache.has(e))return this.cache.get(e);if(t){let n=t();return this.cache.set(e,n),n}}delete(e){return this.throwIfDisposed(),this.cache.delete(e)}clear(){this.throwIfDisposed(),this.cache.clear()}},ContextCache=class extends DisposableCache{constructor(e){super(),this.cache=/* @__PURE__ */ new Map,this.converter=e??(e=>e)}has(e,t){return this.throwIfDisposed(),this.cacheForContext(e).has(t)}set(e,t,n){this.throwIfDisposed(),this.cacheForContext(e).set(t,n)}get(e,t,n){this.throwIfDisposed();let r=this.cacheForContext(e);if(r.has(t))return r.get(t);if(n){let e=n();return r.set(t,e),e}}delete(e,t){return this.throwIfDisposed(),this.cacheForContext(e).delete(t)}clear(e){if(this.throwIfDisposed(),e){let t=this.converter(e);this.cache.delete(t)}else this.cache.clear()}cacheForContext(e){let t=this.converter(e),n=this.cache.get(t);return n||(n=/* @__PURE__ */ new Map,this.cache.set(t,n)),n}},WorkspaceCache=class extends SimpleCache{constructor(e,t){super(),t?(this.toDispose.push(e.workspace.DocumentBuilder.onBuildPhase(t,()=>{this.clear()})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((e,t)=>{t.length>0&&this.clear()}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate(()=>{this.clear()}))}},DefaultScopeProvider=class{constructor(e){this.reflection=e.shared.AstReflection,this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider,this.indexManager=e.shared.workspace.IndexManager,this.globalScopeCache=new WorkspaceCache(e.shared)}getScope(e){let t=[],n=this.reflection.getReferenceType(e),r=getDocument(e.container).localSymbols;if(r){let i=e.container;do r.has(i)&&t.push(r.getStream(i).filter(e=>this.reflection.isSubtype(e.type,n))),i=i.$container;while(i)}let i=this.getGlobalScope(n,e);for(let e=t.length-1;e>=0;e--)i=this.createScope(t[e],i);return i}createScope(e,t,n){return new StreamScope(stream(e),t,n)}createScopeForNodes(e,t,n){return new StreamScope(stream(e).map(e=>{let t=this.nameProvider.getName(e);if(t)return this.descriptions.createDescription(e,t)}).nonNullable(),t,n)}getGlobalScope(e,t){return this.globalScopeCache.get(e,()=>new MultiMapScope(this.indexManager.allElements(e)))}};function isAstNodeWithComment(e){return typeof e.$comment==`string`}function isIntermediateReference(e){return typeof e==`object`&&!!e&&(`$ref`in e||`$refs`in e||`$error`in e)}var DefaultJsonSerializer=class{constructor(e){this.ignoreProperties=/* @__PURE__ */ new Set([`$container`,`$containerProperty`,`$containerIndex`,`$document`,`$cstNode`]),this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider,this.commentProvider=e.documentation.CommentProvider}serialize(e,t){let n=t??{},r=t?.replacer,defaultReplacer=(e,t)=>this.replacer(e,t,n),i=r?(e,t)=>r(e,t,defaultReplacer):defaultReplacer;try{return this.currentDocument=getDocument(e),JSON.stringify(e,i,t?.space)}finally{this.currentDocument=void 0}}deserialize(e,t){let n=t??{},r=JSON.parse(e);return this.linkNode(r,r,n),r}replacer(e,t,{refText:n,sourceText:r,textRegions:i,comments:a,uriConverter:o}){if(!this.ignoreProperties.has(e)){if(isReference(t)){let e=t.ref,r=n?t.$refText:void 0;if(e){let t=getDocument(e),n=``;this.currentDocument&&this.currentDocument!==t&&(n=o?o(t.uri,e):t.uri.toString());let i=this.astNodeLocator.getAstNodePath(e);return{$ref:`${n}#${i}`,$refText:r}}return{$error:t.error?.message??`Could not resolve reference`,$refText:r}}if(isMultiReference(t)){let e=n?t.$refText:void 0,r=[];for(let e of t.items){let t=e.ref,n=getDocument(e.ref),i=``;this.currentDocument&&this.currentDocument!==n&&(i=o?o(n.uri,t):n.uri.toString());let a=this.astNodeLocator.getAstNodePath(t);r.push(`${i}#${a}`)}return{$refs:r,$refText:e}}if(isAstNode(t)){let n;if(i&&(n=this.addAstNodeRegionWithAssignmentsTo({...t}),(!e||t.$document)&&n?.$textRegion&&(n.$textRegion.documentURI=this.currentDocument?.uri.toString())),r&&!e&&(n??={...t},n.$sourceText=t.$cstNode?.text),a){n??={...t};let e=this.commentProvider.getComment(t);e&&(n.$comment=e.replace(/\r/g,``))}return n??t}return t}}addAstNodeRegionWithAssignmentsTo(e){let createDocumentSegment=e=>({offset:e.offset,end:e.end,length:e.length,range:e.range});if(e.$cstNode){let t=e.$textRegion=createDocumentSegment(e.$cstNode),n=t.assignments={};return Object.keys(e).filter(e=>!e.startsWith(`$`)).forEach(t=>{let r=findNodesForProperty(e.$cstNode,t).map(createDocumentSegment);r.length!==0&&(n[t]=r)}),e}}linkNode(e,t,n,r,i,a){for(let[r,i]of Object.entries(e))if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];isIntermediateReference(o)?i[a]=this.reviveReference(e,r,t,o,n):isAstNode(o)&&this.linkNode(o,t,n,e,r,a)}else isIntermediateReference(i)?e[r]=this.reviveReference(e,r,t,i,n):isAstNode(i)&&this.linkNode(i,t,n,e,r);let o=e;o.$container=r,o.$containerProperty=i,o.$containerIndex=a}reviveReference(e,t,n,r,i){let a=r.$refText,o=r.$error,s;if(r.$ref){let e=this.getRefNode(n,r.$ref,i.uriConverter);if(isAstNode(e))return a||=this.nameProvider.getName(e),{$refText:a??``,ref:e};o=e}else if(r.$refs){let e=[];for(let t of r.$refs){let r=this.getRefNode(n,t,i.uriConverter);isAstNode(r)&&e.push({ref:r})}if(e.length===0)s={$refText:a??``,items:e},o??=`Could not resolve multi-reference`;else return{$refText:a??``,items:e}}if(o)return s??={$refText:a??``,ref:void 0},s.error={info:{container:e,property:t,reference:s},message:o},s}getRefNode(e,t,n){try{let r=t.indexOf(`#`);if(r===0)return this.astNodeLocator.getAstNode(e,t.substring(1))||`Could not resolve path: `+t;if(r<0){let e=n?n(t):de.parse(t),r=this.langiumDocuments.getDocument(e);return r?r.parseResult.value:`Could not find document for URI: `+t}let i=n?n(t.substring(0,r)):de.parse(t.substring(0,r)),a=this.langiumDocuments.getDocument(i);return a?r===t.length-1?a.parseResult.value:this.astNodeLocator.getAstNode(a.parseResult.value,t.substring(r+1))||`Could not resolve URI: `+t:`Could not find document for URI: `+t}catch(e){return String(e)}}},DefaultServiceRegistry=class{get map(){return this.fileExtensionMap}constructor(e){this.languageIdMap=/* @__PURE__ */ new Map,this.fileExtensionMap=/* @__PURE__ */ new Map,this.fileNameMap=/* @__PURE__ */ new Map,this.textDocuments=e?.workspace.TextDocuments}register(e){let t=e.LanguageMetaData;for(let n of t.fileExtensions)this.fileExtensionMap.has(n)&&console.warn(`The file extension ${n} is used by multiple languages. It is now assigned to '${t.languageId}'.`),this.fileExtensionMap.set(n,e);if(t.fileNames)for(let n of t.fileNames)this.fileNameMap.has(n)&&console.warn(`The file name ${n} is used by multiple languages. It is now assigned to '${t.languageId}'.`),this.fileNameMap.set(n,e);this.languageIdMap.set(t.languageId,e)}getServices(e){if(this.languageIdMap.size===0)throw Error("The service registry is empty. Use `register` to register the services of a language.");let t=this.textDocuments?.get(e)?.languageId;if(t!==void 0){let e=this.languageIdMap.get(t);if(e)return e}let n=J.extname(e),r=J.basename(e),i=this.fileNameMap.get(r)??this.fileExtensionMap.get(n);if(!i)throw Error(t?`The service registry contains no services for the extension '${n}' for language '${t}'.`:`The service registry contains no services for the extension '${n}'.`);return i}hasServices(e){try{return this.getServices(e),!0}catch{return!1}}get all(){return Array.from(this.languageIdMap.values())}},ht;(function(e){e.merge=(e,t)=>_merge(_merge({},e),t)})(ht||={});function inject(e,t,n,r,i,a,o,s,c){return _inject([e,t,n,r,i,a,o,s,c].reduce(_merge,{}))}const gt=Symbol(`isProxy`);function eagerLoad(e){if(e&&e[gt])for(let t of Object.values(e))eagerLoad(t);return e}function _inject(e,t){let n=new Proxy({},{deleteProperty:()=>!1,set:()=>{throw Error(`Cannot set property on injected service container`)},get:(r,i)=>i===gt||_resolve(r,i,e,t||n),getOwnPropertyDescriptor:(r,i)=>(_resolve(r,i,e,t||n),Object.getOwnPropertyDescriptor(r,i)),has:(t,n)=>n in e,ownKeys:()=>[...Object.getOwnPropertyNames(e)]});return n}const _t=Symbol();function _resolve(e,t,n,r){if(t in e){if(e[t]instanceof Error)throw Error(`Construction failure. Please make sure that your dependencies are constructable. Cause: `+e[t]);if(e[t]===_t)throw Error(`Cycle detected. Please make "`+String(t)+`" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies`);return e[t]}if(t in n){let i=n[t];e[t]=_t;try{e[t]=typeof i==`function`?i(r):_inject(i,r)}catch(n){throw e[t]=n instanceof Error?n:void 0,n}return e[t]}}function _merge(e,t){if(t){for(let[n,r]of Object.entries(t))if(n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&r!=null){if(typeof r==`object`){let t=e[n];e[n]=_merge(typeof t==`object`&&t?t:{},r)}else e[n]=r}}return e}var DefaultCommentProvider=class{constructor(e){this.grammarConfig=()=>e.parser.GrammarConfig}getComment(e){return isAstNodeWithComment(e)?e.$comment:findCommentNode(e.$cstNode,this.grammarConfig().multilineCommentRules)?.text}};function parseJSDoc(e,t,n){let r,i;typeof e==`string`?(i=t,r=n):(i=e.range.start,r=t),i||=x.create(0,0);let a=getLines(e),o=normalizeOptions(r);return parseJSDocComment({index:0,tokens:tokenize({lines:a,position:i,options:o}),position:i})}function isJSDoc(e,t){let n=normalizeOptions(t),r=getLines(e);if(r.length===0)return!1;let i=r[0],a=r[r.length-1],o=n.start,s=n.end;return!!o?.exec(i)&&!!s?.exec(a)}function getLines(e){let t=``;return t=typeof e==`string`?e:e.text,t.split(rt)}const vt=/\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy,yt=/\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;function tokenize(e){let t=[],n=e.position.line,r=e.position.character;for(let i=0;i<e.lines.length;i++){let a=i===0,o=i===e.lines.length-1,s=e.lines[i],c=0;if(a&&e.options.start){let t=e.options.start?.exec(s);t&&(c=t.index+t[0].length)}else{let t=e.options.line?.exec(s);t&&(c=t.index+t[0].length)}if(o){let t=e.options.end?.exec(s);t&&(s=s.substring(0,t.index))}if(s=s.substring(0,lastCharacter(s)),skipWhitespace(s,c)>=s.length){if(t.length>0){let e=x.create(n,r);t.push({type:`break`,content:``,range:S.create(e,e)})}}else{vt.lastIndex=c;let e=vt.exec(s);if(e){let i=e[0],a=e[1],o=x.create(n,r+c),l=x.create(n,r+c+i.length);t.push({type:`tag`,content:a,range:S.create(o,l)}),c+=i.length,c=skipWhitespace(s,c)}if(c<s.length){let e=s.substring(c),i=Array.from(e.matchAll(yt));t.push(...buildInlineTokens(i,e,n,r+c))}}n++,r=0}return t.length>0&&t[t.length-1].type===`break`?t.slice(0,-1):t}function buildInlineTokens(e,t,n,r){let i=[];if(e.length===0){let e=x.create(n,r),a=x.create(n,r+t.length);i.push({type:`text`,content:t,range:S.create(e,a)})}else{let a=0;for(let o of e){let e=o.index,s=t.substring(a,e);s.length>0&&i.push({type:`text`,content:t.substring(a,e),range:S.create(x.create(n,a+r),x.create(n,e+r))});let c=s.length+1,l=o[1];if(i.push({type:`inline-tag`,content:l,range:S.create(x.create(n,a+c+r),x.create(n,a+c+l.length+r))}),c+=l.length,o.length===4){c+=o[2].length;let e=o[3];i.push({type:`text`,content:e,range:S.create(x.create(n,a+c+r),x.create(n,a+c+e.length+r))})}else i.push({type:`text`,content:``,range:S.create(x.create(n,a+c+r),x.create(n,a+c+r))});a=e+o[0].length}let o=t.substring(a);o.length>0&&i.push({type:`text`,content:o,range:S.create(x.create(n,a+r),x.create(n,a+r+o.length))})}return i}const bt=/\S/,xt=/\s*$/;function skipWhitespace(e,t){let n=e.substring(t).match(bt);return n?t+n.index:e.length}function lastCharacter(e){let t=e.match(xt);if(t&&typeof t.index==`number`)return t.index}function parseJSDocComment(e){let t=x.create(e.position.line,e.position.character);if(e.tokens.length===0)return new JSDocCommentImpl([],S.create(t,t));let n=[];for(;e.index<e.tokens.length;){let t=parseJSDocElement(e,n[n.length-1]);t&&n.push(t)}let r=n[0]?.range.start??t,i=n[n.length-1]?.range.end??t;return new JSDocCommentImpl(n,S.create(r,i))}function parseJSDocElement(e,t){let n=e.tokens[e.index];if(n.type===`tag`)return parseJSDocTag(e,!1);if(n.type===`text`||n.type===`inline-tag`)return parseJSDocText(e);appendEmptyLine(n,t),e.index++}function appendEmptyLine(e,t){if(t){let n=new JSDocLineImpl(``,e.range);`inlines`in t?t.inlines.push(n):t.content.inlines.push(n)}}function parseJSDocText(e){let t=e.tokens[e.index],n=t,r=t,i=[];for(;t&&t.type!==`break`&&t.type!==`tag`;)i.push(parseJSDocInline(e)),r=t,t=e.tokens[e.index];return new JSDocTextImpl(i,S.create(n.range.start,r.range.end))}function parseJSDocInline(e){return e.tokens[e.index].type===`inline-tag`?parseJSDocTag(e,!0):parseJSDocLine(e)}function parseJSDocTag(e,t){let n=e.tokens[e.index++],r=n.content.substring(1);if(e.tokens[e.index]?.type===`text`){if(t){let i=parseJSDocLine(e);return new JSDocTagImpl(r,new JSDocTextImpl([i],i.range),t,S.create(n.range.start,i.range.end))}{let i=parseJSDocText(e);return new JSDocTagImpl(r,i,t,S.create(n.range.start,i.range.end))}}{let e=n.range;return new JSDocTagImpl(r,new JSDocTextImpl([],e),t,e)}}function parseJSDocLine(e){let t=e.tokens[e.index++];return new JSDocLineImpl(t.content,t.range)}function normalizeOptions(e){if(!e)return normalizeOptions({start:`/**`,end:`*/`,line:`*`});let{start:t,end:n,line:r}=e;return{start:normalizeOption(t,!0),end:normalizeOption(n,!1),line:normalizeOption(r,!0)}}function normalizeOption(e,t){if(typeof e==`string`||typeof e==`object`){let n=typeof e==`string`?escapeRegExp(e):e.source;return RegExp(t?`^\\s*${n}`:`\\s*${n}\\s*$`)}return e}var JSDocCommentImpl=class{constructor(e,t){this.elements=e,this.range=t}getTag(e){return this.getAllTags().find(t=>t.name===e)}getTags(e){return this.getAllTags().filter(t=>t.name===e)}getAllTags(){return this.elements.filter(e=>`name`in e)}toString(){let e=``;for(let t of this.elements)if(e.length===0)e=t.toString();else{let n=t.toString();e+=fillNewlines(e)+n}return e.trim()}toMarkdown(e){let t=``;for(let n of this.elements)if(t.length===0)t=n.toMarkdown(e);else{let r=n.toMarkdown(e);t+=fillNewlines(t)+r}return t.trim()}},JSDocTagImpl=class{constructor(e,t,n,r){this.name=e,this.content=t,this.inline=n,this.range=r}toString(){let e=`@${this.name}`,t=this.content.toString();return this.content.inlines.length===1?e=`${e} ${t}`:this.content.inlines.length>1&&(e=`${e}\n${t}`),this.inline?`{${e}}`:e}toMarkdown(e){return e?.renderTag?.(this)??this.toMarkdownDefault(e)}toMarkdownDefault(e){let t=this.content.toMarkdown(e);if(this.inline){let n=renderInlineTag(this.name,t,e??{});if(typeof n==`string`)return n}let n=``;e?.tag===`italic`||e?.tag===void 0?n=`*`:e?.tag===`bold`?n=`**`:e?.tag===`bold-italic`&&(n=`***`);let r=`${n}@${this.name}${n}`;return this.content.inlines.length===1?r=`${r} — ${t}`:this.content.inlines.length>1&&(r=`${r}\n${t}`),this.inline?`{${r}}`:r}};function renderInlineTag(e,t,n){if(e===`linkplain`||e===`linkcode`||e===`link`){let r=t.indexOf(` `),i=t;if(r>0){let e=skipWhitespace(t,r);i=t.substring(e),t=t.substring(0,r)}return(e===`linkcode`||e===`link`&&n.link===`code`)&&(i=`\`${i}\``),n.renderLink?.(t,i)??renderLinkDefault(t,i)}}function renderLinkDefault(e,t){try{return y.parse(e,!0),`[${t}](${e})`}catch{return e}}var JSDocTextImpl=class{constructor(e,t){this.inlines=e,this.range=t}toString(){let e=``;for(let t=0;t<this.inlines.length;t++){let n=this.inlines[t],r=this.inlines[t+1];e+=n.toString(),r&&r.range.start.line>n.range.start.line&&(e+=`
6
+ `)}return e}toMarkdown(e){let t=``;for(let n=0;n<this.inlines.length;n++){let r=this.inlines[n],i=this.inlines[n+1];t+=r.toMarkdown(e),i&&i.range.start.line>r.range.start.line&&(t+=`
7
+ `)}return t}},JSDocLineImpl=class{constructor(e,t){this.text=e,this.range=t}toString(){return this.text}toMarkdown(){return this.text}};function fillNewlines(e){return e.endsWith(`
8
+ `)?`
9
+ `:`
10
+
11
+ `}var JSDocDocumentationProvider=class{constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let t=this.commentProvider.getComment(e);if(t&&isJSDoc(t))return parseJSDoc(t).toMarkdown({renderLink:(t,n)=>this.documentationLinkRenderer(e,t,n),renderTag:t=>this.documentationTagRenderer(e,t)})}documentationLinkRenderer(e,t,n){let r=this.findNameInLocalSymbols(e,t)??this.findNameInGlobalScope(e,t);if(r&&r.nameSegment){let e=r.nameSegment.range.start.line+1,t=r.nameSegment.range.start.character+1;return`[${n}](${r.documentUri.with({fragment:`L${e},${t}`}).toString()})`}}documentationTagRenderer(e,t){}findNameInLocalSymbols(e,t){let n=getDocument(e).localSymbols;if(!n)return;let r=e;do{let e=n.getStream(r).find(e=>e.name===t);if(e)return e;r=r.$container}while(r)}findNameInGlobalScope(e,t){return this.indexManager.allElements().find(e=>e.name===t)}},DefaultAsyncParser=class{constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,t){return Promise.resolve(this.syncParser.parse(e))}},DefaultLexerErrorMessageProvider=class{buildUnexpectedCharactersMessage(e,t,n,r,i){return u.buildUnexpectedCharactersMessage(e,t,n,r,i)}buildUnableToPopLexerModeMessage(e){return u.buildUnableToPopLexerModeMessage(e)}};const St={mode:`full`};var DefaultLexer=class{constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let t=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(t);let n=isTokenTypeDictionary(t)?Object.values(t):t,r=e.LanguageMetaData.mode===`production`;this.chevrotainLexer=new a(n,{positionTracking:`full`,skipValidations:r,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,t=St){let n=this.chevrotainLexer.tokenize(e);return{tokens:n.tokens,errors:n.errors,hidden:n.groups.hidden??[],report:this.tokenBuilder.flushLexingReport?.(e)}}toTokenTypeDictionary(e){if(isTokenTypeDictionary(e))return e;let t=isIMultiModeLexerDefinition(e)?Object.values(e.modes).flat():e,n={};return t.forEach(e=>n[e.name]=e),n}};function isTokenTypeArray(e){return Array.isArray(e)&&(e.length===0||`name`in e[0])}function isIMultiModeLexerDefinition(e){return e&&`modes`in e&&`defaultMode`in e}function isTokenTypeDictionary(e){return!isTokenTypeArray(e)&&!isIMultiModeLexerDefinition(e)}var DefaultHydrator=class{constructor(e){this.grammarElementIdMap=new BiMap,this.tokenTypeIdMap=new BiMap,this.cstNodeBuilder=new CstNodeBuilder,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(e=>({...e,message:e.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode))n.set(t,{});return{astNodes:t,cstNodes:n}}dehydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(n.$cstNode=this.dehydrateCstNode(e.$cstNode,t));for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let n of i)isAstNode(n)?e.push(this.dehydrateAstNode(n,t)):isReference(n)?e.push(this.dehydrateReference(n,t)):e.push(n)}else isAstNode(i)?n[r]=this.dehydrateAstNode(i,t):isReference(i)?n[r]=this.dehydrateReference(i,t):i!==void 0&&(n[r]=i)}return n}dehydrateReference(e,t){let n={};return n.$refText=e.$refText,e.$refNode&&(n.$refNode=t.cstNodes.get(e.$refNode)),n}dehydrateCstNode(e,t){let n=t.cstNodes.get(e);if(isRootCstNode(e)?n.fullText=e.fullText:n.grammarSource=this.getGrammarElementId(e.grammarSource),n.hidden=e.hidden,isCompositeCstNode(e))n.content=e.content.map(e=>this.dehydrateCstNode(e,t));else if(isLeafCstNode(e)){n.tokenType=e.tokenType.name,n.offset=e.offset,n.length=e.length;let{start:t,end:r}=e.range;n.startLine=t.line,n.startColumn=t.character,n.endLine=r.line,n.endColumn=r.character}return n}hydrate(e){let t=e.value,n=this.createHydrationContext(t);return`$cstNode`in t&&this.hydrateCstNode(t.$cstNode,n),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(t,n)}}createHydrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode)){let e;`fullText`in t?e=new RootCstNodeImpl(t.fullText):`content`in t?e=new CompositeCstNodeImpl:`tokenType`in t&&(e=this.hydrateCstLeafNode(t)),e&&n.set(t,e)}return{astNodes:t,cstNodes:n,linkedCstNodes:/* @__PURE__ */ new Set}}hydrateAstNode(e,t){let n=t.astNodes.get(e);if(n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode){let r=t.cstNodes.get(e.$cstNode);n.$cstNode=r,r&&!t.linkedCstNodes.has(r)&&(t.linkedCstNodes.add(r),r.astNode=n)}for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let a of i)isAstNode(a)?e.push(this.setParent(this.hydrateAstNode(a,t),n)):isReference(a)?e.push(this.hydrateReference(a,n,r,t)):e.push(a)}else isAstNode(i)?n[r]=this.setParent(this.hydrateAstNode(i,t),n):isReference(i)?n[r]=this.hydrateReference(i,n,r,t):i!==void 0&&(n[r]=i)}return n}setParent(e,t){return e.$container=t,e}hydrateReference(e,t,n,r){return this.linker.buildReference(t,n,r.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,t,n=0){let r=t.cstNodes.get(e);if(typeof e.grammarSource==`number`&&(r.grammarSource=this.getGrammarElement(e.grammarSource)),isCompositeCstNode(r)){let i=[];for(let r of e.content)i.push(this.hydrateCstNode(r,t,n++));this.cstNodeBuilder.appendChildren(r,i)}return r}hydrateCstLeafNode(e){let t=this.getTokenType(e.tokenType);return new LeafCstNodeImpl(e.offset,e.length,e.startLine,e.startColumn,e.endLine,e.endColumn,t,e.hidden)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let t of streamAst(this.grammar))isAbstractElement(t)&&this.grammarElementIdMap.set(t,e++)}},Ct;(function(e){function create(e){return{dispose:async()=>await e()}}e.create=create})(Ct||={});var EmptyFileSystemProvider=class{stat(e){throw Error(`No file system is available.`)}statSync(e){throw Error(`No file system is available.`)}async exists(){return!1}existsSync(){return!1}readBinary(){throw Error(`No file system is available.`)}readBinarySync(){throw Error(`No file system is available.`)}readFile(){throw Error(`No file system is available.`)}readFileSync(){throw Error(`No file system is available.`)}async readDirectory(){return[]}readDirectorySync(){return[]}};const wt={fileSystemProvider:()=>new EmptyFileSystemProvider},Tt={Grammar:()=>void 0,LanguageMetaData:()=>({caseInsensitive:!1,fileExtensions:[`.langium`],languageId:`langium`})},Et={AstReflection:()=>new LangiumGrammarAstReflection};function createMinimalGrammarServices(){let e=inject(createDefaultSharedCoreModule(wt),Et),t=inject(createDefaultCoreModule({shared:e}),Tt);return e.ServiceRegistry.register(t),t}function loadGrammarFromJson(e){let t=createMinimalGrammarServices(),n=t.serializer.JsonSerializer.deserialize(e);return t.shared.workspace.LangiumDocumentFactory.fromModel(n,y.parse(`memory:/${n.name??`grammar`}.langium`)),n}var DefaultAstNodeDescriptionProvider=class{constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,t,n){let r=n??getDocument(e);t??=this.nameProvider.getName(e);let i=this.astNodeLocator.getAstNodePath(e);if(!t)throw Error(`Node at path ${i} has no name.`);let a,nameSegmentGetter=()=>a??=toDocumentSegment(this.nameProvider.getNameNode(e)??e.$cstNode);return{node:e,name:t,get nameSegment(){return nameSegmentGetter()},selectionSegment:toDocumentSegment(e.$cstNode),type:e.$type,documentUri:r.uri,path:i}}},DefaultReferenceDescriptionProvider=class{constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,t=b.None){let n=[],r=e.parseResult.value;for(let e of streamAst(r))await interruptAndCheck(t),streamReferences(e).forEach(e=>{e.reference.error||n.push(...this.createInfoDescriptions(e))});return n}createInfoDescriptions(e){let t=e.reference;if(t.error||!t.$refNode)return[];let n=[];isReference(t)&&t.$nodeDescription?n=[t.$nodeDescription]:isMultiReference(t)&&(n=t.items.map(e=>e.$nodeDescription).filter(e=>e!==void 0));let r=getDocument(e.container).uri,i=this.nodeLocator.getAstNodePath(e.container),a=[],o=toDocumentSegment(t.$refNode);for(let e of n)a.push({sourceUri:r,sourcePath:i,targetUri:e.documentUri,targetPath:e.path,segment:o,local:J.equals(e.documentUri,r)});return a}},DefaultAstNodeLocator=class{constructor(){this.segmentSeparator=`/`,this.indexSeparator=`@`}getAstNodePath(e){if(e.$container){let t=this.getAstNodePath(e.$container),n=this.getPathSegment(e);return t+this.segmentSeparator+n}return``}getPathSegment({$containerProperty:e,$containerIndex:t}){if(!e)throw Error(`Missing '$containerProperty' in AST node.`);return t===void 0?e:e+this.indexSeparator+t}getAstNode(e,t){return t.split(this.segmentSeparator).reduce((e,t)=>{if(!e||t.length===0)return e;let n=t.indexOf(this.indexSeparator);if(n>0){let r=t.substring(0,n),i=parseInt(t.substring(n+1));return e[r]?.[i]}return e[t]},e)}},DefaultConfigurationProvider=class{constructor(e){this._ready=new Deferred,this.onConfigurationSectionUpdateEmitter=new ge,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){this.workspaceConfig=e.capabilities.workspace?.configuration??!1}async initialized(e){if(this.workspaceConfig){if(e.register){let t=this.serviceRegistry.all;e.register({section:t.map(e=>this.toSectionName(e.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let t=this.serviceRegistry.all.map(e=>({section:this.toSectionName(e.LanguageMetaData.languageId)})),n=await e.fetchConfiguration(t);t.forEach((e,t)=>{this.updateSectionConfiguration(e.section,n[t])})}}this._ready.resolve()}updateConfiguration(e){typeof e.settings==`object`&&e.settings!==null&&Object.entries(e.settings).forEach(([e,t])=>{this.updateSectionConfiguration(e,t),this.onConfigurationSectionUpdateEmitter.fire({section:e,configuration:t})})}updateSectionConfiguration(e,t){this.settings[e]=t}async getConfiguration(e,t){await this.ready;let n=this.toSectionName(e);if(this.settings[n])return this.settings[n][t]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}},DefaultDocumentBuilder=class{constructor(e){this.updateBuildOptions={validation:{categories:[`built-in`,`fast`]}},this.updateListeners=[],this.buildPhaseListeners=new MultiMap,this.documentPhaseListeners=new MultiMap,this.buildState=/* @__PURE__ */ new Map,this.documentBuildWaiters=/* @__PURE__ */ new Map,this.currentState=X.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.fileSystemProvider=e.workspace.FileSystemProvider,this.workspaceManager=()=>e.workspace.WorkspaceManager,this.serviceRegistry=e.ServiceRegistry}async build(e,t={},n=b.None){for(let n of e){let e=n.uri.toString();if(n.state===X.Validated){if(typeof t.validation==`boolean`&&t.validation)this.resetToState(n,X.IndexedReferences);else if(typeof t.validation==`object`){let r=this.findMissingValidationCategories(n,t);r.length>0&&(this.buildState.set(e,{completed:!1,options:{validation:{categories:r}},result:this.buildState.get(e)?.result}),n.state=X.IndexedReferences)}}else this.buildState.delete(e)}this.currentState=X.Changed,await this.emitUpdate(e.map(e=>e.uri),[]),await this.buildDocuments(e,t,n)}async update(e,t,n=b.None){this.currentState=X.Changed;let r=[];for(let e of t){let t=this.langiumDocuments.deleteDocuments(e);for(let e of t)r.push(e.uri),this.cleanUpDeleted(e)}let i=(await Promise.all(e.map(e=>this.findChangedUris(e)))).flat();for(let e of i){let t=this.langiumDocuments.getDocument(e);t===void 0&&(t=this.langiumDocumentFactory.fromModel({$type:`INVALID`},e),t.state=X.Changed,this.langiumDocuments.addDocument(t)),this.resetToState(t,X.Changed)}let a=stream(i).concat(r).map(e=>e.toString()).toSet();this.langiumDocuments.all.filter(e=>!a.has(e.uri.toString())&&this.shouldRelink(e,a)).forEach(e=>this.resetToState(e,X.ComputedScopes)),await this.emitUpdate(i,r),await interruptAndCheck(n);let o=this.sortDocuments(this.langiumDocuments.all.filter(e=>e.state<X.Validated||!this.buildState.get(e.uri.toString())?.completed||this.resultsAreIncomplete(e,this.updateBuildOptions)).toArray());await this.buildDocuments(o,this.updateBuildOptions,n)}resultsAreIncomplete(e,t){return this.findMissingValidationCategories(e,t).length>=1}findMissingValidationCategories(e,t){let n=this.buildState.get(e.uri.toString()),r=this.serviceRegistry.getServices(e.uri).validation.ValidationRegistry.getAllValidationCategories(e),i=n?.result?.validationChecks?new Set(n?.result?.validationChecks):n?.completed?r:/* @__PURE__ */ new Set;return stream(t===void 0||t.validation===!0?r:typeof t.validation==`object`?t.validation.categories??r:[]).filter(e=>!i.has(e)).toArray()}async findChangedUris(e){if(this.langiumDocuments.getDocument(e)??this.textDocuments?.get(e))return[e];try{let t=await this.fileSystemProvider.stat(e);if(t.isDirectory)return await this.workspaceManager().searchFolder(e);if(this.workspaceManager().shouldIncludeEntry(t))return[e]}catch{}return[]}async emitUpdate(e,t){await Promise.all(this.updateListeners.map(n=>n(e,t)))}sortDocuments(e){let t=0,n=e.length-1;for(;t<n;){for(;t<e.length&&this.hasTextDocument(e[t]);)t++;for(;n>=0&&!this.hasTextDocument(e[n]);)n--;t<n&&([e[t],e[n]]=[e[n],e[t]])}return e}hasTextDocument(e){return!!this.textDocuments?.get(e.uri)}shouldRelink(e,t){return e.references.some(e=>e.error!==void 0)?!0:this.indexManager.isAffected(e,t)}onUpdate(e){return this.updateListeners.push(e),Ct.create(()=>{let t=this.updateListeners.indexOf(e);t>=0&&this.updateListeners.splice(t,1)})}resetToState(e,t){switch(t){case X.Changed:case X.Parsed:this.indexManager.removeContent(e.uri);case X.IndexedContent:e.localSymbols=void 0;case X.ComputedScopes:this.serviceRegistry.getServices(e.uri).references.Linker.unlink(e);case X.Linked:this.indexManager.removeReferences(e.uri);case X.IndexedReferences:e.diagnostics=void 0,this.buildState.delete(e.uri.toString());case X.Validated:}e.state>t&&(e.state=t)}cleanUpDeleted(e){this.buildState.delete(e.uri.toString()),this.indexManager.remove(e.uri),e.state=X.Changed}async buildDocuments(e,t,n){this.prepareBuild(e,t),await this.runCancelable(e,X.Parsed,n,e=>this.langiumDocumentFactory.update(e,n)),await this.runCancelable(e,X.IndexedContent,n,e=>this.indexManager.updateContent(e,n)),await this.runCancelable(e,X.ComputedScopes,n,async e=>{e.localSymbols=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectLocalSymbols(e,n)});let r=e.filter(e=>this.shouldLink(e));await this.runCancelable(r,X.Linked,n,e=>this.serviceRegistry.getServices(e.uri).references.Linker.link(e,n)),await this.runCancelable(r,X.IndexedReferences,n,e=>this.indexManager.updateReferences(e,n));let i=e.filter(e=>this.shouldValidate(e)?!0:(this.markAsCompleted(e),!1));await this.runCancelable(i,X.Validated,n,async e=>{await this.validate(e,n),this.markAsCompleted(e)})}markAsCompleted(e){let t=this.buildState.get(e.uri.toString());t&&(t.completed=!0)}prepareBuild(e,t){for(let n of e){let e=n.uri.toString(),r=this.buildState.get(e);(!r||r.completed)&&this.buildState.set(e,{completed:!1,options:t,result:r?.result})}}async runCancelable(e,t,n,r){for(let i of e)i.state<t&&(await interruptAndCheck(n),await r(i),i.state=t,await this.notifyDocumentPhase(i,t,n));let i=e.filter(e=>e.state===t);await this.notifyBuildPhase(i,t,n),this.currentState=t}onBuildPhase(e,t){return this.buildPhaseListeners.add(e,t),Ct.create(()=>{this.buildPhaseListeners.delete(e,t)})}onDocumentPhase(e,t){return this.documentPhaseListeners.add(e,t),Ct.create(()=>{this.documentPhaseListeners.delete(e,t)})}waitUntil(e,t,n){let r;return t&&`path`in t?r=t:n=t,n??=b.None,r?this.awaitDocumentState(e,r,n):this.awaitBuilderState(e,n)}awaitDocumentState(e,t,n){let r=this.langiumDocuments.getDocument(t);return r?r.state>=e?Promise.resolve(t):n.isCancellationRequested?Promise.reject(ft):this.currentState>=e&&e>r.state?Promise.reject(new ve(_e.RequestFailed,`Document state of ${t.toString()} is ${X[r.state]}, requiring ${X[e]}, but workspace state is already ${X[this.currentState]}. Returning undefined.`)):new Promise((r,i)=>{let a=this.onDocumentPhase(e,e=>{J.equals(e.uri,t)&&(a.dispose(),o.dispose(),r(e.uri))}),o=n.onCancellationRequested(()=>{a.dispose(),o.dispose(),i(ft)})}):Promise.reject(new ve(_e.ServerCancelled,`No document found for URI: ${t.toString()}`))}awaitBuilderState(e,t){return this.currentState>=e?Promise.resolve():t.isCancellationRequested?Promise.reject(ft):new Promise((n,r)=>{let i=this.onBuildPhase(e,()=>{i.dispose(),a.dispose(),n()}),a=t.onCancellationRequested(()=>{i.dispose(),a.dispose(),r(ft)})})}async notifyDocumentPhase(e,t,n){let r=this.documentPhaseListeners.get(t).slice();for(let t of r)try{await interruptAndCheck(n),await t(e,n)}catch(e){if(!isOperationCancelled(e))throw e}}async notifyBuildPhase(e,t,n){if(e.length===0)return;let r=this.buildPhaseListeners.get(t).slice();for(let t of r)await interruptAndCheck(n),await t(e,n)}shouldLink(e){return this.getBuildOptions(e).eagerLinking??!0}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,t){let n=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,r=this.getBuildOptions(e),i=typeof r.validation==`object`?{...r.validation}:{};i.categories=this.findMissingValidationCategories(e,r);let a=await n.validateDocument(e,i,t);e.diagnostics?e.diagnostics.push(...a):e.diagnostics=a;let o=this.buildState.get(e.uri.toString());o&&(o.result??={},o.result.validationChecks?o.result.validationChecks=stream(o.result.validationChecks).concat(i.categories).distinct().toArray():o.result.validationChecks=[...i.categories])}getBuildOptions(e){return this.buildState.get(e.uri.toString())?.options??{}}},DefaultIndexManager=class{constructor(e){this.symbolIndex=/* @__PURE__ */ new Map,this.symbolByTypeIndex=new ContextCache,this.referenceIndex=/* @__PURE__ */ new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,t){let n=getDocument(e).uri,r=[];return this.referenceIndex.forEach(e=>{e.forEach(e=>{J.equals(e.targetUri,n)&&e.targetPath===t&&r.push(e)})}),stream(r)}allElements(e,t){let n=stream(this.symbolIndex.keys());return t&&(n=n.filter(e=>!t||t.has(e))),n.map(t=>this.getFileDescriptions(t,e)).flat()}getFileDescriptions(e,t){return t?this.symbolByTypeIndex.get(e,t,()=>(this.symbolIndex.get(e)??[]).filter(e=>this.astReflection.isSubtype(e.type,t))):this.symbolIndex.get(e)??[]}remove(e){this.removeContent(e),this.removeReferences(e)}removeContent(e){let t=e.toString();this.symbolIndex.delete(t),this.symbolByTypeIndex.clear(t)}removeReferences(e){let t=e.toString();this.referenceIndex.delete(t)}async updateContent(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectExportedSymbols(e,t),r=e.uri.toString();this.symbolIndex.set(r,n),this.symbolByTypeIndex.clear(r)}async updateReferences(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,t);this.referenceIndex.set(e.uri.toString(),n)}isAffected(e,t){let n=this.referenceIndex.get(e.uri.toString());return n?n.some(e=>!e.local&&t.has(e.targetUri.toString())):!1}},Dt;(function(e){e[e.Normal=0]=`Normal`,e[e.Immediate=1]=`Immediate`})(Dt||={});var DefaultWorkspaceLock=class{constructor(){this.previousTokenSource=new pe,this.writeQueue=[],this.readQueue=[],this.immediateReads=[],this.done=!0}write(e){this.cancelWrite();let t=startCancelableOperation();return this.previousTokenSource=t,this.enqueue(this.writeQueue,e,t.token)}read(e,t=Dt.Normal){if(t===Dt.Immediate){let t=Promise.resolve().then(()=>e());this.immediateReads.push(t);let remove=()=>{this.immediateReads.splice(this.immediateReads.indexOf(t),1)};return t.then(remove,remove),t}return this.enqueue(this.readQueue,e)}enqueue(e,t,n=b.None){let r=new Deferred,i={action:t,deferred:r,cancellationToken:n};return e.push(i),this.performNextOperation(),r.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)for(e.push(this.writeQueue.shift()),this.done=!1;this.immediateReads.length>0;)await Promise.allSettled(this.immediateReads.slice());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length)),this.done=!1;else return;await Promise.all(e.map(async({action:e,deferred:t,cancellationToken:n})=>{try{let r=await Promise.resolve().then(()=>e(n));t.resolve(r)}catch(e){isOperationCancelled(e)?t.resolve(void 0):t.reject(e)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}},DefaultWorkspaceManager=class{constructor(e){this.initialBuildOptions={},this._ready=new Deferred,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){this.folders=e.workspaceFolders??void 0}initialized(e){return this.mutex.write(e=>this.initializeWorkspace(this.folders??[],e))}async initializeWorkspace(e,t=b.None){let n=await this.performStartup(e);await interruptAndCheck(t),await this.documentBuilder.build(n,this.initialBuildOptions,t)}async performStartup(e){let t=[],collector=e=>{t.push(e),this.langiumDocuments.hasDocument(e.uri)||this.langiumDocuments.addDocument(e)};await this.loadAdditionalDocuments(e,collector);let n=[];await Promise.all(e.map(e=>this.getRootFolder(e)).map(async e=>this.traverseFolder(e,n)));let r=stream(n).distinct(e=>e.toString()).filter(e=>!this.langiumDocuments.hasDocument(e));return await this.loadWorkspaceDocuments(r,collector),this._ready.resolve(),t}async loadWorkspaceDocuments(e,t){await Promise.all(e.map(async e=>{t(await this.langiumDocuments.getOrCreateDocument(e))}))}loadAdditionalDocuments(e,t){return Promise.resolve()}getRootFolder(e){return y.parse(e.uri)}async traverseFolder(e,t){try{let n=await this.fileSystemProvider.readDirectory(e);await Promise.all(n.map(async e=>{this.shouldIncludeEntry(e)&&(e.isDirectory?await this.traverseFolder(e.uri,t):e.isFile&&t.push(e.uri))}))}catch(t){console.error(`Failure to read directory content of `+e.toString(!0),t)}}async searchFolder(e){let t=[];return await this.traverseFolder(e,t),t}shouldIncludeEntry(e){let t=J.basename(e.uri);return t.startsWith(`.`)?!1:e.isDirectory?t!==`node_modules`&&t!==`out`:e.isFile?this.serviceRegistry.hasServices(e.uri):!1}};function diagnosticData(e){return{code:e}}var Ot;(function(e){e.defaults=[`fast`,`slow`,`built-in`],e.all=e.defaults})(Ot||={});var ValidationRegistry=class{constructor(e){this.entries=new MultiMap,this.knownCategories=new Set(Ot.defaults),this.entriesBefore=[],this.entriesAfter=[],this.reflection=e.shared.AstReflection}register(e,t=this,n=`fast`){if(n===`built-in`)throw Error(`The 'built-in' category is reserved for lexer, parser, and linker errors.`);this.knownCategories.add(n);for(let[r,i]of Object.entries(e)){let e=i;if(Array.isArray(e))for(let i of e){let e={check:this.wrapValidationException(i,t),category:n};this.addEntry(r,e)}else if(typeof e==`function`){let i={check:this.wrapValidationException(e,t),category:n};this.addEntry(r,i)}else assertUnreachable(e)}}wrapValidationException(e,t){return async(n,r,i)=>{await this.handleException(()=>e.call(t,n,r,i),`An error occurred during validation`,r,n)}}async handleException(e,t,n,r){try{await e()}catch(e){if(isOperationCancelled(e))throw e;console.error(`${t}:`,e),e instanceof Error&&e.stack&&console.error(e.stack),n(`error`,`${t}: ${e instanceof Error?e.message:String(e)}`,{node:r})}}addEntry(e,t){if(e===`AstNode`)this.entries.add(`AstNode`,t);else for(let n of this.reflection.getAllSubTypes(e))this.entries.add(n,t)}getChecks(e,t){let n=stream(this.entries.get(e)).concat(this.entries.get(`AstNode`));return t&&(n=n.filter(e=>t.includes(e.category))),n.map(e=>e.check)}registerBeforeDocument(e,t=this){this.entriesBefore.push(this.wrapPreparationException(e,`An error occurred during set-up of the validation`,t))}registerAfterDocument(e,t=this){this.entriesAfter.push(this.wrapPreparationException(e,`An error occurred during tear-down of the validation`,t))}wrapPreparationException(e,t,n){return async(r,i,a,o)=>{await this.handleException(()=>e.call(n,r,i,a,o),t,i,r)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(e){return this.knownCategories}};const kt=Object.freeze({validateNode:!0,validateChildren:!0});var DefaultDocumentValidator=class{constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async validateDocument(e,t={},n=b.None){let r=e.parseResult,i=[];if(await interruptAndCheck(n),(!t.categories||t.categories.includes(`built-in`))&&(this.processLexingErrors(r,i,t),t.stopAfterLexingErrors&&i.some(e=>e.data?.code===Z.LexingError)||(this.processParsingErrors(r,i,t),t.stopAfterParsingErrors&&i.some(e=>e.data?.code===Z.ParsingError))||(this.processLinkingErrors(e,i,t),t.stopAfterLinkingErrors&&i.some(e=>e.data?.code===Z.LinkingError))))return i;try{i.push(...await this.validateAst(r.value,t,n))}catch(e){if(isOperationCancelled(e))throw e;console.error(`An error occurred during validation:`,e)}return await interruptAndCheck(n),i}processLexingErrors(e,t,n){let r=[...e.lexerErrors,...e.lexerReport?.diagnostics??[]];for(let e of r){let n=e.severity??`error`,r={severity:toDiagnosticSeverity(n),range:{start:{line:e.line-1,character:e.column-1},end:{line:e.line-1,character:e.column+e.length-1}},message:e.message,data:toDiagnosticData(n),source:this.getSource()};t.push(r)}}processParsingErrors(e,t,n){for(let n of e.parserErrors){let e;if(isValidTokenRange(n.token))e=tokenToRange(n.token);else if(`previousToken`in n){let t=n.previousToken;if(isValidTokenRange(t)){let n={line:t.endLine-1,character:t.endColumn};e={start:n,end:n}}else{let t={line:0,character:0};e={start:t,end:t}}}if(e){let r={severity:toDiagnosticSeverity(`error`),range:e,message:n.message,data:diagnosticData(Z.ParsingError),source:this.getSource()};t.push(r)}}}processLinkingErrors(e,t,n){for(let n of e.references){let e=n.error;if(e){let r={node:e.info.container,range:n.$refNode?.range,property:e.info.property,index:e.info.index,data:{code:Z.LinkingError,containerType:e.info.container.$type,property:e.info.property,refText:e.info.reference.$refText}};t.push(this.toDiagnostic(`error`,e.message,r))}}}async validateAst(e,t,n=b.None){let r=[],acceptor=(e,t,n)=>{r.push(this.toDiagnostic(e,t,n))};return await this.validateAstBefore(e,t,acceptor,n),await this.validateAstNodes(e,t,acceptor,n),await this.validateAstAfter(e,t,acceptor,n),r}async validateAstBefore(e,t,n,r=b.None){let i=this.validationRegistry.checksBefore;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}async validateAstNodes(e,t,n,r=b.None){if(this.profiler?.isActive(`validating`)){let i=this.profiler.createTask(`validating`,this.languageId);i.start();try{let a=streamAst(e).iterator();for(let e of a){i.startSubTask(e.$type);let o=this.validateSingleNodeOptions(e,t);if(o.validateNode)try{let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}finally{i.stopSubTask(e.$type)}o.validateChildren||a.prune()}}finally{i.stop()}}else{let i=streamAst(e).iterator();for(let e of i){await interruptAndCheck(r);let a=this.validateSingleNodeOptions(e,t);if(a.validateNode){let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}a.validateChildren||i.prune()}}}validateSingleNodeOptions(e,t){return kt}async validateAstAfter(e,t,n,r=b.None){let i=this.validationRegistry.checksAfter;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}toDiagnostic(e,t,n){return{message:t,range:getDiagnosticRange(n),severity:toDiagnosticSeverity(e),code:n.code,codeDescription:n.codeDescription,tags:n.tags,relatedInformation:n.relatedInformation,data:n.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};function getDiagnosticRange(e){if(e.range)return e.range;let t;return typeof e.property==`string`?t=findNodeForProperty(e.node.$cstNode,e.property,e.index):typeof e.keyword==`string`&&(t=findNodeForKeyword(e.node.$cstNode,e.keyword,e.index)),t??=e.node.$cstNode,t?t.range:{start:{line:0,character:0},end:{line:0,character:0}}}function toDiagnosticSeverity(e){switch(e){case`error`:return 1;case`warning`:return 2;case`info`:return 3;case`hint`:return 4;default:throw Error(`Invalid diagnostic severity: `+e)}}function toDiagnosticData(e){switch(e){case`error`:return diagnosticData(Z.LexingError);case`warning`:return diagnosticData(Z.LexingWarning);case`info`:return diagnosticData(Z.LexingInfo);case`hint`:return diagnosticData(Z.LexingHint);default:throw Error(`Invalid diagnostic severity: `+e)}}var Z;(function(e){e.LexingError=`lexing-error`,e.LexingWarning=`lexing-warning`,e.LexingInfo=`lexing-info`,e.LexingHint=`lexing-hint`,e.ParsingError=`parsing-error`,e.LinkingError=`linking-error`})(Z||={});function createDefaultCoreModule(e){return{documentation:{CommentProvider:e=>new DefaultCommentProvider(e),DocumentationProvider:e=>new JSDocDocumentationProvider(e)},parser:{AsyncParser:e=>new DefaultAsyncParser(e),GrammarConfig:e=>createGrammarConfig(e),LangiumParser:e=>createLangiumParser(e),CompletionParser:e=>createCompletionParser(e),ValueConverter:()=>new DefaultValueConverter,TokenBuilder:()=>new DefaultTokenBuilder,Lexer:e=>new DefaultLexer(e),ParserErrorMessageProvider:()=>new LangiumParserErrorMessageProvider,LexerErrorMessageProvider:()=>new DefaultLexerErrorMessageProvider},workspace:{AstNodeLocator:()=>new DefaultAstNodeLocator,AstNodeDescriptionProvider:e=>new DefaultAstNodeDescriptionProvider(e),ReferenceDescriptionProvider:e=>new DefaultReferenceDescriptionProvider(e)},references:{Linker:e=>new DefaultLinker(e),NameProvider:()=>new DefaultNameProvider,ScopeProvider:e=>new DefaultScopeProvider(e),ScopeComputation:e=>new DefaultScopeComputation(e),References:e=>new DefaultReferences(e)},serializer:{Hydrator:e=>new DefaultHydrator(e),JsonSerializer:e=>new DefaultJsonSerializer(e)},validation:{DocumentValidator:e=>new DefaultDocumentValidator(e),ValidationRegistry:e=>new ValidationRegistry(e)},shared:()=>e.shared}}function createDefaultSharedCoreModule(e){return{ServiceRegistry:e=>new DefaultServiceRegistry(e),workspace:{LangiumDocuments:e=>new DefaultLangiumDocuments(e),LangiumDocumentFactory:e=>new DefaultLangiumDocumentFactory(e),DocumentBuilder:e=>new DefaultDocumentBuilder(e),IndexManager:e=>new DefaultIndexManager(e),WorkspaceManager:e=>new DefaultWorkspaceManager(e),FileSystemProvider:t=>e.fileSystemProvider(t),WorkspaceLock:()=>new DefaultWorkspaceLock,ConfigurationProvider:e=>new DefaultConfigurationProvider(e)},profilers:{}}}var DefaultDocumentHighlightProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}getDocumentHighlight(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return;let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!i)return;let a=this.references.findDeclarations(i),o=[];for(let t of a){let n=J.equals(getDocument(t).uri,e.uri),r={documentUri:e.uri,includeDeclaration:n},i=this.references.findReferences(t,r);o.push(...i.map(e=>this.createDocumentHighlight(e)).toArray())}return o}createDocumentHighlight(e){return te.create(e.segment.range)}},DefaultDocumentSymbolProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.nodeKindProvider=e.shared.lsp.NodeKindProvider}getSymbols(e,t,n){return this.getSymbol(e,e.parseResult.value)}getSymbol(e,t){let n=this.nameProvider.getNameNode(t);if(n&&t.$cstNode){let r=this.nameProvider.getName(t);return[this.createSymbol(e,t,t.$cstNode,n,r)]}return this.getChildSymbols(e,t)||[]}createSymbol(e,t,n,r,i){return{kind:this.nodeKindProvider.getSymbolKind(t),name:i||r.text,range:n.range,selectionRange:r.range,children:this.getChildSymbols(e,t)}}getChildSymbols(e,t){let n=[];for(let r of streamContents(t)){let t=this.getSymbol(e,r);n.push(...t)}if(n.length>0)return n}},DefaultDocumentUpdateHandler=class{constructor(e){this.onWatchedFilesChangeEmitter=new ge,this.workspaceManager=e.workspace.WorkspaceManager,this.documentBuilder=e.workspace.DocumentBuilder,this.workspaceLock=e.workspace.WorkspaceLock,this.serviceRegistry=e.ServiceRegistry;let t=!1;e.lsp.LanguageServer.onInitialize(e=>{t=!!e.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration}),e.lsp.LanguageServer.onInitialized(n=>{t&&this.registerFileWatcher(e)})}registerFileWatcher(e){let t=this.getWatchers();if(t.length>0){let n=e.lsp.Connection,r={watchers:t};n?.client.register(ee.type,r)}}getWatchers(){return[{globPattern:`**/*`}]}fireDocumentUpdate(e,t){this.workspaceManager.ready.then(()=>{this.workspaceLock.write(n=>this.documentBuilder.update(e,t,n))}).catch(e=>{console.error(`Workspace initialization failed. Could not perform document update.`,e)})}didChangeContent(e){this.fireDocumentUpdate([y.parse(e.document.uri)],[])}didChangeWatchedFiles(e){this.onWatchedFilesChangeEmitter.fire(e);let t=stream(e.changes).filter(e=>e.type!==ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray(),n=stream(e.changes).filter(e=>e.type===ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray();this.fireDocumentUpdate(t,n)}get onWatchedFilesChange(){return this.onWatchedFilesChangeEmitter.event}},DefaultFoldingRangeProvider=class{constructor(e){this.commentNames=e.parser.GrammarConfig.multilineCommentRules}getFoldingRanges(e,t,n){let r=[],acceptor=e=>r.push(e);return this.collectFolding(e,acceptor),r}collectFolding(e,t){let n=e.parseResult?.value;if(n){if(this.shouldProcessContent(n)){let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let n=i.value;this.shouldProcess(n)&&this.collectObjectFolding(e,n,t),this.shouldProcessContent(n)||r.prune()}while(!i.done)}this.collectCommentFolding(e,n,t)}}shouldProcess(e){return!0}shouldProcessContent(e){return!0}collectObjectFolding(e,t,n){let r=t.$cstNode;if(r){let t=this.toFoldingRange(e,r);t&&n(t)}}collectCommentFolding(e,t,n){let r=t.$cstNode;if(r){for(let t of flattenCst(r))if(this.commentNames.includes(t.tokenType.name)){let r=this.toFoldingRange(e,t,ie.Comment);r&&n(r)}}}toFoldingRange(e,t,n){let r=t.range,i=r.start,a=r.end;if(!(a.line-i.line<2))return this.includeLastFoldingLine(t,n)||(a=e.textDocument.positionAt(e.textDocument.offsetAt({line:a.line,character:0})-1)),re.create(i.line,a.line,i.character,a.character,n)}includeLastFoldingLine(e,t){if(t===ie.Comment)return!1;let n=e.root.fullText.charAt(e.end-1);return n!==`}`&&n!==`)`&&n!==`]`}},DefaultFuzzyMatcher=class{match(e,t){if(e.length===0)return!0;let n=!1,r,i=0,a=t.length;for(let o=0;o<a;o++){let a=t.charCodeAt(o),s=e.charCodeAt(i);if((a===s||this.toUpperCharCode(a)===this.toUpperCharCode(s))&&(n||=r===void 0||this.isWordTransition(r,a),n&&i++,i===e.length))return!0;r=a}return!1}isWordTransition(e,t){return At<=e&&e<=jt&&Mt<=t&&t<=Nt||e===Pt&&t!==Pt}toUpperCharCode(e){return At<=e&&e<=jt?e-32:e}};const At=97,jt=122,Mt=65,Nt=90,Pt=95;var AstNodeHoverProvider=class{constructor(e){this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}async getHoverContent(e,t){let n=e.parseResult?.value?.$cstNode;if(n){let r=e.textDocument.offsetAt(t.position),i=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(i&&i.offset+i.length>r){let e=[],t=this.references.findDeclarations(i);for(let n of t){let t=await this.getAstNodeHoverContent(n);typeof t==`string`&&e.push(t)}if(e.length>0)return{contents:{kind:`markdown`,value:e.join(` `)}};if(isKeyword(i.grammarSource))return this.getKeywordHoverContent(i.grammarSource)}}}getKeywordHoverContent(e){let t=isAstNodeWithComment(e)?e.$comment:void 0;if(t||=findCommentNode(e.$cstNode,[`ML_COMMENT`])?.text,t&&isJSDoc(t)){let e=parseJSDoc(t).toMarkdown();if(e)return{contents:{kind:`markdown`,value:e}}}}},MultilineCommentHoverProvider=class extends AstNodeHoverProvider{constructor(e){super(e),this.documentationProvider=e.documentation.DocumentationProvider}getAstNodeHoverContent(e){let t=this.documentationProvider.getDocumentation(e);if(t)return t}};const Ft={[v.class]:0,[v.comment]:1,[v.enum]:2,[v.enumMember]:3,[v.event]:4,[v.function]:5,[v.interface]:6,[v.keyword]:7,[v.macro]:8,[v.method]:9,[v.modifier]:10,[v.namespace]:11,[v.number]:12,[v.operator]:13,[v.parameter]:14,[v.property]:15,[v.regexp]:16,[v.string]:17,[v.struct]:18,[v.type]:19,[v.typeParameter]:20,[v.variable]:21,[v.decorator]:22},It={[_.abstract]:1,[_.async]:2,[_.declaration]:4,[_.defaultLibrary]:8,[_.definition]:16,[_.deprecated]:32,[_.documentation]:64,[_.modification]:128,[_.readonly]:256,[_.static]:512};Object.keys(Ft),Object.keys(It);function mergeSemanticTokenProviderOptions(e){let t=[],n=[],r=!0,i=!0,a=!0;for(let o of e)o&&(o.legend.tokenTypes.forEach((e,n)=>{let r=t[n];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token types. They use the same index ${n}.`);t[n]=e}),o.legend.tokenModifiers.forEach((e,t)=>{let r=n[t];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token modifier. They use the same index ${t}.`);n[t]=e}),o.full?typeof o.full==`object`&&!o.full.delta&&(i=!1):r=!1,o.range||(a=!1));return{legend:{tokenTypes:t,tokenModifiers:n},full:r&&{delta:i},range:a}}var SemanticTokensBuilder$1=class extends ce{static{e(this,`SemanticTokensBuilder`)}constructor(){super(...arguments),this._tokens=[]}push(e,t,n,r,i){this._tokens.push({line:e,char:t,length:n,tokenType:r,tokenModifiers:i})}build(){return this.applyTokens(),super.build()}buildEdits(){return this.applyTokens(),super.buildEdits()}flush(){this.previousResult(this.id)}applyTokens(){for(let e of this._tokens.sort(this.compareTokens))super.push(e.line,e.char,e.length,e.tokenType,e.tokenModifiers);this._tokens=[]}compareTokens(e,t){return e.line-t.line||e.char-t.char}},AbstractSemanticTokenProvider=class{constructor(e){this.tokensBuilders=/* @__PURE__ */ new Map,e.shared.workspace.TextDocuments.onDidClose(e=>{this.tokensBuilders.delete(e.document.uri)}),e.shared.lsp.LanguageServer.onInitialize(e=>{this.initialize(e.capabilities.textDocument?.semanticTokens)})}initialize(e){this.clientCapabilities=e}get tokenTypes(){return Ft}get tokenModifiers(){return It}get semanticTokensOptions(){return{legend:{tokenTypes:Object.keys(this.tokenTypes),tokenModifiers:Object.keys(this.tokenModifiers)},full:{delta:!1},range:!0}}async semanticHighlight(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightRange(e,t,n=b.None){return this.currentRange=t.range,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightDelta(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.previousResult(t.previousResultId),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.buildEdits()}createAcceptor(){let acceptor=e=>{`line`in e?this.highlightToken({range:{start:{line:e.line,character:e.char},end:{line:e.line,character:e.char+e.length}},type:e.type,modifier:e.modifier}):`range`in e?this.highlightToken(e):`keyword`in e?this.highlightKeyword(e):`property`in e?this.highlightProperty(e):this.highlightNode({node:e.cst,type:e.type,modifier:e.modifier})};return acceptor}getDocumentTokensBuilder(e){let t=this.tokensBuilders.get(e.uri.toString());if(t)return t;let n=new SemanticTokensBuilder$1;return this.tokensBuilders.set(e.uri.toString(),n),n}async computeHighlighting(e,t,n){let r=e.parseResult.value,i=streamAst(r,{range:this.currentRange}).iterator(),a;do if(a=i.next(),!a.done){await interruptAndCheck(n);let e=a.value;this.highlightElement(e,t)===`prune`&&i.prune()}while(!a.done)}highlightToken(e){let{range:t,type:n}=e,r=e.modifier;if(this.currentRange&&!inRange(t,this.currentRange)||!this.currentDocument||!this.currentTokensBuilder)return;let i=this.tokenTypes[n],a=0;if(r!==void 0){typeof r==`string`&&(r=[r]);for(let e of r){let t=this.tokenModifiers[e];a|=t}}let o=t.start.line,s=t.end.line;if(o===s){let e=t.start.character,n=t.end.character-e;this.currentTokensBuilder.push(o,e,n,i,a)}else if(this.clientCapabilities?.multilineTokenSupport){let e=t.start.character,n=this.currentDocument.textDocument.offsetAt(t.start),r=this.currentDocument.textDocument.offsetAt(t.end);this.currentTokensBuilder.push(o,e,r-n,i,a)}else{let e=t.start,n=this.currentDocument.textDocument.offsetAt({line:o+1,character:0});this.currentTokensBuilder.push(e.line,e.character,n-e.character-1,i,a);for(let e=o+1;e<s;e++){let t=n;n=this.currentDocument.textDocument.offsetAt({line:e+1,character:0}),this.currentTokensBuilder.push(e,0,n-t-1,i,a)}this.currentTokensBuilder.push(s,0,t.end.character,i,a)}}highlightProperty(e){let t=[];if(typeof e.index==`number`){let n=findNodeForProperty(e.node.$cstNode,e.property,e.index);n&&t.push(n)}else t.push(...findNodesForProperty(e.node.$cstNode,e.property));let{type:n,modifier:r}=e;for(let e of t)this.highlightNode({node:e,type:n,modifier:r})}highlightKeyword(e){let{node:t,keyword:n,type:r,index:i,modifier:a}=e,o=[];if(typeof i==`number`){let e=findNodeForKeyword(t.$cstNode,n,i);e&&o.push(e)}else o.push(...findNodesForKeyword(t.$cstNode,n));for(let e of o)this.highlightNode({node:e,type:r,modifier:a})}highlightNode(e){let{node:t,type:n,modifier:r}=e,i=t.range;this.highlightToken({range:i,type:n,modifier:r})}},Lt;(function(e){function decode(e,t,n){let r=/* @__PURE__ */ new Map;Object.entries(t).forEach(([e,t])=>r.set(t,e));let i=0,a=0;return sliceIntoChunks(e.data,5).map(e=>{i+=e[0],e[0]!==0&&(a=0),a+=e[1];let t=e[2];return{offset:n.textDocument.offsetAt({line:i,character:a}),tokenType:r.get(e[3]),tokenModifiers:e[4],text:n.textDocument.getText({start:{line:i,character:a},end:{line:i,character:a+t}})}})}e.decode=decode;function sliceIntoChunks(e,t){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);n.push(i)}return n}})(Lt||={});function mergeSignatureHelpOptions(e){let t=[],n=[];e.forEach(e=>{e?.triggerCharacters&&t.push(...e.triggerCharacters),e?.retriggerCharacters&&n.push(...e.retriggerCharacters)});let r={triggerCharacters:t.length>0?Array.from(new Set(t)).sort():void 0,retriggerCharacters:n.length>0?Array.from(new Set(n)).sort():void 0};return r.triggerCharacters?r:void 0}var DefaultLanguageServer=class{constructor(e){this.onInitializeEmitter=new he,this.onInitializedEmitter=new he,this.services=e}get onInitialize(){return this.onInitializeEmitter.event}get onInitialized(){return this.onInitializedEmitter.event}async initialize(e){return this.eagerLoadServices(),this.fireInitializeOnDefaultServices(e),this.onInitializeEmitter.fire(e),this.onInitializeEmitter.dispose(),this.buildInitializeResult(e)}eagerLoadServices(){eagerLoad(this.services),this.services.ServiceRegistry.all.forEach(e=>eagerLoad(e))}hasService(e){return this.services.ServiceRegistry.all.some(t=>e(t)!==void 0)}buildInitializeResult(e){let t=this.services.lsp.DocumentUpdateHandler,n=this.services.lsp.FileOperationHandler?.fileOperationOptions,r=this.services.ServiceRegistry.all,i=this.hasService(e=>e.lsp?.Formatter),a=r.map(e=>e.lsp?.Formatter?.formatOnTypeOptions).find(e=>!!e),o=this.hasService(e=>e.lsp?.CodeActionProvider),s=this.hasService(e=>e.lsp?.SemanticTokenProvider),c=mergeSemanticTokenProviderOptions(r.map(e=>e.lsp?.SemanticTokenProvider?.semanticTokensOptions)),l=this.services.lsp?.ExecuteCommandHandler?.commands,u=this.hasService(e=>e.lsp?.DocumentLinkProvider),d=mergeSignatureHelpOptions(r.map(e=>e.lsp?.SignatureHelp?.signatureHelpOptions)),f=this.hasService(e=>e.lsp?.TypeProvider),p=this.hasService(e=>e.lsp?.ImplementationProvider),m=this.hasService(e=>e.lsp?.CompletionProvider),ee=mergeCompletionProviderOptions(r.map(e=>e.lsp?.CompletionProvider?.completionOptions)),h=this.hasService(e=>e.lsp?.ReferencesProvider),te=this.hasService(e=>e.lsp?.DocumentSymbolProvider),g=this.hasService(e=>e.lsp?.DefinitionProvider),ne=this.hasService(e=>e.lsp?.DocumentHighlightProvider),re=this.hasService(e=>e.lsp?.FoldingRangeProvider),ie=this.hasService(e=>e.lsp?.HoverProvider),ae=this.hasService(e=>e.lsp?.RenameProvider),oe=this.hasService(e=>e.lsp?.CallHierarchyProvider),se=this.hasService(e=>e.lsp?.TypeHierarchyProvider),_=this.hasService(e=>e.lsp?.CodeLensProvider),v=this.hasService(e=>e.lsp?.DeclarationProvider),ce=this.hasService(e=>e.lsp?.InlayHintProvider),le=this.services.lsp?.WorkspaceSymbolProvider,ue=this.services.lsp?.TextDocumentContentProvider?.schemes;return{capabilities:{workspace:{workspaceFolders:{supported:!0},fileOperations:n,textDocumentContent:ue?{schemes:ue}:void 0},executeCommandProvider:l&&{commands:l},textDocumentSync:{change:ye.Incremental,openClose:!0,save:!!t.didSaveDocument,willSave:!!t.willSaveDocument,willSaveWaitUntil:!!t.willSaveDocumentWaitUntil},completionProvider:m?ee:void 0,referencesProvider:h,documentSymbolProvider:te,definitionProvider:g,typeDefinitionProvider:f,documentHighlightProvider:ne,codeActionProvider:o,documentFormattingProvider:i,documentRangeFormattingProvider:i,documentOnTypeFormattingProvider:a,foldingRangeProvider:re,hoverProvider:ie,renameProvider:ae?{prepareProvider:!0}:void 0,semanticTokensProvider:s?c:void 0,signatureHelpProvider:d,implementationProvider:p,callHierarchyProvider:oe?{}:void 0,typeHierarchyProvider:se?{}:void 0,documentLinkProvider:u?{resolveProvider:!1}:void 0,codeLensProvider:_?{resolveProvider:!1}:void 0,declarationProvider:v,inlayHintProvider:ce?{resolveProvider:!1}:void 0,workspaceSymbolProvider:le?{resolveProvider:!!le.resolveSymbol}:void 0}}}initialized(e){this.fireInitializedOnDefaultServices(e),this.onInitializedEmitter.fire(e),this.onInitializedEmitter.dispose()}fireInitializeOnDefaultServices(e){this.services.workspace.ConfigurationProvider.initialize(e),this.services.workspace.WorkspaceManager.initialize(e)}fireInitializedOnDefaultServices(e){let t=this.services.lsp.Connection,n=t?{...e,register:e=>t.client.register(me.type,e),fetchConfiguration:e=>t.workspace.getConfiguration(e)}:e;this.services.workspace.ConfigurationProvider.initialized(n).catch(e=>console.error(`Error in ConfigurationProvider initialization:`,e)),this.services.workspace.WorkspaceManager.initialized(e).catch(e=>console.error(`Error in WorkspaceManager initialization:`,e))}},Rt;(function(e){e.Parsed=Object.freeze({type:`workspace`,state:X.Parsed}),e.IndexedContent=Object.freeze({type:`workspace`,state:X.IndexedContent}),e.ComputedScopes=Object.freeze({type:`workspace`,state:X.ComputedScopes}),e.Linked=Object.freeze({type:`workspace`,state:X.Linked}),e.IndexedReferences=Object.freeze({type:`workspace`,state:X.IndexedReferences}),e.Validated=Object.freeze({type:`workspace`,state:X.Validated})})(Rt||={});var DefaultNodeKindProvider=class{getSymbolKind(e){return le.Field}getCompletionItemKind(e){return p.Reference}},DefaultReferencesProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}findReferences(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return[];let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);return i?this.getReferences(i,t,e):[]}getReferences(e,t,n){let r=[],i=this.references.findDeclarations(e);for(let e of i){let n={includeDeclaration:t.context.includeDeclaration};this.references.findReferences(e,n).forEach(e=>{r.push(ae.create(e.sourceUri.toString(),e.segment.range))})}return r}},DefaultRenameProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}async rename(e,t,n){let r={},i=e.parseResult.value.$cstNode;if(!i)return;let a=findDeclarationNodeAtOffset(i,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!a)return;let o=this.references.findDeclarations(a);if(o.length===0)return;let s=o[0],c=this.references.findReferences(s,{onlyLocal:!1,includeDeclaration:!0});for(let e of c){let n=xe.replace(e.segment.range,t.newName),i=e.sourceUri.toString();r[i]?r[i].push(n):r[i]=[n]}return{changes:r}}prepareRename(e,t,n){return this.renameNodeRange(e,t.position)}renameNodeRange(e,t){let n=e.parseResult.value.$cstNode,r=e.textDocument.offsetAt(t);if(n){let e=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(!e)return;if(this.references.findDeclarations(e).length>0||this.isNameNode(e))return e.range}}isNameNode(e){return e?.astNode&&isNamed(e.astNode)&&e===this.nameProvider.getNameNode(e.astNode)}},DefaultWorkspaceSymbolProvider=class{constructor(e){this.indexManager=e.workspace.IndexManager,this.nodeKindProvider=e.lsp.NodeKindProvider,this.fuzzyMatcher=e.lsp.FuzzyMatcher}async getSymbols(e,t=b.None){let n=[],r=e.query.toLowerCase();for(let e of this.indexManager.allElements())if(await interruptAndCheck(t),this.fuzzyMatcher.match(r,e.name)){let t=this.getWorkspaceSymbol(e);t&&n.push(t)}return n}getWorkspaceSymbol(e){let t=e.nameSegment;if(t)return{kind:this.nodeKindProvider.getSymbolKind(e),name:e.name,location:{range:t.range,uri:e.documentUri.toString()}}}},NormalizedTextDocuments=class{constructor(e){this._configuration=e,this._syncedDocuments=/* @__PURE__ */ new Map,this._onDidChangeContent=new g,this._onDidOpen=new g,this._onDidClose=new g,this._onDidSave=new g,this._onWillSave=new g}get onDidOpen(){return this._onDidOpen.event}get onDidChangeContent(){return this._onDidChangeContent.event}get onWillSave(){return this._onWillSave.event}onWillSaveWaitUntil(e){this._willSaveWaitUntil=e}get onDidSave(){return this._onDidSave.event}get onDidClose(){return this._onDidClose.event}get(e){return this._syncedDocuments.get(J.normalize(e))}set(e){let t=J.normalize(e.uri),n=!0;this._syncedDocuments.has(t)&&(n=!1),this._syncedDocuments.set(t,e);let r=Object.freeze({document:e});return this._onDidOpen.fire(r),this._onDidChangeContent.fire(r),n}delete(e){let t=J.normalize(typeof e==`object`&&`uri`in e?e.uri:e),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))}all(){return Array.from(this._syncedDocuments.values())}keys(){return Array.from(this._syncedDocuments.keys())}listen(e){e.__textDocumentSync=ue.Incremental;let t=[];return t.push(e.onDidOpenTextDocument(e=>{let t=e.textDocument,n=J.normalize(t.uri),r=this._configuration.create(n,t.languageId,t.version,t.text);this._syncedDocuments.set(n,r);let i=Object.freeze({document:r});this._onDidOpen.fire(i),this._onDidChangeContent.fire(i)})),t.push(e.onDidChangeTextDocument(e=>{let t=e.textDocument,n=e.contentChanges;if(n.length===0)return;let{version:r}=t;if(r==null)throw Error(`Received document change event for ${t.uri} without valid version identifier`);let i=J.normalize(t.uri),a=this._syncedDocuments.get(i);a!==void 0&&(a=this._configuration.update(a,n,r),this._syncedDocuments.set(i,a),this._onDidChangeContent.fire(Object.freeze({document:a})))})),t.push(e.onDidCloseTextDocument(e=>{let t=J.normalize(e.textDocument.uri),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))})),t.push(e.onWillSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onWillSave.fire(Object.freeze({document:t,reason:e.reason}))})),t.push(e.onWillSaveTextDocumentWaitUntil((e,t)=>{let n=this._syncedDocuments.get(J.normalize(e.textDocument.uri));return n!==void 0&&this._willSaveWaitUntil?this._willSaveWaitUntil(Object.freeze({document:n,reason:e.reason}),t):[]})),t.push(e.onDidSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onDidSave.fire(Object.freeze({document:t}))})),h.create(()=>{t.forEach(e=>e.dispose())})}},NormalizedNotebookDocuments=class{constructor(e){this.notebookDocuments=/* @__PURE__ */ new Map,this.notebookCellMap=/* @__PURE__ */ new Map,this._onDidOpen=new g,this._onDidSave=new g,this._onDidChange=new g,this._onDidClose=new g,this._cellTextDocuments=`listen`in e?e:new NormalizedTextDocuments(e)}get cellTextDocuments(){return this._cellTextDocuments}getCellTextDocument(e){return this._cellTextDocuments.get(e.document)}getNotebookDocument(e){return this.notebookDocuments.get(J.normalize(e))}getNotebookCell(e){let t=this.notebookCellMap.get(J.normalize(e));return t&&t[0]}findNotebookDocumentForCell(e){let t=typeof e==`string`||`scheme`in e?e:e.document,n=this.notebookCellMap.get(J.normalize(t));return n&&n[1]}get onDidOpen(){return this._onDidOpen.event}get onDidSave(){return this._onDidSave.event}get onDidChange(){return this._onDidChange.event}get onDidClose(){return this._onDidClose.event}listen(e){let t=new zt,n=[];return n.push(this.cellTextDocuments.listen(t)),n.push(e.notebooks.synchronization.onDidOpenNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri);this.notebookDocuments.set(n,e.notebookDocument);for(let n of e.cellTextDocuments)t.openTextDocument({textDocument:n});this.updateCellMap(e.notebookDocument),this._onDidOpen.fire(e.notebookDocument)})),n.push(e.notebooks.synchronization.onDidChangeNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r===void 0)return;r.version=e.notebookDocument.version;let i=r.metadata,a=!1,o=e.change;o.metadata!==void 0&&(a=!0,r.metadata=o.metadata);let s=[],c=[],l=[],u=[];if(o.cells!==void 0){let e=o.cells;if(e.structure!==void 0){let n=e.structure.array;if(r.cells.splice(n.start,n.deleteCount,...n.cells===void 0?[]:n.cells),e.structure.didOpen!==void 0)for(let n of e.structure.didOpen)t.openTextDocument({textDocument:n}),s.push(n.uri);if(e.structure.didClose)for(let n of e.structure.didClose)t.closeTextDocument({textDocument:n}),c.push(n.uri)}if(e.data!==void 0){let t=new Map(e.data.map(e=>[e.document,e]));for(let e=0;e<=r.cells.length;e++){let n=t.get(r.cells[e].document);if(n!==void 0){let i=r.cells.splice(e,1,n);if(l.push({old:i[0],new:n}),t.delete(n.document),t.size===0)break}}}if(e.textContent!==void 0)for(let n of e.textContent)t.changeTextDocument({textDocument:n.document,contentChanges:n.changes}),u.push(n.document.uri)}this.updateCellMap(r);let d={notebookDocument:r};a&&(d.metadata={old:i,new:r.metadata});let f=[];for(let e of s)f.push(this.getNotebookCell(e));let p=[];for(let e of c)p.push(this.getNotebookCell(e));let m=[];for(let e of u)m.push(this.getNotebookCell(e));(f.length>0||p.length>0||l.length>0||m.length>0)&&(d.cells={added:f,removed:p,changed:{data:l,textContent:m}}),(d.metadata!==void 0||d.cells!==void 0)&&this._onDidChange.fire(d)})),n.push(e.notebooks.synchronization.onDidSaveNotebookDocument(e=>{let t=this.getNotebookDocument(e.notebookDocument.uri);t!==void 0&&this._onDidSave.fire(t)})),n.push(e.notebooks.synchronization.onDidCloseNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r!==void 0){this._onDidClose.fire(r);for(let n of e.cellTextDocuments)t.closeTextDocument({textDocument:n});this.notebookDocuments.delete(n);for(let e of r.cells)this.notebookCellMap.delete(e.document)}})),h.create(()=>{n.forEach(e=>e.dispose())})}updateCellMap(e){for(let t of e.cells)this.notebookCellMap.set(t.document,[t,e])}},zt=class CellTextDocumentConnection{onDidOpenTextDocument(e){return this.openHandler=e,h.create(()=>{this.openHandler=void 0})}openTextDocument(e){this.openHandler&&this.openHandler(e)}onDidChangeTextDocument(e){return this.changeHandler=e,h.create(()=>{this.changeHandler=e})}changeTextDocument(e){this.changeHandler&&this.changeHandler(e)}onDidCloseTextDocument(e){return this.closeHandler=e,h.create(()=>{this.closeHandler=void 0})}closeTextDocument(e){this.closeHandler&&this.closeHandler(e)}onWillSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}onWillSaveTextDocumentWaitUntil(){return CellTextDocumentConnection.NULL_DISPOSE}onDidSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}};zt.NULL_DISPOSE=Object.freeze({dispose:()=>{}});function createDefaultModule(e){return ht.merge(createDefaultCoreModule(e),createDefaultLSPModule(e))}function createDefaultLSPModule(e){return{lsp:{CompletionProvider:e=>new DefaultCompletionProvider(e),DocumentSymbolProvider:e=>new DefaultDocumentSymbolProvider(e),HoverProvider:e=>new MultilineCommentHoverProvider(e),FoldingRangeProvider:e=>new DefaultFoldingRangeProvider(e),ReferencesProvider:e=>new DefaultReferencesProvider(e),DefinitionProvider:e=>new DefaultDefinitionProvider(e),DocumentHighlightProvider:e=>new DefaultDocumentHighlightProvider(e),RenameProvider:e=>new DefaultRenameProvider(e)},shared:()=>e.shared}}function createDefaultSharedModule(e){return ht.merge(createDefaultSharedCoreModule(e),createDefaultSharedLSPModule(e))}function createDefaultSharedLSPModule(e){return{lsp:{Connection:()=>e.connection,LanguageServer:e=>new DefaultLanguageServer(e),DocumentUpdateHandler:e=>new DefaultDocumentUpdateHandler(e),WorkspaceSymbolProvider:e=>new DefaultWorkspaceSymbolProvider(e),NodeKindProvider:()=>new DefaultNodeKindProvider,FuzzyMatcher:()=>new DefaultFuzzyMatcher},workspace:{TextDocuments:()=>new NormalizedTextDocuments(be),NotebookDocuments:e=>new NormalizedNotebookDocuments(e.workspace.TextDocuments)}}}var AbstractFormatter=class{constructor(){this.collector=()=>{}}getNodeFormatter(e){return new DefaultNodeFormatter(e,this.collector)}formatDocument(e,t){let n=e.parseResult;return n.lexerErrors.length===0&&n.parserErrors.length===0?this.doDocumentFormat(e,t.options):[]}isFormatRangeErrorFree(e,t){let n=e.parseResult;return n.lexerErrors.length||n.parserErrors.length?Math.min(...n.lexerErrors.map(e=>e.line??Number.MAX_VALUE),...n.parserErrors.map(e=>e.token.startLine??Number.MAX_VALUE))>t.end.line:!0}formatDocumentRange(e,t){return this.isFormatRangeErrorFree(e,t.range)?this.doDocumentFormat(e,t.options,t.range):[]}formatDocumentOnType(e,t){let n={start:{character:0,line:t.position.line},end:t.position};return this.isFormatRangeErrorFree(e,n)?this.doDocumentFormat(e,t.options,n):[]}get formatOnTypeOptions(){}doDocumentFormat(e,t,n){let r=/* @__PURE__ */ new Map,collector=(e,t,n)=>{let i=this.nodeModeToKey(e,t),a=r.get(i),o=n.options.priority??0,s=a?.options.priority??0;(!a||s<=o)&&r.set(i,n)};this.collector=collector,this.iterateAstFormatting(e,n);let i=this.iterateCstFormatting(e,r,t,n);return this.avoidOverlappingEdits(e.textDocument,i)}avoidOverlappingEdits(e,t){let n=[];for(let r of t){let t=n[n.length-1];for(;t&&e.offsetAt(r.range.start)<e.offsetAt(t.range.end);)n.pop(),t=n[n.length-1];n.push(r)}return n.filter(t=>this.isNecessary(t,e))}iterateAstFormatting(e,t){let n=e.parseResult.value;this.format(n);let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let e=i.value;this.insideRange(e.$cstNode.range,t)?this.format(e):r.prune()}while(!i.done)}nodeModeToKey(e,t){return`${e.offset}:${e.end}:${t}`}insideRange(e,t){return!t||e.start.line<=t.start.line&&e.end.line>=t.end.line||e.start.line>=t.start.line&&e.end.line<=t.end.line||e.start.line<=t.end.line&&e.end.line>=t.end.line}isNecessary(e,t){return e.newText!==t.getText(e.range).replace(/\r/g,``)}iterateCstFormatting(e,t,n,r){let i={indentation:0,options:n,document:e.textDocument},a=[],o=this.iterateCstTree(e,i).iterator(),s,c;do if(c=o.next(),!c.done){let e=c.value,n=isLeafCstNode(e),o=this.nodeModeToKey(e,`prepend`),l=t.get(o);if(t.delete(o),l){let t=this.createTextEdit(s,e,l,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}let u=this.nodeModeToKey(e,`append`),d=t.get(u);if(t.delete(u),d){let t=getNextNode(e);if(t){let n=this.createTextEdit(e,t,d,i);for(let e of n)e&&this.insideRange(e.range,r)&&a.push(e)}}if(!l&&e.hidden){let t=this.createHiddenTextEdits(s,e,void 0,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}n&&(s=e)}while(!c.done);return a}createHiddenTextEdits(e,t,n,r){let i=t.range.start,a=i.line;if(e&&e.range.end.line===a)return[];let o=[],s={start:{character:0,line:a},end:i},c=r.document.getText(s),l=this.findFittingMove(s,n?.moves??[],r),u=this.getExistingIndentationCharacterCount(c,r),d=this.getIndentationCharacterCount(r,l)-u;if(d===0)return[];let f=``;d>0&&(f=(r.options.insertSpaces?` `:` `).repeat(d));let p=t.text.split(`
12
+ `);p[0]=c+p[0];for(let e=0;e<p.length;e++){let t=a+e,n={character:0,line:t};if(d>0)o.push({newText:f,range:{start:n,end:n}});else{let r=p[e],i=0;for(;i<r.length;i++){let e=r.charAt(i);if(e!==` `&&e!==` `)break}o.push({newText:``,range:{start:n,end:{line:t,character:Math.min(i,Math.abs(d))}}})}}return o}getExistingIndentationCharacterCount(e,t){let n=` `.repeat(t.options.tabSize),r=``,i;return t.options.insertSpaces?(i=/* @__PURE__ */ RegExp(`\\t`,`g`),r=n):(i=new RegExp(n,`g`),r=` `),e.replace(i,r).length}getIndentationCharacterCount(e,t){let n=e.indentation;return t&&t.tabs&&(n+=t.tabs),(e.options.insertSpaces?e.options.tabSize:1)*n}createTextEdit(e,t,n,r){if(t.hidden)return this.createHiddenTextEdits(e,t,n,r);let i=e?.range.end,a=t.range.start;if(i&&(i.line>a.line||i.line===a.line&&i.character>a.character))return[];let o={start:i??{character:0,line:0},end:a},s=this.findFittingMove(o,n.moves,r);if(!s)return[];let c=s.characters,l=s.lines,u=s.tabs,d=r.indentation;r.indentation+=u??0;let f=[];return c===void 0?l===void 0?u!==void 0&&f.push(this.createTabTextEdit(o,!!e,r)):f.push(this.createLineTextEdit(o,l,r,n.options)):e?.hidden||f.push(this.createSpaceTextEdit(o,c,n.options)),isLeafCstNode(t)&&(r.indentation=d),f}createSpaceTextEdit(e,t,n){if(e.start.line===e.end.line){let r=e.end.character-e.start.character;t=this.fitIntoOptions(t,r,n)}return{newText:` `.repeat(t),range:e}}createLineTextEdit(e,t,n,r){let i=e.end.line-e.start.line;t=this.fitIntoOptions(t,i,r);let a=(n.options.insertSpaces?` `.repeat(n.options.tabSize):` `).repeat(n.indentation);return{newText:`${`
13
+ `.repeat(t)}${a}`,range:e}}createTabTextEdit(e,t,n){let r=(n.options.insertSpaces?` `.repeat(n.options.tabSize):` `).repeat(n.indentation),i=+!!t,a=Math.max(e.end.line-e.start.line,i);return{newText:`${`
14
+ `.repeat(a)}${r}`,range:e}}fitIntoOptions(e,t,n){return n.allowMore?e=Math.max(t,e):n.allowLess&&(e=Math.min(t,e)),e}findFittingMove(e,t,n){if(t.length===0)return;if(t.length===1)return t[0];let r=e.end.line-e.start.line;for(let e of t)if(e.lines!==void 0&&r<=e.lines)return e;else if(e.lines===void 0&&r===0)return e;return t[t.length-1]}iterateCstTree(e,t){let n=e.parseResult.value.$cstNode;return n?new TreeStreamImpl(n,e=>this.iterateCst(e,t)):G}iterateCst(e,t){if(!isCompositeCstNode(e))return G;let n=t.indentation;return new W(()=>({index:0}),r=>r.index<e.content.length?{done:!1,value:e.content[r.index++]}:(t.indentation=n,K))}},DefaultNodeFormatter=class{constructor(e,t){this.astNode=e,this.collector=t}node(e){return new Q(e.$cstNode?[e.$cstNode]:[],this.collector)}nodes(...e){let t=[];for(let n of e)n.$cstNode&&t.push(n.$cstNode);return new Q(t,this.collector)}property(e,t){let n=findNodeForProperty(this.astNode.$cstNode,e,t);return new Q(n?[n]:[],this.collector)}properties(...e){let t=[];for(let n of e){let e=findNodesForProperty(this.astNode.$cstNode,n);t.push(...e)}return new Q(t,this.collector)}keyword(e,t){let n=findNodeForKeyword(this.astNode.$cstNode,e,t);return new Q(n?[n]:[],this.collector)}keywords(...e){let t=[];for(let n of e){let e=findNodesForKeyword(this.astNode.$cstNode,n);t.push(...e)}return new Q(t,this.collector)}cst(e){return new Q([...e],this.collector)}interior(e,t){let n=e.nodes,r=t.nodes;if(n.length!==1||r.length!==1)return new Q([],this.collector);let i=n[0],a=r[0];if(i.offset>a.offset){let e=i;i=a,a=e}return new Q(getInteriorNodes(i,a),this.collector)}},Q=class FormattingRegion{constructor(e,t){this.nodes=e,this.collector=t}prepend(e){for(let t of this.nodes)this.collector(t,`prepend`,e);return this}append(e){for(let t of this.nodes)this.collector(t,`append`,e);return this}surround(e){for(let t of this.nodes)this.collector(t,`prepend`,e),this.collector(t,`append`,e);return this}slice(e,t){return new FormattingRegion(this.nodes.slice(e,t),this.collector)}},Bt;(function(e){function fit(...e){return{options:{},moves:e.flatMap(e=>e.moves).sort(compareMoves)}}e.fit=fit;function noSpace(e){return spaces(0,e)}e.noSpace=noSpace;function oneSpace(e){return spaces(1,e)}e.oneSpace=oneSpace;function spaces(e,t){return{options:t??{},moves:[{characters:e}]}}e.spaces=spaces;function newLine(e){return newLines(1,e)}e.newLine=newLine;function newLines(e,t){return{options:t??{},moves:[{lines:e}]}}e.newLines=newLines;function indent(e){return{options:e??{},moves:[{tabs:1,lines:1}]}}e.indent=indent;function noIndent(e){return{options:e??{},moves:[{tabs:0}]}}e.noIndent=noIndent;function compareMoves(e,t){let n=e.lines??0,r=t.lines??0,i=e.tabs??0,a=t.tabs??0,o=e.characters??0,s=t.characters??0;return n<r?-1:n>r?1:i<a?-1:i>a?1:o<s?-1:+(o>s)}})(Bt||={});var NodeFileSystemProvider=class{constructor(){this.encoding=`utf-8`}async stat(e){let t=await f.promises.stat(e.fsPath);return{isFile:t.isFile(),isDirectory:t.isDirectory(),uri:e}}statSync(e){let t=f.statSync(e.fsPath);return{isFile:t.isFile(),isDirectory:t.isDirectory(),uri:e}}exists(e){return new Promise(t=>{f.stat(e.fsPath,e=>{t(!e)})})}existsSync(e){return f.existsSync(e.fsPath)}readBinary(e){return f.promises.readFile(e.fsPath)}readBinarySync(e){return f.readFileSync(e.fsPath)}readFile(e){return f.promises.readFile(e.fsPath,this.encoding)}readFileSync(e){return f.readFileSync(e.fsPath,this.encoding)}async readDirectory(e){return(await f.promises.readdir(e.fsPath,{withFileTypes:!0})).map(t=>({dirent:t,isFile:t.isFile(),isDirectory:t.isDirectory(),uri:J.joinPath(e,t.name)}))}readDirectorySync(e){return f.readdirSync(e.fsPath,{withFileTypes:!0}).map(t=>({dirent:t,isFile:t.isFile(),isDirectory:t.isDirectory(),uri:J.joinPath(e,t.name)}))}};function getSourceRegion(e){if(e){if(`astNode`in e)return getSourceRegionOfAstNode(e);if(Array.isArray(e))return e.reduce(mergeDocumentSegment,void 0);{let t=e;return copyDocumentSegment(t,isCstNode(t)?getDocumentURIOrUndefined(t?.root?.astNode??t?.astNode):void 0)}}}function isCstNode(e){return e!==void 0&&`element`in e&&`text`in e}function getDocumentURIOrUndefined(e){try{return getDocument(e).uri.toString()}catch{return}}function getSourceRegionOfAstNode(e){let{astNode:t,property:n,index:r}=e??{},i=t?.$cstNode??t?.$textRegion;if(t!==void 0&&i!==void 0){if(n===void 0)return copyDocumentSegment(i,getDocumentURI(t));{let getSingleOrCompoundRegion=e=>r!==void 0&&r>-1&&Array.isArray(t[n])?r<e.length?e[r]:void 0:e.reduce(mergeDocumentSegment,void 0);if(i.assignments?.[n]){let e=getSingleOrCompoundRegion(i.assignments[n]);return e&&copyDocumentSegment(e,getDocumentURI(t))}if(t.$cstNode){let e=getSingleOrCompoundRegion(findNodesForProperty(t.$cstNode,n));return e&&copyDocumentSegment(e,getDocumentURI(t))}return}}}function getDocumentURI(e){if(e.$cstNode)return getDocument(e)?.uri?.toString();if(e.$textRegion)return e.$textRegion.documentURI||new TreeStreamImpl(e,e=>e.$container?[e.$container]:[]).find(e=>e.$textRegion?.documentURI)?.$textRegion?.documentURI}function copyDocumentSegment(e,t){let n={offset:e.offset,end:e.end??e.offset+e.length,length:e.length??e.end-e.offset};return e.range&&(n.range=e.range),t??=e.fileURI,t&&(n.fileURI=t),n}function mergeDocumentSegment(e,t){if(!e)return t&&copyDocumentSegment(t);if(!t)return e&&copyDocumentSegment(e);let n=e.end??e.offset+e.length,r=t.end??t.offset+t.length,i=Math.min(e.offset,t.offset),a=Math.max(n,r),o={offset:i,end:a,length:a-i};if(e.range&&t.range&&(o.range={start:t.range.start.line<e.range.start.line||t.range.start.line===e.range.start.line&&t.range.start.character<e.range.start.character?t.range.start:e.range.start,end:t.range.end.line>e.range.end.line||t.range.end.line===e.range.end.line&&t.range.end.character>e.range.end.character?t.range.end:e.range.end}),e.fileURI||t.fileURI){let n=e.fileURI,r=t.fileURI;o.fileURI=n&&r&&n!==r?`<unmergable text regions of ${n}, ${r}>`:n??r}return o}var Context=class{constructor(e){this.defaultIndentation=` `,this.pendingIndent=!0,this.currentIndents=[],this.recentNonImmediateIndents=[],this.traceData=[],this.lines=[[]],this.length=0,typeof e==`string`?this.defaultIndentation=e:typeof e==`number`&&(this.defaultIndentation=``.padStart(e))}get content(){return this.lines.map(e=>e.join(``)).join(``)}get contentLength(){return this.length}get currentLineNumber(){return this.lines.length-1}get currentLineContent(){return this.lines[this.currentLineNumber].join(``)}get currentPosition(){return{offset:this.contentLength,line:this.currentLineNumber,character:this.currentLineContent.length}}append(e,t){if(e.length>0){let n=t&&this.currentPosition;this.lines[this.currentLineNumber].push(e),this.length+=e.length,n&&this.indentPendingTraceRegions(n)}}indentPendingTraceRegions(e){for(let t=this.traceData.length-1;t>=0;t--){let n=this.traceData[t];n.targetStart&&n.targetStart.offset===e.offset&&(n.targetStart=this.currentPosition)}}increaseIndent(e){this.currentIndents.push(e),e.indentImmediately||this.recentNonImmediateIndents.push(e)}decreaseIndent(){this.currentIndents.pop()}get relevantIndents(){return this.currentIndents.filter(e=>!this.recentNonImmediateIndents.includes(e))}resetCurrentLine(){this.length-=this.lines[this.currentLineNumber].join(``).length,this.lines[this.currentLineNumber]=[],this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}addNewLine(){this.lines.push([]),this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}pushTraceRegion(e){let t=createTraceRegion(e,this.currentPosition,e=>this.traceData[this.traceData.length-1]?.children?.push(e));return this.traceData.push(t),t}popTraceRegion(e){let t=this.traceData.pop();return this.assertTrue(t===e,`Trace region mismatch!`),t}getParentTraceSourceFileURI(){for(let e=this.traceData.length-1;e>-1;e--){let t=this.traceData[e].sourceRegion?.fileURI;if(t)return t}}assertTrue(e,t){if(!e)throw Error(t)}};function createTraceRegion(e,t,n){let r={sourceRegion:e,targetRegion:void 0,children:[],targetStart:t,complete:e=>(r.targetRegion={offset:r.targetStart.offset,end:e.offset,length:e.offset-r.targetStart.offset,range:{start:{line:r.targetStart.line,character:r.targetStart.character},end:{line:e.line,character:e.character}}},delete r.targetStart,r.children?.length===0&&delete r.children,r.targetRegion?.length&&n(r),delete r.complete,r)};return r}function processGeneratorNode(e,t){let n=new Context(t),r=n.pushTraceRegion(void 0);processNodeInternal(e,n),n.popTraceRegion(r),r.complete&&r.complete(n.currentPosition);let i=r.children&&r.children.length===1?r.children[0]:void 0,a=i?.targetRegion,o=r.targetRegion;return a&&i.sourceRegion&&a.offset===o.offset&&a.length===o.length?{text:n.content,trace:i}:{text:n.content,trace:r}}function processNodeInternal(e,t){typeof e==`string`?processStringNode(e,t):e instanceof IndentNode?processIndentNode(e,t):e instanceof $?processCompositeNode(e,t):e instanceof NewLineNode&&processNewLineNode(e,t)}function hasContent(e,t){return typeof e==`string`?e.length!==0:e instanceof $?e.contents.some(e=>hasContent(e,t)):e instanceof NewLineNode&&!(e.ifNotEmpty&&t.currentLineContent.length===0)}function processStringNode(e,t){e&&(handlePendingIndent(t,!1),t.append(e))}function handlePendingIndent(e,t){if(e.pendingIndent){let n=``;for(let r of e.relevantIndents.filter(e=>e.indentEmptyLines||!t))n+=r.indentation??e.defaultIndentation;e.append(n,!0),e.pendingIndent=!1}}function processCompositeNode(e,t){let n,r=getSourceRegion(e.tracedSource);r&&(n=t.pushTraceRegion(r));for(let n of e.contents)processNodeInternal(n,t);if(n){t.popTraceRegion(n);let e=t.getParentTraceSourceFileURI();e&&r?.fileURI===e&&delete r.fileURI,n.complete&&n.complete(t.currentPosition)}}function processIndentNode(e,t){if(hasContent(e,t)){e.indentImmediately&&!t.pendingIndent&&t.append(e.indentation??t.defaultIndentation,!0);try{t.increaseIndent(e),processCompositeNode(e,t)}finally{t.decreaseIndent()}}}function processNewLineNode(e,t){if(e.ifNotEmpty&&!hasNonWhitespace(t.currentLineContent))t.resetCurrentLine();else{handlePendingIndent(t,!0);let n=e.count;for(;n-->0;)t.append(e.lineDelimiter),t.addNewLine()}}function hasNonWhitespace(e){return e.trimStart()!==``}Object.freeze(`__«SKIP^NEW^LINE^IF^EMPTY»__`);const Vt=/\S|$/;function findIndentation(e){let t=e.filter(e=>e.length>0).map(e=>e.search(Vt)),n=t.length===0?0:Math.min(...t);return Math.max(0,n)}function expandToNode(e,...t){return composeFinalGeneratorNode(splitTemplateLinesAndMergeWithSubstitutions(e,t,findIndentationAndTemplateStructure(e)))}function expandTracedToNode(e,t,n){return(r,...i)=>traceToNode(e,t,n)(expandToNode(r,...i))}function findIndentationAndTemplateStructure(e){let t=e.join(`_`).split(rt),n=t.length>1&&t[0].trim().length===0,r=n&&t.length>1&&t[t.length-1].trim().length===0;if(t.length===1||t.length!==0&&t[0].trim().length!==0||t.length===2&&t[1].trim().length===0)return{indentation:0,omitFirstLine:n,omitLastLine:r,trimLastLine:t.length!==1&&t[t.length-1].trim().length===0};{let e=n?t.slice(1):t;e=r?e.slice(0,e.length-1):e,e=e.filter(e=>e.length!==0);let i=findIndentation(e);return{indentation:i,omitFirstLine:n,omitLastLine:r&&(t[t.length-1].length<i||!t[t.length-1].startsWith(e[0].substring(0,i)))}}}function splitTemplateLinesAndMergeWithSubstitutions(e,t,{indentation:n,omitFirstLine:r,omitLastLine:i,trimLastLine:a}){let o=[];e.forEach((e,i)=>{o.push(...e.split(rt).map((e,t)=>t===0||e.length<n?e:e.substring(n)).reduce(i===0?(e,t,n)=>n===0?r?[]:[t]:n===1&&e.length===0?[t]:e.concat(Ht,t):(e,t,n)=>n===0?[t]:e.concat(Ht,t),[]).filter(e=>typeof e!=`string`||e.length!==0).concat(isGeneratorNode(t[i])?t[i]:t[i]===void 0?i<t.length?Ut:[]:{content:String(t[i])}))});let s=o.length,c=s===0?void 0:o[s-1];return(i||a)&&typeof c==`string`&&c.trim().length===0?r&&s!==1&&o[s-2]===Ht?o.slice(0,s-2):o.slice(0,s-1):o}const Ht={isNewLine:!0},Ut={isUndefinedSegment:!0},isNewLineMarker=e=>e===Ht,isUndefinedSegmentMarker=e=>e===Ut,isSubstitutionWrapper=e=>e.content!==void 0;function composeFinalGeneratorNode(e){return e.reduce((t,n,r)=>isUndefinedSegmentMarker(n)?t:isNewLineMarker(n)?{node:r!==0&&(isUndefinedSegmentMarker(e[r-1])||isGeneratorNode(e[r-1]))||r>1&&typeof e[r-1]==`string`&&(isUndefinedSegmentMarker(e[r-2])||isGeneratorNode(e[r-2]))?t.node.appendNewLineIfNotEmpty():t.node.appendNewLine()}:(()=>{let i=(r===0||isNewLineMarker(e[r-1]))&&typeof n==`string`&&n.length!==0?n.substring(0,n.length-n.trimStart().length):``,a=isSubstitutionWrapper(n)?n.content:n,o;return{node:t.indented?t.node:i.length===0?t.node.append(a):t.node.indent({indentation:i,indentImmediately:!1,indentedChildren:e=>o=e.append(a)}),indented:o??t.indented?.append(a)}})(),{node:new $}).node}const Wt=typeof process>`u`?`
15
+ `:process.platform===`win32`?`\r
16
+ `:`
17
+ `;function isGeneratorNode(e){return e instanceof $||e instanceof IndentNode||e instanceof NewLineNode}function toString(e,t){return isGeneratorNode(e)?processGeneratorNode(e,t).text:String(e)}var $=class CompositeGeneratorNode{constructor(...e){this.contents=[],this.append(...e)}isEmpty(){return this.contents.length===0}trace(e,t,n){if(isAstNode(e)){if(this.tracedSource={astNode:e,property:t,index:n},this.tracedSource.property===void 0&&this.tracedSource.index!==void 0&&this.tracedSource.index>-1)throw Error(`Generation support: 'property' argument must not be 'undefined' if a non-negative value is assigned to 'index' in 'CompositeGeneratorNode.trace(...)'.`)}else this.tracedSource=e;return this}append(...e){for(let t of e)typeof t==`function`?t(this):t&&this.contents.push(t);return this}prepend(...e){return this.contents.unshift(...e.filter(e=>e!==void 0)),this}appendIf(e,...t){return e?this.append(...t):this}prependIf(e,...t){return e?this.prepend(...t):this}appendNewLine(){return this.append(Gt)}appendNewLineIf(e){return e?this.append(Gt):this}appendNewLineIfNotEmpty(){return this.append(Kt)}appendNewLineIfNotEmptyIf(e){return e?this.appendNewLineIfNotEmpty():this}appendTemplate(e,...t){return this.append(expandToNode(e,...t))}appendTemplateIf(e){return e?(e,...t)=>this.appendTemplate(e,...t):()=>this}indent(e){let{indentedChildren:t,indentation:n,indentEmptyLines:r,indentImmediately:i}=Array.isArray(e)||typeof e==`function`?{indentedChildren:e}:typeof e==`object`?e:{},a=new IndentNode(n,i,r);return this.contents.push(a),Array.isArray(t)?a.append(...t):t&&a.append(t),this}appendTraced(e,t,n){return r=>this.append(new CompositeGeneratorNode().trace(e,t,n).append(r))}appendTracedIf(e,t,n,r){return e?this.appendTraced(typeof t==`function`?t():t,n,r):()=>this}appendTracedTemplate(e,t,n){return(r,...i)=>this.append(expandTracedToNode(e,t,n)(r,...i))}appendTracedTemplateIf(e,t,n,r){return e?this.appendTracedTemplate(typeof t==`function`?t():t,n,r):()=>this}};function traceToNode(e,t,n){return r=>r instanceof $&&r.tracedSource===void 0?r.trace(e,t,n):new $().trace(e,t,n).append(r)}var IndentNode=class extends ${constructor(e,t=!0,n=!1){super(),typeof e==`string`?this.indentation=e:typeof e==`number`&&(this.indentation=``.padStart(e)),this.indentImmediately=t,this.indentEmptyLines=n}},NewLineNode=class{constructor(e=Wt,t=!1,n=1){this.lineDelimiter=e,this.ifNotEmpty=t,this.count=n}};const Gt=new NewLineNode,Kt=new NewLineNode(void 0,!0),defaultToGenerated=e=>e===void 0||typeof e==`string`||isGeneratorNode(e)?e:String(e);function joinToNode(e,t=defaultToGenerated,n={}){let r=typeof t==`function`?t:defaultToGenerated,{filter:i,prefix:a,suffix:o,separator:s,appendNewLineIfNotEmpty:c,skipNewLineAfterLastItem:l}=typeof t==`object`?t:n,u=typeof a==`function`?a:(()=>a),d=typeof o==`function`?o:(()=>o),doAppendNewLines=e=>{e.isEmpty()||(c===!0||c===1?e.appendNewLineIfNotEmpty():e.append(new NewLineNode(void 0,!0,c)))};return reduceWithIsLast(e,(e,t,n,a)=>{if(i&&!i(t,n,a))return e;let o=r(t,n,a);return o===void 0?e:(e??=new $).appendIf(!e.isEmpty(),s).appendIf(c!==void 0,doAppendNewLines).append(u(t,n,a)).append(o).append(d(t,n,a))})?.appendIf(!l&&c!==void 0,doAppendNewLines)}function reduceWithIsLast(e,t,n){let r=e[Symbol.iterator](),i=r.next(),a=0,o=n;for(;!i.done;){let e=r.next();o=t(o,i.value,a,!!e.done),i=e,a++}return o}export{G as $,DefaultNameProvider as A,J as B,SimpleCache as C,StreamScope as D,MapScope as E,interruptAndCheck as F,st as G,findNodeForKeyword as H,isOperationCancelled as I,getDocument as J,nt as K,DefaultValueConverter as L,DefaultLangiumDocuments as M,X as N,DefaultScopeComputation as O,be as P,findCommentNode as Q,Y as R,ContextCache as S,mt as T,findNodeForProperty as U,DefaultCompletionProvider as V,findNodesForProperty as W,streamAllContents as X,hasContainerOfType as Y,et as Z,loadGrammarFromJson as _,NodeFileSystemProvider as a,isAstNode as at,inject as b,createDefaultModule as c,AbstractSemanticTokenProvider as d,stream as et,AstNodeHoverProvider as f,DefaultIndexManager as g,DefaultWorkspaceManager as h,toString as i,AbstractAstReflection as it,isNamed as j,MultiMap as k,createDefaultSharedModule as l,DefaultDocumentValidator as m,$ as n,isKeyword as nt,AbstractFormatter as o,DefaultDocumentHighlightProvider as p,getContainerOfType as q,NewLineNode as r,isRuleCall as rt,Bt as s,joinToNode as t,isCrossReference as tt,DefaultWorkspaceSymbolProvider as u,Ct as v,WorkspaceCache as w,DefaultScopeProvider as x,JSDocDocumentationProvider as y,y as z};
@@ -0,0 +1,2 @@
1
+ import"../rolldown-runtime.mjs";function defaultStringLength(e){return e.length}function markdownTable(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||defaultStringLength,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=serialize(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=toAlignment(r[d]);else{let e=toAlignment(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&(n.alignDelimiters!==!1||i!==``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
2
+ `)}function serialize(e){return e==null?``:String(e)}function toAlignment(e){let t=typeof e==`string`?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}export{markdownTable as t};
@@ -0,0 +1 @@
1
+ import"../rolldown-runtime.mjs";const convert=(function(e){if(e==null)return ok;if(typeof e==`function`)return castFactory(e);if(typeof e==`object`)return Array.isArray(e)?anyFactory(e):propsFactory(e);if(typeof e==`string`)return typeFactory(e);throw Error(`Expected function, string, or object as test`)});function anyFactory(e){let t=[],n=-1;for(;++n<e.length;)t[n]=convert(e[n]);return castFactory(any);function any(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function propsFactory(e){let t=e;return castFactory(all);function all(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function typeFactory(e){return castFactory(type);function type(t){return t&&t.type===e}}function castFactory(e){return check;function check(t,n,r){return!!(looksLikeANode(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function ok(){return!0}function looksLikeANode(e){return typeof e==`object`&&!!e&&`type`in e}function color(e){return`\x1B[33m`+e+`\x1B[39m`}const e=[];function visitParents(t,n,r,i){let a;typeof n==`function`&&typeof r!=`function`?(i=r,r=n):a=n;let o=convert(a),s=i?-1:1;factory(t,void 0,[])();function factory(t,a,c){let l=t&&typeof t==`object`?t:{};if(typeof l.type==`string`){let e=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(visit,"name",{value:`node (`+color(t.type+(e?`<`+e+`>`:``))+`)`})}return visit;function visit(){let l=e,u,d,f;if((!n||o(t,a,c[c.length-1]||void 0))&&(l=toResult(r(t,c)),l[0]===!1))return l;if(`children`in t&&t.children){let e=t;if(e.children&&l[0]!==`skip`)for(d=(i?e.children.length:-1)+s,f=c.concat(e);d>-1&&d<e.children.length;){let t=e.children[d];if(u=factory(t,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+s}}return l}}}function toResult(t){return Array.isArray(t)?t:typeof t==`number`?[!0,t]:t==null?e:[t]}function escapeStringRegexp(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function findAndReplace(e,t,n){let r=convert((n||{}).ignore||[]),i=toPairs(t),a=-1;for(;++a<i.length;)visitParents(e,`text`,visitor);function visitor(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return handler(e,t)}function handler(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function toPairs(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([toExpression(e[0]),toFunction(e[1])])}return t}function toExpression(e){return typeof e==`string`?new RegExp(escapeStringRegexp(e),`g`):e}function toFunction(e){return typeof e==`function`?e:function(){return e}}export{visitParents as n,convert as r,findAndReplace as t};