UNPKG

mermaid

Version:

Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.

8 lines • 773 kB
{
  "version": 3,
  "sources": ["../../../src/diagrams/common/parser/runChevrotainParse.ts", "../../../src/diagrams/usecase/usecaseTypes.ts", "../../../src/diagrams/usecase/usecaseDb.ts", "../../../../../node_modules/.pnpm/@chevrotain+utils@13.2.0/node_modules/@chevrotain/utils/src/print.ts", "../../../../../node_modules/.pnpm/@chevrotain+utils@13.2.0/node_modules/@chevrotain/utils/src/timer.ts", "../../../../../node_modules/.pnpm/@chevrotain+utils@13.2.0/node_modules/@chevrotain/utils/src/to-fast-properties.ts", "../../../../../node_modules/.pnpm/@chevrotain+gast@13.2.0/node_modules/@chevrotain/gast/src/model.ts", "../../../../../node_modules/.pnpm/@chevrotain+gast@13.2.0/node_modules/@chevrotain/gast/src/visitor.ts", "../../../../../node_modules/.pnpm/@chevrotain+gast@13.2.0/node_modules/@chevrotain/gast/src/helpers.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/rest.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/first.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/constants.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/follow.ts", "../../../../../node_modules/.pnpm/@chevrotain+regexp-to-ast@13.2.0/node_modules/@chevrotain/regexp-to-ast/src/utils.ts", "../../../../../node_modules/.pnpm/@chevrotain+regexp-to-ast@13.2.0/node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts", "../../../../../node_modules/.pnpm/@chevrotain+regexp-to-ast@13.2.0/node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts", "../../../../../node_modules/.pnpm/@chevrotain+regexp-to-ast@13.2.0/node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/reg_exp_parser.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/reg_exp.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/lexer.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/tokens.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/lexer_errors_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/lexer_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/scan/tokens_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/errors_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/resolver.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/interpreter.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/lookahead.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/checks.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/gast/gast_resolver_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/exceptions_public.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/recoverable.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/keys.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/grammar/llk_lookahead.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/looksahead.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/cst/cst.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/lang/lang_extensions.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/cst/cst_visitor.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/tree_builder.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/lexer_adapter.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/recognizer_api.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/recognizer_engine.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/error_handler.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/gast_recorder.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/traits/perf_tracer.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/utils/apply_mixins.ts", "../../../../../node_modules/.pnpm/chevrotain@13.2.0/node_modules/chevrotain/src/parse/parser/parser.ts", "../../../src/diagrams/usecase/parser/usecase.tokens.ts", "../../../src/diagrams/usecase/parser/usecase.lexer.ts", "../../../src/diagrams/usecase/parser/usecase.parser.ts", "../../../src/diagrams/usecase/parser/usecaseJson.ts", "../../../src/diagrams/usecase/usecaseAst.ts", "../../../src/diagrams/usecase/parser/usecaseModelBuilder.ts", "../../../src/diagrams/usecase/parser/usecase.visitor.ts", "../../../src/diagrams/usecase/parser/usecase.chevrotain.ts", "../../../src/diagrams/usecase/usecaseRenderer.ts", "../../../src/diagrams/usecase/styles.ts", "../../../src/diagrams/usecase/usecaseDiagram.ts"],
  "sourcesContent": ["import type { CstNode, CstParser, Lexer } from 'chevrotain';\n\ninterface ChevrotainParseConfig {\n  diagramType: string;\n  lexer: Lexer;\n  parser: CstParser;\n  entry: () => CstNode;\n  visit: (cst: CstNode) => void;\n}\n\n/** Chevrotain marks missing locations (EOF, inserted tokens) with -1 (v13+) or NaN (older). */\nexport const isKnownLocation = (value: number | undefined): value is number =>\n  value !== undefined && value >= 0;\n\n/** Runs a singleton lexer/parser pair and visits the resulting CST. */\nexport function runChevrotainParse(config: ChevrotainParseConfig, input: string): void {\n  const lexResult = config.lexer.tokenize(input);\n  if (lexResult.errors.length > 0) {\n    // Lexer failures never reach `parser.errors`, so callers cannot enrich them the way\n    // they enrich parser errors. Attach the position here so both failure modes report\n    // the same fields.\n    const lexError = lexResult.errors[0];\n    const start = isKnownLocation(lexError.offset) ? lexError.offset : input.length;\n    const end = start + (isKnownLocation(lexError.length) ? lexError.length : 0);\n    throw new Error(\n      `Error lexing ${config.diagramType} diagram: ${lexError.message} at line ${\n        lexError.line ?? 1\n      }, column ${lexError.column ?? 1} [${start},${end})`\n    );\n  }\n\n  config.parser.input = lexResult.tokens;\n  const cst = config.entry();\n  if (config.parser.errors.length > 0) {\n    throw new Error(\n      `Error parsing ${config.diagramType} diagram: ${config.parser.errors[0].message}`\n    );\n  }\n\n  config.visit(cst);\n}\n", "import type { DiagramDB } from '../../diagram-api/types.js';\nimport type { MermaidConfig, UsecaseDiagramConfig } from '../../config.type.js';\nimport type { ClusterNode, Edge, LayoutData, NonClusterNode } from '../../rendering-util/types.js';\n\nexport type LabelType = 'text' | 'markdown';\nexport type ActorType = 'normal' | 'hollow' | 'awesome' | 'icon';\nexport type UseCaseShape = 'ellipse' | 'rect';\nexport type BoundaryType = 'rect' | 'package';\nexport type RelationshipType = 'association' | 'include' | 'extend' | 'generalization';\nexport type Animation = 'fast' | 'slow';\n\nexport interface Actor {\n  id: string;\n  label: string;\n  labelType: LabelType;\n  type: ActorType;\n  icon?: string;\n  business: boolean;\n  stereotype?: string;\n  parentId?: string;\n  classes: string[];\n  styles: string[];\n}\n\nexport interface UseCase {\n  id: string;\n  label: string;\n  labelType: LabelType;\n  shape: UseCaseShape;\n  business: boolean;\n  stereotype?: string;\n  parentId?: string;\n  classes: string[];\n  styles: string[];\n}\n\nexport interface SystemBoundary {\n  id: string;\n  label: string;\n  labelType: LabelType;\n  type: BoundaryType;\n  members: string[];\n  classes: string[];\n  styles: string[];\n}\n\nexport const ARROW_TYPE = {\n  SOLID_ARROW: 0,\n  BACK_ARROW: 1,\n  LINE_SOLID: 2,\n  CIRCLE_ARROW: 3,\n  CROSS_ARROW: 4,\n  CIRCLE_ARROW_REVERSED: 5,\n  CROSS_ARROW_REVERSED: 6,\n} as const;\n\nexport type ArrowType = (typeof ARROW_TYPE)[keyof typeof ARROW_TYPE];\n\nexport interface Relationship {\n  id: string;\n  explicitId: boolean;\n  source: string;\n  target: string;\n  type: RelationshipType;\n  arrowType: ArrowType;\n  label?: string;\n  labelType?: LabelType;\n  minlen: number;\n  classes: string[];\n  styles: string[];\n  animate: boolean;\n  animation?: Animation;\n}\n\nexport interface UsecaseNote {\n  id: string;\n  target: string;\n  label: string;\n  labelType: LabelType;\n}\n\nexport interface UsecaseJsonNode {\n  id: string;\n  value: Record<string, unknown>;\n  propertyOrder: Record<string, string[]>;\n  classes: string[];\n  styles: string[];\n}\n\n// Direction types for usecase diagrams\nexport type Direction = 'TB' | 'TD' | 'BT' | 'RL' | 'LR';\n\nexport const DEFAULT_DIRECTION: Direction = 'LR';\n\nexport interface ClassDef {\n  id: string;\n  styles: string[];\n}\n\nexport interface UsecaseJsonRow {\n  /** The visual key cell. Scalar-array rows after the first use an empty string. */\n  key: string;\n  /** The key repeated for assistive technology even when the visual key is blank. */\n  accessibleKey: string;\n  value: string;\n}\n\nexport type UsecaseLayoutNodeShape =\n  | 'usecaseActor'\n  | 'usecaseActorHollow'\n  | 'usecaseActorAwesome'\n  | 'usecaseActorIcon'\n  | 'usecaseEllipse'\n  | 'rect'\n  | 'usecaseBusiness'\n  | 'note'\n  | 'usecaseJsonTable';\n\nexport type UsecaseLayoutNode = Omit<NonClusterNode, 'shape'> & {\n  shape: UsecaseLayoutNodeShape;\n  labelType: LabelType;\n  actorType?: ActorType;\n  business?: boolean;\n  stereotype?: string;\n  jsonRows?: UsecaseJsonRow[];\n  noteTarget?: string;\n  noteTargetLabel?: string;\n};\n\nexport type UsecaseLayoutCluster = ClusterNode & {\n  shape: 'usecaseSystemBoundary';\n  labelType: LabelType;\n  boundaryType: BoundaryType;\n};\n\nexport interface UsecaseLayoutEdge extends Edge {\n  start: string;\n  end: string;\n  source: string;\n  sourceLabel: string;\n  targetLabel: string;\n  target: string;\n  type: 'edge';\n  relationshipType: RelationshipType | 'note';\n  pattern: 'solid' | 'dotted';\n  arrowTypeStart: string;\n  arrowTypeEnd: string;\n  internal: boolean;\n  style: string[];\n  cssCompiledStyles: string[];\n  minlen: number;\n}\n\nexport interface UsecaseLayoutData extends Omit<LayoutData, 'nodes' | 'edges'> {\n  nodes: (UsecaseLayoutNode | UsecaseLayoutCluster)[];\n  edges: UsecaseLayoutEdge[];\n  config: MermaidConfig;\n  type: 'usecase';\n  layoutAlgorithm: string;\n  direction: Direction;\n  nodeSpacing: number;\n  actorFontSize: number;\n  actorFontFamily: string;\n  actorFontWeight: string;\n  usecaseFontSize: number;\n  usecaseFontFamily: string;\n  usecaseFontWeight: string;\n  rankSpacing: number;\n  diagramPadding: number;\n  useMaxWidth: boolean;\n  markers: ('point' | 'circle' | 'cross' | 'extension')[];\n}\n\nexport type Span = [start: number, end: number];\n\nexport interface GraphNode {\n  label?: string;\n  shape?: string;\n  classes?: string[];\n  styles?: string[];\n  attrs?: Record<string, unknown>;\n}\n\nexport interface GraphEdge {\n  id: string;\n  source: string;\n  target: string;\n  label?: string;\n  classes?: string[];\n  styles?: string[];\n  attrs?: Record<string, unknown>;\n}\n\nexport interface GraphGroup {\n  title?: string;\n  parent?: string;\n  nodes: string[];\n  direction?: Exclude<Direction, 'TD'>;\n  classes?: string[];\n  styles?: string[];\n  attrs?: Record<string, unknown>;\n}\n\nexport interface MetadataOccurrence {\n  key: string;\n  span: Span;\n  keySpan: Span;\n  valueSpan: Span;\n}\n\nexport interface NodeOccurrence {\n  id: string;\n  span: Span;\n  idSpan: Span;\n  labelSpan?: Span;\n  defines?: boolean;\n  stereotypeSpan?: Span;\n  metadata?: MetadataOccurrence[];\n  classSpans?: Span[];\n}\n\nexport interface EdgeOccurrence {\n  id: string;\n  span: Span;\n  labelSpan?: Span;\n  idSpan?: Span;\n  metadata?: MetadataOccurrence[];\n  classSpans?: Span[];\n}\n\nexport interface GraphStatement {\n  kind:\n    | 'node'\n    | 'edge'\n    | 'group'\n    | 'note'\n    | 'json'\n    | 'metadata'\n    | 'edgeMetadata'\n    | 'classDef'\n    | 'classAssign'\n    | 'style'\n    | 'linkStyle'\n    | 'click'\n    | 'direction'\n    | 'accTitle'\n    | 'accDescr'\n    | 'comment'\n    | 'blank'\n    | 'frontmatter';\n  span: Span;\n  nodes?: NodeOccurrence[];\n  edges?: EdgeOccurrence[];\n  group?: string;\n  idSpan?: Span;\n  titleSpan?: Span;\n  endSpan?: Span;\n  ref?: string;\n  refSpan?: Span;\n  children?: GraphStatement[];\n  metadata?: MetadataOccurrence[];\n  stereotypeSpan?: Span;\n  classSpans?: Span[];\n}\n\nexport interface GraphAST {\n  version: 1;\n  diagramType: 'usecase';\n  source: string;\n  header: {\n    keyword: 'usecase';\n    direction: Exclude<Direction, 'TD'>;\n    span: Span;\n  };\n  accTitle?: string;\n  accDescr?: string;\n  nodes: Record<string, GraphNode>;\n  edges: GraphEdge[];\n  groups: Record<string, GraphGroup>;\n  classDefs: Record<string, { styles: string[] }>;\n  statements: GraphStatement[];\n}\n\nexport type UsecaseSymbolKind = 'actor' | 'usecase' | 'boundary' | 'json' | 'edge';\n\nexport interface UsecaseFields {\n  actors: Map<string, Actor>;\n  useCases: Map<string, UseCase>;\n  systemBoundaries: Map<string, SystemBoundary>;\n  relationships: Relationship[];\n  notes: Map<string, UsecaseNote>;\n  jsonNodes: Map<string, UsecaseJsonNode>;\n  classDefs: Map<string, ClassDef>;\n  symbols: Map<string, UsecaseSymbolKind>;\n  direction: Direction;\n  relationshipCounter: number;\n  noteCounter: number;\n  accTitle: string;\n  accDescription: string;\n  ast: GraphAST | undefined;\n  config: Required<UsecaseDiagramConfig>;\n}\n\nexport interface UsecaseDB extends DiagramDB {\n  getConfig: () => Required<UsecaseDiagramConfig>;\n  createModel: () => UsecaseFields;\n  commit: (model: UsecaseFields) => void;\n  getAST: () => GraphAST | undefined;\n\n  getActors: () => ReadonlyMap<string, Actor>;\n  getActor: (id: string) => Actor | undefined;\n  getUseCases: () => ReadonlyMap<string, UseCase>;\n  getUseCase: (id: string) => UseCase | undefined;\n  getSystemBoundaries: () => ReadonlyMap<string, SystemBoundary>;\n  getSystemBoundary: (id: string) => SystemBoundary | undefined;\n  getRelationships: () => readonly Relationship[];\n  getNotes: () => ReadonlyMap<string, UsecaseNote>;\n  getNote: (id: string) => UsecaseNote | undefined;\n  getJsonNodes: () => ReadonlyMap<string, UsecaseJsonNode>;\n  getJsonNode: (id: string) => UsecaseJsonNode | undefined;\n  getClassDefs: () => ReadonlyMap<string, ClassDef>;\n  getClassDef: (id: string) => ClassDef | undefined;\n  getDirection: () => Direction;\n\n  getData: () => UsecaseLayoutData;\n  clear: () => void;\n}\n", "import {\n  setAccTitle,\n  getAccTitle,\n  setDiagramTitle,\n  getDiagramTitle,\n  getAccDescription,\n  setAccDescription,\n  clear as commonClear,\n} from '../common/commonDb.js';\nimport type {\n  Actor,\n  ClassDef,\n  Direction,\n  GraphAST,\n  Relationship,\n  SystemBoundary,\n  UseCase,\n  UsecaseDB,\n  UsecaseFields,\n  UsecaseJsonNode,\n  UsecaseJsonRow,\n  UsecaseLayoutData,\n  UsecaseLayoutEdge,\n  UsecaseLayoutNode,\n  UsecaseNote,\n} from './usecaseTypes.js';\nimport { DEFAULT_DIRECTION, ARROW_TYPE } from './usecaseTypes.js';\nimport type { UsecaseDiagramConfig } from '../../config.type.js';\nimport DEFAULT_CONFIG from '../../defaultConfig.js';\nimport { getConfig as getGlobalConfig } from '../../diagram-api/diagramAPI.js';\nimport { sanitizeText } from '../common/common.js';\n\nexport const DEFAULT_USECASE_CONFIG: Required<UsecaseDiagramConfig> = DEFAULT_CONFIG.usecase;\n\nconst createModel = (): UsecaseFields => ({\n  actors: new Map(),\n  useCases: new Map(),\n  systemBoundaries: new Map(),\n  relationships: [],\n  notes: new Map(),\n  jsonNodes: new Map(),\n  classDefs: new Map(),\n  symbols: new Map(),\n  direction: DEFAULT_DIRECTION,\n  relationshipCounter: 0,\n  noteCounter: 0,\n  accTitle: '',\n  accDescription: '',\n  ast: undefined,\n  config: structuredClone(DEFAULT_USECASE_CONFIG),\n});\n\nconst assertCompleteModel = (model: UsecaseFields): void => {\n  if (\n    !(model.actors instanceof Map) ||\n    !(model.useCases instanceof Map) ||\n    !(model.systemBoundaries instanceof Map) ||\n    !Array.isArray(model.relationships) ||\n    !(model.notes instanceof Map) ||\n    !(model.jsonNodes instanceof Map) ||\n    !(model.classDefs instanceof Map) ||\n    !(model.symbols instanceof Map) ||\n    !['TB', 'TD', 'BT', 'RL', 'LR'].includes(model.direction) ||\n    !Number.isSafeInteger(model.relationshipCounter) ||\n    model.relationshipCounter < 0 ||\n    !Number.isSafeInteger(model.noteCounter) ||\n    model.noteCounter < 0 ||\n    typeof model.accTitle !== 'string' ||\n    typeof model.accDescription !== 'string' ||\n    !model.config\n  ) {\n    throw new Error('Cannot commit an incomplete usecase model');\n  }\n};\n\nlet state = createModel();\n\nconst getConfig = (): Required<UsecaseDiagramConfig> => structuredClone(state.config);\nconst getAST = (): GraphAST | undefined => state.ast;\n\nconst commit = (model: UsecaseFields): void => {\n  const nextState = structuredClone(model);\n  assertCompleteModel(nextState);\n  const previousAccTitle = getAccTitle();\n  const previousAccDescription = getAccDescription();\n  try {\n    setAccTitle(nextState.accTitle);\n    setAccDescription(nextState.accDescription);\n    state = nextState;\n  } catch (error) {\n    setAccTitle(previousAccTitle);\n    setAccDescription(previousAccDescription);\n    throw error;\n  }\n};\n\nconst clear = (): void => {\n  state = createModel();\n  commonClear();\n};\n\nconst getActors = (): ReadonlyMap<string, Actor> => state.actors;\nconst getActor = (id: string): Actor | undefined => state.actors.get(id);\nconst getUseCases = (): ReadonlyMap<string, UseCase> => state.useCases;\nconst getUseCase = (id: string): UseCase | undefined => state.useCases.get(id);\nconst getSystemBoundaries = (): ReadonlyMap<string, SystemBoundary> => state.systemBoundaries;\nconst getSystemBoundary = (id: string): SystemBoundary | undefined =>\n  state.systemBoundaries.get(id);\nconst getRelationships = (): readonly Relationship[] => state.relationships;\nconst getNotes = (): ReadonlyMap<string, UsecaseNote> => state.notes;\nconst getNote = (id: string): UsecaseNote | undefined => state.notes.get(id);\nconst getJsonNodes = (): ReadonlyMap<string, UsecaseJsonNode> => state.jsonNodes;\nconst getJsonNode = (id: string): UsecaseJsonNode | undefined => state.jsonNodes.get(id);\nconst getClassDefs = (): ReadonlyMap<string, ClassDef> => state.classDefs;\nconst getClassDef = (id: string): ClassDef | undefined => state.classDefs.get(id);\nconst getDirection = (): Direction => state.direction;\n\nconst getCompiledStyles = (classNames: readonly string[]): string[] => {\n  const compiled = new Map<string, string>();\n  for (const className of ['default', ...classNames]) {\n    const definition = state.classDefs.get(className);\n    if (!definition) {\n      continue;\n    }\n    for (const rawStyle of definition.styles) {\n      const style = rawStyle.trim();\n      const separator = style.indexOf(':');\n      const property = (separator === -1 ? style : style.slice(0, separator)).trim();\n      if (property) {\n        compiled.set(property, style);\n      }\n    }\n  }\n  return [...compiled.values()];\n};\n\nconst escapeJsonPointerPart = (part: string): string =>\n  part.replaceAll('~', '~0').replaceAll('/', '~1');\n\nconst displayJsonScalar = (value: string | number | boolean | null): string =>\n  typeof value === 'string' ? value : value === null ? 'null' : String(value);\n\ntype JsonCellSanitizer = (value: string) => string;\n\n/**\n * Flattens a JSON object once into renderer-ready rows. The supplied sanitizer keeps this helper\n * deterministic and makes the security policy an explicit conversion input.\n */\nconst flattenJsonRows = (\n  value: Record<string, unknown>,\n  propertyOrder: Readonly<Record<string, readonly string[]>>,\n  sanitize: JsonCellSanitizer = (cell) => cell\n): UsecaseJsonRow[] => {\n  const rows: UsecaseJsonRow[] = [];\n\n  const append = (key: string, accessibleKey: string, cellValue: string): void => {\n    rows.push({\n      key: sanitize(key),\n      accessibleKey: sanitize(accessibleKey),\n      value: sanitize(cellValue),\n    });\n  };\n\n  const visit = (current: unknown, path: string, pointer: string): void => {\n    if (Array.isArray(current)) {\n      if (current.length === 0) {\n        append(path, path, '[]');\n        return;\n      }\n\n      const scalarArray = current.every(\n        (item) => item === null || ['string', 'number', 'boolean'].includes(typeof item)\n      );\n      if (scalarArray) {\n        for (const [index, element] of current.entries()) {\n          append(\n            index === 0 ? path : '',\n            path,\n            displayJsonScalar(element as string | number | boolean | null)\n          );\n        }\n        return;\n      }\n\n      for (const [index, element] of current.entries()) {\n        visit(element, `${path}[${index}]`, `${pointer}/${index}`);\n      }\n      return;\n    }\n\n    if (current !== null && typeof current === 'object') {\n      const object = current as Record<string, unknown>;\n      const keys = propertyOrder[pointer] ?? Object.keys(object);\n      if (keys.length === 0) {\n        append(path, path, '{}');\n        return;\n      }\n\n      for (const key of keys) {\n        const childPath = path ? `${path}.${key}` : key;\n        visit(object[key], childPath, `${pointer}/${escapeJsonPointerPart(key)}`);\n      }\n      return;\n    }\n\n    append(path, path, displayJsonScalar(current as string | number | boolean | null));\n  };\n\n  visit(value, '', '');\n  return rows;\n};\n\nconst actorShape = (actor: Actor): UsecaseLayoutNode['shape'] => {\n  switch (actor.type) {\n    case 'hollow':\n      return 'usecaseActorHollow';\n    case 'awesome':\n      return 'usecaseActorAwesome';\n    case 'icon':\n      return 'usecaseActorIcon';\n    case 'normal':\n      return 'usecaseActor';\n  }\n};\n\nconst useCaseShape = (useCase: UseCase): UsecaseLayoutNode['shape'] => {\n  if (useCase.shape === 'ellipse') {\n    return useCase.business ? 'usecaseBusiness' : 'usecaseEllipse';\n  }\n  return useCase.shape;\n};\n\nconst associationMarkers = (\n  arrowType: Relationship['arrowType']\n): Pick<UsecaseLayoutEdge, 'arrowTypeStart' | 'arrowTypeEnd'> => {\n  switch (arrowType) {\n    case ARROW_TYPE.SOLID_ARROW:\n      return { arrowTypeStart: 'none', arrowTypeEnd: 'arrow_point' };\n    case ARROW_TYPE.BACK_ARROW:\n      return { arrowTypeStart: 'arrow_point', arrowTypeEnd: 'none' };\n    case ARROW_TYPE.CIRCLE_ARROW:\n      return { arrowTypeStart: 'none', arrowTypeEnd: 'arrow_circle' };\n    case ARROW_TYPE.CROSS_ARROW:\n      return { arrowTypeStart: 'none', arrowTypeEnd: 'arrow_cross' };\n    case ARROW_TYPE.CIRCLE_ARROW_REVERSED:\n      return { arrowTypeStart: 'arrow_circle', arrowTypeEnd: 'none' };\n    case ARROW_TYPE.CROSS_ARROW_REVERSED:\n      return { arrowTypeStart: 'arrow_cross', arrowTypeEnd: 'none' };\n    case ARROW_TYPE.LINE_SOLID:\n      return { arrowTypeStart: 'none', arrowTypeEnd: 'none' };\n  }\n};\n\nconst relationshipVisuals = (\n  relationship: Relationship\n): Pick<\n  UsecaseLayoutEdge,\n  'arrowTypeStart' | 'arrowTypeEnd' | 'pattern' | 'label' | 'labelType'\n> => {\n  switch (relationship.type) {\n    case 'include':\n    case 'extend':\n      return {\n        arrowTypeStart: 'none',\n        arrowTypeEnd: 'arrow_point',\n        pattern: 'dotted',\n        label: relationship.type,\n        labelType: 'text',\n      };\n    case 'generalization':\n      return {\n        arrowTypeStart: 'none',\n        arrowTypeEnd: 'extension',\n        pattern: 'solid',\n      };\n    case 'association':\n      return {\n        ...associationMarkers(relationship.arrowType),\n        pattern: 'solid',\n        ...(relationship.label ? { label: relationship.label } : {}),\n        ...(relationship.labelType ? { labelType: relationship.labelType } : {}),\n      };\n  }\n};\n\nconst animationClasses = (relationship: Relationship): string[] =>\n  relationship.animate || relationship.animation\n    ? [`edge-animation-${relationship.animation ?? 'fast'}`]\n    : [];\n\nconst classNames = (...names: (string | false | undefined)[]): string =>\n  names.filter((name): name is string => Boolean(name)).join(' ');\n\n// Convert the committed use-case model to the unified renderer contract without semantic re-parsing.\nconst getData = (): UsecaseLayoutData => {\n  const globalConfig = getGlobalConfig();\n  const config: Required<UsecaseDiagramConfig> = {\n    ...state.config,\n    ...globalConfig.usecase,\n  };\n  const sanitize = (value: string): string => sanitizeText(value, globalConfig);\n  const endpointLabel = (id: string): string =>\n    sanitize(\n      state.actors.get(id)?.label ??\n        state.useCases.get(id)?.label ??\n        state.jsonNodes.get(id)?.id ??\n        state.notes.get(id)?.label ??\n        id\n    );\n  const nodes: UsecaseLayoutData['nodes'] = [];\n  const edges: UsecaseLayoutEdge[] = [];\n\n  /**\n   * Two counters, because the two kinds of slot mean different things.\n   *\n   * `boundaryColorIndex` numbers the system boundaries from zero in declaration order, the\n   * way `flowDb` numbers flowchart subgraphs. Here the counter carries real information --\n   * which group a thing belongs to -- so boundary N takes palette slot N, and that holds\n   * under the default colour scheme as well as under `rotate`. It stays stable as long as\n   * the boundary order does, which is the property that makes a counter defensible for a\n   * container and not for a leaf.\n   *\n   * `colorIndex` numbers actors and use cases together, and is consumed only by the opt-in\n   * `usecase.colorScheme: 'rotate'`. Sharing one cycle between the two kinds is what stops\n   * an actor and a use case landing on the same colour and reading as linked. Notes and\n   * JSON tables are deliberately not counted: a note carries the theme's fixed note colour\n   * and a JSON table is reference data, so neither is a participant and neither may shift\n   * the cycle.\n   *\n   * Both are assigned unconditionally -- `stampColorSlot` is a no-op for every theme\n   * without a palette, and `getData` has no business knowing which theme or scheme is\n   * active.\n   */\n  let colorIndex = 0;\n  let boundaryColorIndex = 0;\n\n  for (const actor of state.actors.values()) {\n    nodes.push({\n      id: actor.id,\n      label: sanitize(actor.label),\n      labelType: actor.labelType,\n      shape: actorShape(actor),\n      isGroup: false,\n      padding: 10,\n      look: globalConfig.look,\n      colorIndex: colorIndex++,\n      cssClasses: classNames(\n        'default',\n        'usecase-actor',\n        `usecase-actor-${actor.type}`,\n        actor.business && 'usecase-business',\n        ...actor.classes\n      ),\n      cssStyles: [...actor.styles],\n      cssCompiledStyles: getCompiledStyles(actor.classes),\n      actorType: actor.type,\n      business: actor.business,\n      ...(actor.icon ? { icon: actor.icon } : {}),\n      ...(actor.stereotype ? { stereotype: sanitize(actor.stereotype) } : {}),\n      ...(actor.parentId ? { parentId: actor.parentId } : {}),\n    });\n  }\n\n  for (const useCase of state.useCases.values()) {\n    nodes.push({\n      id: useCase.id,\n      label: sanitize(useCase.label),\n      labelType: useCase.labelType,\n      shape: useCaseShape(useCase),\n      isGroup: false,\n      padding: useCase.shape === 'ellipse' ? 20 : 10,\n      look: globalConfig.look,\n      colorIndex: colorIndex++,\n      cssClasses: classNames(\n        'default',\n        'usecase-element',\n        `usecase-${useCase.shape}`,\n        useCase.business && 'usecase-business',\n        ...useCase.classes\n      ),\n      cssStyles: [...useCase.styles],\n      cssCompiledStyles: getCompiledStyles(useCase.classes),\n      business: useCase.business,\n      ...(useCase.stereotype ? { stereotype: sanitize(useCase.stereotype) } : {}),\n      ...(useCase.parentId ? { parentId: useCase.parentId } : {}),\n    });\n  }\n\n  for (const note of state.notes.values()) {\n    nodes.push({\n      id: note.id,\n      label: sanitize(note.label),\n      labelType: note.labelType,\n      shape: 'note',\n      isGroup: false,\n      padding: 10,\n      look: globalConfig.look,\n      cssClasses: 'default usecase-note',\n      cssStyles: [],\n      cssCompiledStyles: getCompiledStyles([]),\n      noteTarget: note.target,\n      noteTargetLabel: sanitize(\n        state.actors.get(note.target)?.label ??\n          state.useCases.get(note.target)?.label ??\n          state.jsonNodes.get(note.target)?.id ??\n          note.target\n      ),\n    });\n  }\n\n  for (const json of state.jsonNodes.values()) {\n    nodes.push({\n      id: json.id,\n      label: sanitize(json.id),\n      labelType: 'text',\n      shape: 'usecaseJsonTable',\n      isGroup: false,\n      padding: 10,\n      look: globalConfig.look,\n      cssClasses: classNames('default', 'usecase-json-table', ...json.classes),\n      cssStyles: [...json.styles],\n      cssCompiledStyles: getCompiledStyles(json.classes),\n      jsonRows: flattenJsonRows(json.value, json.propertyOrder, sanitize),\n    });\n  }\n\n  for (const boundary of state.systemBoundaries.values()) {\n    nodes.push({\n      id: boundary.id,\n      label: sanitize(boundary.label),\n      labelType: boundary.labelType,\n      shape: 'usecaseSystemBoundary',\n      isGroup: true,\n      padding: 20,\n      look: globalConfig.look,\n      colorIndex: boundaryColorIndex++,\n      cssClasses: classNames(\n        'default',\n        'system-boundary',\n        `system-boundary-${boundary.type}`,\n        ...boundary.classes\n      ),\n      cssStyles: [...boundary.styles],\n      cssCompiledStyles: getCompiledStyles(boundary.classes),\n      boundaryType: boundary.type,\n    });\n  }\n\n  for (const relationship of state.relationships) {\n    const { label: rawLabel, ...visual } = relationshipVisuals(relationship);\n    edges.push({\n      id: relationship.id,\n      start: relationship.source,\n      end: relationship.target,\n      source: relationship.source,\n      target: relationship.target,\n      sourceLabel: endpointLabel(relationship.source),\n      targetLabel: endpointLabel(relationship.target),\n      type: 'edge',\n      relationshipType: relationship.type,\n      internal: false,\n      ...visual,\n      ...(rawLabel !== undefined ? { label: sanitize(rawLabel) } : {}),\n      labelpos: 'c',\n      classes: classNames(\n        'default',\n        'relationship',\n        `relationship-${relationship.type}`,\n        ...relationship.classes,\n        ...animationClasses(relationship)\n      ),\n      style: [...relationship.styles],\n      cssCompiledStyles: getCompiledStyles(relationship.classes),\n      animate: relationship.animate,\n      ...(relationship.animation ? { animation: relationship.animation } : {}),\n      look: globalConfig.look,\n      thickness: 'normal',\n      minlen: relationship.minlen,\n      isUserDefinedId: relationship.explicitId,\n    });\n  }\n\n  for (const note of state.notes.values()) {\n    edges.push({\n      id: `${note.id}-edge`,\n      start: note.id,\n      end: note.target,\n      source: note.id,\n      target: note.target,\n      type: 'edge',\n      relationshipType: 'note',\n      sourceLabel: endpointLabel(note.id),\n      targetLabel: endpointLabel(note.target),\n      internal: true,\n      pattern: 'dotted',\n      arrowTypeStart: 'none',\n      arrowTypeEnd: 'none',\n      labelpos: 'c',\n      classes: 'default relationship relationship-note',\n      style: [],\n      cssCompiledStyles: getCompiledStyles([]),\n      animate: false,\n      look: globalConfig.look,\n      thickness: 'normal',\n      minlen: 1,\n      isUserDefinedId: false,\n    });\n  }\n\n  for (const node of nodes) {\n    node.wrappingWidth ??= config.wrappingWidth;\n    // Actors are glyphs with a caption, not boxes -- a minimum width would only\n    // pad their layout footprint.\n    if (!node.isGroup && !node.shape.startsWith('usecaseActor')) {\n      node.minWidth ??= config.minNodeWidth;\n    }\n    // Several association edges can end on one side of a use case, each with its\n    // own marker; spread their attachment points so the markers stay apart.\n    if (node.shape === 'usecaseEllipse' || node.shape === 'usecaseBusiness') {\n      node.spreadPorts = true;\n    }\n  }\n\n  return {\n    nodes,\n    edges,\n    config: globalConfig,\n    type: 'usecase',\n    layoutAlgorithm: 'dagre',\n    direction: getDirection(),\n    nodeSpacing: config.nodeSpacing,\n    rankSpacing: config.rankSpacing,\n    actorFontSize: config.actorFontSize,\n    actorFontFamily: config.actorFontFamily,\n    actorFontWeight: config.actorFontWeight,\n    usecaseFontSize: config.usecaseFontSize,\n    usecaseFontFamily: config.usecaseFontFamily,\n    usecaseFontWeight: config.usecaseFontWeight,\n    diagramPadding: config.diagramPadding,\n    useMaxWidth: config.useMaxWidth,\n    markers: ['point', 'circle', 'cross', 'extension'],\n  };\n};\n\nexport const db: UsecaseDB = {\n  getConfig,\n  createModel,\n  commit,\n  getAST,\n\n  clear,\n  setDiagramTitle,\n  getDiagramTitle,\n  setAccTitle,\n  getAccTitle,\n  setAccDescription,\n  getAccDescription,\n\n  getActors,\n  getActor,\n  getUseCases,\n  getUseCase,\n  getSystemBoundaries,\n  getSystemBoundary,\n  getRelationships,\n  getNotes,\n  getNote,\n  getJsonNodes,\n  getJsonNode,\n  getClassDefs,\n  getClassDef,\n  getDirection,\n  getData,\n};\n", "export function PRINT_ERROR(msg: string) {\n  /* istanbul ignore else - can't override global.console in node.js */\n  if (console && console.error) {\n    console.error(`Error: ${msg}`);\n  }\n}\n\nexport function PRINT_WARNING(msg: string) {\n  /* istanbul ignore else - can't override global.console in node.js*/\n  if (console && console.warn) {\n    // TODO: modify docs accordingly\n    console.warn(`Warning: ${msg}`);\n  }\n}\n", "export function timer<T>(func: () => T): { time: number; value: T } {\n  const start = new Date().getTime();\n  const val = func();\n  const end = new Date().getTime();\n  const total = end - start;\n  return { time: total, value: val };\n}\n", "// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216\nexport function toFastProperties(toBecomeFast: any) {\n  function FakeConstructor() {}\n\n  // If our object is used as a constructor, it would receive\n  FakeConstructor.prototype = toBecomeFast;\n  const fakeInstance = new (FakeConstructor as any)();\n\n  function fakeAccess() {\n    return typeof fakeInstance.bar;\n  }\n\n  // help V8 understand this is a \"real\" prototype by actually using\n  // the fake instance.\n  fakeAccess();\n  fakeAccess();\n\n  // Always true condition to suppress the Firefox warning of unreachable\n  // code after a return statement.\n  if (1) return toBecomeFast;\n\n  // Eval prevents optimization of this method (even though this is dead code)\n  // - https://esbuild.github.io/content-types/#direct-eval\n  /* istanbul ignore next */\n  // tslint:disable-next-line\n  (0, eval)(toBecomeFast);\n}\n", "import type {\n  IGASTVisitor,\n  IProduction,\n  IProductionWithOccurrence,\n  ISerializedGast,\n  TokenType,\n} from \"@chevrotain/types\";\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction tokenLabel(tokType: TokenType): string {\n  if (hasTokenLabel(tokType)) {\n    return tokType.LABEL;\n  } else {\n    return tokType.name;\n  }\n}\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction hasTokenLabel(\n  obj: TokenType,\n): obj is TokenType & Pick<Required<TokenType>, \"LABEL\"> {\n  return typeof obj.LABEL === \"string\" && obj.LABEL !== \"\";\n}\n\nexport abstract class AbstractProduction<\n  T extends IProduction = IProduction,\n> implements IProduction {\n  public get definition(): T[] {\n    return this._definition;\n  }\n  public set definition(value: T[]) {\n    this._definition = value;\n  }\n\n  constructor(protected _definition: T[]) {}\n\n  accept(visitor: IGASTVisitor): void {\n    visitor.visit(this);\n    this.definition.forEach((prod) => {\n      prod.accept(visitor);\n    });\n  }\n}\n\nexport class NonTerminal\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public nonTerminalName!: string;\n  public label?: string;\n  public referencedRule!: Rule;\n  public idx: number = 1;\n\n  constructor(options: {\n    nonTerminalName: string;\n    label?: string;\n    referencedRule?: Rule;\n    idx?: number;\n  }) {\n    super([]);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n\n  set definition(definition: IProduction[]) {\n    // immutable\n  }\n\n  get definition(): IProduction[] {\n    if (this.referencedRule !== undefined) {\n      return this.referencedRule.definition;\n    }\n    return [];\n  }\n\n  accept(visitor: IGASTVisitor): void {\n    visitor.visit(this);\n    // don't visit children of a reference, we will get cyclic infinite loops if we do so\n  }\n}\n\nexport class Rule extends AbstractProduction {\n  public name!: string;\n  public orgText: string = \"\";\n\n  constructor(options: {\n    name: string;\n    definition: IProduction[];\n    orgText?: string;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class Alternative extends AbstractProduction {\n  public ignoreAmbiguities: boolean = false;\n\n  constructor(options: {\n    definition: IProduction[];\n    ignoreAmbiguities?: boolean;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class Option\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public idx: number = 1;\n  public maxLookahead?: number;\n\n  constructor(options: {\n    definition: IProduction[];\n    idx?: number;\n    maxLookahead?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class RepetitionMandatory\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public idx: number = 1;\n  public maxLookahead?: number;\n\n  constructor(options: {\n    definition: IProduction[];\n    idx?: number;\n    maxLookahead?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class RepetitionMandatoryWithSeparator\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public separator!: TokenType;\n  public idx: number = 1;\n  public maxLookahead?: number;\n\n  constructor(options: {\n    definition: IProduction[];\n    separator: TokenType;\n    idx?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class Repetition\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public separator!: TokenType;\n  public idx: number = 1;\n  public maxLookahead?: number;\n\n  constructor(options: {\n    definition: IProduction[];\n    idx?: number;\n    maxLookahead?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class RepetitionWithSeparator\n  extends AbstractProduction\n  implements IProductionWithOccurrence\n{\n  public separator!: TokenType;\n  public idx: number = 1;\n  public maxLookahead?: number;\n\n  constructor(options: {\n    definition: IProduction[];\n    separator: TokenType;\n    idx?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class Alternation\n  extends AbstractProduction<Alternative>\n  implements IProductionWithOccurrence\n{\n  public idx: number = 1;\n  public ignoreAmbiguities: boolean = false;\n  public hasPredicates: boolean = false;\n  public maxLookahead?: number;\n\n  public get definition(): Alternative[] {\n    return this._definition;\n  }\n  public set definition(value: Alternative[]) {\n    this._definition = value;\n  }\n\n  constructor(options: {\n    definition: Alternative[];\n    idx?: number;\n    ignoreAmbiguities?: boolean;\n    hasPredicates?: boolean;\n    maxLookahead?: number;\n  }) {\n    super(options.definition);\n    Object.assign(this, pickOnlyDefined(options));\n  }\n}\n\nexport class Terminal implements IProductionWithOccurrence {\n  public terminalType!: TokenType;\n  public label?: string;\n  public idx: number = 1;\n\n  constructor(options: {\n    terminalType: TokenType;\n    label?: string;\n    idx?: number;\n  }) {\n    Object.assign(this, pickOnlyDefined(options));\n  }\n\n  accept(visitor: IGASTVisitor): void {\n    visitor.visit(this);\n  }\n}\n\nexport interface ISerializedBasic extends ISerializedGast {\n  type:\n    | \"Alternative\"\n    | \"Option\"\n    | \"RepetitionMandatory\"\n    | \"Repetition\"\n    | \"Alternation\";\n  idx?: number;\n}\n\nexport interface ISerializedGastRule extends ISerializedGast {\n  type: \"Rule\";\n  name: string;\n  orgText: string;\n}\n\nexport interface ISerializedNonTerminal extends ISerializedGast {\n  type: \"NonTerminal\";\n  name: string;\n  label?: string;\n  idx: number;\n}\n\nexport interface ISerializedTerminal extends ISerializedGast {\n  type: \"Terminal\";\n  name: string;\n  terminalLabel?: string;\n  label?: string;\n  pattern?: string;\n  idx: number;\n}\n\nexport interface ISerializedTerminalWithSeparator extends ISerializedGast {\n  type: \"RepetitionMandatoryWithSeparator\" | \"RepetitionWithSeparator\";\n  idx: number;\n  separator: ISerializedTerminal;\n}\n\nexport type ISerializedGastAny =\n  | ISerializedBasic\n  | ISerializedGastRule\n  | ISerializedNonTerminal\n  | ISerializedTerminal\n  | ISerializedTerminalWithSeparator;\n\nexport function serializeGrammar(topRules: Rule[]): ISerializedGast[] {\n  return topRules.map(serializeProduction);\n}\n\nexport function serializeProduction(node: IProduction): ISerializedGast {\n  function convertDefinition(definition: IProduction[]): ISerializedGast[] {\n    return definition.map(serializeProduction);\n  }\n  /* istanbul ignore else */\n  if (node instanceof NonTerminal) {\n    const serializedNonTerminal: ISerializedNonTerminal = {\n      type: \"NonTerminal\",\n      name: node.nonTerminalName,\n      idx: node.idx,\n    };\n\n    if (typeof node.label === \"string\") {\n      serializedNonTerminal.label = node.label;\n    }\n\n    return serializedNonTerminal;\n  } else if (node instanceof Alternative) {\n    return <ISerializedBasic>{\n      type: \"Alternative\",\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof Option) {\n    return <ISerializedBasic>{\n      type: \"Option\",\n      idx: node.idx,\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof RepetitionMandatory) {\n    return <ISerializedBasic>{\n      type: \"RepetitionMandatory\",\n      idx: node.idx,\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof RepetitionMandatoryWithSeparator) {\n    return <ISerializedTerminalWithSeparator>{\n      type: \"RepetitionMandatoryWithSeparator\",\n      idx: node.idx,\n      separator: <ISerializedTerminal>(\n        serializeProduction(new Terminal({ terminalType: node.separator }))\n      ),\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof RepetitionWithSeparator) {\n    return <ISerializedTerminalWithSeparator>{\n      type: \"RepetitionWithSeparator\",\n      idx: node.idx,\n      separator: <ISerializedTerminal>(\n        serializeProduction(new Terminal({ terminalType: node.separator }))\n      ),\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof Repetition) {\n    return <ISerializedBasic>{\n      type: \"Repetition\",\n      idx: node.idx,\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof Alternation) {\n    return <ISerializedBasic>{\n      type: \"Alternation\",\n      idx: node.idx,\n      definition: convertDefinition(node.definition),\n    };\n  } else if (node instanceof Terminal) {\n    const serializedTerminal = <ISerializedTerminal>{\n      type: \"Terminal\",\n      name: node.terminalType.name,\n      label: tokenLabel(node.terminalType),\n      idx: node.idx,\n    };\n\n    if (typeof node.label === \"string\") {\n      serializedTerminal.terminalLabel = node.label;\n    }\n\n    const pattern = node.terminalType.PATTERN;\n    if (node.terminalType.PATTERN) {\n      serializedTerminal.pattern =\n        pattern instanceof RegExp ? (<any>pattern).source : pattern;\n    }\n\n    return serializedTerminal;\n  } else if (node instanceof Rule) {\n    return <ISerializedGastRule>{\n      type: \"Rule\",\n      name: node.name,\n      orgText: node.orgText,\n      definition: convertDefinition(node.definition),\n    };\n    /* c8 ignore next 3 */\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nfunction pickOnlyDefined(obj: Object): any {\n  return Object.fromEntries(\n    Object.entries(obj).filter(([, v]) => v !== undefined),\n  );\n}\n", "import {\n  Alternation,\n  Alternative,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Rule,\n  Terminal,\n} from \"./model.js\";\nimport type { IProduction } from \"@chevrotain/types\";\n\nexport abstract class GAstVisitor {\n  public visit(node: IProduction): any {\n    const nodeAny: any = node;\n    switch (nodeAny.constructor) {\n      case NonTerminal:\n        return this.visitNonTerminal(nodeAny);\n      case Alternative:\n        return this.visitAlternative(nodeAny);\n      case Option:\n        return this.visitOption(nodeAny);\n      case RepetitionMandatory:\n        return this.visitRepetitionMandatory(nodeAny);\n      case RepetitionMandatoryWithSeparator:\n        return this.visitRepetitionMandatoryWithSeparator(nodeAny);\n      case RepetitionWithSeparator:\n        return this.visitRepetitionWithSeparator(nodeAny);\n      case Repetition:\n        return this.visitRepetition(nodeAny);\n      case Alternation:\n        return this.visitAlternation(nodeAny);\n      case Terminal:\n        return this.visitTerminal(nodeAny);\n      case Rule:\n        return this.visitRule(nodeAny);\n      /* c8 ignore next 2 */\n      default:\n        throw Error(\"non exhaustive match\");\n    }\n  }\n\n  /* c8 ignore next */\n  public visitNonTerminal(node: NonTerminal): any {}\n\n  /* c8 ignore next */\n  public visitAlternative(node: Alternative): any {}\n\n  /* c8 ignore next */\n  public visitOption(node: Option): any {}\n\n  /* c8 ignore next */\n  public visitRepetition(node: Repetition): any {}\n\n  /* c8 ignore next */\n  public visitRepetitionMandatory(node: RepetitionMandatory): any {}\n\n  /* c8 ignore next 3 */\n  public visitRepetitionMandatoryWithSeparator(\n    node: RepetitionMandatoryWithSeparator,\n  ): any {}\n\n  /* c8 ignore next */\n  public visitRepetitionWithSeparator(node: RepetitionWithSeparator): any {}\n\n  /* c8 ignore next */\n  public visitAlternation(node: Alternation): any {}\n\n  /* c8 ignore next */\n  public visitTerminal(node: Terminal): any {}\n\n  /* c8 ignore next */\n  public visitRule(node: Rule): any {}\n}\n", "import {\n  AbstractProduction,\n  Alternation,\n  Alternative,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Rule,\n  Terminal,\n} from \"./model.js\";\nimport type { IProduction, IProductionWithOccurrence } from \"@chevrotain/types\";\n\nexport function isSequenceProd(\n  prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n  return (\n    prod instanceof Alternative ||\n    prod instanceof Option ||\n    prod instanceof Repetition ||\n    prod instanceof RepetitionMandatory ||\n    prod instanceof RepetitionMandatoryWithSeparator ||\n    prod instanceof RepetitionWithSeparator ||\n    prod instanceof Terminal ||\n    prod instanceof Rule\n  );\n}\n\nexport function isOptionalProd(\n  prod: IProduction,\n  alreadyVisited: NonTerminal[] = [],\n): boolean {\n  const isDirectlyOptional =\n    prod instanceof Option ||\n    prod instanceof Repetition ||\n    prod instanceof RepetitionWithSeparator;\n  if (isDirectlyOptional) {\n    return true;\n  }\n\n  // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another\n  // empty optional top rule\n  // may be indirectly optional ((A?B?C?) | (D?E?F?))\n  if (prod instanceof Alternation) {\n    // for OR its enough for just one of the alternatives to be optional\n    return (<Alternation>prod).definition.some((subProd: IProduction) => {\n      return isOptionalProd(subProd, alreadyVisited);\n    });\n  } else if (prod instanceof NonTerminal && alreadyVisited.includes(prod)) {\n    // avoiding stack overflow due to infinite recursion\n    return false;\n  } else if (prod instanceof AbstractProduction) {\n    if (prod instanceof NonTerminal) {\n      alreadyVisited.push(prod);\n    }\n    return (<AbstractProduction>prod).definition.every(\n      (subProd: IProduction) => {\n        return isOptionalProd(subProd, alreadyVisited);\n      },\n    );\n  } else {\n    return false;\n  }\n}\n\nexport function isBranchingProd(\n  prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n  return prod instanceof Alternation;\n}\n\nexport function getProductionDslName(prod: IProductionWithOccurrence): string {\n  /* istanbul ignore else */\n  if (prod instanceof NonTerminal) {\n    return \"SUBRULE\";\n  } else if (prod instanceof Option) {\n    return \"OPTION\";\n  } else if (prod instanceof Alternation) {\n    return \"OR\";\n  } else if (prod instanceof RepetitionMandatory) {\n    return \"AT_LEAST_ONE\";\n  } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n    return \"AT_LEAST_ONE_SEP\";\n  } else if (prod instanceof RepetitionWithSeparator) {\n    return \"MANY_SEP\";\n  } else if (prod instanceof Repetition) {\n    return \"MANY\";\n  } else if (prod instanceof Terminal) {\n    return \"CONSUME\";\n    /* c8 ignore next 3 */\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n", "import {\n  Alternation,\n  Alternative,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction } from \"@chevrotain/types\";\n\n/**\n *  A Grammar Walker that computes the \"remaining\" grammar \"after\" a productions in the grammar.\n */\nexport abstract class RestWalker {\n  walk(prod: { definition: IProduction[] }, prevRest: any[] = []): void {\n    prod.definition.forEach((subProd: IProduction, index) => {\n      const currRest = prod.definition.slice(index + 1);\n      /* istanbul ignore else */\n      if (subProd instanceof NonTerminal) {\n        this.walkProdRef(subProd, currRest, prevRest);\n      } else if (subProd instanceof Terminal) {\n        this.walkTerminal(subProd, currRest, prevRest);\n      } else if (subProd instanceof Alternative) {\n        this.walkFlat(subProd, currRest, prevRest);\n      } else if (subProd instanceof Option) {\n        this.walkOption(subProd, currRest, prevRest);\n      } else if (subProd instanceof RepetitionMandatory) {\n        this.walkAtLeastOne(subProd, currRest, prevRest);\n      } else if (subProd instanceof RepetitionMandatoryWithSeparator) {\n        this.walkAtLeastOneSep(subProd, currRest, prevRest);\n      } else if (subProd instanceof RepetitionWithSeparator) {\n        this.walkManySep(subProd, currRest, prevRest);\n      } else if (subProd instanceof Repetition) {\n        this.walkMany(subProd, currRest, prevRest);\n      } else if (subProd instanceof Alternation) {\n        this.walkOr(subProd, currRest, prevRest);\n      } else {\n        throw Error(\"non exhaustive match\");\n      }\n    });\n  }\n\n  walkTerminal(\n    terminal: Terminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {}\n\n  walkProdRef(\n    refProd: NonTerminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {}\n\n  walkFlat(\n    flatProd: Alternative,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABCDEF => after the D the rest is EF\n    const fullOrRest = currRest.concat(prevRest);\n    this.walk(flatProd, <any>fullOrRest);\n  }\n\n  walkOption(\n    optionProd: Option,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC(DE)?F => after the (DE)? the rest is F\n    const fullOrRest = currRest.concat(prevRest);\n    this.walk(optionProd, <any>fullOrRest);\n  }\n\n  walkAtLeastOne(\n    atLeastOneProd: RepetitionMandatory,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC(DE)+F => after the (DE)+ the rest is (DE)?F\n    const fullAtLeastOneRest: IProduction[] = [\n      new Option({ definition: atLeastOneProd.definition }),\n    ].concat(<any>currRest, <any>prevRest);\n    this.walk(atLeastOneProd, fullAtLeastOneRest);\n  }\n\n  walkAtLeastOneSep(\n    atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F\n    const fullAtLeastOneSepRest = restForRepetitionWithSeparator(\n      atLeastOneSepProd,\n      currRest,\n      prevRest,\n    );\n    this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);\n  }\n\n  walkMany(\n    manyProd: Repetition,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC(DE)*F => after the (DE)* the rest is (DE)?F\n    const fullManyRest: IProduction[] = [\n      new Option({ definition: manyProd.definition }),\n    ].concat(<any>currRest, <any>prevRest);\n    this.walk(manyProd, fullManyRest);\n  }\n\n  walkManySep(\n    manySepProd: RepetitionWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F\n    const fullManySepRest = restForRepetitionWithSeparator(\n      manySepProd,\n      currRest,\n      prevRest,\n    );\n    this.walk(manySepProd, fullManySepRest);\n  }\n\n  walkOr(\n    orProd: Alternation,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // ABC(D|E|F)G => when finding the (D|E|F) the rest is G\n    const fullOrRest = currRest.concat(prevRest);\n    // walk all different alternatives\n    orProd.definition.forEach((alt) => {\n      // wrapping each alternative in a single definition wrapper\n      // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows\n      // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1\n      const prodWrapper = new Alternative({ definition: [alt] });\n      this.walk(prodWrapper, <any>fullOrRest);\n    });\n  }\n}\n\nfunction restForRepetitionWithSeparator(\n  repSepProd: RepetitionWithSeparator,\n  currRest: IProduction[],\n  prevRest: IProduction[],\n) {\n  const repSepRest = [\n    new Option({\n      definition: [\n        new Terminal({ terminalType: repSepProd.separator }) as IProduction,\n      ].concat(repSepProd.definition),\n    }) as IProduction,\n  ];\n  const fullRepSepRest: IProduction[] = repSepRest.concat(currRest, prevRest);\n  return fullRepSepRest;\n}\n", "import {\n  isBranchingProd,\n  isOptionalProd,\n  isSequenceProd,\n  NonTerminal,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\nexport function first(prod: IProduction): TokenType[] {\n  /* istanbul ignore else */\n  if (prod instanceof NonTerminal) {\n    // this could in theory cause infinite loops if\n    // (1) prod A refs prod B.\n    // (2) prod B refs prod A\n    // (3) AB can match the empty set\n    // in other words a cycle where everything is optional so the first will keep\n    // looking ahead for the next optional part and will never exit\n    // currently there is no safeguard for this unique edge case because\n    // (1) not sure a grammar in which this can happen is useful for anything (productive)\n    return first((<NonTerminal>prod).referencedRule);\n  } else if (prod instanceof Terminal) {\n    return firstForTerminal(<Terminal>prod);\n  } else if (isSequenceProd(prod)) {\n    return firstForSequence(prod);\n  } else if (isBranchingProd(prod)) {\n    return firstForBranching(prod);\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nexport function firstForSequence(prod: {\n  definition: IProduction[];\n}): TokenType[] {\n  let firstSet: TokenType[] = [];\n  const seq = prod.definition;\n  let nextSubProdIdx = 0;\n  let hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n  let currSubProd;\n  // so we enter the loop at least once (if the definition is not empty\n  let isLastInnerProdOptional = true;\n  // scan a sequence until it's end or until we have found a NONE optional production in it\n  while (hasInnerProdsRemaining && isLastInnerProdOptional) {\n    currSubProd = seq[nextSubProdIdx];\n    isLastInnerProdOptional = isOptionalProd(currSubProd);\n    firstSet = firstSet.concat(first(currSubProd));\n    nextSubProdIdx = nextSubProdIdx + 1;\n    hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n  }\n\n  return [...new Set(firstSet)];\n}\n\nexport function firstForBranching(prod: {\n  definition: IProduction[];\n}): TokenType[] {\n  const allAlternativesFirsts: TokenType[][] = prod.definition.map(\n    (innerProd) => {\n      return first(innerProd);\n    },\n  );\n  return [...new Set(allAlternativesFirsts.flat())];\n}\n\nexport function firstForTerminal(terminal: Terminal): TokenType[] {\n  return [terminal.terminalType];\n}\n", "// TODO: can this be removed? where is it used?\nexport const IN = \"_~IN~_\";\n", "import { RestWalker } from \"./rest.js\";\nimport { first } from \"./first.js\";\nimport { IN } from \"../constants.js\";\nimport { Alternative, NonTerminal, Rule, Terminal } from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\n// This ResyncFollowsWalker computes all of the follows required for RESYNC\n// (skipping reference production).\nexport class ResyncFollowsWalker extends RestWalker {\n  public follows: Record<string, TokenType[]> = {};\n\n  constructor(private topProd: Rule) {\n    super();\n  }\n\n  startWalking(): Record<string, TokenType[]> {\n    this.walk(this.topProd);\n    return this.follows;\n  }\n\n  walkTerminal(\n    terminal: Terminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // do nothing! just like in the public sector after 13:00\n  }\n\n  walkProdRef(\n    refProd: NonTerminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    const followName =\n      buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +\n      this.topProd.name;\n    const fullRest: IProduction[] = currRest.concat(prevRest);\n    const restProd = new Alternative({ definition: fullRest });\n    const t_in_topProd_follows = first(restProd);\n    this.follows[followName] = t_in_topProd_follows;\n  }\n}\n\nexport function computeAllProdsFollows(\n  topProductions: Rule[],\n): Record<string, TokenType[]> {\n  const reSyncFollows = {};\n\n  topProductions.forEach((topProd) => {\n    const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();\n    Object.assign(reSyncFollows, currRefsFollow);\n  });\n  return reSyncFollows;\n}\n\nexport function buildBetweenProdsFollowPrefix(\n  inner: Rule,\n  occurenceInParent: number,\n): string {\n  return inner.name + occurenceInParent + IN;\n}\n\nexport function buildInProdFollowPrefix(terminal: Terminal): string {\n  const terminalName = terminal.terminalType.name;\n  return terminalName + terminal.idx + IN;\n}\n", "import type { Character, IRegExpAST, RegExpFlags } from \"../types\";\n\nexport function cc(char: string): number {\n  return char.charCodeAt(0);\n}\n\nexport function insertToSet<T>(item: T | T[], set: T[]) {\n  if (Array.isArray(item)) {\n    item.forEach(function (subItem) {\n      set.push(subItem);\n    });\n  } else {\n    set.push(item);\n  }\n}\n\nexport function addFlag(\n  flagObj: RegExpFlags,\n  flagKey: keyof Omit<RegExpFlags, keyof IRegExpAST>,\n) {\n  if (flagObj[flagKey] === true) {\n    throw \"duplicate flag \" + flagKey;\n  }\n\n  const x: boolean = flagObj[flagKey];\n  flagObj[flagKey] = true;\n}\n\nexport function ASSERT_EXISTS<T = Object>(obj: any): obj is T {\n  // istanbul ignore next\n  if (obj === undefined) {\n    throw Error(\"Internal Error - Should never get here!\");\n  }\n  return true;\n}\n\n// istanbul ignore next\nexport function ASSERT_NEVER_REACH_HERE(): any {\n  throw Error(\"Internal Error - Should never get here!\");\n}\n\nexport function isCharacter(obj: { type: string }): obj is Character {\n  return obj[\"type\"] === \"Character\";\n}\n", "import { cc } from \"./utils.js\";\n\nexport const digitsCharCodes: number[] = [];\nfor (let i = cc(\"0\"); i <= cc(\"9\"); i++) {\n  digitsCharCodes.push(i);\n}\n\nexport const wordCharCodes: number[] = [cc(\"_\")].concat(digitsCharCodes);\nfor (let i = cc(\"a\"); i <= cc(\"z\"); i++) {\n  wordCharCodes.push(i);\n}\n\nfor (let i = cc(\"A\"); i <= cc(\"Z\"); i++) {\n  wordCharCodes.push(i);\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes\nexport const whitespaceCodes: number[] = [\n  cc(\" \"),\n  cc(\"\\f\"),\n  cc(\"\\n\"),\n  cc(\"\\r\"),\n  cc(\"\\t\"),\n  cc(\"\\v\"),\n  cc(\"\\t\"),\n  cc(\"\\u00a0\"),\n  cc(\"\\u1680\"),\n  cc(\"\\u2000\"),\n  cc(\"\\u2001\"),\n  cc(\"\\u2002\"),\n  cc(\"\\u2003\"),\n  cc(\"\\u2004\"),\n  cc(\"\\u2005\"),\n  cc(\"\\u2006\"),\n  cc(\"\\u2007\"),\n  cc(\"\\u2008\"),\n  cc(\"\\u2009\"),\n  cc(\"\\u200a\"),\n  cc(\"\\u2028\"),\n  cc(\"\\u2029\"),\n  cc(\"\\u202f\"),\n  cc(\"\\u205f\"),\n  cc(\"\\u3000\"),\n  cc(\"\\ufeff\"),\n];\n", "import type {\n  Alternative,\n  Assertion,\n  Atom,\n  Character,\n  Disjunction,\n  Group,\n  GroupBackReference,\n  Location,\n  Quantifier,\n  Range,\n  RegExpFlags,\n  RegExpPattern,\n  Set,\n  Term,\n} from \"../types\";\nimport {\n  addFlag,\n  ASSERT_EXISTS,\n  ASSERT_NEVER_REACH_HERE,\n  cc,\n  insertToSet,\n  isCharacter,\n} from \"./utils.js\";\nimport {\n  digitsCharCodes,\n  whitespaceCodes,\n  wordCharCodes,\n} from \"./character-classes.js\";\n\n// consts and utilities\nconst hexDigitPattern = /[0-9a-fA-F]/;\nconst decimalPattern = /[0-9]/;\nconst decimalPatternNoZero = /[1-9]/;\n\n// https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983\n// https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern\nexport class RegExpParser {\n  protected idx: number = 0;\n  protected input: string = \"\";\n  protected groupIdx: number = 0;\n\n  protected saveState() {\n    return {\n      idx: this.idx,\n      input: this.input,\n      groupIdx: this.groupIdx,\n    };\n  }\n\n  protected restoreState(newState: {\n    idx: number;\n    input: string;\n    groupIdx: number;\n  }) {\n    this.idx = newState.idx;\n    this.input = newState.input;\n    this.groupIdx = newState.groupIdx;\n  }\n\n  public pattern(input: string): RegExpPattern {\n    // parser state\n    this.idx = 0;\n    this.input = input;\n    this.groupIdx = 0;\n\n    this.consumeChar(\"/\");\n    const value = this.disjunction();\n    this.consumeChar(\"/\");\n\n    const flags: RegExpFlags = {\n      type: \"Flags\",\n      loc: { begin: this.idx, end: input.length },\n      global: false,\n      ignoreCase: false,\n      multiLine: false,\n      unicode: false,\n      sticky: false,\n    };\n\n    while (this.isRegExpFlag()) {\n      switch (this.popChar()) {\n        case \"g\":\n          addFlag(flags, \"global\");\n          break;\n        case \"i\":\n          addFlag(flags, \"ignoreCase\");\n          break;\n        case \"m\":\n          addFlag(flags, \"multiLine\");\n          break;\n        case \"u\":\n          addFlag(flags, \"unicode\");\n          break;\n        case \"y\":\n          addFlag(flags, \"sticky\");\n          break;\n      }\n    }\n\n    if (this.idx !== this.input.length) {\n      throw Error(\"Redundant input: \" + this.input.substring(this.idx));\n    }\n    return {\n      type: \"Pattern\",\n      flags: flags,\n      value: value,\n      loc: this.loc(0),\n    };\n  }\n\n  protected disjunction(): Disjunction {\n    const alts = [];\n    const begin = this.idx;\n\n    alts.push(this.alternative());\n\n    while (this.peekChar() === \"|\") {\n      this.consumeChar(\"|\");\n      alts.push(this.alternative());\n    }\n\n    return { type: \"Disjunction\", value: alts, loc: this.loc(begin) };\n  }\n\n  protected alternative(): Alternative {\n    const terms = [];\n    const begin = this.idx;\n\n    while (this.isTerm()) {\n      terms.push(this.term());\n    }\n\n    return { type: \"Alternative\", value: terms, loc: this.loc(begin) };\n  }\n\n  protected term(): Term {\n    if (this.isAssertion()) {\n      return this.assertion();\n    } else {\n      return this.atom();\n    }\n  }\n\n  protected assertion(): Assertion {\n    const begin = this.idx;\n    switch (this.popChar()) {\n      case \"^\":\n        return {\n          type: \"StartAnchor\",\n          loc: this.loc(begin),\n        };\n      case \"$\":\n        return { type: \"EndAnchor\", loc: this.loc(begin) };\n      // '\\b' or '\\B'\n      case \"\\\\\":\n        switch (this.popChar()) {\n          case \"b\":\n            return {\n              type: \"WordBoundary\",\n              loc: this.loc(begin),\n            };\n          case \"B\":\n            return {\n              type: \"NonWordBoundary\",\n              loc: this.loc(begin),\n            };\n        }\n        /* c8 ignore next */\n        throw Error(\"Invalid Assertion Escape\");\n      // '(?=' or '(?!'\n      case \"(\":\n        this.consumeChar(\"?\");\n\n        let type:\n          | \"Lookahead\"\n          | \"NegativeLookahead\"\n          | \"Lookbehind\"\n          | \"NegativeLookbehind\"\n          | undefined;\n        switch (this.popChar()) {\n          case \"=\":\n            type = \"Lookahead\";\n            break;\n          case \"!\":\n            type = \"NegativeLookahead\";\n            break;\n          case \"<\": {\n            switch (this.popChar()) {\n              case \"=\":\n                type = \"Lookbehind\";\n                break;\n              case \"!\":\n                type = \"NegativeLookbehind\";\n            }\n            break;\n          }\n        }\n        ASSERT_EXISTS(type);\n\n        const disjunction = this.disjunction();\n\n        this.consumeChar(\")\");\n\n        return {\n          type: type!,\n          value: disjunction,\n          loc: this.loc(begin),\n        };\n    }\n    // istanbul ignore next\n    return ASSERT_NEVER_REACH_HERE();\n  }\n\n  protected quantifier(\n    isBacktracking: boolean = false,\n  ): Quantifier | undefined {\n    let range: Partial<Quantifier> | undefined = undefined;\n    const begin = this.idx;\n    switch (this.popChar()) {\n      case \"*\":\n        range = {\n          atLeast: 0,\n          atMost: Infinity,\n        };\n        break;\n      case \"+\":\n        range = {\n          atLeast: 1,\n          atMost: Infinity,\n        };\n        break;\n      case \"?\":\n        range = {\n          atLeast: 0,\n          atMost: 1,\n        };\n        break;\n      case \"{\":\n        const atLeast = this.integerIncludingZero();\n        switch (this.popChar()) {\n          case \"}\":\n            range = {\n              atLeast: atLeast,\n              atMost: atLeast,\n            };\n            break;\n          case \",\":\n            let atMost;\n            if (this.isDigit()) {\n              atMost = this.integerIncludingZero();\n              range = {\n                atLeast: atLeast,\n                atMost: atMost,\n              };\n            } else {\n              range = {\n                atLeast: atLeast,\n                atMost: Infinity,\n              };\n            }\n            this.consumeChar(\"}\");\n            break;\n        }\n        // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n        // causes severe performance degradations\n        if (isBacktracking === true && range === undefined) {\n          return undefined;\n        }\n        ASSERT_EXISTS(range);\n        break;\n    }\n\n    // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n    // causes severe performance degradations\n    if (isBacktracking === true && range === undefined) {\n      return undefined;\n    }\n\n    // istanbul ignore else\n    if (ASSERT_EXISTS(range)) {\n      if (this.peekChar(0) === \"?\") {\n        this.consumeChar(\"?\");\n        range.greedy = false;\n      } else {\n        range.greedy = true;\n      }\n\n      range.type = \"Quantifier\";\n      range.loc = this.loc(begin);\n      return range as Quantifier;\n    }\n  }\n\n  protected atom(): Atom {\n    let atom: Omit<Atom, \"loc\" | \"type\"> | undefined;\n    const begin = this.idx;\n    switch (this.peekChar()) {\n      case \".\":\n        atom = this.dotAll();\n        break;\n      case \"\\\\\":\n        atom = this.atomEscape();\n        break;\n      case \"[\":\n        atom = this.characterClass();\n        break;\n      case \"(\":\n        atom = this.group();\n        break;\n    }\n\n    if (atom === undefined && this.isPatternCharacter()) {\n      atom = this.patternCharacter();\n    }\n\n    // istanbul ignore else\n    if (ASSERT_EXISTS<Atom>(atom)) {\n      atom.loc = this.loc(begin);\n\n      if (this.isQuantifier()) {\n        atom.quantifier = this.quantifier();\n      }\n\n      return atom;\n    }\n\n    // istanbul ignore next\n    return ASSERT_NEVER_REACH_HERE();\n  }\n\n  protected dotAll(): Omit<Set, \"loc\"> {\n    this.consumeChar(\".\");\n    return {\n      type: \"Set\",\n      complement: true,\n      value: [cc(\"\\n\"), cc(\"\\r\"), cc(\"\\u2028\"), cc(\"\\u2029\")],\n    };\n  }\n\n  protected atomEscape(): Omit<GroupBackReference | Set | Character, \"loc\"> {\n    this.consumeChar(\"\\\\\");\n\n    switch (this.peekChar()) {\n      case \"1\":\n      case \"2\":\n      case \"3\":\n      case \"4\":\n      case \"5\":\n      case \"6\":\n      case \"7\":\n      case \"8\":\n      case \"9\":\n        return this.decimalEscapeAtom();\n      case \"d\":\n      case \"D\":\n      case \"s\":\n      case \"S\":\n      case \"w\":\n      case \"W\":\n        return this.characterClassEscape();\n      case \"f\":\n      case \"n\":\n      case \"r\":\n      case \"t\":\n      case \"v\":\n        return this.controlEscapeAtom();\n      case \"c\":\n        return this.controlLetterEscapeAtom();\n      case \"0\":\n        return this.nulCharacterAtom();\n      case \"x\":\n        return this.hexEscapeSequenceAtom();\n      case \"u\":\n        return this.regExpUnicodeEscapeSequenceAtom();\n      default:\n        return this.identityEscapeAtom();\n    }\n  }\n\n  protected decimalEscapeAtom(): Omit<GroupBackReference, \"loc\"> {\n    const value = this.positiveInteger();\n\n    return { type: \"GroupBackReference\", value: value };\n  }\n\n  protected characterClassEscape(): Omit<Set, \"loc\"> {\n    let set: (number | Range)[] | undefined;\n    let complement = false;\n    switch (this.popChar()) {\n      case \"d\":\n        set = digitsCharCodes;\n        break;\n      case \"D\":\n        set = digitsCharCodes;\n        complement = true;\n        break;\n      case \"s\":\n        set = whitespaceCodes;\n        break;\n      case \"S\":\n        set = whitespaceCodes;\n        complement = true;\n        break;\n      case \"w\":\n        set = wordCharCodes;\n        break;\n      case \"W\":\n        set = wordCharCodes;\n        complement = true;\n        break;\n    }\n\n    // istanbul ignore else\n    if (ASSERT_EXISTS(set)) {\n      return { type: \"Set\", value: set, complement: complement };\n    }\n    // istanbul ignore next\n    return ASSERT_NEVER_REACH_HERE();\n  }\n\n  protected controlEscapeAtom(): Omit<Character, \"loc\"> {\n    let escapeCode;\n    switch (this.popChar()) {\n      case \"f\":\n        escapeCode = cc(\"\\f\");\n        break;\n      case \"n\":\n        escapeCode = cc(\"\\n\");\n        break;\n      case \"r\":\n        escapeCode = cc(\"\\r\");\n        break;\n      case \"t\":\n        escapeCode = cc(\"\\t\");\n        break;\n      case \"v\":\n        escapeCode = cc(\"\\v\");\n        break;\n    }\n\n    // istanbul ignore else\n    if (ASSERT_EXISTS(escapeCode)) {\n      return { type: \"Character\", value: escapeCode };\n    }\n    // istanbul ignore next\n    return ASSERT_NEVER_REACH_HERE();\n  }\n\n  protected controlLetterEscapeAtom(): Omit<Character, \"loc\"> {\n    this.consumeChar(\"c\");\n    const letter = this.popChar();\n    if (/[a-zA-Z]/.test(letter) === false) {\n      throw Error(\"Invalid \");\n    }\n\n    const letterCode = letter.toUpperCase().charCodeAt(0) - 64;\n    return { type: \"Character\", value: letterCode };\n  }\n\n  protected nulCharacterAtom(): Omit<Character, \"loc\"> {\n    // TODO implement '[lookahead \u2209 DecimalDigit]'\n    // TODO: for the deprecated octal escape sequence\n    this.consumeChar(\"0\");\n    return { type: \"Character\", value: cc(\"\\0\") };\n  }\n\n  protected hexEscapeSequenceAtom(): Omit<Character, \"loc\"> {\n    this.consumeChar(\"x\");\n    return this.parseHexDigits(2);\n  }\n\n  protected regExpUnicodeEscapeSequenceAtom(): Omit<Character, \"loc\"> {\n    this.consumeChar(\"u\");\n    return this.parseHexDigits(4);\n  }\n\n  protected identityEscapeAtom(): Omit<Character, \"loc\"> {\n    // TODO: implement \"SourceCharacter but not UnicodeIDContinue\"\n    // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments\n    const escapedChar = this.popChar();\n    return { type: \"Character\", value: cc(escapedChar) };\n  }\n\n  protected classPatternCharacterAtom(): Omit<Character, \"loc\"> {\n    switch (this.peekChar()) {\n      // istanbul ignore next\n      case \"\\n\":\n      // istanbul ignore next\n      case \"\\r\":\n      // istanbul ignore next\n      case \"\\u2028\":\n      // istanbul ignore next\n      case \"\\u2029\":\n      // istanbul ignore next\n      case \"\\\\\":\n      // istanbul ignore next\n      case \"]\":\n        throw Error(\"TBD\");\n      default:\n        const nextChar = this.popChar();\n        return { type: \"Character\", value: cc(nextChar) };\n    }\n  }\n\n  protected characterClass(): Omit<Set, \"loc\"> {\n    const set: (number | Range)[] = [];\n    let complement = false;\n    this.consumeChar(\"[\");\n    if (this.peekChar(0) === \"^\") {\n      this.consumeChar(\"^\");\n      complement = true;\n    }\n\n    while (this.isClassAtom()) {\n      const from = this.classAtom();\n      const isFromSingleChar = from.type === \"Character\";\n      if (isCharacter(from) && this.isRangeDash()) {\n        this.consumeChar(\"-\");\n        const to = this.classAtom();\n        const isToSingleChar = to.type === \"Character\";\n\n        // a range can only be used when both sides are single characters\n        if (isCharacter(to)) {\n          if (to.value < from.value) {\n            throw Error(\"Range out of order in character class\");\n          }\n          set.push({ from: from.value, to: to.value });\n        } else {\n          // literal dash\n          insertToSet(from.value, set);\n          set.push(cc(\"-\"));\n          insertToSet(to.value, set);\n        }\n      } else {\n        insertToSet(from.value, set);\n      }\n    }\n\n    this.consumeChar(\"]\");\n\n    return { type: \"Set\", complement: complement, value: set };\n  }\n\n  protected classAtom(): Omit<Character | Set, \"loc\"> {\n    switch (this.peekChar()) {\n      // istanbul ignore next\n      case \"]\":\n      // istanbul ignore next\n      case \"\\n\":\n      // istanbul ignore next\n      case \"\\r\":\n      // istanbul ignore next\n      case \"\\u2028\":\n      // istanbul ignore next\n      case \"\\u2029\":\n        throw Error(\"TBD\");\n      case \"\\\\\":\n        return this.classEscape();\n      default:\n        return this.classPatternCharacterAtom();\n    }\n  }\n\n  protected classEscape(): Omit<Character | Set, \"loc\"> {\n    this.consumeChar(\"\\\\\");\n    switch (this.peekChar()) {\n      // Matches a backspace.\n      // (Not to be confused with \\b word boundary outside characterClass)\n      case \"b\":\n        this.consumeChar(\"b\");\n        return { type: \"Character\", value: cc(\"\\u0008\") };\n      case \"d\":\n      case \"D\":\n      case \"s\":\n      case \"S\":\n      case \"w\":\n      case \"W\":\n        return this.characterClassEscape();\n      case \"f\":\n      case \"n\":\n      case \"r\":\n      case \"t\":\n      case \"v\":\n        return this.controlEscapeAtom();\n      case \"c\":\n        return this.controlLetterEscapeAtom();\n      case \"0\":\n        return this.nulCharacterAtom();\n      case \"x\":\n        return this.hexEscapeSequenceAtom();\n      case \"u\":\n        return this.regExpUnicodeEscapeSequenceAtom();\n      default:\n        return this.identityEscapeAtom();\n    }\n  }\n\n  protected group(): Omit<Group, \"loc\"> {\n    let capturing = true;\n    this.consumeChar(\"(\");\n    switch (this.peekChar(0)) {\n      case \"?\":\n        this.consumeChar(\"?\");\n        this.consumeChar(\":\");\n        capturing = false;\n        break;\n      default:\n        this.groupIdx++;\n        break;\n    }\n    const value = this.disjunction();\n    this.consumeChar(\")\");\n\n    const groupAst: Omit<Group, \"loc\"> = {\n      type: \"Group\",\n      capturing: capturing,\n      value: value,\n    };\n\n    if (capturing) {\n      groupAst[\"idx\"] = this.groupIdx;\n    }\n\n    return groupAst;\n  }\n\n  protected positiveInteger(): number {\n    let number = this.popChar();\n\n    // istanbul ignore next - can't ever get here due to previous lookahead checks\n    // still implementing this error checking in case this ever changes.\n    if (decimalPatternNoZero.test(number) === false) {\n      throw Error(\"Expecting a positive integer\");\n    }\n\n    while (decimalPattern.test(this.peekChar(0))) {\n      number += this.popChar();\n    }\n\n    return parseInt(number, 10);\n  }\n\n  protected integerIncludingZero(): number {\n    let number = this.popChar();\n    if (decimalPattern.test(number) === false) {\n      throw Error(\"Expecting an integer\");\n    }\n\n    while (decimalPattern.test(this.peekChar(0))) {\n      number += this.popChar();\n    }\n\n    return parseInt(number, 10);\n  }\n\n  protected patternCharacter(): Omit<Character, \"loc\"> {\n    const nextChar = this.popChar();\n    switch (nextChar) {\n      // istanbul ignore next\n      case \"\\n\":\n      // istanbul ignore next\n      case \"\\r\":\n      // istanbul ignore next\n      case \"\\u2028\":\n      // istanbul ignore next\n      case \"\\u2029\":\n      // istanbul ignore next\n      case \"^\":\n      // istanbul ignore next\n      case \"$\":\n      // istanbul ignore next\n      case \"\\\\\":\n      // istanbul ignore next\n      case \".\":\n      // istanbul ignore next\n      case \"*\":\n      // istanbul ignore next\n      case \"+\":\n      // istanbul ignore next\n      case \"?\":\n      // istanbul ignore next\n      case \"(\":\n      // istanbul ignore next\n      case \")\":\n      // istanbul ignore next\n      case \"[\":\n      // istanbul ignore next\n      case \"|\":\n        // istanbul ignore next\n        throw Error(\"TBD\");\n      default:\n        return { type: \"Character\", value: cc(nextChar) };\n    }\n  }\n  protected isRegExpFlag(): boolean {\n    switch (this.peekChar(0)) {\n      case \"g\":\n      case \"i\":\n      case \"m\":\n      case \"u\":\n      case \"y\":\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  protected isRangeDash(): boolean {\n    return this.peekChar() === \"-\" && this.isClassAtom(1);\n  }\n\n  protected isDigit(): boolean {\n    return decimalPattern.test(this.peekChar(0));\n  }\n\n  protected isClassAtom(howMuch = 0): boolean {\n    switch (this.peekChar(howMuch)) {\n      case \"]\":\n      case \"\\n\":\n      case \"\\r\":\n      case \"\\u2028\":\n      case \"\\u2029\":\n        return false;\n      default:\n        return true;\n    }\n  }\n\n  protected isTerm() {\n    return this.isAtom() || this.isAssertion();\n  }\n\n  protected isAtom(): boolean {\n    if (this.isPatternCharacter()) {\n      return true;\n    }\n\n    switch (this.peekChar(0)) {\n      case \".\":\n      case \"\\\\\": // atomEscape\n      case \"[\": // characterClass\n      // TODO: isAtom must be called before isAssertion - disambiguate\n      case \"(\": // group\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  protected isAssertion(): boolean {\n    switch (this.peekChar(0)) {\n      case \"^\":\n      case \"$\":\n        return true;\n      // '\\b' or '\\B'\n      case \"\\\\\":\n        switch (this.peekChar(1)) {\n          case \"b\":\n          case \"B\":\n            return true;\n          default:\n            return false;\n        }\n      // '(?=' or '(?!' or `(?<=` or `(?<!`\n      case \"(\":\n        return (\n          this.peekChar(1) === \"?\" &&\n          (this.peekChar(2) === \"=\" ||\n            this.peekChar(2) === \"!\" ||\n            (this.peekChar(2) === \"<\" &&\n              (this.peekChar(3) === \"=\" || this.peekChar(3) === \"!\")))\n        );\n      default:\n        return false;\n    }\n  }\n\n  protected isQuantifier(): boolean {\n    const prevState = this.saveState();\n    try {\n      return this.quantifier(true) !== undefined;\n    } catch (e) {\n      return false;\n    } finally {\n      this.restoreState(prevState);\n    }\n  }\n\n  protected isPatternCharacter(): boolean {\n    switch (this.peekChar()) {\n      case \"^\":\n      case \"$\":\n      case \"\\\\\":\n      case \".\":\n      case \"*\":\n      case \"+\":\n      case \"?\":\n      case \"(\":\n      case \")\":\n      case \"[\":\n      case \"|\":\n      case \"/\":\n      case \"\\n\":\n      case \"\\r\":\n      case \"\\u2028\":\n      case \"\\u2029\":\n        return false;\n      default:\n        return true;\n    }\n  }\n\n  protected parseHexDigits(howMany: number): Omit<Character, \"loc\"> {\n    let hexString = \"\";\n    for (let i = 0; i < howMany; i++) {\n      const hexChar = this.popChar();\n      if (hexDigitPattern.test(hexChar) === false) {\n        throw Error(\"Expecting a HexDecimal digits\");\n      }\n      hexString += hexChar;\n    }\n    const charCode = parseInt(hexString, 16);\n    return { type: \"Character\", value: charCode };\n  }\n\n  protected peekChar(howMuch = 0): string {\n    return this.input[this.idx + howMuch];\n  }\n\n  protected popChar(): string {\n    const nextChar = this.peekChar(0);\n    this.consumeChar(undefined);\n    return nextChar;\n  }\n\n  protected consumeChar(char: string | undefined): void {\n    if (char !== undefined && this.input[this.idx] !== char) {\n      throw Error(\n        \"Expected: '\" +\n          char +\n          \"' but found: '\" +\n          this.input[this.idx] +\n          \"' at offset: \" +\n          this.idx,\n      );\n    }\n\n    if (this.idx >= this.input.length) {\n      throw Error(\"Unexpected end of input\");\n    }\n    this.idx++;\n  }\n\n  protected loc(begin: number): Location {\n    return { begin: begin, end: this.idx };\n  }\n}\n", "import type {\n  Alternative,\n  Assertion,\n  Character,\n  Disjunction,\n  Group,\n  GroupBackReference,\n  IRegExpAST,\n  Quantifier,\n  RegExpAstPart,\n  RegExpFlags,\n  RegExpPattern,\n  Set,\n} from \"../types\";\n\nexport class BaseRegExpVisitor {\n  public visitChildren(node: IRegExpAST) {\n    for (const key in node) {\n      const child = (node as any)[key];\n      /* istanbul ignore else */\n      if (node.hasOwnProperty(key)) {\n        if (child.type !== undefined) {\n          this.visit(child);\n        } else if (Array.isArray(child)) {\n          child.forEach((subChild) => {\n            this.visit(subChild);\n          }, this);\n        }\n      }\n    }\n  }\n\n  public visit(node: RegExpAstPart): void {\n    switch (node.type) {\n      case \"Pattern\":\n        this.visitPattern(node);\n        break;\n      case \"Flags\":\n        this.visitFlags(node);\n        break;\n      case \"Disjunction\":\n        this.visitDisjunction(node);\n        break;\n      case \"Alternative\":\n        this.visitAlternative(node);\n        break;\n      case \"StartAnchor\":\n        this.visitStartAnchor(node);\n        break;\n      case \"EndAnchor\":\n        this.visitEndAnchor(node);\n        break;\n      case \"WordBoundary\":\n        this.visitWordBoundary(node);\n        break;\n      case \"NonWordBoundary\":\n        this.visitNonWordBoundary(node);\n        break;\n      case \"Lookahead\":\n        this.visitLookahead(node);\n        break;\n      case \"NegativeLookahead\":\n        this.visitNegativeLookahead(node);\n        break;\n      case \"Lookbehind\":\n        this.visitLookbehind(node);\n        break;\n      case \"NegativeLookbehind\":\n        this.visitNegativeLookbehind(node);\n        break;\n      case \"Character\":\n        this.visitCharacter(node);\n        break;\n      case \"Set\":\n        this.visitSet(node);\n        break;\n      case \"Group\":\n        this.visitGroup(node);\n        break;\n      case \"GroupBackReference\":\n        this.visitGroupBackReference(node);\n        break;\n      case \"Quantifier\":\n        this.visitQuantifier(node);\n        break;\n    }\n\n    this.visitChildren(node);\n  }\n\n  public visitPattern(node: RegExpPattern): void {}\n\n  public visitFlags(node: RegExpFlags): void {}\n\n  public visitDisjunction(node: Disjunction): void {}\n\n  public visitAlternative(node: Alternative): void {}\n\n  // Assertion\n  public visitStartAnchor(node: Assertion): void {}\n\n  public visitEndAnchor(node: Assertion): void {}\n\n  public visitWordBoundary(node: Assertion): void {}\n\n  public visitNonWordBoundary(node: Assertion): void {}\n\n  public visitLookahead(node: Assertion): void {}\n\n  public visitNegativeLookahead(node: Assertion): void {}\n\n  public visitLookbehind(node: Assertion): void {}\n\n  public visitNegativeLookbehind(node: Assertion): void {}\n\n  // atoms\n  public visitCharacter(node: Character): void {}\n\n  public visitSet(node: Set): void {}\n\n  public visitGroup(node: Group): void {}\n\n  public visitGroupBackReference(node: GroupBackReference): void {}\n\n  public visitQuantifier(node: Quantifier): void {}\n}\n", "import {\n  Alternative,\n  Assertion,\n  Atom,\n  Disjunction,\n  RegExpParser,\n  RegExpPattern,\n} from \"@chevrotain/regexp-to-ast\";\n\nlet regExpAstCache: { [regex: string]: RegExpPattern } = {};\nconst regExpParser = new RegExpParser();\n\n// this should be moved to regexp-to-ast\nexport type ASTNode =\n  | RegExpPattern\n  | Disjunction\n  | Alternative\n  | Assertion\n  | Atom;\n\nexport function getRegExpAst(regExp: RegExp): RegExpPattern {\n  const regExpStr = regExp.toString();\n  if (regExpAstCache.hasOwnProperty(regExpStr)) {\n    return regExpAstCache[regExpStr];\n  } else {\n    const regExpAst = regExpParser.pattern(regExpStr);\n    regExpAstCache[regExpStr] = regExpAst;\n    return regExpAst;\n  }\n}\n\nexport function clearRegExpParserCache() {\n  regExpAstCache = {};\n}\n", "import {\n  Alternative,\n  Atom,\n  BaseRegExpVisitor,\n  Character,\n  Disjunction,\n  Group,\n  Set,\n} from \"@chevrotain/regexp-to-ast\";\nimport { PRINT_ERROR, PRINT_WARNING } from \"@chevrotain/utils\";\nimport { ASTNode, getRegExpAst } from \"./reg_exp_parser.js\";\nimport { charCodeToOptimizedIndex, minOptimizationVal } from \"./lexer.js\";\n\nconst complementErrorMessage =\n  \"Complement Sets are not supported for first char optimization\";\nexport const failedOptimizationPrefixMsg =\n  'Unable to use \"first char\" lexer optimizations:\\n';\n\nexport function getOptimizedStartCodesIndices(\n  regExp: RegExp,\n  ensureOptimizations = false,\n): number[] {\n  try {\n    const ast = getRegExpAst(regExp);\n    const firstChars = firstCharOptimizedIndices(\n      ast.value,\n      {},\n      ast.flags.ignoreCase,\n    );\n    return firstChars;\n  } catch (e) {\n    /* istanbul ignore next */\n    // Testing this relies on the regexp-to-ast library having a bug... */\n    // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc\n    if (e.message === complementErrorMessage) {\n      if (ensureOptimizations) {\n        PRINT_WARNING(\n          `${failedOptimizationPrefixMsg}` +\n            `\\tUnable to optimize: < ${regExp.toString()} >\\n` +\n            \"\\tComplement Sets cannot be automatically optimized.\\n\" +\n            \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n            \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.\",\n        );\n      }\n    } else {\n      let msgSuffix = \"\";\n      if (ensureOptimizations) {\n        msgSuffix =\n          \"\\n\\tThis will disable the lexer's first char optimizations.\\n\" +\n          \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.\";\n      }\n      PRINT_ERROR(\n        `${failedOptimizationPrefixMsg}\\n` +\n          `\\tFailed parsing: < ${regExp.toString()} >\\n` +\n          `\\tUsing the @chevrotain/regexp-to-ast library\\n` +\n          \"\\tPlease open an issue at: https://github.com/chevrotain/chevrotain/issues\" +\n          msgSuffix,\n      );\n    }\n  }\n\n  return [];\n}\n\nexport function firstCharOptimizedIndices(\n  ast: ASTNode,\n  result: { [charCode: number]: number },\n  ignoreCase: boolean,\n): number[] {\n  switch (ast.type) {\n    case \"Disjunction\":\n      for (let i = 0; i < ast.value.length; i++) {\n        firstCharOptimizedIndices(ast.value[i], result, ignoreCase);\n      }\n      break;\n    case \"Alternative\":\n      const terms = ast.value;\n      for (let i = 0; i < terms.length; i++) {\n        const term = terms[i];\n\n        // skip terms that cannot effect the first char results\n        switch (term.type) {\n          case \"EndAnchor\":\n          // A group back reference cannot affect potential starting char.\n          // because if a back reference is the first production than automatically\n          // the group being referenced has had to come BEFORE so its codes have already been added\n          case \"GroupBackReference\":\n          // assertions do not affect potential starting codes\n          case \"Lookahead\":\n          case \"NegativeLookahead\":\n          case \"Lookbehind\":\n          case \"NegativeLookbehind\":\n          case \"StartAnchor\":\n          case \"WordBoundary\":\n          case \"NonWordBoundary\":\n            continue;\n        }\n\n        const atom = term;\n        switch (atom.type) {\n          case \"Character\":\n            addOptimizedIdxToResult(atom.value, result, ignoreCase);\n            break;\n          case \"Set\":\n            if (atom.complement === true) {\n              throw Error(complementErrorMessage);\n            }\n            atom.value.forEach((code) => {\n              if (typeof code === \"number\") {\n                addOptimizedIdxToResult(code, result, ignoreCase);\n              } else {\n                // range\n                const range = code as any;\n                // cannot optimize when ignoreCase is\n                if (ignoreCase === true) {\n                  for (\n                    let rangeCode = range.from;\n                    rangeCode <= range.to;\n                    rangeCode++\n                  ) {\n                    addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n                  }\n                }\n                // Optimization (2 orders of magnitude less work for very large ranges)\n                else {\n                  // handle unoptimized values\n                  for (\n                    let rangeCode = range.from;\n                    rangeCode <= range.to && rangeCode < minOptimizationVal;\n                    rangeCode++\n                  ) {\n                    addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n                  }\n\n                  // Less common charCode where we optimize for faster init time, by using larger \"buckets\"\n                  if (range.to >= minOptimizationVal) {\n                    const minUnOptVal =\n                      range.from >= minOptimizationVal\n                        ? range.from\n                        : minOptimizationVal;\n                    const maxUnOptVal = range.to;\n                    const minOptIdx = charCodeToOptimizedIndex(minUnOptVal);\n                    const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal);\n\n                    for (\n                      let currOptIdx = minOptIdx;\n                      currOptIdx <= maxOptIdx;\n                      currOptIdx++\n                    ) {\n                      result[currOptIdx] = currOptIdx;\n                    }\n                  }\n                }\n              }\n            });\n            break;\n          case \"Group\":\n            firstCharOptimizedIndices(atom.value, result, ignoreCase);\n            break;\n          /* istanbul ignore next */\n          default:\n            throw Error(\"Non Exhaustive Match\");\n        }\n\n        // reached a mandatory production, no more **start** codes can be found on this alternative\n        const isOptionalQuantifier =\n          atom.quantifier !== undefined && atom.quantifier.atLeast === 0;\n        if (\n          // A group may be optional due to empty contents /(?:)/\n          // or if everything inside it is optional /((a)?)/\n          (atom.type === \"Group\" && isWholeOptional(atom) === false) ||\n          // If this term is not a group it may only be optional if it has an optional quantifier\n          (atom.type !== \"Group\" && isOptionalQuantifier === false)\n        ) {\n          break;\n        }\n      }\n      break;\n    /* istanbul ignore next */\n    default:\n      throw Error(\"non exhaustive match!\");\n  }\n\n  // console.log(Object.keys(result).length)\n  return Object.values(result);\n}\n\nfunction addOptimizedIdxToResult(\n  code: number,\n  result: { [charCode: number]: number },\n  ignoreCase: boolean,\n) {\n  const optimizedCharIdx = charCodeToOptimizedIndex(code);\n  result[optimizedCharIdx] = optimizedCharIdx;\n\n  if (ignoreCase === true) {\n    handleIgnoreCase(code, result);\n  }\n}\n\nfunction handleIgnoreCase(\n  code: number,\n  result: { [charCode: number]: number },\n) {\n  const char = String.fromCharCode(code);\n  const upperChar = char.toUpperCase();\n  /* istanbul ignore else */\n  if (upperChar !== char) {\n    const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0));\n    result[optimizedCharIdx] = optimizedCharIdx;\n  } else {\n    const lowerChar = char.toLowerCase();\n    if (lowerChar !== char) {\n      const optimizedCharIdx = charCodeToOptimizedIndex(\n        lowerChar.charCodeAt(0),\n      );\n      result[optimizedCharIdx] = optimizedCharIdx;\n    }\n  }\n}\n\nfunction findCode(setNode: Set, targetCharCodes: number[]) {\n  return setNode.value.find((codeOrRange) => {\n    if (typeof codeOrRange === \"number\") {\n      return targetCharCodes.includes(codeOrRange);\n    } else {\n      // range\n      const range = <any>codeOrRange;\n      return (\n        targetCharCodes.find(\n          (targetCode) => range.from <= targetCode && targetCode <= range.to,\n        ) !== undefined\n      );\n    }\n  });\n}\n\nfunction isWholeOptional(ast: any): boolean {\n  const quantifier = (ast as Atom).quantifier;\n  if (quantifier && quantifier.atLeast === 0) {\n    return true;\n  }\n\n  if (!ast.value) {\n    return false;\n  }\n\n  return Array.isArray(ast.value)\n    ? ast.value.every(isWholeOptional)\n    : isWholeOptional(ast.value);\n}\n\nclass CharCodeFinder extends BaseRegExpVisitor {\n  found: boolean = false;\n\n  constructor(private targetCharCodes: number[]) {\n    super();\n  }\n\n  visitChildren(node: ASTNode) {\n    // No need to keep looking...\n    if (this.found === true) {\n      return;\n    }\n\n    // switch lookaheads / lookbehinds as they do not actually consume any characters thus\n    // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.\n    switch (node.type) {\n      case \"Lookahead\":\n        this.visitLookahead(node);\n        return;\n      case \"NegativeLookahead\":\n        this.visitNegativeLookahead(node);\n        return;\n      case \"Lookbehind\":\n        this.visitLookbehind(node);\n        return;\n      case \"NegativeLookbehind\":\n        this.visitNegativeLookbehind(node);\n        return;\n    }\n\n    super.visitChildren(node);\n  }\n\n  visitCharacter(node: Character) {\n    if (this.targetCharCodes.includes(node.value)) {\n      this.found = true;\n    }\n  }\n\n  visitSet(node: Set) {\n    if (node.complement) {\n      if (findCode(node, this.targetCharCodes) === undefined) {\n        this.found = true;\n      }\n    } else {\n      if (findCode(node, this.targetCharCodes) !== undefined) {\n        this.found = true;\n      }\n    }\n  }\n}\n\nexport function canMatchCharCode(\n  charCodes: number[],\n  pattern: RegExp | string,\n): boolean {\n  if (pattern instanceof RegExp) {\n    const ast = getRegExpAst(pattern);\n    const charCodeFinder = new CharCodeFinder(charCodes);\n    charCodeFinder.visit(ast);\n    return charCodeFinder.found;\n  } else {\n    for (const char of pattern) {\n      const charCode = char.charCodeAt(0);\n      if (charCodes.includes(charCode)) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n", "import { BaseRegExpVisitor, Quantifier, Set } from \"@chevrotain/regexp-to-ast\";\nimport {\n  IRegExpExec,\n  Lexer,\n  LexerDefinitionErrorType,\n} from \"./lexer_public.js\";\n\nimport { PRINT_ERROR } from \"@chevrotain/utils\";\nimport {\n  canMatchCharCode,\n  failedOptimizationPrefixMsg,\n  getOptimizedStartCodesIndices,\n} from \"./reg_exp.js\";\nimport {\n  ILexerDefinitionError,\n  ILineTerminatorsTester,\n  IMultiModeLexerDefinition,\n  IToken,\n  TokenType,\n} from \"@chevrotain/types\";\nimport { getRegExpAst } from \"./reg_exp_parser.js\";\n\nconst PATTERN = \"PATTERN\";\nexport const DEFAULT_MODE = \"defaultMode\";\nexport const MODES = \"modes\";\n\nexport const SINGLE_CHAR_MATCH = 0;\nexport const CUSTOM_MATCH = 1;\nexport const REG_EXP_MATCH = 2;\nexport const ASCII_CLASS_MATCH = 3;\n\ntype MatchType =\n  | typeof SINGLE_CHAR_MATCH\n  | typeof CUSTOM_MATCH\n  | typeof REG_EXP_MATCH\n  | typeof ASCII_CLASS_MATCH;\n\nexport interface IPatternConfig {\n  pattern: IRegExpExec | string;\n  asciiClass: Uint8Array | undefined;\n  longerAlt: number[] | undefined;\n  canLineTerminator: boolean;\n  matchType: MatchType;\n  short: number | false;\n  group: string | undefined | false;\n  push: string | undefined;\n  pop: boolean;\n  tokenType: TokenType;\n  tokenTypeIdx: number;\n}\n\nexport interface IAnalyzeResult {\n  patternIdxToConfig: IPatternConfig[];\n  charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] };\n  emptyGroups: { [groupName: string]: IToken[] };\n  hasCustom: boolean;\n  canBeOptimized: boolean;\n}\n\nexport function analyzeTokenTypes(\n  tokenTypes: TokenType[],\n  options: {\n    positionTracking?: \"full\" | \"onlyStart\" | \"onlyOffset\";\n    ensureOptimizations?: boolean;\n    lineTerminatorCharacters?: (number | string)[];\n    safeMode?: boolean;\n    tracer?: (msg: string, action: () => void) => void;\n  },\n): IAnalyzeResult {\n  options = {\n    safeMode: false as boolean,\n    positionTracking: \"full\",\n    lineTerminatorCharacters: [\"\\r\", \"\\n\"],\n    tracer: (msg: string, action: Function) => action(),\n    ...options,\n  };\n\n  const tracer = options.tracer!;\n\n  tracer(\"initCharCodeToOptimizedIndexMap\", () => {\n    initCharCodeToOptimizedIndexMap();\n  });\n\n  let onlyRelevantTypes: TokenType[];\n  tracer(\"Reject Lexer.NA\", () => {\n    onlyRelevantTypes = tokenTypes.filter((currType) => {\n      return currType[PATTERN] !== Lexer.NA;\n    });\n  });\n\n  let hasCustom = false;\n  let allTransformedPatterns: (IRegExpExec | string)[];\n  tracer(\"Transform Patterns\", () => {\n    hasCustom = false;\n    allTransformedPatterns = onlyRelevantTypes.map(\n      (currType): IRegExpExec | string => {\n        const currPattern = currType[PATTERN];\n\n        /* istanbul ignore else */\n        if (currPattern instanceof RegExp) {\n          const regExpSource = currPattern.source;\n          if (\n            regExpSource.length === 1 &&\n            // only these regExp meta characters which can appear in a length one regExp\n            regExpSource !== \"^\" &&\n            regExpSource !== \"$\" &&\n            regExpSource !== \".\" &&\n            !currPattern.ignoreCase\n          ) {\n            return regExpSource;\n          } else if (\n            regExpSource.length === 2 &&\n            regExpSource[0] === \"\\\\\" &&\n            // not a meta character\n            ![\n              \"d\",\n              \"D\",\n              \"s\",\n              \"S\",\n              \"t\",\n              \"r\",\n              \"n\",\n              \"t\",\n              \"0\",\n              \"c\",\n              \"b\",\n              \"B\",\n              \"f\",\n              \"v\",\n              \"w\",\n              \"W\",\n            ].includes(regExpSource[1])\n          ) {\n            // escaped meta Characters: /\\+/ /\\[/\n            // or redundant escaping: /\\a/\n            // without the escaping \"\\\"\n            return regExpSource[1];\n          } else {\n            return addStickyFlag(currPattern);\n          }\n        } else if (typeof currPattern === \"function\") {\n          hasCustom = true;\n          // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n          return { exec: currPattern };\n        } else if (typeof currPattern === \"object\") {\n          hasCustom = true;\n          // ICustomPattern\n          return currPattern;\n        } else if (typeof currPattern === \"string\") {\n          if (currPattern.length === 1) {\n            return currPattern;\n          } else {\n            const escapedRegExpString = currPattern.replace(\n              /[\\\\^$.*+?()[\\]{}|]/g,\n              \"\\\\$&\",\n            );\n            const wrappedRegExp = new RegExp(escapedRegExpString);\n            return addStickyFlag(wrappedRegExp);\n          }\n        } else {\n          throw Error(\"non exhaustive match\");\n        }\n      },\n    );\n  });\n\n  let patternIdxToType: number[];\n  let patternIdxToGroup: (string | undefined | false)[];\n  let patternIdxToLongerAltIdxArr: (number[] | undefined)[];\n  let patternIdxToPushMode: (string | undefined)[];\n  let patternIdxToPopMode: boolean[];\n  tracer(\"misc mapping\", () => {\n    patternIdxToType = onlyRelevantTypes.map(\n      (currType) => currType.tokenTypeIdx!,\n    );\n\n    patternIdxToGroup = onlyRelevantTypes.map((clazz: any) => {\n      const groupName = clazz.GROUP;\n      /* istanbul ignore next */\n      if (groupName === Lexer.SKIPPED) {\n        return undefined;\n      } else if (typeof groupName === \"string\") {\n        return groupName;\n      } else if (groupName === undefined) {\n        return false;\n      } else {\n        throw Error(\"non exhaustive match\");\n      }\n    });\n\n    patternIdxToLongerAltIdxArr = onlyRelevantTypes.map((clazz: any) => {\n      const longerAltType = clazz.LONGER_ALT;\n\n      if (longerAltType) {\n        const longerAltIdxArr = Array.isArray(longerAltType)\n          ? longerAltType.map((type: any) => onlyRelevantTypes.indexOf(type))\n          : [onlyRelevantTypes.indexOf(longerAltType)];\n        return longerAltIdxArr;\n      }\n    });\n\n    patternIdxToPushMode = onlyRelevantTypes.map(\n      (clazz: any) => clazz.PUSH_MODE,\n    );\n\n    patternIdxToPopMode = onlyRelevantTypes.map((clazz: any) =>\n      Object.hasOwn(clazz, \"POP_MODE\"),\n    );\n  });\n\n  let patternIdxToCanLineTerminator: boolean[];\n  tracer(\"Line Terminator Handling\", () => {\n    const lineTerminatorCharCodes = getCharCodes(\n      options.lineTerminatorCharacters!,\n    );\n    patternIdxToCanLineTerminator = onlyRelevantTypes.map((tokType) => false);\n    if (options.positionTracking !== \"onlyOffset\") {\n      patternIdxToCanLineTerminator = onlyRelevantTypes.map((tokType) => {\n        if (Object.hasOwn(tokType, \"LINE_BREAKS\")) {\n          return !!tokType.LINE_BREAKS;\n        } else {\n          return (\n            checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false &&\n            canMatchCharCode(\n              lineTerminatorCharCodes,\n              tokType.PATTERN as RegExp | string,\n            )\n          );\n        }\n      });\n    }\n  });\n\n  let patternIdxToIsCustom: boolean[];\n  let patternIdxToShort: (number | false)[];\n  let emptyGroups!: { [groupName: string]: IToken[] };\n  let patternIdxToConfig!: IPatternConfig[];\n  tracer(\"Misc Mapping #2\", () => {\n    patternIdxToIsCustom = onlyRelevantTypes.map(isCustomPattern);\n    patternIdxToShort = allTransformedPatterns.map(isShortPattern);\n\n    emptyGroups = onlyRelevantTypes.reduce(\n      (acc, clazz: any) => {\n        const groupName = clazz.GROUP;\n        if (typeof groupName === \"string\" && !(groupName === Lexer.SKIPPED)) {\n          acc[groupName] = [];\n        }\n        return acc;\n      },\n      {} as { [groupName: string]: IToken[] },\n    );\n\n    patternIdxToConfig = allTransformedPatterns.map(\n      (x, idx): IPatternConfig => {\n        const asciiClass =\n          patternIdxToGroup[idx] === undefined &&\n          patternIdxToLongerAltIdxArr[idx] === undefined\n            ? getAsciiClass(onlyRelevantTypes[idx].PATTERN)\n            : undefined;\n\n        return {\n          pattern: allTransformedPatterns[idx],\n          asciiClass,\n          longerAlt: patternIdxToLongerAltIdxArr[idx],\n          canLineTerminator: patternIdxToCanLineTerminator[idx],\n          matchType:\n            asciiClass !== undefined\n              ? ASCII_CLASS_MATCH\n              : patternIdxToShort[idx] !== false\n                ? SINGLE_CHAR_MATCH\n                : patternIdxToIsCustom[idx]\n                  ? CUSTOM_MATCH\n                  : REG_EXP_MATCH,\n          short: patternIdxToShort[idx],\n          group: patternIdxToGroup[idx],\n          push: patternIdxToPushMode[idx],\n          pop: patternIdxToPopMode[idx],\n          tokenTypeIdx: patternIdxToType[idx],\n          tokenType: onlyRelevantTypes[idx],\n        };\n      },\n    );\n  });\n\n  let canBeOptimized = true;\n  let charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] } =\n    [];\n\n  if (!options.safeMode) {\n    tracer(\"First Char Optimization\", () => {\n      charCodeToPatternIdxToConfig = onlyRelevantTypes.reduce(\n        (result, currTokType, idx) => {\n          if (typeof currTokType.PATTERN === \"string\") {\n            const charCode = currTokType.PATTERN.charCodeAt(0);\n            const optimizedIdx = charCodeToOptimizedIndex(charCode);\n            addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);\n          } else if (Array.isArray(currTokType.START_CHARS_HINT)) {\n            let lastOptimizedIdx: number;\n            currTokType.START_CHARS_HINT.forEach((charOrInt) => {\n              const charCode =\n                typeof charOrInt === \"string\"\n                  ? charOrInt.charCodeAt(0)\n                  : charOrInt;\n              const currOptimizedIdx = charCodeToOptimizedIndex(charCode);\n              // Avoid adding the config multiple times\n              /* istanbul ignore else */\n              // - Difficult to check this scenario effects as it is only a performance\n              //   optimization that does not change correctness\n              if (lastOptimizedIdx !== currOptimizedIdx) {\n                lastOptimizedIdx = currOptimizedIdx;\n                addToMapOfArrays(\n                  result,\n                  currOptimizedIdx,\n                  patternIdxToConfig[idx],\n                );\n              }\n            });\n          } else if (currTokType.PATTERN instanceof RegExp) {\n            if (currTokType.PATTERN.unicode) {\n              canBeOptimized = false;\n              if (options.ensureOptimizations) {\n                PRINT_ERROR(\n                  `${failedOptimizationPrefixMsg}` +\n                    `\\tUnable to analyze < ${currTokType.PATTERN.toString()} > pattern.\\n` +\n                    \"\\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\\n\" +\n                    \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n                    \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE\",\n                );\n              }\n            } else {\n              const optimizedCodes = getOptimizedStartCodesIndices(\n                currTokType.PATTERN,\n                options.ensureOptimizations,\n              );\n              /* istanbul ignore if */\n              // start code will only be empty given an empty regExp or failure of regexp-to-ast library\n              // the first should be a different validation and the second cannot be tested.\n              if (optimizedCodes.length === 0) {\n                // we cannot understand what codes may start possible matches\n                // The optimization correctness requires knowing start codes for ALL patterns.\n                // Not actually sure this is an error, no debug message\n                canBeOptimized = false;\n              }\n              optimizedCodes.forEach((code) => {\n                addToMapOfArrays(result, code, patternIdxToConfig[idx]);\n              });\n            }\n          } else {\n            if (options.ensureOptimizations) {\n              PRINT_ERROR(\n                `${failedOptimizationPrefixMsg}` +\n                  `\\tTokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.\\n` +\n                  \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n                  \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE\",\n              );\n            }\n            canBeOptimized = false;\n          }\n\n          return result;\n        },\n        [] as { [charCode: number]: IPatternConfig[] },\n      );\n    });\n  }\n\n  return {\n    emptyGroups: emptyGroups,\n    patternIdxToConfig: patternIdxToConfig,\n    charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,\n    hasCustom: hasCustom,\n    canBeOptimized: canBeOptimized,\n  };\n}\n\nfunction getAsciiClass(pattern: unknown): Uint8Array | undefined {\n  // Flags may change character-set semantics, so only analyze plain RegExps.\n  if (!(pattern instanceof RegExp) || pattern.flags !== \"\") {\n    return undefined;\n  }\n\n  let ast;\n  try {\n    ast = getRegExpAst(pattern);\n  } catch {\n    return undefined;\n  }\n\n  // The fast scanner can only replace one alternative containing one atom.\n  if (ast.value.value.length !== 1 || ast.value.value[0].value.length !== 1) {\n    return undefined;\n  }\n\n  // Unwrap noncapturing single-atom groups while retaining the sole quantifier.\n  let atom = ast.value.value[0].value[0];\n  let quantifier: Quantifier | undefined;\n  while (atom.type === \"Group\") {\n    if (\n      atom.capturing ||\n      (atom.quantifier !== undefined && quantifier !== undefined) ||\n      atom.value.value.length !== 1 ||\n      atom.value.value[0].value.length !== 1\n    ) {\n      return undefined;\n    }\n    quantifier = atom.quantifier ?? quantifier;\n    atom = atom.value.value[0].value[0];\n  }\n\n  // The remaining atom must be a non-complement set repeated greedily 1+ times.\n  if (\n    atom.type !== \"Set\" ||\n    atom.complement ||\n    (atom.quantifier !== undefined && quantifier !== undefined)\n  ) {\n    return undefined;\n  }\n  quantifier = atom.quantifier ?? quantifier;\n  if (\n    quantifier?.atLeast !== 1 ||\n    quantifier.atMost !== Infinity ||\n    !quantifier.greedy\n  ) {\n    return undefined;\n  }\n\n  // Materialize ASCII membership, rejecting any code point outside the table.\n  const result = new Uint8Array(128);\n  for (const item of (atom as Set).value) {\n    const from = typeof item === \"number\" ? item : item.from;\n    const to = typeof item === \"number\" ? item : item.to;\n    if (from < 0 || to >= result.length) {\n      return undefined;\n    }\n    result.fill(1, from, to + 1);\n  }\n  return result;\n}\n\nexport function validatePatterns(\n  tokenTypes: TokenType[],\n  validModesNames: string[],\n): ILexerDefinitionError[] {\n  let errors: ILexerDefinitionError[] = [];\n\n  const missingResult = findMissingPatterns(tokenTypes);\n  errors = errors.concat(missingResult.errors);\n\n  const invalidResult = findInvalidPatterns(missingResult.valid);\n  const validTokenTypes = invalidResult.valid;\n  errors = errors.concat(invalidResult.errors);\n\n  errors = errors.concat(validateRegExpPattern(validTokenTypes));\n\n  errors = errors.concat(findInvalidGroupType(validTokenTypes));\n\n  errors = errors.concat(\n    findModesThatDoNotExist(validTokenTypes, validModesNames),\n  );\n\n  errors = errors.concat(findUnreachablePatterns(validTokenTypes));\n\n  return errors;\n}\n\nfunction validateRegExpPattern(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  let errors: ILexerDefinitionError[] = [];\n  const withRegExpPatterns = tokenTypes.filter(\n    (currTokType) => currTokType[PATTERN] instanceof RegExp,\n  );\n\n  errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));\n\n  errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));\n\n  errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));\n\n  errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));\n\n  errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));\n\n  return errors;\n}\n\nexport interface ILexerFilterResult {\n  errors: ILexerDefinitionError[];\n  valid: TokenType[];\n}\n\nexport function findMissingPatterns(\n  tokenTypes: TokenType[],\n): ILexerFilterResult {\n  const tokenTypesWithMissingPattern = tokenTypes.filter((currType) => {\n    return !Object.hasOwn(currType, PATTERN);\n  });\n\n  const errors = tokenTypesWithMissingPattern.map((currType) => {\n    return {\n      message:\n        \"Token Type: ->\" +\n        currType.name +\n        \"<- missing static 'PATTERN' property\",\n      type: LexerDefinitionErrorType.MISSING_PATTERN,\n      tokenTypes: [currType],\n    };\n  });\n\n  const valid = tokenTypes.filter(\n    (x) => !tokenTypesWithMissingPattern.includes(x),\n  );\n  return { errors, valid };\n}\n\nexport function findInvalidPatterns(\n  tokenTypes: TokenType[],\n): ILexerFilterResult {\n  const tokenTypesWithInvalidPattern = tokenTypes.filter((currType) => {\n    const pattern = currType[PATTERN];\n    return (\n      !(pattern instanceof RegExp) &&\n      !(typeof pattern === \"function\") &&\n      !Object.hasOwn(pattern as any, \"exec\") &&\n      !(typeof pattern === \"string\")\n    );\n  });\n\n  const errors = tokenTypesWithInvalidPattern.map((currType) => {\n    return {\n      message:\n        \"Token Type: ->\" +\n        currType.name +\n        \"<- static 'PATTERN' can only be a RegExp, a\" +\n        \" Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.\",\n      type: LexerDefinitionErrorType.INVALID_PATTERN,\n      tokenTypes: [currType],\n    };\n  });\n\n  const valid = tokenTypes.filter(\n    (x) => !tokenTypesWithInvalidPattern.includes(x),\n  );\n  return { errors, valid };\n}\n\nconst end_of_input = /[^\\\\][$]/;\n\nexport function findEndOfInputAnchor(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  class EndAnchorFinder extends BaseRegExpVisitor {\n    found = false;\n\n    visitEndAnchor(node: unknown) {\n      this.found = true;\n    }\n  }\n\n  const invalidRegex = tokenTypes.filter((currType) => {\n    const pattern = currType.PATTERN;\n\n    try {\n      const regexpAst = getRegExpAst(pattern as RegExp);\n      const endAnchorVisitor = new EndAnchorFinder();\n      endAnchorVisitor.visit(regexpAst);\n\n      return endAnchorVisitor.found;\n    } catch (e) {\n      // old behavior in case of runtime exceptions with regexp-to-ast.\n      /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n      return end_of_input.test((pattern as RegExp).source);\n    }\n  });\n\n  const errors = invalidRegex.map((currType) => {\n    return {\n      message:\n        \"Unexpected RegExp Anchor Error:\\n\" +\n        \"\\tToken Type: ->\" +\n        currType.name +\n        \"<- static 'PATTERN' cannot contain end of input anchor '$'\\n\" +\n        \"\\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n        \"\\tfor details.\",\n      type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND,\n      tokenTypes: [currType],\n    };\n  });\n\n  return errors;\n}\n\nexport function findEmptyMatchRegExps(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  const matchesEmptyString = tokenTypes.filter((currType) => {\n    const pattern = currType.PATTERN as RegExp;\n    return pattern.test(\"\");\n  });\n\n  const errors = matchesEmptyString.map((currType) => {\n    return {\n      message:\n        \"Token Type: ->\" +\n        currType.name +\n        \"<- static 'PATTERN' must not match an empty string\",\n      type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,\n      tokenTypes: [currType],\n    };\n  });\n\n  return errors;\n}\n\nconst start_of_input = /[^\\\\[][\\^]|^\\^/;\n\nexport function findStartOfInputAnchor(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  class StartAnchorFinder extends BaseRegExpVisitor {\n    found = false;\n\n    visitStartAnchor(node: unknown) {\n      this.found = true;\n    }\n  }\n\n  const invalidRegex = tokenTypes.filter((currType) => {\n    const pattern = currType.PATTERN as RegExp;\n    try {\n      const regexpAst = getRegExpAst(pattern);\n      const startAnchorVisitor = new StartAnchorFinder();\n      startAnchorVisitor.visit(regexpAst);\n\n      return startAnchorVisitor.found;\n    } catch (e) {\n      // old behavior in case of runtime exceptions with regexp-to-ast.\n      /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n      return start_of_input.test(pattern.source);\n    }\n  });\n\n  const errors = invalidRegex.map((currType) => {\n    return {\n      message:\n        \"Unexpected RegExp Anchor Error:\\n\" +\n        \"\\tToken Type: ->\" +\n        currType.name +\n        \"<- static 'PATTERN' cannot contain start of input anchor '^'\\n\" +\n        \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n        \"\\tfor details.\",\n      type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND,\n      tokenTypes: [currType],\n    };\n  });\n\n  return errors;\n}\n\nexport function findUnsupportedFlags(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  const invalidFlags = tokenTypes.filter((currType) => {\n    const pattern = currType[PATTERN];\n    return pattern instanceof RegExp && (pattern.multiline || pattern.global);\n  });\n\n  const errors = invalidFlags.map((currType) => {\n    return {\n      message:\n        \"Token Type: ->\" +\n        currType.name +\n        \"<- static 'PATTERN' may NOT contain global('g') or multiline('m')\",\n      type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,\n      tokenTypes: [currType],\n    };\n  });\n\n  return errors;\n}\n\n// This can only test for identical duplicate RegExps, not semantically equivalent ones.\nexport function findDuplicatePatterns(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  const found: TokenType[] = [];\n  let identicalPatterns = tokenTypes.map((outerType: any) => {\n    return tokenTypes.reduce((result, innerType) => {\n      if (\n        outerType.PATTERN.source === (innerType.PATTERN as RegExp).source &&\n        !found.includes(innerType) &&\n        innerType.PATTERN !== Lexer.NA\n      ) {\n        // this avoids duplicates in the result, each Token Type may only appear in one \"set\"\n        // in essence we are creating Equivalence classes on equality relation.\n        found.push(innerType);\n        result.push(innerType);\n        return result;\n      }\n      return result;\n    }, [] as TokenType[]);\n  });\n\n  identicalPatterns = identicalPatterns.filter(Boolean);\n\n  const duplicatePatterns = identicalPatterns.filter((currIdenticalSet) => {\n    return currIdenticalSet.length > 1;\n  });\n\n  const errors = duplicatePatterns.map((setOfIdentical: any) => {\n    const tokenTypeNames = setOfIdentical.map((currType: any) => {\n      return currType.name;\n    });\n\n    const dupPatternSrc = (<any>setOfIdentical[0]).PATTERN;\n    return {\n      message:\n        `The same RegExp pattern ->${dupPatternSrc}<-` +\n        `has been used in all of the following Token Types: ${tokenTypeNames.join(\n          \", \",\n        )} <-`,\n      type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,\n      tokenTypes: setOfIdentical,\n    };\n  });\n\n  return errors;\n}\n\nexport function findInvalidGroupType(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  const invalidTypes = tokenTypes.filter((clazz: any) => {\n    if (!Object.hasOwn(clazz, \"GROUP\")) {\n      return false;\n    }\n    const group = clazz.GROUP;\n\n    return (\n      group !== Lexer.SKIPPED &&\n      group !== Lexer.NA &&\n      !(typeof group === \"string\")\n    );\n  });\n\n  const errors = invalidTypes.map((currType) => {\n    return {\n      message:\n        \"Token Type: ->\" +\n        currType.name +\n        \"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String\",\n      type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,\n      tokenTypes: [currType],\n    };\n  });\n\n  return errors;\n}\n\nexport function findModesThatDoNotExist(\n  tokenTypes: TokenType[],\n  validModes: string[],\n): ILexerDefinitionError[] {\n  const invalidModes = tokenTypes.filter((clazz: any) => {\n    return (\n      clazz.PUSH_MODE !== undefined && !validModes.includes(clazz.PUSH_MODE)\n    );\n  });\n\n  const errors = invalidModes.map((tokType) => {\n    const msg =\n      `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-` +\n      `which does not exist`;\n    return {\n      message: msg,\n      type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,\n      tokenTypes: [tokType],\n    };\n  });\n\n  return errors;\n}\n\nexport function findUnreachablePatterns(\n  tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n  const errors: ILexerDefinitionError[] = [];\n\n  const canBeTested = tokenTypes.reduce(\n    (result, tokType, idx) => {\n      const pattern = tokType.PATTERN;\n\n      if (pattern === Lexer.NA) {\n        return result;\n      }\n\n      // a more comprehensive validation for all forms of regExps would require\n      // deeper regExp analysis capabilities\n      if (typeof pattern === \"string\") {\n        result.push({ str: pattern, idx, tokenType: tokType });\n      } else if (pattern instanceof RegExp && noMetaChar(pattern)) {\n        result.push({ str: pattern.source, idx, tokenType: tokType });\n      }\n      return result;\n    },\n    [] as { str: string; idx: number; tokenType: TokenType }[],\n  );\n\n  tokenTypes.forEach((aTokType, aIdx) => {\n    canBeTested.forEach(({ str: bStr, idx: bIdx, tokenType: bTokType }) => {\n      if (aIdx < bIdx && tryToMatchStrToPattern(bStr, aTokType.PATTERN)) {\n        const msg =\n          `Token: ->${bTokType.name}<- can never be matched.\\n` +\n          `Because it appears AFTER the Token Type ->${aTokType.name}<-` +\n          `in the lexer's definition.\\n` +\n          `See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;\n        errors.push({\n          message: msg,\n          type: LexerDefinitionErrorType.UNREACHABLE_PATTERN,\n          tokenTypes: [aTokType, bTokType],\n        });\n      }\n    });\n  });\n\n  return errors;\n}\n\nfunction tryToMatchStrToPattern(str: string, pattern: any): boolean {\n  if (pattern instanceof RegExp) {\n    if (usesLookAheadOrBehind(pattern)) {\n      // if lookahead or lookbehind assertions are used\n      // we assume they would be responsible for disambiguating the match\n      // The alternative is to risk false positive unreachable pattern errors.\n      // e.g.: /(?<!a)b/ and /b/ tokens would cause such false positives.\n      return false;\n    }\n    const regExpArray = pattern.exec(str);\n    return regExpArray !== null && regExpArray.index === 0;\n  } else if (typeof pattern === \"function\") {\n    // maintain the API of custom patterns\n    return pattern(str, 0, [], {});\n  } else if (Object.hasOwn(pattern, \"exec\")) {\n    // maintain the API of custom patterns\n    return pattern.exec(str, 0, [], {});\n  } else if (typeof pattern === \"string\") {\n    return pattern === str;\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nfunction noMetaChar(regExp: RegExp): boolean {\n  //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\n  const metaChars = [\n    \".\",\n    \"\\\\\",\n    \"[\",\n    \"]\",\n    \"|\",\n    \"^\",\n    \"$\",\n    \"(\",\n    \")\",\n    \"?\",\n    \"*\",\n    \"+\",\n    \"{\",\n  ];\n  return (\n    metaChars.find((char) => regExp.source.indexOf(char) !== -1) === undefined\n  );\n}\n\nfunction usesLookAheadOrBehind(regExp: RegExp): boolean {\n  return /(\\(\\?=)|(\\(\\?!)|(\\(\\?<=)|(\\(\\?<!)/.test(regExp.source);\n}\n\nexport function addStartOfInput(pattern: RegExp): RegExp {\n  const flags = pattern.ignoreCase ? \"i\" : \"\";\n  // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.\n  // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)\n  return new RegExp(`^(?:${pattern.source})`, flags);\n}\n\nexport function addStickyFlag(pattern: RegExp): RegExp {\n  const flags = pattern.ignoreCase ? \"iy\" : \"y\";\n  return new RegExp(`${pattern.source}`, flags);\n}\n\nexport function performRuntimeChecks(\n  lexerDefinition: IMultiModeLexerDefinition,\n  trackLines: boolean,\n  lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n  const errors: ILexerDefinitionError[] = [];\n\n  // some run time checks to help the end users.\n  if (!Object.hasOwn(lexerDefinition, DEFAULT_MODE)) {\n    errors.push({\n      message:\n        \"A MultiMode Lexer cannot be initialized without a <\" +\n        DEFAULT_MODE +\n        \"> property in its definition\\n\",\n      type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n    });\n  }\n  if (!Object.hasOwn(lexerDefinition, MODES)) {\n    errors.push({\n      message:\n        \"A MultiMode Lexer cannot be initialized without a <\" +\n        MODES +\n        \"> property in its definition\\n\",\n      type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n    });\n  }\n\n  if (\n    Object.hasOwn(lexerDefinition, MODES) &&\n    Object.hasOwn(lexerDefinition, DEFAULT_MODE) &&\n    !Object.hasOwn(lexerDefinition.modes, lexerDefinition.defaultMode)\n  ) {\n    errors.push({\n      message:\n        `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>` +\n        `which does not exist\\n`,\n      type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n    });\n  }\n\n  if (Object.hasOwn(lexerDefinition, MODES)) {\n    Object.keys(lexerDefinition.modes).forEach((currModeName) => {\n      const currModeValue = lexerDefinition.modes[currModeName];\n      currModeValue.forEach((currTokType, currIdx) => {\n        if (currTokType === undefined) {\n          errors.push({\n            message:\n              `A Lexer cannot be initialized using an undefined Token Type. Mode:` +\n              `<${currModeName}> at index: <${currIdx}>\\n`,\n            type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n          });\n        } else if (Object.hasOwn(currTokType, \"LONGER_ALT\")) {\n          const longerAlt = Array.isArray(currTokType.LONGER_ALT)\n            ? currTokType.LONGER_ALT\n            : [currTokType.LONGER_ALT];\n          longerAlt.forEach((currLongerAlt) => {\n            if (\n              currLongerAlt !== undefined &&\n              !currModeValue.includes(currLongerAlt)\n            ) {\n              errors.push({\n                message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt!.name}> on token <${currTokType.name}> outside of mode <${currModeName}>\\n`,\n                type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n              });\n            }\n          });\n        }\n      });\n    });\n  }\n\n  return errors;\n}\n\nexport function performWarningRuntimeChecks(\n  lexerDefinition: IMultiModeLexerDefinition,\n  trackLines: boolean,\n  lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n  const warnings = [];\n  let hasAnyLineBreak = false;\n  const allTokenTypes = Object.values(lexerDefinition.modes || {})\n    .flat()\n    .filter(Boolean);\n\n  const concreteTokenTypes = allTokenTypes.filter(\n    (currType) => currType[PATTERN] !== Lexer.NA,\n  );\n  const terminatorCharCodes = getCharCodes(lineTerminatorCharacters);\n  if (trackLines) {\n    concreteTokenTypes.forEach((tokType) => {\n      const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);\n      if (currIssue !== false) {\n        const message = buildLineBreakIssueMessage(tokType, currIssue);\n        const warningDescriptor = {\n          message,\n          type: currIssue.issue,\n          tokenType: tokType,\n        };\n        warnings.push(warningDescriptor);\n      } else {\n        // we don't want to attempt to scan if the user explicitly specified the line_breaks option.\n        if (Object.hasOwn(tokType, \"LINE_BREAKS\")) {\n          if (tokType.LINE_BREAKS === true) {\n            hasAnyLineBreak = true;\n          }\n        } else {\n          if (\n            canMatchCharCode(terminatorCharCodes, tokType.PATTERN as RegExp)\n          ) {\n            hasAnyLineBreak = true;\n          }\n        }\n      }\n    });\n  }\n\n  if (trackLines && !hasAnyLineBreak) {\n    warnings.push({\n      message:\n        \"Warning: No LINE_BREAKS Found.\\n\" +\n        \"\\tThis Lexer has been defined to track line and column information,\\n\" +\n        \"\\tBut none of the Token Types can be identified as matching a line terminator.\\n\" +\n        \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \\n\" +\n        \"\\tfor details.\",\n      type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS,\n    });\n  }\n  return warnings;\n}\n\n// TODO: refactor to avoid duplication\nexport function isCustomPattern(tokenType: TokenType): boolean {\n  const pattern = tokenType.PATTERN;\n  /* istanbul ignore else */\n  if (pattern instanceof RegExp) {\n    return false;\n  } else if (typeof pattern === \"function\") {\n    // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n    return true;\n  } else if (Object.hasOwn(pattern as any, \"exec\")) {\n    // ICustomPattern\n    return true;\n  } else if (typeof pattern === \"string\") {\n    return false;\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nexport function isShortPattern(pattern: any): number | false {\n  if (typeof pattern === \"string\" && pattern.length === 1) {\n    return pattern.charCodeAt(0);\n  } else {\n    return false;\n  }\n}\n\n/**\n * Faster than using a RegExp for default newline detection during lexing.\n */\nexport const LineTerminatorOptimizedTester: ILineTerminatorsTester = {\n  // implements /\\n|\\r\\n?/g.test\n  test: function (text) {\n    const len = text.length;\n    for (let i = this.lastIndex; i < len; i++) {\n      const c = text.charCodeAt(i);\n      if (c === 10) {\n        this.lastIndex = i + 1;\n        return true;\n      } else if (c === 13) {\n        if (text.charCodeAt(i + 1) === 10) {\n          this.lastIndex = i + 2;\n        } else {\n          this.lastIndex = i + 1;\n        }\n        return true;\n      }\n    }\n    return false;\n  },\n\n  lastIndex: 0,\n};\n\nfunction checkLineBreaksIssues(\n  tokType: TokenType,\n  lineTerminatorCharCodes: number[],\n):\n  | {\n      issue:\n        | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n        | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n      errMsg?: string;\n    }\n  | false {\n  if (Object.hasOwn(tokType, \"LINE_BREAKS\")) {\n    // if the user explicitly declared the line_breaks option we will respect their choice\n    // and assume it is correct.\n    return false;\n  } else {\n    /* istanbul ignore else */\n    if (tokType.PATTERN instanceof RegExp) {\n      try {\n        // TODO: why is the casting suddenly needed?\n        canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN as RegExp);\n      } catch (e) {\n        /* istanbul ignore next - to test this we would have to mock <canMatchCharCode> to throw an error */\n        return {\n          issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR,\n          errMsg: (e as Error).message,\n        };\n      }\n      return false;\n    } else if (typeof tokType.PATTERN === \"string\") {\n      // string literal patterns can always be analyzed to detect line terminator usage\n      return false;\n    } else if (isCustomPattern(tokType)) {\n      // custom token types\n      return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK };\n    } else {\n      throw Error(\"non exhaustive match\");\n    }\n  }\n}\n\nexport function buildLineBreakIssueMessage(\n  tokType: TokenType,\n  details: {\n    issue:\n      | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n      | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n    errMsg?: string;\n  },\n): string {\n  /* istanbul ignore else */\n  if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {\n    return (\n      \"Warning: unable to identify line terminator usage in pattern.\\n\" +\n      `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n      `\\t Root cause: ${details.errMsg}.\\n` +\n      \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR\"\n    );\n  } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {\n    return (\n      \"Warning: A Custom Token Pattern should specify the <line_breaks> option.\\n\" +\n      `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n      \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK\"\n    );\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nfunction getCharCodes(charsOrCodes: (number | string)[]): number[] {\n  const charCodes = charsOrCodes.map((numOrString) => {\n    if (typeof numOrString === \"string\") {\n      return numOrString.charCodeAt(0);\n    } else {\n      return numOrString;\n    }\n  });\n\n  return charCodes;\n}\n\nfunction addToMapOfArrays<T>(\n  map: Record<number, T[]>,\n  key: number,\n  value: T,\n): void {\n  if (map[key] === undefined) {\n    map[key] = [value];\n  } else {\n    map[key].push(value);\n  }\n}\n\nexport const minOptimizationVal = 256;\n\n/**\n * We are mapping charCode above ASCI (256) into buckets each in the size of 256.\n * This is because ASCI are the most common start chars so each one of those will get its own\n * possible token configs vector.\n *\n * Tokens starting with charCodes \"above\" ASCI are uncommon, so we can \"afford\"\n * to place these into buckets of possible token configs, What we gain from\n * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig'\n * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario).\n * Our 'charCodeToPatternIdxToConfig' max size will now be:\n * 256 + (2^16 / 2^8) - 1 === 511\n *\n * note the hack for fast division integer part extraction\n * See: https://stackoverflow.com/a/4228528\n */\nlet charCodeToOptimizedIdxMap: number[] = [];\nexport function charCodeToOptimizedIndex(charCode: number): number {\n  return charCode < minOptimizationVal\n    ? charCode\n    : charCodeToOptimizedIdxMap[charCode];\n}\n\n/**\n * This is a compromise between cold start / hot running performance\n * Creating this array takes ~3ms on a modern machine,\n * But if we perform the computation at runtime as needed the CSS Lexer benchmark\n * performance degrades by ~10%\n *\n * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used.\n */\nfunction initCharCodeToOptimizedIndexMap() {\n  if (charCodeToOptimizedIdxMap.length === 0) {\n    charCodeToOptimizedIdxMap = new Array(65536);\n    for (let i = 0; i < 65536; i++) {\n      charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n    }\n  }\n}\n", "import { IToken, TokenType } from \"@chevrotain/types\";\n\nexport function tokenStructuredMatcher(\n  tokInstance: IToken,\n  tokConstructor: TokenType,\n) {\n  const instanceType = tokInstance.tokenTypeIdx;\n  if (instanceType === tokConstructor.tokenTypeIdx) {\n    return true;\n  } else {\n    return (\n      tokConstructor.isParent === true &&\n      tokConstructor.categoryMatchesMap![instanceType] === true\n    );\n  }\n}\n\n// Optimized tokenMatcher in case our grammar does not use token categories\n// Being so tiny it is much more likely to be in-lined and this avoid the function call overhead\nexport function tokenStructuredMatcherNoCategories(\n  token: IToken,\n  tokType: TokenType,\n) {\n  return token.tokenTypeIdx === tokType.tokenTypeIdx;\n}\n\nexport let tokenShortNameIdx = 1;\nexport const tokenIdxToClass: { [tokenIdx: number]: TokenType } = {};\n\nexport function augmentTokenTypes(tokenTypes: TokenType[]): void {\n  // collect the parent Token Types as well.\n  const tokenTypesAndParents = expandCategories(tokenTypes);\n\n  // add required tokenType and categoryMatches properties\n  assignTokenDefaultProps(tokenTypesAndParents);\n\n  // fill up the categoryMatches\n  assignCategoriesMapProp(tokenTypesAndParents);\n  assignCategoriesTokensProp(tokenTypesAndParents);\n\n  tokenTypesAndParents.forEach((tokType) => {\n    tokType.isParent = tokType.categoryMatches!.length > 0;\n  });\n}\n\nexport function expandCategories(tokenTypes: TokenType[]): TokenType[] {\n  let result = [...tokenTypes];\n\n  let categories = tokenTypes;\n  let searching = true;\n  while (searching) {\n    categories = categories\n      .map((currTokType) => currTokType.CATEGORIES)\n      .flat()\n      .filter(Boolean) as TokenType[];\n\n    const newCategories = categories.filter((x) => !result.includes(x));\n\n    result = result.concat(newCategories);\n\n    if (newCategories.length === 0) {\n      searching = false;\n    } else {\n      categories = newCategories;\n    }\n  }\n  return result;\n}\n\nexport function assignTokenDefaultProps(tokenTypes: TokenType[]): void {\n  tokenTypes.forEach((currTokType) => {\n    if (!hasShortKeyProperty(currTokType)) {\n      tokenIdxToClass[tokenShortNameIdx] = currTokType;\n      (<any>currTokType).tokenTypeIdx = tokenShortNameIdx++;\n    }\n\n    // CATEGORIES? : TokenType | TokenType[]\n    if (\n      hasCategoriesProperty(currTokType) &&\n      !Array.isArray(currTokType.CATEGORIES)\n      // &&\n      // !isUndefined(currTokType.CATEGORIES.PATTERN)\n    ) {\n      currTokType.CATEGORIES = [currTokType.CATEGORIES as unknown as TokenType];\n    }\n\n    if (!hasCategoriesProperty(currTokType)) {\n      currTokType.CATEGORIES = [];\n    }\n\n    if (!hasExtendingTokensTypesProperty(currTokType)) {\n      currTokType.categoryMatches = [];\n    }\n\n    if (!hasExtendingTokensTypesMapProperty(currTokType)) {\n      currTokType.categoryMatchesMap = {};\n    }\n  });\n}\n\nexport function assignCategoriesTokensProp(tokenTypes: TokenType[]): void {\n  tokenTypes.forEach((currTokType) => {\n    // avoid duplications\n    currTokType.categoryMatches = [];\n    Object.keys(currTokType.categoryMatchesMap!).forEach((key) => {\n      currTokType.categoryMatches!.push(\n        tokenIdxToClass[key as unknown as number].tokenTypeIdx!,\n      );\n    });\n  });\n}\n\nexport function assignCategoriesMapProp(tokenTypes: TokenType[]): void {\n  tokenTypes.forEach((currTokType) => {\n    singleAssignCategoriesToksMap([], currTokType);\n  });\n}\n\nexport function singleAssignCategoriesToksMap(\n  path: TokenType[],\n  nextNode: TokenType,\n): void {\n  path.forEach((pathNode) => {\n    nextNode.categoryMatchesMap![pathNode.tokenTypeIdx!] = true;\n  });\n\n  nextNode.CATEGORIES!.forEach((nextCategory) => {\n    const newPath = path.concat(nextNode);\n    // avoids infinite loops due to cyclic categories.\n    if (!newPath.includes(nextCategory)) {\n      singleAssignCategoriesToksMap(newPath, nextCategory);\n    }\n  });\n}\n\nexport function hasShortKeyProperty(tokType: TokenType): boolean {\n  return Object.hasOwn(tokType ?? {}, \"tokenTypeIdx\");\n}\n\nexport function hasCategoriesProperty(tokType: TokenType): boolean {\n  return Object.hasOwn(tokType ?? {}, \"CATEGORIES\");\n}\n\nexport function hasExtendingTokensTypesProperty(tokType: TokenType): boolean {\n  return Object.hasOwn(tokType ?? {}, \"categoryMatches\");\n}\n\nexport function hasExtendingTokensTypesMapProperty(\n  tokType: TokenType,\n): boolean {\n  return Object.hasOwn(tokType ?? {}, \"categoryMatchesMap\");\n}\n\nexport function isTokenType(tokType: TokenType): boolean {\n  return Object.hasOwn(tokType ?? {}, \"tokenTypeIdx\");\n}\n", "import { ILexerErrorMessageProvider, IToken } from \"@chevrotain/types\";\n\nexport const defaultLexerErrorProvider: ILexerErrorMessageProvider = {\n  buildUnableToPopLexerModeMessage(token: IToken): string {\n    return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`;\n  },\n\n  buildUnexpectedCharactersMessage(\n    fullText: string,\n    startOffset: number,\n    length: number,\n    line?: number,\n    column?: number,\n    mode?: string,\n  ): string {\n    return (\n      `unexpected character: ->${fullText.charAt(\n        startOffset,\n      )}<- at offset: ${startOffset},` + ` skipped ${length} characters.`\n    );\n  },\n};\n", "import {\n  analyzeTokenTypes,\n  ASCII_CLASS_MATCH,\n  charCodeToOptimizedIndex,\n  CUSTOM_MATCH,\n  DEFAULT_MODE,\n  IAnalyzeResult,\n  IPatternConfig,\n  LineTerminatorOptimizedTester,\n  performRuntimeChecks,\n  performWarningRuntimeChecks,\n  REG_EXP_MATCH,\n  SINGLE_CHAR_MATCH,\n  validatePatterns,\n} from \"./lexer.js\";\nimport { PRINT_WARNING, timer, toFastProperties } from \"@chevrotain/utils\";\nimport { augmentTokenTypes } from \"./tokens.js\";\nimport {\n  CustomPatternMatcherFunc,\n  CustomPatternMatcherReturn,\n  ILexerConfig,\n  ILexerDefinitionError,\n  ILexingError,\n  IMultiModeLexerDefinition,\n  IToken,\n  TokenType,\n} from \"@chevrotain/types\";\nimport { defaultLexerErrorProvider } from \"./lexer_errors_public.js\";\nimport { clearRegExpParserCache } from \"./reg_exp_parser.js\";\n\nexport interface ILexingResult {\n  tokens: IToken[];\n  groups: { [groupName: string]: IToken[] };\n  errors: ILexingError[];\n}\n\nexport enum LexerDefinitionErrorType {\n  MISSING_PATTERN,\n  INVALID_PATTERN,\n  EOI_ANCHOR_FOUND,\n  UNSUPPORTED_FLAGS_FOUND,\n  DUPLICATE_PATTERNS_FOUND,\n  INVALID_GROUP_TYPE_FOUND,\n  PUSH_MODE_DOES_NOT_EXIST,\n  MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n  MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n  MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n  LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n  SOI_ANCHOR_FOUND,\n  EMPTY_MATCH_PATTERN,\n  NO_LINE_BREAKS_FLAGS,\n  UNREACHABLE_PATTERN,\n  IDENTIFY_TERMINATOR,\n  CUSTOM_LINE_BREAK,\n  MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n}\n\nexport interface IRegExpExec {\n  exec: CustomPatternMatcherFunc;\n}\n\nconst DEFAULT_LEXER_CONFIG: Required<ILexerConfig> = {\n  deferDefinitionErrorsHandling: false,\n  positionTracking: \"full\",\n  lineTerminatorsPattern: /\\n|\\r\\n?/g,\n  lineTerminatorCharacters: [\"\\n\", \"\\r\"],\n  ensureOptimizations: false,\n  safeMode: false,\n  errorMessageProvider: defaultLexerErrorProvider,\n  traceInitPerf: false,\n  skipValidations: false,\n  recoveryEnabled: true,\n};\n\nObject.freeze(DEFAULT_LEXER_CONFIG);\n\nexport class Lexer {\n  public static SKIPPED =\n    \"This marks a skipped Token pattern, this means each token identified by it will \" +\n    \"be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.\";\n\n  public static NA = /NOT_APPLICABLE/;\n  public lexerDefinitionErrors: ILexerDefinitionError[] = [];\n  public lexerDefinitionWarning: ILexerDefinitionError[] = [];\n\n  protected patternIdxToConfig: Record<string, IPatternConfig[]> = {};\n  protected charCodeToPatternIdxToConfig: {\n    [modeName: string]: { [charCode: number]: IPatternConfig[] };\n  } = {};\n\n  protected modes: string[] = [];\n  protected defaultMode!: string;\n  protected emptyGroups: { [groupName: string]: IToken } = {};\n  private cachedGroupKeys: string[] = [];\n\n  private config: Required<ILexerConfig>;\n  private trackStartLines: boolean = true;\n  private trackEndLines: boolean = true;\n  private hasCustom: boolean = false;\n  private canModeBeOptimized: Record<string, boolean> = {};\n\n  private traceInitPerf!: boolean | number;\n  private traceInitMaxIdent!: number;\n  private traceInitIndent: number;\n\n  constructor(\n    protected lexerDefinition: TokenType[] | IMultiModeLexerDefinition,\n    config: ILexerConfig = DEFAULT_LEXER_CONFIG,\n  ) {\n    if (typeof config === \"boolean\") {\n      throw Error(\n        \"The second argument to the Lexer constructor is now an ILexerConfig Object.\\n\" +\n          \"a boolean 2nd argument is no longer supported\",\n      );\n    }\n\n    this.config = Object.assign({}, DEFAULT_LEXER_CONFIG, config) as any;\n\n    const traceInitVal = this.config.traceInitPerf;\n    if (traceInitVal === true) {\n      this.traceInitMaxIdent = Infinity;\n      this.traceInitPerf = true;\n    } else if (typeof traceInitVal === \"number\") {\n      this.traceInitMaxIdent = traceInitVal;\n      this.traceInitPerf = true;\n    }\n    this.traceInitIndent = -1;\n\n    this.TRACE_INIT(\"Lexer Constructor\", () => {\n      let actualDefinition!: IMultiModeLexerDefinition;\n      let hasOnlySingleMode = true;\n      this.TRACE_INIT(\"Lexer Config handling\", () => {\n        if (\n          this.config.lineTerminatorsPattern ===\n          DEFAULT_LEXER_CONFIG.lineTerminatorsPattern\n        ) {\n          // optimized built-in implementation for the defaults definition of lineTerminators\n          this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester;\n        } else {\n          if (\n            this.config.lineTerminatorCharacters ===\n            DEFAULT_LEXER_CONFIG.lineTerminatorCharacters\n          ) {\n            throw Error(\n              \"Error: Missing <lineTerminatorCharacters> property on the Lexer config.\\n\" +\n                \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS\",\n            );\n          }\n        }\n\n        if (config.safeMode && config.ensureOptimizations) {\n          throw Error(\n            '\"safeMode\" and \"ensureOptimizations\" flags are mutually exclusive.',\n          );\n        }\n\n        this.trackStartLines = /full|onlyStart/i.test(\n          this.config.positionTracking,\n        );\n        this.trackEndLines = /full/i.test(this.config.positionTracking);\n\n        // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition.\n        if (Array.isArray(lexerDefinition)) {\n          actualDefinition = {\n            modes: { defaultMode: [...lexerDefinition] },\n            defaultMode: DEFAULT_MODE,\n          };\n        } else {\n          // no conversion needed, input should already be a IMultiModeLexerDefinition\n          hasOnlySingleMode = false;\n          actualDefinition = {\n            ...(<IMultiModeLexerDefinition>lexerDefinition),\n          };\n        }\n      });\n\n      if (this.config.skipValidations === false) {\n        this.TRACE_INIT(\"performRuntimeChecks\", () => {\n          this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n            performRuntimeChecks(\n              actualDefinition,\n              this.trackStartLines,\n              this.config.lineTerminatorCharacters,\n            ),\n          );\n        });\n\n        this.TRACE_INIT(\"performWarningRuntimeChecks\", () => {\n          this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat(\n            performWarningRuntimeChecks(\n              actualDefinition,\n              this.trackStartLines,\n              this.config.lineTerminatorCharacters,\n            ),\n          );\n        });\n      }\n\n      // for extra robustness to avoid throwing a none informative error message\n      actualDefinition.modes = actualDefinition.modes\n        ? actualDefinition.modes\n        : {};\n\n      // an error of undefined TokenTypes will be detected in \"performRuntimeChecks\" above.\n      // this transformation is to increase robustness in the case of partially invalid lexer definition.\n      Object.entries(actualDefinition.modes).forEach(\n        ([currModeName, currModeValue]) => {\n          actualDefinition.modes[currModeName] = currModeValue.filter(\n            (currTokType: TokenType) => currTokType !== undefined,\n          );\n        },\n      );\n\n      const allModeNames = Object.keys(actualDefinition.modes);\n\n      Object.entries(actualDefinition.modes).forEach(\n        ([currModName, currModDef]: [string, TokenType[]]) => {\n          this.TRACE_INIT(`Mode: <${currModName}> processing`, () => {\n            this.modes.push(currModName);\n\n            if (this.config.skipValidations === false) {\n              this.TRACE_INIT(`validatePatterns`, () => {\n                this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n                  validatePatterns(currModDef, allModeNames),\n                );\n              });\n            }\n\n            // If definition errors were encountered, the analysis phase may fail unexpectedly/\n            // Considering a lexer with definition errors may never be used, there is no point\n            // to performing the analysis anyhow...\n            if (this.lexerDefinitionErrors.length === 0) {\n              augmentTokenTypes(currModDef);\n\n              let currAnalyzeResult!: IAnalyzeResult;\n              this.TRACE_INIT(`analyzeTokenTypes`, () => {\n                currAnalyzeResult = analyzeTokenTypes(currModDef, {\n                  lineTerminatorCharacters:\n                    this.config.lineTerminatorCharacters,\n                  positionTracking: config.positionTracking,\n                  ensureOptimizations: config.ensureOptimizations,\n                  safeMode: config.safeMode,\n                  tracer: this.TRACE_INIT,\n                });\n              });\n\n              this.patternIdxToConfig[currModName] =\n                currAnalyzeResult.patternIdxToConfig;\n\n              this.charCodeToPatternIdxToConfig[currModName] =\n                currAnalyzeResult.charCodeToPatternIdxToConfig;\n\n              this.emptyGroups = Object.assign(\n                {},\n                this.emptyGroups,\n                currAnalyzeResult.emptyGroups,\n              ) as any;\n\n              this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom;\n\n              this.canModeBeOptimized[currModName] =\n                currAnalyzeResult.canBeOptimized;\n            }\n          });\n        },\n      );\n\n      this.defaultMode = actualDefinition.defaultMode;\n      this.cachedGroupKeys = Object.keys(this.emptyGroups);\n\n      if (\n        this.lexerDefinitionErrors.length > 0 &&\n        !this.config.deferDefinitionErrorsHandling\n      ) {\n        const allErrMessages = this.lexerDefinitionErrors.map((error) => {\n          return error.message;\n        });\n        const allErrMessagesString = allErrMessages.join(\n          \"-----------------------\\n\",\n        );\n        throw new Error(\n          \"Errors detected in definition of Lexer:\\n\" + allErrMessagesString,\n        );\n      }\n\n      // Only print warning if there are no errors, This will avoid pl\n      this.lexerDefinitionWarning.forEach((warningDescriptor) => {\n        PRINT_WARNING(warningDescriptor.message);\n      });\n\n      this.TRACE_INIT(\"Choosing sub-methods implementations\", () => {\n        // Choose the relevant internal implementations for this specific parser.\n        // These implementations should be in-lined by the JavaScript engine\n        // to provide optimal performance in each scenario.\n\n        if (hasOnlySingleMode) {\n          this.handleModes = () => {};\n        }\n\n        if (this.trackStartLines === false) {\n          this.computeNewColumn = (x: any) => x;\n        }\n\n        if (this.trackEndLines === false) {\n          this.updateTokenEndLineColumnLocation = () => {};\n        }\n\n        if (/full/i.test(this.config.positionTracking)) {\n          this.createTokenInstance = this.createFullToken;\n        } else if (/onlyStart/i.test(this.config.positionTracking)) {\n          this.createTokenInstance = this.createStartOnlyToken;\n        } else if (/onlyOffset/i.test(this.config.positionTracking)) {\n          this.createTokenInstance = this.createOffsetOnlyToken;\n        } else {\n          throw Error(\n            `Invalid <positionTracking> config option: \"${this.config.positionTracking}\"`,\n          );\n        }\n\n        if (this.hasCustom) {\n          this.addToken = this.addTokenUsingPush;\n          this.handlePayload = this.handlePayloadWithCustom;\n        } else {\n          this.addToken = this.addTokenUsingMemberAccess;\n          this.handlePayload = this.handlePayloadNoCustom;\n        }\n      });\n\n      this.TRACE_INIT(\"Failed Optimization Warnings\", () => {\n        const unOptimizedModes = Object.entries(this.canModeBeOptimized).reduce(\n          (cannotBeOptimized, [modeName, canBeOptimized]) => {\n            if (canBeOptimized === false) {\n              cannotBeOptimized.push(modeName);\n            }\n            return cannotBeOptimized;\n          },\n          [] as string[],\n        );\n\n        if (config.ensureOptimizations && unOptimizedModes.length > 0) {\n          throw Error(\n            `Lexer Modes: < ${unOptimizedModes.join(\n              \", \",\n            )} > cannot be optimized.\\n` +\n              '\\t Disable the \"ensureOptimizations\" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\\n' +\n              \"\\t Or inspect the console log for details on how to resolve these issues.\",\n          );\n        }\n      });\n\n      this.TRACE_INIT(\"clearRegExpParserCache\", () => {\n        clearRegExpParserCache();\n      });\n\n      this.TRACE_INIT(\"toFastProperties\", () => {\n        toFastProperties(this);\n      });\n    });\n  }\n\n  public tokenize(\n    text: string,\n    initialMode: string = this.defaultMode,\n  ): ILexingResult {\n    if (this.lexerDefinitionErrors.length > 0) {\n      const allErrMessages = this.lexerDefinitionErrors.map((error) => {\n        return error.message;\n      });\n      const allErrMessagesString = allErrMessages.join(\n        \"-----------------------\\n\",\n      );\n      throw new Error(\n        \"Unable to Tokenize because Errors detected in definition of Lexer:\\n\" +\n          allErrMessagesString,\n      );\n    }\n\n    return this.tokenizeInternal(text, initialMode);\n  }\n\n  // There is quite a bit of duplication between this and \"tokenizeInternalLazy\"\n  // This is intentional due to performance considerations.\n  // this method also used quite a bit of `!` none null assertions because it is too optimized\n  // for `tsc` to always understand it is \"safe\"\n  private tokenizeInternal(text: string, initialMode: string): ILexingResult {\n    let i,\n      j,\n      k,\n      matchAltImage,\n      longerAlt,\n      matchedImage: string | null,\n      payload,\n      altPayload,\n      imageLength,\n      group,\n      tokType,\n      newToken: IToken,\n      errLength,\n      msg,\n      match;\n    const orgText = text;\n    const orgLength = orgText.length;\n    let offset = 0;\n    let matchedTokensIndex = 0;\n    // initializing the tokensArray to the \"guessed\" size.\n    // guessing too little will still reduce the number of array re-sizes on pushes.\n    // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory\n    // but would still have a faster runtime by avoiding (All but one) array resizing.\n    const guessedNumberOfTokens = this.hasCustom\n      ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.\n      : Math.floor(text.length / 10);\n    const matchedTokens = new Array(guessedNumberOfTokens);\n    const errors: ILexingError[] = [];\n    let line = this.trackStartLines ? 1 : undefined;\n    let column = this.trackStartLines ? 1 : undefined;\n    const groups: { [groupName: string]: IToken[] } = {};\n    // fast clone implementation for the empty Groups.\n    // provides a slight ~1% performance boost\n    for (let gi = 0; gi < this.cachedGroupKeys.length; gi++) {\n      groups[this.cachedGroupKeys[gi]] = [];\n    }\n    const trackLines = this.trackStartLines;\n    const lineTerminatorPattern = this.config.lineTerminatorsPattern;\n\n    let currModePatternsLength = 0;\n    let patternIdxToConfig: IPatternConfig[] = [];\n    let currCharCodeToPatternIdxToConfig: {\n      [charCode: number]: IPatternConfig[];\n    } = [];\n\n    const modeStack: string[] = [];\n\n    const emptyArray: IPatternConfig[] = [];\n    Object.freeze(emptyArray);\n    let isOptimizedMode = false;\n\n    const pop_mode = (popToken: IToken) => {\n      // TODO: perhaps avoid this error in the edge case there is no more input?\n      if (\n        modeStack.length === 1 &&\n        // if we have both a POP_MODE and a PUSH_MODE this is in-fact a \"transition\"\n        // So no error should occur.\n        popToken.tokenType.PUSH_MODE === undefined\n      ) {\n        // if we try to pop the last mode there lexer will no longer have ANY mode.\n        // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode.\n        const msg =\n          this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(\n            popToken,\n          );\n\n        errors.push({\n          offset: popToken.startOffset,\n          line: popToken.startLine,\n          column: popToken.startColumn,\n          length: popToken.image.length,\n          message: msg,\n        });\n      } else {\n        modeStack.pop();\n        const newMode = modeStack.at(-1)!;\n        patternIdxToConfig = this.patternIdxToConfig[newMode];\n        currCharCodeToPatternIdxToConfig =\n          this.charCodeToPatternIdxToConfig[newMode];\n        currModePatternsLength = patternIdxToConfig.length;\n        const modeCanBeOptimized =\n          this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n        if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n          isOptimizedMode = true;\n        } else {\n          isOptimizedMode = false;\n        }\n      }\n    };\n\n    function push_mode(this: Lexer, newMode: string) {\n      modeStack.push(newMode);\n      currCharCodeToPatternIdxToConfig =\n        this.charCodeToPatternIdxToConfig[newMode];\n\n      patternIdxToConfig = this.patternIdxToConfig[newMode];\n      currModePatternsLength = patternIdxToConfig.length;\n      const modeCanBeOptimized =\n        this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n      if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n        isOptimizedMode = true;\n      } else {\n        isOptimizedMode = false;\n      }\n    }\n\n    // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not\n    // seem to matter performance wise.\n    push_mode.call(this, initialMode);\n\n    let currConfig!: IPatternConfig;\n\n    const recoveryEnabled = this.config.recoveryEnabled;\n\n    while (offset < orgLength) {\n      matchedImage = null;\n      imageLength = -1;\n\n      const nextCharCode = orgText.charCodeAt(offset);\n      let chosenPatternIdxToConfig: IPatternConfig[];\n      if (isOptimizedMode) {\n        const optimizedCharIdx = charCodeToOptimizedIndex(nextCharCode);\n        const possiblePatterns =\n          currCharCodeToPatternIdxToConfig[optimizedCharIdx];\n        chosenPatternIdxToConfig =\n          possiblePatterns !== undefined ? possiblePatterns : emptyArray;\n      } else {\n        chosenPatternIdxToConfig = patternIdxToConfig;\n      }\n      const chosenPatternsLength = chosenPatternIdxToConfig.length;\n\n      for (i = 0; i < chosenPatternsLength; i++) {\n        currConfig = chosenPatternIdxToConfig[i];\n        const currPattern = currConfig.pattern;\n        payload = null;\n\n        // manually in-lined because > 600 chars won't be in-lined in V8\n        switch (currConfig.matchType) {\n          case SINGLE_CHAR_MATCH:\n            if (nextCharCode === currConfig.short) {\n              // single character string\n              imageLength = 1;\n              matchedImage = currPattern as string;\n            }\n            break;\n          case CUSTOM_MATCH:\n            match = (currPattern as IRegExpExec).exec(\n              orgText,\n              offset,\n              matchedTokens,\n              groups,\n            );\n            if (match !== null) {\n              matchedImage = match[0];\n              imageLength = matchedImage.length;\n              if ((match as CustomPatternMatcherReturn).payload !== undefined) {\n                payload = (match as CustomPatternMatcherReturn).payload;\n              }\n            } else {\n              matchedImage = null;\n            }\n            break;\n          case ASCII_CLASS_MATCH: {\n            const asciiClass = currConfig.asciiClass!;\n            if (asciiClass[nextCharCode] !== 1) {\n              (currPattern as RegExp).lastIndex = 0;\n              break;\n            }\n            let endOffset = offset + 1;\n            while (asciiClass[orgText.charCodeAt(endOffset)] === 1) {\n              endOffset++;\n            }\n            imageLength = endOffset - offset;\n            (currPattern as RegExp).lastIndex = endOffset;\n            break;\n          }\n          case REG_EXP_MATCH:\n            (currPattern as RegExp).lastIndex = offset;\n            imageLength = this.matchLength(currPattern as RegExp, text, offset);\n            break;\n        }\n\n        // longer alts handling\n        if (imageLength !== -1) {\n          // even though this pattern matched we must try a another longer alternative.\n          // this can be used to prioritize keywords over identifiers\n          longerAlt = currConfig.longerAlt;\n          if (longerAlt !== undefined) {\n            matchedImage = text.substring(offset, offset + imageLength);\n            const longerAltLength = longerAlt.length;\n            for (k = 0; k < longerAltLength; k++) {\n              const longerAltConfig = patternIdxToConfig[longerAlt[k]];\n              const longerAltPattern = longerAltConfig.pattern;\n              altPayload = null;\n\n              // single Char can never be a longer alt so no need to test it.\n              // manually in-lined because > 600 chars won't be in-lined in V8\n              if (longerAltConfig.matchType === CUSTOM_MATCH) {\n                match = (longerAltPattern as IRegExpExec).exec(\n                  orgText,\n                  offset,\n                  matchedTokens,\n                  groups,\n                );\n                if (match !== null) {\n                  matchAltImage = match[0];\n                  if (\n                    (match as CustomPatternMatcherReturn).payload !== undefined\n                  ) {\n                    altPayload = (match as CustomPatternMatcherReturn).payload;\n                  }\n                } else {\n                  matchAltImage = null;\n                }\n              } else {\n                (longerAltPattern as RegExp).lastIndex = offset;\n                matchAltImage = this.match(\n                  longerAltPattern as RegExp,\n                  text,\n                  offset,\n                );\n              }\n\n              if (matchAltImage && matchAltImage.length > matchedImage.length) {\n                matchedImage = matchAltImage;\n                imageLength = matchAltImage.length;\n                payload = altPayload;\n                currConfig = longerAltConfig;\n                // Exit the loop early after matching one of the longer alternatives\n                // The first matched alternative takes precedence\n                break;\n              }\n            }\n          }\n          break;\n        }\n      }\n\n      // successful match\n      if (imageLength !== -1) {\n        group = currConfig.group;\n        if (group !== undefined) {\n          matchedImage =\n            matchedImage !== null\n              ? matchedImage // for custom Tokens we will already have the `matchedImage`\n              : text.substring(offset, offset + imageLength);\n          tokType = currConfig.tokenTypeIdx;\n          newToken = this.createTokenInstance(\n            matchedImage,\n            offset,\n            tokType,\n            currConfig.tokenType,\n            line,\n            column,\n            imageLength,\n          );\n\n          this.handlePayload(newToken, payload);\n\n          if (group === false) {\n            matchedTokensIndex = this.addToken(\n              matchedTokens,\n              matchedTokensIndex,\n              newToken,\n            );\n          } else {\n            groups[group].push(newToken);\n          }\n        }\n\n        // line terminator handling\n        if (trackLines === true && currConfig.canLineTerminator === true) {\n          let numOfLTsInMatch = 0;\n          let foundTerminator;\n          let lastLTEndOffset: number;\n          lineTerminatorPattern.lastIndex = 0;\n          do {\n            // only for skipped tokens the matchedImage may be null at this point\n            matchedImage =\n              matchedImage !== null\n                ? matchedImage\n                : text.substring(offset, offset + imageLength);\n            foundTerminator = lineTerminatorPattern.test(matchedImage);\n            if (foundTerminator === true) {\n              lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;\n              numOfLTsInMatch++;\n            }\n          } while (foundTerminator === true);\n\n          if (numOfLTsInMatch !== 0) {\n            line = line! + numOfLTsInMatch;\n            column = imageLength - lastLTEndOffset!;\n            this.updateTokenEndLineColumnLocation(\n              newToken!,\n              group!,\n              lastLTEndOffset!,\n              numOfLTsInMatch,\n              line,\n              column,\n              imageLength,\n            );\n          } else {\n            column = this.computeNewColumn(column!, imageLength);\n          }\n        } else {\n          column = this.computeNewColumn(column!, imageLength);\n        }\n\n        offset = offset + imageLength;\n\n        // will be NOOP if no modes present\n        this.handleModes(currConfig, pop_mode, push_mode, newToken!);\n      } else {\n        // error recovery, drop characters until we identify a valid token's start point\n        const errorStartOffset = offset;\n        const errorLine = line;\n        const errorColumn = column;\n        let foundResyncPoint = recoveryEnabled === false;\n\n        while (foundResyncPoint === false && offset < orgLength) {\n          offset++;\n          for (j = 0; j < currModePatternsLength; j++) {\n            const currConfig = patternIdxToConfig[j];\n            const currPattern = currConfig.pattern;\n\n            // manually in-lined because > 600 chars won't be in-lined in V8\n            switch (currConfig.matchType) {\n              case SINGLE_CHAR_MATCH:\n                if (orgText.charCodeAt(offset) === currConfig.short) {\n                  // single character string\n                  foundResyncPoint = true;\n                }\n                break;\n              case CUSTOM_MATCH:\n                foundResyncPoint =\n                  (currPattern as IRegExpExec).exec(\n                    orgText,\n                    offset,\n                    matchedTokens,\n                    groups,\n                  ) !== null;\n                break;\n              case ASCII_CLASS_MATCH:\n              case REG_EXP_MATCH:\n                (currPattern as RegExp).lastIndex = offset;\n                foundResyncPoint = (currPattern as RegExp).exec(text) !== null;\n                break;\n            }\n\n            if (foundResyncPoint === true) {\n              break;\n            }\n          }\n        }\n\n        errLength = offset - errorStartOffset;\n        column = this.computeNewColumn(column!, errLength);\n        // at this point we either re-synced or reached the end of the input text\n        msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(\n          orgText,\n          errorStartOffset,\n          errLength,\n          errorLine,\n          errorColumn,\n          modeStack.at(-1),\n        );\n        errors.push({\n          offset: errorStartOffset,\n          line: errorLine,\n          column: errorColumn,\n          length: errLength,\n          message: msg,\n        });\n\n        if (recoveryEnabled === false) {\n          break;\n        }\n      }\n    }\n\n    // if we do have custom patterns which push directly into the\n    // TODO: custom tokens should not push directly??\n    if (!this.hasCustom) {\n      // if we guessed a too large size for the tokens array this will shrink it to the right size.\n      matchedTokens.length = matchedTokensIndex;\n    }\n\n    return {\n      tokens: matchedTokens,\n      groups: groups,\n      errors: errors,\n    };\n  }\n\n  private handleModes(\n    config: IPatternConfig,\n    pop_mode: (tok: IToken) => void,\n    push_mode: (this: Lexer, pushMode: string) => void,\n    newToken: IToken,\n  ) {\n    if (config.pop === true) {\n      // need to save the PUSH_MODE property as if the mode is popped\n      // patternIdxToPopMode is updated to reflect the new mode after popping the stack\n      const pushMode = config.push;\n      pop_mode(newToken);\n      if (pushMode !== undefined) {\n        push_mode.call(this, pushMode);\n      }\n    } else if (config.push !== undefined) {\n      push_mode.call(this, config.push);\n    }\n  }\n\n  // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler\n  private updateTokenEndLineColumnLocation(\n    newToken: IToken,\n    group: string | false,\n    lastLTIdx: number,\n    numOfLTsInMatch: number,\n    line: number,\n    column: number,\n    imageLength: number,\n  ): void {\n    let lastCharIsLT, fixForEndingInLT;\n    if (group !== undefined) {\n      // a none skipped multi line Token, need to update endLine/endColumn\n      lastCharIsLT = lastLTIdx === imageLength - 1;\n      fixForEndingInLT = lastCharIsLT ? -1 : 0;\n      if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {\n        // if a token ends in a LT that last LT only affects the line numbering of following Tokens\n        newToken.endLine = line + fixForEndingInLT;\n        // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)\n        // inclusive to exclusive range.\n        newToken.endColumn = column - 1 + -fixForEndingInLT;\n      }\n      // else single LT in the last character of a token, no need to modify the endLine/EndColumn\n    }\n  }\n\n  private computeNewColumn(oldColumn: number, imageLength: number) {\n    return oldColumn + imageLength;\n  }\n\n  // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n  /* istanbul ignore next - place holder */\n  private createTokenInstance!: (...args: any[]) => IToken;\n\n  private createOffsetOnlyToken(\n    image: string,\n    startOffset: number,\n    tokenTypeIdx: number,\n    tokenType: TokenType,\n  ): IToken {\n    return {\n      image,\n      startOffset,\n      tokenTypeIdx,\n      tokenType,\n    };\n  }\n\n  private createStartOnlyToken(\n    image: string,\n    startOffset: number,\n    tokenTypeIdx: number,\n    tokenType: TokenType,\n    startLine: number,\n    startColumn: number,\n  ): IToken {\n    return {\n      image,\n      startOffset,\n      startLine,\n      startColumn,\n      tokenTypeIdx,\n      tokenType,\n    };\n  }\n\n  private createFullToken(\n    image: string,\n    startOffset: number,\n    tokenTypeIdx: number,\n    tokenType: TokenType,\n    startLine: number,\n    startColumn: number,\n    imageLength: number,\n  ): IToken {\n    return {\n      image,\n      startOffset,\n      endOffset: startOffset + imageLength - 1,\n      startLine,\n      endLine: startLine,\n      startColumn,\n      endColumn: startColumn + imageLength - 1,\n      tokenTypeIdx,\n      tokenType,\n    };\n  }\n\n  // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n  /* istanbul ignore next - place holder */\n  private addToken!: (\n    tokenVector: IToken[],\n    index: number,\n    tokenToAdd: IToken,\n  ) => number;\n\n  private addTokenUsingPush(\n    tokenVector: IToken[],\n    index: number,\n    tokenToAdd: IToken,\n  ): number {\n    tokenVector.push(tokenToAdd);\n    return index;\n  }\n\n  private addTokenUsingMemberAccess(\n    tokenVector: IToken[],\n    index: number,\n    tokenToAdd: IToken,\n  ): number {\n    tokenVector[index] = tokenToAdd;\n    index++;\n    return index;\n  }\n\n  // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.\n  private handlePayload: (token: IToken, payload: any) => void;\n\n  private handlePayloadNoCustom(token: IToken, payload: any): void {}\n\n  private handlePayloadWithCustom(token: IToken, payload: any): void {\n    if (payload !== null) {\n      token.payload = payload;\n    }\n  }\n\n  private match(pattern: RegExp, text: string, offset: number): string | null {\n    const found = pattern.test(text);\n    if (found === true) {\n      return text.substring(offset, pattern.lastIndex);\n    }\n    return null;\n  }\n\n  private matchLength(\n    pattern: RegExp,\n    text: string,\n    offset: number,\n  ): number | -1 {\n    const found = pattern.test(text);\n    if (found === true) {\n      return pattern.lastIndex - offset;\n    }\n    return -1;\n  }\n\n  // Duplicated from the parser's perf trace trait to allow future extraction\n  // of the lexer to a separate package.\n  TRACE_INIT = <T>(phaseDesc: string, phaseImpl: () => T): T => {\n    // No need to optimize this using NOOP pattern because\n    // It is not called in a hot spot...\n    if (this.traceInitPerf === true) {\n      this.traceInitIndent++;\n      const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n      if (this.traceInitIndent < this.traceInitMaxIdent) {\n        console.log(`${indent}--> <${phaseDesc}>`);\n      }\n      const { time, value } = timer(phaseImpl);\n      /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n      const traceMethod = time > 10 ? console.warn : console.log;\n      if (this.traceInitIndent < this.traceInitMaxIdent) {\n        traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n      }\n      this.traceInitIndent--;\n      return value;\n    } else {\n      return phaseImpl();\n    }\n  };\n}\n", "import { Lexer } from \"./lexer_public.js\";\nimport { augmentTokenTypes, tokenStructuredMatcher } from \"./tokens.js\";\nimport { IToken, ITokenConfig, TokenType } from \"@chevrotain/types\";\n\nexport function tokenLabel(tokType: TokenType): string {\n  if (hasTokenLabel(tokType)) {\n    return tokType.LABEL;\n  } else {\n    return tokType.name;\n  }\n}\n\nexport function tokenName(tokType: TokenType): string {\n  return tokType.name;\n}\n\nexport function hasTokenLabel(\n  obj: TokenType,\n): obj is TokenType & Pick<Required<TokenType>, \"LABEL\"> {\n  return typeof obj.LABEL === \"string\" && obj.LABEL !== \"\";\n}\n\nconst PARENT = \"parent\";\nconst CATEGORIES = \"categories\";\nconst LABEL = \"label\";\nconst GROUP = \"group\";\nconst PUSH_MODE = \"push_mode\";\nconst POP_MODE = \"pop_mode\";\nconst LONGER_ALT = \"longer_alt\";\nconst LINE_BREAKS = \"line_breaks\";\nconst START_CHARS_HINT = \"start_chars_hint\";\n\nexport function createToken(config: ITokenConfig): TokenType {\n  return createTokenInternal(config);\n}\n\nfunction createTokenInternal(config: ITokenConfig): TokenType {\n  const pattern = config.pattern;\n\n  const tokenType: TokenType = <any>{};\n  tokenType.name = config.name;\n\n  if (pattern !== undefined) {\n    tokenType.PATTERN = pattern;\n  }\n\n  if (Object.hasOwn(config, PARENT)) {\n    throw (\n      \"The parent property is no longer supported.\\n\" +\n      \"See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.\"\n    );\n  }\n\n  if (Object.hasOwn(config, CATEGORIES)) {\n    // casting to ANY as this will be fixed inside `augmentTokenTypes``\n    tokenType.CATEGORIES = <any>config[CATEGORIES];\n  }\n\n  augmentTokenTypes([tokenType]);\n\n  if (Object.hasOwn(config, LABEL)) {\n    tokenType.LABEL = config[LABEL];\n  }\n\n  if (Object.hasOwn(config, GROUP)) {\n    tokenType.GROUP = config[GROUP];\n  }\n\n  if (Object.hasOwn(config, POP_MODE)) {\n    tokenType.POP_MODE = config[POP_MODE];\n  }\n\n  if (Object.hasOwn(config, PUSH_MODE)) {\n    tokenType.PUSH_MODE = config[PUSH_MODE];\n  }\n\n  if (Object.hasOwn(config, LONGER_ALT)) {\n    tokenType.LONGER_ALT = config[LONGER_ALT];\n  }\n\n  if (Object.hasOwn(config, LINE_BREAKS)) {\n    tokenType.LINE_BREAKS = config[LINE_BREAKS];\n  }\n\n  if (Object.hasOwn(config, START_CHARS_HINT)) {\n    tokenType.START_CHARS_HINT = config[START_CHARS_HINT];\n  }\n\n  return tokenType;\n}\n\nexport const EOF = createToken({ name: \"EOF\", pattern: Lexer.NA });\naugmentTokenTypes([EOF]);\n\nexport function createTokenInstance(\n  tokType: TokenType,\n  image: string,\n  startOffset: number,\n  endOffset: number,\n  startLine: number,\n  endLine: number,\n  startColumn: number,\n  endColumn: number,\n): IToken {\n  return {\n    image,\n    startOffset,\n    endOffset,\n    startLine,\n    endLine,\n    startColumn,\n    endColumn,\n    tokenTypeIdx: (<any>tokType).tokenTypeIdx,\n    tokenType: tokType,\n  };\n}\n\nexport function tokenMatcher(token: IToken, tokType: TokenType): boolean {\n  return tokenStructuredMatcher(token, tokType);\n}\n", "import { hasTokenLabel, tokenLabel } from \"../scan/tokens_public.js\";\nimport {\n  Alternation,\n  getProductionDslName,\n  NonTerminal,\n  Rule,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport {\n  IParserErrorMessageProvider,\n  IProductionWithOccurrence,\n  TokenType,\n} from \"@chevrotain/types\";\nimport {\n  IGrammarResolverErrorMessageProvider,\n  IGrammarValidatorErrorMessageProvider,\n} from \"./grammar/types.js\";\n\nexport const defaultParserErrorProvider: IParserErrorMessageProvider = {\n  buildMismatchTokenMessage({ expected, actual, previous, ruleName }): string {\n    const hasLabel = hasTokenLabel(expected);\n    const expectedMsg = hasLabel\n      ? `--> ${tokenLabel(expected)} <--`\n      : `token of type --> ${expected.name} <--`;\n\n    const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`;\n\n    return msg;\n  },\n\n  buildNotAllInputParsedMessage({ firstRedundant, ruleName }): string {\n    return \"Redundant input, expecting EOF but found: \" + firstRedundant.image;\n  },\n\n  buildNoViableAltMessage({\n    expectedPathsPerAlt,\n    actual,\n    previous,\n    customUserDescription,\n    ruleName,\n  }): string {\n    const errPrefix = \"Expecting: \";\n    // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n    const actualText = actual[0]!.image;\n    const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n    if (customUserDescription) {\n      return errPrefix + customUserDescription + errSuffix;\n    } else {\n      const allLookAheadPaths = expectedPathsPerAlt.reduce(\n        (result, currAltPaths) => result.concat(currAltPaths),\n        [] as TokenType[][],\n      );\n      const nextValidTokenSequences = allLookAheadPaths.map(\n        (currPath) =>\n          `[${currPath\n            .map((currTokenType) => tokenLabel(currTokenType))\n            .join(\", \")}]`,\n      );\n      const nextValidSequenceItems = nextValidTokenSequences.map(\n        (itemMsg, idx) => `  ${idx + 1}. ${itemMsg}`,\n      );\n      const calculatedDescription = `one of these possible Token sequences:\\n${nextValidSequenceItems.join(\n        \"\\n\",\n      )}`;\n\n      return errPrefix + calculatedDescription + errSuffix;\n    }\n  },\n\n  buildEarlyExitMessage({\n    expectedIterationPaths,\n    actual,\n    customUserDescription,\n    ruleName,\n  }): string {\n    const errPrefix = \"Expecting: \";\n    // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n    const actualText = actual[0]!.image;\n    const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n    if (customUserDescription) {\n      return errPrefix + customUserDescription + errSuffix;\n    } else {\n      const nextValidTokenSequences = expectedIterationPaths.map(\n        (currPath) =>\n          `[${currPath\n            .map((currTokenType) => tokenLabel(currTokenType))\n            .join(\",\")}]`,\n      );\n      const calculatedDescription =\n        `expecting at least one iteration which starts with one of these possible Token sequences::\\n  ` +\n        `<${nextValidTokenSequences.join(\" ,\")}>`;\n\n      return errPrefix + calculatedDescription + errSuffix;\n    }\n  },\n};\n\nObject.freeze(defaultParserErrorProvider);\n\nexport const defaultGrammarResolverErrorProvider: IGrammarResolverErrorMessageProvider =\n  {\n    buildRuleNotFoundError(\n      topLevelRule: Rule,\n      undefinedRule: NonTerminal,\n    ): string {\n      const msg =\n        \"Invalid grammar, reference to a rule which is not defined: ->\" +\n        undefinedRule.nonTerminalName +\n        \"<-\\n\" +\n        \"inside top level rule: ->\" +\n        topLevelRule.name +\n        \"<-\";\n      return msg;\n    },\n  };\n\nexport const defaultGrammarValidatorErrorProvider: IGrammarValidatorErrorMessageProvider =\n  {\n    buildDuplicateFoundError(\n      topLevelRule: Rule,\n      duplicateProds: IProductionWithOccurrence[],\n    ): string {\n      function getExtraProductionArgument(\n        prod: IProductionWithOccurrence,\n      ): string {\n        if (prod instanceof Terminal) {\n          return prod.terminalType.name;\n        } else if (prod instanceof NonTerminal) {\n          return prod.nonTerminalName;\n        } else {\n          return \"\";\n        }\n      }\n\n      const topLevelName = topLevelRule.name;\n      const duplicateProd = duplicateProds[0]!;\n      const index = duplicateProd.idx;\n      const dslName = getProductionDslName(duplicateProd);\n      const extraArgument = getExtraProductionArgument(duplicateProd);\n\n      const hasExplicitIndex = index > 0;\n      let msg = `->${dslName}${hasExplicitIndex ? index : \"\"}<- ${\n        extraArgument ? `with argument: ->${extraArgument}<-` : \"\"\n      }\n                  appears more than once (${\n                    duplicateProds.length\n                  } times) in the top level rule: ->${topLevelName}<-.                  \n                  For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n                  `;\n\n      // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...\n      msg = msg.replace(/[ \\t]+/g, \" \");\n      msg = msg.replace(/\\s\\s+/g, \"\\n\");\n\n      return msg;\n    },\n\n    buildNamespaceConflictError(rule: Rule): string {\n      const errMsg =\n        `Namespace conflict found in grammar.\\n` +\n        `The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.\\n` +\n        `To resolve this make sure each Terminal and Non-Terminal names are unique\\n` +\n        `This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\\n` +\n        `and Non-Terminal names start with a lower case letter.`;\n\n      return errMsg;\n    },\n\n    buildAlternationPrefixAmbiguityError(options: {\n      topLevelRule: Rule;\n      prefixPath: TokenType[];\n      ambiguityIndices: number[];\n      alternation: Alternation;\n    }): string {\n      const pathMsg = options.prefixPath\n        .map((currTok) => tokenLabel(currTok))\n        .join(\", \");\n      const occurrence =\n        options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n      const errMsg =\n        `Ambiguous alternatives: <${options.ambiguityIndices.join(\n          \" ,\",\n        )}> due to common lookahead prefix\\n` +\n        `in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,\\n` +\n        `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n` +\n        `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\\n` +\n        `For Further details.`;\n\n      return errMsg;\n    },\n\n    buildAlternationAmbiguityError(options: {\n      topLevelRule: Rule;\n      prefixPath: TokenType[];\n      ambiguityIndices: number[];\n      alternation: Alternation;\n    }): string {\n      const occurrence =\n        options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n\n      const isEmptyPath = options.prefixPath.length === 0;\n\n      let currMessage =\n        `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(\n          \" ,\",\n        )}> in <OR${occurrence}>` +\n        ` inside <${options.topLevelRule.name}> Rule,\\n`;\n\n      if (isEmptyPath) {\n        currMessage +=\n          `These alternatives are all empty (match no tokens), making them indistinguishable.\\n` +\n          `Only the last alternative may be empty.\\n`;\n      } else {\n        const pathMsg = options.prefixPath\n          .map((currtok) => tokenLabel(currtok))\n          .join(\", \");\n        currMessage += `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n`;\n      }\n\n      currMessage +=\n        `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\\n` +\n        `For Further details.`;\n      return currMessage;\n    },\n\n    buildEmptyRepetitionError(options: {\n      topLevelRule: Rule;\n      repetition: IProductionWithOccurrence;\n    }): string {\n      let dslName = getProductionDslName(options.repetition);\n      if (options.repetition.idx !== 0) {\n        dslName += options.repetition.idx;\n      }\n\n      const errMsg =\n        `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.\\n` +\n        `This could lead to an infinite loop.`;\n\n      return errMsg;\n    },\n\n    // TODO: remove - `errors_public` from nyc.config.js exclude\n    //       once this method is fully removed from this file\n    buildTokenNameError(options: {\n      tokenType: TokenType;\n      expectedPattern: RegExp;\n    }): string {\n      /* istanbul ignore next */\n      return \"deprecated\";\n    },\n\n    buildEmptyAlternationError(options: {\n      topLevelRule: Rule;\n      alternation: Alternation;\n      emptyChoiceIdx: number;\n    }): string {\n      const errMsg =\n        `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}>` +\n        ` in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.\\n` +\n        `Only the last alternative may be an empty alternative.`;\n\n      return errMsg;\n    },\n\n    buildTooManyAlternativesError(options: {\n      topLevelRule: Rule;\n      alternation: Alternation;\n    }): string {\n      const errMsg =\n        `An Alternation cannot have more than 256 alternatives:\\n` +\n        `<OR${options.alternation.idx}> inside <${\n          options.topLevelRule.name\n        }> Rule.\\n has ${\n          options.alternation.definition.length + 1\n        } alternatives.`;\n\n      return errMsg;\n    },\n\n    buildLeftRecursionError(options: {\n      topLevelRule: Rule;\n      leftRecursionPath: Rule[];\n    }): string {\n      const ruleName = options.topLevelRule.name;\n      const pathNames = options.leftRecursionPath.map(\n        (currRule) => currRule.name,\n      );\n      const leftRecursivePath = `${ruleName} --> ${pathNames\n        .concat([ruleName])\n        .join(\" --> \")}`;\n      const errMsg =\n        `Left Recursion found in grammar.\\n` +\n        `rule: <${ruleName}> can be invoked from itself (directly or indirectly)\\n` +\n        `without consuming any Tokens. The grammar path that causes this is: \\n ${leftRecursivePath}\\n` +\n        ` To fix this refactor your grammar to remove the left recursion.\\n` +\n        `see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;\n\n      return errMsg;\n    },\n\n    // TODO: remove - `errors_public` from nyc.config.js exclude\n    //       once this method is fully removed from this file\n    buildInvalidRuleNameError(options: {\n      topLevelRule: Rule;\n      expectedPattern: RegExp;\n    }): string {\n      /* istanbul ignore next */\n      return \"deprecated\";\n    },\n\n    buildDuplicateRuleNameError(options: {\n      topLevelRule: Rule | string;\n      grammarName: string;\n    }): string {\n      let ruleName;\n      if (options.topLevelRule instanceof Rule) {\n        ruleName = options.topLevelRule.name;\n      } else {\n        ruleName = options.topLevelRule;\n      }\n\n      const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`;\n\n      return errMsg;\n    },\n  };\n", "import {\n  IParserUnresolvedRefDefinitionError,\n  ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport { GAstVisitor, NonTerminal, Rule } from \"@chevrotain/gast\";\nimport {\n  IGrammarResolverErrorMessageProvider,\n  IParserDefinitionError,\n} from \"./types.js\";\n\nexport function resolveGrammar(\n  topLevels: Record<string, Rule>,\n  errMsgProvider: IGrammarResolverErrorMessageProvider,\n): IParserDefinitionError[] {\n  const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);\n  refResolver.resolveRefs();\n  return refResolver.errors;\n}\n\nexport class GastRefResolverVisitor extends GAstVisitor {\n  public errors: IParserUnresolvedRefDefinitionError[] = [];\n  private currTopLevel: Rule;\n\n  constructor(\n    private nameToTopRule: Record<string, Rule>,\n    private errMsgProvider: IGrammarResolverErrorMessageProvider,\n  ) {\n    super();\n  }\n\n  public resolveRefs(): void {\n    Object.values(this.nameToTopRule).forEach((prod) => {\n      this.currTopLevel = prod;\n      prod.accept(this);\n    });\n  }\n\n  public visitNonTerminal(node: NonTerminal): void {\n    const ref = this.nameToTopRule[node.nonTerminalName];\n\n    if (!ref) {\n      const msg = this.errMsgProvider.buildRuleNotFoundError(\n        this.currTopLevel,\n        node,\n      );\n      this.errors.push({\n        message: msg,\n        type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,\n        ruleName: this.currTopLevel.name,\n        unresolvedRefName: node.nonTerminalName,\n      });\n    } else {\n      node.referencedRule = ref;\n    }\n  }\n}\n", "import { first } from \"./first.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { TokenMatcher } from \"../parser/parser.js\";\nimport {\n  Alternation,\n  Alternative,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Rule,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport {\n  IGrammarPath,\n  IProduction,\n  IToken,\n  ITokenGrammarPath,\n  TokenType,\n} from \"@chevrotain/types\";\n\nexport interface INextTokenPath extends IGrammarPath {\n  nextTokenType: TokenType;\n  nextTokenOccurrence: number;\n}\n\nexport abstract class AbstractNextPossibleTokensWalker extends RestWalker {\n  protected possibleTokTypes: TokenType[] = [];\n  protected ruleStack: string[];\n  protected occurrenceStack: number[];\n\n  protected nextProductionName = \"\";\n  protected nextProductionOccurrence = 0;\n  protected found = false;\n  protected isAtEndOfPath = false;\n\n  constructor(\n    protected topProd: Rule,\n    protected path: IGrammarPath,\n  ) {\n    super();\n  }\n\n  startWalking(): TokenType[] {\n    this.found = false;\n\n    if (this.path.ruleStack[0] !== this.topProd.name) {\n      throw Error(\"The path does not start with the walker's top Rule!\");\n    }\n\n    // immutable for the win\n    this.ruleStack = [...this.path.ruleStack].reverse(); // intelij bug requires assertion\n    this.occurrenceStack = [...this.path.occurrenceStack].reverse(); // intelij bug requires assertion\n\n    // already verified that the first production is valid, we now seek the 2nd production\n    this.ruleStack.pop();\n    this.occurrenceStack.pop();\n\n    this.updateExpectedNext();\n    this.walk(this.topProd);\n\n    return this.possibleTokTypes;\n  }\n\n  walk(\n    prod: { definition: IProduction[] },\n    prevRest: IProduction[] = [],\n  ): void {\n    // stop scanning once we found the path\n    if (!this.found) {\n      super.walk(prod, prevRest);\n    }\n  }\n\n  walkProdRef(\n    refProd: NonTerminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    // found the next production, need to keep walking in it\n    if (\n      refProd.referencedRule.name === this.nextProductionName &&\n      refProd.idx === this.nextProductionOccurrence\n    ) {\n      const fullRest = currRest.concat(prevRest);\n      this.updateExpectedNext();\n      this.walk(refProd.referencedRule, <any>fullRest);\n    }\n  }\n\n  updateExpectedNext(): void {\n    // need to consume the Terminal\n    if (this.ruleStack.length === 0) {\n      // must reset nextProductionXXX to avoid walking down another Top Level production while what we are\n      // really seeking is the last Terminal...\n      this.nextProductionName = \"\";\n      this.nextProductionOccurrence = 0;\n      this.isAtEndOfPath = true;\n    } else {\n      this.nextProductionName = this.ruleStack.pop()!;\n      this.nextProductionOccurrence = this.occurrenceStack.pop()!;\n    }\n  }\n}\n\nexport class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker {\n  private nextTerminalName = \"\";\n  private nextTerminalOccurrence = 0;\n\n  constructor(\n    topProd: Rule,\n    protected path: ITokenGrammarPath,\n  ) {\n    super(topProd, path);\n    this.nextTerminalName = this.path.lastTok.name;\n    this.nextTerminalOccurrence = this.path.lastTokOccurrence;\n  }\n\n  walkTerminal(\n    terminal: Terminal,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (\n      this.isAtEndOfPath &&\n      terminal.terminalType.name === this.nextTerminalName &&\n      terminal.idx === this.nextTerminalOccurrence &&\n      !this.found\n    ) {\n      const fullRest = currRest.concat(prevRest);\n      const restProd = new Alternative({ definition: fullRest });\n      this.possibleTokTypes = first(restProd);\n      this.found = true;\n    }\n  }\n}\n\nexport type AlternativesFirstTokens = TokenType[][];\n\nexport interface IFirstAfterRepetition {\n  token: TokenType | undefined;\n  occurrence: number | undefined;\n  isEndOfRule: boolean | undefined;\n}\n\n/**\n * This walker only \"walks\" a single \"TOP\" level in the Grammar Ast, this means\n * it never \"follows\" production refs\n */\nexport class AbstractNextTerminalAfterProductionWalker extends RestWalker {\n  protected result: IFirstAfterRepetition = {\n    token: undefined,\n    occurrence: undefined,\n    isEndOfRule: undefined,\n  };\n\n  constructor(\n    protected topRule: Rule,\n    protected occurrence: number,\n  ) {\n    super();\n  }\n\n  startWalking(): IFirstAfterRepetition {\n    this.walk(this.topRule);\n    return this.result;\n  }\n}\n\nexport class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker {\n  walkMany(\n    manyProd: Repetition,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (manyProd.idx === this.occurrence) {\n      const firstAfterMany = currRest.concat(prevRest)[0];\n      this.result.isEndOfRule = firstAfterMany === undefined;\n      if (firstAfterMany instanceof Terminal) {\n        this.result.token = firstAfterMany.terminalType;\n        this.result.occurrence = firstAfterMany.idx;\n      }\n    } else {\n      super.walkMany(manyProd, currRest, prevRest);\n    }\n  }\n}\n\nexport class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker {\n  walkManySep(\n    manySepProd: RepetitionWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (manySepProd.idx === this.occurrence) {\n      const firstAfterManySep = currRest.concat(prevRest)[0];\n      this.result.isEndOfRule = firstAfterManySep === undefined;\n      if (firstAfterManySep instanceof Terminal) {\n        this.result.token = firstAfterManySep.terminalType;\n        this.result.occurrence = firstAfterManySep.idx;\n      }\n    } else {\n      super.walkManySep(manySepProd, currRest, prevRest);\n    }\n  }\n}\n\nexport class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker {\n  walkAtLeastOne(\n    atLeastOneProd: RepetitionMandatory,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (atLeastOneProd.idx === this.occurrence) {\n      const firstAfterAtLeastOne = currRest.concat(prevRest)[0];\n      this.result.isEndOfRule = firstAfterAtLeastOne === undefined;\n      if (firstAfterAtLeastOne instanceof Terminal) {\n        this.result.token = firstAfterAtLeastOne.terminalType;\n        this.result.occurrence = firstAfterAtLeastOne.idx;\n      }\n    } else {\n      super.walkAtLeastOne(atLeastOneProd, currRest, prevRest);\n    }\n  }\n}\n\n// TODO: reduce code duplication in the AfterWalkers\nexport class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker {\n  walkAtLeastOneSep(\n    atleastOneSepProd: RepetitionMandatoryWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (atleastOneSepProd.idx === this.occurrence) {\n      const firstAfterfirstAfterAtLeastOneSep = currRest.concat(prevRest)[0];\n      this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined;\n      if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {\n        this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType;\n        this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;\n      }\n    } else {\n      super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest);\n    }\n  }\n}\n\nexport interface PartialPathAndSuffixes {\n  partialPath: TokenType[];\n  suffixDef: IProduction[];\n}\n\nexport function possiblePathsFrom(\n  targetDef: IProduction[],\n  maxLength: number,\n  currPath: TokenType[] = [],\n): PartialPathAndSuffixes[] {\n  // avoid side effects\n  currPath = [...currPath];\n  let result: PartialPathAndSuffixes[] = [];\n  let i = 0;\n\n  // TODO: avoid inner funcs\n  function remainingPathWith(nextDef: IProduction[]) {\n    return nextDef.concat(targetDef.slice(i + 1));\n  }\n\n  // TODO: avoid inner funcs\n  function getAlternativesForProd(definition: IProduction[]) {\n    const alternatives = possiblePathsFrom(\n      remainingPathWith(definition),\n      maxLength,\n      currPath,\n    );\n    return result.concat(alternatives);\n  }\n\n  /**\n   * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the\n   * following (rest) of the targetDef.\n   *\n   * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the\n   * the optional production.\n   */\n  while (currPath.length < maxLength && i < targetDef.length) {\n    const prod = targetDef[i];\n\n    /* istanbul ignore else */\n    if (prod instanceof Alternative) {\n      return getAlternativesForProd(prod.definition);\n    } else if (prod instanceof NonTerminal) {\n      return getAlternativesForProd(prod.definition);\n    } else if (prod instanceof Option) {\n      result = getAlternativesForProd(prod.definition);\n    } else if (prod instanceof RepetitionMandatory) {\n      const newDef = prod.definition.concat([\n        new Repetition({\n          definition: prod.definition,\n        }),\n      ]);\n      return getAlternativesForProd(newDef);\n    } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n      const newDef = [\n        new Alternative({ definition: prod.definition }),\n        new Repetition({\n          definition: [new Terminal({ terminalType: prod.separator })].concat(\n            <any>prod.definition,\n          ),\n        }),\n      ];\n      return getAlternativesForProd(newDef);\n    } else if (prod instanceof RepetitionWithSeparator) {\n      const newDef = prod.definition.concat([\n        new Repetition({\n          definition: [new Terminal({ terminalType: prod.separator })].concat(\n            <any>prod.definition,\n          ),\n        }),\n      ]);\n      result = getAlternativesForProd(newDef);\n    } else if (prod instanceof Repetition) {\n      const newDef = prod.definition.concat([\n        new Repetition({\n          definition: prod.definition,\n        }),\n      ]);\n      result = getAlternativesForProd(newDef);\n    } else if (prod instanceof Alternation) {\n      prod.definition.forEach((currAlt) => {\n        // TODO: this is a limited check for empty alternatives\n        //   It would prevent a common case of infinite loops during parser initialization.\n        //   However **in-directly** empty alternatives may still cause issues.\n        if (currAlt.definition.length !== 0) {\n          result = getAlternativesForProd(currAlt.definition);\n        }\n      });\n      return result;\n    } else if (prod instanceof Terminal) {\n      currPath.push(prod.terminalType);\n    } else {\n      throw Error(\"non exhaustive match\");\n    }\n\n    i++;\n  }\n  result.push({\n    partialPath: currPath,\n    suffixDef: targetDef.slice(i),\n  });\n\n  return result;\n}\n\ninterface IPathToExamine {\n  idx: number;\n  def: IProduction[];\n  ruleStack: string[];\n  occurrenceStack: number[];\n}\n\nexport function nextPossibleTokensAfter(\n  initialDef: IProduction[],\n  tokenVector: IToken[],\n  tokMatcher: TokenMatcher,\n  maxLookAhead: number,\n): INextTokenPath[] {\n  const EXIT_NON_TERMINAL: any = \"EXIT_NONE_TERMINAL\";\n  // to avoid creating a new Array each time.\n  const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];\n  const EXIT_ALTERNATIVE: any = \"EXIT_ALTERNATIVE\";\n  let foundCompletePath = false;\n\n  const tokenVectorLength = tokenVector.length;\n  const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;\n\n  const result: INextTokenPath[] = [];\n\n  const possiblePaths: IPathToExamine[] = [];\n  possiblePaths.push({\n    idx: -1,\n    def: initialDef,\n    ruleStack: [],\n    occurrenceStack: [],\n  });\n\n  while (possiblePaths.length !== 0) {\n    const currPath = possiblePaths.pop()!;\n\n    // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)\n    if (currPath === EXIT_ALTERNATIVE) {\n      if (\n        foundCompletePath &&\n        possiblePaths.at(-1)!.idx <= minimalAlternativesIndex\n      ) {\n        // remove irrelevant alternative\n        possiblePaths.pop();\n      }\n      continue;\n    }\n\n    const currDef = currPath.def;\n    const currIdx = currPath.idx;\n    const currRuleStack = currPath.ruleStack;\n    const currOccurrenceStack = currPath.occurrenceStack;\n\n    // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT\n    if (currDef.length === 0) {\n      continue;\n    }\n\n    const prod = currDef[0];\n    /* istanbul ignore else */\n    if (prod === EXIT_NON_TERMINAL) {\n      const nextPath = {\n        idx: currIdx,\n        def: currDef.slice(1),\n        ruleStack: currRuleStack.slice(0, -1),\n        occurrenceStack: currOccurrenceStack.slice(0, -1),\n      };\n      possiblePaths.push(nextPath);\n    } else if (prod instanceof Terminal) {\n      /* istanbul ignore else */\n      if (currIdx < tokenVectorLength - 1) {\n        const nextIdx = currIdx + 1;\n        const actualToken = tokenVector[nextIdx];\n        if (tokMatcher!(actualToken, prod.terminalType)) {\n          const nextPath = {\n            idx: nextIdx,\n            def: currDef.slice(1),\n            ruleStack: currRuleStack,\n            occurrenceStack: currOccurrenceStack,\n          };\n          possiblePaths.push(nextPath);\n        }\n        // end of the line\n      } else if (currIdx === tokenVectorLength - 1) {\n        // IGNORE ABOVE ELSE\n        result.push({\n          nextTokenType: prod.terminalType,\n          nextTokenOccurrence: prod.idx,\n          ruleStack: currRuleStack,\n          occurrenceStack: currOccurrenceStack,\n        });\n        foundCompletePath = true;\n      } else {\n        throw Error(\"non exhaustive match\");\n      }\n    } else if (prod instanceof NonTerminal) {\n      const newRuleStack = [...currRuleStack];\n      newRuleStack.push(prod.nonTerminalName);\n\n      const newOccurrenceStack = [...currOccurrenceStack];\n      newOccurrenceStack.push(prod.idx);\n\n      const nextPath = {\n        idx: currIdx,\n        def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, currDef.slice(1)),\n        ruleStack: newRuleStack,\n        occurrenceStack: newOccurrenceStack,\n      };\n      possiblePaths.push(nextPath);\n    } else if (prod instanceof Option) {\n      // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n      const nextPathWithout = {\n        idx: currIdx,\n        def: currDef.slice(1),\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWithout);\n      // required marker to avoid backtracking paths whose higher priority alternatives already matched\n      possiblePaths.push(EXIT_ALTERNATIVE);\n\n      const nextPathWith = {\n        idx: currIdx,\n        def: prod.definition.concat(currDef.slice(1)),\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWith);\n    } else if (prod instanceof RepetitionMandatory) {\n      // TODO:(THE NEW operators here take a while...) (convert once?)\n      const secondIteration = new Repetition({\n        definition: prod.definition,\n        idx: prod.idx,\n      });\n      const nextDef = prod.definition.concat(\n        [secondIteration],\n        currDef.slice(1),\n      );\n      const nextPath = {\n        idx: currIdx,\n        def: nextDef,\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPath);\n    } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n      // TODO:(THE NEW operators here take a while...) (convert once?)\n      const separatorGast = new Terminal({\n        terminalType: prod.separator,\n      });\n      const secondIteration = new Repetition({\n        definition: [<any>separatorGast].concat(prod.definition),\n        idx: prod.idx,\n      });\n      const nextDef = prod.definition.concat(\n        [secondIteration],\n        currDef.slice(1),\n      );\n      const nextPath = {\n        idx: currIdx,\n        def: nextDef,\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPath);\n    } else if (prod instanceof RepetitionWithSeparator) {\n      // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n      const nextPathWithout = {\n        idx: currIdx,\n        def: currDef.slice(1),\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWithout);\n      // required marker to avoid backtracking paths whose higher priority alternatives already matched\n      possiblePaths.push(EXIT_ALTERNATIVE);\n\n      const separatorGast = new Terminal({\n        terminalType: prod.separator,\n      });\n      const nthRepetition = new Repetition({\n        definition: [<any>separatorGast].concat(prod.definition),\n        idx: prod.idx,\n      });\n      const nextDef = prod.definition.concat([nthRepetition], currDef.slice(1));\n      const nextPathWith = {\n        idx: currIdx,\n        def: nextDef,\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWith);\n    } else if (prod instanceof Repetition) {\n      // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n      const nextPathWithout = {\n        idx: currIdx,\n        def: currDef.slice(1),\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWithout);\n      // required marker to avoid backtracking paths whose higher priority alternatives already matched\n      possiblePaths.push(EXIT_ALTERNATIVE);\n\n      // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?\n      const nthRepetition = new Repetition({\n        definition: prod.definition,\n        idx: prod.idx,\n      });\n      const nextDef = prod.definition.concat([nthRepetition], currDef.slice(1));\n      const nextPathWith = {\n        idx: currIdx,\n        def: nextDef,\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      };\n      possiblePaths.push(nextPathWith);\n    } else if (prod instanceof Alternation) {\n      // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n      for (let i = prod.definition.length - 1; i >= 0; i--) {\n        const currAlt: any = prod.definition[i];\n        const currAltPath = {\n          idx: currIdx,\n          def: currAlt.definition.concat(currDef.slice(1)),\n          ruleStack: currRuleStack,\n          occurrenceStack: currOccurrenceStack,\n        };\n        possiblePaths.push(currAltPath);\n        possiblePaths.push(EXIT_ALTERNATIVE);\n      }\n    } else if (prod instanceof Alternative) {\n      possiblePaths.push({\n        idx: currIdx,\n        def: prod.definition.concat(currDef.slice(1)),\n        ruleStack: currRuleStack,\n        occurrenceStack: currOccurrenceStack,\n      });\n    } else if (prod instanceof Rule) {\n      // last because we should only encounter at most a single one of these per invocation.\n      possiblePaths.push(\n        expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack),\n      );\n    } else {\n      throw Error(\"non exhaustive match\");\n    }\n  }\n  return result;\n}\n\nfunction expandTopLevelRule(\n  topRule: Rule,\n  currIdx: number,\n  currRuleStack: string[],\n  currOccurrenceStack: number[],\n): IPathToExamine {\n  const newRuleStack = [...currRuleStack];\n  newRuleStack.push(topRule.name);\n\n  const newCurrOccurrenceStack = [...currOccurrenceStack];\n  // top rule is always assumed to have been called with occurrence index 1\n  newCurrOccurrenceStack.push(1);\n\n  return {\n    idx: currIdx,\n    def: topRule.definition,\n    ruleStack: newRuleStack,\n    occurrenceStack: newCurrOccurrenceStack,\n  };\n}\n", "import { possiblePathsFrom } from \"./interpreter.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { Predicate, TokenMatcher } from \"../parser/parser.js\";\nimport {\n  tokenStructuredMatcher,\n  tokenStructuredMatcherNoCategories,\n} from \"../../scan/tokens.js\";\nimport {\n  Alternation,\n  Alternative as AlternativeGAST,\n  GAstVisitor,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n} from \"@chevrotain/gast\";\nimport {\n  BaseParser,\n  IOrAlt,\n  IProduction,\n  IProductionWithOccurrence,\n  LookaheadProductionType,\n  LookaheadSequence,\n  Rule,\n  TokenType,\n} from \"@chevrotain/types\";\n\nexport enum PROD_TYPE {\n  OPTION,\n  REPETITION,\n  REPETITION_MANDATORY,\n  REPETITION_MANDATORY_WITH_SEPARATOR,\n  REPETITION_WITH_SEPARATOR,\n  ALTERNATION,\n}\n\nexport function getProdType(\n  prod: IProduction | LookaheadProductionType,\n): PROD_TYPE {\n  /* istanbul ignore else */\n  if (prod instanceof Option || prod === \"Option\") {\n    return PROD_TYPE.OPTION;\n  } else if (prod instanceof Repetition || prod === \"Repetition\") {\n    return PROD_TYPE.REPETITION;\n  } else if (\n    prod instanceof RepetitionMandatory ||\n    prod === \"RepetitionMandatory\"\n  ) {\n    return PROD_TYPE.REPETITION_MANDATORY;\n  } else if (\n    prod instanceof RepetitionMandatoryWithSeparator ||\n    prod === \"RepetitionMandatoryWithSeparator\"\n  ) {\n    return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;\n  } else if (\n    prod instanceof RepetitionWithSeparator ||\n    prod === \"RepetitionWithSeparator\"\n  ) {\n    return PROD_TYPE.REPETITION_WITH_SEPARATOR;\n  } else if (prod instanceof Alternation || prod === \"Alternation\") {\n    return PROD_TYPE.ALTERNATION;\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n}\n\nexport function getLookaheadPaths(options: {\n  occurrence: number;\n  rule: Rule;\n  prodType: LookaheadProductionType;\n  maxLookahead: number;\n}): LookaheadSequence[] {\n  const { occurrence, rule, prodType, maxLookahead } = options;\n  const type = getProdType(prodType);\n  if (type === PROD_TYPE.ALTERNATION) {\n    return getLookaheadPathsForOr(occurrence, rule, maxLookahead);\n  } else {\n    return getLookaheadPathsForOptionalProd(\n      occurrence,\n      rule,\n      type,\n      maxLookahead,\n    );\n  }\n}\n\nexport function buildLookaheadFuncForOr(\n  occurrence: number,\n  ruleGrammar: Rule,\n  maxLookahead: number,\n  hasPredicates: boolean,\n  dynamicTokensEnabled: boolean,\n  laFuncBuilder: Function,\n): (orAlts?: IOrAlt<any>[]) => number | undefined {\n  const lookAheadPaths = getLookaheadPathsForOr(\n    occurrence,\n    ruleGrammar,\n    maxLookahead,\n  );\n\n  const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n    ? tokenStructuredMatcherNoCategories\n    : tokenStructuredMatcher;\n\n  return laFuncBuilder(\n    lookAheadPaths,\n    hasPredicates,\n    tokenMatcher,\n    dynamicTokensEnabled,\n  );\n}\n\n/**\n *  When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare\n *  the lookahead \"inside\" the production and the lookahead immediately \"after\" it in the same top level rule (context free).\n *\n *  Example: given a production:\n *  ABC(DE)?DF\n *\n *  The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two\n *  alternatives.\n *\n *  @returns A Lookahead function which will return true IFF the parser should parse the Optional production.\n */\nexport function buildLookaheadFuncForOptionalProd(\n  occurrence: number,\n  ruleGrammar: Rule,\n  k: number,\n  dynamicTokensEnabled: boolean,\n  prodType: PROD_TYPE,\n  lookaheadBuilder: (\n    lookAheadSequence: LookaheadSequence,\n    tokenMatcher: TokenMatcher,\n    dynamicTokensEnabled: boolean,\n  ) => () => boolean,\n): () => boolean {\n  const lookAheadPaths = getLookaheadPathsForOptionalProd(\n    occurrence,\n    ruleGrammar,\n    prodType,\n    k,\n  );\n\n  const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n    ? tokenStructuredMatcherNoCategories\n    : tokenStructuredMatcher;\n\n  return lookaheadBuilder(\n    lookAheadPaths[0],\n    tokenMatcher,\n    dynamicTokensEnabled,\n  );\n}\n\nexport type Alternative = TokenType[][];\n\nexport function buildAlternativesLookAheadFunc(\n  alts: LookaheadSequence[],\n  hasPredicates: boolean,\n  tokenMatcher: TokenMatcher,\n  dynamicTokensEnabled: boolean,\n): (orAlts: IOrAlt<any>[]) => number | undefined {\n  const numOfAlts = alts.length;\n  const areAllOneTokenLookahead = alts.every((currAlt) => {\n    return currAlt.every((currPath) => {\n      return currPath.length === 1;\n    });\n  });\n\n  // This version takes into account the predicates as well.\n  if (hasPredicates) {\n    /**\n     * @returns {number} - The chosen alternative index\n     */\n    return function (\n      this: BaseParser,\n      orAlts: IOrAlt<any>[],\n    ): number | undefined {\n      // unfortunately the predicates must be extracted every single time\n      // as they cannot be cached due to references to parameters(vars) which are no longer valid.\n      // note that in the common case of no predicates, no cpu time will be wasted on this (see else block)\n      const predicates: (Predicate | undefined)[] = orAlts.map(\n        (currAlt) => currAlt.GATE,\n      );\n\n      for (let t = 0; t < numOfAlts; t++) {\n        const currAlt = alts[t];\n        const currNumOfPaths = currAlt.length;\n\n        const currPredicate = predicates[t];\n        if (currPredicate !== undefined && currPredicate.call(this) === false) {\n          // if the predicate does not match there is no point in checking the paths\n          continue;\n        }\n        nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n          const currPath = currAlt[j];\n          const currPathLength = currPath.length;\n          for (let i = 0; i < currPathLength; i++) {\n            const nextToken = this.LA_FAST(i + 1);\n            if (tokenMatcher(nextToken, currPath[i]) === false) {\n              // mismatch in current path\n              // try the next pth\n              continue nextPath;\n            }\n          }\n          // found a full path that matches.\n          // this will also work for an empty ALT as the loop will be skipped\n          return t;\n        }\n        // none of the paths for the current alternative matched\n        // try the next alternative\n      }\n      // none of the alternatives could be matched\n      return undefined;\n    };\n  } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n    // optimized (common) case of all the lookaheads paths requiring only\n    // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used.\n    const singleTokenAlts = alts.map((currAlt) => {\n      return currAlt.flat();\n    });\n\n    const choiceToAlt = singleTokenAlts.reduce(\n      (result, currAlt, idx) => {\n        currAlt.forEach((currTokType) => {\n          if (!(currTokType.tokenTypeIdx! in result)) {\n            result[currTokType.tokenTypeIdx!] = idx;\n          }\n          currTokType.categoryMatches!.forEach((currExtendingType) => {\n            if (!Object.hasOwn(result, currExtendingType)) {\n              result[currExtendingType] = idx;\n            }\n          });\n        });\n        return result;\n      },\n      {} as Record<number, number>,\n    );\n\n    /**\n     * @returns {number} - The chosen alternative index\n     */\n    return function (this: BaseParser): number {\n      const nextToken = this.LA_FAST(1);\n      return choiceToAlt[nextToken.tokenTypeIdx];\n    };\n  } else {\n    // optimized lookahead without needing to check the predicates at all.\n    // this causes code duplication which is intentional to improve performance.\n    /**\n     * @returns {number} - The chosen alternative index\n     */\n    return function (this: BaseParser): number | undefined {\n      for (let t = 0; t < numOfAlts; t++) {\n        const currAlt = alts[t];\n        const currNumOfPaths = currAlt.length;\n        nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n          const currPath = currAlt[j];\n          const currPathLength = currPath.length;\n          for (let i = 0; i < currPathLength; i++) {\n            const nextToken = this.LA_FAST(i + 1);\n            if (tokenMatcher(nextToken, currPath[i]) === false) {\n              // mismatch in current path\n              // try the next pth\n              continue nextPath;\n            }\n          }\n          // found a full path that matches.\n          // this will also work for an empty ALT as the loop will be skipped\n          return t;\n        }\n        // none of the paths for the current alternative matched\n        // try the next alternative\n      }\n      // none of the alternatives could be matched\n      return undefined;\n    };\n  }\n}\n\nexport function buildSingleAlternativeLookaheadFunction(\n  alt: LookaheadSequence,\n  tokenMatcher: TokenMatcher,\n  dynamicTokensEnabled: boolean,\n): () => boolean {\n  const areAllOneTokenLookahead = alt.every((currPath) => {\n    return currPath.length === 1;\n  });\n\n  const numOfPaths = alt.length;\n\n  // optimized (common) case of all the lookaheads paths requiring only\n  // a single token lookahead.\n  if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n    const singleTokensTypes = alt.flat();\n\n    if (\n      singleTokensTypes.length === 1 &&\n      (<any>singleTokensTypes[0]).categoryMatches.length === 0\n    ) {\n      const expectedTokenType = singleTokensTypes[0];\n      const expectedTokenUniqueKey = (<any>expectedTokenType).tokenTypeIdx;\n\n      return function (this: BaseParser): boolean {\n        return this.LA_FAST(1).tokenTypeIdx === expectedTokenUniqueKey;\n      };\n    } else {\n      const choiceToAlt = singleTokensTypes.reduce(\n        (result, currTokType, idx) => {\n          result[currTokType.tokenTypeIdx!] = true;\n          currTokType.categoryMatches!.forEach((currExtendingType) => {\n            result[currExtendingType] = true;\n          });\n          return result;\n        },\n        [] as boolean[],\n      );\n\n      return function (this: BaseParser): boolean {\n        const nextToken = this.LA_FAST(1);\n        return choiceToAlt[nextToken.tokenTypeIdx] === true;\n      };\n    }\n  } else {\n    return function (this: BaseParser): boolean {\n      nextPath: for (let j = 0; j < numOfPaths; j++) {\n        const currPath = alt[j];\n        const currPathLength = currPath.length;\n        for (let i = 0; i < currPathLength; i++) {\n          const nextToken = this.LA_FAST(i + 1);\n          if (tokenMatcher(nextToken, currPath[i]) === false) {\n            // mismatch in current path\n            // try the next pth\n            continue nextPath;\n          }\n        }\n        // found a full path that matches.\n        return true;\n      }\n\n      // none of the paths matched\n      return false;\n    };\n  }\n}\n\nclass RestDefinitionFinderWalker extends RestWalker {\n  private restDef: IProduction[];\n\n  constructor(\n    private topProd: Rule,\n    private targetOccurrence: number,\n    private targetProdType: PROD_TYPE,\n  ) {\n    super();\n  }\n\n  startWalking(): IProduction[] {\n    this.walk(this.topProd);\n    return this.restDef;\n  }\n\n  private checkIsTarget(\n    node: IProductionWithOccurrence,\n    expectedProdType: PROD_TYPE,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): boolean {\n    if (\n      node.idx === this.targetOccurrence &&\n      this.targetProdType === expectedProdType\n    ) {\n      this.restDef = currRest.concat(prevRest);\n      return true;\n    }\n    // performance optimization, do not iterate over the entire Grammar ast after we have found the target\n    return false;\n  }\n\n  walkOption(\n    optionProd: Option,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {\n      super.walkOption(optionProd, currRest, prevRest);\n    }\n  }\n\n  walkAtLeastOne(\n    atLeastOneProd: RepetitionMandatory,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (\n      !this.checkIsTarget(\n        atLeastOneProd,\n        PROD_TYPE.REPETITION_MANDATORY,\n        currRest,\n        prevRest,\n      )\n    ) {\n      super.walkOption(atLeastOneProd, currRest, prevRest);\n    }\n  }\n\n  walkAtLeastOneSep(\n    atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (\n      !this.checkIsTarget(\n        atLeastOneSepProd,\n        PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n        currRest,\n        prevRest,\n      )\n    ) {\n      super.walkOption(atLeastOneSepProd, currRest, prevRest);\n    }\n  }\n\n  walkMany(\n    manyProd: Repetition,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (\n      !this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)\n    ) {\n      super.walkOption(manyProd, currRest, prevRest);\n    }\n  }\n\n  walkManySep(\n    manySepProd: RepetitionWithSeparator,\n    currRest: IProduction[],\n    prevRest: IProduction[],\n  ): void {\n    if (\n      !this.checkIsTarget(\n        manySepProd,\n        PROD_TYPE.REPETITION_WITH_SEPARATOR,\n        currRest,\n        prevRest,\n      )\n    ) {\n      super.walkOption(manySepProd, currRest, prevRest);\n    }\n  }\n}\n\n/**\n * Returns the definition of a target production in a top level level rule.\n */\nclass InsideDefinitionFinderVisitor extends GAstVisitor {\n  public result: IProduction[] = [];\n\n  constructor(\n    private targetOccurrence: number,\n    private targetProdType: PROD_TYPE,\n    private targetRef?: any,\n  ) {\n    super();\n  }\n\n  private checkIsTarget(\n    node: { definition: IProduction[] } & IProductionWithOccurrence,\n    expectedProdName: PROD_TYPE,\n  ): void {\n    if (\n      node.idx === this.targetOccurrence &&\n      this.targetProdType === expectedProdName &&\n      (this.targetRef === undefined || node === this.targetRef)\n    ) {\n      this.result = node.definition;\n    }\n  }\n\n  public visitOption(node: Option): void {\n    this.checkIsTarget(node, PROD_TYPE.OPTION);\n  }\n\n  public visitRepetition(node: Repetition): void {\n    this.checkIsTarget(node, PROD_TYPE.REPETITION);\n  }\n\n  public visitRepetitionMandatory(node: RepetitionMandatory): void {\n    this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);\n  }\n\n  public visitRepetitionMandatoryWithSeparator(\n    node: RepetitionMandatoryWithSeparator,\n  ): void {\n    this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);\n  }\n\n  public visitRepetitionWithSeparator(node: RepetitionWithSeparator): void {\n    this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);\n  }\n\n  public visitAlternation(node: Alternation): void {\n    this.checkIsTarget(node, PROD_TYPE.ALTERNATION);\n  }\n}\n\nfunction initializeArrayOfArrays(size: number): any[][] {\n  const result = new Array(size);\n  for (let i = 0; i < size; i++) {\n    result[i] = [];\n  }\n  return result;\n}\n\n/**\n * A sort of hash function between a Path in the grammar and a string.\n * Note that this returns multiple \"hashes\" to support the scenario of token categories.\n * -  A single path with categories may match multiple **actual** paths.\n */\nfunction pathToHashKeys(path: TokenType[]): string[] {\n  let keys = [\"\"];\n  for (let i = 0; i < path.length; i++) {\n    const tokType = path[i];\n    const longerKeys = [];\n    for (let j = 0; j < keys.length; j++) {\n      const currShorterKey = keys[j];\n      longerKeys.push(currShorterKey + \"_\" + tokType.tokenTypeIdx);\n      for (let t = 0; t < tokType.categoryMatches!.length; t++) {\n        const categoriesKeySuffix = \"_\" + tokType.categoryMatches![t];\n        longerKeys.push(currShorterKey + categoriesKeySuffix);\n      }\n    }\n    keys = longerKeys;\n  }\n  return keys;\n}\n\n/**\n * Imperative style due to being called from a hot spot\n */\nfunction isUniquePrefixHash(\n  altKnownPathsKeys: Record<string, boolean>[],\n  searchPathKeys: string[],\n  idx: number,\n): boolean {\n  for (\n    let currAltIdx = 0;\n    currAltIdx < altKnownPathsKeys.length;\n    currAltIdx++\n  ) {\n    // We only want to test vs the other alternatives\n    if (currAltIdx === idx) {\n      continue;\n    }\n    const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];\n    for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {\n      const searchKey = searchPathKeys[searchIdx];\n      if (otherAltKnownPathsKeys[searchKey] === true) {\n        return false;\n      }\n    }\n  }\n  // None of the SearchPathKeys were found in any of the other alternatives\n  return true;\n}\n\nexport function lookAheadSequenceFromAlternatives(\n  altsDefs: IProduction[],\n  k: number,\n): LookaheadSequence[] {\n  const partialAlts = altsDefs.map((currAlt) =>\n    possiblePathsFrom([currAlt], 1),\n  );\n  const finalResult = initializeArrayOfArrays(partialAlts.length);\n  const altsHashes = partialAlts.map((currAltPaths) => {\n    const dict: { [key: string]: boolean } = {};\n    currAltPaths.forEach((item) => {\n      const keys = pathToHashKeys(item.partialPath);\n      keys.forEach((currKey) => {\n        dict[currKey] = true;\n      });\n    });\n    return dict;\n  });\n  let newData = partialAlts;\n\n  // maxLookahead loop\n  for (let pathLength = 1; pathLength <= k; pathLength++) {\n    const currDataset = newData;\n    newData = initializeArrayOfArrays(currDataset.length);\n\n    // alternatives loop\n    for (let altIdx = 0; altIdx < currDataset.length; altIdx++) {\n      const currAltPathsAndSuffixes = currDataset[altIdx];\n      // paths in current alternative loop\n      for (\n        let currPathIdx = 0;\n        currPathIdx < currAltPathsAndSuffixes.length;\n        currPathIdx++\n      ) {\n        const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;\n        const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;\n        const prefixKeys = pathToHashKeys(currPathPrefix);\n        const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);\n        // End of the line for this path.\n        if (isUnique || suffixDef.length === 0 || currPathPrefix.length === k) {\n          const currAltResult = finalResult[altIdx];\n          // TODO: Can we implement a containsPath using Maps/Dictionaries?\n          if (containsPath(currAltResult, currPathPrefix) === false) {\n            currAltResult.push(currPathPrefix);\n            // Update all new  keys for the current path.\n            for (let j = 0; j < prefixKeys.length; j++) {\n              const currKey = prefixKeys[j];\n              altsHashes[altIdx][currKey] = true;\n            }\n          }\n        }\n        // Expand longer paths\n        else {\n          const newPartialPathsAndSuffixes = possiblePathsFrom(\n            suffixDef,\n            pathLength + 1,\n            currPathPrefix,\n          );\n          newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);\n\n          // Update keys for new known paths\n          newPartialPathsAndSuffixes.forEach((item) => {\n            const prefixKeys = pathToHashKeys(item.partialPath);\n            prefixKeys.forEach((key) => {\n              altsHashes[altIdx][key] = true;\n            });\n          });\n        }\n      }\n    }\n  }\n\n  return finalResult;\n}\n\nexport function getLookaheadPathsForOr(\n  occurrence: number,\n  ruleGrammar: Rule,\n  k: number,\n  orProd?: Alternation,\n): LookaheadSequence[] {\n  const visitor = new InsideDefinitionFinderVisitor(\n    occurrence,\n    PROD_TYPE.ALTERNATION,\n    orProd,\n  );\n  ruleGrammar.accept(visitor);\n  return lookAheadSequenceFromAlternatives(visitor.result, k);\n}\n\nexport function getLookaheadPathsForOptionalProd(\n  occurrence: number,\n  ruleGrammar: Rule,\n  prodType: PROD_TYPE,\n  k: number,\n): LookaheadSequence[] {\n  const insideDefVisitor = new InsideDefinitionFinderVisitor(\n    occurrence,\n    prodType,\n  );\n  ruleGrammar.accept(insideDefVisitor);\n  const insideDef = insideDefVisitor.result;\n\n  const afterDefWalker = new RestDefinitionFinderWalker(\n    ruleGrammar,\n    occurrence,\n    prodType,\n  );\n  const afterDef = afterDefWalker.startWalking();\n\n  const insideFlat = new AlternativeGAST({ definition: insideDef });\n  const afterFlat = new AlternativeGAST({ definition: afterDef });\n\n  return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);\n}\n\nexport function containsPath(\n  alternative: Alternative,\n  searchPath: TokenType[],\n): boolean {\n  compareOtherPath: for (let i = 0; i < alternative.length; i++) {\n    const otherPath = alternative[i];\n    if (otherPath.length !== searchPath.length) {\n      continue;\n    }\n    for (let j = 0; j < otherPath.length; j++) {\n      const searchTok = searchPath[j];\n      const otherTok = otherPath[j];\n\n      const matchingTokens =\n        searchTok === otherTok ||\n        otherTok.categoryMatchesMap![searchTok.tokenTypeIdx!] !== undefined;\n      if (matchingTokens === false) {\n        continue compareOtherPath;\n      }\n    }\n    return true;\n  }\n\n  return false;\n}\n\nexport function isStrictPrefixOfPath(\n  prefix: TokenType[],\n  other: TokenType[],\n): boolean {\n  return (\n    prefix.length < other.length &&\n    prefix.every((tokType, idx) => {\n      const otherTokType = other[idx];\n      return (\n        tokType === otherTokType ||\n        otherTokType.categoryMatchesMap![tokType.tokenTypeIdx!]\n      );\n    })\n  );\n}\n\nexport function areTokenCategoriesNotUsed(\n  lookAheadPaths: LookaheadSequence[],\n): boolean {\n  return lookAheadPaths.every((singleAltPaths) =>\n    singleAltPaths.every((singlePath) =>\n      singlePath.every((token) => token.categoryMatches!.length === 0),\n    ),\n  );\n}\n", "import {\n  IParserAmbiguousAlternativesDefinitionError,\n  IParserDuplicatesDefinitionError,\n  IParserEmptyAlternativeDefinitionError,\n  ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport {\n  Alternation,\n  Alternative as AlternativeGAST,\n  GAstVisitor,\n  getProductionDslName,\n  isOptionalProd,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport {\n  Alternative,\n  containsPath,\n  getLookaheadPathsForOptionalProd,\n  getLookaheadPathsForOr,\n  getProdType,\n  isStrictPrefixOfPath,\n} from \"./lookahead.js\";\nimport { nextPossibleTokensAfter } from \"./interpreter.js\";\nimport {\n  ILookaheadStrategy,\n  IProduction,\n  IProductionWithOccurrence,\n  Rule,\n  TokenType,\n} from \"@chevrotain/types\";\nimport {\n  IGrammarValidatorErrorMessageProvider,\n  IParserDefinitionError,\n} from \"./types.js\";\nimport { tokenStructuredMatcher } from \"../../scan/tokens.js\";\n\nexport function validateLookahead(options: {\n  lookaheadStrategy: ILookaheadStrategy;\n  rules: Rule[];\n  tokenTypes: TokenType[];\n  grammarName: string;\n}): IParserDefinitionError[] {\n  const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({\n    rules: options.rules,\n    tokenTypes: options.tokenTypes,\n    grammarName: options.grammarName,\n  });\n  return lookaheadValidationErrorMessages.map((errorMessage) => ({\n    type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION,\n    ...errorMessage,\n  }));\n}\n\nexport function validateGrammar(\n  topLevels: Rule[],\n  tokenTypes: TokenType[],\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n  grammarName: string,\n): IParserDefinitionError[] {\n  const duplicateErrors: IParserDefinitionError[] = topLevels.flatMap(\n    (currTopLevel) =>\n      validateDuplicateProductions(currTopLevel, errMsgProvider),\n  );\n\n  const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(\n    topLevels,\n    tokenTypes,\n    errMsgProvider,\n  );\n\n  const tooManyAltsErrors = topLevels.flatMap((curRule) =>\n    validateTooManyAlts(curRule, errMsgProvider),\n  );\n\n  const duplicateRulesError = topLevels.flatMap((curRule) =>\n    validateRuleDoesNotAlreadyExist(\n      curRule,\n      topLevels,\n      grammarName,\n      errMsgProvider,\n    ),\n  );\n\n  return duplicateErrors.concat(\n    termsNamespaceConflictErrors,\n    tooManyAltsErrors,\n    duplicateRulesError,\n  );\n}\n\nfunction validateDuplicateProductions(\n  topLevelRule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDuplicatesDefinitionError[] {\n  const collectorVisitor = new OccurrenceValidationCollector();\n  topLevelRule.accept(collectorVisitor);\n  const allRuleProductions = collectorVisitor.allProductions;\n\n  const productionGroups = Object.groupBy(\n    allRuleProductions,\n    identifyProductionForDuplicates,\n  );\n\n  const duplicates = Object.fromEntries(\n    Object.entries(productionGroups).filter(\n      ([_k, currGroup]) => currGroup!.length > 1,\n    ),\n  );\n\n  const errors = Object.values(duplicates).map((currDuplicates: any) => {\n    const firstProd: any = currDuplicates[0];\n    const msg = errMsgProvider.buildDuplicateFoundError(\n      topLevelRule,\n      currDuplicates,\n    );\n    const dslName = getProductionDslName(firstProd);\n    const defError: IParserDuplicatesDefinitionError = {\n      message: msg,\n      type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,\n      ruleName: topLevelRule.name,\n      dslName: dslName,\n      occurrence: firstProd.idx,\n    };\n\n    const param = getExtraProductionArgument(firstProd);\n    if (param) {\n      defError.parameter = param;\n    }\n\n    return defError;\n  });\n  return errors;\n}\n\nexport function identifyProductionForDuplicates(\n  prod: IProductionWithOccurrence,\n): string {\n  return `${getProductionDslName(prod)}_#_${\n    prod.idx\n  }_#_${getExtraProductionArgument(prod)}`;\n}\n\nfunction getExtraProductionArgument(prod: IProductionWithOccurrence): string {\n  if (prod instanceof Terminal) {\n    return prod.terminalType.name;\n  } else if (prod instanceof NonTerminal) {\n    return prod.nonTerminalName;\n  } else {\n    return \"\";\n  }\n}\n\nexport class OccurrenceValidationCollector extends GAstVisitor {\n  public allProductions: IProductionWithOccurrence[] = [];\n\n  public visitNonTerminal(subrule: NonTerminal): void {\n    this.allProductions.push(subrule);\n  }\n\n  public visitOption(option: Option): void {\n    this.allProductions.push(option);\n  }\n\n  public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n    this.allProductions.push(manySep);\n  }\n\n  public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n    this.allProductions.push(atLeastOne);\n  }\n\n  public visitRepetitionMandatoryWithSeparator(\n    atLeastOneSep: RepetitionMandatoryWithSeparator,\n  ): void {\n    this.allProductions.push(atLeastOneSep);\n  }\n\n  public visitRepetition(many: Repetition): void {\n    this.allProductions.push(many);\n  }\n\n  public visitAlternation(or: Alternation): void {\n    this.allProductions.push(or);\n  }\n\n  public visitTerminal(terminal: Terminal): void {\n    this.allProductions.push(terminal);\n  }\n}\n\nexport function validateRuleDoesNotAlreadyExist(\n  rule: Rule,\n  allRules: Rule[],\n  className: string,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n  const errors = [];\n  const occurrences = allRules.reduce((result, curRule) => {\n    if (curRule.name === rule.name) {\n      return result + 1;\n    }\n    return result;\n  }, 0);\n  if (occurrences > 1) {\n    const errMsg = errMsgProvider.buildDuplicateRuleNameError({\n      topLevelRule: rule,\n      grammarName: className,\n    });\n    errors.push({\n      message: errMsg,\n      type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n      ruleName: rule.name,\n    });\n  }\n\n  return errors;\n}\n\n// TODO: is there anyway to get only the rule names of rules inherited from the super grammars?\n// This is not part of the IGrammarErrorProvider because the validation cannot be performed on\n// The grammar structure, only at runtime.\nexport function validateRuleIsOverridden(\n  ruleName: string,\n  definedRulesNames: string[],\n  className: string,\n): IParserDefinitionError[] {\n  const errors = [];\n  let errMsg;\n\n  if (!definedRulesNames.includes(ruleName)) {\n    errMsg =\n      `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-` +\n      `as it is not defined in any of the super grammars `;\n    errors.push({\n      message: errMsg,\n      type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,\n      ruleName: ruleName,\n    });\n  }\n\n  return errors;\n}\n\nexport function validateNoLeftRecursion(\n  topRule: Rule,\n  currRule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n  path: Rule[] = [],\n): IParserDefinitionError[] {\n  const errors: IParserDefinitionError[] = [];\n  const nextNonTerminals = getFirstNoneTerminal(currRule.definition);\n  if (nextNonTerminals.length === 0) {\n    return [];\n  } else {\n    const ruleName = topRule.name;\n    const foundLeftRecursion = nextNonTerminals.includes(topRule);\n    if (foundLeftRecursion) {\n      errors.push({\n        message: errMsgProvider.buildLeftRecursionError({\n          topLevelRule: topRule,\n          leftRecursionPath: path,\n        }),\n        type: ParserDefinitionErrorType.LEFT_RECURSION,\n        ruleName: ruleName,\n      });\n    }\n\n    // we are only looking for cyclic paths leading back to the specific topRule\n    // other cyclic paths are ignored, we still need this difference to avoid infinite loops...\n    const excluded = path.concat([topRule]);\n    const validNextSteps = nextNonTerminals.filter(\n      (x) => !excluded.includes(x),\n    );\n    const errorsFromNextSteps = validNextSteps.flatMap((currRefRule) => {\n      const newPath = [...path];\n      newPath.push(currRefRule);\n      return validateNoLeftRecursion(\n        topRule,\n        currRefRule,\n        errMsgProvider,\n        newPath,\n      );\n    });\n\n    return errors.concat(errorsFromNextSteps);\n  }\n}\n\nexport function getFirstNoneTerminal(definition: IProduction[]): Rule[] {\n  let result: Rule[] = [];\n  if (definition.length === 0) {\n    return result;\n  }\n  const firstProd = definition[0];\n\n  /* istanbul ignore else */\n  if (firstProd instanceof NonTerminal) {\n    result.push(firstProd.referencedRule);\n  } else if (\n    firstProd instanceof AlternativeGAST ||\n    firstProd instanceof Option ||\n    firstProd instanceof RepetitionMandatory ||\n    firstProd instanceof RepetitionMandatoryWithSeparator ||\n    firstProd instanceof RepetitionWithSeparator ||\n    firstProd instanceof Repetition\n  ) {\n    result = result.concat(\n      getFirstNoneTerminal(<IProduction[]>firstProd.definition),\n    );\n  } else if (firstProd instanceof Alternation) {\n    // each sub definition in alternation is a FLAT\n    result = firstProd.definition\n      .map((currSubDef) =>\n        getFirstNoneTerminal((<AlternativeGAST>currSubDef).definition),\n      )\n      .flat();\n  } else if (firstProd instanceof Terminal) {\n    // nothing to see, move along\n  } else {\n    throw Error(\"non exhaustive match\");\n  }\n\n  const isFirstOptional = isOptionalProd(firstProd);\n  const hasMore = definition.length > 1;\n  if (isFirstOptional && hasMore) {\n    const rest = definition.slice(1);\n    return result.concat(getFirstNoneTerminal(rest));\n  } else {\n    return result;\n  }\n}\n\nclass OrCollector extends GAstVisitor {\n  public alternations: Alternation[] = [];\n\n  public visitAlternation(node: Alternation): void {\n    this.alternations.push(node);\n  }\n}\n\nexport function validateEmptyOrAlternative(\n  topLevelRule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserEmptyAlternativeDefinitionError[] {\n  const orCollector = new OrCollector();\n  topLevelRule.accept(orCollector);\n  const ors = orCollector.alternations;\n\n  const errors = ors.flatMap<IParserEmptyAlternativeDefinitionError>(\n    (currOr) => {\n      const exceptLast = currOr.definition.slice(0, -1);\n      return exceptLast.flatMap((currAlternative, currAltIdx) => {\n        const possibleFirstInAlt = nextPossibleTokensAfter(\n          [currAlternative],\n          [],\n          tokenStructuredMatcher,\n          1,\n        );\n        if (possibleFirstInAlt.length === 0) {\n          return [\n            {\n              message: errMsgProvider.buildEmptyAlternationError({\n                topLevelRule: topLevelRule,\n                alternation: currOr,\n                emptyChoiceIdx: currAltIdx,\n              }),\n              type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,\n              ruleName: topLevelRule.name,\n              occurrence: currOr.idx,\n              alternative: currAltIdx + 1,\n            },\n          ];\n        } else {\n          return [];\n        }\n      });\n    },\n  );\n\n  return errors;\n}\n\nexport function validateAmbiguousAlternationAlternatives(\n  topLevelRule: Rule,\n  globalMaxLookahead: number,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n  const orCollector = new OrCollector();\n  topLevelRule.accept(orCollector);\n  let ors = orCollector.alternations;\n\n  // New Handling of ignoring ambiguities\n  // - https://github.com/chevrotain/chevrotain/issues/869\n  ors = ors.filter((currOr) => currOr.ignoreAmbiguities !== true);\n\n  const errors = ors.flatMap((currOr: Alternation) => {\n    const currOccurrence = currOr.idx;\n    const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;\n    const alternatives = getLookaheadPathsForOr(\n      currOccurrence,\n      topLevelRule,\n      actualMaxLookahead,\n      currOr,\n    );\n    const altsAmbiguityErrors = checkAlternativesAmbiguities(\n      alternatives,\n      currOr,\n      topLevelRule,\n      errMsgProvider,\n    );\n    const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(\n      alternatives,\n      currOr,\n      topLevelRule,\n      errMsgProvider,\n    );\n\n    return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors);\n  });\n\n  return errors;\n}\n\nexport class RepetitionCollector extends GAstVisitor {\n  public allProductions: (IProductionWithOccurrence & {\n    maxLookahead?: number;\n  })[] = [];\n\n  public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n    this.allProductions.push(manySep);\n  }\n\n  public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n    this.allProductions.push(atLeastOne);\n  }\n\n  public visitRepetitionMandatoryWithSeparator(\n    atLeastOneSep: RepetitionMandatoryWithSeparator,\n  ): void {\n    this.allProductions.push(atLeastOneSep);\n  }\n\n  public visitRepetition(many: Repetition): void {\n    this.allProductions.push(many);\n  }\n}\n\nexport function validateTooManyAlts(\n  topLevelRule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n  const orCollector = new OrCollector();\n  topLevelRule.accept(orCollector);\n  const ors = orCollector.alternations;\n\n  const errors = ors.flatMap((currOr) => {\n    if (currOr.definition.length > 255) {\n      return [\n        {\n          message: errMsgProvider.buildTooManyAlternativesError({\n            topLevelRule: topLevelRule,\n            alternation: currOr,\n          }),\n          type: ParserDefinitionErrorType.TOO_MANY_ALTS,\n          ruleName: topLevelRule.name,\n          occurrence: currOr.idx,\n        },\n      ];\n    } else {\n      return [];\n    }\n  });\n\n  return errors;\n}\n\nexport function validateSomeNonEmptyLookaheadPath(\n  topLevelRules: Rule[],\n  maxLookahead: number,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n  const errors: IParserDefinitionError[] = [];\n  topLevelRules.forEach((currTopRule) => {\n    const collectorVisitor = new RepetitionCollector();\n    currTopRule.accept(collectorVisitor);\n    const allRuleProductions = collectorVisitor.allProductions;\n    allRuleProductions.forEach((currProd) => {\n      const prodType = getProdType(currProd);\n      const actualMaxLookahead = currProd.maxLookahead || maxLookahead;\n      const currOccurrence = currProd.idx;\n      const paths = getLookaheadPathsForOptionalProd(\n        currOccurrence,\n        currTopRule,\n        prodType,\n        actualMaxLookahead,\n      );\n      const pathsInsideProduction = paths[0];\n      if (pathsInsideProduction.flat().length === 0) {\n        const errMsg = errMsgProvider.buildEmptyRepetitionError({\n          topLevelRule: currTopRule,\n          repetition: currProd,\n        });\n        errors.push({\n          message: errMsg,\n          type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,\n          ruleName: currTopRule.name,\n        });\n      }\n    });\n  });\n\n  return errors;\n}\n\nexport interface IAmbiguityDescriptor {\n  alts: number[];\n  path: TokenType[];\n}\n\nfunction checkAlternativesAmbiguities(\n  alternatives: Alternative[],\n  alternation: Alternation,\n  rule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n  const foundAmbiguousPaths: Alternative = [];\n  const identicalAmbiguities = alternatives.reduce(\n    (result, currAlt, currAltIdx) => {\n      // ignore (skip) ambiguities with this alternative\n      if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {\n        return result;\n      }\n\n      currAlt.forEach((currPath) => {\n        const altsCurrPathAppearsIn = [currAltIdx];\n        alternatives.forEach((currOtherAlt, currOtherAltIdx) => {\n          if (\n            currAltIdx !== currOtherAltIdx &&\n            containsPath(currOtherAlt, currPath) &&\n            // ignore (skip) ambiguities with this \"other\" alternative\n            alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true\n          ) {\n            altsCurrPathAppearsIn.push(currOtherAltIdx);\n          }\n        });\n\n        if (\n          altsCurrPathAppearsIn.length > 1 &&\n          !containsPath(foundAmbiguousPaths, currPath)\n        ) {\n          foundAmbiguousPaths.push(currPath);\n          result.push({\n            alts: altsCurrPathAppearsIn,\n            path: currPath,\n          });\n        }\n      });\n      return result;\n    },\n    [] as { alts: number[]; path: TokenType[] }[],\n  );\n\n  const currErrors = identicalAmbiguities.map((currAmbDescriptor) => {\n    const ambgIndices = currAmbDescriptor.alts.map(\n      (currAltIdx) => currAltIdx + 1,\n    );\n\n    const currMessage = errMsgProvider.buildAlternationAmbiguityError({\n      topLevelRule: rule,\n      alternation: alternation,\n      ambiguityIndices: ambgIndices,\n      prefixPath: currAmbDescriptor.path,\n    });\n\n    return {\n      message: currMessage,\n      type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,\n      ruleName: rule.name,\n      occurrence: alternation.idx,\n      alternatives: currAmbDescriptor.alts,\n    };\n  });\n\n  return currErrors;\n}\n\nexport function checkPrefixAlternativesAmbiguities(\n  alternatives: Alternative[],\n  alternation: Alternation,\n  rule: Rule,\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n  // flatten\n  const pathsAndIndices = alternatives.reduce(\n    (result, currAlt, idx) => {\n      const currPathsAndIdx = currAlt.map((currPath) => {\n        return { idx: idx, path: currPath };\n      });\n      return result.concat(currPathsAndIdx);\n    },\n    [] as { idx: number; path: TokenType[] }[],\n  );\n\n  const errors = pathsAndIndices.flatMap((currPathAndIdx) => {\n    const alternativeGast = alternation.definition[currPathAndIdx.idx];\n    // ignore (skip) ambiguities with this alternative\n    if (alternativeGast.ignoreAmbiguities === true) {\n      return [];\n    }\n    const targetIdx = currPathAndIdx.idx;\n    const targetPath = currPathAndIdx.path;\n\n    const prefixAmbiguitiesPathsAndIndices = pathsAndIndices.filter(\n      (searchPathAndIdx) => {\n        // prefix ambiguity can only be created from lower idx (higher priority) path\n        return (\n          // ignore (skip) ambiguities with this \"other\" alternative\n          alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !==\n            true &&\n          searchPathAndIdx.idx < targetIdx &&\n          // checking for strict prefix because identical lookaheads\n          // will be be detected using a different validation.\n          isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)\n        );\n      },\n    );\n\n    const currPathPrefixErrors = prefixAmbiguitiesPathsAndIndices.map(\n      (currAmbPathAndIdx): IParserAmbiguousAlternativesDefinitionError => {\n        const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];\n        const occurrence = alternation.idx === 0 ? \"\" : alternation.idx;\n\n        const message = errMsgProvider.buildAlternationPrefixAmbiguityError({\n          topLevelRule: rule,\n          alternation: alternation,\n          ambiguityIndices: ambgIndices,\n          prefixPath: currAmbPathAndIdx.path,\n        });\n        return {\n          message: message,\n          type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,\n          ruleName: rule.name,\n          occurrence: occurrence,\n          alternatives: ambgIndices,\n        };\n      },\n    );\n\n    return currPathPrefixErrors;\n  });\n\n  return errors;\n}\n\nfunction checkTerminalAndNoneTerminalsNameSpace(\n  topLevels: Rule[],\n  tokenTypes: TokenType[],\n  errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n  const errors: IParserDefinitionError[] = [];\n\n  const tokenNames = tokenTypes.map((currToken) => currToken.name);\n\n  topLevels.forEach((currRule) => {\n    const currRuleName = currRule.name;\n    if (tokenNames.includes(currRuleName)) {\n      const errMsg = errMsgProvider.buildNamespaceConflictError(currRule);\n\n      errors.push({\n        message: errMsg,\n        type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,\n        ruleName: currRuleName,\n      });\n    }\n  });\n\n  return errors;\n}\n", "import { Rule } from \"@chevrotain/gast\";\nimport { resolveGrammar as orgResolveGrammar } from \"../resolver.js\";\nimport { validateGrammar as orgValidateGrammar } from \"../checks.js\";\nimport {\n  defaultGrammarResolverErrorProvider,\n  defaultGrammarValidatorErrorProvider,\n} from \"../../errors_public.js\";\nimport { TokenType } from \"@chevrotain/types\";\nimport {\n  IGrammarResolverErrorMessageProvider,\n  IGrammarValidatorErrorMessageProvider,\n  IParserDefinitionError,\n} from \"../types.js\";\n\ntype ResolveGrammarOpts = {\n  rules: Rule[];\n  errMsgProvider?: IGrammarResolverErrorMessageProvider;\n};\nexport function resolveGrammar(\n  options: ResolveGrammarOpts,\n): IParserDefinitionError[] {\n  const actualOptions: Required<ResolveGrammarOpts> = {\n    errMsgProvider: defaultGrammarResolverErrorProvider,\n    ...options,\n  };\n\n  const topRulesTable: { [ruleName: string]: Rule } = {};\n  options.rules.forEach((rule) => {\n    topRulesTable[rule.name] = rule;\n  });\n  return orgResolveGrammar(topRulesTable, actualOptions.errMsgProvider);\n}\n\nexport function validateGrammar(options: {\n  rules: Rule[];\n  tokenTypes: TokenType[];\n  grammarName: string;\n  errMsgProvider?: IGrammarValidatorErrorMessageProvider;\n}): IParserDefinitionError[] {\n  const errMsgProvider =\n    options.errMsgProvider ?? defaultGrammarValidatorErrorProvider;\n\n  return orgValidateGrammar(\n    options.rules,\n    options.tokenTypes,\n    errMsgProvider,\n    options.grammarName,\n  );\n}\n", "import {\n  IRecognitionException,\n  IRecognizerContext,\n  IToken,\n} from \"@chevrotain/types\";\n\nconst MISMATCHED_TOKEN_EXCEPTION = \"MismatchedTokenException\";\nconst NO_VIABLE_ALT_EXCEPTION = \"NoViableAltException\";\nconst EARLY_EXIT_EXCEPTION = \"EarlyExitException\";\nconst NOT_ALL_INPUT_PARSED_EXCEPTION = \"NotAllInputParsedException\";\n\nconst RECOGNITION_EXCEPTION_NAMES = [\n  MISMATCHED_TOKEN_EXCEPTION,\n  NO_VIABLE_ALT_EXCEPTION,\n  EARLY_EXIT_EXCEPTION,\n  NOT_ALL_INPUT_PARSED_EXCEPTION,\n];\n\nObject.freeze(RECOGNITION_EXCEPTION_NAMES);\n\n// hacks to bypass no support for custom Errors in javascript/typescript\nexport function isRecognitionException(error: Error) {\n  // can't do instanceof on hacked custom js exceptions\n  return RECOGNITION_EXCEPTION_NAMES.includes(error.name);\n}\n\nabstract class RecognitionException\n  extends Error\n  implements IRecognitionException\n{\n  context: IRecognizerContext;\n  resyncedTokens: IToken[] = [];\n\n  protected constructor(\n    message: string,\n    public token: IToken,\n  ) {\n    super(message);\n\n    // fix prototype chain when typescript target is ES5\n    Object.setPrototypeOf(this, new.target.prototype);\n\n    /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, this.constructor);\n    }\n  }\n}\n\nexport class MismatchedTokenException extends RecognitionException {\n  constructor(\n    message: string,\n    token: IToken,\n    public previousToken: IToken,\n  ) {\n    super(message, token);\n    this.name = MISMATCHED_TOKEN_EXCEPTION;\n  }\n}\n\nexport class NoViableAltException extends RecognitionException {\n  constructor(\n    message: string,\n    token: IToken,\n    public previousToken: IToken,\n  ) {\n    super(message, token);\n    this.name = NO_VIABLE_ALT_EXCEPTION;\n  }\n}\n\nexport class NotAllInputParsedException extends RecognitionException {\n  constructor(message: string, token: IToken) {\n    super(message, token);\n    this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;\n  }\n}\n\nexport class EarlyExitException extends RecognitionException {\n  constructor(\n    message: string,\n    token: IToken,\n    public previousToken: IToken,\n  ) {\n    super(message, token);\n    this.name = EARLY_EXIT_EXCEPTION;\n  }\n}\n", "import {\n  createTokenInstance,\n  EOF,\n  tokenMatcher,\n} from \"../../../scan/tokens_public.js\";\nimport {\n  AbstractNextTerminalAfterProductionWalker,\n  IFirstAfterRepetition,\n  NextAfterTokenWalker,\n} from \"../../grammar/interpreter.js\";\n\nimport {\n  IParserConfig,\n  IToken,\n  ITokenGrammarPath,\n  TokenType,\n} from \"@chevrotain/types\";\nimport { MismatchedTokenException } from \"../../exceptions_public.js\";\nimport { IN } from \"../../constants.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\nexport const EOF_FOLLOW_KEY: any = {};\n\nexport interface IFollowKey {\n  ruleName: string;\n  idxInCallingRule: number;\n  inRule: string;\n}\n\nexport const IN_RULE_RECOVERY_EXCEPTION = \"InRuleRecoveryException\";\n\nexport class InRuleRecoveryException extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = IN_RULE_RECOVERY_EXCEPTION;\n  }\n}\n\n/**\n * This trait is responsible for the error recovery and fault tolerant logic\n */\nexport class Recoverable {\n  recoveryEnabled: boolean;\n  firstAfterRepMap: IFirstAfterRepetition[][];\n  resyncFollows: Record<string, TokenType[]>;\n\n  initRecoverable(config: IParserConfig) {\n    this.firstAfterRepMap = [];\n    this.resyncFollows = {};\n\n    this.recoveryEnabled = Object.hasOwn(config, \"recoveryEnabled\")\n      ? (config.recoveryEnabled as boolean) // assumes end user provides the correct config value/type\n      : DEFAULT_PARSER_CONFIG.recoveryEnabled;\n\n    // performance optimization, NOOP will be inlined which\n    // effectively means that this optional feature does not exist\n    // when not used.\n    if (this.recoveryEnabled) {\n      this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;\n    }\n  }\n\n  public getTokenToInsert(tokType: TokenType): IToken {\n    const tokToInsert = createTokenInstance(\n      tokType,\n      \"\",\n      -1,\n      -1,\n      -1,\n      -1,\n      -1,\n      -1,\n    );\n    tokToInsert.isInsertedInRecovery = true;\n    return tokToInsert;\n  }\n\n  public canTokenTypeBeInsertedInRecovery(tokType: TokenType): boolean {\n    return true;\n  }\n\n  public canTokenTypeBeDeletedInRecovery(tokType: TokenType): boolean {\n    return true;\n  }\n\n  tryInRepetitionRecovery(\n    this: MixedInParser,\n    grammarRule: Function,\n    grammarRuleArgs: any[],\n    lookAheadFunc: () => boolean,\n    expectedTokType: TokenType,\n  ): void {\n    // TODO: can the resyncTokenType be cached?\n    const reSyncTokType = this.findReSyncTokenType();\n    const savedLexerState = this.exportLexerState();\n    const resyncedTokens: IToken[] = [];\n    let passedResyncPoint = false;\n\n    const nextTokenWithoutResync = this.LA_FAST(1);\n    let currToken = this.LA_FAST(1);\n\n    const generateErrorMessage = () => {\n      const previousToken = this.LA(0);\n      // we are preemptively re-syncing before an error has been detected, therefor we must reproduce\n      // the error that would have been thrown\n      const msg = this.errorMessageProvider.buildMismatchTokenMessage({\n        expected: expectedTokType,\n        actual: nextTokenWithoutResync,\n        previous: previousToken,\n        ruleName: this.getCurrRuleFullName(),\n      });\n      const error = new MismatchedTokenException(\n        msg,\n        nextTokenWithoutResync,\n        this.LA(0),\n      );\n      // the first token here will be the original cause of the error, this is not part of the resyncedTokens property.\n      error.resyncedTokens = resyncedTokens.slice(0, -1);\n      this.SAVE_ERROR(error);\n    };\n\n    while (!passedResyncPoint) {\n      // re-synced to a point where we can safely exit the repetition/\n      if (this.tokenMatcher(currToken, expectedTokType)) {\n        generateErrorMessage();\n        return; // must return here to avoid reverting the inputIdx\n      } else if (lookAheadFunc.call(this)) {\n        // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule\n        generateErrorMessage();\n        // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule\n        grammarRule.apply(this, grammarRuleArgs);\n        return; // must return here to avoid reverting the inputIdx\n      } else if (this.tokenMatcher(currToken, reSyncTokType)) {\n        passedResyncPoint = true;\n      } else {\n        currToken = this.SKIP_TOKEN();\n        this.addToResyncTokens(currToken, resyncedTokens);\n      }\n    }\n\n    // we were unable to find a CLOSER point to resync inside the Repetition, reset the state.\n    // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by\n    // \"between rules\" resync recovery later in the flow.\n    this.importLexerState(savedLexerState);\n  }\n\n  shouldInRepetitionRecoveryBeTried(\n    this: MixedInParser,\n    expectTokAfterLastMatch: TokenType,\n    nextTokIdx: number,\n    notStuck: boolean | undefined,\n  ): boolean {\n    // Edge case of arriving from a MANY repetition which is stuck\n    // Attempting recovery in this case could cause an infinite loop\n    if (notStuck === false) {\n      return false;\n    }\n\n    // no need to recover, next token is what we expect...\n    if (this.tokenMatcher(this.LA_FAST(1), expectTokAfterLastMatch)) {\n      return false;\n    }\n\n    // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path\n    // and prefer some backtracking path that includes recovered errors.\n    if (this.isBackTracking()) {\n      return false;\n    }\n\n    // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm\n    // because if it works, it makes the least amount of changes to the input stream (greedy algorithm)\n    //noinspection RedundantIfStatementJS\n    if (\n      this.canPerformInRuleRecovery(\n        expectTokAfterLastMatch,\n        this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx),\n      )\n    ) {\n      return false;\n    }\n\n    return true;\n  }\n\n  // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...\n  // TODO: should this be more explicitly part of the public API?\n  getNextPossibleTokenTypes(\n    this: MixedInParser,\n    grammarPath: ITokenGrammarPath,\n  ): TokenType[] {\n    const topRuleName = grammarPath.ruleStack[0]!;\n    const gastProductions = this.getGAstProductions();\n    const topProduction = gastProductions[topRuleName];\n    const nextPossibleTokenTypes = new NextAfterTokenWalker(\n      topProduction,\n      grammarPath,\n    ).startWalking();\n    return nextPossibleTokenTypes;\n  }\n\n  // Error Recovery functionality\n  getFollowsForInRuleRecovery(\n    this: MixedInParser,\n    tokType: TokenType,\n    tokIdxInRule: number,\n  ): TokenType[] {\n    const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);\n    const follows = this.getNextPossibleTokenTypes(grammarPath);\n    return follows;\n  }\n\n  tryInRuleRecovery(\n    this: MixedInParser,\n    expectedTokType: TokenType,\n    follows: TokenType[],\n  ): IToken {\n    if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {\n      const tokToInsert = this.getTokenToInsert(expectedTokType);\n      return tokToInsert;\n    }\n\n    if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {\n      const nextTok = this.SKIP_TOKEN();\n      this.consumeToken();\n      return nextTok;\n    }\n\n    throw new InRuleRecoveryException(\"sad sad panda\");\n  }\n\n  canPerformInRuleRecovery(\n    this: MixedInParser,\n    expectedToken: TokenType,\n    follows: TokenType[],\n  ): boolean {\n    return (\n      this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||\n      this.canRecoverWithSingleTokenDeletion(expectedToken)\n    );\n  }\n\n  canRecoverWithSingleTokenInsertion(\n    this: MixedInParser,\n    expectedTokType: TokenType,\n    follows: TokenType[],\n  ): boolean {\n    if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {\n      return false;\n    }\n\n    // must know the possible following tokens to perform single token insertion\n    if (follows.length === 0) {\n      return false;\n    }\n\n    const mismatchedTok = this.LA_FAST(1);\n    const isMisMatchedTokInFollows =\n      follows.find((possibleFollowsTokType: TokenType) => {\n        return this.tokenMatcher(mismatchedTok, possibleFollowsTokType);\n      }) !== undefined;\n\n    return isMisMatchedTokInFollows;\n  }\n\n  canRecoverWithSingleTokenDeletion(\n    this: MixedInParser,\n    expectedTokType: TokenType,\n  ): boolean {\n    if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) {\n      return false;\n    }\n\n    const isNextTokenWhatIsExpected = this.tokenMatcher(\n      // not using LA_FAST because LA(2) might be un-safe with maxLookahead=1\n      // in some edge cases (?)\n      this.LA(2),\n      expectedTokType,\n    );\n    return isNextTokenWhatIsExpected;\n  }\n\n  isInCurrentRuleReSyncSet(\n    this: MixedInParser,\n    tokenTypeIdx: TokenType,\n  ): boolean {\n    const followKey = this.getCurrFollowKey();\n    const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);\n    return currentRuleReSyncSet.includes(tokenTypeIdx);\n  }\n\n  findReSyncTokenType(this: MixedInParser): TokenType {\n    const allPossibleReSyncTokTypes = this.flattenFollowSet();\n    // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input\n    let nextToken = this.LA_FAST(1);\n    let k = 2;\n    while (true) {\n      const foundMatch = allPossibleReSyncTokTypes.find((resyncTokType) => {\n        const canMatch = tokenMatcher(nextToken, resyncTokType);\n        return canMatch;\n      });\n      if (foundMatch !== undefined) {\n        return foundMatch;\n      }\n      nextToken = this.LA(k);\n      k++;\n    }\n  }\n\n  getCurrFollowKey(this: MixedInParser): IFollowKey {\n    // the length is at least one as we always add the ruleName to the stack before invoking the rule.\n    if (this.RULE_STACK_IDX === 0) {\n      return EOF_FOLLOW_KEY;\n    }\n    const currRuleShortName = this.currRuleShortName;\n    const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();\n    const prevRuleShortName = this.getPreviousExplicitRuleShortName();\n\n    return {\n      ruleName: this.shortRuleNameToFullName(currRuleShortName),\n      idxInCallingRule: currRuleIdx,\n      inRule: this.shortRuleNameToFullName(prevRuleShortName),\n    };\n  }\n\n  buildFullFollowKeyStack(this: MixedInParser): IFollowKey[] {\n    const explicitRuleStack = this.RULE_STACK;\n    const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;\n    const len = this.RULE_STACK_IDX + 1;\n\n    const result: IFollowKey[] = new Array(len);\n    for (let idx = 0; idx < len; idx++) {\n      if (idx === 0) {\n        result[idx] = EOF_FOLLOW_KEY;\n      } else {\n        result[idx] = {\n          ruleName: this.shortRuleNameToFullName(explicitRuleStack[idx]),\n          idxInCallingRule: explicitOccurrenceStack[idx],\n          inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1]),\n        };\n      }\n    }\n    return result;\n  }\n\n  flattenFollowSet(this: MixedInParser): TokenType[] {\n    const followStack = this.buildFullFollowKeyStack().map((currKey) => {\n      return this.getFollowSetFromFollowKey(currKey);\n    });\n    return <any>followStack.flat();\n  }\n\n  getFollowSetFromFollowKey(\n    this: MixedInParser,\n    followKey: IFollowKey,\n  ): TokenType[] {\n    if (followKey === EOF_FOLLOW_KEY) {\n      return [EOF];\n    }\n\n    const followName =\n      followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule;\n\n    return this.resyncFollows[followName];\n  }\n\n  // It does not make any sense to include a virtual EOF token in the list of resynced tokens\n  // as EOF does not really exist and thus does not contain any useful information (line/column numbers)\n  addToResyncTokens(\n    this: MixedInParser,\n    token: IToken,\n    resyncTokens: IToken[],\n  ): IToken[] {\n    if (!this.tokenMatcher(token, EOF)) {\n      resyncTokens.push(token);\n    }\n    return resyncTokens;\n  }\n\n  reSyncTo(this: MixedInParser, tokType: TokenType): IToken[] {\n    const resyncedTokens: IToken[] = [];\n    let nextTok = this.LA_FAST(1);\n    while (this.tokenMatcher(nextTok, tokType) === false) {\n      nextTok = this.SKIP_TOKEN();\n      this.addToResyncTokens(nextTok, resyncedTokens);\n    }\n    // the last token is not part of the error.\n    return resyncedTokens.slice(0, -1);\n  }\n\n  attemptInRepetitionRecovery(\n    this: MixedInParser,\n    prodFunc: Function,\n    args: any[],\n    lookaheadFunc: () => boolean,\n    dslMethodIdx: number,\n    prodOccurrence: number,\n    nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n    notStuck?: boolean,\n  ): void {\n    // by default this is a NO-OP\n    // The actual implementation is with the function(not method) below\n  }\n\n  getCurrentGrammarPath(\n    this: MixedInParser,\n    tokType: TokenType,\n    tokIdxInRule: number,\n  ): ITokenGrammarPath {\n    const pathRuleStack: string[] = this.getHumanReadableRuleStack();\n    const pathOccurrenceStack: number[] = this.RULE_OCCURRENCE_STACK.slice(\n      0,\n      this.RULE_OCCURRENCE_STACK_IDX + 1,\n    );\n    const grammarPath: any = {\n      ruleStack: pathRuleStack,\n      occurrenceStack: pathOccurrenceStack,\n      lastTok: tokType,\n      lastTokOccurrence: tokIdxInRule,\n    };\n\n    return grammarPath;\n  }\n  getHumanReadableRuleStack(this: MixedInParser): string[] {\n    const len = this.RULE_STACK_IDX + 1;\n    const result: string[] = new Array(len);\n    for (let i = 0; i < len; i++) {\n      result[i] = this.shortRuleNameToFullName(this.RULE_STACK[i]);\n    }\n    return result;\n  }\n}\n\nexport function attemptInRepetitionRecovery(\n  this: MixedInParser,\n  prodFunc: Function,\n  args: any[],\n  lookaheadFunc: () => boolean,\n  dslMethodIdx: number,\n  prodOccurrence: number,\n  nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n  notStuck?: boolean,\n): void {\n  const key = dslMethodIdx | prodOccurrence;\n  const ruleCache = (this.firstAfterRepMap[this.currRuleShortName] ??= []);\n  let firstAfterRepInfo = ruleCache[key];\n  if (firstAfterRepInfo === undefined) {\n    const currRuleName = this.getCurrRuleFullName();\n    const ruleGrammar = this.getGAstProductions()[currRuleName];\n    const walker: AbstractNextTerminalAfterProductionWalker =\n      new nextToksWalker(ruleGrammar, prodOccurrence);\n    firstAfterRepInfo = walker.startWalking();\n    ruleCache[key] = firstAfterRepInfo;\n  }\n\n  let expectTokAfterLastMatch = firstAfterRepInfo.token;\n  let nextTokIdx = firstAfterRepInfo.occurrence;\n  const isEndOfRule = firstAfterRepInfo.isEndOfRule;\n\n  // special edge case of a TOP most repetition after which the input should END.\n  // this will force an attempt for inRule recovery in that scenario.\n  if (\n    this.RULE_STACK_IDX === 0 &&\n    isEndOfRule &&\n    expectTokAfterLastMatch === undefined\n  ) {\n    expectTokAfterLastMatch = EOF;\n    nextTokIdx = 1;\n  }\n\n  // We don't have anything to re-sync to...\n  // this condition was extracted from `shouldInRepetitionRecoveryBeTried` to act as a type-guard\n  if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {\n    return;\n  }\n\n  if (\n    this.shouldInRepetitionRecoveryBeTried(\n      expectTokAfterLastMatch,\n      nextTokIdx,\n      notStuck,\n    )\n  ) {\n    // TODO: performance optimization: instead of passing the original args here, we modify\n    // the args param (or create a new one) and make sure the lookahead func is explicitly provided\n    // to avoid searching the cache for it once more.\n    this.tryInRepetitionRecovery(\n      prodFunc,\n      args,\n      lookaheadFunc,\n      expectTokAfterLastMatch,\n    );\n  }\n}\n", "const BITS_FOR_OCCURRENCE_IDX = 8;\n\n// Method offsets in each rule's lookahead table. The lower 8 bits hold the\n// occurrence index.\nexport const OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;\nexport const OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;\n", "import {\n  ILookaheadStrategy,\n  ILookaheadValidationError,\n  IOrAlt,\n  OptionalProductionType,\n  Rule,\n  TokenType,\n} from \"@chevrotain/types\";\nimport { defaultGrammarValidatorErrorProvider } from \"../errors_public.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser/parser.js\";\nimport {\n  validateAmbiguousAlternationAlternatives,\n  validateEmptyOrAlternative,\n  validateNoLeftRecursion,\n  validateSomeNonEmptyLookaheadPath,\n} from \"./checks.js\";\nimport {\n  buildAlternativesLookAheadFunc,\n  buildLookaheadFuncForOptionalProd,\n  buildLookaheadFuncForOr,\n  buildSingleAlternativeLookaheadFunction,\n  getProdType,\n} from \"./lookahead.js\";\nimport { IParserDefinitionError } from \"./types.js\";\n\nexport class LLkLookaheadStrategy implements ILookaheadStrategy {\n  readonly maxLookahead: number;\n\n  constructor(options?: { maxLookahead?: number }) {\n    this.maxLookahead =\n      options?.maxLookahead ?? DEFAULT_PARSER_CONFIG.maxLookahead;\n  }\n\n  validate(options: {\n    rules: Rule[];\n    tokenTypes: TokenType[];\n    grammarName: string;\n  }): ILookaheadValidationError[] {\n    const leftRecursionErrors = this.validateNoLeftRecursion(options.rules);\n\n    if (leftRecursionErrors.length === 0) {\n      const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules);\n      const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(\n        options.rules,\n        this.maxLookahead,\n      );\n      const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(\n        options.rules,\n        this.maxLookahead,\n      );\n      const allErrors = [\n        ...leftRecursionErrors,\n        ...emptyAltErrors,\n        ...ambiguousAltsErrors,\n        ...emptyRepetitionErrors,\n      ];\n      return allErrors;\n    }\n    return leftRecursionErrors;\n  }\n\n  validateNoLeftRecursion(rules: Rule[]): IParserDefinitionError[] {\n    return rules.flatMap((currTopRule) =>\n      validateNoLeftRecursion(\n        currTopRule,\n        currTopRule,\n        defaultGrammarValidatorErrorProvider,\n      ),\n    );\n  }\n\n  validateEmptyOrAlternatives(rules: Rule[]): IParserDefinitionError[] {\n    return rules.flatMap((currTopRule) =>\n      validateEmptyOrAlternative(\n        currTopRule,\n        defaultGrammarValidatorErrorProvider,\n      ),\n    );\n  }\n\n  validateAmbiguousAlternationAlternatives(\n    rules: Rule[],\n    maxLookahead: number,\n  ): IParserDefinitionError[] {\n    return rules.flatMap((currTopRule) =>\n      validateAmbiguousAlternationAlternatives(\n        currTopRule,\n        maxLookahead,\n        defaultGrammarValidatorErrorProvider,\n      ),\n    );\n  }\n\n  validateSomeNonEmptyLookaheadPath(\n    rules: Rule[],\n    maxLookahead: number,\n  ): IParserDefinitionError[] {\n    return validateSomeNonEmptyLookaheadPath(\n      rules,\n      maxLookahead,\n      defaultGrammarValidatorErrorProvider,\n    );\n  }\n\n  buildLookaheadForAlternation(options: {\n    prodOccurrence: number;\n    rule: Rule;\n    maxLookahead: number;\n    hasPredicates: boolean;\n    dynamicTokensEnabled: boolean;\n  }): (orAlts?: IOrAlt<any>[] | undefined) => number | undefined {\n    return buildLookaheadFuncForOr(\n      options.prodOccurrence,\n      options.rule,\n      options.maxLookahead,\n      options.hasPredicates,\n      options.dynamicTokensEnabled,\n      buildAlternativesLookAheadFunc,\n    );\n  }\n\n  buildLookaheadForOptional(options: {\n    prodOccurrence: number;\n    prodType: OptionalProductionType;\n    rule: Rule;\n    maxLookahead: number;\n    dynamicTokensEnabled: boolean;\n  }): () => boolean {\n    return buildLookaheadFuncForOptionalProd(\n      options.prodOccurrence,\n      options.rule,\n      options.maxLookahead,\n      options.dynamicTokensEnabled,\n      getProdType(options.prodType),\n      buildSingleAlternativeLookaheadFunction,\n    );\n  }\n}\n", "import { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\nimport {\n  ILookaheadStrategy,\n  IParserConfig,\n  OptionalProductionType,\n} from \"@chevrotain/types\";\nimport {\n  AT_LEAST_ONE_IDX,\n  AT_LEAST_ONE_SEP_IDX,\n  MANY_IDX,\n  MANY_SEP_IDX,\n  OPTION_IDX,\n  OR_IDX,\n} from \"../../grammar/keys.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n  Alternation,\n  GAstVisitor,\n  getProductionDslName,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Rule,\n} from \"@chevrotain/gast\";\nimport { LLkLookaheadStrategy } from \"../../grammar/llk_lookahead.js\";\n\n/**\n * Trait responsible for the lookahead related utilities and optimizations.\n */\nexport class LooksAhead {\n  maxLookahead: number;\n  // Indexed by rule, then by the DSL method and occurrence local to that rule.\n  lookAheadFuncsCache: Function[][];\n  // Cached rule table for the active rule\n  currRuleLookaheadFuncs: Function[];\n  dynamicTokensEnabled: boolean;\n  lookaheadStrategy: ILookaheadStrategy;\n\n  initLooksAhead(config: IParserConfig) {\n    this.dynamicTokensEnabled = Object.hasOwn(config, \"dynamicTokensEnabled\")\n      ? (config.dynamicTokensEnabled as boolean) // assumes end user provides the correct config value/type\n      : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;\n\n    this.maxLookahead = Object.hasOwn(config, \"maxLookahead\")\n      ? (config.maxLookahead as number) // assumes end user provides the correct config value/type\n      : DEFAULT_PARSER_CONFIG.maxLookahead;\n\n    this.lookaheadStrategy = Object.hasOwn(config, \"lookaheadStrategy\")\n      ? (config.lookaheadStrategy as ILookaheadStrategy) // assumes end user provides the correct config value/type\n      : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead });\n\n    this.lookAheadFuncsCache = [];\n    this.currRuleLookaheadFuncs = [];\n  }\n\n  preComputeLookaheadFunctions(this: MixedInParser, rules: Rule[]): void {\n    rules.forEach((currRule) => {\n      this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => {\n        const {\n          alternation,\n          repetition,\n          option,\n          repetitionMandatory,\n          repetitionMandatoryWithSeparator,\n          repetitionWithSeparator,\n        } = collectMethods(currRule);\n\n        alternation.forEach((currProd) => {\n          const prodIdx = currProd.idx === 0 ? \"\" : currProd.idx;\n          this.TRACE_INIT(`${getProductionDslName(currProd)}${prodIdx}`, () => {\n            const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({\n              prodOccurrence: currProd.idx,\n              rule: currRule,\n              maxLookahead: currProd.maxLookahead || this.maxLookahead,\n              hasPredicates: currProd.hasPredicates,\n              dynamicTokensEnabled: this.dynamicTokensEnabled,\n            });\n\n            this.setLaFuncCache(\n              this.fullRuleNameToShort[currRule.name],\n              OR_IDX | currProd.idx,\n              laFunc,\n            );\n          });\n        });\n\n        repetition.forEach((currProd) => {\n          this.computeLookaheadFunc(\n            currRule,\n            currProd.idx,\n            MANY_IDX,\n            \"Repetition\",\n            currProd.maxLookahead,\n            getProductionDslName(currProd),\n          );\n        });\n\n        option.forEach((currProd) => {\n          this.computeLookaheadFunc(\n            currRule,\n            currProd.idx,\n            OPTION_IDX,\n            \"Option\",\n            currProd.maxLookahead,\n            getProductionDslName(currProd),\n          );\n        });\n\n        repetitionMandatory.forEach((currProd) => {\n          this.computeLookaheadFunc(\n            currRule,\n            currProd.idx,\n            AT_LEAST_ONE_IDX,\n            \"RepetitionMandatory\",\n            currProd.maxLookahead,\n            getProductionDslName(currProd),\n          );\n        });\n\n        repetitionMandatoryWithSeparator.forEach((currProd) => {\n          this.computeLookaheadFunc(\n            currRule,\n            currProd.idx,\n            AT_LEAST_ONE_SEP_IDX,\n            \"RepetitionMandatoryWithSeparator\",\n            currProd.maxLookahead,\n            getProductionDslName(currProd),\n          );\n        });\n\n        repetitionWithSeparator.forEach((currProd) => {\n          this.computeLookaheadFunc(\n            currRule,\n            currProd.idx,\n            MANY_SEP_IDX,\n            \"RepetitionWithSeparator\",\n            currProd.maxLookahead,\n            getProductionDslName(currProd),\n          );\n        });\n      });\n    });\n  }\n\n  computeLookaheadFunc(\n    this: MixedInParser,\n    rule: Rule,\n    prodOccurrence: number,\n    prodKey: number,\n    prodType: OptionalProductionType,\n    prodMaxLookahead: number | undefined,\n    dslMethodName: string,\n  ): void {\n    this.TRACE_INIT(\n      `${dslMethodName}${prodOccurrence === 0 ? \"\" : prodOccurrence}`,\n      () => {\n        const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({\n          prodOccurrence,\n          rule,\n          maxLookahead: prodMaxLookahead || this.maxLookahead,\n          dynamicTokensEnabled: this.dynamicTokensEnabled,\n          prodType,\n        });\n        this.setLaFuncCache(\n          this.fullRuleNameToShort[rule.name],\n          prodKey | prodOccurrence,\n          laFunc,\n        );\n      },\n    );\n  }\n\n  setLaFuncCache(\n    this: MixedInParser,\n    ruleIdx: number,\n    key: number,\n    value: Function,\n  ): void {\n    let ruleLookaheadFuncs = this.lookAheadFuncsCache[ruleIdx];\n    if (ruleLookaheadFuncs === undefined) {\n      ruleLookaheadFuncs = [];\n      this.lookAheadFuncsCache[ruleIdx] = ruleLookaheadFuncs;\n    }\n    ruleLookaheadFuncs[key] = value;\n  }\n}\n\nclass DslMethodsCollectorVisitor extends GAstVisitor {\n  public dslMethods: {\n    option: Option[];\n    alternation: Alternation[];\n    repetition: Repetition[];\n    repetitionWithSeparator: RepetitionWithSeparator[];\n    repetitionMandatory: RepetitionMandatory[];\n    repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n  } = {\n    option: [],\n    alternation: [],\n    repetition: [],\n    repetitionWithSeparator: [],\n    repetitionMandatory: [],\n    repetitionMandatoryWithSeparator: [],\n  };\n\n  reset() {\n    this.dslMethods = {\n      option: [],\n      alternation: [],\n      repetition: [],\n      repetitionWithSeparator: [],\n      repetitionMandatory: [],\n      repetitionMandatoryWithSeparator: [],\n    };\n  }\n\n  public visitOption(option: Option): void {\n    this.dslMethods.option.push(option);\n  }\n\n  public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n    this.dslMethods.repetitionWithSeparator.push(manySep);\n  }\n\n  public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n    this.dslMethods.repetitionMandatory.push(atLeastOne);\n  }\n\n  public visitRepetitionMandatoryWithSeparator(\n    atLeastOneSep: RepetitionMandatoryWithSeparator,\n  ): void {\n    this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);\n  }\n\n  public visitRepetition(many: Repetition): void {\n    this.dslMethods.repetition.push(many);\n  }\n\n  public visitAlternation(or: Alternation): void {\n    this.dslMethods.alternation.push(or);\n  }\n}\n\nconst collectorVisitor = new DslMethodsCollectorVisitor();\nexport function collectMethods(rule: Rule): {\n  option: Option[];\n  alternation: Alternation[];\n  repetition: Repetition[];\n  repetitionWithSeparator: RepetitionWithSeparator[];\n  repetitionMandatory: RepetitionMandatory[];\n  repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n} {\n  collectorVisitor.reset();\n  rule.accept(collectorVisitor);\n  const dslMethods = collectorVisitor.dslMethods;\n  // avoid uncleaned references\n  collectorVisitor.reset();\n  return <any>dslMethods;\n}\n", "import { CstNode, CstNodeLocation, IToken } from \"@chevrotain/types\";\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationOnlyOffset(\n  currNodeLocation: CstNodeLocation,\n  newLocationInfo: Required<Pick<IToken, \"startOffset\" | \"endOffset\">>,\n): void {\n  // First (valid) update for this cst node\n  if (currNodeLocation.startOffset === -1) {\n    // assumption1: Token location information is either invalid or a valid number\n    // assumption2: Token location information is fully valid if it exist\n    // (both start/end offsets exist and are numbers).\n    currNodeLocation.startOffset = newLocationInfo.startOffset;\n    currNodeLocation.endOffset = newLocationInfo.endOffset;\n  }\n  // Once the startOffset has been updated with a valid number it should never receive\n  // any farther updates as the Token vector is sorted.\n  // We still have to check this this condition for every new possible location info\n  // because with error recovery enabled we may encounter invalid token locations.\n  else if (currNodeLocation.endOffset! < newLocationInfo.endOffset === true) {\n    currNodeLocation.endOffset = newLocationInfo.endOffset;\n  }\n}\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationFull(\n  currNodeLocation: CstNodeLocation,\n  newLocationInfo: CstNodeLocation,\n): void {\n  // First (valid) update for this cst node\n  if (currNodeLocation.startOffset === -1) {\n    // assumption1: Token location information is either invalid or a valid number\n    // assumption2: Token location information is fully valid if it exist\n    // (all start/end props exist and are numbers).\n    currNodeLocation.startOffset = newLocationInfo.startOffset;\n    currNodeLocation.startColumn = newLocationInfo.startColumn;\n    currNodeLocation.startLine = newLocationInfo.startLine;\n    currNodeLocation.endOffset = newLocationInfo.endOffset;\n    currNodeLocation.endColumn = newLocationInfo.endColumn;\n    currNodeLocation.endLine = newLocationInfo.endLine;\n  }\n  // Once the start props has been updated with a valid number it should never receive\n  // any farther updates as the Token vector is sorted.\n  // We still have to check this this condition for every new possible location info\n  // because with error recovery enabled we may encounter invalid token locations.\n  else if (currNodeLocation.endOffset! < newLocationInfo.endOffset! === true) {\n    currNodeLocation.endOffset = newLocationInfo.endOffset;\n    currNodeLocation.endColumn = newLocationInfo.endColumn;\n    currNodeLocation.endLine = newLocationInfo.endLine;\n  }\n}\n\nexport function addTerminalToCst(\n  node: CstNode,\n  token: IToken,\n  tokenTypeName: string,\n): void {\n  if (node.children[tokenTypeName] === undefined) {\n    node.children[tokenTypeName] = [token];\n  } else {\n    node.children[tokenTypeName].push(token);\n  }\n}\n\nexport function addNoneTerminalToCst(\n  node: CstNode,\n  ruleName: string,\n  ruleResult: any,\n): void {\n  if (node.children[ruleName] === undefined) {\n    node.children[ruleName] = [ruleResult];\n  } else {\n    node.children[ruleName].push(ruleResult);\n  }\n}\n", "const NAME = \"name\";\n\nexport function defineNameProp(obj: {}, nameValue: string): void {\n  Object.defineProperty(obj, NAME, {\n    enumerable: false,\n    configurable: true,\n    writable: false,\n    value: nameValue,\n  });\n}\n", "import { defineNameProp } from \"../../lang/lang_extensions.js\";\nimport { CstNode, ICstVisitor } from \"@chevrotain/types\";\n\nexport function defaultVisit<IN>(ctx: any, param: IN): void {\n  const childrenNames = Object.keys(ctx);\n  const childrenNamesLength = childrenNames.length;\n  for (let i = 0; i < childrenNamesLength; i++) {\n    const currChildName = childrenNames[i];\n    const currChildArray = ctx[currChildName];\n    const currChildArrayLength = currChildArray.length;\n    for (let j = 0; j < currChildArrayLength; j++) {\n      const currChild: any = currChildArray[j];\n      // distinction between Tokens Children and CstNode children\n      if (currChild.tokenTypeIdx === undefined) {\n        this[currChild.name](currChild.children, param);\n      }\n    }\n  }\n  // defaultVisit does not support generic out param\n}\n\nexport function createBaseSemanticVisitorConstructor(\n  grammarName: string,\n  ruleNames: string[],\n): {\n  new (...args: any[]): ICstVisitor<any, any>;\n} {\n  const derivedConstructor: any = function () {};\n\n  // can be overwritten according to:\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n  // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n  defineNameProp(derivedConstructor, grammarName + \"BaseSemantics\");\n\n  const semanticProto = {\n    visit: function (cstNode: CstNode | CstNode[], param: any) {\n      // enables writing more concise visitor methods when CstNode has only a single child\n      if (Array.isArray(cstNode)) {\n        // A CST Node's children dictionary can never have empty arrays as values\n        // If a key is defined there will be at least one element in the corresponding value array.\n        cstNode = cstNode[0];\n      }\n\n      // enables passing optional CstNodes concisely.\n      if (cstNode === undefined) {\n        return undefined;\n      }\n\n      return this[cstNode.name](cstNode.children, param);\n    },\n\n    validateVisitor: function () {\n      const semanticDefinitionErrors = validateVisitor(this, ruleNames);\n      if (semanticDefinitionErrors.length !== 0) {\n        const errorMessages = semanticDefinitionErrors.map(\n          (currDefError) => currDefError.msg,\n        );\n        throw Error(\n          `Errors Detected in CST Visitor <${this.constructor.name}>:\\n\\t` +\n            `${errorMessages.join(\"\\n\\n\").replace(/\\n/g, \"\\n\\t\")}`,\n        );\n      }\n    },\n  };\n\n  derivedConstructor.prototype = semanticProto;\n  derivedConstructor.prototype.constructor = derivedConstructor;\n\n  derivedConstructor._RULE_NAMES = ruleNames;\n\n  return derivedConstructor;\n}\n\nexport function createBaseVisitorConstructorWithDefaults(\n  grammarName: string,\n  ruleNames: string[],\n  baseConstructor: Function,\n): {\n  new (...args: any[]): ICstVisitor<any, any>;\n} {\n  const derivedConstructor: any = function () {};\n\n  // can be overwritten according to:\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n  // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n  defineNameProp(derivedConstructor, grammarName + \"BaseSemanticsWithDefaults\");\n\n  const withDefaultsProto = Object.create(baseConstructor.prototype);\n  ruleNames.forEach((ruleName) => {\n    withDefaultsProto[ruleName] = defaultVisit;\n  });\n\n  derivedConstructor.prototype = withDefaultsProto;\n  derivedConstructor.prototype.constructor = derivedConstructor;\n\n  return derivedConstructor;\n}\n\nexport enum CstVisitorDefinitionError {\n  REDUNDANT_METHOD,\n  MISSING_METHOD,\n}\n\nexport interface IVisitorDefinitionError {\n  msg: string;\n  type: CstVisitorDefinitionError;\n  methodName: string;\n}\n\nexport function validateVisitor(\n  visitorInstance: ICstVisitor<unknown, unknown>,\n  ruleNames: string[],\n): IVisitorDefinitionError[] {\n  const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);\n\n  return missingErrors;\n}\n\nexport function validateMissingCstMethods(\n  visitorInstance: ICstVisitor<unknown, unknown>,\n  ruleNames: string[],\n): IVisitorDefinitionError[] {\n  const missingRuleNames = ruleNames.filter((currRuleName) => {\n    return (\n      (typeof (visitorInstance as any)[currRuleName] === \"function\") === false\n    );\n  });\n\n  const errors: IVisitorDefinitionError[] = missingRuleNames.map(\n    (currRuleName) => {\n      return {\n        msg: `Missing visitor method: <${currRuleName}> on ${<any>(\n          visitorInstance.constructor.name\n        )} CST Visitor.`,\n        type: CstVisitorDefinitionError.MISSING_METHOD,\n        methodName: currRuleName,\n      };\n    },\n  );\n\n  return errors.filter(Boolean) as IVisitorDefinitionError[];\n}\n", "import {\n  addNoneTerminalToCst,\n  addTerminalToCst,\n  setNodeLocationFull,\n  setNodeLocationOnlyOffset,\n} from \"../../cst/cst.js\";\nimport {\n  createBaseSemanticVisitorConstructor,\n  createBaseVisitorConstructorWithDefaults,\n} from \"../../cst/cst_visitor.js\";\nimport {\n  CstNode,\n  CstNodeLocation,\n  ICstVisitor,\n  IParserConfig,\n  IToken,\n  nodeLocationTrackingOptions,\n} from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * This trait is responsible for the CST building logic.\n */\nexport class TreeBuilder {\n  outputCst: boolean;\n  CST_STACK: CstNode[];\n  baseCstVisitorConstructor: Function;\n  baseCstVisitorWithDefaultsConstructor: Function;\n\n  // dynamically assigned Methods\n  setNodeLocationFromNode: (\n    nodeLocation: CstNodeLocation,\n    locationInformation: CstNodeLocation,\n  ) => void;\n  setNodeLocationFromToken: (\n    nodeLocation: CstNodeLocation,\n    locationInformation: CstNodeLocation,\n  ) => void;\n  cstPostRule: (this: MixedInParser, ruleCstNode: CstNode) => void;\n\n  setInitialNodeLocation: (cstNode: CstNode) => void;\n  nodeLocationTracking: nodeLocationTrackingOptions;\n\n  initTreeBuilder(this: MixedInParser, config: IParserConfig) {\n    this.CST_STACK = [];\n\n    // outputCst is no longer exposed/defined in the pubic API\n    this.outputCst = (config as any).outputCst;\n\n    this.nodeLocationTracking = Object.hasOwn(config, \"nodeLocationTracking\")\n      ? (config.nodeLocationTracking as nodeLocationTrackingOptions) // assumes end user provides the correct config value/type\n      : DEFAULT_PARSER_CONFIG.nodeLocationTracking;\n\n    if (!this.outputCst) {\n      this.cstInvocationStateUpdate = () => {};\n      this.cstFinallyStateUpdate = () => {};\n      this.cstPostTerminal = () => {};\n      this.cstPostNonTerminal = () => {};\n      this.cstPostRule = () => {};\n    } else {\n      if (/full/i.test(this.nodeLocationTracking)) {\n        if (this.recoveryEnabled) {\n          this.setNodeLocationFromToken = setNodeLocationFull;\n          this.setNodeLocationFromNode = setNodeLocationFull;\n          this.cstPostRule = () => {};\n          this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;\n        } else {\n          this.setNodeLocationFromToken = () => {};\n          this.setNodeLocationFromNode = () => {};\n          this.cstPostRule = this.cstPostRuleFull;\n          this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;\n        }\n      } else if (/onlyOffset/i.test(this.nodeLocationTracking)) {\n        if (this.recoveryEnabled) {\n          this.setNodeLocationFromToken = <any>setNodeLocationOnlyOffset;\n          this.setNodeLocationFromNode = <any>setNodeLocationOnlyOffset;\n          this.cstPostRule = () => {};\n          this.setInitialNodeLocation =\n            this.setInitialNodeLocationOnlyOffsetRecovery;\n        } else {\n          this.setNodeLocationFromToken = () => {};\n          this.setNodeLocationFromNode = () => {};\n          this.cstPostRule = this.cstPostRuleOnlyOffset;\n          this.setInitialNodeLocation =\n            this.setInitialNodeLocationOnlyOffsetRegular;\n        }\n      } else if (/none/i.test(this.nodeLocationTracking)) {\n        this.setNodeLocationFromToken = () => {};\n        this.setNodeLocationFromNode = () => {};\n        this.cstPostRule = () => {};\n        this.setInitialNodeLocation = () => {};\n      } else {\n        throw Error(\n          `Invalid <nodeLocationTracking> config option: \"${config.nodeLocationTracking}\"`,\n        );\n      }\n    }\n  }\n\n  setInitialNodeLocationOnlyOffsetRecovery(\n    this: MixedInParser,\n    cstNode: any,\n  ): void {\n    cstNode.location = {\n      startOffset: -1,\n      endOffset: -1,\n    };\n  }\n\n  setInitialNodeLocationOnlyOffsetRegular(\n    this: MixedInParser,\n    cstNode: any,\n  ): void {\n    cstNode.location = {\n      // without error recovery the starting Location of a new CstNode is guaranteed\n      // To be the next Token's startOffset (for valid inputs).\n      // For invalid inputs there won't be any CSTOutput so this potential\n      // inaccuracy does not matter\n      startOffset: this.LA_FAST(1).startOffset,\n      endOffset: -1,\n    };\n  }\n\n  setInitialNodeLocationFullRecovery(this: MixedInParser, cstNode: any): void {\n    cstNode.location = {\n      startOffset: -1,\n      startLine: -1,\n      startColumn: -1,\n      endOffset: -1,\n      endLine: -1,\n      endColumn: -1,\n    };\n  }\n\n  /**\n     *  @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work\n\n     * @param cstNode\n     */\n  setInitialNodeLocationFullRegular(this: MixedInParser, cstNode: any): void {\n    const nextToken = this.LA_FAST(1);\n    cstNode.location = {\n      startOffset: nextToken.startOffset,\n      startLine: nextToken.startLine,\n      startColumn: nextToken.startColumn,\n      endOffset: -1,\n      endLine: -1,\n      endColumn: -1,\n    };\n  }\n\n  cstInvocationStateUpdate(this: MixedInParser, fullRuleName: string): void {\n    const cstNode: CstNode = {\n      name: fullRuleName,\n      children: Object.create(null),\n    };\n\n    this.setInitialNodeLocation(cstNode);\n    this.CST_STACK.push(cstNode);\n  }\n\n  cstFinallyStateUpdate(this: MixedInParser): void {\n    this.CST_STACK.pop();\n  }\n\n  cstPostRuleFull(this: MixedInParser, ruleCstNode: CstNode): void {\n    // casts to `required<CstNodeLocation>` are safe because `cstPostRuleFull` should only be invoked when full location is enabled\n    // TODO(perf): can we replace this with LA_FAST?\n    //       edge case is the empty CstNode on first rule invocation.\n    //       perhaps create a test case to verify correctness of LA vs LA_FAST in this scenario?\n    const prevToken = this.LA(0) as Required<CstNodeLocation>;\n    const loc = ruleCstNode.location as Required<CstNodeLocation>;\n\n    // If this condition is true it means we consumed at least one Token\n    // In this CstNode.\n    if (\n      loc.startOffset !== -1 &&\n      loc.startOffset <= prevToken.startOffset === true\n    ) {\n      loc.endOffset = prevToken.endOffset;\n      loc.endLine = prevToken.endLine;\n      loc.endColumn = prevToken.endColumn;\n    }\n    // \"empty\" CstNode edge case\n    else {\n      loc.startOffset = -1;\n      loc.startLine = -1;\n      loc.startColumn = -1;\n    }\n  }\n\n  cstPostRuleOnlyOffset(this: MixedInParser, ruleCstNode: CstNode): void {\n    // TODO: can we replace this with LA_FAST? see comment in `cstPostRuleFull()`\n    const prevToken = this.LA(0);\n    // `location' is not null because `cstPostRuleOnlyOffset` will only be invoked when location tracking is enabled.\n    const loc = ruleCstNode.location!;\n\n    // If this condition is true it means we consumed at least one Token\n    // In this CstNode.\n    if (\n      loc.startOffset !== -1 &&\n      loc.startOffset <= prevToken.startOffset === true\n    ) {\n      loc.endOffset = prevToken.endOffset;\n    }\n    // \"empty\" CstNode edge case\n    else {\n      loc.startOffset = -1;\n    }\n  }\n\n  cstPostTerminal(\n    this: MixedInParser,\n    key: string,\n    consumedToken: IToken,\n  ): void {\n    const rootCst = this.CST_STACK[this.CST_STACK.length - 1];\n    addTerminalToCst(rootCst, consumedToken, key);\n    // This is only used when **both** error recovery and CST Output are enabled.\n    this.setNodeLocationFromToken(rootCst.location!, <any>consumedToken);\n  }\n\n  cstPostNonTerminal(\n    this: MixedInParser,\n    ruleCstResult: CstNode,\n    ruleName: string,\n  ): void {\n    const preCstNode = this.CST_STACK[this.CST_STACK.length - 1];\n    addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult);\n    // This is only used when **both** error recovery and CST Output are enabled.\n    this.setNodeLocationFromNode(preCstNode.location!, ruleCstResult.location!);\n  }\n\n  get currCSTNode(): CstNode {\n    // casting to unknown because: `TS2784: get and set accessors cannot declare this parameters.`\n    const mixedIn = this as unknown as MixedInParser;\n    return mixedIn.CST_STACK[mixedIn.CST_STACK.length - 1];\n  }\n\n  getBaseCstVisitorConstructor<IN = any, OUT = any>(\n    this: MixedInParser,\n  ): {\n    new (...args: any[]): ICstVisitor<IN, OUT>;\n  } {\n    if (this.baseCstVisitorConstructor === undefined) {\n      const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(\n        this.className,\n        Object.keys(this.gastProductionsCache),\n      );\n      this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;\n      return newBaseCstVisitorConstructor;\n    }\n\n    return <any>this.baseCstVisitorConstructor;\n  }\n\n  getBaseCstVisitorConstructorWithDefaults<IN = any, OUT = any>(\n    this: MixedInParser,\n  ): {\n    new (...args: any[]): ICstVisitor<IN, OUT>;\n  } {\n    if (this.baseCstVisitorWithDefaultsConstructor === undefined) {\n      const newConstructor = createBaseVisitorConstructorWithDefaults(\n        this.className,\n        Object.keys(this.gastProductionsCache),\n        this.getBaseCstVisitorConstructor(),\n      );\n      this.baseCstVisitorWithDefaultsConstructor = newConstructor;\n      return newConstructor;\n    }\n\n    return <any>this.baseCstVisitorWithDefaultsConstructor;\n  }\n\n  getPreviousExplicitRuleShortName(this: MixedInParser): number {\n    return this.RULE_STACK[this.RULE_STACK_IDX - 1];\n  }\n\n  getLastExplicitRuleOccurrenceIndex(this: MixedInParser): number {\n    return this.RULE_OCCURRENCE_STACK[this.RULE_OCCURRENCE_STACK_IDX];\n  }\n}\n", "import { END_OF_FILE } from \"../parser.js\";\nimport { IToken } from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\n\n/**\n * Trait responsible abstracting over the interaction with Lexer output (Token vector).\n *\n * This could be generalized to support other kinds of lexers, e.g.\n * - Just in Time Lexing / Lexer-Less parsing.\n * - Streaming Lexer.\n */\nexport class LexerAdapter {\n  tokVector: IToken[];\n  tokVectorLength: number;\n  currIdx: number;\n\n  initLexerAdapter() {\n    this.tokVector = [];\n    this.tokVectorLength = 0;\n    this.currIdx = -1;\n  }\n\n  set input(newInput: IToken[]) {\n    // @ts-ignore - `this parameter` not supported in setters/getters\n    //   - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n    if (this.selfAnalysisDone !== true) {\n      throw Error(\n        `Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.`,\n      );\n    }\n    // @ts-ignore - `this parameter` not supported in setters/getters\n    //   - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n    this.reset();\n    this.tokVector = newInput;\n    this.tokVectorLength = newInput.length;\n  }\n\n  get input(): IToken[] {\n    return this.tokVector;\n  }\n\n  // skips a token and returns the next token\n  SKIP_TOKEN(this: MixedInParser): IToken {\n    if (this.currIdx <= this.tokVectorLength - 2) {\n      this.consumeToken();\n      return this.LA_FAST(1);\n    } else {\n      return END_OF_FILE;\n    }\n  }\n\n  // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers\n  // or lexers dependent on parser context.\n\n  // Performance Optimized version of LA without bound checks\n  // note that token beyond the end of the token vector EOF Token will still be returned\n  // due to using sentinels at the end of the token vector. (for K=max lookahead)\n  LA_FAST(this: MixedInParser, howMuch: number): IToken {\n    const soughtIdx = this.currIdx + howMuch;\n    return this.tokVector[soughtIdx];\n  }\n\n  LA(this: MixedInParser, howMuch: number): IToken {\n    const soughtIdx = this.currIdx + howMuch;\n    if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {\n      return END_OF_FILE;\n    } else {\n      return this.tokVector[soughtIdx];\n    }\n  }\n\n  consumeToken(this: MixedInParser) {\n    this.currIdx++;\n  }\n\n  exportLexerState(this: MixedInParser): number {\n    return this.currIdx;\n  }\n\n  importLexerState(this: MixedInParser, newState: number) {\n    this.currIdx = newState;\n  }\n\n  resetLexerState(this: MixedInParser): void {\n    this.currIdx = -1;\n  }\n\n  moveToTerminatedState(this: MixedInParser): void {\n    this.currIdx = this.tokVectorLength - 1;\n  }\n\n  getLexerPosition(this: MixedInParser): number {\n    return this.exportLexerState();\n  }\n}\n", "import {\n  AtLeastOneSepMethodOpts,\n  ConsumeMethodOpts,\n  DSLMethodOpts,\n  DSLMethodOptsWithErr,\n  GrammarAction,\n  InferOr,\n  IOrAlt,\n  IRuleConfig,\n  ISerializedGast,\n  IToken,\n  ManySepMethodOpts,\n  OrMethodOpts,\n  SubruleMethodOpts,\n  TokenType,\n} from \"@chevrotain/types\";\nimport { isRecognitionException } from \"../../exceptions_public.js\";\nimport { DEFAULT_RULE_CONFIG, ParserDefinitionErrorType } from \"../parser.js\";\nimport { defaultGrammarValidatorErrorProvider } from \"../../errors_public.js\";\nimport { validateRuleIsOverridden } from \"../../grammar/checks.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { Rule, serializeGrammar } from \"@chevrotain/gast\";\nimport { IParserDefinitionError } from \"../../grammar/types.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for implementing the public API\n * for defining Chevrotain parsers, i.e:\n * - CONSUME\n * - RULE\n * - OPTION\n * - ...\n */\nexport class RecognizerApi {\n  ACTION<T>(this: MixedInParser, impl: () => T): T {\n    return impl.call(this);\n  }\n\n  consume(\n    this: MixedInParser,\n    idx: number,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, idx, options);\n  }\n\n  subrule<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    idx: number,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, idx, options);\n  }\n\n  option<OUT>(\n    this: MixedInParser,\n    idx: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, idx);\n  }\n\n  or<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    idx: number,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      idx,\n    );\n  }\n\n  many<OUT>(\n    this: MixedInParser,\n    idx: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    return this.manyInternal(idx, actionORMethodDef);\n  }\n\n  atLeastOne<OUT>(\n    this: MixedInParser,\n    idx: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    return this.atLeastOneInternal(idx, actionORMethodDef);\n  }\n\n  CONSUME(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 0, options);\n  }\n\n  CONSUME1(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 1, options);\n  }\n\n  CONSUME2(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 2, options);\n  }\n\n  CONSUME3(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 3, options);\n  }\n\n  CONSUME4(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 4, options);\n  }\n\n  CONSUME5(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 5, options);\n  }\n\n  CONSUME6(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 6, options);\n  }\n\n  CONSUME7(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 7, options);\n  }\n\n  CONSUME8(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 8, options);\n  }\n\n  CONSUME9(\n    this: MixedInParser,\n    tokType: TokenType,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    return this.consumeInternal(tokType, 9, options);\n  }\n\n  SUBRULE<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 0, options);\n  }\n\n  SUBRULE1<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 1, options);\n  }\n\n  SUBRULE2<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 2, options);\n  }\n\n  SUBRULE3<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 3, options);\n  }\n\n  SUBRULE4<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 4, options);\n  }\n\n  SUBRULE5<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 5, options);\n  }\n\n  SUBRULE6<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 6, options);\n  }\n\n  SUBRULE7<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 7, options);\n  }\n\n  SUBRULE8<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 8, options);\n  }\n\n  SUBRULE9<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    return this.subruleInternal(ruleToCall, 9, options);\n  }\n\n  OPTION<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 0);\n  }\n\n  OPTION1<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 1);\n  }\n\n  OPTION2<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 2);\n  }\n\n  OPTION3<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 3);\n  }\n\n  OPTION4<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 4);\n  }\n\n  OPTION5<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 5);\n  }\n\n  OPTION6<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 6);\n  }\n\n  OPTION7<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 7);\n  }\n\n  OPTION8<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 8);\n  }\n\n  OPTION9<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): OUT | undefined {\n    return this.optionInternal(actionORMethodDef, 9);\n  }\n\n  OR<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      0,\n    );\n  }\n\n  OR1<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      1,\n    );\n  }\n\n  OR2<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      2,\n    );\n  }\n\n  OR3<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      3,\n    );\n  }\n\n  OR4<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      4,\n    );\n  }\n\n  OR5<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      5,\n    );\n  }\n\n  OR6<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      6,\n    );\n  }\n\n  OR7<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      7,\n    );\n  }\n\n  OR8<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      8,\n    );\n  }\n\n  OR9<Alts extends readonly IOrAlt<any>[]>(\n    this: MixedInParser,\n    altsOrOpts: [...Alts] | OrMethodOpts<unknown>,\n  ): InferOr<Alts> {\n    return this.orInternal(\n      altsOrOpts as IOrAlt<any>[] | OrMethodOpts<unknown>,\n      9,\n    );\n  }\n\n  MANY<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(0, actionORMethodDef);\n  }\n\n  MANY1<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(1, actionORMethodDef);\n  }\n\n  MANY2<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(2, actionORMethodDef);\n  }\n\n  MANY3<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(3, actionORMethodDef);\n  }\n\n  MANY4<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(4, actionORMethodDef);\n  }\n\n  MANY5<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(5, actionORMethodDef);\n  }\n\n  MANY6<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(6, actionORMethodDef);\n  }\n\n  MANY7<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(7, actionORMethodDef);\n  }\n\n  MANY8<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(8, actionORMethodDef);\n  }\n\n  MANY9<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    this.manyInternal(9, actionORMethodDef);\n  }\n\n  MANY_SEP<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(0, options);\n  }\n\n  MANY_SEP1<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(1, options);\n  }\n\n  MANY_SEP2<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(2, options);\n  }\n\n  MANY_SEP3<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(3, options);\n  }\n\n  MANY_SEP4<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(4, options);\n  }\n\n  MANY_SEP5<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(5, options);\n  }\n\n  MANY_SEP6<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(6, options);\n  }\n\n  MANY_SEP7<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(7, options);\n  }\n\n  MANY_SEP8<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(8, options);\n  }\n\n  MANY_SEP9<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n    this.manySepFirstInternal(9, options);\n  }\n\n  AT_LEAST_ONE<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(0, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE1<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    return this.atLeastOneInternal(1, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE2<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(2, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE3<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(3, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE4<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(4, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE5<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(5, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE6<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(6, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE7<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(7, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE8<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(8, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE9<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    this.atLeastOneInternal(9, actionORMethodDef);\n  }\n\n  AT_LEAST_ONE_SEP<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(0, options);\n  }\n\n  AT_LEAST_ONE_SEP1<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(1, options);\n  }\n\n  AT_LEAST_ONE_SEP2<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(2, options);\n  }\n\n  AT_LEAST_ONE_SEP3<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(3, options);\n  }\n\n  AT_LEAST_ONE_SEP4<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(4, options);\n  }\n\n  AT_LEAST_ONE_SEP5<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(5, options);\n  }\n\n  AT_LEAST_ONE_SEP6<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(6, options);\n  }\n\n  AT_LEAST_ONE_SEP7<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(7, options);\n  }\n\n  AT_LEAST_ONE_SEP8<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(8, options);\n  }\n\n  AT_LEAST_ONE_SEP9<OUT>(\n    this: MixedInParser,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    this.atLeastOneSepFirstInternal(9, options);\n  }\n\n  RULE<T>(\n    this: MixedInParser,\n    name: string,\n    implementation: (...implArgs: any[]) => T,\n    config: IRuleConfig<T> = DEFAULT_RULE_CONFIG,\n  ): ParserMethodInternal<any[], T> {\n    if (this.definedRulesNames.includes(name)) {\n      const errMsg =\n        defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({\n          topLevelRule: name,\n          grammarName: this.className,\n        });\n\n      const error = {\n        message: errMsg,\n        type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n        ruleName: name,\n      };\n      this.definitionErrors.push(error);\n    }\n\n    this.definedRulesNames.push(name);\n\n    const ruleImplementation = this.defineRule(name, implementation, config);\n    (this as any)[name] = ruleImplementation;\n    return ruleImplementation;\n  }\n\n  OVERRIDE_RULE<T>(\n    this: MixedInParser,\n    name: string,\n    impl: (...implArgs: any[]) => T,\n    config: IRuleConfig<T> = DEFAULT_RULE_CONFIG,\n  ): ParserMethodInternal<any[], T> {\n    const ruleErrors: IParserDefinitionError[] = validateRuleIsOverridden(\n      name,\n      this.definedRulesNames,\n      this.className,\n    );\n    this.definitionErrors = this.definitionErrors.concat(ruleErrors);\n\n    const ruleImplementation = this.defineRule(name, impl, config);\n    (this as any)[name] = ruleImplementation;\n    return ruleImplementation;\n  }\n\n  BACKTRACK<ARGS extends unknown[], T>(\n    this: MixedInParser,\n    grammarRule: (...args: ARGS) => T,\n    args?: ARGS,\n  ): () => boolean {\n    // Use coreRule to bypass root-level hooks (onBeforeParse/onAfterParse).\n    // Backtracking is speculative and should not trigger parse lifecycle hooks.\n    const ruleToCall = (grammarRule as any).coreRule ?? grammarRule;\n    return function () {\n      // save org state\n      this.isBackTrackingStack.push(1);\n      const orgState = this.saveRecogState();\n      try {\n        ruleToCall.apply(this, args);\n        // if no exception was thrown we have succeed parsing the rule.\n        return true;\n      } catch (e) {\n        if (isRecognitionException(e)) {\n          return false;\n        } else {\n          throw e;\n        }\n      } finally {\n        this.reloadRecogState(orgState);\n        this.isBackTrackingStack.pop();\n      }\n    };\n  }\n\n  // GAST export APIs\n  public getGAstProductions(this: MixedInParser): Record<string, Rule> {\n    return this.gastProductionsCache;\n  }\n\n  public getSerializedGastProductions(this: MixedInParser): ISerializedGast[] {\n    return serializeGrammar(Object.values(this.gastProductionsCache));\n  }\n}\n", "import {\n  AtLeastOneSepMethodOpts,\n  ConsumeMethodOpts,\n  DSLMethodOpts,\n  DSLMethodOptsWithErr,\n  GrammarAction,\n  IOrAlt,\n  IParserConfig,\n  IRuleConfig,\n  IToken,\n  ManySepMethodOpts,\n  OrMethodOpts,\n  ParserMethod,\n  SubruleMethodOpts,\n  TokenType,\n  TokenTypeDictionary,\n  TokenVocabulary,\n} from \"@chevrotain/types\";\n\nimport {\n  AT_LEAST_ONE_IDX,\n  AT_LEAST_ONE_SEP_IDX,\n  MANY_IDX,\n  MANY_SEP_IDX,\n  OPTION_IDX,\n  OR_IDX,\n} from \"../../grammar/keys.js\";\nimport {\n  isRecognitionException,\n  MismatchedTokenException,\n  NotAllInputParsedException,\n} from \"../../exceptions_public.js\";\nimport { PROD_TYPE } from \"../../grammar/lookahead.js\";\nimport {\n  AbstractNextTerminalAfterProductionWalker,\n  NextTerminalAfterAtLeastOneSepWalker,\n  NextTerminalAfterAtLeastOneWalker,\n  NextTerminalAfterManySepWalker,\n  NextTerminalAfterManyWalker,\n} from \"../../grammar/interpreter.js\";\nimport {\n  DEFAULT_RULE_CONFIG,\n  END_OF_FILE,\n  IParserState,\n  TokenMatcher,\n} from \"../parser.js\";\nimport { IN_RULE_RECOVERY_EXCEPTION } from \"./recoverable.js\";\nimport { EOF } from \"../../../scan/tokens_public.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n  augmentTokenTypes,\n  isTokenType,\n  tokenStructuredMatcher,\n  tokenStructuredMatcherNoCategories,\n} from \"../../../scan/tokens.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for the runtime parsing engine\n * Used by the official API (recognizer_api.ts)\n */\nexport class RecognizerEngine {\n  isBackTrackingStack: boolean[];\n  className: string;\n  RULE_STACK: number[];\n  RULE_OCCURRENCE_STACK: number[];\n  // Depth counters for the pre-allocated state stacks.\n  // Using index-based access (arr[++idx] = val / idx--) instead of push/pop\n  // avoids method-call overhead on every rule entry/exit.\n  RULE_STACK_IDX: number;\n  RULE_OCCURRENCE_STACK_IDX: number;\n  definedRulesNames: string[];\n  tokensMap: { [fqn: string]: TokenType };\n  gastProductionsCache: Record<string, Rule>;\n  shortRuleNameToFull: string[];\n  fullRuleNameToShort: Record<string, number>;\n  ruleShortNameIdx: number;\n  tokenMatcher: TokenMatcher;\n  subruleIdx: number;\n  // Cached value of the current rule's short name to avoid repeated RULE_STACK[length-1] lookups.\n  // Updated on rule entry/exit and state reload.\n  currRuleShortName: number;\n\n  initRecognizerEngine(\n    tokenVocabulary: TokenVocabulary,\n    config: IParserConfig,\n  ) {\n    this.className = this.constructor.name;\n    // TODO: would using an ES6 Map or plain object be faster (CST building scenario)\n    this.shortRuleNameToFull = [];\n    this.fullRuleNameToShort = {};\n    this.ruleShortNameIdx = 0;\n    this.tokenMatcher = tokenStructuredMatcherNoCategories;\n    this.subruleIdx = 0;\n    this.currRuleShortName = -1;\n\n    this.definedRulesNames = [];\n    this.tokensMap = {};\n    this.isBackTrackingStack = [];\n    this.RULE_STACK = [];\n    this.RULE_STACK_IDX = -1;\n    this.RULE_OCCURRENCE_STACK = [];\n    this.RULE_OCCURRENCE_STACK_IDX = -1;\n    this.gastProductionsCache = {};\n\n    if (Object.hasOwn(config, \"serializedGrammar\")) {\n      throw Error(\n        \"The Parser's configuration can no longer contain a <serializedGrammar> property.\\n\" +\n          \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\\n\" +\n          \"\\tFor Further details.\",\n      );\n    }\n\n    if (Array.isArray(tokenVocabulary)) {\n      // This only checks for Token vocabularies provided as arrays.\n      // That is good enough because the main objective is to detect users of pre-V4.0 APIs\n      // rather than all edge cases of empty Token vocabularies.\n      if ((tokenVocabulary as any[]).length === 0) {\n        throw Error(\n          \"A Token Vocabulary cannot be empty.\\n\" +\n            \"\\tNote that the first argument for the parser constructor\\n\" +\n            \"\\tis no longer a Token vector (since v4.0).\",\n        );\n      }\n\n      if (typeof (tokenVocabulary as any[])[0].startOffset === \"number\") {\n        throw Error(\n          \"The Parser constructor no longer accepts a token vector as the first argument.\\n\" +\n            \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\\n\" +\n            \"\\tFor Further details.\",\n        );\n      }\n    }\n\n    if (Array.isArray(tokenVocabulary)) {\n      this.tokensMap = (tokenVocabulary as TokenType[]).reduce(\n        (acc: { [tokenName: string]: TokenType }, tokType: TokenType) => {\n          acc[tokType.name] = tokType;\n          return acc;\n        },\n        {} as { [tokenName: string]: TokenType },\n      );\n    } else if (\n      Object.hasOwn(tokenVocabulary, \"modes\") &&\n      (Object.values((<any>tokenVocabulary).modes) as any[][])\n        .flat()\n        .every(isTokenType)\n    ) {\n      const allTokenTypes = (\n        Object.values((<any>tokenVocabulary).modes) as any[][]\n      ).flat();\n      const uniqueTokens = [...new Set(allTokenTypes)];\n      this.tokensMap = <any>uniqueTokens.reduce(\n        (acc: { [tokenName: string]: TokenType }, tokType: TokenType) => {\n          acc[tokType.name] = tokType;\n          return acc;\n        },\n        {} as { [tokenName: string]: TokenType },\n      );\n    } else if (\n      typeof tokenVocabulary === \"object\" &&\n      tokenVocabulary !== null\n    ) {\n      this.tokensMap = { ...(tokenVocabulary as TokenTypeDictionary) };\n    } else {\n      throw new Error(\n        \"<tokensDictionary> argument must be An Array of Token constructors,\" +\n          \" A dictionary of Token constructors or an IMultiModeLexerDefinition\",\n      );\n    }\n\n    // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been\n    // parsed with a clear error message (\"expecting EOF but found ...\")\n    this.tokensMap[\"EOF\"] = EOF;\n\n    const allTokenTypes = Object.hasOwn(tokenVocabulary, \"modes\")\n      ? (Object.values((<any>tokenVocabulary).modes) as any[][]).flat()\n      : Object.values(tokenVocabulary);\n    const noTokenCategoriesUsed = allTokenTypes.every(\n      // intentional \"==\" to also cover \"undefined\"\n      (tokenConstructor: any) => tokenConstructor.categoryMatches?.length == 0,\n    );\n\n    this.tokenMatcher = noTokenCategoriesUsed\n      ? tokenStructuredMatcherNoCategories\n      : tokenStructuredMatcher;\n\n    // Because ES2015+ syntax should be supported for creating Token classes\n    // We cannot assume that the Token classes were created using the \"extendToken\" utilities\n    // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization\n    augmentTokenTypes(Object.values(this.tokensMap));\n  }\n\n  defineRule<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleName: string,\n    impl: (...args: ARGS) => R,\n    config: IRuleConfig<R>,\n  ): ParserMethodInternal<ARGS, R> {\n    if (this.selfAnalysisDone) {\n      throw Error(\n        `Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'\\n` +\n          `Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`,\n      );\n    }\n    const resyncEnabled: boolean = Object.hasOwn(config, \"resyncEnabled\")\n      ? (config.resyncEnabled as boolean) // assumes end user provides the correct config value/type\n      : DEFAULT_RULE_CONFIG.resyncEnabled;\n    const recoveryValueFunc = Object.hasOwn(config, \"recoveryValueFunc\")\n      ? (config.recoveryValueFunc as () => R) // assumes end user provides the correct config value/type\n      : DEFAULT_RULE_CONFIG.recoveryValueFunc;\n\n    const shortName = this.ruleShortNameIdx++;\n    this.shortRuleNameToFull[shortName] = ruleName;\n    this.fullRuleNameToShort[ruleName] = shortName;\n\n    let coreRuleFunction: ParserMethod<ARGS, R>;\n\n    // Micro optimization, only check the condition **once** on rule definition\n    // instead of **every single** rule invocation.\n    if (this.outputCst === true) {\n      coreRuleFunction = function invokeRuleWithTry(\n        this: MixedInParser,\n        ...args: ARGS\n      ): R {\n        try {\n          this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n          impl.apply(this, args);\n          const cst = this.CST_STACK[this.CST_STACK.length - 1];\n          this.cstPostRule(cst);\n          return cst as unknown as R;\n        } catch (e) {\n          return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n        } finally {\n          this.ruleFinallyStateUpdate();\n        }\n      };\n    } else {\n      coreRuleFunction = function invokeRuleWithTryCst(\n        this: MixedInParser,\n        ...args: ARGS\n      ): R {\n        try {\n          this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n          return impl.apply(this, args);\n        } catch (e) {\n          return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n        } finally {\n          this.ruleFinallyStateUpdate();\n        }\n      };\n    }\n\n    // wrapper to allow before/after parsing hooks\n    const rootRuleFunction: ParserMethod<ARGS, R> = function rootRule(\n      this: MixedInParser,\n      ...args: ARGS\n    ): R {\n      this.onBeforeParse(ruleName);\n      try {\n        return coreRuleFunction.apply(this, args);\n      } finally {\n        this.onAfterParse(ruleName);\n      }\n    };\n\n    const wrappedGrammarRule: ParserMethodInternal<ARGS, R> = Object.assign(\n      rootRuleFunction as any,\n      { ruleName, originalGrammarAction: impl, coreRule: coreRuleFunction },\n    );\n\n    return wrappedGrammarRule;\n  }\n\n  invokeRuleCatch(\n    this: MixedInParser,\n    e: Error,\n    resyncEnabledConfig: boolean,\n    recoveryValueFunc: Function,\n  ): unknown {\n    const isFirstInvokedRule = this.RULE_STACK_IDX === 0;\n    // note the reSync is always enabled for the first rule invocation, because we must always be able to\n    // reSync with EOF and just output some INVALID ParseTree\n    // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking\n    // path is really the most valid one\n    const reSyncEnabled =\n      resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled;\n\n    if (isRecognitionException(e)) {\n      const recogError: any = e;\n      if (reSyncEnabled) {\n        const reSyncTokType = this.findReSyncTokenType();\n        if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {\n          recogError.resyncedTokens = this.reSyncTo(reSyncTokType);\n          if (this.outputCst) {\n            const partialCstResult: any =\n              this.CST_STACK[this.CST_STACK.length - 1];\n            partialCstResult.recoveredNode = true;\n            return partialCstResult;\n          } else {\n            return recoveryValueFunc(e);\n          }\n        } else {\n          if (this.outputCst) {\n            const partialCstResult: any =\n              this.CST_STACK[this.CST_STACK.length - 1];\n            partialCstResult.recoveredNode = true;\n            recogError.partialCstResult = partialCstResult;\n          }\n          // to be handled Further up the call stack\n          throw recogError;\n        }\n      } else if (isFirstInvokedRule) {\n        // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case\n        this.moveToTerminatedState();\n        // the parser should never throw one of its own errors outside its flow.\n        // even if error recovery is disabled\n        return recoveryValueFunc(e);\n      } else {\n        // to be recovered Further up the call stack\n        throw recogError;\n      }\n    } else {\n      // some other Error type which we don't know how to handle (for example a built in JavaScript Error)\n      throw e;\n    }\n  }\n\n  // Implementation of parsing DSL\n  optionInternal<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n    occurrence: number,\n  ): OUT | undefined {\n    const key = OPTION_IDX | occurrence;\n    return this.optionInternalLogic(actionORMethodDef, occurrence, key);\n  }\n\n  optionInternalLogic<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n    occurrence: number,\n    key: number,\n  ): OUT | undefined {\n    let lookAheadFunc = this.currRuleLookaheadFuncs[key];\n    let action: GrammarAction<OUT>;\n    if (typeof actionORMethodDef !== \"function\") {\n      action = actionORMethodDef.DEF;\n      const predicate = actionORMethodDef.GATE;\n      // predicate present\n      if (predicate !== undefined) {\n        const orgLookaheadFunction = lookAheadFunc;\n        lookAheadFunc = () => {\n          return predicate.call(this) && orgLookaheadFunction.call(this);\n        };\n      }\n    } else {\n      action = actionORMethodDef;\n    }\n\n    if (lookAheadFunc.call(this) === true) {\n      return action.call(this);\n    }\n    return undefined;\n  }\n\n  atLeastOneInternal<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    const key = AT_LEAST_ONE_IDX | prodOccurrence;\n    return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key);\n  }\n\n  atLeastOneInternalLogic<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n    key: number,\n  ): void {\n    let lookAheadFunc = this.currRuleLookaheadFuncs[key];\n    let action;\n    if (typeof actionORMethodDef !== \"function\") {\n      action = actionORMethodDef.DEF;\n      const predicate = actionORMethodDef.GATE;\n      // predicate present\n      if (predicate !== undefined) {\n        const orgLookaheadFunction = lookAheadFunc;\n        lookAheadFunc = () => {\n          return predicate.call(this) && orgLookaheadFunction.call(this);\n        };\n      }\n    } else {\n      action = actionORMethodDef;\n    }\n\n    if ((<Function>lookAheadFunc).call(this) === true) {\n      let notStuck = this.doSingleRepetition(action);\n      while (\n        (<Function>lookAheadFunc).call(this) === true &&\n        notStuck === true\n      ) {\n        notStuck = this.doSingleRepetition(action);\n      }\n    } else {\n      throw this.raiseEarlyExitException(\n        prodOccurrence,\n        PROD_TYPE.REPETITION_MANDATORY,\n        (<DSLMethodOptsWithErr<OUT>>actionORMethodDef).ERR_MSG,\n      );\n    }\n\n    // note that while it may seem that this can cause an error because by using a recursive call to\n    // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call\n    // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items.\n\n    // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n    this.attemptInRepetitionRecovery(\n      this.atLeastOneInternal,\n      [prodOccurrence, actionORMethodDef],\n      <any>lookAheadFunc,\n      AT_LEAST_ONE_IDX,\n      prodOccurrence,\n      NextTerminalAfterAtLeastOneWalker,\n    );\n  }\n\n  atLeastOneSepFirstInternal<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    const key = AT_LEAST_ONE_SEP_IDX | prodOccurrence;\n    this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, key);\n  }\n\n  atLeastOneSepFirstInternalLogic<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    options: AtLeastOneSepMethodOpts<OUT>,\n    key: number,\n  ): void {\n    const action = options.DEF;\n    const separator = options.SEP;\n\n    const firstIterationLookaheadFunc = this.currRuleLookaheadFuncs[key];\n\n    // 1st iteration\n    if (firstIterationLookaheadFunc.call(this) === true) {\n      (<GrammarAction<OUT>>action).call(this);\n\n      //  TODO: Optimization can move this function construction into \"attemptInRepetitionRecovery\"\n      //  because it is only needed in error recovery scenarios.\n      const separatorLookAheadFunc = () => {\n        return this.tokenMatcher(this.LA_FAST(1), separator);\n      };\n\n      // 2nd..nth iterations\n      while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {\n        // note that this CONSUME will never enter recovery because\n        // the separatorLookAheadFunc checks that the separator really does exist.\n        this.CONSUME(separator);\n        // No need for checking infinite loop here due to consuming the separator.\n        (<GrammarAction<OUT>>action).call(this);\n      }\n\n      // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n      this.attemptInRepetitionRecovery(\n        this.repetitionSepSecondInternal,\n        [\n          prodOccurrence,\n          separator,\n          separatorLookAheadFunc,\n          action,\n          NextTerminalAfterAtLeastOneSepWalker,\n        ],\n        separatorLookAheadFunc,\n        AT_LEAST_ONE_SEP_IDX,\n        prodOccurrence,\n        NextTerminalAfterAtLeastOneSepWalker,\n      );\n    } else {\n      throw this.raiseEarlyExitException(\n        prodOccurrence,\n        PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n        options.ERR_MSG,\n      );\n    }\n  }\n\n  manyInternal<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    const key = MANY_IDX | prodOccurrence;\n    return this.manyInternalLogic(prodOccurrence, actionORMethodDef, key);\n  }\n\n  manyInternalLogic<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n    key: number,\n  ) {\n    let lookaheadFunction = this.currRuleLookaheadFuncs[key];\n    let action;\n    if (typeof actionORMethodDef !== \"function\") {\n      action = actionORMethodDef.DEF;\n      const predicate = actionORMethodDef.GATE;\n      // predicate present\n      if (predicate !== undefined) {\n        const orgLookaheadFunction = lookaheadFunction;\n        lookaheadFunction = () => {\n          return predicate.call(this) && orgLookaheadFunction.call(this);\n        };\n      }\n    } else {\n      action = actionORMethodDef;\n    }\n\n    let notStuck = true;\n    while (lookaheadFunction.call(this) === true && notStuck === true) {\n      notStuck = this.doSingleRepetition(action);\n    }\n\n    // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n    this.attemptInRepetitionRecovery(\n      this.manyInternal,\n      [prodOccurrence, actionORMethodDef],\n      <any>lookaheadFunction,\n      MANY_IDX,\n      prodOccurrence,\n      NextTerminalAfterManyWalker,\n      // The notStuck parameter is only relevant when \"attemptInRepetitionRecovery\"\n      // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]\n      // An infinite loop cannot occur as:\n      // - Either the lookahead is guaranteed to consume something (Single Token Separator)\n      // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).\n      notStuck,\n    );\n  }\n\n  manySepFirstInternal<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    options: ManySepMethodOpts<OUT>,\n  ): void {\n    const key = MANY_SEP_IDX | prodOccurrence;\n    this.manySepFirstInternalLogic(prodOccurrence, options, key);\n  }\n\n  manySepFirstInternalLogic<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    options: ManySepMethodOpts<OUT>,\n    key: number,\n  ): void {\n    const action = options.DEF;\n    const separator = options.SEP;\n    const firstIterationLaFunc = this.currRuleLookaheadFuncs[key];\n\n    // 1st iteration\n    if (firstIterationLaFunc.call(this) === true) {\n      action.call(this);\n\n      const separatorLookAheadFunc = () => {\n        return this.tokenMatcher(this.LA_FAST(1), separator);\n      };\n      // 2nd..nth iterations\n      while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {\n        // note that this CONSUME will never enter recovery because\n        // the separatorLookAheadFunc checks that the separator really does exist.\n        this.CONSUME(separator);\n        // No need for checking infinite loop here due to consuming the separator.\n        action.call(this);\n      }\n\n      // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n      this.attemptInRepetitionRecovery(\n        this.repetitionSepSecondInternal,\n        [\n          prodOccurrence,\n          separator,\n          separatorLookAheadFunc,\n          action,\n          NextTerminalAfterManySepWalker,\n        ],\n        separatorLookAheadFunc,\n        MANY_SEP_IDX,\n        prodOccurrence,\n        NextTerminalAfterManySepWalker,\n      );\n    }\n  }\n\n  repetitionSepSecondInternal<OUT>(\n    this: MixedInParser,\n    prodOccurrence: number,\n    separator: TokenType,\n    separatorLookAheadFunc: () => boolean,\n    action: GrammarAction<OUT>,\n    nextTerminalAfterWalker: typeof AbstractNextTerminalAfterProductionWalker,\n  ): void {\n    while (separatorLookAheadFunc()) {\n      // note that this CONSUME will never enter recovery because\n      // the separatorLookAheadFunc checks that the separator really does exist.\n      this.CONSUME(separator);\n      action.call(this);\n    }\n\n    // we can only arrive to this function after an error\n    // has occurred (hence the name 'second') so the following\n    // IF will always be entered, its possible to remove it...\n    // however it is kept to avoid confusion and be consistent.\n    // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n    /* istanbul ignore else */\n    this.attemptInRepetitionRecovery(\n      this.repetitionSepSecondInternal,\n      [\n        prodOccurrence,\n        separator,\n        separatorLookAheadFunc,\n        action,\n        nextTerminalAfterWalker,\n      ],\n      separatorLookAheadFunc,\n      AT_LEAST_ONE_SEP_IDX,\n      prodOccurrence,\n      nextTerminalAfterWalker,\n    );\n  }\n\n  doSingleRepetition(this: MixedInParser, action: Function): any {\n    const beforeIteration = this.getLexerPosition();\n    action.call(this);\n    const afterIteration = this.getLexerPosition();\n\n    // This boolean will indicate if this repetition progressed\n    // or if we are \"stuck\" (potential infinite loop in the repetition).\n    return afterIteration > beforeIteration;\n  }\n\n  orInternal<T>(\n    this: MixedInParser,\n    altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n    occurrence: number,\n  ): T {\n    const key = OR_IDX | occurrence;\n    const alts = Array.isArray(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF;\n\n    const laFunc = this.currRuleLookaheadFuncs[key];\n    const altIdxToTake = laFunc.call(this, alts);\n    if (altIdxToTake !== undefined) {\n      const chosenAlternative: any = alts[altIdxToTake];\n      return chosenAlternative.ALT.call(this);\n    }\n    this.raiseNoAltException(\n      occurrence,\n      (altsOrOpts as OrMethodOpts<unknown>).ERR_MSG,\n    );\n  }\n\n  ruleFinallyStateUpdate(this: MixedInParser): void {\n    this.RULE_STACK_IDX--;\n    this.RULE_OCCURRENCE_STACK_IDX--;\n\n    // Restore the parent rule's cached index and lookahead table. When the stack\n    // is empty, stale values are harmless because the next rule entry replaces them.\n    if (this.RULE_STACK_IDX >= 0) {\n      this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];\n      this.currRuleLookaheadFuncs =\n        this.lookAheadFuncsCache[this.currRuleShortName];\n    }\n\n    // NOOP when cst is disabled\n    this.cstFinallyStateUpdate();\n  }\n\n  subruleInternal<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    idx: number,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R {\n    let ruleResult;\n    try {\n      const args = options !== undefined ? options.ARGS : undefined;\n      this.subruleIdx = idx;\n      // Use coreRule to bypass root-level hooks (onBeforeParse/onAfterParse)\n      ruleResult = ruleToCall.coreRule.apply(this, args);\n      this.cstPostNonTerminal(\n        ruleResult,\n        options !== undefined && options.LABEL !== undefined\n          ? options.LABEL\n          : ruleToCall.ruleName,\n      );\n      return ruleResult;\n    } catch (e) {\n      throw this.subruleInternalError(e, options, ruleToCall.ruleName);\n    }\n  }\n\n  subruleInternalError(\n    this: MixedInParser,\n    e: any,\n    options: SubruleMethodOpts<unknown[]> | undefined,\n    ruleName: string,\n  ): void {\n    if (isRecognitionException(e) && e.partialCstResult !== undefined) {\n      this.cstPostNonTerminal(\n        e.partialCstResult,\n        options !== undefined && options.LABEL !== undefined\n          ? options.LABEL\n          : ruleName,\n      );\n\n      delete e.partialCstResult;\n    }\n    throw e;\n  }\n\n  consumeInternal(\n    this: MixedInParser,\n    tokType: TokenType,\n    idx: number,\n    options: ConsumeMethodOpts | undefined,\n  ): IToken {\n    let consumedToken!: IToken;\n    try {\n      const nextToken = this.LA_FAST(1);\n      if (this.tokenMatcher(nextToken, tokType) === true) {\n        this.consumeToken();\n        consumedToken = nextToken;\n      } else {\n        this.consumeInternalError(tokType, nextToken, options);\n      }\n    } catch (eFromConsumption) {\n      consumedToken = this.consumeInternalRecovery(\n        tokType,\n        idx,\n        eFromConsumption,\n      );\n    }\n\n    this.cstPostTerminal(\n      options !== undefined && options.LABEL !== undefined\n        ? options.LABEL\n        : tokType.name,\n      consumedToken,\n    );\n    return consumedToken;\n  }\n\n  consumeInternalError(\n    this: MixedInParser,\n    tokType: TokenType,\n    nextToken: IToken,\n    options: ConsumeMethodOpts | undefined,\n  ): void {\n    let msg;\n    const previousToken = this.LA(0);\n    if (options !== undefined && options.ERR_MSG) {\n      msg = options.ERR_MSG;\n    } else {\n      msg = this.errorMessageProvider.buildMismatchTokenMessage({\n        expected: tokType,\n        actual: nextToken,\n        previous: previousToken,\n        ruleName: this.getCurrRuleFullName(),\n      });\n    }\n    throw this.SAVE_ERROR(\n      new MismatchedTokenException(msg, nextToken, previousToken),\n    );\n  }\n\n  consumeInternalRecovery(\n    this: MixedInParser,\n    tokType: TokenType,\n    idx: number,\n    eFromConsumption: Error,\n  ): IToken {\n    // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it\n    // but the original syntax could have been parsed successfully without any backtracking + recovery\n    if (\n      this.recoveryEnabled &&\n      // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?\n      eFromConsumption.name === \"MismatchedTokenException\" &&\n      !this.isBackTracking()\n    ) {\n      const follows = this.getFollowsForInRuleRecovery(<any>tokType, idx);\n      try {\n        return this.tryInRuleRecovery(<any>tokType, follows);\n      } catch (eFromInRuleRecovery) {\n        if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) {\n          // failed in RuleRecovery.\n          // throw the original error in order to trigger reSync error recovery\n          throw eFromConsumption;\n        } else {\n          throw eFromInRuleRecovery;\n        }\n      }\n    } else {\n      throw eFromConsumption;\n    }\n  }\n\n  saveRecogState(this: MixedInParser): IParserState {\n    // errors is a getter which will clone the errors array\n    const savedErrors = this.errors;\n    // Slice only the active portion of the pre-allocated stack\n    const savedRuleStack = this.RULE_STACK.slice(0, this.RULE_STACK_IDX + 1);\n    return {\n      errors: savedErrors,\n      lexerState: this.exportLexerState(),\n      RULE_STACK: savedRuleStack,\n      CST_STACK: this.CST_STACK,\n    };\n  }\n\n  reloadRecogState(this: MixedInParser, newState: IParserState) {\n    this.errors = newState.errors;\n    this.importLexerState(newState.lexerState);\n    // Copy saved stack back into the pre-allocated array and restore the index\n    const saved = newState.RULE_STACK;\n    for (let i = 0; i < saved.length; i++) {\n      this.RULE_STACK[i] = saved[i];\n    }\n    this.RULE_STACK_IDX = saved.length - 1;\n    // Restore the current-rule caches from the restored stack.\n    if (this.RULE_STACK_IDX >= 0) {\n      this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];\n      this.currRuleLookaheadFuncs =\n        this.lookAheadFuncsCache[this.currRuleShortName];\n    }\n  }\n\n  ruleInvocationStateUpdate(\n    this: MixedInParser,\n    shortName: number,\n    fullName: string,\n    idxInCallingRule: number,\n  ): void {\n    this.RULE_OCCURRENCE_STACK[++this.RULE_OCCURRENCE_STACK_IDX] =\n      idxInCallingRule;\n    this.RULE_STACK[++this.RULE_STACK_IDX] = shortName;\n    this.currRuleShortName = shortName;\n    this.currRuleLookaheadFuncs = this.lookAheadFuncsCache[shortName];\n    // NOOP when cst is disabled\n    this.cstInvocationStateUpdate(fullName);\n  }\n\n  isBackTracking(this: MixedInParser): boolean {\n    return this.isBackTrackingStack.length !== 0;\n  }\n\n  getCurrRuleFullName(this: MixedInParser): string {\n    const shortName = this.currRuleShortName;\n    return this.shortRuleNameToFull[shortName];\n  }\n\n  shortRuleNameToFullName(this: MixedInParser, shortName: number) {\n    return this.shortRuleNameToFull[shortName];\n  }\n\n  public isAtEndOfInput(this: MixedInParser): boolean {\n    return this.tokenMatcher(this.LA(1), EOF);\n  }\n\n  public reset(this: MixedInParser): void {\n    this.resetLexerState();\n    this.subruleIdx = 0;\n    this.currRuleShortName = -1;\n    this.currRuleLookaheadFuncs = [];\n    this.isBackTrackingStack = [];\n    this.errors = [];\n    // Reset depth counters but keep arrays allocated to avoid re-allocation.\n    // Stale number values in unused slots are harmless.\n    this.RULE_STACK_IDX = -1;\n    this.RULE_OCCURRENCE_STACK_IDX = -1;\n    // TODO: extract a specific reset for TreeBuilder trait\n    this.CST_STACK = [];\n  }\n\n  /**\n   * Hook called before the root-level parsing rule is invoked.\n   * This is only called when a rule is invoked directly by the consumer\n   * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.\n   *\n   * Override this method to perform actions before parsing begins.\n   * The default implementation is a no-op.\n   *\n   * @param ruleName - The name of the root rule being invoked.\n   */\n  onBeforeParse(this: MixedInParser, ruleName: string): void {\n    // Pad with sentinels for bounds-free forward LA()\n    for (let i = 0; i < this.maxLookahead + 1; i++) {\n      this.tokVector.push(END_OF_FILE);\n    }\n  }\n\n  /**\n   * Hook called after the root-level parsing rule has completed (or thrown).\n   * This is only called when a rule is invoked directly by the consumer\n   * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.\n   *\n   * This hook is called in a `finally` block, so it executes regardless of\n   * whether parsing succeeded or threw an error.\n   *\n   * Override this method to perform actions after parsing completes.\n   * The default implementation is a no-op.\n   *\n   * @param ruleName - The name of the root rule that was invoked.\n   */\n  onAfterParse(this: MixedInParser, ruleName: string): void {\n    if (this.isAtEndOfInput() === false) {\n      const firstRedundantTok = this.LA(1);\n      const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({\n        firstRedundant: firstRedundantTok,\n        ruleName: this.getCurrRuleFullName(),\n      });\n      this.SAVE_ERROR(\n        new NotAllInputParsedException(errMsg, firstRedundantTok),\n      );\n    }\n\n    // undo the padding of sentinels for bounds-free forward LA() in onBeforeParse\n    while (this.tokVector.at(-1) === END_OF_FILE) {\n      this.tokVector.pop();\n    }\n  }\n}\n", "import {\n  IParserConfig,\n  IParserErrorMessageProvider,\n  IRecognitionException,\n} from \"@chevrotain/types\";\nimport {\n  EarlyExitException,\n  isRecognitionException,\n  NoViableAltException,\n} from \"../../exceptions_public.js\";\nimport {\n  getLookaheadPathsForOptionalProd,\n  getLookaheadPathsForOr,\n  PROD_TYPE,\n} from \"../../grammar/lookahead.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class ErrorHandler {\n  _errors: IRecognitionException[];\n  errorMessageProvider: IParserErrorMessageProvider;\n\n  initErrorHandler(config: IParserConfig) {\n    this._errors = [];\n    this.errorMessageProvider = Object.hasOwn(config, \"errorMessageProvider\")\n      ? (config.errorMessageProvider as IParserErrorMessageProvider) // assumes end user provides the correct config value/type\n      : DEFAULT_PARSER_CONFIG.errorMessageProvider;\n  }\n\n  SAVE_ERROR(\n    this: MixedInParser,\n    error: IRecognitionException,\n  ): IRecognitionException {\n    if (isRecognitionException(error)) {\n      error.context = {\n        ruleStack: this.getHumanReadableRuleStack(),\n        ruleOccurrenceStack: this.RULE_OCCURRENCE_STACK.slice(\n          0,\n          this.RULE_OCCURRENCE_STACK_IDX + 1,\n        ),\n      };\n      this._errors.push(error);\n      return error;\n    } else {\n      throw Error(\n        \"Trying to save an Error which is not a RecognitionException\",\n      );\n    }\n  }\n\n  get errors(): IRecognitionException[] {\n    return [...this._errors];\n  }\n\n  set errors(newErrors: IRecognitionException[]) {\n    this._errors = newErrors;\n  }\n\n  // TODO: consider caching the error message computed information\n  raiseEarlyExitException(\n    this: MixedInParser,\n    occurrence: number,\n    prodType: PROD_TYPE,\n    userDefinedErrMsg: string | undefined,\n  ): never {\n    const ruleName = this.getCurrRuleFullName();\n    const ruleGrammar = this.getGAstProductions()[ruleName];\n    const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(\n      occurrence,\n      ruleGrammar,\n      prodType,\n      this.maxLookahead,\n    );\n    const insideProdPaths = lookAheadPathsPerAlternative[0];\n    const actualTokens = [];\n    for (let i = 1; i <= this.maxLookahead; i++) {\n      actualTokens.push(this.LA(i));\n    }\n    const msg = this.errorMessageProvider.buildEarlyExitMessage({\n      expectedIterationPaths: insideProdPaths,\n      actual: actualTokens,\n      previous: this.LA(0),\n      customUserDescription: userDefinedErrMsg,\n      ruleName: ruleName,\n    });\n\n    throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0)));\n  }\n\n  // TODO: consider caching the error message computed information\n  raiseNoAltException(\n    this: MixedInParser,\n    occurrence: number,\n    errMsgTypes: string | undefined,\n  ): never {\n    const ruleName = this.getCurrRuleFullName();\n    const ruleGrammar = this.getGAstProductions()[ruleName];\n    // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ?\n    const lookAheadPathsPerAlternative = getLookaheadPathsForOr(\n      occurrence,\n      ruleGrammar,\n      this.maxLookahead,\n    );\n\n    const actualTokens = [];\n    for (let i = 1; i <= this.maxLookahead; i++) {\n      actualTokens.push(this.LA(i));\n    }\n    const previousToken = this.LA(0);\n\n    const errMsg = this.errorMessageProvider.buildNoViableAltMessage({\n      expectedPathsPerAlt: lookAheadPathsPerAlternative,\n      actual: actualTokens,\n      previous: previousToken,\n      customUserDescription: errMsgTypes,\n      ruleName: this.getCurrRuleFullName(),\n    });\n\n    throw this.SAVE_ERROR(\n      new NoViableAltException(errMsg, this.LA(1), previousToken),\n    );\n  }\n}\n", "import {\n  AtLeastOneSepMethodOpts,\n  ConsumeMethodOpts,\n  CstNode,\n  DSLMethodOpts,\n  DSLMethodOptsWithErr,\n  GrammarAction,\n  IOrAlt,\n  IParserConfig,\n  IProduction,\n  IToken,\n  ManySepMethodOpts,\n  OrMethodOpts,\n  SubruleMethodOpts,\n  TokenType,\n} from \"@chevrotain/types\";\n\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n  Alternation,\n  Alternative,\n  NonTerminal,\n  Option,\n  Repetition,\n  RepetitionMandatory,\n  RepetitionMandatoryWithSeparator,\n  RepetitionWithSeparator,\n  Rule,\n  Terminal,\n} from \"@chevrotain/gast\";\nimport { Lexer } from \"../../../scan/lexer_public.js\";\nimport {\n  augmentTokenTypes,\n  hasShortKeyProperty,\n} from \"../../../scan/tokens.js\";\nimport {\n  createToken,\n  createTokenInstance,\n} from \"../../../scan/tokens_public.js\";\nimport { END_OF_FILE } from \"../parser.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\ntype ProdWithDef = IProduction & { definition?: IProduction[] };\nconst RECORDING_NULL_OBJECT = {\n  description: \"This Object indicates the Parser is during Recording Phase\",\n};\nObject.freeze(RECORDING_NULL_OBJECT);\n\nconst HANDLE_SEPARATOR = true;\nconst MAX_METHOD_IDX = 255;\n\nconst RFT = createToken({ name: \"RECORDING_PHASE_TOKEN\", pattern: Lexer.NA });\naugmentTokenTypes([RFT]);\nconst RECORDING_PHASE_TOKEN = createTokenInstance(\n  RFT,\n  \"This IToken indicates the Parser is in Recording Phase\\n\\t\" +\n    \"\" +\n    \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n  // Negative positions are less likely to cause errors if the output of LA or CONSUME\n  // is incorrectly used during the recording phase.\n  -1,\n  -1,\n  -1,\n  -1,\n  -1,\n  -1,\n);\nObject.freeze(RECORDING_PHASE_TOKEN);\n\nconst RECORDING_PHASE_CSTNODE: CstNode = {\n  name:\n    \"This CSTNode indicates the Parser is in Recording Phase\\n\\t\" +\n    \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n  children: {},\n};\n\n/**\n * This trait handles the creation of the GAST structure for Chevrotain Grammars\n */\nexport class GastRecorder {\n  recordingProdStack: ProdWithDef[];\n  RECORDING_PHASE: boolean;\n\n  initGastRecorder(this: MixedInParser, config: IParserConfig): void {\n    this.recordingProdStack = [];\n    this.RECORDING_PHASE = false;\n  }\n\n  enableRecording(this: MixedInParser): void {\n    this.RECORDING_PHASE = true;\n\n    this.TRACE_INIT(\"Enable Recording\", () => {\n      /**\n       * Warning Dark Voodoo Magic upcoming!\n       * We are \"replacing\" the public parsing DSL methods API\n       * With **new** alternative implementations on the Parser **instance**\n       *\n       * So far this is the only way I've found to avoid performance regressions during parsing time.\n       * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the \"internal\"\n       *   implementations directly instead.\n       */\n      for (let i = 0; i < 10; i++) {\n        const idx = i > 0 ? i : \"\";\n        this[`CONSUME${idx}` as \"CONSUME\"] = function (arg1, arg2) {\n          return this.consumeInternalRecord(arg1, i, arg2);\n        };\n        this[`SUBRULE${idx}` as \"SUBRULE\"] = function (arg1, arg2) {\n          return this.subruleInternalRecord(arg1, i, arg2) as any;\n        };\n        this[`OPTION${idx}` as \"OPTION\"] = function (arg1) {\n          return this.optionInternalRecord(arg1, i);\n        };\n        this[`OR${idx}` as \"OR\"] = function (arg1) {\n          return this.orInternalRecord(arg1, i);\n        };\n        this[`MANY${idx}` as \"MANY\"] = function (arg1) {\n          this.manyInternalRecord(i, arg1);\n        };\n        this[`MANY_SEP${idx}` as \"MANY_SEP\"] = function (arg1) {\n          this.manySepFirstInternalRecord(i, arg1);\n        };\n        this[`AT_LEAST_ONE${idx}` as \"AT_LEAST_ONE\"] = function (arg1) {\n          this.atLeastOneInternalRecord(i, arg1);\n        };\n        this[`AT_LEAST_ONE_SEP${idx}` as \"AT_LEAST_ONE_SEP\"] = function (arg1) {\n          this.atLeastOneSepFirstInternalRecord(i, arg1);\n        };\n      }\n\n      // DSL methods with the idx(suffix) as an argument\n      this[`consume`] = function (idx, arg1, arg2) {\n        return this.consumeInternalRecord(arg1, idx, arg2);\n      };\n      this[`subrule`] = function (idx, arg1, arg2) {\n        return this.subruleInternalRecord(arg1, idx, arg2) as any;\n      };\n      this[`option`] = function (idx, arg1) {\n        return this.optionInternalRecord(arg1, idx);\n      };\n      this[`or`] = function (idx, arg1) {\n        return this.orInternalRecord(arg1, idx);\n      };\n      this[`many`] = function (idx, arg1) {\n        this.manyInternalRecord(idx, arg1);\n      };\n      this[`atLeastOne`] = function (idx, arg1) {\n        this.atLeastOneInternalRecord(idx, arg1);\n      };\n\n      this.ACTION = this.ACTION_RECORD;\n      this.BACKTRACK = this.BACKTRACK_RECORD;\n      this.LA = this.LA_RECORD;\n    });\n  }\n\n  disableRecording(this: MixedInParser) {\n    this.RECORDING_PHASE = false;\n    // By deleting these **instance** properties, any future invocation\n    // will be deferred to the original methods on the **prototype** object\n    // This seems to get rid of any incorrect optimizations that V8 may\n    // do during the recording phase.\n    this.TRACE_INIT(\"Deleting Recording methods\", () => {\n      const that: any = this;\n\n      for (let i = 0; i < 10; i++) {\n        const idx = i > 0 ? i : \"\";\n        delete that[`CONSUME${idx}`];\n        delete that[`SUBRULE${idx}`];\n        delete that[`OPTION${idx}`];\n        delete that[`OR${idx}`];\n        delete that[`MANY${idx}`];\n        delete that[`MANY_SEP${idx}`];\n        delete that[`AT_LEAST_ONE${idx}`];\n        delete that[`AT_LEAST_ONE_SEP${idx}`];\n      }\n\n      delete that[`consume`];\n      delete that[`subrule`];\n      delete that[`option`];\n      delete that[`or`];\n      delete that[`many`];\n      delete that[`atLeastOne`];\n\n      delete that.ACTION;\n      delete that.BACKTRACK;\n      delete that.LA;\n    });\n  }\n\n  //   Parser methods are called inside an ACTION?\n  //   Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?\n  // @ts-expect-error -- noop place holder\n  ACTION_RECORD<T>(this: MixedInParser, impl: () => T): T {\n    // NO-OP during recording\n  }\n\n  // Executing backtracking logic will break our recording logic assumptions\n  BACKTRACK_RECORD<ARGS extends unknown[], T>(\n    grammarRule: (...args: ARGS) => T,\n    args?: ARGS,\n  ): () => boolean {\n    return () => true;\n  }\n\n  // LA is part of the official API and may be used for custom lookahead logic\n  // by end users who may forget to wrap it in ACTION or inside a GATE\n  LA_RECORD(howMuch: number): IToken {\n    // We cannot use the RECORD_PHASE_TOKEN here because someone may depend\n    // On LA return EOF at the end of the input so an infinite loop may occur.\n    return END_OF_FILE;\n  }\n\n  topLevelRuleRecord(name: string, def: Function): Rule {\n    try {\n      const newTopLevelRule = new Rule({ definition: [], name: name });\n      newTopLevelRule.name = name;\n      this.recordingProdStack.push(newTopLevelRule);\n      def.call(this);\n      this.recordingProdStack.pop();\n      return newTopLevelRule;\n    } catch (originalError) {\n      if (originalError.KNOWN_RECORDER_ERROR !== true) {\n        try {\n          originalError.message =\n            originalError.message +\n            '\\n\\t This error was thrown during the \"grammar recording phase\" For more info see:\\n\\t' +\n            \"https://chevrotain.io/docs/guide/internals.html#grammar-recording\";\n        } catch (mutabilityError) {\n          // We may not be able to modify the original error object\n          throw originalError;\n        }\n      }\n      throw originalError;\n    }\n  }\n\n  // Implementation of parsing DSL\n  optionInternalRecord<OUT>(\n    this: MixedInParser,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n    occurrence: number,\n  ): OUT {\n    return recordProd.call(this, Option, actionORMethodDef, occurrence);\n  }\n\n  atLeastOneInternalRecord<OUT>(\n    this: MixedInParser,\n    occurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n  ): void {\n    recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);\n  }\n\n  atLeastOneSepFirstInternalRecord<OUT>(\n    this: MixedInParser,\n    occurrence: number,\n    options: AtLeastOneSepMethodOpts<OUT>,\n  ): void {\n    recordProd.call(\n      this,\n      RepetitionMandatoryWithSeparator,\n      options,\n      occurrence,\n      HANDLE_SEPARATOR,\n    );\n  }\n\n  manyInternalRecord<OUT>(\n    this: MixedInParser,\n    occurrence: number,\n    actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n  ): void {\n    recordProd.call(this, Repetition, actionORMethodDef, occurrence);\n  }\n\n  manySepFirstInternalRecord<OUT>(\n    this: MixedInParser,\n    occurrence: number,\n    options: ManySepMethodOpts<OUT>,\n  ): void {\n    recordProd.call(\n      this,\n      RepetitionWithSeparator,\n      options,\n      occurrence,\n      HANDLE_SEPARATOR,\n    );\n  }\n\n  orInternalRecord<T>(\n    this: MixedInParser,\n    altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n    occurrence: number,\n  ): T {\n    return recordOrProd.call(this, altsOrOpts, occurrence);\n  }\n\n  subruleInternalRecord<ARGS extends unknown[], R>(\n    this: MixedInParser,\n    ruleToCall: ParserMethodInternal<ARGS, R>,\n    occurrence: number,\n    options?: SubruleMethodOpts<ARGS>,\n  ): R | CstNode {\n    assertMethodIdxIsValid(occurrence);\n    if (!ruleToCall || !Object.hasOwn(ruleToCall, \"ruleName\")) {\n      const error: any = new Error(\n        `<SUBRULE${getIdxSuffix(occurrence)}> argument is invalid` +\n          ` expecting a Parser method reference but got: <${JSON.stringify(\n            ruleToCall,\n          )}>` +\n          `\\n inside top level rule: <${\n            (<Rule>this.recordingProdStack[0]).name\n          }>`,\n      );\n      error.KNOWN_RECORDER_ERROR = true;\n      throw error;\n    }\n\n    const prevProd: any = this.recordingProdStack.at(-1);\n    const ruleName = ruleToCall.ruleName;\n    const newNoneTerminal = new NonTerminal({\n      idx: occurrence,\n      nonTerminalName: ruleName,\n      label: options?.LABEL,\n      // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created\n      referencedRule: undefined,\n    });\n    prevProd.definition.push(newNoneTerminal);\n\n    return this.outputCst\n      ? RECORDING_PHASE_CSTNODE\n      : <any>RECORDING_NULL_OBJECT;\n  }\n\n  consumeInternalRecord(\n    this: MixedInParser,\n    tokType: TokenType,\n    occurrence: number,\n    options?: ConsumeMethodOpts,\n  ): IToken {\n    assertMethodIdxIsValid(occurrence);\n    if (!hasShortKeyProperty(tokType)) {\n      const error: any = new Error(\n        `<CONSUME${getIdxSuffix(occurrence)}> argument is invalid` +\n          ` expecting a TokenType reference but got: <${JSON.stringify(\n            tokType,\n          )}>` +\n          `\\n inside top level rule: <${\n            (<Rule>this.recordingProdStack[0]).name\n          }>`,\n      );\n      error.KNOWN_RECORDER_ERROR = true;\n      throw error;\n    }\n    const prevProd: any = this.recordingProdStack.at(-1);\n    const newNoneTerminal = new Terminal({\n      idx: occurrence,\n      terminalType: tokType,\n      label: options?.LABEL,\n    });\n    prevProd.definition.push(newNoneTerminal);\n\n    return RECORDING_PHASE_TOKEN;\n  }\n}\n\nfunction recordProd(\n  prodConstructor: any,\n  mainProdArg: any,\n  occurrence: number,\n  handleSep: boolean = false,\n): any {\n  assertMethodIdxIsValid(occurrence);\n  const prevProd: any = this.recordingProdStack.at(-1);\n  const grammarAction =\n    typeof mainProdArg === \"function\" ? mainProdArg : mainProdArg.DEF;\n\n  const newProd = new prodConstructor({ definition: [], idx: occurrence });\n  if (handleSep) {\n    newProd.separator = mainProdArg.SEP;\n  }\n  if (Object.hasOwn(mainProdArg, \"MAX_LOOKAHEAD\")) {\n    newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n  }\n\n  this.recordingProdStack.push(newProd);\n  grammarAction.call(this);\n  prevProd.definition.push(newProd);\n  this.recordingProdStack.pop();\n\n  return RECORDING_NULL_OBJECT;\n}\n\nfunction recordOrProd(mainProdArg: any, occurrence: number): any {\n  assertMethodIdxIsValid(occurrence);\n  const prevProd: any = this.recordingProdStack.at(-1);\n  // Only an array of alternatives\n  const hasOptions = Array.isArray(mainProdArg) === false;\n  const alts: IOrAlt<unknown>[] =\n    hasOptions === false ? mainProdArg : mainProdArg.DEF;\n\n  const newOrProd = new Alternation({\n    definition: [],\n    idx: occurrence,\n    ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true,\n  });\n  if (Object.hasOwn(mainProdArg, \"MAX_LOOKAHEAD\")) {\n    newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n  }\n\n  const hasPredicates = alts.some(\n    (currAlt: any) => typeof currAlt.GATE === \"function\",\n  );\n  newOrProd.hasPredicates = hasPredicates;\n\n  prevProd.definition.push(newOrProd);\n\n  alts.forEach((currAlt) => {\n    const currAltFlat = new Alternative({ definition: [] });\n    newOrProd.definition.push(currAltFlat);\n    if (Object.hasOwn(currAlt, \"IGNORE_AMBIGUITIES\")) {\n      currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES as boolean; // assumes end user provides the correct config value/type\n    }\n    // **implicit** ignoreAmbiguities due to usage of gate\n    else if (Object.hasOwn(currAlt, \"GATE\")) {\n      currAltFlat.ignoreAmbiguities = true;\n    }\n    this.recordingProdStack.push(currAltFlat);\n    currAlt.ALT.call(this);\n    this.recordingProdStack.pop();\n  });\n  return RECORDING_NULL_OBJECT;\n}\n\nfunction getIdxSuffix(idx: number): string {\n  return idx === 0 ? \"\" : `${idx}`;\n}\n\nfunction assertMethodIdxIsValid(idx: number): void {\n  if (idx < 0 || idx > MAX_METHOD_IDX) {\n    const error: any = new Error(\n      // The stack trace will contain all the needed details\n      `Invalid DSL Method idx value: <${idx}>\\n\\t` +\n        `Idx value must be a none negative value smaller than ${\n          MAX_METHOD_IDX + 1\n        }`,\n    );\n    error.KNOWN_RECORDER_ERROR = true;\n    throw error;\n  }\n}\n", "import { IParserConfig } from \"@chevrotain/types\";\nimport { timer } from \"@chevrotain/utils\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class PerformanceTracer {\n  traceInitPerf: boolean | number;\n  traceInitMaxIdent: number;\n  traceInitIndent: number;\n\n  initPerformanceTracer(config: IParserConfig) {\n    if (Object.hasOwn(config, \"traceInitPerf\")) {\n      const userTraceInitPerf = config.traceInitPerf;\n      const traceIsNumber = typeof userTraceInitPerf === \"number\";\n      this.traceInitMaxIdent = traceIsNumber\n        ? <number>userTraceInitPerf\n        : Infinity;\n      this.traceInitPerf = traceIsNumber\n        ? userTraceInitPerf > 0\n        : (userTraceInitPerf as boolean); // assumes end user provides the correct config value/type\n    } else {\n      this.traceInitMaxIdent = 0;\n      this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf;\n    }\n\n    this.traceInitIndent = -1;\n  }\n\n  TRACE_INIT<T>(this: MixedInParser, phaseDesc: string, phaseImpl: () => T): T {\n    // No need to optimize this using NOOP pattern because\n    // It is not called in a hot spot...\n    if (this.traceInitPerf === true) {\n      this.traceInitIndent++;\n      const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n      if (this.traceInitIndent < this.traceInitMaxIdent) {\n        console.log(`${indent}--> <${phaseDesc}>`);\n      }\n      const { time, value } = timer(phaseImpl);\n      /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n      const traceMethod = time > 10 ? console.warn : console.log;\n      if (this.traceInitIndent < this.traceInitMaxIdent) {\n        traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n      }\n      this.traceInitIndent--;\n      return value;\n    } else {\n      return phaseImpl();\n    }\n  }\n}\n", "export function applyMixins(derivedCtor: any, baseCtors: any[]) {\n  baseCtors.forEach((baseCtor) => {\n    const baseProto = baseCtor.prototype;\n    Object.getOwnPropertyNames(baseProto).forEach((propName) => {\n      if (propName === \"constructor\") {\n        return;\n      }\n\n      const basePropDescriptor = Object.getOwnPropertyDescriptor(\n        baseProto,\n        propName,\n      );\n      // Handle Accessors\n      if (\n        basePropDescriptor &&\n        (basePropDescriptor.get || basePropDescriptor.set)\n      ) {\n        Object.defineProperty(\n          derivedCtor.prototype,\n          propName,\n          basePropDescriptor,\n        );\n      } else {\n        derivedCtor.prototype[propName] = baseCtor.prototype[propName];\n      }\n    });\n  });\n}\n", "import { toFastProperties } from \"@chevrotain/utils\";\nimport { computeAllProdsFollows } from \"../grammar/follow.js\";\nimport { createTokenInstance, EOF } from \"../../scan/tokens_public.js\";\nimport {\n  defaultGrammarValidatorErrorProvider,\n  defaultParserErrorProvider,\n} from \"../errors_public.js\";\nimport {\n  resolveGrammar,\n  validateGrammar,\n} from \"../grammar/gast/gast_resolver_public.js\";\nimport {\n  CstNode,\n  IParserConfig,\n  IRecognitionException,\n  IRuleConfig,\n  IToken,\n  TokenType,\n  TokenVocabulary,\n} from \"@chevrotain/types\";\nimport { Recoverable } from \"./traits/recoverable.js\";\nimport { LooksAhead } from \"./traits/looksahead.js\";\nimport { TreeBuilder } from \"./traits/tree_builder.js\";\nimport { LexerAdapter } from \"./traits/lexer_adapter.js\";\nimport { RecognizerApi } from \"./traits/recognizer_api.js\";\nimport { RecognizerEngine } from \"./traits/recognizer_engine.js\";\n\nimport { ErrorHandler } from \"./traits/error_handler.js\";\nimport { MixedInParser } from \"./traits/parser_traits.js\";\nimport { GastRecorder } from \"./traits/gast_recorder.js\";\nimport { PerformanceTracer } from \"./traits/perf_tracer.js\";\nimport { applyMixins } from \"./utils/apply_mixins.js\";\nimport { IParserDefinitionError } from \"../grammar/types.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { IParserConfigInternal, ParserMethodInternal } from \"./types.js\";\nimport { validateLookahead } from \"../grammar/checks.js\";\n\nexport const END_OF_FILE = createTokenInstance(EOF, \"\", -1, -1, -1, -1, -1, -1);\nObject.freeze(END_OF_FILE);\n\nexport type TokenMatcher = (token: IToken, tokType: TokenType) => boolean;\n\nexport const DEFAULT_PARSER_CONFIG: Required<\n  Omit<IParserConfigInternal, \"lookaheadStrategy\">\n> = Object.freeze({\n  recoveryEnabled: false,\n  maxLookahead: 3,\n  dynamicTokensEnabled: false,\n  outputCst: true,\n  errorMessageProvider: defaultParserErrorProvider,\n  nodeLocationTracking: \"none\",\n  traceInitPerf: false,\n  skipValidations: false,\n});\n\nexport const DEFAULT_RULE_CONFIG: Required<IRuleConfig<any>> = Object.freeze({\n  recoveryValueFunc: () => undefined,\n  resyncEnabled: true,\n});\n\nexport enum ParserDefinitionErrorType {\n  INVALID_RULE_NAME = 0,\n  DUPLICATE_RULE_NAME = 1,\n  INVALID_RULE_OVERRIDE = 2,\n  DUPLICATE_PRODUCTIONS = 3,\n  UNRESOLVED_SUBRULE_REF = 4,\n  LEFT_RECURSION = 5,\n  NONE_LAST_EMPTY_ALT = 6,\n  AMBIGUOUS_ALTS = 7,\n  CONFLICT_TOKENS_RULES_NAMESPACE = 8,\n  INVALID_TOKEN_NAME = 9,\n  NO_NON_EMPTY_LOOKAHEAD = 10,\n  AMBIGUOUS_PREFIX_ALTS = 11,\n  TOO_MANY_ALTS = 12,\n  CUSTOM_LOOKAHEAD_VALIDATION = 13,\n}\n\nexport interface IParserDuplicatesDefinitionError extends IParserDefinitionError {\n  dslName: string;\n  occurrence: number;\n  parameter?: string;\n}\n\nexport interface IParserEmptyAlternativeDefinitionError extends IParserDefinitionError {\n  occurrence: number;\n  alternative: number;\n}\n\nexport interface IParserAmbiguousAlternativesDefinitionError extends IParserDefinitionError {\n  occurrence: number | string;\n  alternatives: number[];\n}\n\nexport interface IParserUnresolvedRefDefinitionError extends IParserDefinitionError {\n  unresolvedRefName: string;\n}\n\nexport interface IParserState {\n  errors: IRecognitionException[];\n  lexerState: any;\n  RULE_STACK: number[];\n  CST_STACK: CstNode[];\n}\n\nexport type Predicate = () => boolean;\n\nexport function EMPTY_ALT(): () => undefined;\nexport function EMPTY_ALT<T>(value: T): () => T;\nexport function EMPTY_ALT(value: any = undefined) {\n  return function () {\n    return value;\n  };\n}\n\nexport class Parser {\n  // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected.\n  // (normally during the parser's constructor).\n  // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors,\n  // for example: duplicate rule names, referencing an unresolved subrule, etc...\n  // This flag should not be enabled during normal usage, it is used in special situations, for example when\n  // needing to display the parser definition errors in some GUI(online playground).\n  static DEFER_DEFINITION_ERRORS_HANDLING: boolean = false;\n\n  /**\n   *  @deprecated use the **instance** method with the same name instead\n   */\n  static performSelfAnalysis(parserInstance: Parser): void {\n    throw Error(\n      \"The **static** `performSelfAnalysis` method has been deprecated.\" +\n        \"\\t\\nUse the **instance** method with the same name instead.\",\n    );\n  }\n\n  public performSelfAnalysis(this: MixedInParser): void {\n    this.TRACE_INIT(\"performSelfAnalysis\", () => {\n      let defErrorsMsgs;\n\n      this.selfAnalysisDone = true;\n      const className = this.className;\n\n      this.TRACE_INIT(\"toFastProps\", () => {\n        // Without this voodoo magic the parser would be x3-x4 slower\n        // It seems it is better to invoke `toFastProperties` **before**\n        // Any manipulations of the `this` object done during the recording phase.\n        toFastProperties(this);\n      });\n\n      this.TRACE_INIT(\"Grammar Recording\", () => {\n        try {\n          this.enableRecording();\n          // Building the GAST\n          this.definedRulesNames.forEach((currRuleName: string) => {\n            const wrappedRule = (this as any)[\n              currRuleName\n            ] as ParserMethodInternal<unknown[], unknown>;\n            const originalGrammarAction = wrappedRule[\"originalGrammarAction\"];\n            let recordedRuleGast!: Rule;\n            this.TRACE_INIT(`${currRuleName} Rule`, () => {\n              recordedRuleGast = this.topLevelRuleRecord(\n                currRuleName,\n                originalGrammarAction,\n              );\n            });\n            this.gastProductionsCache[currRuleName] = recordedRuleGast;\n          });\n        } finally {\n          this.disableRecording();\n        }\n      });\n\n      let resolverErrors: IParserDefinitionError[] = [];\n      this.TRACE_INIT(\"Grammar Resolving\", () => {\n        resolverErrors = resolveGrammar({\n          rules: Object.values(this.gastProductionsCache),\n        });\n        this.definitionErrors = this.definitionErrors.concat(resolverErrors);\n      });\n\n      this.TRACE_INIT(\"Grammar Validations\", () => {\n        // only perform additional grammar validations IFF no resolving errors have occurred.\n        // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations.\n        if (resolverErrors.length === 0 && this.skipValidations === false) {\n          const validationErrors = validateGrammar({\n            rules: Object.values(this.gastProductionsCache),\n            tokenTypes: Object.values(this.tokensMap),\n            errMsgProvider: defaultGrammarValidatorErrorProvider,\n            grammarName: className,\n          });\n          const lookaheadValidationErrors = validateLookahead({\n            lookaheadStrategy: this.lookaheadStrategy,\n            rules: Object.values(this.gastProductionsCache),\n            tokenTypes: Object.values(this.tokensMap),\n            grammarName: className,\n          });\n          this.definitionErrors = this.definitionErrors.concat(\n            validationErrors,\n            lookaheadValidationErrors,\n          );\n        }\n      });\n\n      // this analysis may fail if the grammar is not perfectly valid\n      if (this.definitionErrors.length === 0) {\n        // The results of these computations are not needed unless error recovery is enabled.\n        if (this.recoveryEnabled) {\n          this.TRACE_INIT(\"computeAllProdsFollows\", () => {\n            const allFollows = computeAllProdsFollows(\n              Object.values(this.gastProductionsCache),\n            );\n            this.resyncFollows = allFollows;\n          });\n        }\n\n        this.TRACE_INIT(\"ComputeLookaheadFunctions\", () => {\n          this.lookaheadStrategy.initialize?.({\n            rules: Object.values(this.gastProductionsCache),\n          });\n          this.preComputeLookaheadFunctions(\n            Object.values(this.gastProductionsCache),\n          );\n        });\n      }\n\n      if (\n        !Parser.DEFER_DEFINITION_ERRORS_HANDLING &&\n        this.definitionErrors.length !== 0\n      ) {\n        defErrorsMsgs = this.definitionErrors.map(\n          (defError) => defError.message,\n        );\n        throw new Error(\n          `Parser Definition Errors detected:\\n ${defErrorsMsgs.join(\n            \"\\n-------------------------------\\n\",\n          )}`,\n        );\n      }\n    });\n  }\n\n  definitionErrors: IParserDefinitionError[] = [];\n  selfAnalysisDone = false;\n  protected skipValidations: boolean;\n\n  constructor(tokenVocabulary: TokenVocabulary, config: IParserConfig) {\n    const that: MixedInParser = this as any;\n    that.initErrorHandler(config);\n    that.initLexerAdapter();\n    that.initLooksAhead(config);\n    that.initRecognizerEngine(tokenVocabulary, config);\n    that.initRecoverable(config);\n    that.initTreeBuilder(config);\n    that.initGastRecorder(config);\n    that.initPerformanceTracer(config);\n\n    if (Object.hasOwn(config, \"ignoredIssues\")) {\n      throw new Error(\n        \"The <ignoredIssues> IParserConfig property has been deprecated.\\n\\t\" +\n          \"Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\\n\\t\" +\n          \"See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\\n\\t\" +\n          \"For further details.\",\n      );\n    }\n\n    this.skipValidations = Object.hasOwn(config, \"skipValidations\")\n      ? (config.skipValidations as boolean) // casting assumes the end user passing the correct type\n      : DEFAULT_PARSER_CONFIG.skipValidations;\n  }\n}\n\napplyMixins(Parser, [\n  Recoverable,\n  LooksAhead,\n  TreeBuilder,\n  LexerAdapter,\n  RecognizerEngine,\n  RecognizerApi,\n  ErrorHandler,\n  GastRecorder,\n  PerformanceTracer,\n]);\n\nexport class CstParser extends Parser {\n  constructor(\n    tokenVocabulary: TokenVocabulary,\n    config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n  ) {\n    const configClone = { ...config };\n    configClone.outputCst = true;\n    super(tokenVocabulary, configClone);\n  }\n}\n\nexport class EmbeddedActionsParser extends Parser {\n  constructor(\n    tokenVocabulary: TokenVocabulary,\n    config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n  ) {\n    const configClone = { ...config };\n    configClone.outputCst = false;\n    super(tokenVocabulary, configClone);\n  }\n}\n", "// cspell:ignore lparen markerless rparen\n\nimport { createToken, Lexer } from 'chevrotain';\nimport type { CustomPatternMatcherFunc, TokenType } from 'chevrotain';\n\nfunction customMatch(text: string, offset: number, image: string): RegExpExecArray {\n  const match = [image] as unknown as RegExpExecArray;\n  match.index = offset;\n  match.input = text;\n  return match;\n}\n\nconst matchMarkdownString: CustomPatternMatcherFunc = (text, offset) => {\n  if (text[offset] !== '\"' || text[offset + 1] !== '`') {\n    return null;\n  }\n  for (let index = offset + 2; index < text.length - 1; index++) {\n    if (text[index] === '`' && text[index + 1] === '\"') {\n      return customMatch(text, offset, text.slice(offset, index + 2));\n    }\n  }\n  return null;\n};\n\nconst matchComment: CustomPatternMatcherFunc = (text, offset) => {\n  if (text[offset] !== '%' || text[offset + 1] !== '%') {\n    return null;\n  }\n  for (let index = offset - 1; index >= 0; index--) {\n    const character = text[index];\n    if (character === '\\n' || character === '\\r') {\n      break;\n    }\n    if (character !== ' ' && character !== '\\t') {\n      return null;\n    }\n  }\n  let end = offset + 2;\n  while (end < text.length && text[end] !== '\\n' && text[end] !== '\\r') {\n    end++;\n  }\n  return customMatch(text, offset, text.slice(offset, end));\n};\n\nconst isIndentedLineStart = (text: string, offset: number): boolean => {\n  for (let index = offset - 1; index >= 0; index--) {\n    const character = text[index];\n    if (character === '\\n' || character === '\\r') {\n      return true;\n    }\n    if (character !== ' ' && character !== '\\t') {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst matchAccessibilityLine = (\n  text: string,\n  offset: number,\n  pattern: RegExp\n): RegExpExecArray | null => {\n  if (!isIndentedLineStart(text, offset)) {\n    return null;\n  }\n  const match = pattern.exec(text.slice(offset));\n  return match ? customMatch(text, offset, match[0]) : null;\n};\n\nconst matchAccDescrBlock: CustomPatternMatcherFunc = (text, offset) => {\n  if (!isIndentedLineStart(text, offset)) {\n    return null;\n  }\n  const opening = /^accDescr[\\t ]*{/.exec(text.slice(offset));\n  if (!opening) {\n    return null;\n  }\n  const end = text.indexOf('}', offset + opening[0].length);\n  return end === -1 ? null : customMatch(text, offset, text.slice(offset, end + 1));\n};\n\nconst matchJsonObject: CustomPatternMatcherFunc = (text, offset) => {\n  if (text[offset] !== '{') {\n    return null;\n  }\n\n  let depth = 0;\n  let quoted = false;\n  let escaped = false;\n  for (let index = offset; index < text.length; index++) {\n    const character = text[index];\n    if (quoted) {\n      if (escaped) {\n        escaped = false;\n      } else if (character === '\\\\') {\n        escaped = true;\n      } else if (character === '\"') {\n        quoted = false;\n      }\n      continue;\n    }\n    if (character === '\"') {\n      quoted = true;\n    } else if (character === '{') {\n      depth++;\n    } else if (character === '}' && --depth === 0) {\n      return customMatch(text, offset, text.slice(offset, index + 1));\n    }\n  }\n\n  // No match makes Chevrotain locate the lexer error at this unmatched opening brace.\n  return null;\n};\n\nconst matchStereotypeText: CustomPatternMatcherFunc = (text, offset) => {\n  const end = text.indexOf('>>', offset);\n  if (end === -1 || /[\\n\\r]/.test(text.slice(offset, end))) {\n    return null;\n  }\n  const image = text.slice(offset, end);\n  return image.trim() ? customMatch(text, offset, image) : null;\n};\n\n// Everything an unquoted label may contain. Membership is opt-in per token, so a token\n// only becomes label text once it is provably not a delimiter, operator, or suffix marker.\nexport const LabelText = createToken({ name: 'LABEL_TEXT', pattern: Lexer.NA });\nexport const Word = createToken({ name: 'WORD', pattern: Lexer.NA, categories: LabelText });\n// Declared before IDENTIFIER so it can serve as its longer_alt.\nexport const NumberLiteral = createToken({\n  name: 'NUMBER',\n  pattern: /(?:\\d+\\.\\d+|\\d+|\\.\\d+)(?:[A-Za-z]+)?/,\n  categories: LabelText,\n});\n// Ids may start with a digit (`1`, `1mg`), so this is `\\w+` rather than an\n// identifier-shaped pattern. NUMBER is the longer_alt so decimals such as `1.5`\n// and `1.5px` still lex as a single number instead of `1` + `.` + `5`.\nexport const Identifier = createToken({\n  name: 'IDENTIFIER',\n  pattern: /\\w+/,\n  longer_alt: NumberLiteral,\n  categories: Word,\n});\nexport const WhiteSpace = createToken({\n  name: 'HWS',\n  pattern: /[\\t ]+/,\n  group: Lexer.SKIPPED,\n});\nexport const MarkdownString = createToken({\n  name: 'MARKDOWN_STRING',\n  pattern: matchMarkdownString,\n  start_chars_hint: ['\"'],\n  line_breaks: true,\n});\nexport const UnclosedMarkdownString = createToken({\n  name: 'UNCLOSED_MARKDOWN_STRING',\n  pattern: /\"`[^]*/,\n  line_breaks: true,\n});\nexport const Comment = createToken({\n  name: 'COMMENT',\n  pattern: matchComment,\n  start_chars_hint: ['%'],\n  line_breaks: false,\n});\nexport const NewLine = createToken({\n  name: 'NEWLINE',\n  pattern: /\\r\\n|\\n|\\r/,\n  line_breaks: true,\n});\n\nexport const AccDescrBlock = createToken({\n  name: 'ACC_DESCR_BLOCK',\n  pattern: matchAccDescrBlock,\n  start_chars_hint: ['a'],\n  line_breaks: true,\n});\nconst accTitleLinePattern = /^accTitle[\\t ]*:[^\\n\\r]*/;\nconst accDescrLinePattern = /^accDescr[\\t ]*:[^\\n\\r]*/;\n\nexport const AccTitleLine = createToken({\n  name: 'ACC_TITLE_LINE',\n  pattern: (text, offset) => matchAccessibilityLine(text, offset, accTitleLinePattern),\n  start_chars_hint: ['a'],\n  line_breaks: false,\n});\nexport const AccDescrLine = createToken({\n  name: 'ACC_DESCR_LINE',\n  pattern: (text, offset) => matchAccessibilityLine(text, offset, accDescrLinePattern),\n  start_chars_hint: ['a'],\n  line_breaks: false,\n});\n\nexport const JsonDeclarationStart = createToken({\n  name: 'JSON_DECLARATION_START',\n  pattern: /json[\\t ]+\\w+[\\t ]*@[\\t ]*(?={)/,\n  push_mode: 'jsonBody',\n});\nexport const JsonObjectLiteral = createToken({\n  name: 'JSON_OBJECT_LITERAL',\n  pattern: matchJsonObject,\n  start_chars_hint: ['{'],\n  line_breaks: true,\n  pop_mode: true,\n});\nexport const UnclosedJsonObjectLiteral = createToken({\n  name: 'UNCLOSED_JSON_OBJECT_LITERAL',\n  pattern: /{[^]*/,\n  line_breaks: true,\n  pop_mode: true,\n});\n\nconst keyword = (name: string, pattern: RegExp) =>\n  createToken({ name, pattern, longer_alt: Identifier, categories: Word });\n\nexport const Usecase = keyword('USECASE', /usecase-beta/);\nexport const Actor = keyword('ACTOR', /actor/);\nexport const SystemBoundary = keyword('SYSTEM_BOUNDARY', /systemBoundary/);\nexport const End = keyword('END', /end/);\nexport const Direction = keyword('DIRECTION', /direction/);\nexport const Td = keyword('TD', /TD/);\nexport const Tb = keyword('TB', /TB/);\nexport const Bt = keyword('BT', /BT/);\nexport const Lr = keyword('LR', /LR/);\nexport const Rl = keyword('RL', /RL/);\nexport const Note = keyword('NOTE', /note/);\nexport const For = keyword('FOR', /for/);\nconst Json = keyword('JSON', /json/);\nexport const ClassDef = keyword('CLASS_DEF', /classDef/);\nexport const Class = keyword('CLASS', /class/);\nexport const Style = keyword('STYLE', /style/);\nexport const Include = keyword('INCLUDE', /include/i);\nexport const Extend = keyword('EXTEND', /extend/i);\nexport const True = keyword('TRUE', /true/);\nexport const False = keyword('FALSE', /false/);\n\nexport const Generalization = createToken({ name: 'GENERALIZATION', pattern: /--\\|>/ });\nexport const DependencyArrow = createToken({ name: 'DEPENDENCY_ARROW', pattern: /\\.\\.>/ });\nexport const StereotypeStart = createToken({\n  name: 'STEREOTYPE_START',\n  pattern: /<</,\n  push_mode: 'stereotype',\n});\nexport const StereotypeEnd = createToken({\n  name: 'STEREOTYPE_END',\n  pattern: />>/,\n  pop_mode: true,\n});\nexport const StereotypeText = createToken({\n  name: 'STEREOTYPE_TEXT',\n  pattern: matchStereotypeText,\n  line_breaks: false,\n});\nexport const UnclosedStereotypeText = createToken({\n  name: 'UNCLOSED_STEREOTYPE_TEXT',\n  pattern: /[^\\n\\r]+/,\n  line_breaks: false,\n  pop_mode: true,\n});\nexport const ClassSeparator = createToken({ name: 'CLASS_SEPARATOR', pattern: /:::/ });\nexport const ForwardSolid = createToken({ name: 'FORWARD_SOLID', pattern: /--+>/ });\nexport const BackwardSolid = createToken({ name: 'BACKWARD_SOLID', pattern: /<--+/ });\nexport const ForwardCircle = createToken({ name: 'FORWARD_CIRCLE', pattern: /--o/ });\nexport const BackwardCircle = createToken({ name: 'BACKWARD_CIRCLE', pattern: /o--/ });\nexport const ForwardCross = createToken({ name: 'FORWARD_CROSS', pattern: /--x/ });\nexport const BackwardCross = createToken({ name: 'BACKWARD_CROSS', pattern: /x--/ });\nexport const MarkerlessSolid = createToken({ name: 'MARKERLESS_SOLID', pattern: /--+/ });\nexport const MetadataStart = createToken({ name: 'METADATA_START', pattern: /@{/ });\nexport const At = createToken({ name: 'AT', pattern: /@/, categories: LabelText });\nexport const LeftBrace = createToken({ name: 'LBRACE', pattern: /{/ });\nexport const RightBrace = createToken({ name: 'RBRACE', pattern: /}/ });\nexport const LeftBracket = createToken({ name: 'LBRACKET', pattern: /\\[/ });\nexport const RightBracket = createToken({ name: 'RBRACKET', pattern: /]/ });\nexport const LeftParen = createToken({ name: 'LPAREN', pattern: /\\(/ });\nexport const RightParen = createToken({ name: 'RPAREN', pattern: /\\)/ });\nexport const Comma = createToken({ name: 'COMMA', pattern: /,/, categories: LabelText });\nexport const Colon = createToken({ name: 'COLON', pattern: /:/, categories: LabelText });\n\nexport const HashColor = createToken({\n  name: 'HASH_COLOR',\n  pattern: /#[\\dA-Fa-f]+/,\n  categories: LabelText,\n});\nexport const PlainString = createToken({\n  name: 'PLAIN_STRING',\n  pattern: /\"[^\\n\\r\"]*\"|'[^\\n\\r']*'/,\n});\nexport const CssIdentifier = createToken({\n  name: 'CSS_IDENTIFIER',\n  pattern: /--[A-Z_a-z][\\w-]*|[A-Z_a-z]\\w*(?:-\\w+)+/,\n  categories: LabelText,\n});\nexport const CssEscapedComma = createToken({\n  name: 'CSS_ESCAPED_COMMA',\n  pattern: /\\\\,/,\n  categories: LabelText,\n});\nexport const Dash = createToken({ name: 'DASH', pattern: /-/, categories: LabelText });\nexport const Dot = createToken({ name: 'DOT', pattern: /\\./, categories: LabelText });\nexport const Percent = createToken({ name: 'PERCENT', pattern: /%/, categories: LabelText });\nexport const CssPunctuation = createToken({\n  name: 'CSS_PUNCTUATION',\n  pattern: /[!#$&*+/=?^_|~]/,\n  categories: LabelText,\n});\n// Last-resort label text. These characters carry meaning only inside a longer operator\n// (`\\,`, `<<`, `<--`, `-->`, `..>`) or a Markdown string, all of which are matched earlier,\n// so on their own they are literal. `\"` and `'` are deliberately absent: they open the two\n// quoted-string forms, and letting them stand alone would turn an unterminated string into\n// a silently accepted label.\nexport const LabelPunctuation = createToken({\n  name: 'LABEL_PUNCTUATION',\n  pattern: /[;<>\\\\`]/,\n  categories: LabelText,\n});\n// Any run of characters outside printable ASCII, so unquoted labels are not English-only.\n// Disjoint from every other pattern in the mode, which all match printable ASCII.\nexport const LabelSymbol = createToken({\n  name: 'LABEL_SYMBOL',\n  pattern: /[^\\t\\n\\r !-~]+/,\n  categories: LabelText,\n});\n\nconst defaultModeTokens = [\n  LabelText,\n  Word,\n  WhiteSpace,\n  MarkdownString,\n  UnclosedMarkdownString,\n  Comment,\n  NewLine,\n  AccDescrBlock,\n  AccTitleLine,\n  AccDescrLine,\n  JsonDeclarationStart,\n  Usecase,\n  Actor,\n  SystemBoundary,\n  End,\n  Direction,\n  Td,\n  Tb,\n  Bt,\n  Lr,\n  Rl,\n  Note,\n  For,\n  Json,\n  ClassDef,\n  Class,\n  Style,\n  Include,\n  Extend,\n  True,\n  False,\n  Generalization,\n  DependencyArrow,\n  StereotypeStart,\n  ClassSeparator,\n  ForwardSolid,\n  BackwardSolid,\n  ForwardCircle,\n  BackwardCircle,\n  ForwardCross,\n  BackwardCross,\n  MarkerlessSolid,\n  MetadataStart,\n  At,\n  LeftBrace,\n  RightBrace,\n  LeftBracket,\n  RightBracket,\n  LeftParen,\n  RightParen,\n  Comma,\n  Colon,\n  HashColor,\n  PlainString,\n  CssIdentifier,\n  // IDENTIFIER precedes NUMBER so `1mg` lexes as one id; its longer_alt still hands\n  // decimals like `1.5px` to NUMBER.\n  Identifier,\n  NumberLiteral,\n  CssEscapedComma,\n  Dash,\n  Dot,\n  Percent,\n  CssPunctuation,\n  // Both fallbacks stay last so every operator, delimiter, and string form wins first.\n  LabelPunctuation,\n  LabelSymbol,\n] as const;\n\nexport const usecaseLexerModes = {\n  defaultMode: 'defaultMode',\n  modes: {\n    defaultMode: [...defaultModeTokens],\n    jsonBody: [JsonObjectLiteral, UnclosedJsonObjectLiteral],\n    stereotype: [StereotypeEnd, StereotypeText, UnclosedStereotypeText],\n  },\n};\n\n/** Flat vocabulary used by the parser; the lexer itself uses the mode table above. */\nexport const usecaseTokens: TokenType[] = [\n  ...defaultModeTokens,\n  JsonObjectLiteral,\n  UnclosedJsonObjectLiteral,\n  StereotypeEnd,\n  StereotypeText,\n  UnclosedStereotypeText,\n];\n", "import { Lexer } from 'chevrotain';\nimport { usecaseLexerModes } from './usecase.tokens.js';\n\n/** Singleton mode-aware lexer; construction and validation happen once at module load. */\nexport const usecaseLexer = new Lexer(usecaseLexerModes);\n", "// cspell:ignore allowmixing markerless newpage skinparam\n\nimport { CstParser, EOF, tokenMatcher } from 'chevrotain';\nimport type { CstNode, IToken, TokenType } from 'chevrotain';\nimport {\n  AccDescrBlock,\n  AccDescrLine,\n  AccTitleLine,\n  Actor,\n  At,\n  BackwardCircle,\n  BackwardCross,\n  BackwardSolid,\n  Bt,\n  Class,\n  ClassDef,\n  ClassSeparator,\n  Colon,\n  Comma,\n  Comment,\n  CssEscapedComma,\n  CssIdentifier,\n  CssPunctuation,\n  Dash,\n  DependencyArrow,\n  Direction,\n  Dot,\n  End,\n  Extend,\n  False,\n  For,\n  ForwardCircle,\n  ForwardCross,\n  ForwardSolid,\n  Generalization,\n  HashColor,\n  Identifier,\n  Include,\n  JsonDeclarationStart,\n  JsonObjectLiteral,\n  LabelText,\n  LeftBrace,\n  LeftBracket,\n  LeftParen,\n  Lr,\n  MarkdownString,\n  MarkerlessSolid,\n  MetadataStart,\n  NewLine,\n  Note,\n  NumberLiteral,\n  Percent,\n  PlainString,\n  RightBrace,\n  RightBracket,\n  RightParen,\n  Rl,\n  StereotypeEnd,\n  StereotypeStart,\n  StereotypeText,\n  Style,\n  SystemBoundary,\n  Tb,\n  Td,\n  True,\n  Usecase,\n  Word,\n  usecaseTokens,\n} from './usecase.tokens.js';\n\nconst isLabelToken = (token: IToken): boolean =>\n  tokenMatcher(token, LabelText) ||\n  token.tokenType === PlainString ||\n  token.tokenType === MarkdownString;\n\nconst forbiddenPlantUmlStatements: Record<string, true> = {\n  allowmixing: true,\n  newpage: true,\n  package: true,\n  rectangle: true,\n  skinparam: true,\n};\n\nclass UsecaseParser extends CstParser {\n  declare start: () => CstNode;\n  declare line: () => CstNode;\n  declare statement: () => CstNode;\n  declare lineEnd: () => CstNode;\n  declare blankLine: () => CstNode;\n  declare commentLine: () => CstNode;\n  declare accTitleStatement: () => CstNode;\n  declare accDescrStatement: () => CstNode;\n  declare actorStatement: () => CstNode;\n  declare actorItem: () => CstNode;\n  declare actorName: () => CstNode;\n  declare actorDeclarationOnly: () => CstNode;\n  declare entityStatement: () => CstNode;\n  declare entityName: () => CstNode;\n  declare nodeLabel: () => CstNode;\n  declare useCaseMetadata: () => CstNode;\n  declare relationTail: () => CstNode;\n  declare arrow: () => CstNode;\n  declare edgeLabel: () => CstNode;\n  declare semanticRelation: () => CstNode;\n  declare metadata: () => CstNode;\n  declare metadataProperty: () => CstNode;\n  declare metadataSeparator: () => CstNode;\n  declare systemBoundaryStatement: () => CstNode;\n  declare systemBoundaryName: () => CstNode;\n  declare systemBoundaryContent: () => CstNode;\n  declare boundaryElement: () => CstNode;\n  declare metadataAssignmentStatement: () => CstNode;\n  declare metadataAssignmentTarget: () => CstNode;\n  declare noteStatement: () => CstNode;\n  declare stereotype: () => CstNode;\n  declare classSuffix: () => CstNode;\n  declare jsonStatement: () => CstNode;\n  declare directionStatement: () => CstNode;\n  declare classDefStatement: () => CstNode;\n  declare classStatement: () => CstNode;\n  declare styleStatement: () => CstNode;\n  declare styles: () => CstNode;\n  declare styleValue: () => CstNode;\n\n  declare forwardSolidOperator: () => CstNode;\n  declare backwardSolidOperator: () => CstNode;\n  declare markerlessSolidOperator: () => CstNode;\n  declare forwardCircleOperator: () => CstNode;\n  declare backwardCircleOperator: () => CstNode;\n  declare forwardCrossOperator: () => CstNode;\n  declare backwardCrossOperator: () => CstNode;\n  declare styleComponent: () => CstNode;\n\n  constructor() {\n    super(usecaseTokens, { nodeLocationTracking: 'full' });\n\n    this.RULE('start', () => {\n      this.CONSUME(Usecase);\n      this.SUBRULE(this.lineEnd);\n      this.MANY(() => this.SUBRULE(this.line));\n    });\n\n    this.RULE('line', () => {\n      this.OR([\n        { ALT: () => this.SUBRULE(this.blankLine) },\n        { ALT: () => this.SUBRULE(this.commentLine) },\n        {\n          GATE: () => this.isStatementStart(),\n          ALT: () => this.SUBRULE(this.statement),\n        },\n      ]);\n    });\n\n    this.RULE('statement', () => {\n      this.OR([\n        { ALT: () => this.SUBRULE(this.accTitleStatement) },\n        { ALT: () => this.SUBRULE(this.accDescrStatement) },\n        { ALT: () => this.SUBRULE(this.directionStatement) },\n        { ALT: () => this.SUBRULE(this.actorStatement) },\n        { ALT: () => this.SUBRULE(this.systemBoundaryStatement) },\n        { ALT: () => this.SUBRULE(this.noteStatement) },\n        { ALT: () => this.SUBRULE(this.jsonStatement) },\n        { ALT: () => this.SUBRULE(this.classDefStatement) },\n        { ALT: () => this.SUBRULE(this.classStatement) },\n        { ALT: () => this.SUBRULE(this.styleStatement) },\n        {\n          GATE: () => this.isMetadataAssignment(),\n          ALT: () => this.SUBRULE(this.metadataAssignmentStatement),\n        },\n        {\n          GATE: () => !this.isForbiddenPlantUmlStatement(),\n          ALT: () => this.SUBRULE(this.entityStatement),\n        },\n      ]);\n    });\n\n    this.RULE('lineEnd', () => {\n      this.OR([{ ALT: () => this.CONSUME(NewLine) }, { ALT: () => this.CONSUME(EOF) }]);\n    });\n\n    this.RULE('blankLine', () => {\n      this.CONSUME(NewLine);\n    });\n\n    this.RULE('commentLine', () => {\n      this.CONSUME(Comment);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('accTitleStatement', () => {\n      this.CONSUME(AccTitleLine);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('accDescrStatement', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(AccDescrLine) },\n        { ALT: () => this.CONSUME(AccDescrBlock) },\n      ]);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('actorStatement', () => {\n      this.CONSUME(Actor);\n      this.SUBRULE(this.actorItem);\n      this.OPTION(() => {\n        this.OR([\n          {\n            ALT: () =>\n              this.AT_LEAST_ONE(() => {\n                this.CONSUME(Comma);\n                this.SUBRULE2(this.actorItem);\n              }),\n          },\n          { ALT: () => this.SUBRULE(this.relationTail) },\n        ]);\n      });\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('actorItem', () => {\n      this.SUBRULE(this.actorName);\n      this.OPTION(() => this.SUBRULE(this.metadata));\n      this.OPTION2(() => this.SUBRULE(this.stereotype));\n      this.OPTION3(() => this.SUBRULE(this.classSuffix));\n    });\n\n    this.RULE('actorName', () => {\n      this.OR([\n        {\n          ALT: () => {\n            this.CONSUME(Identifier);\n            this.OPTION(() => {\n              this.CONSUME(LeftParen);\n              this.SUBRULE(this.nodeLabel);\n              this.CONSUME(RightParen);\n            });\n          },\n        },\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n      ]);\n    });\n\n    this.RULE('actorDeclarationOnly', () => {\n      this.CONSUME(Actor);\n      this.SUBRULE(this.actorItem);\n      this.MANY(() => {\n        this.CONSUME(Comma);\n        this.SUBRULE2(this.actorItem);\n      });\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('entityStatement', () => {\n      this.SUBRULE(this.entityName);\n      this.OPTION(() => this.SUBRULE(this.relationTail));\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('entityName', () => {\n      this.OR([\n        {\n          ALT: () => {\n            this.CONSUME(Identifier);\n            this.OPTION(() => {\n              this.OR2([\n                {\n                  ALT: () => {\n                    this.CONSUME(LeftParen);\n                    this.SUBRULE(this.nodeLabel);\n                    this.CONSUME(RightParen);\n                  },\n                },\n                {\n                  ALT: () => {\n                    this.CONSUME(LeftBracket);\n                    this.SUBRULE2(this.nodeLabel);\n                    this.CONSUME(RightBracket);\n                  },\n                },\n              ]);\n            });\n          },\n        },\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n      ]);\n      this.OPTION2(() => this.SUBRULE(this.useCaseMetadata));\n      this.OPTION3(() => this.SUBRULE(this.stereotype));\n      this.OPTION4(() => this.SUBRULE(this.classSuffix));\n    });\n\n    this.RULE('nodeLabel', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n        // Unquoted labels run until a delimiter, operator, or suffix marker, none of\n        // which belong to `LabelText`. The visitor rebuilds the text from the source\n        // slice, so the internal token split never reaches the model.\n        { ALT: () => this.AT_LEAST_ONE(() => this.CONSUME(LabelText)) },\n      ]);\n    });\n\n    this.RULE('useCaseMetadata', () => {\n      this.SUBRULE(this.metadata);\n    });\n\n    this.RULE('relationTail', () => {\n      this.OPTION({\n        GATE: () => this.LA(1).tokenType === Identifier && this.LA(2).tokenType === At,\n        DEF: () => {\n          this.CONSUME(Identifier);\n          this.CONSUME(At);\n        },\n      });\n      this.SUBRULE(this.arrow);\n      this.SUBRULE(this.entityName);\n    });\n\n    this.RULE('arrow', () => {\n      this.OR([\n        { ALT: () => this.SUBRULE(this.semanticRelation) },\n        { ALT: () => this.SUBRULE(this.forwardSolidOperator) },\n        { ALT: () => this.SUBRULE(this.backwardSolidOperator) },\n        { ALT: () => this.SUBRULE(this.markerlessSolidOperator) },\n        { ALT: () => this.SUBRULE(this.forwardCircleOperator) },\n        { ALT: () => this.SUBRULE(this.backwardCircleOperator) },\n        { ALT: () => this.SUBRULE(this.forwardCrossOperator) },\n        { ALT: () => this.SUBRULE(this.backwardCrossOperator) },\n      ]);\n    });\n\n    this.RULE('forwardSolidOperator', () => {\n      this.CONSUME(ForwardSolid);\n    });\n\n    this.RULE('backwardSolidOperator', () => {\n      this.CONSUME(BackwardSolid);\n      this.OPTION({\n        GATE: () => this.LA(0).image === '<--' && this.hasLabeledRight([MarkerlessSolid]),\n        DEF: () => {\n          this.SUBRULE(this.edgeLabel);\n          this.CONSUME(MarkerlessSolid);\n        },\n      });\n    });\n\n    this.RULE('markerlessSolidOperator', () => {\n      this.CONSUME(MarkerlessSolid);\n      this.OPTION({\n        GATE: () =>\n          this.LA(0).image === '--' &&\n          this.hasLabeledRight([ForwardSolid, MarkerlessSolid, ForwardCircle, ForwardCross]),\n        DEF: () => {\n          this.SUBRULE(this.edgeLabel);\n          this.OR([\n            { ALT: () => this.CONSUME(ForwardSolid) },\n            { ALT: () => this.CONSUME2(MarkerlessSolid) },\n            { ALT: () => this.CONSUME(ForwardCircle) },\n            { ALT: () => this.CONSUME(ForwardCross) },\n          ]);\n        },\n      });\n    });\n\n    this.RULE('forwardCircleOperator', () => {\n      this.CONSUME(ForwardCircle);\n    });\n\n    this.RULE('backwardCircleOperator', () => {\n      this.CONSUME(BackwardCircle);\n      this.OPTION({\n        GATE: () => this.hasLabeledRight([MarkerlessSolid]),\n        DEF: () => {\n          this.SUBRULE(this.edgeLabel);\n          this.CONSUME(MarkerlessSolid);\n        },\n      });\n    });\n\n    this.RULE('forwardCrossOperator', () => {\n      this.CONSUME(ForwardCross);\n    });\n\n    this.RULE('backwardCrossOperator', () => {\n      this.CONSUME(BackwardCross);\n      this.OPTION({\n        GATE: () => this.hasLabeledRight([MarkerlessSolid]),\n        DEF: () => {\n          this.SUBRULE(this.edgeLabel);\n          this.CONSUME(MarkerlessSolid);\n        },\n      });\n    });\n\n    this.RULE('edgeLabel', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n        { ALT: () => this.AT_LEAST_ONE(() => this.CONSUME(LabelText)) },\n      ]);\n    });\n\n    this.RULE('semanticRelation', () => {\n      this.OR([\n        {\n          ALT: () => {\n            this.CONSUME(DependencyArrow);\n            this.CONSUME(Colon);\n            this.OR2([{ ALT: () => this.CONSUME(Include) }, { ALT: () => this.CONSUME(Extend) }]);\n          },\n        },\n        { ALT: () => this.CONSUME(Generalization) },\n      ]);\n    });\n\n    this.RULE('metadata', () => {\n      this.CONSUME(MetadataStart);\n      this.MANY(() => this.CONSUME(NewLine));\n      this.OPTION(() => {\n        this.SUBRULE(this.metadataProperty);\n        this.MANY2(() => {\n          this.SUBRULE(this.metadataSeparator);\n          this.SUBRULE2(this.metadataProperty);\n        });\n        this.OPTION2(() => this.CONSUME(Comma));\n        this.MANY3(() => this.CONSUME2(NewLine));\n      });\n      this.CONSUME(RightBrace);\n    });\n\n    this.RULE('metadataProperty', () => {\n      this.OR([{ ALT: () => this.CONSUME(Identifier) }, { ALT: () => this.CONSUME(PlainString) }]);\n      this.CONSUME(Colon);\n      this.OR2([\n        { ALT: () => this.CONSUME2(Identifier) },\n        { ALT: () => this.CONSUME2(PlainString) },\n        { ALT: () => this.CONSUME(True) },\n        { ALT: () => this.CONSUME(False) },\n      ]);\n    });\n\n    this.RULE('metadataSeparator', () => {\n      this.OR([\n        {\n          ALT: () => {\n            this.CONSUME(Comma);\n            this.MANY(() => this.CONSUME(NewLine));\n          },\n        },\n        {\n          ALT: () => {\n            this.AT_LEAST_ONE(() => this.CONSUME2(NewLine));\n            this.OPTION(() => this.CONSUME2(Comma));\n            this.MANY2(() => this.CONSUME3(NewLine));\n          },\n        },\n      ]);\n    });\n\n    this.RULE('systemBoundaryStatement', () => {\n      this.CONSUME(SystemBoundary);\n      this.SUBRULE(this.systemBoundaryName);\n      // Same suffix order as actor and use case declarations: metadata, then classes.\n      this.OPTION(() => this.SUBRULE(this.metadata));\n      this.OPTION2(() => this.SUBRULE(this.classSuffix));\n      this.SUBRULE(this.lineEnd);\n      this.SUBRULE(this.systemBoundaryContent);\n      this.CONSUME(End);\n      this.SUBRULE2(this.lineEnd);\n    });\n\n    this.RULE('systemBoundaryName', () => {\n      this.OR([\n        {\n          ALT: () => {\n            this.CONSUME(Identifier);\n            // Mirrors `entityName`, so a short id can carry a long title. Unlike a use\n            // case, the bracket form does not select a shape; boundary geometry comes\n            // from `type` metadata only.\n            this.OPTION(() => {\n              this.OR2([\n                {\n                  ALT: () => {\n                    this.CONSUME(LeftParen);\n                    this.SUBRULE(this.nodeLabel);\n                    this.CONSUME(RightParen);\n                  },\n                },\n                {\n                  ALT: () => {\n                    this.CONSUME(LeftBracket);\n                    this.SUBRULE2(this.nodeLabel);\n                    this.CONSUME(RightBracket);\n                  },\n                },\n              ]);\n            });\n          },\n        },\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n      ]);\n    });\n\n    this.RULE('systemBoundaryContent', () => {\n      this.MANY(() => {\n        this.OR([\n          { ALT: () => this.SUBRULE(this.blankLine) },\n          { ALT: () => this.SUBRULE(this.commentLine) },\n          { ALT: () => this.SUBRULE(this.boundaryElement) },\n        ]);\n      });\n    });\n\n    this.RULE('boundaryElement', () => {\n      this.OR([\n        { ALT: () => this.SUBRULE(this.actorDeclarationOnly) },\n        {\n          ALT: () => {\n            this.SUBRULE(this.entityName);\n            this.SUBRULE(this.lineEnd);\n          },\n        },\n      ]);\n    });\n\n    this.RULE('metadataAssignmentStatement', () => {\n      this.SUBRULE(this.metadataAssignmentTarget);\n      this.SUBRULE(this.metadata);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('metadataAssignmentTarget', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(Identifier) },\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(MarkdownString) },\n      ]);\n    });\n\n    this.RULE('noteStatement', () => {\n      this.CONSUME(Note);\n      this.CONSUME(For);\n      this.CONSUME(Identifier);\n      this.SUBRULE(this.nodeLabel);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('stereotype', () => {\n      this.CONSUME(StereotypeStart);\n      this.CONSUME(StereotypeText);\n      this.CONSUME(StereotypeEnd);\n    });\n\n    this.RULE('classSuffix', () => {\n      this.CONSUME(ClassSeparator);\n      this.CONSUME(Identifier);\n      this.MANY(() => {\n        this.CONSUME(Comma);\n        this.CONSUME2(Identifier);\n      });\n    });\n\n    this.RULE('jsonStatement', () => {\n      this.CONSUME(JsonDeclarationStart);\n      this.CONSUME(JsonObjectLiteral);\n      this.OPTION(() => this.SUBRULE(this.classSuffix));\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('directionStatement', () => {\n      this.CONSUME(Direction);\n      this.OR([\n        { ALT: () => this.CONSUME(Td) },\n        { ALT: () => this.CONSUME(Tb) },\n        { ALT: () => this.CONSUME(Bt) },\n        { ALT: () => this.CONSUME(Lr) },\n        { ALT: () => this.CONSUME(Rl) },\n      ]);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('classDefStatement', () => {\n      this.CONSUME(ClassDef);\n      this.CONSUME(Identifier);\n      this.MANY(() => {\n        this.CONSUME(Comma);\n        this.CONSUME2(Identifier);\n      });\n      this.SUBRULE(this.styles);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('classStatement', () => {\n      this.CONSUME(Class);\n      this.CONSUME(Identifier);\n      this.MANY(() => {\n        this.CONSUME(Comma);\n        this.CONSUME2(Identifier);\n      });\n      this.CONSUME3(Identifier);\n      this.MANY2(() => {\n        this.CONSUME2(Comma);\n        this.CONSUME4(Identifier);\n      });\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('styleStatement', () => {\n      this.CONSUME(Style);\n      this.CONSUME(Identifier);\n      this.SUBRULE(this.styles);\n      this.SUBRULE(this.lineEnd);\n    });\n\n    this.RULE('styles', () => {\n      this.SUBRULE(this.styleValue);\n      this.MANY(() => {\n        this.CONSUME(Comma);\n        this.SUBRULE2(this.styleValue);\n      });\n    });\n\n    this.RULE('styleValue', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(Word) },\n        { ALT: () => this.CONSUME(CssIdentifier) },\n        {\n          ALT: () => {\n            this.CONSUME(MarkerlessSolid);\n            this.CONSUME2(Word);\n          },\n        },\n      ]);\n      this.CONSUME(Colon);\n      this.AT_LEAST_ONE(() => this.SUBRULE(this.styleComponent));\n    });\n\n    this.RULE('styleComponent', () => {\n      this.OR([\n        { ALT: () => this.CONSUME(Word) },\n        { ALT: () => this.CONSUME(PlainString) },\n        { ALT: () => this.CONSUME(NumberLiteral) },\n        { ALT: () => this.CONSUME(HashColor) },\n        { ALT: () => this.CONSUME(CssIdentifier) },\n        { ALT: () => this.CONSUME(CssEscapedComma) },\n        { ALT: () => this.CONSUME(Dash) },\n        { ALT: () => this.CONSUME(Dot) },\n        { ALT: () => this.CONSUME(Percent) },\n        { ALT: () => this.CONSUME(CssPunctuation) },\n        { ALT: () => this.CONSUME(Colon) },\n        { ALT: () => this.CONSUME(LeftParen) },\n        { ALT: () => this.CONSUME(RightParen) },\n        { ALT: () => this.CONSUME(LeftBracket) },\n        { ALT: () => this.CONSUME(RightBracket) },\n        { ALT: () => this.CONSUME(LeftBrace) },\n        { ALT: () => this.CONSUME(RightBrace) },\n        { ALT: () => this.CONSUME(At) },\n        { ALT: () => this.CONSUME(MarkerlessSolid) },\n      ]);\n    });\n\n    this.performSelfAnalysis();\n  }\n\n  private isMetadataAssignment(): boolean {\n    const target = this.LA(1).tokenType;\n    return (\n      (target === Identifier || target === PlainString || target === MarkdownString) &&\n      this.LA(2).tokenType === MetadataStart\n    );\n  }\n\n  private isStatementStart(): boolean {\n    const tokenType = this.LA(1).tokenType;\n    return tokenType !== EOF && tokenType !== NewLine && tokenType !== Comment;\n  }\n\n  private isForbiddenPlantUmlStatement(): boolean {\n    return (\n      this.LA(1).tokenType === Identifier &&\n      forbiddenPlantUmlStatements[this.LA(1).image.toLowerCase()] === true\n    );\n  }\n\n  private hasLabeledRight(allowed: TokenType[]): boolean {\n    if (!isLabelToken(this.LA(1))) {\n      return false;\n    }\n    for (let index = 2; ; index++) {\n      const token = this.LA(index);\n      if (allowed.includes(token.tokenType)) {\n        return true;\n      }\n      if (!isLabelToken(token)) {\n        return false;\n      }\n    }\n  }\n}\n\n/** Singleton parser; grammar self-analysis runs once at module load. */\nexport const usecaseParser = new UsecaseParser();\n", "export interface OrderedJsonObject {\n  value: Record<string, unknown>;\n  propertyOrder: Record<string, string[]>;\n}\n\nexport class UsecaseJsonError extends Error {\n  constructor(\n    message: string,\n    public readonly line: number,\n    public readonly column: number\n  ) {\n    super(`${message} (line ${line}, column ${column})`);\n    this.name = 'UsecaseJsonError';\n  }\n}\n\nconst locationAtOffset = (\n  text: string,\n  offset: number,\n  startLine: number,\n  startColumn: number\n): { line: number; column: number } => {\n  let line = startLine;\n  let column = startColumn;\n  const end = Math.min(Math.max(offset, 0), text.length);\n\n  for (let index = 0; index < end; index++) {\n    const character = text[index];\n    if (character === '\\r') {\n      line++;\n      column = 1;\n    } else if (character === '\\n') {\n      if (index === 0 || text[index - 1] !== '\\r') {\n        line++;\n        column = 1;\n      }\n    } else {\n      column++;\n    }\n  }\n\n  return { line, column };\n};\n\nconst locationFromErrorMessage = (\n  message: string,\n  text: string,\n  startLine: number,\n  startColumn: number\n): { line: number; column: number } | undefined => {\n  const position = /\\bposition (\\d+)\\b/u.exec(message);\n  if (position) {\n    return locationAtOffset(text, Number.parseInt(position[1], 10), startLine, startColumn);\n  }\n\n  const localLocation = /\\bline (\\d+) column (\\d+)\\b/u.exec(message);\n  if (localLocation) {\n    const localLine = Number.parseInt(localLocation[1], 10);\n    const localColumn = Number.parseInt(localLocation[2], 10);\n    return {\n      line: startLine + localLine - 1,\n      column: localLine === 1 ? startColumn + localColumn - 1 : localColumn,\n    };\n  }\n\n  if (/unexpected end|end of json input/iu.test(message)) {\n    return locationAtOffset(text, text.length, startLine, startColumn);\n  }\n\n  return undefined;\n};\n\nclass JsonWalkError extends Error {\n  constructor(public readonly offset: number) {\n    super('Invalid JSON token');\n  }\n}\n\n/**\n * Walks JSON tokens only after JSON.parse has authoritatively accepted or rejected the text.\n * Its output is property order on success and a portable diagnostic offset on failure.\n */\nclass PropertyOrderCollector {\n  private offset = 0;\n  readonly propertyOrder: Record<string, string[]> = {};\n\n  constructor(private readonly text: string) {}\n\n  collect(): Record<string, string[]> {\n    this.skipWhitespace();\n    this.collectValue('');\n    this.skipWhitespace();\n    if (this.offset !== this.text.length) {\n      throw new JsonWalkError(this.offset);\n    }\n    return this.propertyOrder;\n  }\n\n  private collectValue(pointer: string): void {\n    this.skipWhitespace();\n    const character = this.text[this.offset];\n\n    if (character === '{') {\n      this.collectObject(pointer);\n    } else if (character === '[') {\n      this.collectArray(pointer);\n    } else if (character === '\"') {\n      this.readString(false);\n    } else if (character === 't') {\n      this.consumeLiteral('true');\n    } else if (character === 'f') {\n      this.consumeLiteral('false');\n    } else if (character === 'n') {\n      this.consumeLiteral('null');\n    } else if (character === '-' || (character >= '0' && character <= '9')) {\n      this.consumeNumber();\n    } else {\n      throw new JsonWalkError(this.offset);\n    }\n  }\n\n  private collectObject(pointer: string): void {\n    this.offset++;\n    const order: string[] = [];\n    const seen = new Set<string>();\n    this.propertyOrder[pointer] = order;\n    this.skipWhitespace();\n\n    if (this.text[this.offset] === '}') {\n      this.offset++;\n      return;\n    }\n\n    while (this.offset < this.text.length) {\n      if (this.text[this.offset] !== '\"') {\n        throw new JsonWalkError(this.offset);\n      }\n      const property = this.readString(true);\n      const propertyPointer = `${pointer}/${property.replaceAll('~', '~0').replaceAll('/', '~1')}`;\n\n      if (seen.has(property)) {\n        this.deletePointerSubtree(propertyPointer);\n      } else {\n        seen.add(property);\n        order.push(property);\n      }\n\n      this.skipWhitespace();\n      if (this.text[this.offset] !== ':') {\n        throw new JsonWalkError(this.offset);\n      }\n      this.offset++;\n      this.collectValue(propertyPointer);\n      this.skipWhitespace();\n\n      if (this.text[this.offset] === '}') {\n        this.offset++;\n        return;\n      }\n      if (this.text[this.offset] !== ',') {\n        throw new JsonWalkError(this.offset);\n      }\n\n      this.offset++;\n      this.skipWhitespace();\n    }\n\n    throw new JsonWalkError(this.offset);\n  }\n\n  private collectArray(pointer: string): void {\n    this.offset++;\n    this.skipWhitespace();\n\n    if (this.text[this.offset] === ']') {\n      this.offset++;\n      return;\n    }\n\n    let index = 0;\n    while (this.offset < this.text.length) {\n      this.collectValue(`${pointer}/${index}`);\n      index++;\n      this.skipWhitespace();\n\n      if (this.text[this.offset] === ']') {\n        this.offset++;\n        return;\n      }\n      if (this.text[this.offset] !== ',') {\n        throw new JsonWalkError(this.offset);\n      }\n\n      this.offset++;\n      this.skipWhitespace();\n    }\n\n    throw new JsonWalkError(this.offset);\n  }\n\n  private readString(decode: boolean): string {\n    this.offset++;\n    let value = '';\n\n    while (this.offset < this.text.length) {\n      const characterOffset = this.offset;\n      const character = this.text[this.offset++];\n      if (character === '\"') {\n        return value;\n      }\n      if (character.charCodeAt(0) < 0x20) {\n        throw new JsonWalkError(characterOffset);\n      }\n      if (character !== '\\\\') {\n        if (decode) {\n          value += character;\n        }\n        continue;\n      }\n\n      const escapeOffset = this.offset;\n      const escape = this.text[this.offset++];\n      switch (escape) {\n        case '\"':\n        case '\\\\':\n        case '/':\n          if (decode) {\n            value += escape;\n          }\n          break;\n        case 'b':\n          if (decode) {\n            value += '\\b';\n          }\n          break;\n        case 'f':\n          if (decode) {\n            value += '\\f';\n          }\n          break;\n        case 'n':\n          if (decode) {\n            value += '\\n';\n          }\n          break;\n        case 'r':\n          if (decode) {\n            value += '\\r';\n          }\n          break;\n        case 't':\n          if (decode) {\n            value += '\\t';\n          }\n          break;\n        case 'u': {\n          const codeUnit = this.text.slice(this.offset, this.offset + 4);\n          if (!/^[\\dA-Fa-f]{4}$/u.test(codeUnit)) {\n            throw new JsonWalkError(this.offset);\n          }\n          if (decode) {\n            value += String.fromCharCode(Number.parseInt(codeUnit, 16));\n          }\n          this.offset += 4;\n          break;\n        }\n        default:\n          throw new JsonWalkError(escapeOffset);\n      }\n    }\n\n    throw new JsonWalkError(this.offset);\n  }\n\n  private consumeLiteral(literal: string): void {\n    let index = 0;\n    for (const element of literal) {\n      if (this.text[this.offset + index] !== element) {\n        throw new JsonWalkError(this.offset + index);\n      }\n      index++;\n    }\n    this.offset += literal.length;\n  }\n\n  private consumeNumber(): void {\n    if (this.text[this.offset] === '-') {\n      this.offset++;\n    }\n\n    if (this.text[this.offset] === '0') {\n      this.offset++;\n    } else if (this.text[this.offset] >= '1' && this.text[this.offset] <= '9') {\n      while (this.text[this.offset] >= '0' && this.text[this.offset] <= '9') {\n        this.offset++;\n      }\n    } else {\n      throw new JsonWalkError(this.offset);\n    }\n\n    if (this.text[this.offset] === '.') {\n      this.offset++;\n      if (this.text[this.offset] < '0' || this.text[this.offset] > '9') {\n        throw new JsonWalkError(this.offset);\n      }\n      while (this.text[this.offset] >= '0' && this.text[this.offset] <= '9') {\n        this.offset++;\n      }\n    }\n\n    if (this.text[this.offset] === 'e' || this.text[this.offset] === 'E') {\n      this.offset++;\n      if (this.text[this.offset] === '+' || this.text[this.offset] === '-') {\n        this.offset++;\n      }\n      if (this.text[this.offset] < '0' || this.text[this.offset] > '9') {\n        throw new JsonWalkError(this.offset);\n      }\n      while (this.text[this.offset] >= '0' && this.text[this.offset] <= '9') {\n        this.offset++;\n      }\n    }\n  }\n\n  private skipWhitespace(): void {\n    while (this.offset < this.text.length) {\n      const character = this.text[this.offset];\n      if (character !== ' ' && character !== '\\t' && character !== '\\n' && character !== '\\r') {\n        return;\n      }\n      this.offset++;\n    }\n  }\n\n  private deletePointerSubtree(pointer: string): void {\n    const descendantPrefix = `${pointer}/`;\n    for (const existingPointer of Object.keys(this.propertyOrder)) {\n      if (existingPointer === pointer || existingPointer.startsWith(descendantPrefix)) {\n        delete this.propertyOrder[existingPointer];\n      }\n    }\n  }\n}\n\nexport function parseOrderedJsonObject(\n  jsonText: string,\n  startLine: number,\n  startColumn: number\n): OrderedJsonObject {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(jsonText);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    let location = locationFromErrorMessage(message, jsonText, startLine, startColumn);\n    if (!location) {\n      let invalidOffset = 0;\n      try {\n        new PropertyOrderCollector(jsonText).collect();\n      } catch (walkError) {\n        if (walkError instanceof JsonWalkError) {\n          invalidOffset = walkError.offset;\n        }\n      }\n      location = locationAtOffset(jsonText, invalidOffset, startLine, startColumn);\n    }\n    throw new UsecaseJsonError(`Invalid JSON: ${message}`, location.line, location.column);\n  }\n\n  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n    throw new UsecaseJsonError('JSON value must have an object root', startLine, startColumn);\n  }\n\n  return {\n    value: parsed as Record<string, unknown>,\n    propertyOrder: new PropertyOrderCollector(jsonText).collect(),\n  };\n}\n", "import { ARROW_TYPE } from './usecaseTypes.js';\nimport type {\n  Actor,\n  ClassDef,\n  Direction,\n  GraphAST,\n  GraphEdge,\n  GraphGroup,\n  GraphNode,\n  GraphStatement,\n  Relationship,\n  Span,\n  SystemBoundary,\n  UseCase,\n  UsecaseJsonNode,\n  UsecaseNote,\n} from './usecaseTypes.js';\n\nexport interface UsecaseModelReader {\n  getActors(): ReadonlyMap<string, Actor>;\n  getUseCases(): ReadonlyMap<string, UseCase>;\n  getSystemBoundaries(): ReadonlyMap<string, SystemBoundary>;\n  getRelationships(): readonly Relationship[];\n  getNotes(): ReadonlyMap<string, UsecaseNote>;\n  getJsonNodes(): ReadonlyMap<string, UsecaseJsonNode>;\n  getClassDefs(): ReadonlyMap<string, ClassDef>;\n  getDirection(): Direction;\n  getAccTitle(): string;\n  getAccDescription(): string;\n}\n\nconst actorNode = (actor: Actor): GraphNode => ({\n  shape:\n    actor.type === 'normal'\n      ? 'actor'\n      : actor.type === 'hollow'\n        ? 'actor-hollow'\n        : actor.type === 'awesome'\n          ? 'actor-awesome'\n          : 'actor-icon',\n  ...(actor.label === actor.id ? {} : { label: actor.label }),\n  ...(actor.classes.length ? { classes: [...actor.classes] } : {}),\n  ...(actor.styles.length ? { styles: [...actor.styles] } : {}),\n  attrs: {\n    kind: 'actor',\n    actorType: actor.type,\n    business: actor.business,\n    labelType: actor.labelType,\n    ...(actor.icon ? { icon: actor.icon } : {}),\n    ...(actor.stereotype ? { stereotype: actor.stereotype } : {}),\n    ...(actor.parentId ? { parentId: actor.parentId } : {}),\n  },\n});\n\nconst useCaseNode = (useCase: UseCase): GraphNode => ({\n  shape: useCase.shape,\n  ...(useCase.label === useCase.id ? {} : { label: useCase.label }),\n  ...(useCase.classes.length ? { classes: [...useCase.classes] } : {}),\n  ...(useCase.styles.length ? { styles: [...useCase.styles] } : {}),\n  attrs: {\n    kind: 'usecase',\n    useCaseShape: useCase.shape,\n    business: useCase.business,\n    labelType: useCase.labelType,\n    ...(useCase.stereotype ? { stereotype: useCase.stereotype } : {}),\n    ...(useCase.parentId ? { parentId: useCase.parentId } : {}),\n  },\n});\n\nconst noteNode = (note: UsecaseNote): GraphNode => ({\n  label: note.label,\n  shape: 'note',\n  attrs: { kind: 'note', target: note.target, labelType: note.labelType },\n});\n\nconst jsonNode = (json: UsecaseJsonNode): GraphNode => ({\n  label: json.id,\n  shape: 'json-table',\n  ...(json.classes.length ? { classes: [...json.classes] } : {}),\n  ...(json.styles.length ? { styles: [...json.styles] } : {}),\n  attrs: { kind: 'json', value: json.value, propertyOrder: json.propertyOrder, labelType: 'text' },\n});\n\nconst relationshipEdge = (relationship: Relationship): GraphEdge => ({\n  id: relationship.id,\n  source: relationship.source,\n  target: relationship.target,\n  ...(relationship.label ? { label: relationship.label } : {}),\n  ...(relationship.classes.length ? { classes: [...relationship.classes] } : {}),\n  ...(relationship.styles.length ? { styles: [...relationship.styles] } : {}),\n  attrs: {\n    relationshipType: relationship.type,\n    arrowType: relationship.arrowType,\n    minlen: relationship.minlen,\n    explicitId: relationship.explicitId,\n    animate: relationship.animate,\n    ...(relationship.animation ? { animation: relationship.animation } : {}),\n    ...(relationship.labelType ? { labelType: relationship.labelType } : {}),\n  },\n});\n\nconst noteEdge = (note: UsecaseNote): GraphEdge => ({\n  id: `${note.id}-edge`,\n  source: note.id,\n  target: note.target,\n  attrs: {\n    relationshipType: 'note',\n    arrowType: ARROW_TYPE.LINE_SOLID,\n    pattern: 'dotted',\n    minlen: 1,\n    explicitId: false,\n    animate: false,\n    internal: true,\n  },\n});\n\nexport const buildUsecaseGraphAST = (\n  model: UsecaseModelReader,\n  source: string,\n  headerSpan: Span,\n  statements: GraphStatement[]\n): GraphAST => {\n  const nodes: Record<string, GraphNode> = {};\n  for (const actor of model.getActors().values()) {\n    nodes[actor.id] = actorNode(actor);\n  }\n  for (const useCase of model.getUseCases().values()) {\n    nodes[useCase.id] = useCaseNode(useCase);\n  }\n  for (const note of model.getNotes().values()) {\n    nodes[note.id] = noteNode(note);\n  }\n  for (const json of model.getJsonNodes().values()) {\n    nodes[json.id] = jsonNode(json);\n  }\n\n  const groups: Record<string, GraphGroup> = {};\n  for (const boundary of model.getSystemBoundaries().values()) {\n    groups[boundary.id] = {\n      ...(boundary.label === boundary.id ? {} : { title: boundary.label }),\n      nodes: [...boundary.members],\n      ...(boundary.classes.length ? { classes: [...boundary.classes] } : {}),\n      ...(boundary.styles.length ? { styles: [...boundary.styles] } : {}),\n      attrs: {\n        kind: 'systemBoundary',\n        boundaryType: boundary.type,\n        labelType: boundary.labelType,\n      },\n    };\n  }\n\n  const classDefs: GraphAST['classDefs'] = {};\n  for (const definition of model.getClassDefs().values()) {\n    classDefs[definition.id] = { styles: [...definition.styles] };\n  }\n  const direction = model.getDirection();\n  return {\n    version: 1,\n    diagramType: 'usecase',\n    source,\n    header: {\n      keyword: 'usecase',\n      direction: direction === 'TD' ? 'TB' : direction,\n      span: headerSpan,\n    },\n    ...(model.getAccTitle() ? { accTitle: model.getAccTitle() } : {}),\n    ...(model.getAccDescription() ? { accDescr: model.getAccDescription() } : {}),\n    nodes,\n    edges: [\n      ...model.getRelationships().map(relationshipEdge),\n      ...[...model.getNotes().values()].map(noteEdge),\n    ],\n    groups,\n    classDefs,\n    statements,\n  };\n};\n", "// cspell:ignore markerless\n\nimport { buildUsecaseGraphAST, type UsecaseModelReader } from '../usecaseAst.js';\nimport type {\n  Actor,\n  ActorType,\n  Animation,\n  ArrowType,\n  BoundaryType,\n  ClassDef,\n  Direction,\n  GraphAST,\n  GraphStatement,\n  LabelType,\n  MetadataOccurrence,\n  Relationship,\n  RelationshipType,\n  Span,\n  SystemBoundary,\n  UseCase,\n  UseCaseShape,\n  UsecaseDB,\n  UsecaseFields,\n  UsecaseJsonNode,\n  UsecaseNote,\n  UsecaseSymbolKind,\n} from '../usecaseTypes.js';\n\nexport interface DraftLocation {\n  span: Span;\n  line: number;\n  column: number;\n}\nexport interface DraftLabel {\n  text: string;\n  type: LabelType;\n  span: Span;\n}\nexport interface DraftMetadataProperty extends MetadataOccurrence {\n  value: string | boolean;\n  location: DraftLocation;\n}\nexport interface DraftMetadata {\n  properties: DraftMetadataProperty[];\n  location: DraftLocation;\n}\nexport interface DraftElement {\n  id: string;\n  kind: 'actor' | 'usecase';\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  parentId?: string;\n  parentLocation?: DraftLocation;\n  shape?: UseCaseShape;\n  metadata?: DraftMetadata;\n  stereotype?: string;\n  stereotypeSpan?: Span;\n  classes: string[];\n}\nexport interface DraftBoundary {\n  id: string;\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  classes: string[];\n}\nexport interface DraftJson {\n  id: string;\n  value: Record<string, unknown>;\n  propertyOrder: Record<string, string[]>;\n  location: DraftLocation;\n  classes: string[];\n}\nexport interface DraftEndpoint {\n  id: string;\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  declaration: boolean;\n  classesOnReference: boolean;\n}\nexport interface DraftRelationship {\n  source: DraftEndpoint;\n  target: DraftEndpoint;\n  location: DraftLocation;\n  explicitId?: string;\n  explicitIdLocation?: DraftLocation;\n  type: RelationshipType;\n  arrowType: ArrowType;\n  label?: DraftLabel;\n  minlen: number;\n}\nexport interface DraftNote {\n  target: string;\n  targetLocation: DraftLocation;\n  label: DraftLabel;\n  location: DraftLocation;\n}\ninterface DraftMetadataAssignment {\n  target: string;\n  targetLocation: DraftLocation;\n  metadata: DraftMetadata;\n  statement: GraphStatement;\n}\ninterface DraftClassAssignment {\n  targets: { id: string; location: DraftLocation }[];\n  classes: string[];\n}\ninterface DraftStyleAssignment {\n  target: string;\n  location: DraftLocation;\n  styles: string[];\n}\ninterface SymbolOrigin {\n  kind: UsecaseSymbolKind;\n  location: DraftLocation;\n  generated: boolean;\n  /** Source label a generated ID was derived from; absent when the ID was written explicitly. */\n  label?: string;\n}\ninterface ElementState {\n  kind: 'actor' | 'usecase';\n  id: string;\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  parentId?: string;\n  parentLocation?: DraftLocation;\n  shape?: UseCaseShape;\n  stereotype?: string;\n  stereotypeLocation?: DraftLocation;\n  classes: string[];\n  actorType?: Exclude<ActorType, 'icon'>;\n  icon?: string;\n  business?: boolean;\n}\ninterface BoundaryState {\n  id: string;\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  type?: BoundaryType;\n  classes: string[];\n  styles: string[];\n  members: string[];\n}\ninterface EdgeState {\n  draft: DraftRelationship;\n  relationship: Relationship;\n}\n\nconst locationText = (location: DraftLocation): string =>\n  `line ${location.line}, column ${location.column} [${location.span[0]},${location.span[1]})`;\n/**\n * Names the source label a generated ID was derived from, so that a collision between two\n * different labels that normalize to the same ID points at both originals.\n */\nconst labelSuffix = (label: string | undefined): string =>\n  label === undefined ? '' : ` (label \"${label}\")`;\nconst generatedFrom = (origin: { generated: boolean; label?: string }): string | undefined =>\n  origin.generated ? origin.label : undefined;\nconst pushUnique = (target: string[], values: readonly string[]): void => {\n  for (const value of values) {\n    if (!target.includes(value)) {\n      target.push(value);\n    }\n  }\n};\n\n/** Collects detached CST drafts and atomically publishes a fully resolved model and AST. */\nexport class UsecaseModelBuilder implements UsecaseModelReader {\n  private model: UsecaseFields;\n  private source = '';\n  private statements: GraphStatement[] = [];\n  private readonly elements: DraftElement[] = [];\n  private readonly boundaries: DraftBoundary[] = [];\n  private readonly jsonDrafts: DraftJson[] = [];\n  private readonly relationshipDrafts: DraftRelationship[] = [];\n  private readonly noteDrafts: DraftNote[] = [];\n  private readonly metadataAssignments: DraftMetadataAssignment[] = [];\n  private readonly classAssignments: DraftClassAssignment[] = [];\n  private readonly styleAssignments: DraftStyleAssignment[] = [];\n  private readonly classDefinitions: { ids: string[]; styles: string[] }[] = [];\n  private readonly directions: Direction[] = [];\n\n  constructor(private readonly db: UsecaseDB) {\n    this.model = db.createModel();\n  }\n  reset(source: string): void {\n    this.model = this.db.createModel();\n    this.source = source;\n    this.statements = [];\n    this.elements.length = 0;\n    this.boundaries.length = 0;\n    this.jsonDrafts.length = 0;\n    this.relationshipDrafts.length = 0;\n    this.noteDrafts.length = 0;\n    this.metadataAssignments.length = 0;\n    this.classAssignments.length = 0;\n    this.styleAssignments.length = 0;\n    this.classDefinitions.length = 0;\n    this.directions.length = 0;\n  }\n  addElement(value: DraftElement): void {\n    this.elements.push(value);\n  }\n  addBoundary(value: DraftBoundary): void {\n    this.boundaries.push(value);\n  }\n  addJson(value: DraftJson): void {\n    this.jsonDrafts.push(value);\n  }\n  addRelationship(value: DraftRelationship): void {\n    this.relationshipDrafts.push(value);\n  }\n  addNote(value: DraftNote): void {\n    this.noteDrafts.push(value);\n  }\n  addMetadataAssignment(\n    target: string,\n    targetLocation: DraftLocation,\n    metadata: DraftMetadata,\n    statement: GraphStatement\n  ): void {\n    this.metadataAssignments.push({ target, targetLocation, metadata, statement });\n  }\n  addClassDef(ids: string[], styles: string[]): void {\n    this.classDefinitions.push({ ids, styles });\n  }\n  addClassAssignment(targets: { id: string; location: DraftLocation }[], classes: string[]): void {\n    this.classAssignments.push({ targets, classes });\n  }\n  addStyleAssignment(target: string, location: DraftLocation, styles: string[]): void {\n    this.styleAssignments.push({ target, location, styles });\n  }\n  setDirection(direction: Direction): void {\n    this.directions.push(direction === 'TD' ? 'TB' : direction);\n  }\n  setAccTitle(title: string): void {\n    this.model.accTitle = title;\n  }\n  setAccDescription(description: string): void {\n    this.model.accDescription = description;\n  }\n  setStatements(statements: GraphStatement[]): void {\n    this.statements = statements;\n  }\n  getActors(): ReadonlyMap<string, Actor> {\n    return this.model.actors;\n  }\n  getUseCases(): ReadonlyMap<string, UseCase> {\n    return this.model.useCases;\n  }\n  getSystemBoundaries(): ReadonlyMap<string, SystemBoundary> {\n    return this.model.systemBoundaries;\n  }\n  getRelationships(): readonly Relationship[] {\n    return this.model.relationships;\n  }\n  getNotes(): ReadonlyMap<string, UsecaseNote> {\n    return this.model.notes;\n  }\n  getJsonNodes(): ReadonlyMap<string, UsecaseJsonNode> {\n    return this.model.jsonNodes;\n  }\n  getClassDefs(): ReadonlyMap<string, ClassDef> {\n    return this.model.classDefs;\n  }\n  getDirection(): Direction {\n    return this.model.direction;\n  }\n  getAccTitle(): string {\n    return this.model.accTitle;\n  }\n  getAccDescription(): string {\n    return this.model.accDescription;\n  }\n\n  finalize(headerSpan: Span): GraphAST {\n    const symbols = new Map<string, SymbolOrigin>();\n    const elements = new Map<string, ElementState>();\n    const boundaries = new Map<string, BoundaryState>();\n    const first = new Map<string, number>();\n    for (const relation of this.relationshipDrafts) {\n      this.recordFirst(first, relation.source.id, relation.source.location.span[0]);\n      this.recordFirst(first, relation.target.id, relation.target.location.span[0]);\n    }\n    for (const draft of this.elements) {\n      this.recordFirst(first, draft.id, draft.location.span[0]);\n    }\n    for (const draft of this.boundaries) {\n      this.recordFirst(first, draft.id, draft.location.span[0]);\n    }\n    for (const draft of this.jsonDrafts) {\n      this.recordFirst(first, draft.id, draft.location.span[0]);\n    }\n    const declarations = [\n      ...this.elements.map((value) => ({\n        offset: value.location.span[0],\n        type: 'element' as const,\n        value,\n      })),\n      ...this.boundaries.map((value) => ({\n        offset: value.location.span[0],\n        type: 'boundary' as const,\n        value,\n      })),\n      ...this.jsonDrafts.map((value) => ({\n        offset: value.location.span[0],\n        type: 'json' as const,\n        value,\n      })),\n      ...this.relationshipDrafts\n        .filter((value) => value.explicitId)\n        .map((value) => ({\n          offset: value.explicitIdLocation!.span[0],\n          type: 'edge' as const,\n          value,\n        })),\n    ].sort((a, b) => a.offset - b.offset);\n    for (const item of declarations) {\n      if (item.type === 'element') {\n        this.collectElement(item.value, symbols, elements);\n      } else if (item.type === 'boundary') {\n        this.collectBoundary(item.value, symbols, boundaries);\n      } else if (item.type === 'json') {\n        this.registerUnique(symbols, item.value.id, 'json', item.value.location, false);\n      } else {\n        this.registerUnique(\n          symbols,\n          item.value.explicitId!,\n          'edge',\n          item.value.explicitIdLocation!,\n          false\n        );\n      }\n    }\n    this.materializeElements(elements, first);\n    this.materializeBoundaries(boundaries, first);\n    this.materializeJson(first);\n    const edges = this.materializeRelationships(symbols, elements, first);\n    this.reorderElements(elements, first);\n    this.applyMetadataAssignments(symbols, elements, boundaries, edges);\n    this.validateAndRefreshElements(elements);\n    this.refreshBoundaries(boundaries, elements);\n    this.materializeNotes(symbols);\n    this.applyClassDefinitions();\n    this.applyClassesAndStyles(symbols, edges);\n    this.model.direction = this.directions.at(-1) ?? this.model.direction;\n    this.model.symbols = new Map([...symbols].map(([id, origin]) => [id, origin.kind]));\n    const ast = buildUsecaseGraphAST(this, this.source, headerSpan, this.statements);\n    this.model.ast = ast;\n    this.db.commit(this.model);\n    return ast;\n  }\n\n  private collectElement(\n    draft: DraftElement,\n    symbols: Map<string, SymbolOrigin>,\n    states: Map<string, ElementState>\n  ): void {\n    const origin = symbols.get(draft.id);\n    const draftLabel = generatedFrom({ generated: draft.generated, label: draft.label.text });\n    if (origin && origin.kind !== draft.kind) {\n      this.conflict(\n        `ID '${draft.id}' is declared as both ${origin.kind} and ${draft.kind}`,\n        draft.location,\n        origin.location,\n        draftLabel,\n        generatedFrom(origin)\n      );\n    }\n    if (origin && (origin.generated || draft.generated)) {\n      this.conflict(\n        `Generated ID '${draft.id}' collides with another declaration`,\n        draft.location,\n        origin.location,\n        draftLabel,\n        generatedFrom(origin)\n      );\n    }\n    const existing = states.get(draft.id);\n    if (!existing) {\n      const state: ElementState = {\n        kind: draft.kind,\n        id: draft.id,\n        label: draft.label,\n        location: draft.location,\n        generated: draft.generated,\n        classes: [...draft.classes],\n        ...(draft.parentId\n          ? { parentId: draft.parentId, parentLocation: draft.parentLocation }\n          : {}),\n        ...(draft.shape ? { shape: draft.shape } : {}),\n        ...(draft.stereotype\n          ? { stereotype: draft.stereotype, stereotypeLocation: draft.location }\n          : {}),\n      };\n      this.applyDeclarationMetadata(state, draft.metadata);\n      states.set(draft.id, state);\n      symbols.set(draft.id, {\n        kind: draft.kind,\n        location: draft.location,\n        generated: draft.generated,\n        label: draft.label.text,\n      });\n      return;\n    }\n    if (existing.label.text !== draft.label.text || existing.label.type !== draft.label.type) {\n      this.conflict(`ID '${draft.id}' has conflicting labels`, draft.location, existing.location);\n    }\n    if (draft.shape && existing.shape && draft.shape !== existing.shape) {\n      this.conflict(\n        `Use case '${draft.id}' has conflicting shapes`,\n        draft.location,\n        existing.location\n      );\n    }\n    if (draft.parentId && existing.parentId && draft.parentId !== existing.parentId) {\n      this.conflict(\n        `Element '${draft.id}' belongs to more than one system boundary`,\n        draft.parentLocation ?? draft.location,\n        existing.parentLocation ?? existing.location\n      );\n    }\n    if (draft.stereotype && existing.stereotype && draft.stereotype !== existing.stereotype) {\n      this.conflict(\n        `Element '${draft.id}' has conflicting stereotypes`,\n        draft.location,\n        existing.stereotypeLocation ?? existing.location\n      );\n    }\n    existing.shape ??= draft.shape;\n    existing.parentId ??= draft.parentId;\n    existing.parentLocation ??= draft.parentLocation;\n    existing.stereotype ??= draft.stereotype;\n    existing.stereotypeLocation ??= draft.stereotype ? draft.location : undefined;\n    pushUnique(existing.classes, draft.classes);\n    this.applyDeclarationMetadata(existing, draft.metadata);\n  }\n\n  private collectBoundary(\n    draft: DraftBoundary,\n    symbols: Map<string, SymbolOrigin>,\n    states: Map<string, BoundaryState>\n  ): void {\n    const origin = symbols.get(draft.id);\n    const draftLabel = generatedFrom({ generated: draft.generated, label: draft.label.text });\n    if (origin && origin.kind !== 'boundary') {\n      this.conflict(\n        `ID '${draft.id}' is declared as both ${origin.kind} and boundary`,\n        draft.location,\n        origin.location,\n        draftLabel,\n        generatedFrom(origin)\n      );\n    }\n    if (origin && (origin.generated || draft.generated)) {\n      this.conflict(\n        `Generated ID '${draft.id}' collides with another declaration`,\n        draft.location,\n        origin.location,\n        draftLabel,\n        generatedFrom(origin)\n      );\n    }\n    const existing = states.get(draft.id);\n    if (existing) {\n      if (existing.label.text !== draft.label.text || existing.label.type !== draft.label.type) {\n        this.conflict(\n          `Boundary '${draft.id}' has conflicting titles`,\n          draft.location,\n          existing.location\n        );\n      }\n      pushUnique(existing.classes, draft.classes);\n      return;\n    }\n    states.set(draft.id, {\n      id: draft.id,\n      label: draft.label,\n      location: draft.location,\n      generated: draft.generated,\n      classes: [...draft.classes],\n      styles: [],\n      members: [],\n    });\n    symbols.set(draft.id, {\n      kind: 'boundary',\n      location: draft.location,\n      generated: draft.generated,\n      label: draft.label.text,\n    });\n  }\n\n  private materializeElements(states: Map<string, ElementState>, first: Map<string, number>): void {\n    for (const state of [...states.values()].sort(\n      (a, b) => (first.get(a.id) ?? 0) - (first.get(b.id) ?? 0)\n    )) {\n      this.setElementModel(state);\n    }\n  }\n  private materializeBoundaries(\n    states: Map<string, BoundaryState>,\n    first: Map<string, number>\n  ): void {\n    for (const state of [...states.values()].sort(\n      (a, b) => (first.get(a.id) ?? 0) - (first.get(b.id) ?? 0)\n    )) {\n      this.model.systemBoundaries.set(state.id, {\n        id: state.id,\n        label: state.label.text,\n        labelType: state.label.type,\n        type: state.type ?? 'rect',\n        members: [],\n        classes: [...state.classes],\n        styles: [...state.styles],\n      });\n    }\n  }\n  private materializeJson(first: Map<string, number>): void {\n    for (const draft of [...this.jsonDrafts].sort(\n      (a, b) => (first.get(a.id) ?? 0) - (first.get(b.id) ?? 0)\n    )) {\n      this.model.jsonNodes.set(draft.id, {\n        id: draft.id,\n        value: draft.value,\n        propertyOrder: draft.propertyOrder,\n        classes: [...draft.classes],\n        styles: [],\n      });\n    }\n  }\n  private materializeRelationships(\n    symbols: Map<string, SymbolOrigin>,\n    states: Map<string, ElementState>,\n    first: Map<string, number>\n  ): Map<string, EdgeState> {\n    const edges = new Map<string, EdgeState>();\n    let anonymous = 0;\n    for (const draft of this.relationshipDrafts) {\n      const sourceKind = this.resolveEndpoint(draft.source, symbols, states, first);\n      const targetKind = this.resolveEndpoint(draft.target, symbols, states, first);\n      this.validateRelationship(draft, sourceKind, targetKind, symbols);\n      const id = draft.explicitId ?? `edge-${anonymous++}`;\n      const relationship: Relationship = {\n        id,\n        explicitId: Boolean(draft.explicitId),\n        source: draft.source.id,\n        target: draft.target.id,\n        type: draft.type,\n        arrowType: draft.arrowType,\n        ...(draft.label ? { label: draft.label.text, labelType: draft.label.type } : {}),\n        minlen: draft.minlen,\n        classes: [],\n        styles: [],\n        animate: false,\n      };\n      this.model.relationships.push(relationship);\n      edges.set(id, { draft, relationship });\n    }\n    this.model.relationshipCounter = anonymous;\n    return edges;\n  }\n  private resolveEndpoint(\n    endpoint: DraftEndpoint,\n    symbols: Map<string, SymbolOrigin>,\n    states: Map<string, ElementState>,\n    first: Map<string, number>\n  ): UsecaseSymbolKind {\n    if (endpoint.classesOnReference && !endpoint.declaration) {\n      throw new Error(\n        `Relationship endpoint '${endpoint.id}' uses ::: without declaring the node at ${locationText(endpoint.location)}`\n      );\n    }\n    const origin = symbols.get(endpoint.id);\n    if (origin) {\n      return origin.kind;\n    }\n    states.set(endpoint.id, {\n      kind: 'usecase',\n      id: endpoint.id,\n      label: endpoint.label,\n      location: endpoint.location,\n      generated: endpoint.generated,\n      shape: 'ellipse',\n      classes: [],\n    });\n    symbols.set(endpoint.id, {\n      kind: 'usecase',\n      location: endpoint.location,\n      generated: endpoint.generated,\n      label: endpoint.label.text,\n    });\n    this.recordFirst(first, endpoint.id, endpoint.location.span[0]);\n    return 'usecase';\n  }\n  private reorderElements(states: Map<string, ElementState>, first: Map<string, number>): void {\n    const actors = new Map(this.model.actors);\n    const useCases = new Map(this.model.useCases);\n    this.model.actors.clear();\n    this.model.useCases.clear();\n    for (const state of [...states.values()].sort(\n      (a, b) => (first.get(a.id) ?? 0) - (first.get(b.id) ?? 0)\n    )) {\n      if (!actors.has(state.id) && !useCases.has(state.id)) {\n        this.setElementModel(state);\n      }\n      const actor = actors.get(state.id) ?? this.model.actors.get(state.id);\n      const useCase = useCases.get(state.id) ?? this.model.useCases.get(state.id);\n      if (actor) {\n        this.model.actors.set(state.id, actor);\n      } else if (useCase) {\n        this.model.useCases.set(state.id, useCase);\n      }\n    }\n  }\n\n  private applyMetadataAssignments(\n    symbols: Map<string, SymbolOrigin>,\n    elements: Map<string, ElementState>,\n    boundaries: Map<string, BoundaryState>,\n    edges: Map<string, EdgeState>\n  ): void {\n    for (const assignment of this.metadataAssignments) {\n      const origin = symbols.get(assignment.target);\n      if (!origin) {\n        const inferred = this.inferMetadataKind(assignment.metadata);\n        throw new Error(\n          `Metadata target '${assignment.target}' is unresolved${inferred ? ` (metadata implies ${inferred})` : ''} at ${locationText(assignment.targetLocation)}`\n        );\n      }\n      if (origin.kind === 'actor' || origin.kind === 'usecase') {\n        this.applyStandaloneElementMetadata(elements.get(assignment.target)!, assignment.metadata);\n      } else if (origin.kind === 'boundary') {\n        const boundary = boundaries.get(assignment.target)!;\n        for (const property of assignment.metadata.properties) {\n          if (\n            property.key !== 'type' ||\n            (property.value !== 'rect' && property.value !== 'package')\n          ) {\n            this.invalidMetadata(assignment.target, origin.kind, property);\n          }\n          boundary.type = property.value;\n        }\n      } else if (origin.kind === 'edge') {\n        const edge = edges.get(assignment.target);\n        if (!edge) {\n          throw new Error(\n            `Metadata target '${assignment.target}' is not an explicit edge at ${locationText(assignment.targetLocation)}`\n          );\n        }\n        assignment.statement.kind = 'edgeMetadata';\n        assignment.statement.edges = [\n          {\n            id: assignment.target,\n            span: assignment.statement.span,\n            idSpan: assignment.targetLocation.span,\n            ...(assignment.statement.metadata ? { metadata: assignment.statement.metadata } : {}),\n          },\n        ];\n        delete assignment.statement.nodes;\n        for (const property of assignment.metadata.properties) {\n          if (property.key === 'animate' && typeof property.value === 'boolean') {\n            edge.relationship.animate = property.value;\n          } else if (\n            property.key === 'animation' &&\n            (property.value === 'fast' || property.value === 'slow')\n          ) {\n            edge.relationship.animation = property.value as Animation;\n            edge.relationship.animate = true;\n          } else {\n            this.invalidMetadata(assignment.target, origin.kind, property);\n          }\n        }\n      } else {\n        for (const property of assignment.metadata.properties) {\n          this.invalidMetadata(assignment.target, origin.kind, property);\n        }\n      }\n    }\n    for (const { relationship } of edges.values()) {\n      if (relationship.animation) {\n        relationship.animate = true;\n      }\n    }\n  }\n  private applyStandaloneElementMetadata(state: ElementState, metadata: DraftMetadata): void {\n    for (const property of metadata.properties) {\n      if (state.kind === 'actor') {\n        this.applyActorProperty(state, property, true);\n      } else if (property.key === 'business' && typeof property.value === 'boolean') {\n        state.business = property.value;\n      } else {\n        this.invalidMetadata(state.id, state.kind, property);\n      }\n    }\n  }\n  private applyDeclarationMetadata(state: ElementState, metadata?: DraftMetadata): void {\n    if (!metadata) {\n      return;\n    }\n    for (const property of metadata.properties) {\n      if (state.kind === 'actor') {\n        this.applyActorProperty(state, property, false);\n      } else if (property.key === 'business' && typeof property.value === 'boolean') {\n        if (state.business !== undefined && state.business !== property.value) {\n          this.conflict(\n            `Use case '${state.id}' has conflicting business metadata`,\n            property.location,\n            state.location\n          );\n        }\n        state.business = property.value;\n      } else {\n        this.invalidMetadata(state.id, state.kind, property);\n      }\n    }\n  }\n  private applyActorProperty(\n    state: ElementState,\n    property: DraftMetadataProperty,\n    replace: boolean\n  ): void {\n    if (\n      property.key === 'type' &&\n      (property.value === 'normal' || property.value === 'hollow' || property.value === 'awesome')\n    ) {\n      if (!replace && state.actorType !== undefined && state.actorType !== property.value) {\n        this.conflict(\n          `Actor '${state.id}' has conflicting type metadata`,\n          property.location,\n          state.location\n        );\n      }\n      state.actorType = property.value;\n    } else if (property.key === 'icon' && typeof property.value === 'string') {\n      if (!replace && state.icon !== undefined && state.icon !== property.value) {\n        this.conflict(\n          `Actor '${state.id}' has conflicting icon metadata`,\n          property.location,\n          state.location\n        );\n      }\n      state.icon = property.value;\n    } else if (property.key === 'business' && typeof property.value === 'boolean') {\n      if (!replace && state.business !== undefined && state.business !== property.value) {\n        this.conflict(\n          `Actor '${state.id}' has conflicting business metadata`,\n          property.location,\n          state.location\n        );\n      }\n      state.business = property.value;\n    } else {\n      this.invalidMetadata(state.id, state.kind, property);\n    }\n  }\n  private validateAndRefreshElements(states: Map<string, ElementState>): void {\n    for (const state of states.values()) {\n      const type: ActorType = state.icon ? 'icon' : (state.actorType ?? 'normal');\n      if (state.kind === 'actor') {\n        if (state.icon && state.actorType && state.actorType !== 'normal') {\n          throw new Error(\n            `Actor '${state.id}' cannot combine icon with type '${state.actorType}' at ${locationText(state.location)}`\n          );\n        }\n        if (state.business && (type === 'icon' || type === 'awesome')) {\n          throw new Error(\n            `Business actor '${state.id}' must use normal or hollow geometry at ${locationText(state.location)}`\n          );\n        }\n      } else if ((state.shape ?? 'ellipse') === 'rect' && state.business) {\n        throw new Error(\n          `Rectangular use case '${state.id}' cannot be a business use case at ${locationText(state.location)}`\n        );\n      }\n      this.setElementModel(state);\n    }\n  }\n  private refreshBoundaries(\n    boundaries: Map<string, BoundaryState>,\n    elements: Map<string, ElementState>\n  ): void {\n    for (const boundary of boundaries.values()) {\n      boundary.members.length = 0;\n    }\n    for (const draft of [...this.elements].sort(\n      (a, b) => a.location.span[0] - b.location.span[0]\n    )) {\n      if (!draft.parentId) {\n        continue;\n      }\n      const boundary = boundaries.get(draft.parentId);\n      if (!boundary) {\n        throw new Error(\n          `Parent boundary '${draft.parentId}' for '${draft.id}' is unresolved at ${locationText(draft.parentLocation ?? draft.location)}`\n        );\n      }\n      if (!boundary.members.includes(draft.id)) {\n        boundary.members.push(draft.id);\n      }\n    }\n    for (const state of elements.values()) {\n      if (state.parentId && !boundaries.has(state.parentId)) {\n        throw new Error(\n          `Parent boundary '${state.parentId}' for '${state.id}' is unresolved at ${locationText(state.parentLocation ?? state.location)}`\n        );\n      }\n    }\n    for (const state of boundaries.values()) {\n      const model = this.model.systemBoundaries.get(state.id)!;\n      model.type = state.type ?? 'rect';\n      model.members = [...state.members];\n      model.classes = [...state.classes];\n      model.styles = [...state.styles];\n    }\n  }\n  private materializeNotes(symbols: Map<string, SymbolOrigin>): void {\n    let counter = 0;\n    for (const draft of this.noteDrafts) {\n      const origin = symbols.get(draft.target);\n      if (!origin) {\n        throw new Error(\n          `Note target '${draft.target}' is unresolved at ${locationText(draft.targetLocation)}`\n        );\n      }\n      if (origin.kind !== 'actor' && origin.kind !== 'usecase') {\n        this.conflict(\n          `Note target '${draft.target}' must be an actor or use case, not ${origin.kind}`,\n          draft.targetLocation,\n          origin.location\n        );\n      }\n      const id = `note-${counter++}`;\n      this.model.notes.set(id, {\n        id,\n        target: draft.target,\n        label: draft.label.text,\n        labelType: draft.label.type,\n      });\n    }\n    this.model.noteCounter = counter;\n  }\n  private applyClassDefinitions(): void {\n    for (const definition of this.classDefinitions) {\n      for (const id of definition.ids) {\n        this.model.classDefs.set(id, { id, styles: [...definition.styles] });\n      }\n    }\n  }\n  private applyClassesAndStyles(\n    symbols: Map<string, SymbolOrigin>,\n    edges: Map<string, EdgeState>\n  ): void {\n    for (const assignment of this.classAssignments) {\n      for (const target of assignment.targets) {\n        pushUnique(\n          this.getStylable(target.id, symbols, edges, target.location).classes,\n          assignment.classes\n        );\n      }\n    }\n    for (const assignment of this.styleAssignments) {\n      this.getStylable(assignment.target, symbols, edges, assignment.location).styles.push(\n        ...assignment.styles\n      );\n    }\n  }\n  private getStylable(\n    id: string,\n    symbols: Map<string, SymbolOrigin>,\n    edges: Map<string, EdgeState>,\n    location: DraftLocation\n  ): { classes: string[]; styles: string[] } {\n    const kind = symbols.get(id)?.kind;\n    const target =\n      kind === 'actor'\n        ? this.model.actors.get(id)\n        : kind === 'usecase'\n          ? this.model.useCases.get(id)\n          : kind === 'boundary'\n            ? this.model.systemBoundaries.get(id)\n            : kind === 'json'\n              ? this.model.jsonNodes.get(id)\n              : kind === 'edge'\n                ? edges.get(id)?.relationship\n                : undefined;\n    if (!target) {\n      throw new Error(\n        `Class/style target '${id}' is unresolved or anonymous at ${locationText(location)}`\n      );\n    }\n    return target;\n  }\n  private validateRelationship(\n    draft: DraftRelationship,\n    sourceKind: UsecaseSymbolKind,\n    targetKind: UsecaseSymbolKind,\n    symbols: Map<string, SymbolOrigin>\n  ): void {\n    const allowed = (kind: UsecaseSymbolKind): boolean =>\n      kind === 'actor' || kind === 'usecase' || kind === 'json';\n    if (!allowed(sourceKind)) {\n      this.conflict(\n        `Relationship source '${draft.source.id}' cannot be ${sourceKind}`,\n        draft.source.location,\n        symbols.get(draft.source.id)!.location\n      );\n    }\n    if (!allowed(targetKind)) {\n      this.conflict(\n        `Relationship target '${draft.target.id}' cannot be ${targetKind}`,\n        draft.target.location,\n        symbols.get(draft.target.id)!.location\n      );\n    }\n    if (\n      (draft.type === 'include' || draft.type === 'extend') &&\n      (sourceKind !== 'usecase' || targetKind !== 'usecase')\n    ) {\n      throw new Error(\n        `${draft.type} relationship requires use-case endpoints at ${locationText(draft.location)}`\n      );\n    }\n    if (\n      draft.type === 'generalization' &&\n      ((sourceKind !== 'actor' && sourceKind !== 'usecase') || sourceKind !== targetKind)\n    ) {\n      throw new Error(\n        `Generalization requires actor-to-actor or use-case-to-use-case endpoints at ${locationText(draft.location)}`\n      );\n    }\n    if (\n      draft.type === 'association' &&\n      (sourceKind === 'json' || targetKind === 'json') &&\n      ![0, 1, 2].includes(draft.arrowType)\n    ) {\n      throw new Error(\n        `JSON relationship '${draft.source.id}' to '${draft.target.id}' permits only point, reversed-point, or markerless solid association at ${locationText(draft.location)}`\n      );\n    }\n  }\n  private setElementModel(state: ElementState): void {\n    if (state.kind === 'actor') {\n      const type: ActorType = state.icon ? 'icon' : (state.actorType ?? 'normal');\n      this.model.useCases.delete(state.id);\n      this.model.actors.set(state.id, {\n        id: state.id,\n        label: state.label.text,\n        labelType: state.label.type,\n        type,\n        ...(state.icon ? { icon: state.icon } : {}),\n        business: state.business ?? false,\n        ...(state.stereotype ? { stereotype: state.stereotype } : {}),\n        ...(state.parentId ? { parentId: state.parentId } : {}),\n        classes: [...state.classes],\n        styles: this.model.actors.get(state.id)?.styles ?? [],\n      });\n    } else {\n      this.model.actors.delete(state.id);\n      this.model.useCases.set(state.id, {\n        id: state.id,\n        label: state.label.text,\n        labelType: state.label.type,\n        shape: state.shape ?? 'ellipse',\n        business: state.business ?? false,\n        ...(state.stereotype ? { stereotype: state.stereotype } : {}),\n        ...(state.parentId ? { parentId: state.parentId } : {}),\n        classes: [...state.classes],\n        styles: this.model.useCases.get(state.id)?.styles ?? [],\n      });\n    }\n  }\n  private inferMetadataKind(metadata: DraftMetadata): string | undefined {\n    const possible = new Set(['actor', 'usecase', 'boundary', 'edge']);\n    for (const property of metadata.properties) {\n      if (property.key === 'icon') {\n        possible.clear();\n        possible.add('actor');\n      } else if (property.key === 'animate' || property.key === 'animation') {\n        possible.clear();\n        possible.add('edge');\n      } else if (property.key === 'type') {\n        possible.clear();\n        if (property.value === 'rect' || property.value === 'package') {\n          possible.add('boundary');\n        } else if (\n          property.value === 'normal' ||\n          property.value === 'hollow' ||\n          property.value === 'awesome'\n        ) {\n          possible.add('actor');\n        }\n      } else if (property.key === 'business') {\n        possible.delete('boundary');\n        possible.delete('edge');\n      } else {\n        return undefined;\n      }\n    }\n    return possible.size === 1 ? [...possible][0] : undefined;\n  }\n  private invalidMetadata(\n    id: string,\n    kind: UsecaseSymbolKind | 'actor' | 'usecase',\n    property: DraftMetadataProperty\n  ): never {\n    throw new Error(\n      `Metadata property '${property.key}' is invalid for ${kind} '${id}' at ${locationText(property.location)}`\n    );\n  }\n  private registerUnique(\n    symbols: Map<string, SymbolOrigin>,\n    id: string,\n    kind: UsecaseSymbolKind,\n    location: DraftLocation,\n    generated: boolean\n  ): void {\n    const previous = symbols.get(id);\n    if (previous) {\n      this.conflict(\n        `ID '${id}' is declared more than once (${previous.kind} and ${kind})`,\n        location,\n        previous.location,\n        undefined,\n        generatedFrom(previous)\n      );\n    }\n    symbols.set(id, { kind, location, generated });\n  }\n  private recordFirst(map: Map<string, number>, id: string, offset: number): void {\n    const previous = map.get(id);\n    if (previous === undefined || offset < previous) {\n      map.set(id, offset);\n    }\n  }\n  private conflict(\n    message: string,\n    current: DraftLocation,\n    previous: DraftLocation,\n    currentLabel?: string,\n    previousLabel?: string\n  ): never {\n    throw new Error(\n      `${message} at ${locationText(current)}${labelSuffix(currentLabel)}; previous declaration at ${locationText(previous)}${labelSuffix(previousLabel)}`\n    );\n  }\n}\n", "// cspell:ignore markerless\n\nimport type { CstNode, IToken } from 'chevrotain';\nimport { db } from '../usecaseDb.js';\nimport { ARROW_TYPE } from '../usecaseTypes.js';\nimport type {\n  ArrowType,\n  Direction,\n  GraphStatement,\n  LabelType,\n  NodeOccurrence,\n  RelationshipType,\n  Span,\n  UseCaseShape,\n} from '../usecaseTypes.js';\nimport { parseOrderedJsonObject } from './usecaseJson.js';\nimport {\n  UsecaseModelBuilder,\n  type DraftBoundary,\n  type DraftElement,\n  type DraftEndpoint,\n  type DraftJson,\n  type DraftLabel,\n  type DraftLocation,\n  type DraftMetadata,\n  type DraftMetadataProperty,\n  type DraftRelationship,\n} from './usecaseModelBuilder.js';\nimport { usecaseParser } from './usecase.parser.js';\n\ntype Ctx = Record<string, (CstNode | IToken)[]>;\ninterface ParsedStereotype {\n  value: string;\n  span: Span;\n}\ninterface ParsedClassSuffix {\n  classes: string[];\n  spans: Span[];\n}\ninterface ParsedActorItem {\n  id: string;\n  label: DraftLabel;\n  location: DraftLocation;\n  generated: boolean;\n  metadata?: DraftMetadata;\n  stereotype?: ParsedStereotype;\n  classes: string[];\n  classSpans: Span[];\n}\ninterface ParsedEntity extends ParsedActorItem {\n  shape?: UseCaseShape;\n  explicitDeclaration: boolean;\n}\ninterface ParsedArrow {\n  type: RelationshipType;\n  arrowType: ArrowType;\n  label?: DraftLabel;\n  minlen: number;\n}\ninterface ParsedRelationTail {\n  explicitId?: string;\n  explicitIdLocation?: DraftLocation;\n  arrow: ParsedArrow;\n  target: ParsedEntity;\n}\nconst BaseVisitor = usecaseParser.getBaseCstVisitorConstructor();\n\nclass UsecaseVisitor extends BaseVisitor {\n  private readonly builder = new UsecaseModelBuilder(db);\n  private source = '';\n  private parentBoundary: { id: string; location: DraftLocation } | undefined;\n  private anonymousEdge = 0;\n  private anonymousNote = 0;\n  constructor() {\n    super();\n    this.validateVisitor();\n  }\n  build(cst: CstNode, source: string): void {\n    this.source = source;\n    this.parentBoundary = undefined;\n    this.anonymousEdge = 0;\n    this.anonymousNote = 0;\n    this.builder.reset(source);\n    this.visit(cst);\n  }\n  start(ctx: Ctx): void {\n    const header = this.tokens(ctx, 'USECASE')[0];\n    const statements: GraphStatement[] = [];\n    for (const line of this.nodes(ctx, 'line')) {\n      statements.push(this.visit(line) as GraphStatement);\n    }\n    this.builder.setStatements(statements);\n    this.builder.finalize(this.tokenSpan(header));\n  }\n  line(ctx: Ctx): GraphStatement {\n    const child = this.firstNode(ctx, 'blankLine', 'commentLine', 'statement');\n    return this.wrap(child, this.visit(child) as GraphStatement);\n  }\n  statement(ctx: Ctx): GraphStatement {\n    return this.visit(\n      this.firstNode(\n        ctx,\n        'accTitleStatement',\n        'accDescrStatement',\n        'directionStatement',\n        'actorStatement',\n        'systemBoundaryStatement',\n        'noteStatement',\n        'jsonStatement',\n        'classDefStatement',\n        'classStatement',\n        'styleStatement',\n        'metadataAssignmentStatement',\n        'entityStatement'\n      )\n    ) as GraphStatement;\n  }\n  lineEnd(_ctx: Ctx): undefined {\n    return undefined;\n  }\n  blankLine(ctx: Ctx): GraphStatement {\n    return { kind: 'blank', span: this.tokenSpan(this.tokens(ctx, 'NEWLINE')[0]) };\n  }\n  commentLine(ctx: Ctx): GraphStatement {\n    return { kind: 'comment', span: this.tokenSpan(this.tokens(ctx, 'COMMENT')[0]) };\n  }\n  accTitleStatement(ctx: Ctx): GraphStatement {\n    const image = this.tokens(ctx, 'ACC_TITLE_LINE')[0].image;\n    this.builder.setAccTitle(image.slice(image.indexOf(':') + 1).trim());\n    return { kind: 'accTitle', span: [0, 0] };\n  }\n  accDescrStatement(ctx: Ctx): GraphStatement {\n    const line = this.tokens(ctx, 'ACC_DESCR_LINE')[0];\n    const block = this.tokens(ctx, 'ACC_DESCR_BLOCK')[0];\n    const description = line\n      ? line.image.slice(line.image.indexOf(':') + 1).trim()\n      : block.image.slice(block.image.indexOf('{') + 1, block.image.lastIndexOf('}')).trim();\n    this.builder.setAccDescription(description);\n    return { kind: 'accDescr', span: [0, 0] };\n  }\n\n  actorStatement(ctx: Ctx): GraphStatement {\n    const nodes = this.nodes(ctx, 'actorItem');\n    const items = nodes.map((node) => this.visit(node) as ParsedActorItem);\n    const relationNode = this.nodes(ctx, 'relationTail')[0];\n    const occurrences = items.map((item, index) => this.actorOccurrence(nodes[index], item, true));\n    for (const item of items) {\n      this.builder.addElement(this.actorDraft(item));\n    }\n    if (!relationNode) {\n      return { kind: 'node', span: [0, 0], nodes: occurrences };\n    }\n    const relation = this.visit(relationNode) as ParsedRelationTail;\n    if (relation.target.explicitDeclaration) {\n      this.builder.addElement(this.entityDraft(relation.target));\n    }\n    const draft = this.relationshipDraft(items[0], relation, this.nodeLocation(relationNode));\n    this.builder.addRelationship(draft);\n    const id = draft.explicitId ?? `edge-${this.anonymousEdge++}`;\n    occurrences.push(\n      this.entityOccurrence(\n        this.nodes(relationNode.children as Ctx, 'entityName')[0],\n        relation.target,\n        relation.target.explicitDeclaration\n      )\n    );\n    return {\n      kind: 'edge',\n      span: [0, 0],\n      nodes: occurrences,\n      edges: [\n        {\n          id,\n          span: [0, 0],\n          ...(draft.explicitIdLocation ? { idSpan: draft.explicitIdLocation.span } : {}),\n          ...(draft.label ? { labelSpan: draft.label.span } : {}),\n        },\n      ],\n    };\n  }\n  actorItem(ctx: Ctx): ParsedActorItem {\n    const base = this.visit(this.nodes(ctx, 'actorName')[0]) as ParsedActorItem;\n    const metadataNode = this.nodes(ctx, 'metadata')[0];\n    const stereotypeNode = this.nodes(ctx, 'stereotype')[0];\n    const classNode = this.nodes(ctx, 'classSuffix')[0];\n    const classes = classNode\n      ? (this.visit(classNode) as ParsedClassSuffix)\n      : { classes: [], spans: [] };\n    return {\n      ...base,\n      ...(metadataNode ? { metadata: this.visit(metadataNode) as DraftMetadata } : {}),\n      ...(stereotypeNode ? { stereotype: this.visit(stereotypeNode) as ParsedStereotype } : {}),\n      classes: classes.classes,\n      classSpans: classes.spans,\n    };\n  }\n  actorName(ctx: Ctx): ParsedActorItem {\n    const identifier = this.tokens(ctx, 'IDENTIFIER')[0];\n    const string = this.tokens(ctx, 'PLAIN_STRING')[0] ?? this.tokens(ctx, 'MARKDOWN_STRING')[0];\n    if (identifier) {\n      const labelNode = this.nodes(ctx, 'nodeLabel')[0];\n      const label = labelNode ? (this.visit(labelNode) as DraftLabel) : this.tokenLabel(identifier);\n      return {\n        id: identifier.image,\n        label,\n        location: this.tokenLocation(identifier),\n        generated: false,\n        classes: [],\n        classSpans: [],\n      };\n    }\n    const label = this.tokenLabel(string);\n    return {\n      id: this.generateId(label.text),\n      label,\n      location: this.tokenLocation(string),\n      generated: true,\n      classes: [],\n      classSpans: [],\n    };\n  }\n  actorDeclarationOnly(ctx: Ctx): GraphStatement {\n    const nodes = this.nodes(ctx, 'actorItem');\n    const items = nodes.map((node) => this.visit(node) as ParsedActorItem);\n    for (const item of items) {\n      this.builder.addElement(this.actorDraft(item));\n    }\n    return {\n      kind: 'node',\n      span: [0, 0],\n      nodes: items.map((item, index) => this.actorOccurrence(nodes[index], item, true)),\n    };\n  }\n\n  entityStatement(ctx: Ctx): GraphStatement {\n    const entityNodes = this.nodes(ctx, 'entityName');\n    const source = this.visit(entityNodes[0]) as ParsedEntity;\n    const relationNode = this.nodes(ctx, 'relationTail')[0];\n    if (!relationNode) {\n      source.explicitDeclaration = true;\n      source.shape ??= 'ellipse';\n      this.builder.addElement(this.entityDraft(source));\n      return {\n        kind: 'node',\n        span: [0, 0],\n        nodes: [this.entityOccurrence(entityNodes[0], source, true)],\n      };\n    }\n    if (source.explicitDeclaration) {\n      this.builder.addElement(this.entityDraft(source));\n    }\n    const relation = this.visit(relationNode) as ParsedRelationTail;\n    if (relation.target.explicitDeclaration) {\n      this.builder.addElement(this.entityDraft(relation.target));\n    }\n    const draft: DraftRelationship = {\n      source: this.endpoint(source),\n      target: this.endpoint(relation.target),\n      location: this.nodeLocation(relationNode),\n      ...(relation.explicitId\n        ? { explicitId: relation.explicitId, explicitIdLocation: relation.explicitIdLocation }\n        : {}),\n      ...relation.arrow,\n    };\n    this.builder.addRelationship(draft);\n    const id = draft.explicitId ?? `edge-${this.anonymousEdge++}`;\n    return {\n      kind: 'edge',\n      span: [0, 0],\n      nodes: [\n        this.entityOccurrence(entityNodes[0], source, source.explicitDeclaration),\n        this.entityOccurrence(\n          this.nodes(relationNode.children as Ctx, 'entityName')[0],\n          relation.target,\n          relation.target.explicitDeclaration\n        ),\n      ],\n      edges: [\n        {\n          id,\n          span: [0, 0],\n          ...(draft.explicitIdLocation ? { idSpan: draft.explicitIdLocation.span } : {}),\n          ...(draft.label ? { labelSpan: draft.label.span } : {}),\n        },\n      ],\n    };\n  }\n  entityName(ctx: Ctx): ParsedEntity {\n    const identifier = this.tokens(ctx, 'IDENTIFIER')[0];\n    const string = this.tokens(ctx, 'PLAIN_STRING')[0] ?? this.tokens(ctx, 'MARKDOWN_STRING')[0];\n    const labelNode = this.nodes(ctx, 'nodeLabel')[0];\n    const metadataNode = this.nodes(ctx, 'useCaseMetadata')[0];\n    const stereotypeNode = this.nodes(ctx, 'stereotype')[0];\n    const classNode = this.nodes(ctx, 'classSuffix')[0];\n    const classes = classNode\n      ? (this.visit(classNode) as ParsedClassSuffix)\n      : { classes: [], spans: [] };\n    if (identifier) {\n      const label = labelNode ? (this.visit(labelNode) as DraftLabel) : this.tokenLabel(identifier);\n      const shape = labelNode\n        ? this.tokens(ctx, 'LBRACKET').length\n          ? 'rect'\n          : 'ellipse'\n        : undefined;\n      return {\n        id: identifier.image,\n        label,\n        location: this.tokenLocation(identifier),\n        generated: false,\n        ...(shape ? { shape } : {}),\n        ...(metadataNode ? { metadata: this.visit(metadataNode) as DraftMetadata } : {}),\n        ...(stereotypeNode ? { stereotype: this.visit(stereotypeNode) as ParsedStereotype } : {}),\n        classes: classes.classes,\n        classSpans: classes.spans,\n        explicitDeclaration: Boolean(shape || metadataNode || stereotypeNode),\n      };\n    }\n    const label = this.tokenLabel(string);\n    return {\n      id: this.generateId(label.text),\n      label,\n      location: this.tokenLocation(string),\n      generated: true,\n      ...(metadataNode ? { metadata: this.visit(metadataNode) as DraftMetadata } : {}),\n      ...(stereotypeNode ? { stereotype: this.visit(stereotypeNode) as ParsedStereotype } : {}),\n      classes: classes.classes,\n      classSpans: classes.spans,\n      explicitDeclaration: Boolean(metadataNode || stereotypeNode),\n    };\n  }\n  nodeLabel(ctx: Ctx): DraftLabel {\n    const tokens = this.allTokens(ctx);\n    if (\n      tokens.length === 1 &&\n      (tokens[0].tokenType.name === 'PLAIN_STRING' ||\n        tokens[0].tokenType.name === 'MARKDOWN_STRING')\n    ) {\n      return this.tokenLabel(tokens[0]);\n    }\n    const span: Span = [\n      tokens[0].startOffset,\n      (tokens.at(-1)!.endOffset ?? tokens.at(-1)!.startOffset) + 1,\n    ];\n    return { text: this.source.slice(span[0], span[1]), type: 'text', span };\n  }\n  useCaseMetadata(ctx: Ctx): DraftMetadata {\n    return this.visit(this.nodes(ctx, 'metadata')[0]) as DraftMetadata;\n  }\n  relationTail(ctx: Ctx): ParsedRelationTail {\n    const explicitId = this.tokens(ctx, 'IDENTIFIER')[0];\n    return {\n      ...(explicitId\n        ? { explicitId: explicitId.image, explicitIdLocation: this.tokenLocation(explicitId) }\n        : {}),\n      arrow: this.visit(this.nodes(ctx, 'arrow')[0]) as ParsedArrow,\n      target: this.visit(this.nodes(ctx, 'entityName')[0]) as ParsedEntity,\n    };\n  }\n  arrow(ctx: Ctx): ParsedArrow {\n    return this.visit(\n      this.firstNode(\n        ctx,\n        'semanticRelation',\n        'forwardSolidOperator',\n        'backwardSolidOperator',\n        'markerlessSolidOperator',\n        'forwardCircleOperator',\n        'backwardCircleOperator',\n        'forwardCrossOperator',\n        'backwardCrossOperator'\n      )\n    ) as ParsedArrow;\n  }\n  edgeLabel(ctx: Ctx): DraftLabel {\n    return this.nodeLabel(ctx);\n  }\n  semanticRelation(ctx: Ctx): ParsedArrow {\n    if (this.tokens(ctx, 'GENERALIZATION').length) {\n      return { type: 'generalization', arrowType: ARROW_TYPE.SOLID_ARROW, minlen: 1 };\n    }\n    const type: RelationshipType = this.tokens(ctx, 'INCLUDE').length ? 'include' : 'extend';\n    const token = this.tokens(ctx, type === 'include' ? 'INCLUDE' : 'EXTEND')[0];\n    return {\n      type,\n      arrowType: ARROW_TYPE.SOLID_ARROW,\n      label: { text: type, type: 'text', span: this.tokenSpan(token) },\n      minlen: 1,\n    };\n  }\n\n  metadata(ctx: Ctx): DraftMetadata {\n    return {\n      properties: this.nodes(ctx, 'metadataProperty').map(\n        (node) => this.visit(node) as DraftMetadataProperty\n      ),\n      location: this.ctxLocation(ctx),\n    };\n  }\n  metadataProperty(ctx: Ctx): DraftMetadataProperty {\n    const tokens = this.allTokens(ctx).filter((token) => token.tokenType.name !== 'COLON');\n    const keyToken = tokens[0];\n    const valueToken = tokens[1];\n    const value =\n      valueToken.tokenType.name === 'TRUE'\n        ? true\n        : valueToken.tokenType.name === 'FALSE'\n          ? false\n          : this.decodePlain(valueToken);\n    const span: Span = [keyToken.startOffset, (valueToken.endOffset ?? valueToken.startOffset) + 1];\n    return {\n      key: this.decodePlain(keyToken),\n      value,\n      span,\n      keySpan: this.contentSpan(keyToken),\n      valueSpan: this.contentSpan(valueToken),\n      location: this.tokenLocation(keyToken),\n    };\n  }\n  metadataSeparator(_ctx: Ctx): undefined {\n    return undefined;\n  }\n\n  systemBoundaryStatement(ctx: Ctx): GraphStatement {\n    const boundary = this.visit(this.nodes(ctx, 'systemBoundaryName')[0]) as DraftBoundary;\n    const classNode = this.nodes(ctx, 'classSuffix')[0];\n    const classes = classNode\n      ? (this.visit(classNode) as ParsedClassSuffix)\n      : { classes: [], spans: [] };\n    boundary.classes = classes.classes;\n    this.builder.addBoundary(boundary);\n    const previous = this.parentBoundary;\n    this.parentBoundary = { id: boundary.id, location: boundary.location };\n    const contentNode = this.nodes(ctx, 'systemBoundaryContent')[0];\n    const children = contentNode ? (this.visit(contentNode) as GraphStatement[]) : [];\n    this.parentBoundary = previous;\n    const end = this.tokens(ctx, 'END')[0];\n    const metadataNode = this.nodes(ctx, 'metadata')[0];\n    const metadata = metadataNode ? (this.visit(metadataNode) as DraftMetadata) : undefined;\n    const statement: GraphStatement = {\n      kind: 'group',\n      span: [0, 0],\n      group: boundary.id,\n      idSpan: boundary.location.span,\n      titleSpan: boundary.label.span,\n      endSpan: this.tokenSpan(end),\n      classSpans: classes.spans,\n      ...(metadata\n        ? {\n            metadata: metadata.properties.map(({ key, span, keySpan, valueSpan }) => ({\n              key,\n              span,\n              keySpan,\n              valueSpan,\n            })),\n          }\n        : {}),\n      ...(children.length ? { children } : {}),\n    };\n    if (metadata) {\n      // Inline metadata resolves exactly like the standalone `id@{ \u2026 }` statement, so\n      // both forms share one validation path and a later statement can still override.\n      this.builder.addMetadataAssignment(boundary.id, boundary.location, metadata, statement);\n    }\n    return statement;\n  }\n  systemBoundaryName(ctx: Ctx): DraftBoundary {\n    const identifier = this.tokens(ctx, 'IDENTIFIER')[0];\n    if (identifier) {\n      const labelNode = this.nodes(ctx, 'nodeLabel')[0];\n      return {\n        id: identifier.image,\n        label: labelNode ? (this.visit(labelNode) as DraftLabel) : this.tokenLabel(identifier),\n        location: this.tokenLocation(identifier),\n        generated: false,\n        classes: [],\n      };\n    }\n    const token = this.tokens(ctx, 'PLAIN_STRING')[0] ?? this.tokens(ctx, 'MARKDOWN_STRING')[0];\n    const label = this.tokenLabel(token);\n    return {\n      id: this.generateId(label.text),\n      label,\n      location: this.tokenLocation(token),\n      generated: true,\n      classes: [],\n    };\n  }\n  systemBoundaryContent(ctx: Ctx): GraphStatement[] {\n    const children = [\n      ...this.nodes(ctx, 'blankLine'),\n      ...this.nodes(ctx, 'commentLine'),\n      ...this.nodes(ctx, 'boundaryElement'),\n    ].sort((a, b) => (a.location?.startOffset ?? 0) - (b.location?.startOffset ?? 0));\n    return children.map((node) => this.wrap(node, this.visit(node) as GraphStatement));\n  }\n  boundaryElement(ctx: Ctx): GraphStatement {\n    const actorNode = this.nodes(ctx, 'actorDeclarationOnly')[0];\n    if (actorNode) {\n      return this.visit(actorNode) as GraphStatement;\n    }\n    const entityNode = this.nodes(ctx, 'entityName')[0];\n    const entity = this.visit(entityNode) as ParsedEntity;\n    entity.explicitDeclaration = true;\n    entity.shape ??= 'ellipse';\n    this.builder.addElement(this.entityDraft(entity));\n    return { kind: 'node', span: [0, 0], nodes: [this.entityOccurrence(entityNode, entity, true)] };\n  }\n\n  metadataAssignmentStatement(ctx: Ctx): GraphStatement {\n    const target = this.visit(this.nodes(ctx, 'metadataAssignmentTarget')[0]) as {\n      id: string;\n      location: DraftLocation;\n    };\n    const metadata = this.visit(this.nodes(ctx, 'metadata')[0]) as DraftMetadata;\n    const statement: GraphStatement = {\n      kind: 'metadata',\n      span: [0, 0],\n      nodes: [{ id: target.id, span: target.location.span, idSpan: target.location.span }],\n      metadata: metadata.properties.map(({ key, span, keySpan, valueSpan }) => ({\n        key,\n        span,\n        keySpan,\n        valueSpan,\n      })),\n    };\n    this.builder.addMetadataAssignment(target.id, target.location, metadata, statement);\n    return statement;\n  }\n  metadataAssignmentTarget(ctx: Ctx): { id: string; location: DraftLocation } {\n    const token = this.allTokens(ctx)[0];\n    const label = this.tokenLabel(token);\n    return {\n      id: token.tokenType.name === 'IDENTIFIER' ? token.image : this.generateId(label.text),\n      location: this.tokenLocation(token),\n    };\n  }\n  noteStatement(ctx: Ctx): GraphStatement {\n    const target = this.tokens(ctx, 'IDENTIFIER')[0];\n    const label = this.visit(this.nodes(ctx, 'nodeLabel')[0]) as DraftLabel;\n    this.builder.addNote({\n      target: target.image,\n      targetLocation: this.tokenLocation(target),\n      label,\n      location: this.ctxLocation(ctx),\n    });\n    return {\n      kind: 'note',\n      span: [0, 0],\n      ref: `note-${this.anonymousNote++}`,\n      refSpan: label.span,\n      nodes: [{ id: target.image, span: this.tokenSpan(target), idSpan: this.tokenSpan(target) }],\n    };\n  }\n  stereotype(ctx: Ctx): ParsedStereotype {\n    const token = this.tokens(ctx, 'STEREOTYPE_TEXT')[0];\n    return { value: token.image.trim(), span: this.tokenSpan(token) };\n  }\n  classSuffix(ctx: Ctx): ParsedClassSuffix {\n    const tokens = this.tokens(ctx, 'IDENTIFIER');\n    return {\n      classes: tokens.map((token) => token.image),\n      spans: tokens.map((token) => this.tokenSpan(token)),\n    };\n  }\n\n  jsonStatement(ctx: Ctx): GraphStatement {\n    const start = this.tokens(ctx, 'JSON_DECLARATION_START')[0];\n    const literal = this.tokens(ctx, 'JSON_OBJECT_LITERAL')[0];\n    const match = /^json[\\t ]+(\\w+)/.exec(start.image)!;\n    const id = match[1];\n    // The match is anchored at the start of the image, so the id begins where the\n    // matched prefix ends. A text search would instead find ids like `o` or `son`\n    // inside the leading `json` keyword.\n    const relative = match[0].length - id.length;\n    const idLocation: DraftLocation = {\n      span: [start.startOffset + relative, start.startOffset + relative + id.length],\n      line: start.startLine ?? 1,\n      column: (start.startColumn ?? 1) + relative,\n    };\n    const parsed = parseOrderedJsonObject(\n      literal.image,\n      literal.startLine ?? 1,\n      literal.startColumn ?? 1\n    );\n    const classNode = this.nodes(ctx, 'classSuffix')[0];\n    const classes = classNode\n      ? (this.visit(classNode) as ParsedClassSuffix)\n      : { classes: [], spans: [] };\n    const draft: DraftJson = {\n      id,\n      value: parsed.value,\n      propertyOrder: parsed.propertyOrder,\n      location: idLocation,\n      classes: classes.classes,\n    };\n    this.builder.addJson(draft);\n    return {\n      kind: 'json',\n      span: [0, 0],\n      nodes: [\n        {\n          id,\n          span: idLocation.span,\n          idSpan: idLocation.span,\n          defines: true,\n          classSpans: classes.spans,\n        },\n      ],\n      classSpans: classes.spans,\n    };\n  }\n  directionStatement(ctx: Ctx): GraphStatement {\n    const token = this.allTokens(ctx).find((value) =>\n      ['TD', 'TB', 'BT', 'RL', 'LR'].includes(value.tokenType.name)\n    )!;\n    this.builder.setDirection(token.image as Direction);\n    return { kind: 'direction', span: [0, 0] };\n  }\n  classDefStatement(ctx: Ctx): GraphStatement {\n    const ids = this.tokens(ctx, 'IDENTIFIER');\n    const styles = this.visit(this.nodes(ctx, 'styles')[0]) as string[];\n    this.builder.addClassDef(\n      ids.map((token) => token.image),\n      styles\n    );\n    return { kind: 'classDef', span: [0, 0], ref: ids[0].image, refSpan: this.tokenSpan(ids[0]) };\n  }\n  classStatement(ctx: Ctx): GraphStatement {\n    const ids = this.tokens(ctx, 'IDENTIFIER');\n    let split = 1;\n    for (; split < ids.length; split++) {\n      const between = this.source.slice(\n        (ids[split - 1].endOffset ?? ids[split - 1].startOffset) + 1,\n        ids[split].startOffset\n      );\n      if (!between.includes(',')) {\n        break;\n      }\n    }\n    const targets = ids\n      .slice(0, split)\n      .map((token) => ({ id: token.image, location: this.tokenLocation(token) }));\n    const classes = ids.slice(split).map((token) => token.image);\n    this.builder.addClassAssignment(targets, classes);\n    return {\n      kind: 'classAssign',\n      span: [0, 0],\n      ref: classes[0],\n      refSpan: this.tokenSpan(ids[split]),\n      nodes: targets.map(({ id, location }) => ({\n        id,\n        span: location.span,\n        idSpan: location.span,\n      })),\n    };\n  }\n  styleStatement(ctx: Ctx): GraphStatement {\n    const target = this.tokens(ctx, 'IDENTIFIER')[0];\n    const styles = this.visit(this.nodes(ctx, 'styles')[0]) as string[];\n    this.builder.addStyleAssignment(target.image, this.tokenLocation(target), styles);\n    return {\n      kind: 'style',\n      span: [0, 0],\n      nodes: [{ id: target.image, span: this.tokenSpan(target), idSpan: this.tokenSpan(target) }],\n    };\n  }\n  styles(ctx: Ctx): string[] {\n    return this.nodes(ctx, 'styleValue').map((node) => this.visit(node) as string);\n  }\n  styleValue(ctx: Ctx): string {\n    const tokens = this.allTokens(ctx);\n    // WhiteSpace is Lexer.SKIPPED, so joining the token images would collapse the\n    // separators inside multi-word values such as `border:1px solid red`. Commas are\n    // consumed by the `styles` rule, so the source slice never spans two values.\n    const span: Span = [\n      tokens[0].startOffset,\n      (tokens.at(-1)!.endOffset ?? tokens.at(-1)!.startOffset) + 1,\n    ];\n    return this.source.slice(span[0], span[1]).replaceAll('\\\\,', ',');\n  }\n  styleComponent(ctx: Ctx): string {\n    return this.allTokens(ctx)\n      .map((token) => token.image)\n      .join('');\n  }\n\n  forwardSolidOperator(ctx: Ctx): ParsedArrow {\n    const token = this.tokens(ctx, 'FORWARD_SOLID')[0];\n    return {\n      type: 'association',\n      arrowType: ARROW_TYPE.SOLID_ARROW,\n      minlen: this.solidMinlen(token),\n    };\n  }\n  backwardSolidOperator(ctx: Ctx): ParsedArrow {\n    const token = this.tokens(ctx, 'BACKWARD_SOLID')[0];\n    const labelNode = this.nodes(ctx, 'edgeLabel')[0];\n    const lengthToken = labelNode ? this.tokens(ctx, 'MARKERLESS_SOLID').at(-1)! : token;\n    return {\n      type: 'association',\n      arrowType: ARROW_TYPE.BACK_ARROW,\n      minlen: this.solidMinlen(lengthToken),\n      ...(labelNode ? { label: this.visit(labelNode) as DraftLabel } : {}),\n    };\n  }\n  markerlessSolidOperator(ctx: Ctx): ParsedArrow {\n    const labelNode = this.nodes(ctx, 'edgeLabel')[0];\n    const tokens = this.allTokens(ctx);\n    if (!labelNode) {\n      return {\n        type: 'association',\n        arrowType: ARROW_TYPE.LINE_SOLID,\n        minlen: this.solidMinlen(this.tokens(ctx, 'MARKERLESS_SOLID')[0]),\n      };\n    }\n    const last = tokens.at(-1)!;\n    const arrowType =\n      last.tokenType.name === 'FORWARD_SOLID'\n        ? ARROW_TYPE.SOLID_ARROW\n        : last.tokenType.name === 'FORWARD_CIRCLE'\n          ? ARROW_TYPE.CIRCLE_ARROW\n          : last.tokenType.name === 'FORWARD_CROSS'\n            ? ARROW_TYPE.CROSS_ARROW\n            : ARROW_TYPE.LINE_SOLID;\n    return {\n      type: 'association',\n      arrowType,\n      label: this.visit(labelNode) as DraftLabel,\n      minlen:\n        arrowType === ARROW_TYPE.SOLID_ARROW || arrowType === ARROW_TYPE.LINE_SOLID\n          ? this.solidMinlen(last)\n          : 1,\n    };\n  }\n  forwardCircleOperator(_ctx: Ctx): ParsedArrow {\n    return { type: 'association', arrowType: ARROW_TYPE.CIRCLE_ARROW, minlen: 1 };\n  }\n  backwardCircleOperator(ctx: Ctx): ParsedArrow {\n    const labelNode = this.nodes(ctx, 'edgeLabel')[0];\n    return {\n      type: 'association',\n      arrowType: ARROW_TYPE.CIRCLE_ARROW_REVERSED,\n      minlen: 1,\n      ...(labelNode ? { label: this.visit(labelNode) as DraftLabel } : {}),\n    };\n  }\n  forwardCrossOperator(_ctx: Ctx): ParsedArrow {\n    return { type: 'association', arrowType: ARROW_TYPE.CROSS_ARROW, minlen: 1 };\n  }\n  backwardCrossOperator(ctx: Ctx): ParsedArrow {\n    const labelNode = this.nodes(ctx, 'edgeLabel')[0];\n    return {\n      type: 'association',\n      arrowType: ARROW_TYPE.CROSS_ARROW_REVERSED,\n      minlen: 1,\n      ...(labelNode ? { label: this.visit(labelNode) as DraftLabel } : {}),\n    };\n  }\n\n  private actorDraft(item: ParsedActorItem): DraftElement {\n    return {\n      id: item.id,\n      kind: 'actor',\n      label: item.label,\n      location: item.location,\n      generated: item.generated,\n      ...(this.parentBoundary\n        ? { parentId: this.parentBoundary.id, parentLocation: this.parentBoundary.location }\n        : {}),\n      ...(item.metadata ? { metadata: item.metadata } : {}),\n      ...(item.stereotype\n        ? { stereotype: item.stereotype.value, stereotypeSpan: item.stereotype.span }\n        : {}),\n      classes: item.classes,\n    };\n  }\n  private entityDraft(entity: ParsedEntity): DraftElement {\n    return {\n      id: entity.id,\n      kind: 'usecase',\n      label: entity.label,\n      location: entity.location,\n      generated: entity.generated,\n      ...(this.parentBoundary\n        ? { parentId: this.parentBoundary.id, parentLocation: this.parentBoundary.location }\n        : {}),\n      ...(entity.shape ? { shape: entity.shape } : {}),\n      ...(entity.metadata ? { metadata: entity.metadata } : {}),\n      ...(entity.stereotype\n        ? { stereotype: entity.stereotype.value, stereotypeSpan: entity.stereotype.span }\n        : {}),\n      classes: entity.classes,\n    };\n  }\n  private endpoint(\n    entity: ParsedEntity | ParsedActorItem,\n    declaration = (entity as ParsedEntity).explicitDeclaration ?? true\n  ): DraftEndpoint {\n    return {\n      id: entity.id,\n      label: entity.label,\n      location: entity.location,\n      generated: entity.generated,\n      declaration,\n      classesOnReference: entity.classes.length > 0,\n    };\n  }\n  private relationshipDraft(\n    source: ParsedActorItem,\n    tail: ParsedRelationTail,\n    location: DraftLocation\n  ): DraftRelationship {\n    return {\n      source: this.endpoint(source, true),\n      target: this.endpoint(tail.target),\n      location,\n      ...(tail.explicitId\n        ? { explicitId: tail.explicitId, explicitIdLocation: tail.explicitIdLocation }\n        : {}),\n      ...tail.arrow,\n    };\n  }\n  private actorOccurrence(node: CstNode, item: ParsedActorItem, defines: boolean): NodeOccurrence {\n    return {\n      id: item.id,\n      span: this.nodeSpan(node),\n      idSpan: item.location.span,\n      labelSpan: item.label.span,\n      ...(defines ? { defines: true } : {}),\n      ...(item.stereotype ? { stereotypeSpan: item.stereotype.span } : {}),\n      ...(item.metadata\n        ? {\n            metadata: item.metadata.properties.map(({ key, span, keySpan, valueSpan }) => ({\n              key,\n              span,\n              keySpan,\n              valueSpan,\n            })),\n          }\n        : {}),\n      ...(item.classSpans.length ? { classSpans: item.classSpans } : {}),\n    };\n  }\n  private entityOccurrence(node: CstNode, item: ParsedEntity, defines: boolean): NodeOccurrence {\n    return this.actorOccurrence(node, item, defines);\n  }\n  private wrap(node: CstNode, statement: GraphStatement): GraphStatement {\n    if (statement.kind === 'blank' || statement.kind === 'comment') {\n      return statement;\n    }\n    statement.span = this.nodeSpan(node);\n    for (const edge of statement.edges ?? []) {\n      edge.span = statement.span;\n    }\n    return statement;\n  }\n  private tokenLabel(token: IToken): DraftLabel {\n    const type: LabelType = token.tokenType.name === 'MARKDOWN_STRING' ? 'markdown' : 'text';\n    const trim = type === 'markdown' ? 2 : token.tokenType.name === 'PLAIN_STRING' ? 1 : 0;\n    const span = this.tokenSpan(token, trim);\n    return { text: this.source.slice(span[0], span[1]), type, span };\n  }\n  private decodePlain(token: IToken): string {\n    return token.tokenType.name === 'PLAIN_STRING' ? token.image.slice(1, -1) : token.image;\n  }\n  private contentSpan(token: IToken): Span {\n    return this.tokenSpan(\n      token,\n      token.tokenType.name === 'PLAIN_STRING'\n        ? 1\n        : token.tokenType.name === 'MARKDOWN_STRING'\n          ? 2\n          : 0\n    );\n  }\n  private generateId(label: string): string {\n    return label.replace(/\\W/g, '_');\n  }\n  private solidMinlen(token: IToken): number {\n    return Math.max(1, (token.image.match(/-/g)?.length ?? 2) - 1);\n  }\n  private nodeLocation(node: CstNode): DraftLocation {\n    const first = this.allTokens(node.children as Ctx)[0];\n    return {\n      span: this.nodeSpan(node),\n      line: first.startLine ?? 1,\n      column: first.startColumn ?? 1,\n    };\n  }\n  private ctxLocation(ctx: Ctx): DraftLocation {\n    const tokens = this.allTokens(ctx).filter(\n      (token) => token.tokenType.name !== 'NEWLINE' && token.tokenType.name !== 'EOF'\n    );\n    const first = tokens[0];\n    const last = tokens.at(-1)!;\n    return {\n      span: [\n        first.startOffset,\n        Math.min(\n          this.source.length,\n          (last.endOffset ?? last.startOffset + last.image.length - 1) + 1\n        ),\n      ],\n      line: first.startLine ?? 1,\n      column: first.startColumn ?? 1,\n    };\n  }\n  private tokenLocation(token: IToken): DraftLocation {\n    const trim =\n      token.tokenType.name === 'PLAIN_STRING'\n        ? 1\n        : token.tokenType.name === 'MARKDOWN_STRING'\n          ? 2\n          : 0;\n    return {\n      span: this.tokenSpan(token, trim),\n      line: token.startLine ?? 1,\n      column: (token.startColumn ?? 1) + trim,\n    };\n  }\n  private nodeSpan(node: CstNode): Span {\n    const tokens = this.allTokens(node.children as Ctx).filter(\n      (token) => token.tokenType.name !== 'NEWLINE' && token.tokenType.name !== 'EOF'\n    );\n    const first = tokens[0];\n    const last = tokens.at(-1);\n    if (!first || !last) {\n      throw new Error('Usecase CST node has no source token');\n    }\n    return [\n      first.startOffset,\n      Math.min(\n        this.source.length,\n        (last.endOffset ?? last.startOffset + last.image.length - 1) + 1\n      ),\n    ];\n  }\n  private tokenSpan(token: IToken, trim = 0): Span {\n    return [\n      token.startOffset + trim,\n      Math.min(\n        this.source.length,\n        (token.endOffset ?? token.startOffset + token.image.length - 1) + 1 - trim\n      ),\n    ];\n  }\n  private nodes(ctx: Ctx, key: string): CstNode[] {\n    return (ctx[key] ?? []).filter((item): item is CstNode => 'children' in item);\n  }\n  private tokens(ctx: Ctx, key: string): IToken[] {\n    return (ctx[key] ?? []).filter((item): item is IToken => 'tokenTypeIdx' in item);\n  }\n  private firstNode(ctx: Ctx, ...keys: string[]): CstNode {\n    for (const key of keys) {\n      const node = this.nodes(ctx, key)[0];\n      if (node) {\n        return node;\n      }\n    }\n    throw new Error(`Usecase CST is missing one of: ${keys.join(', ')}`);\n  }\n  private allTokens(ctx: Ctx): IToken[] {\n    const result: IToken[] = [];\n    for (const values of Object.values(ctx)) {\n      for (const value of values) {\n        if ('tokenTypeIdx' in value) {\n          result.push(value);\n        } else {\n          result.push(...this.allTokens(value.children as Ctx));\n        }\n      }\n    }\n    return result.sort((a, b) => a.startOffset - b.startOffset);\n  }\n}\nexport const usecaseVisitor = new UsecaseVisitor();\n", "import type { ParserDefinition } from '../../../diagram-api/types.js';\nimport { isKnownLocation, runChevrotainParse } from '../../common/parser/runChevrotainParse.js';\nimport { db } from '../usecaseDb.js';\nimport { usecaseLexer } from './usecase.lexer.js';\nimport { usecaseParser } from './usecase.parser.js';\nimport { usecaseVisitor } from './usecase.visitor.js';\n\nexport const parser: ParserDefinition = {\n  // eslint-disable-next-line @typescript-eslint/require-await -- normalizes synchronous parser errors into rejected promises\n  parse: async (input: string): Promise<void> => {\n    db.clear();\n    usecaseParser.input = [];\n    try {\n      runChevrotainParse(\n        {\n          diagramType: 'usecase',\n          lexer: usecaseLexer,\n          parser: usecaseParser,\n          entry: () => usecaseParser.start(),\n          visit: (cst) => usecaseVisitor.build(cst, input),\n        },\n        input\n      );\n    } catch (error) {\n      db.clear();\n      const parseError = usecaseParser.errors[0];\n      if (parseError) {\n        const { token } = parseError;\n        const start = isKnownLocation(token.startOffset) ? token.startOffset : input.length;\n        const end = isKnownLocation(token.endOffset) ? token.endOffset + 1 : start;\n        const line = isKnownLocation(token.startLine)\n          ? token.startLine\n          : input.slice(0, start).split(/\\r\\n|\\r|\\n/).length;\n        const lineStart = Math.max(\n          input.lastIndexOf('\\n', start - 1),\n          input.lastIndexOf('\\r', start - 1)\n        );\n        const column = isKnownLocation(token.startColumn) ? token.startColumn : start - lineStart;\n        const message = error instanceof Error ? error.message : String(error);\n        throw new Error(`${message} at line ${line}, column ${column} [${start},${end})`);\n      }\n      throw error;\n    }\n  },\n};\n", "import { select } from 'd3';\nimport { getConfig } from '../../diagram-api/diagramAPI.js';\nimport type { DrawDefinition, SVG } from '../../diagram-api/types.js';\nimport { log } from '../../logger.js';\nimport { getDiagramElement } from '../../rendering-util/insertElementsForSize.js';\nimport { getRegisteredLayoutAlgorithm, render } from '../../rendering-util/render.js';\nimport { markdownToLines } from '../../rendering-util/handle-markdown-text.js';\nimport { setupViewPortForSVG } from '../../rendering-util/setupViewPortForSVG.js';\nimport type { UsecaseLayoutData, UsecaseLayoutEdge, UsecaseLayoutNode } from './usecaseTypes.js';\nimport utils from '../../utils.js';\nimport type { UsecaseDB } from './usecaseTypes.js';\n\nexport const USECASE_MARKERS: UsecaseLayoutData['markers'] = [\n  'point',\n  'circle',\n  'cross',\n  'extension',\n];\n\nconst ACTOR_SHAPES: Record<string, true> = {\n  usecaseActor: true,\n  usecaseActorHollow: true,\n  usecaseActorAwesome: true,\n  usecaseActorIcon: true,\n};\n\nexport const usecaseDomId = (diagramId: string, modelId: string): string => {\n  const [safeDiagramId, safeModelId] = [diagramId, modelId].map(\n    (value) => value.replace(/[^\\w-]+/g, '_').replace(/^_+|_+$/g, '') || 'element'\n  );\n  return `usecase-${safeDiagramId}-${safeModelId}`;\n};\n\nconst usecaseNodeDomId = (modelId: string): string =>\n  `usecase-${modelId.replace(/[^\\w-]+/g, '_').replace(/^_+|_+$/g, '') || 'element'}`;\n\nconst getAccessibleLabel = (label: string, labelType?: string): string => {\n  if (labelType !== 'markdown') {\n    return label;\n  }\n  return markdownToLines(label)\n    .map((line) => line.map((word) => word.content).join(' '))\n    .join('\\n');\n};\n\nexport const getUsecaseNodeAccessibleName = (node: UsecaseLayoutNode): string => {\n  const label = getAccessibleLabel(node.label ?? node.id, node.labelType);\n  if (ACTOR_SHAPES[node.shape]) {\n    const variant = node.actorType && node.actorType !== 'normal' ? `${node.actorType} ` : '';\n    const business = node.business ? 'business ' : '';\n    const stereotype = node.stereotype ? `, stereotype ${node.stereotype}` : '';\n    return `${business}${variant}actor ${label}${stereotype}`;\n  }\n  if (node.shape === 'note') {\n    return `Note for ${node.noteTargetLabel ?? node.noteTarget ?? ''}: ${label}`;\n  }\n  if (node.shape === 'usecaseJsonTable') {\n    const rows = (node.jsonRows ?? [])\n      .map((row) => `${row.accessibleKey}: ${row.value}`)\n      .join('; ');\n    return rows ? `${label}: ${rows}` : label;\n  }\n  const stereotype = node.stereotype ? `, stereotype ${node.stereotype}` : '';\n  return `${node.business ? 'business ' : ''}use case ${label}${stereotype}`;\n};\n\nexport const getUsecaseBoundaryAccessibleName = (\n  boundary: Extract<UsecaseLayoutData['nodes'][number], { isGroup: true }>\n): string =>\n  `${boundary.boundaryType} system boundary ${getAccessibleLabel(\n    boundary.label ?? boundary.id,\n    boundary.labelType\n  )}`;\n\nexport const getUsecaseEdgeAccessibleName = (edge: UsecaseLayoutEdge): string => {\n  if (edge.relationshipType === 'note') {\n    return '';\n  }\n  const relation =\n    edge.relationshipType === 'association' && edge.label\n      ? `association ${getAccessibleLabel(edge.label, edge.labelType)}`\n      : edge.relationshipType;\n  return `${relation} from ${edge.sourceLabel} to ${edge.targetLabel}`;\n};\n\nconst escapePlainLabel = (label: string): string =>\n  label.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\nconst escapeMarkdownMarkers = (label: string): string => label.replace(/([*[\\\\\\]_`])/g, '\\\\$1');\n\ninterface UsecaseAccessibleNames {\n  nodes: ReadonlyMap<string, string>;\n  edges: ReadonlyMap<string, string>;\n}\n\ntype UsecaseRenderingNode = UsecaseLayoutData['nodes'][number] & {\n  hasFoldedStereotype?: boolean;\n};\n\nexport const prepareUsecaseLayoutData = (\n  data: UsecaseLayoutData,\n  diagramId: string\n): UsecaseLayoutData => {\n  data.diagramId = diagramId;\n  data.markers = [...USECASE_MARKERS];\n  for (const node of data.nodes) {\n    const renderingNode = node as UsecaseRenderingNode;\n    renderingNode.domId = usecaseNodeDomId(node.id);\n    if (node.label !== undefined && node.labelType === 'text') {\n      node.label = escapePlainLabel(node.label);\n    }\n    if (node.stereotype) {\n      node.stereotype = escapePlainLabel(node.stereotype);\n    }\n    if (!node.isGroup && node.shape === 'usecaseJsonTable') {\n      node.jsonRows = node.jsonRows?.map((row) => ({\n        ...row,\n        key: escapePlainLabel(row.key),\n        value: escapePlainLabel(row.value),\n      }));\n    }\n    if (\n      !node.isGroup &&\n      (node.shape === 'usecaseEllipse' || node.shape === 'rect') &&\n      node.stereotype\n    ) {\n      const label = node.label ?? escapePlainLabel(node.id);\n      node.label = `\u00AB${escapeMarkdownMarkers(node.stereotype)}\u00BB<br/>${\n        node.labelType === 'text' ? escapeMarkdownMarkers(label) : label\n      }`;\n      node.labelType = 'markdown';\n      renderingNode.hasFoldedStereotype = true;\n      delete node.stereotype;\n    }\n  }\n  for (const edge of data.edges) {\n    if (edge.label !== undefined && edge.labelType === 'text') {\n      edge.label = escapePlainLabel(edge.label);\n    }\n  }\n  return data;\n};\n\nconst annotateUsecaseElements = (\n  svg: SVG,\n  data: UsecaseLayoutData,\n  accessibleNames: UsecaseAccessibleNames\n) => {\n  for (const node of data.nodes) {\n    const stableDomId =\n      typeof node.domId === 'string' ? node.domId : usecaseDomId(data.diagramId, node.id);\n    const element = svg.select<SVGGElement>(`#${stableDomId}`);\n    const kind = node.isGroup\n      ? 'boundary'\n      : ACTOR_SHAPES[node.shape]\n        ? 'actor'\n        : node.shape === 'note'\n          ? 'note'\n          : node.shape === 'usecaseJsonTable'\n            ? 'json'\n            : 'usecase';\n    const accessibleName = accessibleNames.nodes.get(node.id) ?? node.id;\n    element\n      .attr('data-usecase-id', node.id)\n      .attr('data-usecase-kind', kind)\n      .attr('role', 'img')\n      .attr('aria-label', accessibleName);\n    if (\n      !node.isGroup &&\n      (node.shape === 'usecaseEllipse' || node.shape === 'rect') &&\n      'hasFoldedStereotype' in node &&\n      node.hasFoldedStereotype === true\n    ) {\n      const root = element.node();\n      const htmlLabel = root?.querySelector('.nodeLabel');\n      const container = htmlLabel?.querySelector('p') ?? htmlLabel;\n      const firstLabelNode = container?.firstChild;\n      if (container && firstLabelNode?.nodeType === 3) {\n        const stereotype = container.ownerDocument.createElement('span');\n        stereotype.className = 'usecase-stereotype';\n        container.insertBefore(stereotype, firstLabelNode);\n        stereotype.appendChild(firstLabelNode);\n      } else {\n        root\n          ?.querySelector('.label tspan tspan, .label tspan')\n          ?.classList.add('usecase-stereotype');\n      }\n    }\n  }\n\n  // Index the edges by id so the paths are matched in a single pass instead of\n  // re-scanning every path for each edge.\n  const edgesById = new Map(data.edges.map((edge) => [edge.id, edge]));\n  svg.selectAll<SVGPathElement, unknown>('path[data-et=\"edge\"]').each(function () {\n    const edge = edgesById.get(this.getAttribute('data-id') ?? '');\n    if (!edge) {\n      return;\n    }\n    const path = select(this);\n    path\n      .attr('id', usecaseDomId(data.diagramId, edge.id))\n      .attr('data-usecase-id', edge.id)\n      .attr('data-usecase-kind', edge.internal ? 'note-connector' : 'relationship');\n    if (edge.internal) {\n      path.attr('aria-hidden', 'true');\n    } else {\n      path.attr('role', 'img').attr('aria-label', accessibleNames.edges.get(edge.id) ?? edge.id);\n    }\n  });\n};\n\n/**\n * Publishes the configured use-case fonts on the diagram root as the CSS custom properties that\n * `styles.ts` reads through `var(--mermaid-usecase-*, <fallback>)`.\n *\n * This has to be applied twice. The labels are measured while `render` runs, and the measured\n * width is frozen onto each label `foreignObject`; the fonts therefore have to be in force by\n * then. `setupViewPortForSVG` then runs `configureSvgSize`, which assigns the whole `style`\n * attribute (`max-width: \u2026`) and so wipes the custom properties again. Without the second call\n * the finished diagram repaints every label in the fallback font \u2014 a different typeface from the\n * one it was measured in \u2014 and the wider glyphs spill past the fixed `foreignObject` width, where\n * they are clipped at the trailing edge.\n */\nconst applyUsecaseFonts = (svg: SVG, data: UsecaseLayoutData): void => {\n  svg\n    .style('--mermaid-usecase-actor-font-size', `${data.actorFontSize}px`)\n    .style('--mermaid-usecase-actor-font-family', data.actorFontFamily)\n    .style('--mermaid-usecase-actor-font-weight', data.actorFontWeight)\n    .style('--mermaid-usecase-font-size', `${data.usecaseFontSize}px`)\n    .style('--mermaid-usecase-font-family', data.usecaseFontFamily)\n    .style('--mermaid-usecase-font-weight', data.usecaseFontWeight);\n};\n\n/**\n * Main draw function using unified rendering system\n */\nconst draw: DrawDefinition = async (_text, id, _version, diag) => {\n  log.info('Drawing usecase diagram (unified)', id);\n  const { layout } = getConfig();\n\n  // The getData method provided in all supported diagrams is used to extract the data from the parsed structure\n  // into the Layout data format\n  const usecaseDb = diag.db as UsecaseDB;\n  const data4Layout = usecaseDb.getData();\n  const accessibleLabels = new Map(\n    data4Layout.nodes.map((node) => [\n      node.id,\n      getAccessibleLabel(node.label ?? node.id, node.labelType),\n    ])\n  );\n  const accessibleNames: UsecaseAccessibleNames = {\n    nodes: new Map(\n      data4Layout.nodes.map((node) => [\n        node.id,\n        node.isGroup\n          ? getUsecaseBoundaryAccessibleName(node)\n          : getUsecaseNodeAccessibleName(\n              node.shape === 'note'\n                ? { ...node, noteTargetLabel: accessibleLabels.get(node.noteTarget ?? '') }\n                : node\n            ),\n      ])\n    ),\n    edges: new Map(\n      data4Layout.edges.map((edge) => [\n        edge.id,\n        getUsecaseEdgeAccessibleName({\n          ...edge,\n          sourceLabel: accessibleLabels.get(edge.source) ?? edge.sourceLabel,\n          targetLabel: accessibleLabels.get(edge.target) ?? edge.targetLabel,\n        }),\n      ])\n    ),\n  };\n  const svg = getDiagramElement(id, data4Layout.config.securityLevel);\n\n  data4Layout.layoutAlgorithm = getRegisteredLayoutAlgorithm(layout);\n  prepareUsecaseLayoutData(data4Layout, id);\n\n  // Set before `render` so the labels are measured in the fonts they will be painted in.\n  applyUsecaseFonts(svg, data4Layout);\n\n  await render(data4Layout, svg);\n  annotateUsecaseElements(svg, data4Layout, accessibleNames);\n\n  const padding = data4Layout.diagramPadding;\n  utils.insertTitle(\n    svg,\n    'usecaseDiagramTitleText',\n    0, // Default title top margin\n    usecaseDb.getDiagramTitle?.() ?? ''\n  );\n  setupViewPortForSVG(svg, padding, 'usecaseDiagram', data4Layout.useMaxWidth);\n  // Restore the fonts that `setupViewPortForSVG` just dropped from the `style` attribute.\n  applyUsecaseFonts(svg, data4Layout);\n};\n\nexport const renderer = { draw };\n", "import * as configApi from '../../config.js';\nimport type { DiagramStylesProvider } from '../../diagram-api/types.js';\nimport { hasPalette, isColorTheme, paletteSlotCount, safeLook } from '../common/colorThemeGate.js';\n\ninterface UsecaseStyleOptions {\n  actorBkg?: string;\n  actorBorder?: string;\n  actorTextColor?: string;\n  clusterBkg: string;\n  clusterBorder: string;\n  edgeLabelBackground: string;\n  fontFamily: string;\n  lineColor: string;\n  mainBkg: string;\n  nodeBorder?: string;\n  noteBkgColor: string;\n  noteBorderColor: string;\n  noteTextColor: string;\n  primaryColor: string;\n  primaryTextColor: string;\n  titleColor?: string;\n  theme?: string;\n  look?: string;\n  borderColorArray?: string[];\n  bkgColorArray?: string[];\n  usecaseActorBkg?: string;\n  usecaseActorBorder?: string;\n  usecaseBkg?: string;\n  usecaseBorder?: string;\n  usecaseBoundaryBkg?: string;\n  usecaseBoundaryBorder?: string;\n  usecaseIncludeLine?: string;\n  usecaseExtendLine?: string;\n}\n\n/**\n * One colour per kind of element, rather than a slot per element.\n *\n * These are the values the `role` scheme paints with, and they are the default because\n * colour that tracks *type* survives editing: inserting a use case in the middle of a\n * diagram leaves every other element's colour alone, so diffs, documentation screenshots\n * and visual baselines stay stable. In a use case diagram the shape already encodes the\n * type -- stick figure, ellipse, frame -- so rotating hue across ellipses would add a\n * second encoding that carries no information, and a fixed set of tokens can be tuned for\n * contrast once per theme instead of being a per-instance lottery.\n *\n * Every fallback ends at the value the stylesheet used before these tokens existed, so a\n * theme that sets none of them renders exactly as it did. A user `themeVariables` override\n * lands on the options object whether or not the active theme declares the token.\n */\nconst roleColors = (options: UsecaseStyleOptions) => ({\n  actorBkg: options.usecaseActorBkg ?? options.actorBkg ?? options.mainBkg,\n  actorBorder: options.usecaseActorBorder ?? options.actorBorder ?? options.primaryColor,\n  bkg: options.usecaseBkg ?? options.mainBkg,\n  border: options.usecaseBorder ?? options.nodeBorder ?? options.primaryColor,\n  boundaryBkg: options.usecaseBoundaryBkg ?? options.clusterBkg,\n  boundaryBorder: options.usecaseBoundaryBorder ?? options.clusterBorder,\n  includeLine: options.usecaseIncludeLine ?? options.lineColor,\n  extendLine: options.usecaseExtendLine ?? options.lineColor,\n});\n\n/**\n * Cycling per-item colour under the `redux-color` / `redux-dark-color` themes. Actors, use\n * cases and system boundaries all take a slot from one cycle assigned in `usecaseDb`;\n * notes and JSON tables are never stamped, so they keep the theme's fixed colours.\n *\n * Every selector here is scoped to a `usecase-` class rather than a bare `.node`. `usecaseDb`\n * hands a slot only to the three roles above, and the shapes stamp only what it assigned, so\n * a note or JSON table carries no `data-color-id` to match -- the scoping keeps these rules\n * narrow rather than being what makes them miss.\n *\n * Nothing is `!important`: the shapes put user `classDef` / `style` declarations in an\n * inline `style` attribute, which has to keep winning over the theme palette.\n */\nconst genColor: DiagramStylesProvider = (options) => {\n  const { theme, bkgColorArray, borderColorArray } = options;\n  // Both halves of the gate: a colour theme *and* a non-empty palette. An empty palette is\n  // reachable through a `themeVariables` override, and would otherwise leave every slot\n  // emitting `stroke: undefined`.\n  if (!isColorTheme(theme, borderColorArray)) {\n    return '';\n  }\n  // System boundaries take a palette slot under both schemes; actors and use cases only\n  // under `rotate`. Read from `getConfig()` rather than `options`, which carries theme\n  // variables and not the per-diagram config; `requirement` reads its palette the same way.\n  const rotate = configApi.getConfig().usecase?.colorScheme === 'rotate';\n  // `look` is validated before it reaches the selector -- see `safeLook`.\n  const look = safeLook(options.look);\n  // Every rule below is scoped to `[data-look=\"${look}\"]`, and one look applies to a whole\n  // diagram, so this flag decides the rules for exactly the nodes they can match.\n  const isHandDrawn = look === 'handDrawn';\n  const hasBkgColors = hasPalette(bkgColorArray);\n  let sections = '';\n\n  // One rule per slot that can actually be stamped. `stampColorSlot` assigns\n  // `colorIndex % borderColorArray.length`, so deriving the bound from the same length is\n  // what keeps the emitted rules and the stamped ids from disagreeing.\n  for (let i = 0; i < paletteSlotCount(borderColorArray); i++) {\n    const borderColor = borderColorArray[i];\n    // The background palette is a separate array that may be shorter, so it still wraps --\n    // guarded by `hasBkgColors`, since `i % 0` is NaN and `[][NaN]` is `undefined`.\n    // `redux-dark-color` is the live no-background case: it colours outlines only.\n    const fill = hasBkgColors ? `fill: ${bkgColorArray[i % bkgColorArray.length]};` : '';\n    const slot = `[data-look=\"${look}\"][data-color-id=\"color-${i}\"]`;\n\n    /* System boundaries, in both schemes. A boundary is a container, and numbering the\n       containers is the one place a counter carries information rather than noise: the slot\n       says which group a thing belongs to, and it stays put as long as the boundary order\n       does. Same reasoning, and the same declaration-index numbering, as flowchart\n       subgraphs.\n\n       Descends into the handDrawn paths as flowchart does, which collapses a handDrawn\n       boundary into a solid hachure block -- a handDrawn flowchart subgraph under these\n       themes already renders that way, and diverging here would be the odder result. */\n    sections += `\n\n    & ${slot}.system-boundary rect.boundary-body,\n    & ${slot}.system-boundary rect.boundary-tab,\n    & ${slot}.system-boundary .boundary-body path,\n    & ${slot}.system-boundary .boundary-tab path {\n      stroke: ${borderColor};\n      ${fill}\n    }\n    `;\n\n    if (!rotate) {\n      continue;\n    }\n\n    sections += `\n\n    /* Use case bodies -- \\`.usecase-element\\` covers the ellipse form, the \\`[Rect]\\` form and\n       the business variant.\n\n       Element selectors only, never a bare \\`path\\`. Under the handDrawn look roughjs draws\n       the body as a *pair* of paths, an outline stroked in the border colour and a hachure\n       fill stroked in the background colour, with no class to tell them apart. Stroking\n       both repaints the fill lines as border colour and the shape collapses into a solid\n       block -- which is what \\`.usecase-element path\\` did. So handDrawn bodies keep the\n       theme's uniform colours, exactly as handDrawn flowchart nodes do. */\n    & ${slot}.usecase-element ellipse,\n    & ${slot}.usecase-element rect {\n      stroke: ${borderColor};\n      ${fill}\n    }\n\n    /* The business marker is a single classed path, so it can be reached safely by name --\n       without it the marker keeps the uniform border beside a palette-coloured body. No\n       \\`fill\\`: the marker is drawn with \\`fill=\"none\"\\` and has to stay that way. */\n    & ${slot}.usecase-element .usecase-business-marker {\n      stroke: ${borderColor};\n    }\n\n    /* Actor glyphs, mirroring the uniform rule further down. The fill goes on the glyph\n       group, never on its children, so the hollow variant's own \\`fill=\"none\"\\` keeps\n       winning and a hollow actor stays hollow. Same reason as above for not descending\n       into the handDrawn paths. */\n    & ${slot}.usecase-actor .usecase-actor-shape,\n    & ${slot}.usecase-actor .usecase-actor-hollow,\n    & ${slot}.usecase-actor .usecase-actor-awesome,\n    & ${slot}.usecase-actor .usecase-actor-icon {\n      stroke: ${borderColor};\n      ${fill}\n    }\n${\n  isHandDrawn\n    ? ''\n    : `\n    /* The group rule above reaches the glyph by inheritance, which the neo look breaks: it\n       ships a \\`[data-look=\"neo\"].node path { stroke }\\` rule that hits the glyph's own paths,\n       and a value set directly on the child always beats one inherited from the parent,\n       whatever the parent rule's specificity. So name the children too.\n\n       Emitted for every look *except* handDrawn, where roughjs draws the glyph as an\n       outline path plus a hachure fill path stroked in the fill colour, indistinguishable\n       in CSS -- stroking both turns a hollow actor into a solid disc. Deliberately no\n       \\`fill\\` either way, so the hollow variant's own \\`fill=\"none\"\\` keeps winning. */\n    & ${slot}.usecase-actor .usecase-actor-glyph path,\n    & ${slot}.usecase-actor .usecase-actor-glyph circle {\n      stroke: ${borderColor};\n    }\n`\n}\n    `;\n  }\n  return sections;\n};\n\nconst getStyles: DiagramStylesProvider = (options: UsecaseStyleOptions) => {\n  const role = roleColors(options);\n  // Under handDrawn the glyph is a roughjs outline path plus a hachure fill path stroked in\n  // the fill colour, with nothing in CSS to tell them apart -- so the descendant rule below\n  // is emitted for every other look only. See `genColor` for the same split.\n  const isHandDrawn = safeLook(options.look) === 'handDrawn';\n  return `\n  ${genColor(options)}\n  & .usecase-actor {\n    color: ${options.actorTextColor ?? options.primaryTextColor};\n  }\n\n  & .usecase-actor-shape,\n  & .usecase-actor-hollow,\n  & .usecase-actor-awesome,\n  & .usecase-actor-icon {\n    fill: ${role.actorBkg};\n    stroke: ${role.actorBorder};\n    stroke-width: 2px;\n  }\n${\n  isHandDrawn\n    ? ''\n    : `\n  /* The rule above colours the glyph group and lets its children inherit, which the neo\n     look breaks: it ships a \\`[data-look=\"neo\"].node path { stroke }\\` rule that lands on\n     the glyph's own paths, and a value set directly on a child always beats one inherited\n     from its parent, whatever the parent rule's specificity. Since neo is the default look,\n     without this every actor renders in the node border colour rather than the actor\n     colour the rule above asks for.\n\n     \\`.node\\` is in the selector to outrank that neo rule rather than tie with it: both\n     would otherwise be one attribute plus one class plus one element, leaving the winner to\n     depend on which stylesheet is concatenated last.\n\n     Stroke only: the hollow variant's own \\`fill=\"none\"\\` has to keep winning. */\n  & .node.usecase-actor .usecase-actor-glyph path,\n  & .node.usecase-actor .usecase-actor-glyph circle {\n    stroke: ${role.actorBorder};\n  }\n`\n}\n  & .usecase-actor .nodeLabel,\n  & .actor-label {\n    color: ${options.actorTextColor ?? options.primaryTextColor};\n    fill: ${options.actorTextColor ?? options.primaryTextColor};\n    font-family: var(--mermaid-usecase-actor-font-family, ${options.fontFamily});\n    font-size: var(--mermaid-usecase-actor-font-size, 14px);\n    font-weight: var(--mermaid-usecase-actor-font-weight, normal);\n  }\n\n  & .usecase-element ellipse,\n  & .usecase-element rect,\n  & .usecase-business ellipse,\n  & .usecase-business rect {\n    fill: ${role.bkg};\n    stroke: ${role.border};\n    stroke-width: 2px;\n  }\n${\n  isHandDrawn\n    ? ''\n    : `\n  /* The same interception the actor glyph hits, one element down: neo ships\n     \\`[data-look=\"neo\"].node rect { stroke: nodeBorder }\\`, which outranks the plain\n     \\`.usecase-element rect\\` above, so a use case written in the \\`[Rect]\\` form kept the node\n     border colour while its ellipse siblings took the role colour. An \\`<ellipse>\\` has no\n     equivalent neo rule and is already correct; restating it here costs nothing and means\n     the two forms cannot drift apart again.\n\n     Qualified with \\`[data-look]\\` *and* \\`.node\\` to land strictly above that rule rather than\n     tie with it -- on a tie the later stylesheet would win, which is how neo took this in\n     the first place. Skipped under handDrawn, where roughjs draws paths and neither element\n     exists. */\n  & [data-look=\"${safeLook(options.look)}\"].node.usecase-element ellipse,\n  & [data-look=\"${safeLook(options.look)}\"].node.usecase-element rect {\n    fill: ${role.bkg};\n    stroke: ${role.border};\n  }\n\n  /* The business marker is a \\`<path>\\`, so it loses to \\`[data-look=\"neo\"].node path\\` the same\n     way. No \\`fill\\`: the marker is drawn with \\`fill=\"none\"\\` and has to stay that way. */\n  & [data-look=\"${safeLook(options.look)}\"].node.usecase-element .usecase-business-marker {\n    stroke: ${role.border};\n  }\n`\n}\n  & .usecase-element .nodeLabel,\n  & .usecase-label {\n    color: ${options.primaryTextColor};\n    fill: ${options.primaryTextColor};\n    font-family: var(--mermaid-usecase-font-family, ${options.fontFamily});\n    font-size: var(--mermaid-usecase-font-size, 12px);\n    font-weight: var(--mermaid-usecase-font-weight, normal);\n  }\n\n  & .usecase-stereotype,\n  & .usecase-business-marker {\n    color: ${options.primaryTextColor};\n    fill: ${options.primaryTextColor};\n    stroke: ${role.border};\n  }\n\n  & .system-boundary rect.boundary-body,\n  & .system-boundary rect.boundary-tab,\n  & .system-boundary-package-tab {\n    fill: ${role.boundaryBkg};\n    stroke: ${role.boundaryBorder};\n    stroke-width: 1px;\n  }\n\n  & .system-boundary-title text {\n    fill: ${options.titleColor ?? options.primaryTextColor};\n  }\n\n  /* Only the span, never the <p> inside it: the renderer puts a user-supplied\n     'color' on the span, and that has to stay inheritable by its children. */\n  & .system-boundary-title span {\n    color: ${options.titleColor ?? options.primaryTextColor};\n  }\n\n  & .usecase-note {\n    fill: ${options.noteBkgColor};\n    stroke: ${options.noteBorderColor};\n    color: ${options.noteTextColor};\n  }\n\n  & .usecase-note .nodeLabel {\n    color: ${options.noteTextColor};\n    fill: ${options.noteTextColor};\n  }\n\n  & .usecase-json-table,\n  & .usecase-json-table rect,\n  & .usecase-json-cell {\n    fill: ${options.mainBkg};\n    stroke: ${options.nodeBorder ?? options.primaryColor};\n  }\n\n  & .usecase-json-title,\n  & .usecase-json-key,\n  & .usecase-json-value {\n    color: ${options.primaryTextColor};\n    fill: ${options.primaryTextColor};\n  }\n\n  & .relationship {\n    fill: none;\n    stroke: ${options.lineColor};\n  }\n\n  & .relationship-include,\n  & .relationship-extend,\n  & .relationship-note {\n    stroke-dasharray: 3;\n  }\n\n  /* Include and extend are both dashed, which is a weak distinction at small sizes. The\n     tokens default to \\`lineColor\\`, so a theme that does not set them is unchanged. */\n  & .relationship-include {\n    stroke: ${role.includeLine};\n  }\n\n  & .relationship-extend {\n    stroke: ${role.extendLine};\n  }\n\n  & .relationship.edge-animation-fast,\n  & .relationship.edge-animation-slow {\n    stroke-linecap: round;\n  }\n\n  & .edgeLabel,\n  & .edgeLabel p {\n    background-color: ${options.edgeLabelBackground};\n  }\n\n  & .labelBkg {\n    background-color: ${options.edgeLabelBackground};\n    padding: 0 2px;\n  }\n\n  & .edgeLabel .label rect {\n    fill: ${options.edgeLabelBackground};\n  }\n\n  & .relationship-label,\n  & .edgeLabel {\n    color: ${options.primaryTextColor};\n    fill: ${options.primaryTextColor};\n    font-family: ${options.fontFamily};\n    font-size: 10px;\n    font-weight: normal;\n  }\n\n  & .marker,\n  & .marker.point,\n  & .marker.circle,\n  & .marker.cross {\n    fill: ${options.lineColor};\n    stroke: ${options.lineColor};\n  }\n\n  & .marker.extension {\n    fill: ${options.mainBkg};\n    stroke: ${options.lineColor};\n  }\n`;\n};\n\nexport default getStyles;\n", "import type { DiagramDefinition } from '../../diagram-api/types.js';\nimport { parser } from './parser/usecase.chevrotain.js';\nimport { db } from './usecaseDb.js';\nimport { renderer } from './usecaseRenderer.js';\nimport styles from './styles.js';\n\nexport const diagram: DiagramDefinition = {\n  parser,\n  db,\n  renderer,\n  styles,\n};\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,kBAAkB,wBAAC,UAC9B,UAAU,UAAa,SAAS,GADH;AAIxB,SAAS,mBAAmB,QAA+B,OAAqB;AACrF,QAAM,YAAY,OAAO,MAAM,SAAS,KAAK;AAC7C,MAAI,UAAU,OAAO,SAAS,GAAG;AAI/B,UAAM,WAAW,UAAU,OAAO,CAAC;AACnC,UAAM,QAAQ,gBAAgB,SAAS,MAAM,IAAI,SAAS,SAAS,MAAM;AACzE,UAAM,MAAM,SAAS,gBAAgB,SAAS,MAAM,IAAI,SAAS,SAAS;AAC1E,UAAM,IAAI;AAAA,MACR,gBAAgB,OAAO,WAAW,aAAa,SAAS,OAAO,YAC7D,SAAS,QAAQ,CACnB,YAAY,SAAS,UAAU,C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AAAA,YACzB,QAAQ,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,cAKtB,QAAQ,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAYjB,KAAK,WAAW;AAAA;AAAA;AAAA;AAAA,cAIhB,KAAK,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAUL,QAAQ,mBAAmB;AAAA;AAAA;AAAA;AAAA,wBAI3B,QAAQ,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA,YAKvC,QAAQ,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA,aAK1B,QAAQ,gBAAgB;AAAA,YACzB,QAAQ,gBAAgB;AAAA,mBACjB,QAAQ,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YASzB,QAAQ,SAAS;AAAA,cACf,QAAQ,SAAS;AAAA;AAAA;AAAA;AAAA,YAInB,QAAQ,OAAO;AAAA,cACb,QAAQ,SAAS;AAAA;AAAA;AAG/B,GAhNyC;AAkNzC,IAAO,iBAAQ;;;ACxYR,IAAM,UAA6B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
  "names": ["getConfig", "clear", "classNames", "LexerDefinitionErrorType", "msg", "currConfig", "tokenLabel", "hasTokenLabel", "hasTokenLabel", "hasTokenLabel", "tokenLabel", "getExtraProductionArgument", "PROD_TYPE", "tokenMatcher", "prefixKeys", "collectorVisitor", "resolveGrammar", "validateGrammar", "CstVisitorDefinitionError", "allTokenTypes", "ParserDefinitionErrorType", "resolveGrammar", "validateGrammar", "db", "first", "state", "label", "actorNode", "first", "stereotype", "getConfig"]
}