n: () => isPropertyDeclaration,
  isPropertyName: () => isPropertyName,
  isPropertyNameLiteral: () => isPropertyNameLiteral,
  isPropertySignature: () => isPropertySignature,
  isPrototypeAccess: () => isPrototypeAccess,
  isPrototypePropertyAssignment: () => isPrototypePropertyAssignment,
  isPunctuation: () => isPunctuation,
  isPushOrUnshiftIdentifier: () => isPushOrUnshiftIdentifier,
  isQualifiedName: () => isQualifiedName,
  isQuestionDotToken: () => isQuestionDotToken,
  isQuestionOrExclamationToken: () => isQuestionOrExclamationToken,
  isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken,
  isQuestionToken: () => isQuestionToken,
  isReadonlyKeyword: () => isReadonlyKeyword,
  isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken,
  isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment,
  isReferenceFileLocation: () => isReferenceFileLocation,
  isReferencedFile: () => isReferencedFile,
  isRegularExpressionLiteral: () => isRegularExpressionLiteral,
  isRequireCall: () => isRequireCall,
  isRequireVariableStatement: () => isRequireVariableStatement,
  isRestParameter: () => isRestParameter,
  isRestTypeNode: () => isRestTypeNode,
  isReturnStatement: () => isReturnStatement,
  isReturnStatementWithFixablePromiseHandler: () => isReturnStatementWithFixablePromiseHandler,
  isRightSideOfAccessExpression: () => isRightSideOfAccessExpression,
  isRightSideOfInstanceofExpression: () => isRightSideOfInstanceofExpression,
  isRightSideOfPropertyAccess: () => isRightSideOfPropertyAccess,
  isRightSideOfQualifiedName: () => isRightSideOfQualifiedName,
  isRightSideOfQualifiedNameOrPropertyAccess: () => isRightSideOfQualifiedNameOrPropertyAccess,
  isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName: () => isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName,
  isRootedDiskPath: () => isRootedDiskPath,
  isSameEntityName: () => isSameEntityName,
  isSatisfiesExpression: () => isSatisfiesExpression,
  isSemicolonClassElement: () => isSemicolonClassElement,
  isSetAccessor: () => isSetAccessor,
  isSetAccessorDeclaration: () => isSetAccessorDeclaration,
  isShiftOperatorOrHigher: () => isShiftOperatorOrHigher,
  isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol,
  isShorthandPropertyAssignment: () => isShorthandPropertyAssignment,
  isSideEffectImport: () => isSideEffectImport,
  isSignedNumericLiteral: () => isSignedNumericLiteral,
  isSimpleCopiableExpression: () => isSimpleCopiableExpression,
  isSimpleInlineableExpression: () => isSimpleInlineableExpression,
  isSimpleParameterList: () => isSimpleParameterList,
  isSingleOrDoubleQuote: () => isSingleOrDoubleQuote,
  isSolutionConfig: () => isSolutionConfig,
  isSourceElement: () => isSourceElement,
  isSourceFile: () => isSourceFile,
  isSourceFileFromLibrary: () => isSourceFileFromLibrary,
  isSourceFileJS: () => isSourceFileJS,
  isSourceFileNotJson: () => isSourceFileNotJson,
  isSourceMapping: () => isSourceMapping,
  isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration,
  isSpreadAssignment: () => isSpreadAssignment,
  isSpreadElement: () => isSpreadElement,
  isStatement: () => isStatement,
  isStatementButNotDeclaration: () => isStatementButNotDeclaration,
  isStatementOrBlock: () => isStatementOrBlock,
  isStatementWithLocals: () => isStatementWithLocals,
  isStatic: () => isStatic,
  isStaticModifier: () => isStaticModifier,
  isString: () => isString,
  isStringANonContextualKeyword: () => isStringANonContextualKeyword,
  isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection,
  isStringDoubleQuoted: () => isStringDoubleQuoted,
  isStringLiteral: () => isStringLiteral,
  isStringLiteralLike: () => isStringLiteralLike,
  isStringLiteralOrJsxExpression: () => isStringLiteralOrJsxExpression,
  isStringLiteralOrTemplate: () => isStringLiteralOrTemplate,
  isStringOrNumericLiteralLike: () => isStringOrNumericLiteralLike,
  isStringOrRegularExpressionOrTemplateLiteral: () => isStringOrRegularExpressionOrTemplateLiteral,
  isStringTextContainingNode: () => isStringTextContainingNode,
  isSuperCall: () => isSuperCall,
  isSuperKeyword: () => isSuperKeyword,
  isSuperProperty: () => isSuperProperty,
  isSupportedSourceFileName: () => isSupportedSourceFileName,
  isSwitchStatement: () => isSwitchStatement,
  isSyntaxList: () => isSyntaxList,
  isSyntheticExpression: () => isSyntheticExpression,
  isSyntheticReference: () => isSyntheticReference,
  isTagName: () => isTagName,
  isTaggedTemplateExpression: () => isTaggedTemplateExpression,
  isTaggedTemplateTag: () => isTaggedTemplateTag,
  isTemplateExpression: () => isTemplateExpression,
  isTemplateHead: () => isTemplateHead,
  isTemplateLiteral: () => isTemplateLiteral,
  isTemplateLiteralKind: () => isTemplateLiteralKind,
  isTemplateLiteralToken: () => isTemplateLiteralToken,
  isTemplateLiteralTypeNode: () => isTemplateLiteralTypeNode,
  isTemplateLiteralTypeSpan: () => isTemplateLiteralTypeSpan,
  isTemplateMiddle: () => isTemplateMiddle,
  isTemplateMiddleOrTemplateTail: () => isTemplateMiddleOrTemplateTail,
  isTemplateSpan: () => isTemplateSpan,
  isTemplateTail: () => isTemplateTail,
  isTextWhiteSpaceLike: () => isTextWhiteSpaceLike,
  isThis: () => isThis,
  isThisContainerOrFunctionBlock: () => isThisContainerOrFunctionBlock,
  isThisIdentifier: () => isThisIdentifier,
  isThisInTypeQuery: () => isThisInTypeQuery,
  isThisInitializedDeclaration: () => isThisInitializedDeclaration,
  isThisInitializedObjectBindingExpression: () => isThisInitializedObjectBindingExpression,
  isThisProperty: () => isThisProperty,
  isThisTypeNode: () => isThisTypeNode,
  isThisTypeParameter: () => isThisTypeParameter,
  isThisTypePredicate: () => isThisTypePredicate,
  isThrowStatement: () => isThrowStatement,
  isToken: () => isToken,
  isTokenKind: () => isTokenKind,
  isTraceEnabled: () => isTraceEnabled,
  isTransientSymbol: () => isTransientSymbol,
  isTrivia: () => isTrivia,
  isTryStatement: () => isTryStatement,
  isTupleTypeNode: () => isTupleTypeNode,
  isTypeAlias: () => isTypeAlias,
  isTypeAliasDeclaration: () => isTypeAliasDeclaration,
  isTypeAssertionExpression: () => isTypeAssertionExpression,
  isTypeDeclaration: () => isTypeDeclaration,
  isTypeElement: () => isTypeElement,
  isTypeKeyword: () => isTypeKeyword,
  isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier,
  isTypeLiteralNode: () => isTypeLiteralNode,
  isTypeNode: () => isTypeNode,
  isTypeNodeKind: () => isTypeNodeKind,
  isTypeOfExpression: () => isTypeOfExpression,
  isTypeOnlyExportDeclaration: () => isTypeOnlyExportDeclaration,
  isTypeOnlyImportDeclaration: () => isTypeOnlyImportDeclaration,
  isTypeOnlyImportOrExportDeclaration: () => isTypeOnlyImportOrExportDeclaration,
  isTypeOperatorNode: () => isTypeOperatorNode,
  isTypeParameterDeclaration: () => isTypeParameterDeclaration,
  isTypePredicateNode: () => isTypePredicateNode,
  isTypeQueryNode: () => isTypeQueryNode,
  isTypeReferenceNode: () => isTypeReferenceNode,
  isTypeReferenceType: () => isTypeReferenceType,
  isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName,
  isUMDExportSymbol: () => isUMDExportSymbol,
  isUnaryExpression: () => isUnaryExpression,
  isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite,
  isUnicodeIdentifierStart: () => isUnicodeIdentifierStart,
  isUnionTypeNode: () => isUnionTypeNode,
  isUrl: () => isUrl,
  isValidBigIntString: () => isValidBigIntString,
  isValidESSymbolDeclaration: () => isValidESSymbolDeclaration,
  isValidTypeOnlyAliasUseSite: () => isValidTypeOnlyAliasUseSite,
  isValueSignatureDeclaration: () => isValueSignatureDeclaration,
  isVarAwaitUsing: () => isVarAwaitUsing,
  isVarConst: () => isVarConst,
  isVarConstLike: () => isVarConstLike,
  isVarUsing: () => isVarUsing,
  isVariableDeclaration: () => isVariableDeclaration,
  isVariableDeclarationInVariableStatement: () => isVariableDeclarationInVariableStatement,
  isVariableDeclarationInitializedToBareOrAccessedRequire: () => isVariableDeclarationInitializedToBareOrAccessedRequire,
  isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire,
  isVariableDeclarationList: () => isVariableDeclarationList,
  isVariableLike: () => isVariableLike,
  isVariableStatement: () => isVariableStatement,
  isVoidExpression: () => isVoidExpression,
  isWatchSet: () => isWatchSet,
  isWhileStatement: () => isWhileStatement,
  isWhiteSpaceLike: () => isWhiteSpaceLike,
  isWhiteSpaceSingleLine: () => isWhiteSpaceSingleLine,
  isWithStatement: () => isWithStatement,
  isWriteAccess: () => isWriteAccess,
  isWriteOnlyAccess: () => isWriteOnlyAccess,
  isYieldExpression: () => isYieldExpression,
  jsxModeNeedsExplicitImport: () => jsxModeNeedsExplicitImport,
  keywordPart: () => keywordPart,
  last: () => last,
  lastOrUndefined: () => lastOrUndefined,
  length: () => length,
  libMap: () => libMap,
  libs: () => libs,
  lineBreakPart: () => lineBreakPart,
  loadModuleFromGlobalCache: () => loadModuleFromGlobalCache,
  loadWithModeAwareCache: () => loadWithModeAwareCache,
  makeIdentifierFromModuleName: () => makeIdentifierFromModuleName,
  makeImport: () => makeImport,
  makeStringLiteral: () => makeStringLiteral,
  mangleScopedPackageName: () => mangleScopedPackageName,
  map: () => map,
  mapAllOrFail: () => mapAllOrFail,
  mapDefined: () => mapDefined,
  mapDefinedIterator: () => mapDefinedIterator,
  mapEntries: () => mapEntries,
  mapIterator: () => mapIterator,
  mapOneOrMany: () => mapOneOrMany,
  mapToDisplayParts: () => mapToDisplayParts,
  matchFiles: () => matchFiles,
  matchPatternOrExact: () => matchPatternOrExact,
  matchedText: () => matchedText,
  matchesExclude: () => matchesExclude,
  matchesExcludeWorker: () => matchesExcludeWorker,
  maxBy: () => maxBy,
  maybeBind: () => maybeBind,
  maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages,
  memoize: () => memoize,
  memoizeOne: () => memoizeOne,
  min: () => min,
  minAndMax: () => minAndMax,
  missingFileModifiedTime: () => missingFileModifiedTime,
  modifierToFlag: () => modifierToFlag,
  modifiersToFlags: () => modifiersToFlags,
  moduleExportNameIsDefault: () => moduleExportNameIsDefault,
  moduleExportNameTextEscaped: () => moduleExportNameTextEscaped,
  moduleExportNameTextUnescaped: () => moduleExportNameTextUnescaped,
  moduleOptionDeclaration: () => moduleOptionDeclaration,
  moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo,
  moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter,
  moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations,
  moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports,
  moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules,
  moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier,
  moduleSpecifiers: () => ts_moduleSpecifiers_exports,
  moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier,
  moveEmitHelpers: () => moveEmitHelpers,
  moveRangeEnd: () => moveRangeEnd,
  moveRangePastDecorators: () => moveRangePastDecorators,
  moveRangePastModifiers: () => moveRangePastModifiers,
  moveRangePos: () => moveRangePos,
  moveSyntheticComments: () => moveSyntheticComments,
  mutateMap: () => mutateMap,
  mutateMapSkippingNewValues: () => mutateMapSkippingNewValues,
  needsParentheses: () => needsParentheses,
  needsScopeMarker: () => needsScopeMarker,
  newCaseClauseTracker: () => newCaseClauseTracker,
  newPrivateEnvironment: () => newPrivateEnvironment,
  noEmitNotification: () => noEmitNotification,
  noEmitSubstitution: () => noEmitSubstitution,
  noTransformers: () => noTransformers,
  noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength,
  nodeCanBeDecorated: () => nodeCanBeDecorated,
  nodeCoreModules: () => nodeCoreModules,
  nodeHasName: () => nodeHasName,
  nodeIsDecorated: () => nodeIsDecorated,
  nodeIsMissing: () => nodeIsMissing,
  nodeIsPresent: () => nodeIsPresent,
  nodeIsSynthesized: () => nodeIsSynthesized,
  nodeModuleNameResolver: () => nodeModuleNameResolver,
  nodeModulesPathPart: () => nodeModulesPathPart,
  nodeNextJsonConfigResolver: () => nodeNextJsonConfigResolver,
  nodeOrChildIsDecorated: () => nodeOrChildIsDecorated,
  nodeOverlapsWithStartEnd: () => nodeOverlapsWithStartEnd,
  nodePosToString: () => nodePosToString,
  nodeSeenTracker: () => nodeSeenTracker,
  nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment,
  noop: () => noop,
  noopFileWatcher: () => noopFileWatcher,
  normalizePath: () => normalizePath,
  normalizeSlashes: () => normalizeSlashes,
  normalizeSpans: () => normalizeSpans,
  not: () => not,
  notImplemented: () => notImplemented,
  notImplementedResolver: () => notImplementedResolver,
  nullNodeConverters: () => nullNodeConverters,
  nullParenthesizerRules: () => nullParenthesizerRules,
  nullTransformationContext: () => nullTransformationContext,
  objectAllocator: () => objectAllocator,
  operatorPart: () => operatorPart,
  optionDeclarations: () => optionDeclarations,
  optionMapToObject: () => optionMapToObject,
  optionsAffectingProgramStructure: () => optionsAffectingProgramStructure,
  optionsForBuild: () => optionsForBuild,
  optionsForWatch: () => optionsForWatch,
  optionsHaveChanges: () => optionsHaveChanges,
  or: () => or,
  orderedRemoveItem: () => orderedRemoveItem,
  orderedRemoveItemAt: () => orderedRemoveItemAt,
  packageIdToPackageName: () => packageIdToPackageName,
  packageIdToString: () => packageIdToString,
  parameterIsThisKeyword: () => parameterIsThisKeyword,
  parameterNamePart: () => parameterNamePart,
  parseBaseNodeFactory: () => parseBaseNodeFactory,
  parseBigInt: () => parseBigInt,
  parseBuildCommand: () => parseBuildCommand,
  parseCommandLine: () => parseCommandLine,
  parseCommandLineWorker: () => parseCommandLineWorker,
  parseConfigFileTextToJson: () => parseConfigFileTextToJson,
  parseConfigFileWithSystem: () => parseConfigFileWithSystem,
  parseConfigHostFromCompilerHostLike: () => parseConfigHostFromCompilerHostLike,
  parseCustomTypeOption: () => parseCustomTypeOption,
  parseIsolatedEntityName: () => parseIsolatedEntityName,
  parseIsolatedJSDocComment: () => parseIsolatedJSDocComment,
  parseJSDocTypeExpressionForTests: () => parseJSDocTypeExpressionForTests,
  parseJsonConfigFileContent: () => parseJsonConfigFileContent,
  parseJsonSourceFileConfigFileContent: () => parseJsonSourceFileConfigFileContent,
  parseJsonText: () => parseJsonText,
  parseListTypeOption: () => parseListTypeOption,
  parseNodeFactory: () => parseNodeFactory,
  parseNodeModuleFromPath: () => parseNodeModuleFromPath,
  parsePackageName: () => parsePackageName,
  parsePseudoBigInt: () => parsePseudoBigInt,
  parseValidBigInt: () => parseValidBigInt,
  pasteEdits: () => ts_PasteEdits_exports,
  patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory,
  pathContainsNodeModules: () => pathContainsNodeModules,
  pathIsAbsolute: () => pathIsAbsolute,
  pathIsBareSpecifier: () => pathIsBareSpecifier,
  pathIsRelative: () => pathIsRelative,
  patternText: () => patternText,
  performIncrementalCompilation: () => performIncrementalCompilation,
  performance: () => ts_performance_exports,
  positionBelongsToNode: () => positionBelongsToNode,
  positionIsASICandidate: () => positionIsASICandidate,
  positionIsSynthesized: () => positionIsSynthesized,
  positionsAreOnSameLine: () => positionsAreOnSameLine,
  preProcessFile: () => preProcessFile,
  probablyUsesSemicolons: () => probablyUsesSemicolons,
  processCommentPragmas: () => processCommentPragmas,
  processPragmasIntoFields: () => processPragmasIntoFields,
  processTaggedTemplateExpression: () => processTaggedTemplateExpression,
  programContainsEsModules: () => programContainsEsModules,
  programContainsModules: () => programContainsModules,
  projectReferenceIsEqualTo: () => projectReferenceIsEqualTo,
  propertyNamePart: () => propertyNamePart,
  pseudoBigIntToString: () => pseudoBigIntToString,
  punctuationPart: () => punctuationPart,
  pushIfUnique: () => pushIfUnique,
  quote: () => quote,
  quotePreferenceFromString: () => quotePreferenceFromString,
  rangeContainsPosition: () => rangeContainsPosition,
  rangeContainsPositionExclusive: () => rangeContainsPositionExclusive,
  rangeContainsRange: () => rangeContainsRange,
  rangeContainsRangeExclusive: () => rangeContainsRangeExclusive,
  rangeContainsStartEnd: () => rangeContainsStartEnd,
  rangeEndIsOnSameLineAsRangeStart: () => rangeEndIsOnSameLineAsRangeStart,
  rangeEndPositionsAreOnSameLine: () => rangeEndPositionsAreOnSameLine,
  rangeEquals: () => rangeEquals,
  rangeIsOnSingleLine: () => rangeIsOnSingleLine,
  rangeOfNode: () => rangeOfNode,
  rangeOfTypeParameters: () => rangeOfTypeParameters,
  rangeOverlapsWithStartEnd: () => rangeOverlapsWithStartEnd,
  rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd,
  rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine,
  readBuilderProgram: () => readBuilderProgram,
  readConfigFile: () => readConfigFile,
  readJson: () => readJson,
  readJsonConfigFile: () => readJsonConfigFile,
  readJsonOrUndefined: () => readJsonOrUndefined,
  reduceEachLeadingCommentRange: () => reduceEachLeadingCommentRange,
  reduceEachTrailingCommentRange: () => reduceEachTrailingCommentRange,
  reduceLeft: () => reduceLeft,
  reduceLeftIterator: () => reduceLeftIterator,
  reducePathComponents: () => reducePathComponents,
  refactor: () => ts_refactor_exports,
  regExpEscape: () => regExpEscape,
  regularExpressionFlagToCharacterCode: () => regularExpressionFlagToCharacterCode,
  relativeComplement: () => relativeComplement,
  removeAllComments: () => removeAllComments,
  removeEmitHelper: () => removeEmitHelper,
  removeExtension: () => removeExtension,
  removeFileExtension: () => removeFileExtension,
  removeIgnoredPath: () => removeIgnoredPath,
  removeMinAndVersionNumbers: () => removeMinAndVersionNumbers,
  removePrefix: () => removePrefix,
  removeSuffix: () => removeSuffix,
  removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator,
  repeatString: () => repeatString,
  replaceElement: () => replaceElement,
  replaceFirstStar: () => replaceFirstStar,
  resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson,
  resolveConfigFileProjectName: () => resolveConfigFileProjectName,
  resolveJSModule: () => resolveJSModule,
  resolveLibrary: () => resolveLibrary,
  resolveModuleName: () => resolveModuleName,
  resolveModuleNameFromCache: () => resolveModuleNameFromCache,
  resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson,
  resolvePath: () => resolvePath,
  resolveProjectReferencePath: () => resolveProjectReferencePath,
  resolveTripleslashReference: () => resolveTripleslashReference,
  resolveTypeReferenceDirective: () => resolveTypeReferenceDirective,
  resolvingEmptyArray: () => resolvingEmptyArray,
  returnFalse: () => returnFalse,
  returnNoopFileWatcher: () => returnNoopFileWatcher,
  returnTrue: () => returnTrue,
  returnUndefined: () => returnUndefined,
  returnsPromise: () => returnsPromise,
  rewriteModuleSpecifier: () => rewriteModuleSpecifier,
  sameFlatMap: () => sameFlatMap,
  sameMap: () => sameMap,
  sameMapping: () => sameMapping,
  scanTokenAtPosition: () => scanTokenAtPosition,
  scanner: () => scanner,
  semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations,
  serializeCompilerOptions: () => serializeCompilerOptions,
  server: () => ts_server_exports3,
  servicesVersion: () => servicesVersion,
  setCommentRange: () => setCommentRange,
  setConfigFileInOptions: () => setConfigFileInOptions,
  setConstantValue: () => setConstantValue,
  setEmitFlags: () => setEmitFlags,
  setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned,
  setIdentifierAutoGenerate: () => setIdentifierAutoGenerate,
  setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference,
  setIdentifierTypeArguments: () => setIdentifierTypeArguments,
  setInternalEmitFlags: () => setInternalEmitFlags,
  setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages,
  setNodeChildren: () => setNodeChildren,
  setNodeFlags: () => setNodeFlags,
  setObjectAllocator: () => setObjectAllocator,
  setOriginalNode: () => setOriginalNode,
  setParent: () => setParent,
  setParentRecursive: () => setParentRecursive,
  setPrivateIdentifier: () => setPrivateIdentifier,
  setSnippetElement: () => setSnippetElement,
  setSourceMapRange: () => setSourceMapRange,
  setStackTraceLimit: () => setStackTraceLimit,
  setStartsOnNewLine: () => setStartsOnNewLine,
  setSyntheticLeadingComments: () => setSyntheticLeadingComments,
  setSyntheticTrailingComments: () => setSyntheticTrailingComments,
  setSys: () => setSys,
  setSysLog: () => setSysLog,
  setTextRange: () => setTextRange,
  setTextRangeEnd: () => setTextRangeEnd,
  setTextRangePos: () => setTextRangePos,
  setTextRangePosEnd: () => setTextRangePosEnd,
  setTextRangePosWidth: () => setTextRangePosWidth,
  setTokenSourceMapRange: () => setTokenSourceMapRange,
  setTypeNode: () => setTypeNode,
  setUILocale: () => setUILocale,
  setValueDeclaration: () => setValueDeclaration,
  shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension,
  shouldPreserveConstEnums: () => shouldPreserveConstEnums,
  shouldRewriteModuleSpecifier: () => shouldRewriteModuleSpecifier,
  shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules,
  showModuleSpecifier: () => showModuleSpecifier,
  signatureHasRestParameter: () => signatureHasRestParameter,
  signatureToDisplayParts: () => signatureToDisplayParts,
  single: () => single,
  singleElementArray: () => singleElementArray,
  singleIterator: () => singleIterator,
  singleOrMany: () => singleOrMany,
  singleOrUndefined: () => singleOrUndefined,
  skipAlias: () => skipAlias,
  skipConstraint: () => skipConstraint,
  skipOuterExpressions: () => skipOuterExpressions,
  skipParentheses: () => skipParentheses,
  skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions,
  skipTrivia: () => skipTrivia,
  skipTypeChecking: () => skipTypeChecking,
  skipTypeCheckingIgnoringNoCheck: () => skipTypeCheckingIgnoringNoCheck,
  skipTypeParentheses: () => skipTypeParentheses,
  skipWhile: () => skipWhile,
  sliceAfter: () => sliceAfter,
  some: () => some,
  sortAndDeduplicate: () => sortAndDeduplicate,
  sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics,
  sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions,
  sourceFileMayBeEmitted: () => sourceFileMayBeEmitted,
  sourceMapCommentRegExp: () => sourceMapCommentRegExp,
  sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart,
  spacePart: () => spacePart,
  spanMap: () => spanMap,
  startEndContainsRange: () => startEndContainsRange,
  startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd,
  startOnNewLine: () => startOnNewLine,
  startTracing: () => startTracing,
  startsWith: () => startsWith,
  startsWithDirectory: () => startsWithDirectory,
  startsWithUnderscore: () => startsWithUnderscore,
  startsWithUseStrict: () => startsWithUseStrict,
  stringContainsAt: () => stringContainsAt,
  stringToToken: () => stringToToken,
  stripQuotes: () => stripQuotes,
  supportedDeclarationExtensions: () => supportedDeclarationExtensions,
  supportedJSExtensionsFlat: () => supportedJSExtensionsFlat,
  supportedLocaleDirectories: () => supportedLocaleDirectories,
  supportedTSExtensionsFlat: () => supportedTSExtensionsFlat,
  supportedTSImplementationExtensions: () => supportedTSImplementationExtensions,
  suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia,
  suppressLeadingTrivia: () => suppressLeadingTrivia,
  suppressTrailingTrivia: () => suppressTrailingTrivia,
  symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault,
  symbolName: () => symbolName,
  symbolNameNoDefault: () => symbolNameNoDefault,
  symbolToDisplayParts: () => symbolToDisplayParts,
  sys: () => sys,
  sysLog: () => sysLog,
  tagNamesAreEquivalent: () => tagNamesAreEquivalent,
  takeWhile: () => takeWhile,
  targetOptionDeclaration: () => targetOptionDeclaration,
  targetToLibMap: () => targetToLibMap,
  testFormatSettings: () => testFormatSettings,
  textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged,
  textChangeRangeNewSpan: () => textChangeRangeNewSpan,
  textChanges: () => ts_textChanges_exports,
  textOrKeywordPart: () => textOrKeywordPart,
  textPart: () => textPart,
  textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive,
  textRangeContainsTextSpan: () => textRangeContainsTextSpan,
  textRangeIntersectsWithTextSpan: () => textRangeIntersectsWithTextSpan,
  textSpanContainsPosition: () => textSpanContainsPosition,
  textSpanContainsTextRange: () => textSpanContainsTextRange,
  textSpanContainsTextSpan: () => textSpanContainsTextSpan,
  textSpanEnd: () => textSpanEnd,
  textSpanIntersection: () => textSpanIntersection,
  textSpanIntersectsWith: () => textSpanIntersectsWith,
  textSpanIntersectsWithPosition: () => textSpanIntersectsWithPosition,
  textSpanIntersectsWithTextSpan: () => textSpanIntersectsWithTextSpan,
  textSpanIsEmpty: () => textSpanIsEmpty,
  textSpanOverlap: () => textSpanOverlap,
  textSpanOverlapsWith: () => textSpanOverlapsWith,
  textSpansEqual: () => textSpansEqual,
  textToKeywordObj: () => textToKeywordObj,
  timestamp: () => timestamp,
  toArray: () => toArray,
  toBuilderFileEmit: () => toBuilderFileEmit,
  toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit,
  toEditorSettings: () => toEditorSettings,
  toFileNameLowerCase: () => toFileNameLowerCase,
  toPath: () => toPath,
  toProgramEmitPending: () => toProgramEmitPending,
  toSorted: () => toSorted,
  tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword,
  tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan,
  tokenToString: () => tokenToString,
  trace: () => trace,
  tracing: () => tracing,
  tracingEnabled: () => tracingEnabled,
  transferSourceFileChildren: () => transferSourceFileChildren,
  transform: () => transform,
  transformClassFields: () => transformClassFields,
  transformDeclarations: () => transformDeclarations,
  transformECMAScriptModule: () => transformECMAScriptModule,
  transformES2015: () => transformES2015,
  transformES2016: () => transformES2016,
  transformES2017: () => transformES2017,
  transformES2018: () => transformES2018,
  transformES2019: () => transformES2019,
  transformES2020: () => transformES2020,
  transformES2021: () => transformES2021,
  transformESDecorators: () => transformESDecorators,
  transformESNext: () => transformESNext,
  transformGenerators: () => transformGenerators,
  transformImpliedNodeFormatDependentModule: () => transformImpliedNodeFormatDependentModule,
  transformJsx: () => transformJsx,
  transformLegacyDecorators: () => transformLegacyDecorators,
  transformModule: () => transformModule,
  transformNamedEvaluation: () => transformNamedEvaluation,
  transformNodes: () => transformNodes,
  transformSystemModule: () => transformSystemModule,
  transformTypeScript: () => transformTypeScript,
  transpile: () => transpile,
  transpileDeclaration: () => transpileDeclaration,
  transpileModule: () => transpileModule,
  transpileOptionValueCompilerOptions: () => transpileOptionValueCompilerOptions,
  tryAddToSet: () => tryAddToSet,
  tryAndIgnoreErrors: () => tryAndIgnoreErrors,
  tryCast: () => tryCast,
  tryDirectoryExists: () => tryDirectoryExists,
  tryExtractTSExtension: () => tryExtractTSExtension,
  tryFileExists: () => tryFileExists,
  tryGetClassExtendingExpressionWithTypeArguments: () => tryGetClassExtendingExpressionWithTypeArguments,
  tryGetClassImplementingOrExtendingExpressionWithTypeArguments: () => tryGetClassImplementingOrExtendingExpressionWithTypeArguments,
  tryGetDirectories: () => tryGetDirectories,
  tryGetExtensionFromPath: () => tryGetExtensionFromPath2,
  tryGetImportFromModuleSpecifier: () => tryGetImportFromModuleSpecifier,
  tryGetJSDocSatisfiesTypeNode: () => tryGetJSDocSatisfiesTypeNode,
  tryGetModuleNameFromFile: () => tryGetModuleNameFromFile,
  tryGetModuleSpecifierFromDeclaration: () => tryGetModuleSpecifierFromDeclaration,
  tryGetNativePerformanceHooks: () => tryGetNativePerformanceHooks,
  tryGetPropertyAccessOrIdentifierToString: () => tryGetPropertyAccessOrIdentifierToString,
  tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement,
  tryGetSourceMappingURL: () => tryGetSourceMappingURL,
  tryGetTextOfPropertyName: () => tryGetTextOfPropertyName,
  tryParseJson: () => tryParseJson,
  tryParsePattern: () => tryParsePattern,
  tryParsePatterns: () => tryParsePatterns,
  tryParseRawSourceMap: () => tryParseRawSourceMap,
  tryReadDirectory: () => tryReadDirectory,
  tryReadFile: () => tryReadFile,
  tryRemoveDirectoryPrefix: () => tryRemoveDirectoryPrefix,
  tryRemoveExtension: () => tryRemoveExtension,
  tryRemovePrefix: () => tryRemovePrefix,
  tryRemoveSuffix: () => tryRemoveSuffix,
  tscBuildOption: () => tscBuildOption,
  typeAcquisitionDeclarations: () => typeAcquisitionDeclarations,
  typeAliasNamePart: () => typeAliasNamePart,
  typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo,
  typeKeywords: () => typeKeywords,
  typeParameterNamePart: () => typeParameterNamePart,
  typeToDisplayParts: () => typeToDisplayParts,
  unchangedPollThresholds: () => unchangedPollThresholds,
  unchangedTextChangeRange: () => unchangedTextChangeRange,
  unescapeLeadingUnderscores: () => unescapeLeadingUnderscores,
  unmangleScopedPackageName: () => unmangleScopedPackageName,
  unorderedRemoveItem: () => unorderedRemoveItem,
  unprefixedNodeCoreModules: () => unprefixedNodeCoreModules,
  unreachableCodeIsError: () => unreachableCodeIsError,
  unsetNodeChildren: () => unsetNodeChildren,
  unusedLabelIsError: () => unusedLabelIsError,
  unwrapInnermostStatementOfLabel: () => unwrapInnermostStatementOfLabel,
  unwrapParenthesizedExpression: () => unwrapParenthesizedExpression,
  updateErrorForNoInputFiles: () => updateErrorForNoInputFiles,
  updateLanguageServiceSourceFile: () => updateLanguageServiceSourceFile,
  updateMissingFilePathsWatch: () => updateMissingFilePathsWatch,
  updateResolutionField: () => updateResolutionField,
  updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher,
  updateSourceFile: () => updateSourceFile,
  updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories,
  usingSingleLineStringWriter: () => usingSingleLineStringWriter,
  utf16EncodeAsString: () => utf16EncodeAsString,
  validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage,
  version: () => version,
  versionMajorMinor: () => versionMajorMinor,
  visitArray: () => visitArray,
  visitCommaListElements: () => visitCommaListElements,
  visitEachChild: () => visitEachChild,
  visitFunctionBody: () => visitFunctionBody,
  visitIterationBody: () => visitIterationBody,
  visitLexicalEnvironment: () => visitLexicalEnvironment,
  visitNode: () => visitNode,
  visitNodes: () => visitNodes2,
  visitParameterList: () => visitParameterList,
  walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns,
  walkUpOuterExpressions: () => walkUpOuterExpressions,
  walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions,
  walkUpParenthesizedTypes: () => walkUpParenthesizedTypes,
  walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild,
  whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp,
  writeCommentRange: () => writeCommentRange,
  writeFile: () => writeFile,
  writeFileEnsuringDirectories: () => writeFileEnsuringDirectories,
  zipWith: () => zipWith
});

// src/deprecatedCompat/deprecate.ts
var enableDeprecationWarnings = true;
var typeScriptVersion2;
function getTypeScriptVersion() {
  return typeScriptVersion2 ?? (typeScriptVersion2 = new Version(version));
}
function formatDeprecationMessage(name, error2, errorAfter, since, message) {
  let deprecationMessage = error2 ? "DeprecationError: " : "DeprecationWarning: ";
  deprecationMessage += `'${name}' `;
  deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated";
  deprecationMessage += error2 ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : ".";
  deprecationMessage += message ? ` ${formatStringFromArgs(message, [name])}` : "";
  return deprecationMessage;
}
function createErrorDeprecation(name, errorAfter, since, message) {
  const deprecationMessage = formatDeprecationMessage(
    name,
    /*error*/
    true,
    errorAfter,
    since,
    message
  );
  return () => {
    throw new TypeError(deprecationMessage);
  };
}
function createWarningDeprecation(name, errorAfter, since, message) {
  let hasWrittenDeprecation = false;
  return () => {
    if (enableDeprecationWarnings && !hasWrittenDeprecation) {
      Debug.log.warn(formatDeprecationMessage(
        name,
        /*error*/
        false,
        errorAfter,
        since,
        message
      ));
      hasWrittenDeprecation = true;
    }
  };
}
function createDeprecation(name, options = {}) {
  const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion();
  const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter;
  const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter;
  const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter;
  const error2 = options.error || errorAfter && version2.compareTo(errorAfter) >= 0;
  const warn = !warnAfter || version2.compareTo(warnAfter) >= 0;
  return error2 ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop;
}
function wrapFunction(deprecation, func) {
  return function() {
    deprecation();
    return func.apply(this, arguments);
  };
}
function deprecate(func, options) {
  const deprecation = createDeprecation((options == null ? void 0 : options.name) ?? Debug.getFunctionName(func), options);
  return wrapFunction(deprecation, func);
}

// src/deprecatedCompat/deprecations.ts
function createOverload(name, overloads, binder2, deprecations) {
  Object.defineProperty(call, "name", { ...Object.getOwnPropertyDescriptor(call, "name"), value: name });
  if (deprecations) {
    for (const key of Object.keys(deprecations)) {
      const index = +key;
      if (!isNaN(index) && hasProperty(overloads, `${index}`)) {
        overloads[index] = deprecate(overloads[index], { ...deprecations[index], name });
      }
    }
  }
  const bind = createBinder2(overloads, binder2);
  return call;
  function call(...args) {
    const index = bind(args);
    const fn = index !== void 0 ? overloads[index] : void 0;
    if (typeof fn === "function") {
      return fn(...args);
    }
    throw new TypeError("Invalid arguments");
  }
}
function createBinder2(overloads, binder2) {
  return (args) => {
    for (let i = 0; hasProperty(overloads, `${i}`) && hasProperty(binder2, `${i}`); i++) {
      const fn = binder2[i];
      if (fn(args)) {
        return i;
      }
    }
  };
}
function buildOverload(name) {
  return {
    overload: (overloads) => ({
      bind: (binder2) => ({
        finish: () => createOverload(name, overloads, binder2),
        deprecate: (deprecations) => ({
          finish: () => createOverload(name, overloads, binder2, deprecations)
        })
      })
    })
  };
}

// src/server/_namespaces/ts.server.ts
var ts_server_exports3 = {};
__export(ts_server_exports3, {
  ActionInvalidate: () => ActionInvalidate,
  ActionPackageInstalled: () => ActionPackageInstalled,
  ActionSet: () => ActionSet,
  ActionWatchTypingLocations: () => ActionWatchTypingLocations,
  Arguments: () => Arguments,
  AutoImportProviderProject: () => AutoImportProviderProject,
  AuxiliaryProject: () => AuxiliaryProject,
  CharRangeSection: () => CharRangeSection,
  CloseFileWatcherEvent: () => CloseFileWatcherEvent,
  CommandNames: () => CommandNames,
  ConfigFileDiagEvent: () => ConfigFileDiagEvent,
  ConfiguredProject: () => ConfiguredProject2,
  ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind,
  CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent,
  CreateFileWatcherEvent: () => CreateFileWatcherEvent,
  Errors: () => Errors,
  EventBeginInstallTypes: () => EventBeginInstallTypes,
  EventEndInstallTypes: () => EventEndInstallTypes,
  EventInitializationFailed: () => EventInitializationFailed,
  EventTypesRegistry: () => EventTypesRegistry,
  ExternalProject: () => ExternalProject,
  GcTimer: () => GcTimer,
  InferredProject: () => InferredProject2,
  LargeFileReferencedEvent: () => LargeFileReferencedEvent,
  LineIndex: () => LineIndex,
  LineLeaf: () => LineLeaf,
  LineNode: () => LineNode,
  LogLevel: () => LogLevel2,
  Msg: () => Msg,
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
  Project: () => Project2,
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
  ProjectKind: () => ProjectKind,
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
  ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent,
  ProjectLoadingStartEvent: () => ProjectLoadingStartEvent,
  ProjectService: () => ProjectService2,
  ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent,
  ScriptInfo: () => ScriptInfo,
  ScriptVersionCache: () => ScriptVersionCache,
  Session: () => Session3,
  TextStorage: () => TextStorage,
  ThrottledOperations: () => ThrottledOperations,
  TypingsInstallerAdapter: () => TypingsInstallerAdapter,
  allFilesAreJsOrDts: () => allFilesAreJsOrDts,
  allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts,
  asNormalizedPath: () => asNormalizedPath,
  convertCompilerOptions: () => convertCompilerOptions,
  convertFormatOptions: () => convertFormatOptions,
  convertScriptKindName: () => convertScriptKindName,
  convertTypeAcquisition: () => convertTypeAcquisition,
  convertUserPreferences: () => convertUserPreferences,
  convertWatchOptions: () => convertWatchOptions,
  countEachFileTypes: () => countEachFileTypes,
  createInstallTypingsRequest: () => createInstallTypingsRequest,
  createModuleSpecifierCache: () => createModuleSpecifierCache,
  createNormalizedPathMap: () => createNormalizedPathMap,
  createPackageJsonCache: () => createPackageJsonCache,
  createSortedArray: () => createSortedArray2,
  emptyArray: () => emptyArray2,
  findArgument: () => findArgument,
  formatDiagnosticToProtocol: () => formatDiagnosticToProtocol,
  formatMessage: () => formatMessage2,
  getBaseConfigFileName: () => getBaseConfigFileName,
  getDetailWatchInfo: () => getDetailWatchInfo,
  getLocationInNewDocument: () => getLocationInNewDocument,
  hasArgument: () => hasArgument,
  hasNoTypeScriptSource: () => hasNoTypeScriptSource,
  indent: () => indent2,
  isBackgroundProject: () => isBackgroundProject,
  isConfigFile: () => isConfigFile,
  isConfiguredProject: () => isConfiguredProject,
  isDynamicFileName: () => isDynamicFileName,
  isExternalProject: () => isExternalProject,
  isInferredProject: () => isInferredProject,
  isInferredProjectName: () => isInferredProjectName,
  isProjectDeferredClose: () => isProjectDeferredClose,
  makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName,
  makeAuxiliaryProjectName: () => makeAuxiliaryProjectName,
  makeInferredProjectName: () => makeInferredProjectName,
  maxFileSize: () => maxFileSize,
  maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles,
  normalizedPathToPath: () => normalizedPathToPath,
  nowString: () => nowString,
  nullCancellationToken: () => nullCancellationToken,
  nullTypingsInstaller: () => nullTypingsInstaller,
  protocol: () => ts_server_protocol_exports,
  scriptInfoIsContainedByBackgroundProject: () => scriptInfoIsContainedByBackgroundProject,
  scriptInfoIsContainedByDeferredClosedProject: () => scriptInfoIsContainedByDeferredClosedProject,
  stringifyIndented: () => stringifyIndented,
  toEvent: () => toEvent,
  toNormalizedPath: () => toNormalizedPath,
  tryConvertScriptKindName: () => tryConvertScriptKindName,
  typingsInstaller: () => ts_server_typingsInstaller_exports,
  updateProjectIfDirty: () => updateProjectIfDirty
});

// src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts
var ts_server_typingsInstaller_exports = {};
__export(ts_server_typingsInstaller_exports, {
  TypingsInstaller: () => TypingsInstaller,
  getNpmCommandForInstallation: () => getNpmCommandForInstallation,
  installNpmPackages: () => installNpmPackages,
  typingsName: () => typingsName
});

// src/typingsInstallerCore/typingsInstaller.ts
var nullLog = {
  isEnabled: () => false,
  writeLine: noop
};
function typingToFileName(cachePath, packageName, installTypingHost, log) {
  try {
    const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: 2 /* Node10 */ }, installTypingHost);
    return result.resolvedModule && result.resolvedModule.resolvedFileName;
  } catch (e) {
    if (log.isEnabled()) {
      log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${e.message}`);
    }
    return void 0;
  }
}
function installNpmPackages(npmPath, tsVersion, packageNames, install) {
  let hasError = false;
  for (let remaining = packageNames.length; remaining > 0; ) {
    const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
    remaining = result.remaining;
    hasError = install(result.command) || hasError;
  }
  return hasError;
}
function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
  const sliceStart = packageNames.length - remaining;
  let command, toSlice = remaining;
  while (true) {
    command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`;
    if (command.length < 8e3) {
      break;
    }
    toSlice = toSlice - Math.floor(toSlice / 2);
  }
  return { command, remaining: remaining - toSlice };
}
var TypingsInstaller = class {
  constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log = nullLog) {
    this.installTypingHost = installTypingHost;
    this.globalCachePath = globalCachePath;
    this.safeListPath = safeListPath;
    this.typesMapLocation = typesMapLocation;
    this.throttleLimit = throttleLimit;
    this.log = log;
    this.packageNameToTypingLocation = /* @__PURE__ */ new Map();
    this.missingTypingsSet = /* @__PURE__ */ new Set();
    this.knownCachesSet = /* @__PURE__ */ new Set();
    this.projectWatchers = /* @__PURE__ */ new Map();
    this.pendingRunRequests = [];
    this.installRunCount = 1;
    this.inFlightRequestCount = 0;
    // eslint-disable-line @typescript-eslint/unified-signatures
    this.latestDistTag = "latest";
    const isLoggingEnabled = this.log.isEnabled();
    if (isLoggingEnabled) {
      this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`);
    }
    this.processCacheLocation(this.globalCachePath);
  }
  /** @internal */
  handleRequest(req) {
    switch (req.kind) {
      case "discover":
        this.install(req);
        break;
      case "closeProject":
        this.closeProject(req);
        break;
      case "typesRegistry": {
        const typesRegistry = {};
        this.typesRegistry.forEach((value, key) => {
          typesRegistry[key] = value;
        });
        const response = { kind: EventTypesRegistry, typesRegistry };
        this.sendResponse(response);
        break;
      }
      case "installPackage": {
        this.installPackage(req);
        break;
      }
      default:
        Debug.assertNever(req);
    }
  }
  closeProject(req) {
    this.closeWatchers(req.projectName);
  }
  closeWatchers(projectName) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Closing file watchers for project '${projectName}'`);
    }
    const watchers = this.projectWatchers.get(projectName);
    if (!watchers) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`No watchers are registered for project '${projectName}'`);
      }
      return;
    }
    this.projectWatchers.delete(projectName);
    this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] });
    if (this.log.isEnabled()) {
      this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`);
    }
  }
  install(req) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Got install request${stringifyIndented(req)}`);
    }
    if (req.cachePath) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`);
      }
      this.processCacheLocation(req.cachePath);
    }
    if (this.safeList === void 0) {
      this.initializeSafeList();
    }
    const discoverTypingsResult = ts_JsTyping_exports.discoverTypings(
      this.installTypingHost,
      this.log.isEnabled() ? (s) => this.log.writeLine(s) : void 0,
      req.fileNames,
      req.projectRootPath,
      this.safeList,
      this.packageNameToTypingLocation,
      req.typeAcquisition,
      req.unresolvedImports,
      this.typesRegistry,
      req.compilerOptions
    );
    this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch);
    if (discoverTypingsResult.newTypingNames.length) {
      this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
    } else {
      this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
      if (this.log.isEnabled()) {
        this.log.writeLine(`No new typings were requested as a result of typings discovery`);
      }
    }
  }
  /** @internal */
  installPackage(req) {
    const { fileName, packageName, projectName, projectRootPath, id } = req;
    const cwd = forEachAncestorDirectory(getDirectoryPath(fileName), (directory) => {
      if (this.installTypingHost.fileExists(combinePaths(directory, "package.json"))) {
        return directory;
      }
    }) || projectRootPath;
    if (cwd) {
      this.installWorker(-1, [packageName], cwd, (success) => {
        const message = success ? `Package ${packageName} installed.` : `There was an error installing ${packageName}.`;
        const response = {
          kind: ActionPackageInstalled,
          projectName,
          id,
          success,
          message
        };
        this.sendResponse(response);
      });
    } else {
      const response = {
        kind: ActionPackageInstalled,
        projectName,
        id,
        success: false,
        message: "Could not determine a project root path."
      };
      this.sendResponse(response);
    }
  }
  initializeSafeList() {
    if (this.typesMapLocation) {
      const safeListFromMap = ts_JsTyping_exports.loadTypesMap(this.installTypingHost, this.typesMapLocation);
      if (safeListFromMap) {
        this.log.writeLine(`Loaded safelist from types map file '${this.typesMapLocation}'`);
        this.safeList = safeListFromMap;
        return;
      }
      this.log.writeLine(`Failed to load safelist from types map file '${this.typesMapLocation}'`);
    }
    this.safeList = ts_JsTyping_exports.loadSafeList(this.installTypingHost, this.safeListPath);
  }
  processCacheLocation(cacheLocation) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Processing cache location '${cacheLocation}'`);
    }
    if (this.knownCachesSet.has(cacheLocation)) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Cache location was already processed...`);
      }
      return;
    }
    const packageJson = combinePaths(cacheLocation, "package.json");
    const packageLockJson = combinePaths(cacheLocation, "package-lock.json");
    if (this.log.isEnabled()) {
      this.log.writeLine(`Trying to find '${packageJson}'...`);
    }
    if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
      const npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson));
      const npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson));
      if (this.log.isEnabled()) {
        this.log.writeLine(`Loaded content of '${packageJson}':${stringifyIndented(npmConfig)}`);
        this.log.writeLine(`Loaded content of '${packageLockJson}':${stringifyIndented(npmLock)}`);
      }
      if (npmConfig.devDependencies && npmLock.dependencies) {
        for (const key in npmConfig.devDependencies) {
          if (!hasProperty(npmLock.dependencies, key)) {
            continue;
          }
          const packageName = getBaseFileName(key);
          if (!packageName) {
            continue;
          }
          const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
          if (!typingFile) {
            this.missingTypingsSet.add(packageName);
            continue;
          }
          const existingTypingFile = this.packageNameToTypingLocation.get(packageName);
          if (existingTypingFile) {
            if (existingTypingFile.typingLocation === typingFile) {
              continue;
            }
            if (this.log.isEnabled()) {
              this.log.writeLine(`New typing for package ${packageName} from '${typingFile}' conflicts with existing typing file '${existingTypingFile}'`);
            }
          }
          if (this.log.isEnabled()) {
            this.log.writeLine(`Adding entry into typings cache: '${packageName}' => '${typingFile}'`);
          }
          const info = getProperty(npmLock.dependencies, key);
          const version2 = info && info.version;
          if (!version2) {
            continue;
          }
          const newTyping = { typingLocation: typingFile, version: new Version(version2) };
          this.packageNameToTypingLocation.set(packageName, newTyping);
        }
      }
    }
    if (this.log.isEnabled()) {
      this.log.writeLine(`Finished processing cache location '${cacheLocation}'`);
    }
    this.knownCachesSet.add(cacheLocation);
  }
  filterTypings(typingsToInstall) {
    return mapDefined(typingsToInstall, (typing) => {
      const typingKey = mangleScopedPackageName(typing);
      if (this.missingTypingsSet.has(typingKey)) {
        if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`);
        return void 0;
      }
      const validationResult = ts_JsTyping_exports.validatePackageName(typing);
      if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) {
        this.missingTypingsSet.add(typingKey);
        if (this.log.isEnabled()) this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing));
        return void 0;
      }
      if (!this.typesRegistry.has(typingKey)) {
        if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`);
        return void 0;
      }
      if (this.packageNameToTypingLocation.get(typingKey) && ts_JsTyping_exports.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey), this.typesRegistry.get(typingKey))) {
        if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`);
        return void 0;
      }
      return typingKey;
    });
  }
  ensurePackageDirectoryExists(directory) {
    const npmConfigPath = combinePaths(directory, "package.json");
    if (this.log.isEnabled()) {
      this.log.writeLine(`Npm config file: ${npmConfigPath}`);
    }
    if (!this.installTypingHost.fileExists(npmConfigPath)) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`);
      }
      this.ensureDirectoryExists(directory, this.installTypingHost);
      this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
    }
  }
  installTypings(req, cachePath, currentlyCachedTypings, typingsToInstall) {
    if (this.log.isEnabled()) {
      this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`);
    }
    const filteredTypings = this.filterTypings(typingsToInstall);
    if (filteredTypings.length === 0) {
      if (this.log.isEnabled()) {
        this.log.writeLine(`All typings are known to be missing or invalid - no need to install more typings`);
      }
      this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
      return;
    }
    this.ensurePackageDirectoryExists(cachePath);
    const requestId = this.installRunCount;
    this.installRunCount++;
    this.sendResponse({
      kind: EventBeginInstallTypes,
      eventId: requestId,
      typingsInstallerVersion: version,
      projectName: req.projectName
    });
    const scopedTypings = filteredTypings.map(typingsName);
    this.installTypingsAsync(requestId, scopedTypings, cachePath, (ok) => {
      try {
        if (!ok) {
          if (this.log.isEnabled()) {
            this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`);
          }
          for (const typing of filteredTypings) {
            this.missingTypingsSet.add(typing);
          }
          return;
        }
        if (this.log.isEnabled()) {
          this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`);
        }
        const installedTypingFiles = [];
        for (const packageName of filteredTypings) {
          const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log);
          if (!typingFile) {
            this.missingTypingsSet.add(packageName);
            continue;
          }
          const distTags = this.typesRegistry.get(packageName);
          const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]);
          const newTyping = { typingLocation: typingFile, version: newVersion };
          this.packageNameToTypingLocation.set(packageName, newTyping);
          installedTypingFiles.push(typingFile);
        }
        if (this.log.isEnabled()) {
          this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`);
        }
        this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
      } finally {
        const response = {
          kind: EventEndInstallTypes,
          eventId: requestId,
          projectName: req.projectName,
          packagesToInstall: scopedTypings,
          installSuccess: ok,
          typingsInstallerVersion: version
        };
        this.sendResponse(response);
      }
    });
  }
  ensureDirectoryExists(directory, host) {
    const directoryName = getDirectoryPath(directory);
    if (!host.directoryExists(directoryName)) {
      this.ensureDirectoryExists(directoryName, host);
    }
    if (!host.directoryExists(directory)) {
      host.createDirectory(directory);
    }
  }
  watchFiles(projectName, files) {
    if (!files.length) {
      this.closeWatchers(projectName);
      return;
    }
    const existing = this.projectWatchers.get(projectName);
    const newSet = new Set(files);
    if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) {
      this.projectWatchers.set(projectName, newSet);
      this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files });
    } else {
      this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 });
    }
  }
  createSetTypings(request, typings) {
    return {
      projectName: request.projectName,
      typeAcquisition: request.typeAcquisition,
      compilerOptions: request.compilerOptions,
      typings,
      unresolvedImports: request.unresolvedImports,
      kind: ActionSet
    };
  }
  installTypingsAsync(requestId, packageNames, cwd, onRequestCompleted) {
    this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted });
    this.executeWithThrottling();
  }
  executeWithThrottling() {
    while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
      this.inFlightRequestCount++;
      const request = this.pendingRunRequests.pop();
      this.installWorker(request.requestId, request.packageNames, request.cwd, (ok) => {
        this.inFlightRequestCount--;
        request.onRequestCompleted(ok);
        this.executeWithThrottling();
      });
    }
  }
};
function typingsName(packageName) {
  return `@types/${packageName}@ts${versionMajorMinor}`;
}

// src/server/utilitiesPublic.ts
var LogLevel2 = /* @__PURE__ */ ((LogLevel3) => {
  LogLevel3[LogLevel3["terse"] = 0] = "terse";
  LogLevel3[LogLevel3["normal"] = 1] = "normal";
  LogLevel3[LogLevel3["requestTime"] = 2] = "requestTime";
  LogLevel3[LogLevel3["verbose"] = 3] = "verbose";
  return LogLevel3;
})(LogLevel2 || {});
var emptyArray2 = createSortedArray2();
var Msg = /* @__PURE__ */ ((Msg2) => {
  Msg2["Err"] = "Err";
  Msg2["Info"] = "Info";
  Msg2["Perf"] = "Perf";
  return Msg2;
})(Msg || {});
function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) {
  return {
    projectName: project.getProjectName(),
    fileNames: project.getFileNames(
      /*excludeFilesFromExternalLibraries*/
      true,
      /*excludeConfigFiles*/
      true
    ).concat(project.getExcludedFiles()),
    compilerOptions: project.getCompilationSettings(),
    typeAcquisition,
    unresolvedImports,
    projectRootPath: project.getCurrentDirectory(),
    cachePath,
    kind: "discover"
  };
}
var Errors;
((Errors2) => {
  function ThrowNoProject() {
    throw new Error("No Project.");
  }
  Errors2.ThrowNoProject = ThrowNoProject;
  function ThrowProjectLanguageServiceDisabled() {
    throw new Error("The project's language service is disabled.");
  }
  Errors2.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled;
  function ThrowProjectDoesNotContainDocument(fileName, project) {
    throw new Error(`Project '${project.getProjectName()}' does not contain document '${fileName}'`);
  }
  Errors2.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument;
})(Errors || (Errors = {}));
function toNormalizedPath(fileName) {
  return normalizePath(fileName);
}
function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) {
  const f = isRootedDiskPath(normalizedPath) ? normalizedPath : getNormalizedAbsolutePath(normalizedPath, currentDirectory);
  return getCanonicalFileName(f);
}
function asNormalizedPath(fileName) {
  return fileName;
}
function createNormalizedPathMap() {
  const map2 = /* @__PURE__ */ new Map();
  return {
    get(path) {
      return map2.get(path);
    },
    set(path, value) {
      map2.set(path, value);
    },
    contains(path) {
      return map2.has(path);
    },
    remove(path) {
      map2.delete(path);
    }
  };
}
function isInferredProjectName(name) {
  return /dev\/null\/inferredProject\d+\*/.test(name);
}
function makeInferredProjectName(counter) {
  return `/dev/null/inferredProject${counter}*`;
}
function makeAutoImportProviderProjectName(counter) {
  return `/dev/null/autoImportProviderProject${counter}*`;
}
function makeAuxiliaryProjectName(counter) {
  return `/dev/null/auxiliaryProject${counter}*`;
}
function createSortedArray2() {
  return [];
}

// src/server/utilities.ts
var ThrottledOperations = class _ThrottledOperations {
  constructor(host, logger) {
    this.host = host;
    this.pendingTimeouts = /* @__PURE__ */ new Map();
    this.logger = logger.hasLevel(3 /* verbose */) ? logger : void 0;
  }
  /**
   * Wait `number` milliseconds and then invoke `cb`.  If, while waiting, schedule
   * is called again with the same `operationId`, cancel this operation in favor
   * of the new one.  (Note that the amount of time the canceled operation had been
   * waiting does not affect the amount of time that the new operation waits.)
   */
  schedule(operationId, delay, cb) {
    const pendingTimeout = this.pendingTimeouts.get(operationId);
    if (pendingTimeout) {
      this.host.clearTimeout(pendingTimeout);
    }
    this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay, operationId, this, cb));
    if (this.logger) {
      this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
    }
  }
  cancel(operationId) {
    const pendingTimeout = this.pendingTimeouts.get(operationId);
    if (!pendingTimeout) return false;
    this.host.clearTimeout(pendingTimeout);
    return this.pendingTimeouts.delete(operationId);
  }
  static run(operationId, self, cb) {
    self.pendingTimeouts.delete(operationId);
    if (self.logger) {
      self.logger.info(`Running: ${operationId}`);
    }
    cb();
  }
};
var GcTimer = class _GcTimer {
  constructor(host, delay, logger) {
    this.host = host;
    this.delay = delay;
    this.logger = logger;
  }
  scheduleCollect() {
    if (!this.host.gc || this.timerId !== void 0) {
      return;
    }
    this.timerId = this.host.setTimeout(_GcTimer.run, this.delay, this);
  }
  static run(self) {
    self.timerId = void 0;
    const log = self.logger.hasLevel(2 /* requestTime */);
    const before = log && self.host.getMemoryUsage();
    self.host.gc();
    if (log) {
      const after = self.host.getMemoryUsage();
      self.logger.perftrc(`GC::before ${before}, after ${after}`);
    }
  }
};
function getBaseConfigFileName(configFilePath) {
  const base = getBaseFileName(configFilePath);
  return base === "tsconfig.json" || base === "jsconfig.json" ? base : void 0;
}

// src/server/_namespaces/ts.server.protocol.ts
var ts_server_protocol_exports = {};
__export(ts_server_protocol_exports, {
  ClassificationType: () => ClassificationType,
  CommandTypes: () => CommandTypes,
  CompletionTriggerKind: () => CompletionTriggerKind,
  IndentStyle: () => IndentStyle2,
  JsxEmit: () => JsxEmit2,
  ModuleKind: () => ModuleKind2,
  ModuleResolutionKind: () => ModuleResolutionKind2,
  NewLineKind: () => NewLineKind2,
  OrganizeImportsMode: () => OrganizeImportsMode,
  PollingWatchKind: () => PollingWatchKind2,
  ScriptTarget: () => ScriptTarget11,
  SemicolonPreference: () => SemicolonPreference,
  WatchDirectoryKind: () => WatchDirectoryKind2,
  WatchFileKind: () => WatchFileKind2
});

// src/server/protocol.ts
var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => {
  CommandTypes2["JsxClosingTag"] = "jsxClosingTag";
  CommandTypes2["LinkedEditingRange"] = "linkedEditingRange";
  CommandTypes2["Brace"] = "brace";
  CommandTypes2["BraceFull"] = "brace-full";
  CommandTypes2["BraceCompletion"] = "braceCompletion";
  CommandTypes2["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment";
  CommandTypes2["Change"] = "change";
  CommandTypes2["Close"] = "close";
  CommandTypes2["Completions"] = "completions";
  CommandTypes2["CompletionInfo"] = "completionInfo";
  CommandTypes2["CompletionsFull"] = "completions-full";
  CommandTypes2["CompletionDetails"] = "completionEntryDetails";
  CommandTypes2["CompletionDetailsFull"] = "completionEntryDetails-full";
  CommandTypes2["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList";
  CommandTypes2["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile";
  CommandTypes2["Configure"] = "configure";
  CommandTypes2["Definition"] = "definition";
  CommandTypes2["DefinitionFull"] = "definition-full";
  CommandTypes2["DefinitionAndBoundSpan"] = "definitionAndBoundSpan";
  CommandTypes2["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full";
  CommandTypes2["Implementation"] = "implementation";
  CommandTypes2["ImplementationFull"] = "implementation-full";
  CommandTypes2["EmitOutput"] = "emit-output";
  CommandTypes2["Exit"] = "exit";
  CommandTypes2["FileReferences"] = "fileReferences";
  CommandTypes2["FileReferencesFull"] = "fileReferences-full";
  CommandTypes2["Format"] = "format";
  CommandTypes2["Formatonkey"] = "formatonkey";
  CommandTypes2["FormatFull"] = "format-full";
  CommandTypes2["FormatonkeyFull"] = "formatonkey-full";
  CommandTypes2["FormatRangeFull"] = "formatRange-full";
  CommandTypes2["Geterr"] = "geterr";
  CommandTypes2["GeterrForProject"] = "geterrForProject";
  CommandTypes2["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync";
  CommandTypes2["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
  CommandTypes2["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
  CommandTypes2["NavBar"] = "navbar";
  CommandTypes2["NavBarFull"] = "navbar-full";
  CommandTypes2["Navto"] = "navto";
  CommandTypes2["NavtoFull"] = "navto-full";
  CommandTypes2["NavTree"] = "navtree";
  CommandTypes2["NavTreeFull"] = "navtree-full";
  CommandTypes2["DocumentHighlights"] = "documentHighlights";
  CommandTypes2["DocumentHighlightsFull"] = "documentHighlights-full";
  CommandTypes2["Open"] = "open";
  CommandTypes2["Quickinfo"] = "quickinfo";
  CommandTypes2["QuickinfoFull"] = "quickinfo-full";
  CommandTypes2["References"] = "references";
  CommandTypes2["ReferencesFull"] = "references-full";
  CommandTypes2["Reload"] = "reload";
  CommandTypes2["Rename"] = "rename";
  CommandTypes2["RenameInfoFull"] = "rename-full";
  CommandTypes2["RenameLocationsFull"] = "renameLocations-full";
  CommandTypes2["Saveto"] = "saveto";
  CommandTypes2["SignatureHelp"] = "signatureHelp";
  CommandTypes2["SignatureHelpFull"] = "signatureHelp-full";
  CommandTypes2["FindSourceDefinition"] = "findSourceDefinition";
  CommandTypes2["Status"] = "status";
  CommandTypes2["TypeDefinition"] = "typeDefinition";
  CommandTypes2["ProjectInfo"] = "projectInfo";
  CommandTypes2["ReloadProjects"] = "reloadProjects";
  CommandTypes2["Unknown"] = "unknown";
  CommandTypes2["OpenExternalProject"] = "openExternalProject";
  CommandTypes2["OpenExternalProjects"] = "openExternalProjects";
  CommandTypes2["CloseExternalProject"] = "closeExternalProject";
  CommandTypes2["SynchronizeProjectList"] = "synchronizeProjectList";
  CommandTypes2["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
  CommandTypes2["UpdateOpen"] = "updateOpen";
  CommandTypes2["EncodedSyntacticClassificationsFull"] = "encodedSyntacticClassifications-full";
  CommandTypes2["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
  CommandTypes2["Cleanup"] = "cleanup";
  CommandTypes2["GetOutliningSpans"] = "getOutliningSpans";
  CommandTypes2["GetOutliningSpansFull"] = "outliningSpans";
  CommandTypes2["TodoComments"] = "todoComments";
  CommandTypes2["Indentation"] = "indentation";
  CommandTypes2["DocCommentTemplate"] = "docCommentTemplate";
  CommandTypes2["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full";
  CommandTypes2["NameOrDottedNameSpan"] = "nameOrDottedNameSpan";
  CommandTypes2["BreakpointStatement"] = "breakpointStatement";
  CommandTypes2["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects";
  CommandTypes2["GetCodeFixes"] = "getCodeFixes";
  CommandTypes2["GetCodeFixesFull"] = "getCodeFixes-full";
  CommandTypes2["GetCombinedCodeFix"] = "getCombinedCodeFix";
  CommandTypes2["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full";
  CommandTypes2["ApplyCodeActionCommand"] = "applyCodeActionCommand";
  CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes";
  CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors";
  CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor";
  CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions";
  CommandTypes2["PreparePasteEdits"] = "preparePasteEdits";
  CommandTypes2["GetPasteEdits"] = "getPasteEdits";
  CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full";
  CommandTypes2["OrganizeImports"] = "organizeImports";
  CommandTypes2["OrganizeImportsFull"] = "organizeImports-full";
  CommandTypes2["GetEditsForFileRename"] = "getEditsForFileRename";
  CommandTypes2["GetEditsForFileRenameFull"] = "getEditsForFileRename-full";
  CommandTypes2["ConfigurePlugin"] = "configurePlugin";
  CommandTypes2["SelectionRange"] = "selectionRange";
  CommandTypes2["SelectionRangeFull"] = "selectionRange-full";
  CommandTypes2["ToggleLineComment"] = "toggleLineComment";
  CommandTypes2["ToggleLineCommentFull"] = "toggleLineComment-full";
  CommandTypes2["ToggleMultilineComment"] = "toggleMultilineComment";
  CommandTypes2["ToggleMultilineCommentFull"] = "toggleMultilineComment-full";
  CommandTypes2["CommentSelection"] = "commentSelection";
  CommandTypes2["CommentSelectionFull"] = "commentSelection-full";
  CommandTypes2["UncommentSelection"] = "uncommentSelection";
  CommandTypes2["UncommentSelectionFull"] = "uncommentSelection-full";
  CommandTypes2["PrepareCallHierarchy"] = "prepareCallHierarchy";
  CommandTypes2["ProvideCallHierarchyIncomingCalls"] = "provideCallHierarchyIncomingCalls";
  CommandTypes2["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls";
  CommandTypes2["ProvideInlayHints"] = "provideInlayHints";
  CommandTypes2["WatchChange"] = "watchChange";
  CommandTypes2["MapCode"] = "mapCode";
  CommandTypes2["CopilotRelated"] = "copilotRelated";
  return CommandTypes2;
})(CommandTypes || {});
var WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => {
  WatchFileKind3["FixedPollingInterval"] = "FixedPollingInterval";
  WatchFileKind3["PriorityPollingInterval"] = "PriorityPollingInterval";
  WatchFileKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling";
  WatchFileKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling";
  WatchFileKind3["UseFsEvents"] = "UseFsEvents";
  WatchFileKind3["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory";
  return WatchFileKind3;
})(WatchFileKind2 || {});
var WatchDirectoryKind2 = /* @__PURE__ */ ((WatchDirectoryKind3) => {
  WatchDirectoryKind3["UseFsEvents"] = "UseFsEvents";
  WatchDirectoryKind3["FixedPollingInterval"] = "FixedPollingInterval";
  WatchDirectoryKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling";
  WatchDirectoryKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling";
  return WatchDirectoryKind3;
})(WatchDirectoryKind2 || {});
var PollingWatchKind2 = /* @__PURE__ */ ((PollingWatchKind3) => {
  PollingWatchKind3["FixedInterval"] = "FixedInterval";
  PollingWatchKind3["PriorityInterval"] = "PriorityInterval";
  PollingWatchKind3["DynamicPriority"] = "DynamicPriority";
  PollingWatchKind3["FixedChunkSize"] = "FixedChunkSize";
  return PollingWatchKind3;
})(PollingWatchKind2 || {});
var IndentStyle2 = /* @__PURE__ */ ((IndentStyle3) => {
  IndentStyle3["None"] = "None";
  IndentStyle3["Block"] = "Block";
  IndentStyle3["Smart"] = "Smart";
  return IndentStyle3;
})(IndentStyle2 || {});
var JsxEmit2 = /* @__PURE__ */ ((JsxEmit3) => {
  JsxEmit3["None"] = "none";
  JsxEmit3["Preserve"] = "preserve";
  JsxEmit3["ReactNative"] = "react-native";
  JsxEmit3["React"] = "react";
  JsxEmit3["ReactJSX"] = "react-jsx";
  JsxEmit3["ReactJSXDev"] = "react-jsxdev";
  return JsxEmit3;
})(JsxEmit2 || {});
var ModuleKind2 = /* @__PURE__ */ ((ModuleKind3) => {
  ModuleKind3["None"] = "none";
  ModuleKind3["CommonJS"] = "commonjs";
  ModuleKind3["AMD"] = "amd";
  ModuleKind3["UMD"] = "umd";
  ModuleKind3["System"] = "system";
  ModuleKind3["ES6"] = "es6";
  ModuleKind3["ES2015"] = "es2015";
  ModuleKind3["ES2020"] = "es2020";
  ModuleKind3["ES2022"] = "es2022";
  ModuleKind3["ESNext"] = "esnext";
  ModuleKind3["Node16"] = "node16";
  ModuleKind3["NodeNext"] = "nodenext";
  ModuleKind3["Preserve"] = "preserve";
  return ModuleKind3;
})(ModuleKind2 || {});
var ModuleResolutionKind2 = /* @__PURE__ */ ((ModuleResolutionKind3) => {
  ModuleResolutionKind3["Classic"] = "classic";
  ModuleResolutionKind3["Node"] = "node";
  ModuleResolutionKind3["NodeJs"] = "node";
  ModuleResolutionKind3["Node10"] = "node10";
  ModuleResolutionKind3["Node16"] = "node16";
  ModuleResolutionKind3["NodeNext"] = "nodenext";
  ModuleResolutionKind3["Bundler"] = "bundler";
  return ModuleResolutionKind3;
})(ModuleResolutionKind2 || {});
var NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => {
  NewLineKind3["Crlf"] = "Crlf";
  NewLineKind3["Lf"] = "Lf";
  return NewLineKind3;
})(NewLineKind2 || {});
var ScriptTarget11 = /* @__PURE__ */ ((ScriptTarget12) => {
  ScriptTarget12["ES3"] = "es3";
  ScriptTarget12["ES5"] = "es5";
  ScriptTarget12["ES6"] = "es6";
  ScriptTarget12["ES2015"] = "es2015";
  ScriptTarget12["ES2016"] = "es2016";
  ScriptTarget12["ES2017"] = "es2017";
  ScriptTarget12["ES2018"] = "es2018";
  ScriptTarget12["ES2019"] = "es2019";
  ScriptTarget12["ES2020"] = "es2020";
  ScriptTarget12["ES2021"] = "es2021";
  ScriptTarget12["ES2022"] = "es2022";
  ScriptTarget12["ES2023"] = "es2023";
  ScriptTarget12["ES2024"] = "es2024";
  ScriptTarget12["ESNext"] = "esnext";
  ScriptTarget12["JSON"] = "json";
  ScriptTarget12["Latest"] = "esnext" /* ESNext */;
  return ScriptTarget12;
})(ScriptTarget11 || {});
{
}

// src/server/scriptInfo.ts
var TextStorage = class {
  constructor(host, info, initialVersion) {
    this.host = host;
    this.info = info;
    /**
     * True if the text is for the file thats open in the editor
     */
    this.isOpen = false;
    /**
     * True if the text present is the text from the file on the disk
     */
    this.ownFileText = false;
    /**
     * True when reloading contents of file from the disk is pending
     */
    this.pendingReloadFromDisk = false;
    this.version = initialVersion || 0;
  }
  getVersion() {
    return this.svc ? `SVC-${this.version}-${this.svc.getSnapshotVersion()}` : `Text-${this.version}`;
  }
  hasScriptVersionCache_TestOnly() {
    return this.svc !== void 0;
  }
  resetSourceMapInfo() {
    this.info.sourceFileLike = void 0;
    this.info.closeSourceMapFileWatcher();
    this.info.sourceMapFilePath = void 0;
    this.info.declarationInfoPath = void 0;
    this.info.sourceInfos = void 0;
    this.info.documentPositionMapper = void 0;
  }
  /** Public for testing */
  useText(newText) {
    this.svc = void 0;
    this.text = newText;
    this.textSnapshot = void 0;
    this.lineMap = void 0;
    this.fileSize = void 0;
    this.resetSourceMapInfo();
    this.version++;
  }
  edit(start, end, newText) {
    this.switchToScriptVersionCache().edit(start, end - start, newText);
    this.ownFileText = false;
    this.text = void 0;
    this.textSnapshot = void 0;
    this.lineMap = void 0;
    this.fileSize = void 0;
    this.resetSourceMapInfo();
  }
  /**
   * Set the contents as newText
   * returns true if text changed
   */
  reload(newText) {
    Debug.assert(newText !== void 0);
    this.pendingReloadFromDisk = false;
    if (!this.text && this.svc) {
      this.text = getSnapshotText(this.svc.getSnapshot());
    }
    if (this.text !== newText) {
      this.useText(newText);
      this.ownFileText = false;
      return true;
    }
    return false;
  }
  /**
   * Reads the contents from tempFile(if supplied) or own file and sets it as contents
   * returns true if text changed
   */
  reloadWithFileText(tempFileName) {
    const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: void 0 };
    const reloaded = this.reload(newText);
    this.fileSize = fileSize;
    this.ownFileText = !tempFileName || tempFileName === this.info.fileName;
    if (this.ownFileText && this.info.mTime === missingFileModifiedTime.getTime()) {
      this.info.mTime = (this.host.getModifiedTime(this.info.fileName) || missingFileModifiedTime).getTime();
    }
    return reloaded;
  }
  /**
   * Schedule reload from the disk if its not already scheduled and its not own text
   * returns true when scheduling reload
   */
  scheduleReloadIfNeeded() {
    return !this.pendingReloadFromDisk && !this.ownFileText ? this.pendingReloadFromDisk = true : false;
  }
  delayReloadFromFileIntoText() {
    this.pendingReloadFromDisk = true;
  }
  /**
   * For telemetry purposes, we would like to be able to report the size of the file.
   * However, we do not want telemetry to require extra file I/O so we report a size
   * that may be stale (e.g. may not reflect change made on disk since the last reload).
   * NB: Will read from disk if the file contents have never been loaded because
   * telemetry falsely indicating size 0 would be counter-productive.
   */
  getTelemetryFileSize() {
    return !!this.fileSize ? this.fileSize : !!this.text ? this.text.length : !!this.svc ? this.svc.getSnapshot().getLength() : this.getSnapshot().getLength();
  }
  getSnapshot() {
    var _a;
    return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || (this.textSnapshot ?? (this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text))));
  }
  getAbsolutePositionAndLineText(oneBasedLine) {
    const svc = this.tryUseScriptVersionCache();
    if (svc) return svc.getAbsolutePositionAndLineText(oneBasedLine);
    const lineMap = this.getLineMap();
    return oneBasedLine <= lineMap.length ? {
      absolutePosition: lineMap[oneBasedLine - 1],
      lineText: this.text.substring(lineMap[oneBasedLine - 1], lineMap[oneBasedLine])
    } : {
      absolutePosition: this.text.length,
      lineText: void 0
    };
  }
  /**
   *  @param line 0 based index
   */
  lineToTextSpan(line) {
    const svc = this.tryUseScriptVersionCache();
    if (svc) return svc.lineToTextSpan(line);
    const lineMap = this.getLineMap();
    const start = lineMap[line];
    const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length;
    return createTextSpanFromBounds(start, end);
  }
  /**
   * @param line 1 based index
   * @param offset 1 based index
   */
  lineOffsetToPosition(line, offset, allowEdits) {
    const svc = this.tryUseScriptVersionCache();
    return svc ? svc.lineOffsetToPosition(line, offset) : computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
  }
  positionToLineOffset(position) {
    const svc = this.tryUseScriptVersionCache();
    if (svc) return svc.positionToLineOffset(position);
    const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position);
    return { line: line + 1, offset: character + 1 };
  }
  getFileTextAndSize(tempFileName) {
    let text;
    const fileName = tempFileName || this.info.fileName;
    const getText = () => text === void 0 ? text = this.host.readFile(fileName) || "" : text;
    if (!hasTSFileExtension(this.info.fileName)) {
      const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
      if (fileSize > maxFileSize) {
        Debug.assert(!!this.info.containingProjects.length);
        const service = this.info.containingProjects[0].projectService;
        service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`);
        this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize);
        return { text: "", fileSize };
      }
    }
    return { text: getText() };
  }
  /** @internal */
  switchToScriptVersionCache() {
    if (!this.svc || this.pendingReloadFromDisk) {
      this.svc = ScriptVersionCache.fromString(this.getOrLoadText());
      this.textSnapshot = void 0;
      this.version++;
    }
    return this.svc;
  }
  tryUseScriptVersionCache() {
    if (!this.svc || this.pendingReloadFromDisk) {
      this.getOrLoadText();
    }
    if (this.isOpen) {
      if (!this.svc && !this.textSnapshot) {
        this.svc = ScriptVersionCache.fromString(Debug.checkDefined(this.text));
        this.textSnapshot = void 0;
      }
      return this.svc;
    }
    return this.svc;
  }
  getOrLoadText() {
    if (this.text === void 0 || this.pendingReloadFromDisk) {
      Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk");
      this.reloadWithFileText();
    }
    return this.text;
  }
  getLineMap() {
    Debug.assert(!this.svc, "ScriptVersionCache should not be set");
    return this.lineMap || (this.lineMap = computeLineStarts(Debug.checkDefined(this.text)));
  }
  getLineInfo() {
    const svc = this.tryUseScriptVersionCache();
    if (svc) {
      return {
        getLineCount: () => svc.getLineCount(),
        getLineText: (line) => svc.getAbsolutePositionAndLineText(line + 1).lineText
      };
    }
    const lineMap = this.getLineMap();
    return getLineInfo(this.text, lineMap);
  }
};
function isDynamicFileName(fileName) {
  return fileName[0] === "^" || (fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) && getBaseFileName(fileName)[0] === "^" || fileName.includes(":^") && !fileName.includes(directorySeparator);
}
var ScriptInfo = class {
  constructor(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
    this.host = host;
    this.fileName = fileName;
    this.scriptKind = scriptKind;
    this.hasMixedContent = hasMixedContent;
    this.path = path;
    /**
     * All projects that include this file
     */
    this.containingProjects = [];
    this.isDynamic = isDynamicFileName(fileName);
    this.textStorage = new TextStorage(host, this, initialVersion);
    if (hasMixedContent || this.isDynamic) {
      this.realpath = this.path;
    }
    this.scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName);
  }
  /** @internal */
  isDynamicOrHasMixedContent() {
    return this.hasMixedContent || this.isDynamic;
  }
  isScriptOpen() {
    return this.textStorage.isOpen;
  }
  open(newText) {
    this.textStorage.isOpen = true;
    if (newText !== void 0 && this.textStorage.reload(newText)) {
      this.markContainingProjectsAsDirty();
    }
  }
  close(fileExists = true) {
    this.textStorage.isOpen = false;
    if (fileExists && this.textStorage.scheduleReloadIfNeeded()) {
      this.markContainingProjectsAsDirty();
    }
  }
  getSnapshot() {
    return this.textStorage.getSnapshot();
  }
  ensureRealPath() {
    if (this.realpath === void 0) {
      this.realpath = this.path;
      if (this.host.realpath) {
        Debug.assert(!!this.containingProjects.length);
        const project = this.containingProjects[0];
        const realpath = this.host.realpath(this.path);
        if (realpath) {
          this.realpath = project.toPath(realpath);
          if (this.realpath !== this.path) {
            project.projectService.realpathToScriptInfos.add(this.realpath, this);
          }
        }
      }
    }
  }
  /** @internal */
  getRealpathIfDifferent() {
    return this.realpath && this.realpath !== this.path ? this.realpath : void 0;
  }
  /**
   * @internal
   * Does not compute realpath; uses precomputed result. Use `ensureRealPath`
   * first if a definite result is needed.
   */
  isSymlink() {
    return this.realpath && this.realpath !== this.path;
  }
  getFormatCodeSettings() {
    return this.formatSettings;
  }
  getPreferences() {
    return this.preferences;
  }
  attachToProject(project) {
    const isNew = !this.isAttached(project);
    if (isNew) {
      this.containingProjects.push(project);
      if (!project.getCompilerOptions().preserveSymlinks) {
        this.ensureRealPath();
      }
      project.onFileAddedOrRemoved(this.isSymlink());
    }
    return isNew;
  }
  isAttached(project) {
    switch (this.containingProjects.length) {
      case 0:
        return false;
      case 1:
        return this.containingProjects[0] === project;
      case 2:
        return this.containingProjects[0] === project || this.containingProjects[1] === project;
      default:
        return contains(this.containingProjects, project);
    }
  }
  detachFromProject(project) {
    switch (this.containingProjects.length) {
      case 0:
        return;
      case 1:
        if (this.containingProjects[0] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects.pop();
        }
        break;
      case 2:
        if (this.containingProjects[0] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects[0] = this.containingProjects.pop();
        } else if (this.containingProjects[1] === project) {
          project.onFileAddedOrRemoved(this.isSymlink());
          this.containingProjects.pop();
        }
        break;
      default:
        if (orderedRemoveItem(this.containingProjects, project)) {
          project.onFileAddedOrRemoved(this.isSymlink());
        }
        break;
    }
  }
  detachAllProjects() {
    for (const p of this.containingProjects) {
      if (isConfiguredProject(p)) {
        p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, 2 /* Deleted */);
      }
      const existingRoot = p.getRootFilesMap().get(this.path);
      p.removeFile(
        this,
        /*fileExists*/
        false,
        /*detachFromProject*/
        false
      );
      p.onFileAddedOrRemoved(this.isSymlink());
      if (existingRoot && !isInferredProject(p)) {
        p.addMissingFileRoot(existingRoot.fileName);
      }
    }
    clear(this.containingProjects);
  }
  getDefaultProject() {
    switch (this.containingProjects.length) {
      case 0:
        return Errors.ThrowNoProject();
      case 1:
        return isProjectDeferredClose(this.containingProjects[0]) || isBackgroundProject(this.containingProjects[0]) ? Errors.ThrowNoProject() : this.containingProjects[0];
      default:
        let firstConfiguredProject;
        let firstInferredProject;
        let firstNonSourceOfProjectReferenceRedirect;
        let defaultConfiguredProject;
        for (let index = 0; index < this.containingProjects.length; index++) {
          const project = this.containingProjects[index];
          if (isConfiguredProject(project)) {
            if (project.deferredClose) continue;
            if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) {
              if (defaultConfiguredProject === void 0 && index !== this.containingProjects.length - 1) {
                defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false;
              }
              if (defaultConfiguredProject === project) return project;
              if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project;
            }
            if (!firstConfiguredProject) firstConfiguredProject = project;
          } else if (isExternalProject(project)) {
            return project;
          } else if (!firstInferredProject && isInferredProject(project)) {
            firstInferredProject = project;
          }
        }
        return (defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstInferredProject) ?? Errors.ThrowNoProject();
    }
  }
  registerFileUpdate() {
    for (const p of this.containingProjects) {
      p.registerFileUpdate(this.path);
    }
  }
  setOptions(formatSettings, preferences) {
    if (formatSettings) {
      if (!this.formatSettings) {
        this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine);
        assign(this.formatSettings, formatSettings);
      } else {
        this.formatSettings = { ...this.formatSettings, ...formatSettings };
      }
    }
    if (preferences) {
      if (!this.preferences) {
        this.preferences = emptyOptions;
      }
      this.preferences = { ...this.preferences, ...preferences };
    }
  }
  getLatestVersion() {
    this.textStorage.getSnapshot();
    return this.textStorage.getVersion();
  }
  saveTo(fileName) {
    this.host.writeFile(fileName, getSnapshotText(this.textStorage.getSnapshot()));
  }
  /** @internal */
  delayReloadNonMixedContentFile() {
    Debug.assert(!this.isDynamicOrHasMixedContent());
    this.textStorage.delayReloadFromFileIntoText();
    this.markContainingProjectsAsDirty();
  }
  reloadFromFile(tempFileName) {
    if (this.textStorage.reloadWithFileText(tempFileName)) {
      this.markContainingProjectsAsDirty();
      return true;
    }
    return false;
  }
  editContent(start, end, newText) {
    this.textStorage.edit(start, end, newText);
    this.markContainingProjectsAsDirty();
  }
  markContainingProjectsAsDirty() {
    for (const p of this.containingProjects) {
      p.markFileAsDirty(this.path);
    }
  }
  isOrphan() {
    return this.deferredDelete || !forEach(this.containingProjects, (p) => !p.isOrphan());
  }
  /**
   *  @param line 1 based index
   */
  lineToTextSpan(line) {
    return this.textStorage.lineToTextSpan(line);
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  lineOffsetToPosition(line, offset, allowEdits) {
    return this.textStorage.lineOffsetToPosition(line, offset, allowEdits);
  }
  positionToLineOffset(position) {
    failIfInvalidPosition(position);
    const location = this.textStorage.positionToLineOffset(position);
    failIfInvalidLocation(location);
    return location;
  }
  isJavaScript() {
    return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */;
  }
  /** @internal */
  closeSourceMapFileWatcher() {
    if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) {
      closeFileWatcherOf(this.sourceMapFilePath);
      this.sourceMapFilePath = void 0;
    }
  }
};
function failIfInvalidPosition(position) {
  Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`);
  Debug.assert(position >= 0, `Expected position to be non-negative.`);
}
function failIfInvalidLocation(location) {
  Debug.assert(typeof location.line === "number", `Expected line ${location.line} to be a number.`);
  Debug.assert(typeof location.offset === "number", `Expected offset ${location.offset} to be a number.`);
  Debug.assert(location.line > 0, `Expected line to be non-${location.line === 0 ? "zero" : "negative"}`);
  Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`);
}
function scriptInfoIsContainedByBackgroundProject(info) {
  return some(
    info.containingProjects,
    isBackgroundProject
  );
}
function scriptInfoIsContainedByDeferredClosedProject(info) {
  return some(
    info.containingProjects,
    isProjectDeferredClose
  );
}

// src/server/project.ts
var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => {
  ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred";
  ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured";
  ProjectKind2[ProjectKind2["External"] = 2] = "External";
  ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider";
  ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary";
  return ProjectKind2;
})(ProjectKind || {});
function countEachFileTypes(infos, includeSizes = false) {
  const result = {
    js: 0,
    jsSize: 0,
    jsx: 0,
    jsxSize: 0,
    ts: 0,
    tsSize: 0,
    tsx: 0,
    tsxSize: 0,
    dts: 0,
    dtsSize: 0,
    deferred: 0,
    deferredSize: 0
  };
  for (const info of infos) {
    const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0;
    switch (info.scriptKind) {
      case 1 /* JS */:
        result.js += 1;
        result.jsSize += fileSize;
        break;
      case 2 /* JSX */:
        result.jsx += 1;
        result.jsxSize += fileSize;
        break;
      case 3 /* TS */:
        if (isDeclarationFileName(info.fileName)) {
          result.dts += 1;
          result.dtsSize += fileSize;
        } else {
          result.ts += 1;
          result.tsSize += fileSize;
        }
        break;
      case 4 /* TSX */:
        result.tsx += 1;
        result.tsxSize += fileSize;
        break;
      case 7 /* Deferred */:
        result.deferred += 1;
        result.deferredSize += fileSize;
        break;
    }
  }
  return result;
}
function hasOneOrMoreJsAndNoTsFiles(project) {
  const counts2 = countEachFileTypes(project.getScriptInfos());
  return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0;
}
function allRootFilesAreJsOrDts(project) {
  const counts2 = countEachFileTypes(project.getRootScriptInfos());
  return counts2.ts === 0 && counts2.tsx === 0;
}
function allFilesAreJsOrDts(project) {
  const counts2 = countEachFileTypes(project.getScriptInfos());
  return counts2.ts === 0 && counts2.tsx === 0;
}
function hasNoTypeScriptSource(fileNames) {
  return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */));
}
function isGeneratedFileWatcher(watch) {
  return watch.generatedFilePath !== void 0;
}
function setIsEqualTo(arr1, arr2) {
  if (arr1 === arr2) {
    return true;
  }
  if ((arr1 || emptyArray2).length === 0 && (arr2 || emptyArray2).length === 0) {
    return true;
  }
  const set = /* @__PURE__ */ new Map();
  let unique = 0;
  for (const v of arr1) {
    if (set.get(v) !== true) {
      set.set(v, true);
      unique++;
    }
  }
  for (const v of arr2) {
    const isSet = set.get(v);
    if (isSet === void 0) {
      return false;
    }
    if (isSet === true) {
      set.set(v, false);
      unique--;
    }
  }
  return unique === 0;
}
function typeAcquisitionChanged(opt1, opt2) {
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
}
function compilerOptionsChanged(opt1, opt2) {
  return getAllowJSCompilerOption(opt1) !== getAllowJSCompilerOption(opt2);
}
function unresolvedImportsChanged(imports1, imports2) {
  if (imports1 === imports2) {
    return false;
  }
  return !arrayIsEqualTo(imports1, imports2);
}
var Project2 = class _Project {
  /** @internal */
  constructor(projectName, projectKind, projectService, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) {
    this.projectKind = projectKind;
    this.projectService = projectService;
    this.compilerOptions = compilerOptions;
    this.compileOnSaveEnabled = compileOnSaveEnabled;
    this.watchOptions = watchOptions;
    this.rootFilesMap = /* @__PURE__ */ new Map();
    /** @internal */
    this.plugins = [];
    /**
     * This is map from files to unresolved imports in it
     * Maop does not contain entries for files that do not have unresolved imports
     * This helps in containing the set of files to invalidate
     *
     * @internal
     */
    this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map();
    this.hasAddedorRemovedFiles = false;
    this.hasAddedOrRemovedSymlinks = false;
    /**
     * Last version that was reported.
     */
    this.lastReportedVersion = 0;
    /**
     * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one)
     * This property is changed in 'updateGraph' based on the set of files in program
     * @internal
     */
    this.projectProgramVersion = 0;
    /**
     * Current version of the project state. It is changed when:
     * - new root file was added/removed
     * - edit happen in some file that is currently included in the project.
     * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project
     * @internal
     */
    this.projectStateVersion = 0;
    /** @internal */
    this.initialLoadPending = false;
    /** @internal */
    this.dirty = false;
    /** @internal */
    this.typingFiles = emptyArray2;
    this.moduleSpecifierCache = createModuleSpecifierCache(this);
    /** @internal */
    this.createHash = maybeBind(this.projectService.host, this.projectService.host.createHash);
    /** @internal */
    this.globalCacheResolutionModuleName = ts_JsTyping_exports.nonRelativeModuleNameForTypingCache;
    /** @internal */
    this.updateFromProjectInProgress = false;
    projectService.logger.info(`Creating ${ProjectKind[projectKind]}Project: ${projectName}, currentDirectory: ${currentDirectory}`);
    this.projectName = projectName;
    this.directoryStructureHost = directoryStructureHost;
    this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory);
    this.getCanonicalFileName = this.projectService.toCanonicalFileName;
    this.jsDocParsingMode = this.projectService.jsDocParsingMode;
    this.cancellationToken = new ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds);
    if (!this.compilerOptions) {
      this.compilerOptions = getDefaultCompilerOptions2();
      this.compilerOptions.allowNonTsExtensions = true;
      this.compilerOptions.allowJs = true;
    } else if (hasExplicitListOfFiles || getAllowJSCompilerOption(this.compilerOptions) || this.projectService.hasDeferredExtension()) {
      this.compilerOptions.allowNonTsExtensions = true;
    }
    switch (projectService.serverMode) {
      case 0 /* Semantic */:
        this.languageServiceEnabled = true;
        break;
      case 1 /* PartialSemantic */:
        this.languageServiceEnabled = true;
        this.compilerOptions.noResolve = true;
        this.compilerOptions.types = [];
        break;
      case 2 /* Syntactic */:
        this.languageServiceEnabled = false;
        this.compilerOptions.noResolve = true;
        this.compilerOptions.types = [];
        break;
      default:
        Debug.assertNever(projectService.serverMode);
    }
    this.setInternalCompilerOptionsForEmittingJsFiles();
    const host = this.projectService.host;
    if (this.projectService.logger.loggingEnabled()) {
      this.trace = (s) => this.writeLog(s);
    } else if (host.trace) {
      this.trace = (s) => host.trace(s);
    }
    this.realpath = maybeBind(host, host.realpath);
    this.preferNonRecursiveWatch = this.projectService.canUseWatchEvents || host.preferNonRecursiveWatch;
    this.resolutionCache = createResolutionCache(
      this,
      this.currentDirectory,
      /*logChangesWhenResolvingModule*/
      true
    );
    this.languageService = createLanguageService(
      this,
      this.projectService.documentRegistry,
      this.projectService.serverMode
    );
    if (lastFileExceededProgramSize) {
      this.disableLanguageService(lastFileExceededProgramSize);
    }
    this.markAsDirty();
    if (!isBackgroundProject(this)) {
      this.projectService.pendingEnsureProjectForOpenFiles = true;
    }
    this.projectService.onProjectCreation(this);
  }
  /** @internal */
  getResolvedProjectReferenceToRedirect(_fileName) {
    return void 0;
  }
  isNonTsProject() {
    updateProjectIfDirty(this);
    return allFilesAreJsOrDts(this);
  }
  isJsOnlyProject() {
    updateProjectIfDirty(this);
    return hasOneOrMoreJsAndNoTsFiles(this);
  }
  static resolveModule(moduleName, initialDir, host, log) {
    return _Project.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule;
  }
  /** @internal */
  static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) {
    Debug.assertIsDefined(host.require);
    let errorLogs;
    let resolvedModule;
    for (const initialDir of searchPaths) {
      const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules")));
      log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`);
      const result = host.require(resolvedPath, pluginConfigEntry.name);
      if (!result.error) {
        resolvedModule = result.module;
        break;
      }
      const err = result.error.stack || result.error.message || JSON.stringify(result.error);
      (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
    }
    return { pluginConfigEntry, resolvedModule, errorLogs };
  }
  /** @internal */
  static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) {
    Debug.assertIsDefined(host.importPlugin);
    let errorLogs;
    let resolvedModule;
    for (const initialDir of searchPaths) {
      const resolvedPath = combinePaths(initialDir, "node_modules");
      log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`);
      let result;
      try {
        result = await host.importPlugin(resolvedPath, pluginConfigEntry.name);
      } catch (e) {
        result = { module: void 0, error: e };
      }
      if (!result.error) {
        resolvedModule = result.module;
        break;
      }
      const err = result.error.stack || result.error.message || JSON.stringify(result.error);
      (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`);
    }
    return { pluginConfigEntry, resolvedModule, errorLogs };
  }
  isKnownTypesPackageName(name) {
    return this.projectService.typingsInstaller.isKnownTypesPackageName(name);
  }
  installPackage(options) {
    return this.projectService.typingsInstaller.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) });
  }
  /** @internal */
  getGlobalTypingsCacheLocation() {
    return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : void 0;
  }
  /** @internal */
  getSymlinkCache() {
    if (!this.symlinks) {
      this.symlinks = createSymlinkCache(this.getCurrentDirectory(), this.getCanonicalFileName);
    }
    if (this.program && !this.symlinks.hasProcessedResolutions()) {
      this.symlinks.setSymlinksFromResolutions(
        this.program.forEachResolvedModule,
        this.program.forEachResolvedTypeReferenceDirective,
        this.program.getAutomaticTypeDirectiveResolutions()
      );
    }
    return this.symlinks;
  }
  // Method of LanguageServiceHost
  getCompilationSettings() {
    return this.compilerOptions;
  }
  // Method to support public API
  getCompilerOptions() {
    return this.getCompilationSettings();
  }
  getNewLine() {
    return this.projectService.host.newLine;
  }
  getProjectVersion() {
    return this.projectStateVersion.toString();
  }
  getProjectReferences() {
    return void 0;
  }
  getScriptFileNames() {
    if (!this.rootFilesMap.size) {
      return emptyArray;
    }
    let result;
    this.rootFilesMap.forEach((value) => {
      if (this.languageServiceEnabled || value.info && value.info.isScriptOpen()) {
        (result || (result = [])).push(value.fileName);
      }
    });
    return addRange(result, this.typingFiles) || emptyArray;
  }
  getOrCreateScriptInfoAndAttachToProject(fileName) {
    const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(
      fileName,
      this.currentDirectory,
      this.directoryStructureHost,
      /*deferredDeleteOk*/
      false
    );
    if (scriptInfo) {
      const existingValue = this.rootFilesMap.get(scriptInfo.path);
      if (existingValue && existingValue.info !== scriptInfo) {
        existingValue.info = scriptInfo;
      }
      scriptInfo.attachToProject(this);
    }
    return scriptInfo;
  }
  getScriptKind(fileName) {
    const info = this.projectService.getScriptInfoForPath(this.toPath(fileName));
    return info && info.scriptKind;
  }
  getScriptVersion(filename) {
    const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(
      filename,
      this.currentDirectory,
      this.directoryStructureHost,
      /*deferredDeleteOk*/
      false
    );
    return info && info.getLatestVersion();
  }
  getScriptSnapshot(filename) {
    const scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename);
    if (scriptInfo) {
      return scriptInfo.getSnapshot();
    }
  }
  getCancellationToken() {
    return this.cancellationToken;
  }
  getCurrentDirectory() {
    return this.currentDirectory;
  }
  getDefaultLibFileName() {
    const nodeModuleBinDir = getDirectoryPath(normalizePath(this.projectService.getExecutingFilePath()));
    return combinePaths(nodeModuleBinDir, getDefaultLibFileName(this.compilerOptions));
  }
  useCaseSensitiveFileNames() {
    return this.projectService.host.useCaseSensitiveFileNames;
  }
  readDirectory(path, extensions, exclude, include, depth) {
    return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth);
  }
  readFile(fileName) {
    return this.projectService.host.readFile(fileName);
  }
  writeFile(fileName, content) {
    return this.projectService.host.writeFile(fileName, content);
  }
  fileExists(file) {
    const path = this.toPath(file);
    return !!this.projectService.getScriptInfoForPath(path) || !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file);
  }
  /** @internal */
  resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    return this.resolutionCache.resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames);
  }
  /** @internal */
  getModuleResolutionCache() {
    return this.resolutionCache.getModuleResolutionCache();
  }
  /** @internal */
  resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) {
    return this.resolutionCache.resolveTypeReferenceDirectiveReferences(
      typeDirectiveReferences,
      containingFile,
      redirectedReference,
      options,
      containingSourceFile,
      reusedNames
    );
  }
  /** @internal */
  resolveLibrary(libraryName, resolveFrom, options, libFileName) {
    return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName);
  }
  directoryExists(path) {
    return this.directoryStructureHost.directoryExists(path);
  }
  getDirectories(path) {
    return this.directoryStructureHost.getDirectories(path);
  }
  /** @internal */
  getCachedDirectoryStructureHost() {
    return void 0;
  }
  /** @internal */
  toPath(fileName) {
    return toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName);
  }
  /** @internal */
  watchDirectoryOfFailedLookupLocation(directory, cb, flags) {
    return this.projectService.watchFactory.watchDirectory(
      directory,
      cb,
      flags,
      this.projectService.getWatchOptions(this),
      WatchType.FailedLookupLocations,
      this
    );
  }
  /** @internal */
  watchAffectingFileLocation(file, cb) {
    return this.projectService.watchFactory.watchFile(
      file,
      cb,
      2e3 /* High */,
      this.projectService.getWatchOptions(this),
      WatchType.AffectingFileLocation,
      this
    );
  }
  /** @internal */
  clearInvalidateResolutionOfFailedLookupTimer() {
    return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`);
  }
  /** @internal */
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    this.projectService.throttledOperations.schedule(
      `${this.getProjectName()}FailedLookupInvalidation`,
      /*delay*/
      1e3,
      () => {
        if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        }
      }
    );
  }
  /** @internal */
  invalidateResolutionsOfFailedLookupLocations() {
    if (this.clearInvalidateResolutionOfFailedLookupTimer() && this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
      this.markAsDirty();
      this.projectService.delayEnsureProjectForOpenFiles();
    }
  }
  /** @internal */
  onInvalidatedResolution() {
    this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
  }
  /** @internal */
  watchTypeRootsDirectory(directory, cb, flags) {
    return this.projectService.watchFactory.watchDirectory(
      directory,
      cb,
      flags,
      this.projectService.getWatchOptions(this),
      WatchType.TypeRoots,
      this
    );
  }
  /** @internal */
  hasChangedAutomaticTypeDirectiveNames() {
    return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames();
  }
  /** @internal */
  onChangedAutomaticTypeDirectiveNames() {
    this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
  }
  /** @internal */
  fileIsOpen(filePath) {
    return this.projectService.openFiles.has(filePath);
  }
  /** @internal */
  writeLog(s) {
    this.projectService.logger.info(s);
  }
  log(s) {
    this.writeLog(s);
  }
  error(s) {
    this.projectService.logger.msg(s, "Err" /* Err */);
  }
  setInternalCompilerOptionsForEmittingJsFiles() {
    if (this.projectKind === 0 /* Inferred */ || this.projectKind === 2 /* External */) {
      this.compilerOptions.noEmitForJsFiles = true;
    }
  }
  /**
   * Get the errors that dont have any file name associated
   */
  getGlobalProjectErrors() {
    return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2;
  }
  /**
   * Get all the project errors
   */
  getAllProjectErrors() {
    return this.projectErrors || emptyArray2;
  }
  setProjectErrors(projectErrors) {
    this.projectErrors = projectErrors;
  }
  getLanguageService(ensureSynchronized = true) {
    if (ensureSynchronized) {
      updateProjectIfDirty(this);
    }
    return this.languageService;
  }
  /** @internal */
  getSourceMapper() {
    return this.getLanguageService().getSourceMapper();
  }
  /** @internal */
  clearSourceMapperCache() {
    this.languageService.clearSourceMapperCache();
  }
  /** @internal */
  getDocumentPositionMapper(generatedFileName, sourceFileName) {
    return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
  }
  /** @internal */
  getSourceFileLike(fileName) {
    return this.projectService.getSourceFileLike(fileName, this);
  }
  /** @internal */
  shouldEmitFile(scriptInfo) {
    return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent() && !this.program.isSourceOfProjectReferenceRedirect(scriptInfo.path);
  }
  getCompileOnSaveAffectedFileList(scriptInfo) {
    if (!this.languageServiceEnabled) {
      return [];
    }
    updateProjectIfDirty(this);
    this.builderState = BuilderState.create(
      this.program,
      this.builderState,
      /*disableUseFileVersionAsSignature*/
      true
    );
    return mapDefined(
      BuilderState.getFilesAffectedBy(
        this.builderState,
        this.program,
        scriptInfo.path,
        this.cancellationToken,
        this.projectService.host
      ),
      (sourceFile) => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0
    );
  }
  /**
   * Returns true if emit was conducted
   */
  emitFile(scriptInfo, writeFile2) {
    if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) {
      return { emitSkipped: true, diagnostics: emptyArray2 };
    }
    const { emitSkipped, diagnostics, outputFiles } = this.getLanguageService().getEmitOutput(scriptInfo.fileName);
    if (!emitSkipped) {
      for (const outputFile of outputFiles) {
        const outputFileAbsoluteFileName = getNormalizedAbsolutePath(outputFile.name, this.currentDirectory);
        writeFile2(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark);
      }
      if (this.builderState && getEmitDeclarations(this.compilerOptions)) {
        const dtsFiles = outputFiles.filter((f) => isDeclarationFileName(f.name));
        if (dtsFiles.length === 1) {
          const sourceFile = this.program.getSourceFile(scriptInfo.fileName);
          const signature = this.projectService.host.createHash ? this.projectService.host.createHash(dtsFiles[0].text) : generateDjb2Hash(dtsFiles[0].text);
          BuilderState.updateSignatureOfFile(this.builderState, signature, sourceFile.resolvedPath);
        }
      }
    }
    return { emitSkipped, diagnostics };
  }
  enableLanguageService() {
    if (this.languageServiceEnabled || this.projectService.serverMode === 2 /* Syntactic */) {
      return;
    }
    this.languageServiceEnabled = true;
    this.lastFileExceededProgramSize = void 0;
    this.projectService.onUpdateLanguageServiceStateForProject(
      this,
      /*languageServiceEnabled*/
      true
    );
  }
  /** @internal */
  cleanupProgram() {
    if (this.program) {
      for (const f of this.program.getSourceFiles()) {
        this.detachScriptInfoIfNotRoot(f.fileName);
      }
      this.program.forEachResolvedProjectReference((ref) => this.detachScriptInfoFromProject(ref.sourceFile.fileName));
      this.program = void 0;
    }
  }
  disableLanguageService(lastFileExceededProgramSize) {
    if (!this.languageServiceEnabled) {
      return;
    }
    Debug.assert(this.projectService.serverMode !== 2 /* Syntactic */);
    this.languageService.cleanupSemanticCache();
    this.languageServiceEnabled = false;
    this.cleanupProgram();
    this.lastFileExceededProgramSize = lastFileExceededProgramSize;
    this.builderState = void 0;
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.close();
    }
    this.autoImportProviderHost = void 0;
    this.resolutionCache.closeTypeRootsWatch();
    this.clearGeneratedFileWatch();
    this.projectService.verifyDocumentRegistry();
    this.projectService.onUpdateLanguageServiceStateForProject(
      this,
      /*languageServiceEnabled*/
      false
    );
  }
  getProjectName() {
    return this.projectName;
  }
  removeLocalTypingsFromTypeAcquisition(newTypeAcquisition) {
    if (!newTypeAcquisition.enable || !newTypeAcquisition.include) {
      return newTypeAcquisition;
    }
    return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) };
  }
  getExternalFiles(updateLevel) {
    return toSorted(flatMap(this.plugins, (plugin) => {
      if (typeof plugin.module.getExternalFiles !== "function") return;
      try {
        return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */);
      } catch (e) {
        this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`);
        if (e.stack) {
          this.projectService.logger.info(e.stack);
        }
      }
    }));
  }
  getSourceFile(path) {
    if (!this.program) {
      return void 0;
    }
    return this.program.getSourceFileByPath(path);
  }
  /** @internal */
  getSourceFileOrConfigFile(path) {
    const options = this.program.getCompilerOptions();
    return path === options.configFilePath ? options.configFile : this.getSourceFile(path);
  }
  close() {
    var _a;
    if (this.typingsCache) this.projectService.typingsInstaller.onProjectClosed(this);
    this.typingsCache = void 0;
    this.closeWatchingTypingLocations();
    this.cleanupProgram();
    forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile));
    this.rootFilesMap.forEach((root) => {
      var _a2;
      return (_a2 = root.info) == null ? void 0 : _a2.detachFromProject(this);
    });
    this.projectService.pendingEnsureProjectForOpenFiles = true;
    this.rootFilesMap = void 0;
    this.externalFiles = void 0;
    this.program = void 0;
    this.builderState = void 0;
    this.resolutionCache.clear();
    this.resolutionCache = void 0;
    this.cachedUnresolvedImportsPerFile = void 0;
    (_a = this.packageJsonWatches) == null ? void 0 : _a.forEach((watcher) => {
      watcher.projects.delete(this);
      watcher.close();
    });
    this.packageJsonWatches = void 0;
    this.moduleSpecifierCache.clear();
    this.moduleSpecifierCache = void 0;
    this.directoryStructureHost = void 0;
    this.exportMapCache = void 0;
    this.projectErrors = void 0;
    this.plugins.length = 0;
    if (this.missingFilesMap) {
      clearMap(this.missingFilesMap, closeFileWatcher);
      this.missingFilesMap = void 0;
    }
    this.clearGeneratedFileWatch();
    this.clearInvalidateResolutionOfFailedLookupTimer();
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.close();
    }
    this.autoImportProviderHost = void 0;
    if (this.noDtsResolutionProject) {
      this.noDtsResolutionProject.close();
    }
    this.noDtsResolutionProject = void 0;
    this.languageService.dispose();
    this.languageService = void 0;
  }
  detachScriptInfoIfNotRoot(uncheckedFilename) {
    const info = this.projectService.getScriptInfo(uncheckedFilename);
    if (info && !this.isRoot(info)) {
      info.detachFromProject(this);
    }
  }
  isClosed() {
    return this.rootFilesMap === void 0;
  }
  hasRoots() {
    var _a;
    return !!((_a = this.rootFilesMap) == null ? void 0 : _a.size);
  }
  /** @internal */
  isOrphan() {
    return false;
  }
  getRootFiles() {
    return this.rootFilesMap && arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => {
      var _a;
      return (_a = value.info) == null ? void 0 : _a.fileName;
    }));
  }
  /** @internal */
  getRootFilesMap() {
    return this.rootFilesMap;
  }
  getRootScriptInfos() {
    return arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => value.info));
  }
  getScriptInfos() {
    if (!this.languageServiceEnabled) {
      return this.getRootScriptInfos();
    }
    return map(this.program.getSourceFiles(), (sourceFile) => {
      const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath);
      Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`);
      return scriptInfo;
    });
  }
  getExcludedFiles() {
    return emptyArray2;
  }
  getFileNames(excludeFilesFromExternalLibraries, excludeConfigFiles) {
    if (!this.program) {
      return [];
    }
    if (!this.languageServiceEnabled) {
      let rootFiles = this.getRootFiles();
      if (this.compilerOptions) {
        const defaultLibrary = getDefaultLibFilePath(this.compilerOptions);
        if (defaultLibrary) {
          (rootFiles || (rootFiles = [])).push(asNormalizedPath(defaultLibrary));
        }
      }
      return rootFiles;
    }
    const result = [];
    for (const f of this.program.getSourceFiles()) {
      if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) {
        continue;
      }
      result.push(asNormalizedPath(f.fileName));
    }
    if (!excludeConfigFiles) {
      const configFile = this.program.getCompilerOptions().configFile;
      if (configFile) {
        result.push(asNormalizedPath(configFile.fileName));
        if (configFile.extendedSourceFiles) {
          for (const f of configFile.extendedSourceFiles) {
            result.push(asNormalizedPath(f));
          }
        }
      }
    }
    return result;
  }
  /** @internal */
  getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo) {
    return this.getFileNames().map((fileName) => ({
      fileName,
      isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName)
    }));
  }
  hasConfigFile(configFilePath) {
    if (this.program && this.languageServiceEnabled) {
      const configFile = this.program.getCompilerOptions().configFile;
      if (configFile) {
        if (configFilePath === asNormalizedPath(configFile.fileName)) {
          return true;
        }
        if (configFile.extendedSourceFiles) {
          for (const f of configFile.extendedSourceFiles) {
            if (configFilePath === asNormalizedPath(f)) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
  containsScriptInfo(info) {
    if (this.isRoot(info)) return true;
    if (!this.program) return false;
    const file = this.program.getSourceFileByPath(info.path);
    return !!file && file.resolvedPath === info.path;
  }
  containsFile(filename, requireOpen) {
    const info = this.projectService.getScriptInfoForNormalizedPath(filename);
    if (info && (info.isScriptOpen() || !requireOpen)) {
      return this.containsScriptInfo(info);
    }
    return false;
  }
  isRoot(info) {
    var _a, _b;
    return ((_b = (_a = this.rootFilesMap) == null ? void 0 : _a.get(info.path)) == null ? void 0 : _b.info) === info;
  }
  // add a root file to project
  addRoot(info, fileName) {
    Debug.assert(!this.isRoot(info));
    this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info });
    info.attachToProject(this);
    this.markAsDirty();
  }
  // add a root file that doesnt exist on host
  addMissingFileRoot(fileName) {
    const path = this.projectService.toPath(fileName);
    this.rootFilesMap.set(path, { fileName });
    this.markAsDirty();
  }
  removeFile(info, fileExists, detachFromProject) {
    if (this.isRoot(info)) {
      this.removeRoot(info);
    }
    if (fileExists) {
      this.resolutionCache.removeResolutionsOfFile(info.path);
    } else {
      this.resolutionCache.invalidateResolutionOfFile(info.path);
    }
    this.cachedUnresolvedImportsPerFile.delete(info.path);
    if (detachFromProject) {
      info.detachFromProject(this);
    }
    this.markAsDirty();
  }
  registerFileUpdate(fileName) {
    (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */ new Set())).add(fileName);
  }
  /** @internal */
  markFileAsDirty(changedFile) {
    this.markAsDirty();
    if (this.exportMapCache && !this.exportMapCache.isEmpty()) {
      (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */ new Set())).add(changedFile);
    }
  }
  /** @internal */
  markAsDirty() {
    if (!this.dirty) {
      this.projectStateVersion++;
      this.dirty = true;
    }
  }
  /** @internal */
  markAutoImportProviderAsDirty() {
    var _a;
    if (!this.autoImportProviderHost) this.autoImportProviderHost = void 0;
    (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty();
  }
  /** @internal */
  onAutoImportProviderSettingsChanged() {
    this.markAutoImportProviderAsDirty();
  }
  /** @internal */
  onPackageJsonChange() {
    this.moduleSpecifierCache.clear();
    this.markAutoImportProviderAsDirty();
  }
  /** @internal */
  onFileAddedOrRemoved(isSymlink) {
    this.hasAddedorRemovedFiles = true;
    if (isSymlink) {
      this.hasAddedOrRemovedSymlinks = true;
    }
  }
  /** @internal */
  onDiscoveredSymlink() {
    this.hasAddedOrRemovedSymlinks = true;
  }
  /** @internal */
  onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath) {
    if (!newSourceFileByResolvedPath || oldSourceFile.resolvedPath === oldSourceFile.path && newSourceFileByResolvedPath.resolvedPath !== oldSourceFile.path) {
      this.detachScriptInfoFromProject(oldSourceFile.fileName, hasSourceFileByPath);
    }
  }
  /** @internal */
  updateFromProject() {
    updateProjectIfDirty(this);
  }
  /**
   * Updates set of files that contribute to this project
   * @returns: true if set of files in the project stays the same and false - otherwise.
   */
  updateGraph() {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] });
    this.resolutionCache.startRecordingFilesWithChangedResolutions();
    const hasNewProgram = this.updateGraphWorker();
    const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles;
    this.hasAddedorRemovedFiles = false;
    this.hasAddedOrRemovedSymlinks = false;
    const changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray2;
    for (const file of changedFiles) {
      this.cachedUnresolvedImportsPerFile.delete(file);
    }
    if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */ && !this.isOrphan()) {
      if (hasNewProgram || changedFiles.length) {
        this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
      }
      this.enqueueInstallTypingsForProject(hasAddedorRemovedFiles);
    } else {
      this.lastCachedUnresolvedImportsList = void 0;
    }
    const isFirstProgramLoad = this.projectProgramVersion === 0 && hasNewProgram;
    if (hasNewProgram) {
      this.projectProgramVersion++;
    }
    if (hasAddedorRemovedFiles) {
      this.markAutoImportProviderAsDirty();
    }
    if (isFirstProgramLoad) {
      this.getPackageJsonAutoImportProvider();
    }
    (_b = tracing) == null ? void 0 : _b.pop();
    return !hasNewProgram;
  }
  /** @internal */
  enqueueInstallTypingsForProject(forceRefresh) {
    const typeAcquisition = this.getTypeAcquisition();
    if (!typeAcquisition || !typeAcquisition.enable || this.projectService.typingsInstaller === nullTypingsInstaller) {
      return;
    }
    const entry = this.typingsCache;
    if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(this.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(this.lastCachedUnresolvedImportsList, entry.unresolvedImports)) {
      this.typingsCache = {
        compilerOptions: this.getCompilationSettings(),
        typeAcquisition,
        unresolvedImports: this.lastCachedUnresolvedImportsList
      };
      this.projectService.typingsInstaller.enqueueInstallTypingsRequest(this, typeAcquisition, this.lastCachedUnresolvedImportsList);
    }
  }
  /** @internal */
  updateTypingFiles(compilerOptions, typeAcquisition, unresolvedImports, newTypings) {
    this.typingsCache = {
      compilerOptions,
      typeAcquisition,
      unresolvedImports
    };
    const typingFiles = !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : toSorted(newTypings);
    if (enumerateInsertsAndDeletes(
      typingFiles,
      this.typingFiles,
      getStringComparer(!this.useCaseSensitiveFileNames()),
      /*inserted*/
      noop,
      (removed) => this.detachScriptInfoFromProject(removed)
    )) {
      this.typingFiles = typingFiles;
      this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile);
      this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
    }
  }
  closeWatchingTypingLocations() {
    if (this.typingWatchers) clearMap(this.typingWatchers, closeFileWatcher);
    this.typingWatchers = void 0;
  }
  onTypingInstallerWatchInvoke() {
    this.typingWatchers.isInvoked = true;
    this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate });
  }
  /** @internal */
  watchTypingLocations(files) {
    if (!files) {
      this.typingWatchers.isInvoked = false;
      return;
    }
    if (!files.length) {
      this.closeWatchingTypingLocations();
      return;
    }
    const toRemove = new Map(this.typingWatchers);
    if (!this.typingWatchers) this.typingWatchers = /* @__PURE__ */ new Map();
    this.typingWatchers.isInvoked = false;
    const createProjectWatcher = (path, typingsWatcherType) => {
      const canonicalPath = this.toPath(path);
      toRemove.delete(canonicalPath);
      if (!this.typingWatchers.has(canonicalPath)) {
        const watchType = typingsWatcherType === "FileWatcher" /* FileWatcher */ ? WatchType.TypingInstallerLocationFile : WatchType.TypingInstallerLocationDirectory;
        this.typingWatchers.set(
          canonicalPath,
          canWatchDirectoryOrFilePath(canonicalPath) ? typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile(
            path,
            () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`),
            2e3 /* High */,
            this.projectService.getWatchOptions(this),
            watchType,
            this
          ) : this.projectService.watchFactory.watchDirectory(
            path,
            (f) => {
              if (this.typingWatchers.isInvoked) return this.writeLog(`TypingWatchers already invoked`);
              if (!fileExtensionIs(f, ".json" /* Json */)) return this.writeLog(`Ignoring files that are not *.json`);
              if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames())) return this.writeLog(`Ignoring package.json change at global typings location`);
              this.onTypingInstallerWatchInvoke();
            },
            1 /* Recursive */,
            this.projectService.getWatchOptions(this),
            watchType,
            this
          ) : (this.writeLog(`Skipping watcher creation at ${path}:: ${getDetailWatchInfo(watchType, this)}`), noopFileWatcher)
        );
      }
    };
    for (const file of files) {
      const basename = getBaseFileName(file);
      if (basename === "package.json" || basename === "bower.json") {
        createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
        continue;
      }
      if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) {
        const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1);
        if (subDirectory !== -1) {
          createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
        } else {
          createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
        }
        continue;
      }
      if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) {
        createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */);
        continue;
      }
      createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
    }
    toRemove.forEach((watch, path) => {
      watch.close();
      this.typingWatchers.delete(path);
    });
  }
  /** @internal */
  getCurrentProgram() {
    return this.program;
  }
  removeExistingTypings(include) {
    if (!include.length) return include;
    const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this);
    return filter(include, (i) => !existing.includes(i));
  }
  updateGraphWorker() {
    var _a, _b;
    const oldProgram = this.languageService.getCurrentProgram();
    Debug.assert(oldProgram === this.program);
    Debug.assert(!this.isClosed(), "Called update graph worker of closed project");
    this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`);
    const start = timestamp();
    const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse);
    this.hasInvalidatedResolutions = hasInvalidatedResolutions;
    this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions;
    this.resolutionCache.startCachingPerDirectoryResolution();
    this.dirty = false;
    this.updateFromProjectInProgress = true;
    this.program = this.languageService.getProgram();
    this.updateFromProjectInProgress = false;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "finishCachingPerDirectoryResolution");
    this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram);
    (_b = tracing) == null ? void 0 : _b.pop();
    Debug.assert(oldProgram === void 0 || this.program !== void 0);
    let hasNewProgram = false;
    if (this.program && (!oldProgram || this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */)) {
      hasNewProgram = true;
      this.rootFilesMap.forEach((value, path) => {
        var _a2;
        const file = this.program.getSourceFileByPath(path);
        const info = value.info;
        if (!file || ((_a2 = value.info) == null ? void 0 : _a2.path) === file.resolvedPath) return;
        value.info = this.projectService.getScriptInfo(file.fileName);
        Debug.assert(value.info.isAttached(this));
        info == null ? void 0 : info.detachFromProject(this);
      });
      updateMissingFilePathsWatch(
        this.program,
        this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()),
        // Watch the missing files
        (missingFilePath, missingFileName) => this.addMissingFileWatcher(missingFilePath, missingFileName)
      );
      if (this.generatedFilesMap) {
        const outPath = this.compilerOptions.outFile;
        if (isGeneratedFileWatcher(this.generatedFilesMap)) {
          if (!outPath || !this.isValidGeneratedFileWatcher(
            removeFileExtension(outPath) + ".d.ts" /* Dts */,
            this.generatedFilesMap
          )) {
            this.clearGeneratedFileWatch();
          }
        } else {
          if (outPath) {
            this.clearGeneratedFileWatch();
          } else {
            this.generatedFilesMap.forEach((watcher, source) => {
              const sourceFile = this.program.getSourceFileByPath(source);
              if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher(
                getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.program),
                watcher
              )) {
                closeFileWatcherOf(watcher);
                this.generatedFilesMap.delete(source);
              }
            });
          }
        }
      }
      if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) {
        this.resolutionCache.updateTypeRootsWatch();
      }
    }
    this.projectService.verifyProgram(this);
    if (this.exportMapCache && !this.exportMapCache.isEmpty()) {
      this.exportMapCache.releaseSymbols();
      if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) {
        this.exportMapCache.clear();
      } else if (this.changedFilesForExportMapCache && oldProgram && this.program) {
        forEachKey(this.changedFilesForExportMapCache, (fileName) => {
          const oldSourceFile = oldProgram.getSourceFileByPath(fileName);
          const sourceFile = this.program.getSourceFileByPath(fileName);
          if (!oldSourceFile || !sourceFile) {
            this.exportMapCache.clear();
            return true;
          }
          return this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!this.getTypeAcquisition().enable);
        });
      }
    }
    if (this.changedFilesForExportMapCache) {
      this.changedFilesForExportMapCache.clear();
    }
    if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) {
      this.symlinks = void 0;
      this.moduleSpecifierCache.clear();
    }
    const oldExternalFiles = this.externalFiles || emptyArray2;
    this.externalFiles = this.getExternalFiles();
    enumerateInsertsAndDeletes(
      this.externalFiles,
      oldExternalFiles,
      getStringComparer(!this.useCaseSensitiveFileNames()),
      // Ensure a ScriptInfo is created for new external files. This is performed indirectly
      // by the host for files in the program when the program is retrieved above but
      // the program doesn't contain external files so this must be done explicitly.
      (inserted) => {
        const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(
          inserted,
          this.currentDirectory,
          this.directoryStructureHost,
          /*deferredDeleteOk*/
          false
        );
        scriptInfo == null ? void 0 : scriptInfo.attachToProject(this);
      },
      (removed) => this.detachScriptInfoFromProject(removed)
    );
    const elapsed = timestamp() - start;
    this.sendPerformanceEvent("UpdateGraph", elapsed);
    this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} projectStateVersion: ${this.projectStateVersion} projectProgramVersion: ${this.projectProgramVersion} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`);
    if (this.projectService.logger.isTestLogger) {
      if (this.program !== oldProgram) {
        this.print(
          /*writeProjectFileNames*/
          true,
          this.hasAddedorRemovedFiles,
          /*writeFileVersionAndText*/
          true
        );
      } else {
        this.writeLog(`Same program as before`);
      }
    } else if (this.hasAddedorRemovedFiles) {
      this.print(
        /*writeProjectFileNames*/
        true,
        /*writeFileExplaination*/
        true,
        /*writeFileVersionAndText*/
        false
      );
    } else if (this.program !== oldProgram) {
      this.writeLog(`Different program with same set of files`);
    }
    this.projectService.verifyDocumentRegistry();
    return hasNewProgram;
  }
  /** @internal */
  sendPerformanceEvent(kind, durationMs) {
    this.projectService.sendPerformanceEvent(kind, durationMs);
  }
  detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution) {
    const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName);
    if (scriptInfoToDetach) {
      scriptInfoToDetach.detachFromProject(this);
      if (!noRemoveResolution) {
        this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path);
      }
    }
  }
  addMissingFileWatcher(missingFilePath, missingFileName) {
    var _a;
    if (isConfiguredProject(this)) {
      const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath);
      if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) return noopFileWatcher;
    }
    const fileWatcher = this.projectService.watchFactory.watchFile(
      getNormalizedAbsolutePath(missingFileName, this.currentDirectory),
      (fileName, eventKind) => {
        if (isConfiguredProject(this)) {
          this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind);
        }
        if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) {
          this.missingFilesMap.delete(missingFilePath);
          fileWatcher.close();
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        }
      },
      500 /* Medium */,
      this.projectService.getWatchOptions(this),
      WatchType.MissingFile,
      this
    );
    return fileWatcher;
  }
  isWatchedMissingFile(path) {
    return !!this.missingFilesMap && this.missingFilesMap.has(path);
  }
  /** @internal */
  addGeneratedFileWatch(generatedFile, sourceFile) {
    if (this.compilerOptions.outFile) {
      if (!this.generatedFilesMap) {
        this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile);
      }
    } else {
      const path = this.toPath(sourceFile);
      if (this.generatedFilesMap) {
        if (isGeneratedFileWatcher(this.generatedFilesMap)) {
          Debug.fail(`${this.projectName} Expected to not have --out watcher for generated file with options: ${JSON.stringify(this.compilerOptions)}`);
          return;
        }
        if (this.generatedFilesMap.has(path)) return;
      } else {
        this.generatedFilesMap = /* @__PURE__ */ new Map();
      }
      this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile));
    }
  }
  createGeneratedFileWatcher(generatedFile) {
    return {
      generatedFilePath: this.toPath(generatedFile),
      watcher: this.projectService.watchFactory.watchFile(
        generatedFile,
        () => {
          this.clearSourceMapperCache();
          this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
        },
        2e3 /* High */,
        this.projectService.getWatchOptions(this),
        WatchType.MissingGeneratedFile,
        this
      )
    };
  }
  isValidGeneratedFileWatcher(generateFile, watcher) {
    return this.toPath(generateFile) === watcher.generatedFilePath;
  }
  clearGeneratedFileWatch() {
    if (this.generatedFilesMap) {
      if (isGeneratedFileWatcher(this.generatedFilesMap)) {
        closeFileWatcherOf(this.generatedFilesMap);
      } else {
        clearMap(this.generatedFilesMap, closeFileWatcherOf);
      }
      this.generatedFilesMap = void 0;
    }
  }
  getScriptInfoForNormalizedPath(fileName) {
    const scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName));
    if (scriptInfo && !scriptInfo.isAttached(this)) {
      return Errors.ThrowProjectDoesNotContainDocument(fileName, this);
    }
    return scriptInfo;
  }
  getScriptInfo(uncheckedFileName) {
    return this.projectService.getScriptInfo(uncheckedFileName);
  }
  filesToString(writeProjectFileNames) {
    return this.filesToStringWorker(
      writeProjectFileNames,
      /*writeFileExplaination*/
      true,
      /*writeFileVersionAndText*/
      false
    );
  }
  filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) {
    if (this.initialLoadPending) return "	Files (0) InitialLoadPending\n";
    if (!this.program) return "	Files (0) NoProgram\n";
    const sourceFiles = this.program.getSourceFiles();
    let strBuilder = `	Files (${sourceFiles.length})
`;
    if (writeProjectFileNames) {
      for (const file of sourceFiles) {
        strBuilder += `	${file.fileName}${writeFileVersionAndText ? ` ${file.version} ${JSON.stringify(file.text)}` : ""}
`;
      }
      if (writeFileExplaination) {
        strBuilder += "\n\n";
        explainFiles(this.program, (s) => strBuilder += `	${s}
`);
      }
    }
    return strBuilder;
  }
  /** @internal */
  print(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) {
    var _a;
    this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`);
    this.writeLog(this.filesToStringWorker(
      writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */),
      writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */),
      writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */)
    ));
    this.writeLog("-----------------------------------------------");
    if (this.autoImportProviderHost) {
      this.autoImportProviderHost.print(
        /*writeProjectFileNames*/
        false,
        /*writeFileExplaination*/
        false,
        /*writeFileVersionAndText*/
        false
      );
    }
    (_a = this.noDtsResolutionProject) == null ? void 0 : _a.print(
      /*writeProjectFileNames*/
      false,
      /*writeFileExplaination*/
      false,
      /*writeFileVersionAndText*/
      false
    );
  }
  setCompilerOptions(compilerOptions) {
    var _a;
    if (compilerOptions) {
      compilerOptions.allowNonTsExtensions = true;
      const oldOptions = this.compilerOptions;
      this.compilerOptions = compilerOptions;
      this.setInternalCompilerOptionsForEmittingJsFiles();
      (_a = this.noDtsResolutionProject) == null ? void 0 : _a.setCompilerOptions(this.getCompilerOptionsForNoDtsResolutionProject());
      if (changesAffectModuleResolution(oldOptions, compilerOptions)) {
        this.cachedUnresolvedImportsPerFile.clear();
        this.lastCachedUnresolvedImportsList = void 0;
        this.resolutionCache.onChangesAffectModuleResolution();
        this.moduleSpecifierCache.clear();
      }
      this.markAsDirty();
    }
  }
  /** @internal */
  setWatchOptions(watchOptions) {
    this.watchOptions = watchOptions;
  }
  /** @internal */
  getWatchOptions() {
    return this.watchOptions;
  }
  setTypeAcquisition(newTypeAcquisition) {
    if (newTypeAcquisition) {
      this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition);
    }
  }
  getTypeAcquisition() {
    return this.typeAcquisition || {};
  }
  /** @internal */
  getChangesSinceVersion(lastKnownVersion, includeProjectReferenceRedirectInfo) {
    var _a, _b;
    const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? (files) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({
      fileName,
      isSourceOfProjectReferenceRedirect
    })) : (files) => arrayFrom(files.keys());
    if (!this.initialLoadPending) {
      updateProjectIfDirty(this);
    }
    const info = {
      projectName: this.getProjectName(),
      version: this.projectProgramVersion,
      isInferred: isInferredProject(this),
      options: this.getCompilationSettings(),
      languageServiceDisabled: !this.languageServiceEnabled,
      lastFileExceededProgramSize: this.lastFileExceededProgramSize
    };
    const updatedFileNames = this.updatedFileNames;
    this.updatedFileNames = void 0;
    if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
      if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) {
        return { info, projectErrors: this.getGlobalProjectErrors() };
      }
      const lastReportedFileNames = this.lastReportedFileNames;
      const externalFiles = ((_a = this.externalFiles) == null ? void 0 : _a.map((f) => ({
        fileName: toNormalizedPath(f),
        isSourceOfProjectReferenceRedirect: false
      }))) || emptyArray2;
      const currentFiles = arrayToMap(
        this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles),
        (info2) => info2.fileName,
        (info2) => info2.isSourceOfProjectReferenceRedirect
      );
      const added = /* @__PURE__ */ new Map();
      const removed = /* @__PURE__ */ new Map();
      const updated = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : [];
      const updatedRedirects = [];
      forEachEntry(currentFiles, (isSourceOfProjectReferenceRedirect, fileName) => {
        if (!lastReportedFileNames.has(fileName)) {
          added.set(fileName, isSourceOfProjectReferenceRedirect);
        } else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) {
          updatedRedirects.push({
            fileName,
            isSourceOfProjectReferenceRedirect
          });
        }
      });
      forEachEntry(lastReportedFileNames, (isSourceOfProjectReferenceRedirect, fileName) => {
        if (!currentFiles.has(fileName)) {
          removed.set(fileName, isSourceOfProjectReferenceRedirect);
        }
      });
      this.lastReportedFileNames = currentFiles;
      this.lastReportedVersion = this.projectProgramVersion;
      return {
        info,
        changes: {
          added: includeProjectReferenceRedirectInfoIfRequested(added),
          removed: includeProjectReferenceRedirectInfoIfRequested(removed),
          updated: includeProjectReferenceRedirectInfo ? updated.map((fileName) => ({
            fileName,
            isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName)
          })) : updated,
          updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : void 0
        },
        projectErrors: this.getGlobalProjectErrors()
      };
    } else {
      const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo);
      const externalFiles = ((_b = this.externalFiles) == null ? void 0 : _b.map((f) => ({
        fileName: toNormalizedPath(f),
        isSourceOfProjectReferenceRedirect: false
      }))) || emptyArray2;
      const allFiles = projectFileNames.concat(externalFiles);
      this.lastReportedFileNames = arrayToMap(
        allFiles,
        (info2) => info2.fileName,
        (info2) => info2.isSourceOfProjectReferenceRedirect
      );
      this.lastReportedVersion = this.projectProgramVersion;
      return {
        info,
        files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map((f) => f.fileName),
        projectErrors: this.getGlobalProjectErrors()
      };
    }
  }
  // remove a root file from project
  removeRoot(info) {
    this.rootFilesMap.delete(info.path);
  }
  /** @internal */
  isSourceOfProjectReferenceRedirect(fileName) {
    return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName);
  }
  /** @internal */
  getGlobalPluginSearchPaths() {
    return [
      ...this.projectService.pluginProbeLocations,
      // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
      combinePaths(this.projectService.getExecutingFilePath(), "../../..")
    ];
  }
  enableGlobalPlugins(options) {
    if (!this.projectService.globalPlugins.length) return;
    const host = this.projectService.host;
    if (!host.require && !host.importPlugin) {
      this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    const searchPaths = this.getGlobalPluginSearchPaths();
    for (const globalPluginName of this.projectService.globalPlugins) {
      if (!globalPluginName) continue;
      if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) continue;
      this.projectService.logger.info(`Loading global plugin ${globalPluginName}`);
      this.enablePlugin({ name: globalPluginName, global: true }, searchPaths);
    }
  }
  enablePlugin(pluginConfigEntry, searchPaths) {
    this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths);
  }
  /** @internal */
  enableProxy(pluginModuleFactory, configEntry) {
    try {
      if (typeof pluginModuleFactory !== "function") {
        this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did not expose a proper factory function`);
        return;
      }
      const info = {
        config: configEntry,
        project: this,
        languageService: this.languageService,
        languageServiceHost: this,
        serverHost: this.projectService.host,
        session: this.projectService.session
      };
      const pluginModule = pluginModuleFactory({ typescript: ts_exports2 });
      const newLS = pluginModule.create(info);
      for (const k of Object.keys(this.languageService)) {
        if (!(k in newLS)) {
          this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`);
          newLS[k] = this.languageService[k];
        }
      }
      this.projectService.logger.info(`Plugin validation succeeded`);
      this.languageService = newLS;
      this.plugins.push({ name: configEntry.name, module: pluginModule });
    } catch (e) {
      this.projectService.logger.info(`Plugin activation failed: ${e}`);
    }
  }
  /** @internal */
  onPluginConfigurationChanged(pluginName, configuration) {
    this.plugins.filter((plugin) => plugin.name === pluginName).forEach((plugin) => {
      if (plugin.module.onConfigurationChanged) {
        plugin.module.onConfigurationChanged(configuration);
      }
    });
  }
  /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
  refreshDiagnostics() {
    this.projectService.sendProjectsUpdatedInBackgroundEvent();
  }
  /** @internal */
  getPackageJsonsVisibleToFile(fileName, rootDir) {
    if (this.projectService.serverMode !== 0 /* Semantic */) return emptyArray2;
    return this.projectService.getPackageJsonsVisibleToFile(fileName, this, rootDir);
  }
  /** @internal */
  getNearestAncestorDirectoryWithPackageJson(fileName) {
    return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName, this);
  }
  /** @internal */
  getPackageJsonsForAutoImport(rootDir) {
    return this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir);
  }
  /** @internal */
  getPackageJsonCache() {
    return this.projectService.packageJsonCache;
  }
  /** @internal */
  getCachedExportInfoMap() {
    return this.exportMapCache || (this.exportMapCache = createCacheableExportInfoMap(this));
  }
  /** @internal */
  clearCachedExportInfoMap() {
    var _a;
    (_a = this.exportMapCache) == null ? void 0 : _a.clear();
  }
  /** @internal */
  getModuleSpecifierCache() {
    return this.moduleSpecifierCache;
  }
  /** @internal */
  includePackageJsonAutoImports() {
    if (this.projectService.includePackageJsonAutoImports() === 0 /* Off */ || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || !this.isDefaultProjectForOpenFiles()) {
      return 0 /* Off */;
    }
    return this.projectService.includePackageJsonAutoImports();
  }
  /** @internal */
  getHostForAutoImportProvider() {
    var _a, _b;
    if (this.program) {
      return {
        fileExists: this.program.fileExists,
        directoryExists: this.program.directoryExists,
        realpath: this.program.realpath || ((_a = this.projectService.host.realpath) == null ? void 0 : _a.bind(this.projectService.host)),
        getCurrentDirectory: this.getCurrentDirectory.bind(this),
        readFile: this.projectService.host.readFile.bind(this.projectService.host),
        getDirectories: this.projectService.host.getDirectories.bind(this.projectService.host),
        trace: (_b = this.projectService.host.trace) == null ? void 0 : _b.bind(this.projectService.host),
        useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames(),
        readDirectory: this.projectService.host.readDirectory.bind(this.projectService.host)
      };
    }
    return this.projectService.host;
  }
  /** @internal */
  getPackageJsonAutoImportProvider() {
    var _a, _b, _c;
    if (this.autoImportProviderHost === false) {
      return void 0;
    }
    if (this.projectService.serverMode !== 0 /* Semantic */) {
      this.autoImportProviderHost = false;
      return void 0;
    }
    if (this.autoImportProviderHost) {
      updateProjectIfDirty(this.autoImportProviderHost);
      if (this.autoImportProviderHost.isEmpty()) {
        this.autoImportProviderHost.close();
        this.autoImportProviderHost = void 0;
        return void 0;
      }
      return this.autoImportProviderHost.getCurrentProgram();
    }
    const dependencySelection = this.includePackageJsonAutoImports();
    if (dependencySelection) {
      (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider");
      const start = timestamp();
      this.autoImportProviderHost = AutoImportProviderProject.create(
        dependencySelection,
        this,
        this.getHostForAutoImportProvider()
      ) ?? false;
      if (this.autoImportProviderHost) {
        updateProjectIfDirty(this.autoImportProviderHost);
        this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start);
        (_b = tracing) == null ? void 0 : _b.pop();
        return this.autoImportProviderHost.getCurrentProgram();
      }
      (_c = tracing) == null ? void 0 : _c.pop();
    }
  }
  isDefaultProjectForOpenFiles() {
    return !!forEachEntry(
      this.projectService.openFiles,
      (_projectRootPath, path) => this.projectService.tryGetDefaultProjectForFile(this.projectService.getScriptInfoForPath(path)) === this
    );
  }
  /** @internal */
  watchNodeModulesForPackageJsonChanges(directoryPath) {
    return this.projectService.watchPackageJsonsInNodeModules(directoryPath, this);
  }
  /** @internal */
  getIncompleteCompletionsCache() {
    return this.projectService.getIncompleteCompletionsCache();
  }
  /** @internal */
  getNoDtsResolutionProject(rootFile) {
    Debug.assert(this.projectService.serverMode === 0 /* Semantic */);
    this.noDtsResolutionProject ?? (this.noDtsResolutionProject = new AuxiliaryProject(this));
    if (this.noDtsResolutionProject.rootFile !== rootFile) {
      this.projectService.setFileNamesOfAutoImportProviderOrAuxillaryProject(
        this.noDtsResolutionProject,
        [rootFile]
      );
      this.noDtsResolutionProject.rootFile = rootFile;
    }
    return this.noDtsResolutionProject;
  }
  /** @internal */
  runWithTemporaryFileUpdate(rootFile, updatedText, cb) {
    var _a, _b, _c, _d;
    const originalProgram = this.program;
    const rootSourceFile = Debug.checkDefined((_a = this.program) == null ? void 0 : _a.getSourceFile(rootFile), "Expected file to be part of program");
    const originalText = Debug.checkDefined(rootSourceFile.getFullText());
    (_b = this.getScriptInfo(rootFile)) == null ? void 0 : _b.editContent(0, originalText.length, updatedText);
    this.updateGraph();
    try {
      cb(this.program, originalProgram, (_c = this.program) == null ? void 0 : _c.getSourceFile(rootFile));
    } finally {
      (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, updatedText.length, originalText);
    }
  }
  /** @internal */
  getCompilerOptionsForNoDtsResolutionProject() {
    return {
      ...this.getCompilerOptions(),
      noDtsResolution: true,
      allowJs: true,
      maxNodeModuleJsDepth: 3,
      diagnostics: false,
      skipLibCheck: true,
      sourceMap: false,
      types: emptyArray,
      lib: emptyArray,
      noLib: true
    };
  }
};
function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) {
  var _a, _b;
  const sourceFiles = program.getSourceFiles();
  (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length });
  const ambientModules = program.getTypeChecker().getAmbientModules().map((mod) => stripQuotes(mod.getName()));
  const result = sortAndDeduplicate(flatMap(sourceFiles, (sourceFile) => extractUnresolvedImportsFromSourceFile(
    program,
    sourceFile,
    ambientModules,
    cachedUnresolvedImportsPerFile
  )));
  (_b = tracing) == null ? void 0 : _b.pop();
  return result;
}
function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, cachedUnresolvedImportsPerFile) {
  return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => {
    let unresolvedImports;
    program.forEachResolvedModule(({ resolvedModule }, name) => {
      if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some((m) => m === name)) {
        unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName);
      }
    }, file);
    return unresolvedImports || emptyArray2;
  });
}
var InferredProject2 = class extends Project2 {
  /** @internal */
  constructor(projectService, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) {
    super(
      projectService.newInferredProjectName(),
      0 /* Inferred */,
      projectService,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      compilerOptions,
      /*compileOnSaveEnabled*/
      false,
      watchOptions,
      projectService.host,
      currentDirectory
    );
    this._isJsInferredProject = false;
    this.typeAcquisition = typeAcquisition;
    this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath);
    if (!projectRootPath && !projectService.useSingleInferredProject) {
      this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory);
    }
    this.enableGlobalPlugins(this.getCompilerOptions());
  }
  toggleJsInferredProject(isJsInferredProject) {
    if (isJsInferredProject !== this._isJsInferredProject) {
      this._isJsInferredProject = isJsInferredProject;
      this.setCompilerOptions();
    }
  }
  setCompilerOptions(options) {
    if (!options && !this.getCompilationSettings()) {
      return;
    }
    const newOptions = cloneCompilerOptions(options || this.getCompilationSettings());
    if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") {
      newOptions.maxNodeModuleJsDepth = 2;
    } else if (!this._isJsInferredProject) {
      newOptions.maxNodeModuleJsDepth = void 0;
    }
    newOptions.allowJs = true;
    super.setCompilerOptions(newOptions);
  }
  addRoot(info) {
    Debug.assert(info.isScriptOpen());
    this.projectService.startWatchingConfigFilesForInferredProjectRoot(info);
    if (!this._isJsInferredProject && info.isJavaScript()) {
      this.toggleJsInferredProject(
        /*isJsInferredProject*/
        true
      );
    } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) {
      this.toggleJsInferredProject(
        /*isJsInferredProject*/
        false
      );
    }
    super.addRoot(info);
  }
  removeRoot(info) {
    this.projectService.stopWatchingConfigFilesForScriptInfo(info);
    super.removeRoot(info);
    if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) {
      if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) {
        this.toggleJsInferredProject(
          /*isJsInferredProject*/
          false
        );
      }
    }
  }
  /** @internal */
  isOrphan() {
    return !this.hasRoots();
  }
  isProjectWithSingleRoot() {
    return !this.projectRootPath && !this.projectService.useSingleInferredProject || this.getRootScriptInfos().length === 1;
  }
  close() {
    forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForScriptInfo(info));
    super.close();
  }
  getTypeAcquisition() {
    return this.typeAcquisition || {
      enable: allRootFilesAreJsOrDts(this),
      include: emptyArray,
      exclude: emptyArray
    };
  }
};
var AuxiliaryProject = class extends Project2 {
  constructor(hostProject) {
    super(
      hostProject.projectService.newAuxiliaryProjectName(),
      4 /* Auxiliary */,
      hostProject.projectService,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      hostProject.getCompilerOptionsForNoDtsResolutionProject(),
      /*compileOnSaveEnabled*/
      false,
      /*watchOptions*/
      void 0,
      hostProject.projectService.host,
      hostProject.currentDirectory
    );
  }
  isOrphan() {
    return true;
  }
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    return;
  }
};
var _AutoImportProviderProject = class _AutoImportProviderProject extends Project2 {
  /** @internal */
  constructor(hostProject, initialRootNames, compilerOptions) {
    super(
      hostProject.projectService.newAutoImportProviderProjectName(),
      3 /* AutoImportProvider */,
      hostProject.projectService,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      compilerOptions,
      /*compileOnSaveEnabled*/
      false,
      hostProject.getWatchOptions(),
      hostProject.projectService.host,
      hostProject.currentDirectory
    );
    this.hostProject = hostProject;
    this.rootFileNames = initialRootNames;
    this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect);
    this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine);
  }
  /** @internal */
  static getRootFileNames(dependencySelection, hostProject, host, compilerOptions) {
    var _a, _b;
    if (!dependencySelection) {
      return emptyArray;
    }
    const program = hostProject.getCurrentProgram();
    if (!program) {
      return emptyArray;
    }
    const start = timestamp();
    let dependencyNames;
    let rootNames;
    const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile);
    const packageJsons = hostProject.getPackageJsonsForAutoImport(combinePaths(hostProject.currentDirectory, rootFileName));
    for (const packageJson of packageJsons) {
      (_a = packageJson.dependencies) == null ? void 0 : _a.forEach((_, dependenyName) => addDependency(dependenyName));
      (_b = packageJson.peerDependencies) == null ? void 0 : _b.forEach((_, dependencyName) => addDependency(dependencyName));
    }
    let dependenciesAdded = 0;
    if (dependencyNames) {
      const symlinkCache = hostProject.getSymlinkCache();
      for (const name of arrayFrom(dependencyNames.keys())) {
        if (dependencySelection === 2 /* Auto */ && dependenciesAdded >= this.maxDependencies) {
          hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`);
          return emptyArray;
        }
        const packageJson = resolvePackageNameToPackageJson(
          name,
          hostProject.currentDirectory,
          compilerOptions,
          host,
          program.getModuleResolutionCache()
        );
        if (packageJson) {
          const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache);
          if (entrypoints) {
            dependenciesAdded += addRootNames(entrypoints);
            continue;
          }
        }
        const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], (directory) => {
          if (directory) {
            const typesPackageJson = resolvePackageNameToPackageJson(
              `@types/${name}`,
              directory,
              compilerOptions,
              host,
              program.getModuleResolutionCache()
            );
            if (typesPackageJson) {
              const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache);
              dependenciesAdded += addRootNames(entrypoints);
              return true;
            }
          }
        });
        if (done) continue;
        if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) {
          const entrypoints = getRootNamesFromPackageJson(
            packageJson,
            program,
            symlinkCache,
            /*resolveJs*/
            true
          );
          dependenciesAdded += addRootNames(entrypoints);
        }
      }
    }
    const references = program.getResolvedProjectReferences();
    let referencesAddded = 0;
    if ((references == null ? void 0 : references.length) && hostProject.projectService.getHostPreferences().includeCompletionsForModuleExports) {
      references.forEach((ref) => {
        if (ref == null ? void 0 : ref.commandLine.options.outFile) {
          referencesAddded += addRootNames(filterEntrypoints([
            changeExtension(ref.commandLine.options.outFile, ".d.ts")
          ]));
        } else if (ref) {
          const getCommonSourceDirectory2 = memoize(
            () => getCommonSourceDirectoryOfConfig(
              ref.commandLine,
              !hostProject.useCaseSensitiveFileNames()
            )
          );
          referencesAddded += addRootNames(filterEntrypoints(mapDefined(
            ref.commandLine.fileNames,
            (fileName) => !isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */) && !program.getSourceFile(fileName) ? getOutputDeclarationFileName(
              fileName,
              ref.commandLine,
              !hostProject.useCaseSensitiveFileNames(),
              getCommonSourceDirectory2
            ) : void 0
          )));
        }
      });
    }
    if (rootNames == null ? void 0 : rootNames.size) {
      hostProject.log(`AutoImportProviderProject: found ${rootNames.size} root files in ${dependenciesAdded} dependencies ${referencesAddded} referenced projects in ${timestamp() - start} ms`);
    }
    return rootNames ? arrayFrom(rootNames.values()) : emptyArray;
    function addRootNames(entrypoints) {
      if (!(entrypoints == null ? void 0 : entrypoints.length)) return 0;
      rootNames ?? (rootNames = /* @__PURE__ */ new Set());
      entrypoints.forEach((entry) => rootNames.add(entry));
      return 1;
    }
    function addDependency(dependency) {
      if (!startsWith(dependency, "@types/")) {
        (dependencyNames || (dependencyNames = /* @__PURE__ */ new Set())).add(dependency);
      }
    }
    function getRootNamesFromPackageJson(packageJson, program2, symlinkCache, resolveJs) {
      var _a2;
      const entrypoints = getEntrypointsFromPackageJsonInfo(
        packageJson,
        compilerOptions,
        host,
        program2.getModuleResolutionCache(),
        resolveJs
      );
      if (entrypoints) {
        const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory);
        const realPath2 = real ? hostProject.toPath(real) : void 0;
        const isSymlink = realPath2 && realPath2 !== hostProject.toPath(packageJson.packageDirectory);
        if (isSymlink) {
          symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, {
            real: ensureTrailingDirectorySeparator(real),
            realPath: ensureTrailingDirectorySeparator(realPath2)
          });
        }
        return filterEntrypoints(entrypoints, isSymlink ? (entrypoint) => entrypoint.replace(packageJson.packageDirectory, real) : void 0);
      }
    }
    function filterEntrypoints(entrypoints, symlinkName) {
      return mapDefined(entrypoints, (entrypoint) => {
        const resolvedFileName = symlinkName ? symlinkName(entrypoint) : entrypoint;
        if (!program.getSourceFile(resolvedFileName) && !(symlinkName && program.getSourceFile(entrypoint))) {
          return resolvedFileName;
        }
      });
    }
  }
  /** @internal */
  static create(dependencySelection, hostProject, host) {
    if (dependencySelection === 0 /* Off */) {
      return void 0;
    }
    const compilerOptions = {
      ...hostProject.getCompilerOptions(),
      ...this.compilerOptionsOverrides
    };
    const rootNames = this.getRootFileNames(dependencySelection, hostProject, host, compilerOptions);
    if (!rootNames.length) {
      return void 0;
    }
    return new _AutoImportProviderProject(hostProject, rootNames, compilerOptions);
  }
  /** @internal */
  isEmpty() {
    return !some(this.rootFileNames);
  }
  /** @internal */
  isOrphan() {
    return true;
  }
  updateGraph() {
    let rootFileNames = this.rootFileNames;
    if (!rootFileNames) {
      rootFileNames = _AutoImportProviderProject.getRootFileNames(
        this.hostProject.includePackageJsonAutoImports(),
        this.hostProject,
        this.hostProject.getHostForAutoImportProvider(),
        this.getCompilationSettings()
      );
    }
    this.projectService.setFileNamesOfAutoImportProviderOrAuxillaryProject(this, rootFileNames);
    this.rootFileNames = rootFileNames;
    const oldProgram = this.getCurrentProgram();
    const hasSameSetOfFiles = super.updateGraph();
    if (oldProgram && oldProgram !== this.getCurrentProgram()) {
      this.hostProject.clearCachedExportInfoMap();
    }
    return hasSameSetOfFiles;
  }
  /** @internal */
  scheduleInvalidateResolutionsOfFailedLookupLocations() {
    return;
  }
  hasRoots() {
    var _a;
    return !!((_a = this.rootFileNames) == null ? void 0 : _a.length);
  }
  /** @internal */
  markAsDirty() {
    this.rootFileNames = void 0;
    super.markAsDirty();
  }
  getScriptFileNames() {
    return this.rootFileNames || emptyArray;
  }
  getLanguageService() {
    throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`.");
  }
  /** @internal */
  onAutoImportProviderSettingsChanged() {
    throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead.");
  }
  /** @internal */
  onPackageJsonChange() {
    throw new Error("package.json changes should be notified on an AutoImportProvider's host project");
  }
  getHostForAutoImportProvider() {
    throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead.");
  }
  getProjectReferences() {
    return this.hostProject.getProjectReferences();
  }
  /** @internal */
  includePackageJsonAutoImports() {
    return 0 /* Off */;
  }
  /** @internal */
  getSymlinkCache() {
    return this.hostProject.getSymlinkCache();
  }
  /** @internal */
  getModuleResolutionCache() {
    var _a;
    return (_a = this.hostProject.getCurrentProgram()) == null ? void 0 : _a.getModuleResolutionCache();
  }
};
_AutoImportProviderProject.maxDependencies = 10;
/** @internal */
_AutoImportProviderProject.compilerOptionsOverrides = {
  diagnostics: false,
  skipLibCheck: true,
  sourceMap: false,
  types: emptyArray,
  lib: emptyArray,
  noLib: true
};
var AutoImportProviderProject = _AutoImportProviderProject;
var ConfiguredProject2 = class extends Project2 {
  /** @internal */
  constructor(configFileName, canonicalConfigFilePath, projectService, cachedDirectoryStructureHost, pendingUpdateReason) {
    super(
      configFileName,
      1 /* Configured */,
      projectService,
      /*hasExplicitListOfFiles*/
      false,
      /*lastFileExceededProgramSize*/
      void 0,
      /*compilerOptions*/
      {},
      /*compileOnSaveEnabled*/
      false,
      /*watchOptions*/
      void 0,
      cachedDirectoryStructureHost,
      getDirectoryPath(configFileName)
    );
    this.canonicalConfigFilePath = canonicalConfigFilePath;
    /** @internal */
    this.openFileWatchTriggered = /* @__PURE__ */ new Map();
    /** @internal */
    this.initialLoadPending = true;
    /** @internal */
    this.sendLoadingProjectFinish = false;
    this.pendingUpdateLevel = 2 /* Full */;
    this.pendingUpdateReason = pendingUpdateReason;
  }
  /** @internal */
  setCompilerHost(host) {
    this.compilerHost = host;
  }
  /** @internal */
  getCompilerHost() {
    return this.compilerHost;
  }
  /** @internal */
  useSourceOfProjectReferenceRedirect() {
    return this.languageServiceEnabled;
  }
  /** @internal */
  getParsedCommandLine(fileName) {
    const configFileName = toNormalizedPath(fileName);
    const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName));
    let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo) {
      this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) });
    }
    this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this);
    if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) {
      this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this);
    }
    return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : void 0;
  }
  /** @internal */
  onReleaseParsedCommandLine(fileName) {
    this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(toNormalizedPath(fileName))));
  }
  releaseParsedConfig(canonicalConfigFilePath) {
    this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this);
    this.projectService.releaseParsedConfig(canonicalConfigFilePath, this);
  }
  /**
   * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
   * @returns: true if set of files in the project stays the same and false - otherwise.
   */
  updateGraph() {
    if (this.deferredClose) return false;
    const isDirty = this.dirty;
    this.initialLoadPending = false;
    const updateLevel = this.pendingUpdateLevel;
    this.pendingUpdateLevel = 0 /* Update */;
    let result;
    switch (updateLevel) {
      case 1 /* RootNamesAndUpdate */:
        this.openFileWatchTriggered.clear();
        result = this.projectService.reloadFileNamesOfConfiguredProject(this);
        break;
      case 2 /* Full */:
        this.openFileWatchTriggered.clear();
        const reason = Debug.checkDefined(this.pendingUpdateReason);
        this.projectService.reloadConfiguredProject(this, reason);
        result = true;
        break;
      default:
        result = super.updateGraph();
    }
    this.compilerHost = void 0;
    this.projectService.sendProjectLoadingFinishEvent(this);
    this.projectService.sendProjectTelemetry(this);
    if (updateLevel === 2 /* Full */ || // Already sent event through reload
    result && // Not new program
    (!isDirty || !this.triggerFileForConfigFileDiag || this.getCurrentProgram().structureIsReused === 2 /* Completely */)) {
      this.triggerFileForConfigFileDiag = void 0;
    } else if (!this.triggerFileForConfigFileDiag) {
      this.projectService.sendConfigFileDiagEvent(
        this,
        /*triggerFile*/
        void 0,
        /*force*/
        false
      );
    }
    return result;
  }
  /** @internal */
  getCachedDirectoryStructureHost() {
    return this.directoryStructureHost;
  }
  getConfigFilePath() {
    return asNormalizedPath(this.getProjectName());
  }
  getProjectReferences() {
    return this.projectReferences;
  }
  updateReferences(refs) {
    this.projectReferences = refs;
    this.potentialProjectReferences = void 0;
  }
  /** @internal */
  setPotentialProjectReference(canonicalConfigPath) {
    Debug.assert(this.initialLoadPending);
    (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath);
  }
  /** @internal */
  getResolvedProjectReferenceToRedirect(fileName) {
    const program = this.getCurrentProgram();
    return program && program.getResolvedProjectReferenceToRedirect(fileName);
  }
  /** @internal */
  forEachResolvedProjectReference(cb) {
    var _a;
    return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb);
  }
  /** @internal */
  enablePluginsWithOptions(options) {
    var _a;
    this.plugins.length = 0;
    if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) return;
    const host = this.projectService.host;
    if (!host.require && !host.importPlugin) {
      this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    const searchPaths = this.getGlobalPluginSearchPaths();
    if (this.projectService.allowLocalPluginLoads) {
      const local = getDirectoryPath(this.canonicalConfigFilePath);
      this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`);
      searchPaths.unshift(local);
    }
    if (options.plugins) {
      for (const pluginConfigEntry of options.plugins) {
        this.enablePlugin(pluginConfigEntry, searchPaths);
      }
    }
    return this.enableGlobalPlugins(options);
  }
  /**
   * Get the errors that dont have any file name associated
   */
  getGlobalProjectErrors() {
    return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2;
  }
  /**
   * Get all the project errors
   */
  getAllProjectErrors() {
    return this.projectErrors || emptyArray2;
  }
  setProjectErrors(projectErrors) {
    this.projectErrors = projectErrors;
  }
  close() {
    this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath));
    this.projectErrors = void 0;
    this.openFileWatchTriggered.clear();
    this.compilerHost = void 0;
    super.close();
  }
  /** @internal */
  markAsDirty() {
    if (this.deferredClose) return;
    super.markAsDirty();
  }
  /** @internal */
  isOrphan() {
    return !!this.deferredClose;
  }
  getEffectiveTypeRoots() {
    return getEffectiveTypeRoots(this.getCompilationSettings(), this) || [];
  }
  /** @internal */
  updateErrorOnNoInputFiles(parsedCommandLine) {
    this.parsedCommandLine = parsedCommandLine;
    updateErrorForNoInputFiles(
      parsedCommandLine.fileNames,
      this.getConfigFilePath(),
      this.getCompilerOptions().configFile.configFileSpecs,
      this.projectErrors,
      canJsonReportNoInputFiles(parsedCommandLine.raw)
    );
  }
};
var ExternalProject = class extends Project2 {
  /** @internal */
  constructor(externalProjectName, projectService, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) {
    super(
      externalProjectName,
      2 /* External */,
      projectService,
      /*hasExplicitListOfFiles*/
      true,
      lastFileExceededProgramSize,
      compilerOptions,
      compileOnSaveEnabled,
      watchOptions,
      projectService.host,
      getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName))
    );
    this.externalProjectName = externalProjectName;
    this.compileOnSaveEnabled = compileOnSaveEnabled;
    this.excludedFiles = [];
    this.enableGlobalPlugins(this.getCompilerOptions());
  }
  updateGraph() {
    const result = super.updateGraph();
    this.projectService.sendProjectTelemetry(this);
    return result;
  }
  getExcludedFiles() {
    return this.excludedFiles;
  }
};
function isInferredProject(project) {
  return project.projectKind === 0 /* Inferred */;
}
function isConfiguredProject(project) {
  return project.projectKind === 1 /* Configured */;
}
function isExternalProject(project) {
  return project.projectKind === 2 /* External */;
}
function isBackgroundProject(project) {
  return project.projectKind === 3 /* AutoImportProvider */ || project.projectKind === 4 /* Auxiliary */;
}
function isProjectDeferredClose(project) {
  return isConfiguredProject(project) && !!project.deferredClose;
}

// src/server/editorServices.ts
var maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
var maxFileSize = 4 * 1024 * 1024;
var ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
var ProjectLoadingStartEvent = "projectLoadingStart";
var ProjectLoadingFinishEvent = "projectLoadingFinish";
var LargeFileReferencedEvent = "largeFileReferenced";
var ConfigFileDiagEvent = "configFileDiag";
var ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
var ProjectInfoTelemetryEvent = "projectInfo";
var OpenFileInfoTelemetryEvent = "openFileInfo";
var CreateFileWatcherEvent = "createFileWatcher";
var CreateDirectoryWatcherEvent = "createDirectoryWatcher";
var CloseFileWatcherEvent = "closeFileWatcher";
var ensureProjectForOpenFileSchedule = "*ensureProjectForOpenFiles*";
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) {
  const map2 = /* @__PURE__ */ new Map();
  for (const option of commandLineOptions) {
    if (typeof option.type === "object") {
      const optionMap = option.type;
      optionMap.forEach((value) => {
        Debug.assert(typeof value === "number");
      });
      map2.set(option.name, optionMap);
    }
  }
  return map2;
}
var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations);
var watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optionsForWatch);
var indentStyle = new Map(Object.entries({
  none: 0 /* None */,
  block: 1 /* Block */,
  smart: 2 /* Smart */
}));
var defaultTypeSafeList = {
  "jquery": {
    // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
    match: /jquery(-[\d.]+)?(\.intellisense)?(\.min)?\.js$/i,
    types: ["jquery"]
  },
  "WinJS": {
    // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
    match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i,
    // If the winjs/base.js file is found..
    exclude: [["^", 1, "/.*"]],
    // ..then exclude all files under the winjs folder
    types: ["winjs"]
    // And fetch the @types package for WinJS
  },
  "Kendo": {
    // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
    match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i,
    exclude: [["^", 1, "/.*"]],
    types: ["kendo-ui"]
  },
  "Office Nuget": {
    // e.g. /scripts/Office/1/excel-15.debug.js
    match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i,
    // Office NuGet package is installed under a "1/office" folder
    exclude: [["^", 1, "/.*"]],
    // Exclude that whole folder if the file indicated above is found in it
    types: ["office"]
    // @types package to fetch instead
  },
  "References": {
    match: /^(.*\/_references\.js)$/i,
    exclude: [["^", 1, "$"]]
  }
};
function convertFormatOptions(protocolOptions) {
  if (isString(protocolOptions.indentStyle)) {
    protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
    Debug.assert(protocolOptions.indentStyle !== void 0);
  }
  return protocolOptions;
}
function convertCompilerOptions(protocolOptions) {
  compilerOptionConverters.forEach((mappedValues, id) => {
    const propertyValue = protocolOptions[id];
    if (isString(propertyValue)) {
      protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
    }
  });
  return protocolOptions;
}
function convertWatchOptions(protocolOptions, currentDirectory) {
  let watchOptions;
  let errors;
  optionsForWatch.forEach((option) => {
    const propertyValue = protocolOptions[option.name];
    if (propertyValue === void 0) return;
    const mappedValues = watchOptionsConverters.get(option.name);
    (watchOptions || (watchOptions = {}))[option.name] = mappedValues ? isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue : convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = []));
  });
  return watchOptions && { watchOptions, errors };
}
function convertTypeAcquisition(protocolOptions) {
  let result;
  typeAcquisitionDeclarations.forEach((option) => {
    const propertyValue = protocolOptions[option.name];
    if (propertyValue === void 0) return;
    (result || (result = {}))[option.name] = propertyValue;
  });
  return result;
}
function tryConvertScriptKindName(scriptKindName) {
  return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName;
}
function convertScriptKindName(scriptKindName) {
  switch (scriptKindName) {
    case "JS":
      return 1 /* JS */;
    case "JSX":
      return 2 /* JSX */;
    case "TS":
      return 3 /* TS */;
    case "TSX":
      return 4 /* TSX */;
    default:
      return 0 /* Unknown */;
  }
}
function convertUserPreferences(preferences) {
  const { lazyConfiguredProjectsFromExternalProject: _, ...userPreferences } = preferences;
  return userPreferences;
}
var fileNamePropertyReader = {
  getFileName: (x) => x,
  getScriptKind: (fileName, extraFileExtensions) => {
    let result;
    if (extraFileExtensions) {
      const fileExtension = getAnyExtensionFromPath(fileName);
      if (fileExtension) {
        some(extraFileExtensions, (info) => {
          if (info.extension === fileExtension) {
            result = info.scriptKind;
            return true;
          }
          return false;
        });
      }
    }
    return result;
  },
  hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, (ext) => ext.isMixedContent && fileExtensionIs(fileName, ext.extension))
};
var externalFilePropertyReader = {
  getFileName: (x) => x.fileName,
  getScriptKind: (x) => tryConvertScriptKindName(x.scriptKind),
  // TODO: GH#18217
  hasMixedContent: (x) => !!x.hasMixedContent
};
function findProjectByName(projectName, projects) {
  for (const proj of projects) {
    if (proj.getProjectName() === projectName) {
      return proj;
    }
  }
}
var nullTypingsInstaller = {
  isKnownTypesPackageName: returnFalse,
  // Should never be called because we never provide a types registry.
  installPackage: notImplemented,
  enqueueInstallTypingsRequest: noop,
  attach: noop,
  onProjectClosed: noop,
  globalTypingsCacheLocation: void 0
  // TODO: GH#18217
};
var noopConfigFileWatcher = { close: noop };
function getConfigFileNameFromCache(info, cache) {
  if (!cache) return void 0;
  const configFileForOpenFile = cache.get(info.path);
  if (configFileForOpenFile === void 0) return void 0;
  if (!isAncestorConfigFileInfo(info)) {
    return isString(configFileForOpenFile) || !configFileForOpenFile ? configFileForOpenFile : (
      // direct result
      configFileForOpenFile.get(
        /*key*/
        false
      )
    );
  } else {
    return configFileForOpenFile && !isString(configFileForOpenFile) ? (
      // Map with fileName as key
      configFileForOpenFile.get(info.fileName)
    ) : void 0;
  }
}
function isOpenScriptInfo(infoOrFileNameOrConfig) {
  return !!infoOrFileNameOrConfig.containingProjects;
}
function isAncestorConfigFileInfo(infoOrFileNameOrConfig) {
  return !!infoOrFileNameOrConfig.configFileInfo;
}
var ConfiguredProjectLoadKind = /* @__PURE__ */ ((ConfiguredProjectLoadKind2) => {
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["FindOptimized"] = 0] = "FindOptimized";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Find"] = 1] = "Find";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateReplayOptimized"] = 2] = "CreateReplayOptimized";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateReplay"] = 3] = "CreateReplay";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateOptimized"] = 4] = "CreateOptimized";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Create"] = 5] = "Create";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["ReloadOptimized"] = 6] = "ReloadOptimized";
  ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Reload"] = 7] = "Reload";
  return ConfiguredProjectLoadKind2;
})(ConfiguredProjectLoadKind || {});
function toConfiguredProjectLoadOptimized(kind) {
  return kind - 1;
}
function forEachAncestorProjectLoad(info, project, cb, kind, reason, allowDeferredClosed, reloadedProjects, searchOnlyPotentialSolution, delayReloadedConfiguredProjects) {
  var _a;
  while (true) {
    if (project.parsedCommandLine && (searchOnlyPotentialSolution && !project.parsedCommandLine.options.composite || // Currently disableSolutionSearching is shared for finding solution/project when
    // - loading solution for find all references
    // - trying to find default project
    project.parsedCommandLine.options.disableSolutionSearching)) return;
    const configFileName = project.projectService.getConfigFileNameForFile(
      {
        fileName: project.getConfigFilePath(),
        path: info.path,
        configFileInfo: true,
        isForDefaultProject: !searchOnlyPotentialSolution
      },
      kind <= 3 /* CreateReplay */
    );
    if (!configFileName) return;
    const ancestor = project.projectService.findCreateOrReloadConfiguredProject(
      configFileName,
      kind,
      reason,
      allowDeferredClosed,
      !searchOnlyPotentialSolution ? info.fileName : void 0,
      // Config Diag event for project if its for default project
      reloadedProjects,
      searchOnlyPotentialSolution,
      // Delay load if we are searching for solution
      delayReloadedConfiguredProjects
    );
    if (!ancestor) return;
    if (!ancestor.project.parsedCommandLine && ((_a = project.parsedCommandLine) == null ? void 0 : _a.options.composite)) {
      ancestor.project.setPotentialProjectReference(project.canonicalConfigFilePath);
    }
    const result = cb(ancestor);
    if (result) return result;
    project = ancestor.project;
  }
}
function forEachResolvedProjectReferenceProjectLoad(project, parentConfig, cb, kind, reason, allowDeferredClosed, reloadedProjects, seenResolvedRefs) {
  const loadKind = parentConfig.options.disableReferencedProjectLoad ? 0 /* FindOptimized */ : kind;
  let children;
  return forEach(
    parentConfig.projectReferences,
    (ref) => {
      var _a;
      const childConfigName = toNormalizedPath(resolveProjectReferencePath(ref));
      const childCanonicalConfigPath = asNormalizedPath(project.projectService.toCanonicalFileName(childConfigName));
      const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(childCanonicalConfigPath);
      if (seenValue !== void 0 && seenValue >= loadKind) return void 0;
      const configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath);
      let childConfig = loadKind === 0 /* FindOptimized */ ? (configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.exists) || ((_a = project.resolvedChildConfigs) == null ? void 0 : _a.has(childCanonicalConfigPath)) ? configFileExistenceInfo.config.parsedCommandLine : void 0 : project.getParsedCommandLine(childConfigName);
      if (childConfig && loadKind !== kind && loadKind > 2 /* CreateReplayOptimized */) {
        childConfig = project.getParsedCommandLine(childConfigName);
      }
      if (!childConfig) return void 0;
      const childProject = project.projectService.findConfiguredProjectByProjectName(childConfigName, allowDeferredClosed);
      if (loadKind === 2 /* CreateReplayOptimized */ && !configFileExistenceInfo && !childProject) return void 0;
      switch (loadKind) {
        case 6 /* ReloadOptimized */:
          if (childProject) childProject.projectService.reloadConfiguredProjectOptimized(childProject, reason, reloadedProjects);
        // falls through
        case 4 /* CreateOptimized */:
          (project.resolvedChildConfigs ?? (project.resolvedChildConfigs = /* @__PURE__ */ new Set())).add(childCanonicalConfigPath);
        // falls through
        case 2 /* CreateReplayOptimized */:
        case 0 /* FindOptimized */:
          if (childProject || loadKind !== 0 /* FindOptimized */) {
            const result = cb(
              configFileExistenceInfo ?? project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath),
              childProject,
              childConfigName,
              reason,
              project,
              childCanonicalConfigPath
            );
            if (result) return result;
          }
          break;
        default:
          Debug.assertNever(loadKind);
      }
      (seenResolvedRefs ?? (seenResolvedRefs = /* @__PURE__ */ new Map())).set(childCanonicalConfigPath, loadKind);
      (children ?? (children = [])).push(childConfig);
    }
  ) || forEach(
    children,
    (childConfig) => childConfig.projectReferences && forEachResolvedProjectReferenceProjectLoad(
      project,
      childConfig,
      cb,
      loadKind,
      reason,
      allowDeferredClosed,
      reloadedProjects,
      seenResolvedRefs
    )
  );
}
function updateProjectFoundUsingFind(project, kind, triggerFile, reason, reloadedProjects) {
  let sentConfigFileDiag = false;
  let configFileExistenceInfo;
  switch (kind) {
    case 2 /* CreateReplayOptimized */:
    case 3 /* CreateReplay */:
      if (useConfigFileExistenceInfoForOptimizedLoading(project)) {
        configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath);
      }
      break;
    case 4 /* CreateOptimized */:
      configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project);
      if (configFileExistenceInfo) break;
    // falls through
    case 5 /* Create */:
      sentConfigFileDiag = updateConfiguredProject(project, triggerFile);
      break;
    case 6 /* ReloadOptimized */:
      project.projectService.reloadConfiguredProjectOptimized(project, reason, reloadedProjects);
      configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project);
      if (configFileExistenceInfo) break;
    // falls through
    case 7 /* Reload */:
      sentConfigFileDiag = project.projectService.reloadConfiguredProjectClearingSemanticCache(
        project,
        reason,
        reloadedProjects
      );
      break;
    case 0 /* FindOptimized */:
    case 1 /* Find */:
      break;
    default:
      Debug.assertNever(kind);
  }
  return { project, sentConfigFileDiag, configFileExistenceInfo, reason };
}
function forEachPotentialProjectReference(project, cb) {
  return project.initialLoadPending ? (project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb)) ?? (project.resolvedChildConfigs && forEachKey(project.resolvedChildConfigs, cb)) : void 0;
}
function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) {
  return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.initialLoadPending ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef);
}
function callbackRefProject(project, cb, refPath) {
  const refProject = refPath && project.projectService.configuredProjects.get(refPath);
  return refProject && cb(refProject);
}
function forEachReferencedProject(project, cb) {
  return forEachAnyProjectReferenceKind(
    project,
    (resolvedRef) => callbackRefProject(project, cb, resolvedRef.sourceFile.path),
    (projectRef) => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))),
    (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef)
  );
}
function getDetailWatchInfo(watchType, project) {
  return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`;
}
function isScriptInfoWatchedFromNodeModules(info) {
  return !info.isScriptOpen() && info.mTime !== void 0;
}
function updateProjectIfDirty(project) {
  project.invalidateResolutionsOfFailedLookupLocations();
  return project.dirty && !project.updateGraph();
}
function updateWithTriggerFile(project, triggerFile, isReload) {
  if (!isReload) {
    project.invalidateResolutionsOfFailedLookupLocations();
    if (!project.dirty) return false;
  }
  project.triggerFileForConfigFileDiag = triggerFile;
  const updateLevel = project.pendingUpdateLevel;
  project.updateGraph();
  if (!project.triggerFileForConfigFileDiag && !isReload) return updateLevel === 2 /* Full */;
  const sent = project.projectService.sendConfigFileDiagEvent(project, triggerFile, isReload);
  project.triggerFileForConfigFileDiag = void 0;
  return sent;
}
function updateConfiguredProject(project, triggerFile) {
  if (triggerFile) {
    if (updateWithTriggerFile(
      project,
      triggerFile,
      /*isReload*/
      false
    )) return true;
  } else {
    updateProjectIfDirty(project);
  }
  return false;
}
function configFileExistenceInfoForOptimizedLoading(project) {
  const configFileName = toNormalizedPath(project.getConfigFilePath());
  const configFileExistenceInfo = project.projectService.ensureParsedConfigUptoDate(
    configFileName,
    project.canonicalConfigFilePath,
    project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath),
    project
  );
  const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine;
  project.parsedCommandLine = parsedCommandLine;
  project.resolvedChildConfigs = void 0;
  project.updateReferences(parsedCommandLine.projectReferences);
  if (useConfigFileExistenceInfoForOptimizedLoading(project)) return configFileExistenceInfo;
}
function useConfigFileExistenceInfoForOptimizedLoading(project) {
  return !!project.parsedCommandLine && (!!project.parsedCommandLine.options.composite || // If solution, no need to load it to determine if file belongs to it
  !!isSolutionConfig(project.parsedCommandLine));
}
function configFileExistenceInfoForOptimizedReplay(project) {
  return useConfigFileExistenceInfoForOptimizedLoading(project) ? project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath) : void 0;
}
function fileOpenReason(info) {
  return `Creating possible configured project for ${info.fileName} to open`;
}
function reloadReason(reason) {
  return `User requested reload projects: ${reason}`;
}
function setProjectOptionsUsed(project) {
  if (isConfiguredProject(project)) {
    project.projectOptions = true;
  }
}
function createProjectNameFactoryWithCounter(nameFactory) {
  let nextId = 1;
  return () => nameFactory(nextId++);
}
function getHostWatcherMap() {
  return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() };
}
function getCanUseWatchEvents(service, canUseWatchEvents) {
  return !!canUseWatchEvents && !!service.eventHandler && !!service.session;
}
function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) {
  if (!getCanUseWatchEvents(service, canUseWatchEvents)) return void 0;
  const watchedFiles = getHostWatcherMap();
  const watchedDirectories = getHostWatcherMap();
  const watchedDirectoriesRecursive = getHostWatcherMap();
  let ids = 1;
  service.session.addProtocolHandler("watchChange" /* WatchChange */, (req) => {
    onWatchChange(req.arguments);
    return { responseRequired: false };
  });
  return {
    watchFile: watchFile2,
    watchDirectory,
    getCurrentDirectory: () => service.host.getCurrentDirectory(),
    useCaseSensitiveFileNames: service.host.useCaseSensitiveFileNames
  };
  function watchFile2(path, callback) {
    return getOrCreateFileWatcher(
      watchedFiles,
      path,
      callback,
      (id) => ({ eventName: CreateFileWatcherEvent, data: { id, path } })
    );
  }
  function watchDirectory(path, callback, recursive) {
    return getOrCreateFileWatcher(
      recursive ? watchedDirectoriesRecursive : watchedDirectories,
      path,
      callback,
      (id) => ({
        eventName: CreateDirectoryWatcherEvent,
        data: {
          id,
          path,
          recursive: !!recursive,
          // Special case node_modules as we watch it for changes to closed script infos as well
          ignoreUpdate: !path.endsWith("/node_modules") ? true : void 0
        }
      })
    );
  }
  function getOrCreateFileWatcher({ pathToId, idToCallbacks }, path, callback, event) {
    const key = service.toPath(path);
    let id = pathToId.get(key);
    if (!id) pathToId.set(key, id = ids++);
    let callbacks = idToCallbacks.get(id);
    if (!callbacks) {
      idToCallbacks.set(id, callbacks = /* @__PURE__ */ new Set());
      service.eventHandler(event(id));
    }
    callbacks.add(callback);
    return {
      close() {
        const callbacks2 = idToCallbacks.get(id);
        if (!(callbacks2 == null ? void 0 : callbacks2.delete(callback))) return;
        if (callbacks2.size) return;
        idToCallbacks.delete(id);
        pathToId.delete(key);
        service.eventHandler({ eventName: CloseFileWatcherEvent, data: { id } });
      }
    };
  }
  function onWatchChange(args) {
    if (isArray(args)) args.forEach(onWatchChangeRequestArgs);
    else onWatchChangeRequestArgs(args);
  }
  function onWatchChangeRequestArgs({ id, created, deleted, updated }) {
    onWatchEventType(id, created, 0 /* Created */);
    onWatchEventType(id, deleted, 2 /* Deleted */);
    onWatchEventType(id, updated, 1 /* Changed */);
  }
  function onWatchEventType(id, paths, eventKind) {
    if (!(paths == null ? void 0 : paths.length)) return;
    forEachCallback(watchedFiles, id, paths, (callback, eventPath) => callback(eventPath, eventKind));
    forEachCallback(watchedDirectories, id, paths, (callback, eventPath) => callback(eventPath));
    forEachCallback(watchedDirectoriesRecursive, id, paths, (callback, eventPath) => callback(eventPath));
  }
  function forEachCallback(hostWatcherMap, id, eventPaths, cb) {
    var _a;
    (_a = hostWatcherMap.idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => {
      eventPaths.forEach((eventPath) => cb(callback, normalizeSlashes(eventPath)));
    });
  }
}
var _ProjectService = class _ProjectService {
  constructor(opts) {
    /**
     * Container of all known scripts
     *
     * @internal
     */
    this.filenameToScriptInfo = /* @__PURE__ */ new Map();
    this.nodeModulesWatchers = /* @__PURE__ */ new Map();
    /**
     * Contains all the deleted script info's version information so that
     * it does not reset when creating script info again
     * (and could have potentially collided with version where contents mismatch)
     */
    this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map();
    // Set of all '.js' files ever opened.
    this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Set();
    /**
     * maps external project file name to list of config files that were the part of this project
     */
    this.externalProjectToConfiguredProjectMap = /* @__PURE__ */ new Map();
    /**
     * external projects (configuration and list of root files is not controlled by tsserver)
     */
    this.externalProjects = [];
    /**
     * projects built from openFileRoots
     */
    this.inferredProjects = [];
    /**
     * projects specified by a tsconfig.json file
     */
    this.configuredProjects = /* @__PURE__ */ new Map();
    /** @internal */
    this.newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName);
    /** @internal */
    this.newAutoImportProviderProjectName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName);
    /** @internal */
    this.newAuxiliaryProjectName = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName);
    /**
     * Open files: with value being project root path, and key being Path of the file that is open
     */
    this.openFiles = /* @__PURE__ */ new Map();
    /** Config files looked up and cached config files for open script info */
    this.configFileForOpenFiles = /* @__PURE__ */ new Map();
    /** Set of open script infos that are root of inferred project */
    this.rootOfInferredProjects = /* @__PURE__ */ new Set();
    /**
     * Map of open files that are opened without complete path but have projectRoot as current directory
     */
    this.openFilesWithNonRootedDiskPath = /* @__PURE__ */ new Map();
    this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map();
    /**
     * Project size for configured or external projects
     */
    this.projectToSizeMap = /* @__PURE__ */ new Map();
    /**
     * This is a map of config file paths existence that doesnt need query to disk
     * - The entry can be present because there is inferred project that needs to watch addition of config file to directory
     *   In this case the exists could be true/false based on config file is present or not
     * - Or it is present if we have configured project open with config file at that location
     *   In this case the exists property is always true
     *
     * @internal
     */
    this.configFileExistenceInfoCache = /* @__PURE__ */ new Map();
    this.safelist = defaultTypeSafeList;
    this.legacySafelist = /* @__PURE__ */ new Map();
    this.pendingProjectUpdates = /* @__PURE__ */ new Map();
    /** @internal */
    this.pendingEnsureProjectForOpenFiles = false;
    /** Tracks projects that we have already sent telemetry for. */
    this.seenProjects = /* @__PURE__ */ new Map();
    this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map();
    this.extendedConfigCache = /* @__PURE__ */ new Map();
    /** @internal */
    this.baseline = noop;
    /** @internal */
    this.verifyDocumentRegistry = noop;
    /** @internal */
    this.verifyProgram = noop;
    /** @internal */
    this.onProjectCreation = noop;
    var _a;
    this.host = opts.host;
    this.logger = opts.logger;
    this.cancellationToken = opts.cancellationToken;
    this.useSingleInferredProject = opts.useSingleInferredProject;
    this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot;
    this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
    this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
    this.eventHandler = opts.eventHandler;
    this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
    this.globalPlugins = opts.globalPlugins || emptyArray2;
    this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray2;
    this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads;
    this.typesMapLocation = opts.typesMapLocation === void 0 ? combinePaths(getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation;
    this.session = opts.session;
    this.jsDocParsingMode = opts.jsDocParsingMode;
    if (opts.serverMode !== void 0) {
      this.serverMode = opts.serverMode;
    } else {
      this.serverMode = 0 /* Semantic */;
    }
    if (this.host.realpath) {
      this.realpathToScriptInfos = createMultiMap();
    }
    this.currentDirectory = toNormalizedPath(this.host.getCurrentDirectory());
    this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
    this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation ? ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) : void 0;
    this.throttledOperations = new ThrottledOperations(this.host, this.logger);
    this.logger.info(`currentDirectory:: ${this.host.getCurrentDirectory()} useCaseSensitiveFileNames:: ${this.host.useCaseSensitiveFileNames}`);
    this.logger.info(`libs Location:: ${getDirectoryPath(this.host.getExecutingFilePath())}`);
    this.logger.info(`globalTypingsCacheLocation:: ${this.typingsInstaller.globalTypingsCacheLocation}`);
    if (this.typesMapLocation) {
      this.loadTypesMap();
    } else {
      this.logger.info("No types map provided; using the default");
    }
    this.typingsInstaller.attach(this);
    this.hostConfiguration = {
      formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine),
      preferences: emptyOptions,
      hostInfo: "Unknown host",
      extraFileExtensions: []
    };
    this.documentRegistry = createDocumentRegistryInternal(
      this.host.useCaseSensitiveFileNames,
      this.currentDirectory,
      this.jsDocParsingMode,
      this
    );
    const watchLogLevel = this.logger.hasLevel(3 /* verbose */) ? 2 /* Verbose */ : this.logger.loggingEnabled() ? 1 /* TriggerOnly */ : 0 /* None */;
    const log = watchLogLevel !== 0 /* None */ ? (s) => this.logger.info(s) : noop;
    this.packageJsonCache = createPackageJsonCache(this);
    this.watchFactory = this.serverMode !== 0 /* Semantic */ ? {
      watchFile: returnNoopFileWatcher,
      watchDirectory: returnNoopFileWatcher
    } : getWatchFactory(
      createWatchFactoryHostUsingWatchEvents(this, opts.canUseWatchEvents) || this.host,
      watchLogLevel,
      log,
      getDetailWatchInfo
    );
    this.canUseWatchEvents = getCanUseWatchEvents(this, opts.canUseWatchEvents);
    (_a = opts.incrementalVerifier) == null ? void 0 : _a.call(opts, this);
  }
  toPath(fileName) {
    return toPath(fileName, this.currentDirectory, this.toCanonicalFileName);
  }
  /** @internal */
  getExecutingFilePath() {
    return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath());
  }
  /** @internal */
  getNormalizedAbsolutePath(fileName) {
    return getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory());
  }
  /** @internal */
  setDocument(key, path, sourceFile) {
    const info = Debug.checkDefined(this.getScriptInfoForPath(path));
    info.cacheSourceFile = { key, sourceFile };
  }
  /** @internal */
  getDocument(key, path) {
    const info = this.getScriptInfoForPath(path);
    return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : void 0;
  }
  /** @internal */
  ensureInferredProjectsUpToDate_TestOnly() {
    this.ensureProjectStructuresUptoDate();
  }
  /** @internal */
  getCompilerOptionsForInferredProjects() {
    return this.compilerOptionsForInferredProjects;
  }
  /** @internal */
  onUpdateLanguageServiceStateForProject(project, languageServiceEnabled) {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: ProjectLanguageServiceStateEvent,
      data: { project, languageServiceEnabled }
    };
    this.eventHandler(event);
  }
  loadTypesMap() {
    try {
      const fileContent = this.host.readFile(this.typesMapLocation);
      if (fileContent === void 0) {
        this.logger.info(`Provided types map file "${this.typesMapLocation}" doesn't exist`);
        return;
      }
      const raw = JSON.parse(fileContent);
      for (const k of Object.keys(raw.typesMap)) {
        raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i");
      }
      this.safelist = raw.typesMap;
      for (const key in raw.simpleMap) {
        if (hasProperty(raw.simpleMap, key)) {
          this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase());
        }
      }
    } catch (e) {
      this.logger.info(`Error loading types map: ${e}`);
      this.safelist = defaultTypeSafeList;
      this.legacySafelist.clear();
    }
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  updateTypingsForProject(response) {
    const project = this.findProject(response.projectName);
    if (!project) {
      return;
    }
    switch (response.kind) {
      case ActionSet:
        project.updateTypingFiles(
          response.compilerOptions,
          response.typeAcquisition,
          response.unresolvedImports,
          response.typings
        );
        return;
      case ActionInvalidate:
        project.enqueueInstallTypingsForProject(
          /*forceRefresh*/
          true
        );
        return;
    }
  }
  /** @internal */
  watchTypingLocations(response) {
    var _a;
    (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files);
  }
  /** @internal */
  delayEnsureProjectForOpenFiles() {
    if (!this.openFiles.size) return;
    this.pendingEnsureProjectForOpenFiles = true;
    this.throttledOperations.schedule(
      ensureProjectForOpenFileSchedule,
      /*delay*/
      2500,
      () => {
        if (this.pendingProjectUpdates.size !== 0) {
          this.delayEnsureProjectForOpenFiles();
        } else {
          if (this.pendingEnsureProjectForOpenFiles) {
            this.ensureProjectForOpenFiles();
            this.sendProjectsUpdatedInBackgroundEvent();
          }
        }
      }
    );
  }
  delayUpdateProjectGraph(project) {
    if (isProjectDeferredClose(project)) return;
    project.markAsDirty();
    if (isBackgroundProject(project)) return;
    const projectName = project.getProjectName();
    this.pendingProjectUpdates.set(projectName, project);
    this.throttledOperations.schedule(
      projectName,
      /*delay*/
      250,
      () => {
        if (this.pendingProjectUpdates.delete(projectName)) {
          updateProjectIfDirty(project);
        }
      }
    );
  }
  /** @internal */
  hasPendingProjectUpdate(project) {
    return this.pendingProjectUpdates.has(project.getProjectName());
  }
  /** @internal */
  sendProjectsUpdatedInBackgroundEvent() {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: ProjectsUpdatedInBackgroundEvent,
      data: {
        openFiles: arrayFrom(this.openFiles.keys(), (path) => this.getScriptInfoForPath(path).fileName)
      }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendLargeFileReferencedEvent(file, fileSize) {
    if (!this.eventHandler) {
      return;
    }
    const event = {
      eventName: LargeFileReferencedEvent,
      data: { file, fileSize, maxFileSize }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendProjectLoadingStartEvent(project, reason) {
    if (!this.eventHandler) {
      return;
    }
    project.sendLoadingProjectFinish = true;
    const event = {
      eventName: ProjectLoadingStartEvent,
      data: { project, reason }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendProjectLoadingFinishEvent(project) {
    if (!this.eventHandler || !project.sendLoadingProjectFinish) {
      return;
    }
    project.sendLoadingProjectFinish = false;
    const event = {
      eventName: ProjectLoadingFinishEvent,
      data: { project }
    };
    this.eventHandler(event);
  }
  /** @internal */
  sendPerformanceEvent(kind, durationMs) {
    if (this.performanceEventHandler) {
      this.performanceEventHandler({ kind, durationMs });
    }
  }
  /** @internal */
  delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project) {
    this.delayUpdateProjectGraph(project);
    this.delayEnsureProjectForOpenFiles();
  }
  delayUpdateProjectGraphs(projects, clearSourceMapperCache) {
    if (projects.length) {
      for (const project of projects) {
        if (clearSourceMapperCache) project.clearSourceMapperCache();
        this.delayUpdateProjectGraph(project);
      }
      this.delayEnsureProjectForOpenFiles();
    }
  }
  setCompilerOptionsForInferredProjects(projectCompilerOptions, projectRootPath) {
    Debug.assert(projectRootPath === void 0 || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
    const compilerOptions = convertCompilerOptions(projectCompilerOptions);
    const watchOptions = convertWatchOptions(projectCompilerOptions, projectRootPath);
    const typeAcquisition = convertTypeAcquisition(projectCompilerOptions);
    compilerOptions.allowNonTsExtensions = true;
    const canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath);
    if (canonicalProjectRootPath) {
      this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions);
      this.watchOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, watchOptions || false);
      this.typeAcquisitionForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, typeAcquisition);
    } else {
      this.compilerOptionsForInferredProjects = compilerOptions;
      this.watchOptionsForInferredProjects = watchOptions;
      this.typeAcquisitionForInferredProjects = typeAcquisition;
    }
    for (const project of this.inferredProjects) {
      if (canonicalProjectRootPath ? project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) {
        project.setCompilerOptions(compilerOptions);
        project.setTypeAcquisition(typeAcquisition);
        project.setWatchOptions(watchOptions == null ? void 0 : watchOptions.watchOptions);
        project.setProjectErrors(watchOptions == null ? void 0 : watchOptions.errors);
        project.compileOnSaveEnabled = compilerOptions.compileOnSave;
        project.markAsDirty();
        this.delayUpdateProjectGraph(project);
      }
    }
    this.delayEnsureProjectForOpenFiles();
  }
  findProject(projectName) {
    if (projectName === void 0) {
      return void 0;
    }
    if (isInferredProjectName(projectName)) {
      return findProjectByName(projectName, this.inferredProjects);
    }
    return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(toNormalizedPath(projectName));
  }
  /** @internal */
  forEachProject(cb) {
    this.externalProjects.forEach(cb);
    this.configuredProjects.forEach(cb);
    this.inferredProjects.forEach(cb);
  }
  /** @internal */
  forEachEnabledProject(cb) {
    this.forEachProject((project) => {
      if (!project.isOrphan() && project.languageServiceEnabled) {
        cb(project);
      }
    });
  }
  getDefaultProjectForFile(fileName, ensureProject) {
    return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
  }
  /** @internal */
  tryGetDefaultProjectForFile(fileNameOrScriptInfo) {
    const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
    return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : void 0;
  }
  /**
   * If there is default project calculation pending for this file,
   * then it completes that calculation so that correct default project is used for the project
   */
  tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) {
    var _a;
    const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
    if (!scriptInfo) return void 0;
    if ((_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(scriptInfo.path)) {
      this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(
        scriptInfo,
        5 /* Create */
      );
      if (scriptInfo.isOrphan()) {
        this.assignOrphanScriptInfoToInferredProject(scriptInfo, this.openFiles.get(scriptInfo.path));
      }
    }
    return this.tryGetDefaultProjectForFile(scriptInfo);
  }
  /** @internal */
  ensureDefaultProjectForFile(fileNameOrScriptInfo) {
    return this.tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo);
  }
  doEnsureDefaultProjectForFile(fileNameOrScriptInfo) {
    this.ensureProjectStructuresUptoDate();
    const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
    return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject());
  }
  getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName) {
    this.ensureProjectStructuresUptoDate();
    return this.getScriptInfo(uncheckedFileName);
  }
  /**
   * Ensures the project structures are upto date
   * This means,
   * - we go through all the projects and update them if they are dirty
   * - if updates reflect some change in structure or there was pending request to ensure projects for open files
   *   ensure that each open script info has project
   */
  ensureProjectStructuresUptoDate() {
    let hasChanges = this.pendingEnsureProjectForOpenFiles;
    this.pendingProjectUpdates.clear();
    const updateGraph = (project) => {
      hasChanges = updateProjectIfDirty(project) || hasChanges;
    };
    this.externalProjects.forEach(updateGraph);
    this.configuredProjects.forEach(updateGraph);
    this.inferredProjects.forEach(updateGraph);
    if (hasChanges) {
      this.ensureProjectForOpenFiles();
    }
  }
  getFormatCodeOptions(file) {
    const info = this.getScriptInfoForNormalizedPath(file);
    return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions;
  }
  getPreferences(file) {
    const info = this.getScriptInfoForNormalizedPath(file);
    return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() };
  }
  getHostFormatCodeOptions() {
    return this.hostConfiguration.formatCodeOptions;
  }
  getHostPreferences() {
    return this.hostConfiguration.preferences;
  }
  onSourceFileChanged(info, eventKind) {
    Debug.assert(!info.isScriptOpen());
    if (eventKind === 2 /* Deleted */) {
      this.handleDeletedFile(
        info,
        /*deferredDelete*/
        true
      );
    } else {
      if (info.deferredDelete) info.deferredDelete = void 0;
      info.delayReloadNonMixedContentFile();
      this.delayUpdateProjectGraphs(
        info.containingProjects,
        /*clearSourceMapperCache*/
        false
      );
      this.handleSourceMapProjects(info);
    }
  }
  handleSourceMapProjects(info) {
    if (info.sourceMapFilePath) {
      if (isString(info.sourceMapFilePath)) {
        const sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
        this.delayUpdateSourceInfoProjects(sourceMapFileInfo == null ? void 0 : sourceMapFileInfo.sourceInfos);
      } else {
        this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
      }
    }
    this.delayUpdateSourceInfoProjects(info.sourceInfos);
    if (info.declarationInfoPath) {
      this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
    }
  }
  delayUpdateSourceInfoProjects(sourceInfos) {
    if (sourceInfos) {
      sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path));
    }
  }
  delayUpdateProjectsOfScriptInfoPath(path) {
    const info = this.getScriptInfoForPath(path);
    if (info) {
      this.delayUpdateProjectGraphs(
        info.containingProjects,
        /*clearSourceMapperCache*/
        true
      );
    }
  }
  handleDeletedFile(info, deferredDelete) {
    Debug.assert(!info.isScriptOpen());
    this.delayUpdateProjectGraphs(
      info.containingProjects,
      /*clearSourceMapperCache*/
      false
    );
    this.handleSourceMapProjects(info);
    info.detachAllProjects();
    if (deferredDelete) {
      info.delayReloadNonMixedContentFile();
      info.deferredDelete = true;
    } else {
      this.deleteScriptInfo(info);
    }
  }
  /**
   * This is to watch whenever files are added or removed to the wildcard directories
   */
  watchWildcardDirectory(directory, flags, configFileName, config) {
    let watcher = this.watchFactory.watchDirectory(
      directory,
      (fileOrDirectory) => this.onWildCardDirectoryWatcherInvoke(
        directory,
        configFileName,
        config,
        result,
        fileOrDirectory
      ),
      flags,
      this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions, getDirectoryPath(configFileName)),
      WatchType.WildcardDirectory,
      configFileName
    );
    const result = {
      packageJsonWatches: void 0,
      close() {
        var _a;
        if (watcher) {
          watcher.close();
          watcher = void 0;
          (_a = result.packageJsonWatches) == null ? void 0 : _a.forEach((watcher2) => {
            watcher2.projects.delete(result);
            watcher2.close();
          });
          result.packageJsonWatches = void 0;
        }
      }
    };
    return result;
  }
  onWildCardDirectoryWatcherInvoke(directory, configFileName, config, wildCardWatcher, fileOrDirectory) {
    const fileOrDirectoryPath = this.toPath(fileOrDirectory);
    const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
    if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectory))) {
      const file = this.getNormalizedAbsolutePath(fileOrDirectory);
      this.logger.info(`Config: ${configFileName} Detected new package.json: ${file}`);
      this.packageJsonCache.addOrUpdate(file, fileOrDirectoryPath);
      this.watchPackageJsonFile(file, fileOrDirectoryPath, wildCardWatcher);
    }
    if (!(fsResult == null ? void 0 : fsResult.fileExists)) {
      this.sendSourceFileChange(fileOrDirectoryPath);
    }
    const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName);
    if (isIgnoredFileFromWildCardWatching({
      watchedDirPath: this.toPath(directory),
      fileOrDirectory,
      fileOrDirectoryPath,
      configFileName,
      extraFileExtensions: this.hostConfiguration.extraFileExtensions,
      currentDirectory: this.currentDirectory,
      options: config.parsedCommandLine.options,
      program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames,
      useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames,
      writeLog: (s) => this.logger.info(s),
      toPath: (s) => this.toPath(s),
      getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0
    })) return;
    if (config.updateLevel !== 2 /* Full */) config.updateLevel = 1 /* RootNamesAndUpdate */;
    config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => {
      var _a;
      if (!watchWildcardDirectories) return;
      const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath);
      if (!project) return;
      if (configuredProjectForConfig !== project && this.getHostPreferences().includeCompletionsForModuleExports) {
        const path = this.toPath(configFileName);
        if (find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) {
          project.markAutoImportProviderAsDirty();
        }
      }
      const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */;
      if (project.pendingUpdateLevel > updateLevel) return;
      if (this.openFiles.has(fileOrDirectoryPath)) {
        const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath));
        if (info.isAttached(project)) {
          const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */);
          project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet);
        } else {
          project.pendingUpdateLevel = updateLevel;
          this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
        }
      } else {
        project.pendingUpdateLevel = updateLevel;
        this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
      }
    });
  }
  delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, loadReason) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) return false;
    let scheduledAnyProjectUpdate = false;
    configFileExistenceInfo.config.updateLevel = 2 /* Full */;
    configFileExistenceInfo.config.cachedDirectoryStructureHost.clearCache();
    configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => {
      var _a, _b, _c;
      const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath);
      if (!project) return;
      scheduledAnyProjectUpdate = true;
      if (projectCanonicalPath === canonicalConfigFilePath) {
        if (project.initialLoadPending) return;
        project.pendingUpdateLevel = 2 /* Full */;
        project.pendingUpdateReason = loadReason;
        this.delayUpdateProjectGraph(project);
        project.markAutoImportProviderAsDirty();
      } else {
        if (project.initialLoadPending) {
          (_b = (_a = this.configFileExistenceInfoCache.get(projectCanonicalPath)) == null ? void 0 : _a.openFilesImpactedByConfigFile) == null ? void 0 : _b.forEach((path2) => {
            var _a2;
            if (!((_a2 = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a2.has(path2))) {
              (this.pendingOpenFileProjectUpdates ?? (this.pendingOpenFileProjectUpdates = /* @__PURE__ */ new Map())).set(
                path2,
                this.configFileForOpenFiles.get(path2)
              );
            }
          });
          return;
        }
        const path = this.toPath(canonicalConfigFilePath);
        project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
        this.delayUpdateProjectGraph(project);
        if (this.getHostPreferences().includeCompletionsForModuleExports && find((_c = project.getCurrentProgram()) == null ? void 0 : _c.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) {
          project.markAutoImportProviderAsDirty();
        }
      }
    });
    return scheduledAnyProjectUpdate;
  }
  onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    const project = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
    const wasDefferedClose = project == null ? void 0 : project.deferredClose;
    if (eventKind === 2 /* Deleted */) {
      configFileExistenceInfo.exists = false;
      if (project) project.deferredClose = true;
    } else {
      configFileExistenceInfo.exists = true;
      if (wasDefferedClose) {
        project.deferredClose = void 0;
        project.markAsDirty();
      }
    }
    this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(
      canonicalConfigFilePath,
      "Change in config file detected"
    );
    this.openFiles.forEach((_projectRootPath, path) => {
      var _a, _b;
      const configFileForOpenFile = this.configFileForOpenFiles.get(path);
      if (!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(path))) return;
      this.configFileForOpenFiles.delete(path);
      const info = this.getScriptInfoForPath(path);
      const newConfigFileNameForInfo = this.getConfigFileNameForFile(
        info,
        /*findFromCacheOnly*/
        false
      );
      if (!newConfigFileNameForInfo) return;
      if (!((_b = this.pendingOpenFileProjectUpdates) == null ? void 0 : _b.has(path))) {
        (this.pendingOpenFileProjectUpdates ?? (this.pendingOpenFileProjectUpdates = /* @__PURE__ */ new Map())).set(path, configFileForOpenFile);
      }
    });
    this.delayEnsureProjectForOpenFiles();
  }
  removeProject(project) {
    this.logger.info("`remove Project::");
    project.print(
      /*writeProjectFileNames*/
      true,
      /*writeFileExplaination*/
      true,
      /*writeFileVersionAndText*/
      false
    );
    project.close();
    if (Debug.shouldAssert(1 /* Normal */)) {
      this.filenameToScriptInfo.forEach(
        (info) => Debug.assert(
          !info.isAttached(project),
          "Found script Info still attached to project",
          () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify(
            arrayFrom(
              mapDefinedIterator(
                this.filenameToScriptInfo.values(),
                (info2) => info2.isAttached(project) ? {
                  fileName: info2.fileName,
                  projects: info2.containingProjects.map((p) => p.projectName),
                  hasMixedContent: info2.hasMixedContent
                } : void 0
              )
            ),
            /*replacer*/
            void 0,
            " "
          )}`
        )
      );
    }
    this.pendingProjectUpdates.delete(project.getProjectName());
    switch (project.projectKind) {
      case 2 /* External */:
        unorderedRemoveItem(this.externalProjects, project);
        this.projectToSizeMap.delete(project.getProjectName());
        break;
      case 1 /* Configured */:
        this.configuredProjects.delete(project.canonicalConfigFilePath);
        this.projectToSizeMap.delete(project.canonicalConfigFilePath);
        break;
      case 0 /* Inferred */:
        unorderedRemoveItem(this.inferredProjects, project);
        break;
    }
  }
  /** @internal */
  assignOrphanScriptInfoToInferredProject(info, projectRootPath) {
    Debug.assert(info.isOrphan());
    const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot(
      info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath(
        isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath(
          info.fileName,
          projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory
        )
      )
    );
    project.addRoot(info);
    if (info.containingProjects[0] !== project) {
      orderedRemoveItem(info.containingProjects, project);
      info.containingProjects.unshift(project);
    }
    project.updateGraph();
    if (!this.useSingleInferredProject && !project.projectRootPath) {
      for (const inferredProject of this.inferredProjects) {
        if (inferredProject === project || inferredProject.isOrphan()) {
          continue;
        }
        const roots = inferredProject.getRootScriptInfos();
        Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath);
        if (roots.length === 1 && forEach(roots[0].containingProjects, (p) => p !== roots[0].containingProjects[0] && !p.isOrphan())) {
          inferredProject.removeFile(
            roots[0],
            /*fileExists*/
            true,
            /*detachFromProject*/
            true
          );
        }
      }
    }
    return project;
  }
  assignOrphanScriptInfosToInferredProject() {
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      if (info.isOrphan()) {
        this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
      }
    });
  }
  /**
   * Remove this file from the set of open, non-configured files.
   * @param info The file that has been closed or newly configured
   */
  closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) {
    var _a;
    const fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName);
    info.close(fileExists);
    this.stopWatchingConfigFilesForScriptInfo(info);
    const canonicalFileName = this.toCanonicalFileName(info.fileName);
    if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) {
      this.openFilesWithNonRootedDiskPath.delete(canonicalFileName);
    }
    let ensureProjectsForOpenFiles = false;
    for (const p of info.containingProjects) {
      if (isConfiguredProject(p)) {
        if (info.hasMixedContent) {
          info.registerFileUpdate();
        }
        const updateLevel = p.openFileWatchTriggered.get(info.path);
        if (updateLevel !== void 0) {
          p.openFileWatchTriggered.delete(info.path);
          if (p.pendingUpdateLevel < updateLevel) {
            p.pendingUpdateLevel = updateLevel;
            p.markFileAsDirty(info.path);
          }
        }
      } else if (isInferredProject(p) && p.isRoot(info)) {
        if (p.isProjectWithSingleRoot()) {
          ensureProjectsForOpenFiles = true;
        }
        p.removeFile(
          info,
          fileExists,
          /*detachFromProject*/
          true
        );
      }
      if (!p.languageServiceEnabled) {
        p.markAsDirty();
      }
    }
    this.openFiles.delete(info.path);
    this.configFileForOpenFiles.delete(info.path);
    (_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(info.path);
    Debug.assert(!this.rootOfInferredProjects.has(info));
    if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
      this.assignOrphanScriptInfosToInferredProject();
    }
    if (fileExists) {
      this.watchClosedScriptInfo(info);
    } else {
      this.handleDeletedFile(
        info,
        /*deferredDelete*/
        false
      );
    }
    return ensureProjectsForOpenFiles;
  }
  deleteScriptInfo(info) {
    Debug.assert(!info.isScriptOpen());
    this.filenameToScriptInfo.delete(info.path);
    this.filenameToScriptInfoVersion.set(info.path, info.textStorage.version);
    this.stopWatchingScriptInfo(info);
    const realpath = info.getRealpathIfDifferent();
    if (realpath) {
      this.realpathToScriptInfos.remove(realpath, info);
    }
    info.closeSourceMapFileWatcher();
  }
  configFileExists(configFileName, canonicalConfigFilePath, info) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    let openFilesImpactedByConfigFile;
    if (this.openFiles.has(info.path) && (!isAncestorConfigFileInfo(info) || info.isForDefaultProject)) {
      if (configFileExistenceInfo) (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path);
      else (openFilesImpactedByConfigFile = /* @__PURE__ */ new Set()).add(info.path);
    }
    if (configFileExistenceInfo) return configFileExistenceInfo.exists;
    const exists = this.host.fileExists(configFileName);
    this.configFileExistenceInfoCache.set(canonicalConfigFilePath, { exists, openFilesImpactedByConfigFile });
    return exists;
  }
  createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, forProject) {
    var _a, _b;
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) {
      configFileExistenceInfo.watcher = this.watchFactory.watchFile(
        configFileName,
        (_fileName, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind),
        2e3 /* High */,
        this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions, getDirectoryPath(configFileName)),
        WatchType.ConfigFile,
        forProject
      );
    }
    this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject);
  }
  ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject) {
    const projects = configFileExistenceInfo.config.projects;
    projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false);
  }
  /** @internal */
  releaseParsedConfig(canonicalConfigFilePath, forProject) {
    var _a, _b, _c;
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) return;
    if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size) return;
    configFileExistenceInfo.config = void 0;
    clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers);
    Debug.checkDefined(configFileExistenceInfo.watcher);
    if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) {
      if (configFileExistenceInfo.inferredProjectRoots) {
        if (!canWatchDirectoryOrFilePath(getDirectoryPath(canonicalConfigFilePath))) {
          configFileExistenceInfo.watcher.close();
          configFileExistenceInfo.watcher = noopConfigFileWatcher;
        }
      } else {
        configFileExistenceInfo.watcher.close();
        configFileExistenceInfo.watcher = void 0;
      }
    } else {
      configFileExistenceInfo.watcher.close();
      this.configFileExistenceInfoCache.delete(canonicalConfigFilePath);
    }
  }
  /**
   * This is called on file close or when its removed from inferred project as root,
   * so that we handle the watches and inferred project root data
   * @internal
   */
  stopWatchingConfigFilesForScriptInfo(info) {
    if (this.serverMode !== 0 /* Semantic */) return;
    const isRootOfInferredProject = this.rootOfInferredProjects.delete(info);
    const isOpen = info.isScriptOpen();
    if (isOpen && !isRootOfInferredProject) return;
    this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => {
      var _a, _b, _c;
      const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
      if (!configFileExistenceInfo) return;
      if (isOpen) {
        if (!((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) return;
      } else {
        if (!((_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path))) return;
      }
      if (isRootOfInferredProject) {
        configFileExistenceInfo.inferredProjectRoots--;
        if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !configFileExistenceInfo.inferredProjectRoots) {
          configFileExistenceInfo.watcher.close();
          configFileExistenceInfo.watcher = void 0;
        }
      }
      if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) {
        Debug.assert(!configFileExistenceInfo.watcher);
        this.configFileExistenceInfoCache.delete(canonicalConfigFilePath);
      }
    });
  }
  /**
   * This is called by inferred project whenever script info is added as a root
   *
   * @internal
   */
  startWatchingConfigFilesForInferredProjectRoot(info) {
    if (this.serverMode !== 0 /* Semantic */) return;
    Debug.assert(info.isScriptOpen());
    this.rootOfInferredProjects.add(info);
    this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => {
      let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
      if (!configFileExistenceInfo) {
        configFileExistenceInfo = { exists: this.host.fileExists(configFileName), inferredProjectRoots: 1 };
        this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
      } else {
        configFileExistenceInfo.inferredProjectRoots = (configFileExistenceInfo.inferredProjectRoots ?? 0) + 1;
      }
      (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path);
      configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFilePath(getDirectoryPath(canonicalConfigFilePath)) ? this.watchFactory.watchFile(
        configFileName,
        (_filename, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind),
        2e3 /* High */,
        this.hostConfiguration.watchOptions,
        WatchType.ConfigFileForInferredRoot
      ) : noopConfigFileWatcher);
    });
  }
  /**
   * This function tries to search for a tsconfig.json for the given file.
   * This is different from the method the compiler uses because
   * the compiler can assume it will always start searching in the
   * current directory (the directory in which tsc was invoked).
   * The server must start searching from the directory containing
   * the newly opened file.
   */
  forEachConfigFileLocation(info, action) {
    if (this.serverMode !== 0 /* Semantic */) {
      return void 0;
    }
    Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path));
    const projectRootPath = this.openFiles.get(info.path);
    const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path));
    if (scriptInfo.isDynamic) return void 0;
    let searchPath = asNormalizedPath(getDirectoryPath(info.fileName));
    const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames);
    const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
    let searchTsconfig = true;
    let searchJsconfig = true;
    if (isAncestorConfigFileInfo(info)) {
      if (endsWith(info.fileName, "tsconfig.json")) searchTsconfig = false;
      else searchTsconfig = searchJsconfig = false;
    }
    do {
      const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
      if (searchTsconfig) {
        const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json"));
        const result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName);
        if (result) return tsconfigFileName;
      }
      if (searchJsconfig) {
        const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json"));
        const result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName);
        if (result) return jsconfigFileName;
      }
      if (isNodeModulesDirectory(canonicalSearchPath)) {
        break;
      }
      const parentPath = asNormalizedPath(getDirectoryPath(searchPath));
      if (parentPath === searchPath) break;
      searchPath = parentPath;
      searchTsconfig = searchJsconfig = true;
    } while (anySearchPathOk || isSearchPathInProjectRoot());
    return void 0;
  }
  /** @internal */
  findDefaultConfiguredProject(info) {
    var _a;
    return (_a = this.findDefaultConfiguredProjectWorker(
      info,
      1 /* Find */
    )) == null ? void 0 : _a.defaultProject;
  }
  /** @internal */
  findDefaultConfiguredProjectWorker(info, kind) {
    return info.isScriptOpen() ? this.tryFindDefaultConfiguredProjectForOpenScriptInfo(
      info,
      kind
    ) : void 0;
  }
  /** Get cached configFileName for scriptInfo or ancestor of open script info */
  getConfigFileNameForFileFromCache(info, lookInPendingFilesForValue) {
    if (lookInPendingFilesForValue) {
      const result = getConfigFileNameFromCache(info, this.pendingOpenFileProjectUpdates);
      if (result !== void 0) return result;
    }
    return getConfigFileNameFromCache(info, this.configFileForOpenFiles);
  }
  /** Caches the configFilename for script info or ancestor of open script info */
  setConfigFileNameForFileInCache(info, configFileName) {
    if (!this.openFiles.has(info.path)) return;
    const config = configFileName || false;
    if (!isAncestorConfigFileInfo(info)) {
      this.configFileForOpenFiles.set(info.path, config);
    } else {
      let configFileForOpenFile = this.configFileForOpenFiles.get(info.path);
      if (!configFileForOpenFile || isString(configFileForOpenFile)) {
        this.configFileForOpenFiles.set(
          info.path,
          configFileForOpenFile = (/* @__PURE__ */ new Map()).set(false, configFileForOpenFile)
        );
      }
      configFileForOpenFile.set(info.fileName, config);
    }
  }
  /**
   * This function tries to search for a tsconfig.json for the given file.
   * This is different from the method the compiler uses because
   * the compiler can assume it will always start searching in the
   * current directory (the directory in which tsc was invoked).
   * The server must start searching from the directory containing
   * the newly opened file.
   * If script info is passed in, it is asserted to be open script info
   * otherwise just file name
   * when findFromCacheOnly is true only looked up in cache instead of hitting disk to figure things out
   * @internal
   */
  getConfigFileNameForFile(info, findFromCacheOnly) {
    const fromCache = this.getConfigFileNameForFileFromCache(info, findFromCacheOnly);
    if (fromCache !== void 0) return fromCache || void 0;
    if (findFromCacheOnly) return void 0;
    const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info));
    this.logger.info(`getConfigFileNameForFile:: File: ${info.fileName} ProjectRootPath: ${this.openFiles.get(info.path)}:: Result: ${configFileName}`);
    this.setConfigFileNameForFileInCache(info, configFileName);
    return configFileName;
  }
  printProjects() {
    if (!this.logger.hasLevel(1 /* normal */)) {
      return;
    }
    this.logger.startGroup();
    this.externalProjects.forEach(printProjectWithoutFileNames);
    this.configuredProjects.forEach(printProjectWithoutFileNames);
    this.inferredProjects.forEach(printProjectWithoutFileNames);
    this.logger.info("Open files: ");
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      this.logger.info(`	FileName: ${info.fileName} ProjectRootPath: ${projectRootPath}`);
      this.logger.info(`		Projects: ${info.containingProjects.map((p) => p.getProjectName())}`);
    });
    this.logger.endGroup();
  }
  /** @internal */
  findConfiguredProjectByProjectName(configFileName, allowDeferredClosed) {
    const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName));
    const result = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
    return allowDeferredClosed ? result : !(result == null ? void 0 : result.deferredClose) ? result : void 0;
  }
  getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) {
    return this.configuredProjects.get(canonicalConfigFilePath);
  }
  findExternalProjectByProjectName(projectFileName) {
    return findProjectByName(projectFileName, this.externalProjects);
  }
  /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
  getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader) {
    if (options && options.disableSizeLimit || !this.host.getFileSize) {
      return;
    }
    let availableSpace = maxProgramSizeForNonTsFiles;
    this.projectToSizeMap.set(name, 0);
    this.projectToSizeMap.forEach((val) => availableSpace -= val || 0);
    let totalNonTsFileSize = 0;
    for (const f of fileNames) {
      const fileName = propertyReader.getFileName(f);
      if (hasTSFileExtension(fileName)) {
        continue;
      }
      totalNonTsFileSize += this.host.getFileSize(fileName);
      if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
        const top5LargestFiles = fileNames.map((f2) => propertyReader.getFileName(f2)).filter((name2) => !hasTSFileExtension(name2)).map((name2) => ({ name: name2, size: this.host.getFileSize(name2) })).sort((a, b) => b.size - a.size).slice(0, 5);
        this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map((file) => `${file.name}:${file.size}`).join(", ")}`);
        return fileName;
      }
    }
    this.projectToSizeMap.set(name, totalNonTsFileSize);
  }
  createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) {
    const compilerOptions = convertCompilerOptions(options);
    const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName)));
    const project = new ExternalProject(
      projectFileName,
      this,
      compilerOptions,
      /*lastFileExceededProgramSize*/
      this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader),
      options.compileOnSave === void 0 ? true : options.compileOnSave,
      /*projectFilePath*/
      void 0,
      watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions
    );
    project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
    project.excludedFiles = excludedFiles;
    this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
    this.externalProjects.push(project);
    return project;
  }
  /** @internal */
  sendProjectTelemetry(project) {
    if (this.seenProjects.has(project.projectName)) {
      setProjectOptionsUsed(project);
      return;
    }
    this.seenProjects.set(project.projectName, true);
    if (!this.eventHandler || !this.host.createSHA256Hash) {
      setProjectOptionsUsed(project);
      return;
    }
    const projectOptions = isConfiguredProject(project) ? project.projectOptions : void 0;
    setProjectOptionsUsed(project);
    const data = {
      projectId: this.host.createSHA256Hash(project.projectName),
      fileStats: countEachFileTypes(
        project.getScriptInfos(),
        /*includeSizes*/
        true
      ),
      compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
      typeAcquisition: convertTypeAcquisition2(project.getTypeAcquisition()),
      extends: projectOptions && projectOptions.configHasExtendsProperty,
      files: projectOptions && projectOptions.configHasFilesProperty,
      include: projectOptions && projectOptions.configHasIncludeProperty,
      exclude: projectOptions && projectOptions.configHasExcludeProperty,
      compileOnSave: project.compileOnSaveEnabled,
      configFileName: configFileName(),
      projectType: project instanceof ExternalProject ? "external" : "configured",
      languageServiceEnabled: project.languageServiceEnabled,
      version
    };
    this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data });
    function configFileName() {
      if (!isConfiguredProject(project)) {
        return "other";
      }
      return getBaseConfigFileName(project.getConfigFilePath()) || "other";
    }
    function convertTypeAcquisition2({ enable: enable2, include, exclude }) {
      return {
        enable: enable2,
        include: include !== void 0 && include.length !== 0,
        exclude: exclude !== void 0 && exclude.length !== 0
      };
    }
  }
  addFilesToNonInferredProject(project, files, propertyReader, typeAcquisition) {
    this.updateNonInferredProjectFiles(project, files, propertyReader);
    project.setTypeAcquisition(typeAcquisition);
    project.markAsDirty();
  }
  /** @internal */
  createConfiguredProject(configFileName, reason) {
    var _a;
    (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName });
    const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName));
    let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo) {
      this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true });
    } else {
      configFileExistenceInfo.exists = true;
    }
    if (!configFileExistenceInfo.config) {
      configFileExistenceInfo.config = {
        cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames),
        projects: /* @__PURE__ */ new Map(),
        updateLevel: 2 /* Full */
      };
    }
    const project = new ConfiguredProject2(
      configFileName,
      canonicalConfigFilePath,
      this,
      configFileExistenceInfo.config.cachedDirectoryStructureHost,
      reason
    );
    Debug.assert(!this.configuredProjects.has(canonicalConfigFilePath));
    this.configuredProjects.set(canonicalConfigFilePath, project);
    this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project);
    return project;
  }
  /**
   * Read the config file of the project, and update the project root file names.
   */
  loadConfiguredProject(project, reason) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath });
    this.sendProjectLoadingStartEvent(project, reason);
    const configFilename = toNormalizedPath(project.getConfigFilePath());
    const configFileExistenceInfo = this.ensureParsedConfigUptoDate(
      configFilename,
      project.canonicalConfigFilePath,
      this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath),
      project
    );
    const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine;
    Debug.assert(!!parsedCommandLine.fileNames);
    const compilerOptions = parsedCommandLine.options;
    if (!project.projectOptions) {
      project.projectOptions = {
        configHasExtendsProperty: parsedCommandLine.raw.extends !== void 0,
        configHasFilesProperty: parsedCommandLine.raw.files !== void 0,
        configHasIncludeProperty: parsedCommandLine.raw.include !== void 0,
        configHasExcludeProperty: parsedCommandLine.raw.exclude !== void 0
      };
    }
    project.parsedCommandLine = parsedCommandLine;
    project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics);
    project.updateReferences(parsedCommandLine.projectReferences);
    const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader);
    if (lastFileExceededProgramSize) {
      project.disableLanguageService(lastFileExceededProgramSize);
      this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.stopWatchingWildCards(canonicalConfigFilePath, project));
    } else {
      project.setCompilerOptions(compilerOptions);
      project.setWatchOptions(parsedCommandLine.watchOptions);
      project.enableLanguageService();
      this.watchWildcards(configFilename, configFileExistenceInfo, project);
    }
    project.enablePluginsWithOptions(compilerOptions);
    const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles(2 /* Full */));
    this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  /** @internal */
  ensureParsedConfigUptoDate(configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) {
    var _a, _b, _c;
    if (configFileExistenceInfo.config) {
      if (configFileExistenceInfo.config.updateLevel === 1 /* RootNamesAndUpdate */) {
        this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config);
      }
      if (!configFileExistenceInfo.config.updateLevel) {
        this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject);
        return configFileExistenceInfo;
      }
    }
    if (!configFileExistenceInfo.exists && configFileExistenceInfo.config) {
      configFileExistenceInfo.config.updateLevel = void 0;
      this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject);
      return configFileExistenceInfo;
    }
    const cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.cachedDirectoryStructureHost) || createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames);
    const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName));
    const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : "");
    const configFileErrors = configFile.parseDiagnostics;
    if (!isString(configFileContent)) configFileErrors.push(configFileContent);
    const configDir = getDirectoryPath(configFilename);
    const parsedCommandLine = parseJsonSourceFileConfigFileContent(
      configFile,
      cachedDirectoryStructureHost,
      configDir,
      /*existingOptions*/
      void 0,
      configFilename,
      /*resolutionStack*/
      void 0,
      this.hostConfiguration.extraFileExtensions,
      this.extendedConfigCache
    );
    if (parsedCommandLine.errors.length) {
      configFileErrors.push(...parsedCommandLine.errors);
    }
    this.logger.info(`Config: ${configFilename} : ${JSON.stringify(
      {
        rootNames: parsedCommandLine.fileNames,
        options: parsedCommandLine.options,
        watchOptions: parsedCommandLine.watchOptions,
        projectReferences: parsedCommandLine.projectReferences
      },
      /*replacer*/
      void 0,
      " "
    )}`);
    const oldCommandLine = (_b = configFileExistenceInfo.config) == null ? void 0 : _b.parsedCommandLine;
    if (!configFileExistenceInfo.config) {
      configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: /* @__PURE__ */ new Map() };
    } else {
      configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine;
      configFileExistenceInfo.config.watchedDirectoriesStale = true;
      configFileExistenceInfo.config.updateLevel = void 0;
    }
    if (!oldCommandLine && !isJsonEqual(
      // Old options
      this.getWatchOptionsFromProjectWatchOptions(
        /*projectOptions*/
        void 0,
        configDir
      ),
      // New options
      this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions, configDir)
    )) {
      (_c = configFileExistenceInfo.watcher) == null ? void 0 : _c.close();
      configFileExistenceInfo.watcher = void 0;
    }
    this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject);
    updateSharedExtendedConfigFileWatcher(
      canonicalConfigFilePath,
      parsedCommandLine.options,
      this.sharedExtendedConfigFileWatchers,
      (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile(
        extendedConfigFileName,
        () => {
          var _a2;
          cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, (fileName) => this.toPath(fileName));
          let ensureProjectsForOpenFiles = false;
          (_a2 = this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((canonicalPath) => {
            ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles;
          });
          if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles();
        },
        2e3 /* High */,
        this.hostConfiguration.watchOptions,
        WatchType.ExtendedConfigFile,
        configFilename
      ),
      (fileName) => this.toPath(fileName)
    );
    return configFileExistenceInfo;
  }
  /** @internal */
  watchWildcards(configFileName, { exists, config }, forProject) {
    config.projects.set(forProject.canonicalConfigFilePath, true);
    if (exists) {
      if (config.watchedDirectories && !config.watchedDirectoriesStale) return;
      config.watchedDirectoriesStale = false;
      updateWatchingWildcardDirectories(
        config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */ new Map()),
        config.parsedCommandLine.wildcardDirectories,
        // Create new directory watcher
        (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config)
      );
    } else {
      config.watchedDirectoriesStale = false;
      if (!config.watchedDirectories) return;
      clearMap(config.watchedDirectories, closeFileWatcherOf);
      config.watchedDirectories = void 0;
    }
  }
  /** @internal */
  stopWatchingWildCards(canonicalConfigFilePath, forProject) {
    const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
    if (!configFileExistenceInfo.config || !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) {
      return;
    }
    configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false);
    if (forEachEntry(configFileExistenceInfo.config.projects, identity)) return;
    if (configFileExistenceInfo.config.watchedDirectories) {
      clearMap(configFileExistenceInfo.config.watchedDirectories, closeFileWatcherOf);
      configFileExistenceInfo.config.watchedDirectories = void 0;
    }
    configFileExistenceInfo.config.watchedDirectoriesStale = void 0;
  }
  updateNonInferredProjectFiles(project, files, propertyReader) {
    var _a;
    const projectRootFilesMap = project.getRootFilesMap();
    const newRootScriptInfoMap = /* @__PURE__ */ new Map();
    for (const f of files) {
      const newRootFile = propertyReader.getFileName(f);
      const fileName = toNormalizedPath(newRootFile);
      const isDynamic = isDynamicFileName(fileName);
      let path;
      if (!isDynamic && !project.fileExists(newRootFile)) {
        path = normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName);
        const existingValue = projectRootFilesMap.get(path);
        if (existingValue) {
          if (((_a = existingValue.info) == null ? void 0 : _a.path) === path) {
            project.removeFile(
              existingValue.info,
              /*fileExists*/
              false,
              /*detachFromProject*/
              true
            );
            existingValue.info = void 0;
          }
          existingValue.fileName = fileName;
        } else {
          projectRootFilesMap.set(path, { fileName });
        }
      } else {
        const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
        const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
        const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
          fileName,
          project.currentDirectory,
          scriptKind,
          hasMixedContent,
          project.directoryStructureHost,
          /*deferredDeleteOk*/
          false
        ));
        path = scriptInfo.path;
        const existingValue = projectRootFilesMap.get(path);
        if (!existingValue || existingValue.info !== scriptInfo) {
          project.addRoot(scriptInfo, fileName);
          if (scriptInfo.isScriptOpen()) {
            this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo);
          }
        } else {
          existingValue.fileName = fileName;
        }
      }
      newRootScriptInfoMap.set(path, true);
    }
    if (projectRootFilesMap.size > newRootScriptInfoMap.size) {
      projectRootFilesMap.forEach((value, path) => {
        if (!newRootScriptInfoMap.has(path)) {
          if (value.info) {
            project.removeFile(
              value.info,
              project.fileExists(value.info.fileName),
              /*detachFromProject*/
              true
            );
          } else {
            projectRootFilesMap.delete(path);
          }
        }
      });
    }
  }
  updateRootAndOptionsOfNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, watchOptions) {
    project.setCompilerOptions(newOptions);
    project.setWatchOptions(watchOptions);
    if (compileOnSave !== void 0) {
      project.compileOnSaveEnabled = compileOnSave;
    }
    this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition);
  }
  /**
   * Reload the file names from config file specs and update the project graph
   *
   * @internal
   */
  reloadFileNamesOfConfiguredProject(project) {
    const config = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config);
    project.updateErrorOnNoInputFiles(config);
    this.updateNonInferredProjectFiles(
      project,
      config.fileNames.concat(project.getExternalFiles(1 /* RootNamesAndUpdate */)),
      fileNamePropertyReader
    );
    project.markAsDirty();
    return project.updateGraph();
  }
  reloadFileNamesOfParsedConfig(configFileName, config) {
    if (config.updateLevel === void 0) return config.parsedCommandLine;
    Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */);
    const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs;
    const fileNames = getFileNamesFromConfigSpecs(
      configFileSpecs,
      getDirectoryPath(configFileName),
      config.parsedCommandLine.options,
      config.cachedDirectoryStructureHost,
      this.hostConfiguration.extraFileExtensions
    );
    config.parsedCommandLine = { ...config.parsedCommandLine, fileNames };
    config.updateLevel = void 0;
    return config.parsedCommandLine;
  }
  /** @internal */
  setFileNamesOfAutoImportProviderOrAuxillaryProject(project, fileNames) {
    this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader);
  }
  /** @internal */
  reloadConfiguredProjectOptimized(project, reason, reloadedProjects) {
    if (reloadedProjects.has(project)) return;
    reloadedProjects.set(project, 6 /* ReloadOptimized */);
    if (!project.initialLoadPending) {
      this.setProjectForReload(project, 2 /* Full */, reason);
    }
  }
  /** @internal */
  reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects) {
    if (reloadedProjects.get(project) === 7 /* Reload */) return false;
    reloadedProjects.set(project, 7 /* Reload */);
    this.clearSemanticCache(project);
    this.reloadConfiguredProject(project, reloadReason(reason));
    return true;
  }
  setProjectForReload(project, updateLevel, reason) {
    if (updateLevel === 2 /* Full */) this.clearSemanticCache(project);
    project.pendingUpdateReason = reason && reloadReason(reason);
    project.pendingUpdateLevel = updateLevel;
  }
  /**
   * Read the config file of the project again by clearing the cache and update the project graph
   *
   * @internal
   */
  reloadConfiguredProject(project, reason) {
    project.initialLoadPending = false;
    this.setProjectForReload(project, 0 /* Update */);
    this.loadConfiguredProject(project, reason);
    updateWithTriggerFile(
      project,
      project.triggerFileForConfigFileDiag ?? project.getConfigFilePath(),
      /*isReload*/
      true
    );
  }
  clearSemanticCache(project) {
    project.originalConfiguredProjects = void 0;
    project.resolutionCache.clear();
    project.getLanguageService(
      /*ensureSynchronized*/
      false
    ).cleanupSemanticCache();
    project.cleanupProgram();
    project.markAsDirty();
  }
  /** @internal */
  sendConfigFileDiagEvent(project, triggerFile, force) {
    if (!this.eventHandler || this.suppressDiagnosticEvents) return false;
    const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics();
    diagnostics.push(...project.getAllProjectErrors());
    if (!force && diagnostics.length === (project.configDiagDiagnosticsReported ?? 0)) return false;
    project.configDiagDiagnosticsReported = diagnostics.length;
    this.eventHandler(
      {
        eventName: ConfigFileDiagEvent,
        data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile: triggerFile ?? project.getConfigFilePath() }
      }
    );
    return true;
  }
  getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) {
    if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root
    info.isDynamic && projectRootPath === void 0) {
      return void 0;
    }
    if (projectRootPath) {
      const canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath);
      for (const project of this.inferredProjects) {
        if (project.projectRootPath === canonicalProjectRootPath) {
          return project;
        }
      }
      return this.createInferredProject(
        projectRootPath,
        /*isSingleInferredProject*/
        false,
        projectRootPath
      );
    }
    let bestMatch;
    for (const project of this.inferredProjects) {
      if (!project.projectRootPath) continue;
      if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue;
      if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue;
      bestMatch = project;
    }
    return bestMatch;
  }
  getOrCreateSingleInferredProjectIfEnabled() {
    if (!this.useSingleInferredProject) {
      return void 0;
    }
    if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === void 0) {
      return this.inferredProjects[0];
    }
    return this.createInferredProject(
      this.currentDirectory,
      /*isSingleInferredProject*/
      true,
      /*projectRootPath*/
      void 0
    );
  }
  getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) {
    Debug.assert(!this.useSingleInferredProject);
    const expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory));
    for (const inferredProject of this.inferredProjects) {
      if (!inferredProject.projectRootPath && inferredProject.isOrphan() && inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) {
        return inferredProject;
      }
    }
    return this.createInferredProject(
      currentDirectory,
      /*isSingleInferredProject*/
      false,
      /*projectRootPath*/
      void 0
    );
  }
  createInferredProject(currentDirectory, isSingleInferredProject, projectRootPath) {
    const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
    let watchOptionsAndErrors;
    let typeAcquisition;
    if (projectRootPath) {
      watchOptionsAndErrors = this.watchOptionsForInferredProjectsPerProjectRoot.get(projectRootPath);
      typeAcquisition = this.typeAcquisitionForInferredProjectsPerProjectRoot.get(projectRootPath);
    }
    if (watchOptionsAndErrors === void 0) {
      watchOptionsAndErrors = this.watchOptionsForInferredProjects;
    }
    if (typeAcquisition === void 0) {
      typeAcquisition = this.typeAcquisitionForInferredProjects;
    }
    watchOptionsAndErrors = watchOptionsAndErrors || void 0;
    const project = new InferredProject2(
      this,
      compilerOptions,
      watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions,
      projectRootPath,
      currentDirectory,
      typeAcquisition
    );
    project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
    if (isSingleInferredProject) {
      this.inferredProjects.unshift(project);
    } else {
      this.inferredProjects.push(project);
    }
    return project;
  }
  /** @internal */
  getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName, currentDirectory, hostToQueryFileExistsOn, deferredDeleteOk) {
    return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
      toNormalizedPath(uncheckedFileName),
      currentDirectory,
      /*scriptKind*/
      void 0,
      /*hasMixedContent*/
      void 0,
      hostToQueryFileExistsOn,
      deferredDeleteOk
    );
  }
  getScriptInfo(uncheckedFileName) {
    return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
  }
  /** @internal */
  getScriptInfoOrConfig(uncheckedFileName) {
    const path = toNormalizedPath(uncheckedFileName);
    const info = this.getScriptInfoForNormalizedPath(path);
    if (info) return info;
    const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
    return configProject && configProject.getCompilerOptions().configFile;
  }
  /** @internal */
  logErrorForScriptInfoNotFound(fileName) {
    const names = arrayFrom(
      mapDefinedIterator(
        this.filenameToScriptInfo.entries(),
        (entry) => entry[1].deferredDelete ? void 0 : entry
      ),
      ([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName })
    );
    this.logger.msg(`Could not find file ${JSON.stringify(fileName)}.
All files are: ${JSON.stringify(names)}`, "Err" /* Err */);
  }
  /**
   * Returns the projects that contain script info through SymLink
   * Note that this does not return projects in info.containingProjects
   *
   * @internal
   */
  getSymlinkedProjects(info) {
    let projects;
    if (this.realpathToScriptInfos) {
      const realpath = info.getRealpathIfDifferent();
      if (realpath) {
        forEach(this.realpathToScriptInfos.get(realpath), combineProjects);
      }
      forEach(this.realpathToScriptInfos.get(info.path), combineProjects);
    }
    return projects;
    function combineProjects(toAddInfo) {
      if (toAddInfo !== info) {
        for (const project of toAddInfo.containingProjects) {
          if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && !info.isAttached(project)) {
            if (!projects) {
              projects = createMultiMap();
              projects.add(toAddInfo.path, project);
            } else if (!forEachEntry(projects, (projs, path) => path === toAddInfo.path ? false : contains(projs, project))) {
              projects.add(toAddInfo.path, project);
            }
          }
        }
      }
    }
  }
  watchClosedScriptInfo(info) {
    Debug.assert(!info.fileWatcher);
    if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
      const indexOfNodeModules = info.fileName.indexOf("/node_modules/");
      if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
        info.fileWatcher = this.watchFactory.watchFile(
          info.fileName,
          (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind),
          500 /* Medium */,
          this.hostConfiguration.watchOptions,
          WatchType.ClosedScriptInfo
        );
      } else {
        info.mTime = this.getModifiedTime(info);
        info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.fileName.substring(0, indexOfNodeModules));
      }
    }
  }
  createNodeModulesWatcher(dir, dirPath) {
    let watcher = this.watchFactory.watchDirectory(
      dir,
      (fileOrDirectory) => {
        var _a;
        const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory));
        if (!fileOrDirectoryPath) return;
        const basename = getBaseFileName(fileOrDirectoryPath);
        if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename === "package.json" || basename === "node_modules")) {
          result.affectedModuleSpecifierCacheProjects.forEach((project) => {
            var _a2;
            (_a2 = project.getModuleSpecifierCache()) == null ? void 0 : _a2.clear();
          });
        }
        if (result.refreshScriptInfoRefCount) {
          if (dirPath === fileOrDirectoryPath) {
            this.refreshScriptInfosInDirectory(dirPath);
          } else {
            const info = this.filenameToScriptInfo.get(fileOrDirectoryPath);
            if (info) {
              if (isScriptInfoWatchedFromNodeModules(info)) {
                this.refreshScriptInfo(info);
              }
            } else if (!hasExtension(fileOrDirectoryPath)) {
              this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
            }
          }
        }
      },
      1 /* Recursive */,
      this.hostConfiguration.watchOptions,
      WatchType.NodeModules
    );
    const result = {
      refreshScriptInfoRefCount: 0,
      affectedModuleSpecifierCacheProjects: void 0,
      close: () => {
        var _a;
        if (watcher && !result.refreshScriptInfoRefCount && !((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size)) {
          watcher.close();
          watcher = void 0;
          this.nodeModulesWatchers.delete(dirPath);
        }
      }
    };
    this.nodeModulesWatchers.set(dirPath, result);
    return result;
  }
  /** @internal */
  watchPackageJsonsInNodeModules(dir, project) {
    var _a;
    const dirPath = this.toPath(dir);
    const watcher = this.nodeModulesWatchers.get(dirPath) || this.createNodeModulesWatcher(dir, dirPath);
    Debug.assert(!((_a = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.has(project)));
    (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */ new Set())).add(project);
    return {
      close: () => {
        var _a2;
        (_a2 = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a2.delete(project);
        watcher.close();
      }
    };
  }
  watchClosedScriptInfoInNodeModules(dir) {
    const watchDir = dir + "/node_modules";
    const watchDirPath = this.toPath(watchDir);
    const watcher = this.nodeModulesWatchers.get(watchDirPath) || this.createNodeModulesWatcher(watchDir, watchDirPath);
    watcher.refreshScriptInfoRefCount++;
    return {
      close: () => {
        watcher.refreshScriptInfoRefCount--;
        watcher.close();
      }
    };
  }
  getModifiedTime(info) {
    return (this.host.getModifiedTime(info.fileName) || missingFileModifiedTime).getTime();
  }
  refreshScriptInfo(info) {
    const mTime = this.getModifiedTime(info);
    if (mTime !== info.mTime) {
      const eventKind = getFileWatcherEventKind(info.mTime, mTime);
      info.mTime = mTime;
      this.onSourceFileChanged(info, eventKind);
    }
  }
  refreshScriptInfosInDirectory(dir) {
    dir = dir + directorySeparator;
    this.filenameToScriptInfo.forEach((info) => {
      if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) {
        this.refreshScriptInfo(info);
      }
    });
  }
  stopWatchingScriptInfo(info) {
    if (info.fileWatcher) {
      info.fileWatcher.close();
      info.fileWatcher = void 0;
    }
  }
  getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn, deferredDeleteOk) {
    if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) {
      return this.getOrCreateScriptInfoWorker(
        fileName,
        currentDirectory,
        /*openedByClient*/
        false,
        /*fileContent*/
        void 0,
        scriptKind,
        !!hasMixedContent,
        hostToQueryFileExistsOn,
        deferredDeleteOk
      );
    }
    const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
    if (info) {
      return info;
    }
    return void 0;
  }
  getOrCreateScriptInfoForNormalizedPath(fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
    return this.getOrCreateScriptInfoWorker(
      fileName,
      this.currentDirectory,
      openedByClient,
      fileContent,
      scriptKind,
      !!hasMixedContent,
      hostToQueryFileExistsOn,
      /*deferredDeleteOk*/
      false
    );
  }
  getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn, deferredDeleteOk) {
    Debug.assert(fileContent === void 0 || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content");
    const path = normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName);
    let info = this.filenameToScriptInfo.get(path);
    if (!info) {
      const isDynamic = isDynamicFileName(fileName);
      Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Script info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`);
      Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Open script files with non rooted disk path opened with current directory context cannot have same canonical names`);
      Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}
Dynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`);
      if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
        return;
      }
      info = new ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path, this.filenameToScriptInfoVersion.get(path));
      this.filenameToScriptInfo.set(info.path, info);
      this.filenameToScriptInfoVersion.delete(info.path);
      if (!openedByClient) {
        this.watchClosedScriptInfo(info);
      } else if (!isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) {
        this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info);
      }
    } else if (info.deferredDelete) {
      Debug.assert(!info.isDynamic);
      if (!openedByClient && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
        return deferredDeleteOk ? info : void 0;
      }
      info.deferredDelete = void 0;
    }
    if (openedByClient) {
      this.stopWatchingScriptInfo(info);
      info.open(fileContent);
      if (hasMixedContent) {
        info.registerFileUpdate();
      }
    }
    return info;
  }
  /**
   * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred
   */
  getScriptInfoForNormalizedPath(fileName) {
    return !isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName));
  }
  getScriptInfoForPath(fileName) {
    const info = this.filenameToScriptInfo.get(fileName);
    return !info || !info.deferredDelete ? info : void 0;
  }
  /** @internal */
  getDocumentPositionMapper(project, generatedFileName, sourceFileName) {
    const declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(
      generatedFileName,
      project.currentDirectory,
      this.host,
      /*deferredDeleteOk*/
      false
    );
    if (!declarationInfo) {
      if (sourceFileName) {
        project.addGeneratedFileWatch(generatedFileName, sourceFileName);
      }
      return void 0;
    }
    declarationInfo.getSnapshot();
    if (isString(declarationInfo.sourceMapFilePath)) {
      const sourceMapFileInfo2 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
      if (sourceMapFileInfo2) {
        sourceMapFileInfo2.getSnapshot();
        if (sourceMapFileInfo2.documentPositionMapper !== void 0) {
          sourceMapFileInfo2.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo2.sourceInfos);
          return sourceMapFileInfo2.documentPositionMapper ? sourceMapFileInfo2.documentPositionMapper : void 0;
        }
      }
      declarationInfo.sourceMapFilePath = void 0;
    } else if (declarationInfo.sourceMapFilePath) {
      declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos);
      return void 0;
    } else if (declarationInfo.sourceMapFilePath !== void 0) {
      return void 0;
    }
    let sourceMapFileInfo;
    let readMapFile = (mapFileName, mapFileNameFromDts) => {
      const mapInfo = this.getOrCreateScriptInfoNotOpenedByClient(
        mapFileName,
        project.currentDirectory,
        this.host,
        /*deferredDeleteOk*/
        true
      );
      sourceMapFileInfo = mapInfo || mapFileNameFromDts;
      if (!mapInfo || mapInfo.deferredDelete) return void 0;
      const snap = mapInfo.getSnapshot();
      if (mapInfo.documentPositionMapper !== void 0) return mapInfo.documentPositionMapper;
      return getSnapshotText(snap);
    };
    const projectName = project.projectName;
    const documentPositionMapper = getDocumentPositionMapper(
      { getCanonicalFileName: this.toCanonicalFileName, log: (s) => this.logger.info(s), getSourceFileLike: (f) => this.getSourceFileLike(f, projectName, declarationInfo) },
      declarationInfo.fileName,
      declarationInfo.textStorage.getLineInfo(),
      readMapFile
    );
    readMapFile = void 0;
    if (sourceMapFileInfo) {
      if (!isString(sourceMapFileInfo)) {
        declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
        sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
        if (!sourceMapFileInfo.deferredDelete) sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false;
        sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos);
      } else {
        declarationInfo.sourceMapFilePath = {
          watcher: this.addMissingSourceMapFile(
            project.currentDirectory === this.currentDirectory ? sourceMapFileInfo : getNormalizedAbsolutePath(sourceMapFileInfo, project.currentDirectory),
            declarationInfo.path
          ),
          sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project)
        };
      }
    } else {
      declarationInfo.sourceMapFilePath = false;
    }
    return documentPositionMapper;
  }
  addSourceInfoToSourceMap(sourceFileName, project, sourceInfos) {
    if (sourceFileName) {
      const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(
        sourceFileName,
        project.currentDirectory,
        project.directoryStructureHost,
        /*deferredDeleteOk*/
        false
      );
      (sourceInfos || (sourceInfos = /* @__PURE__ */ new Set())).add(sourceInfo.path);
    }
    return sourceInfos;
  }
  addMissingSourceMapFile(mapFileName, declarationInfoPath) {
    const fileWatcher = this.watchFactory.watchFile(
      mapFileName,
      () => {
        const declarationInfo = this.getScriptInfoForPath(declarationInfoPath);
        if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) {
          this.delayUpdateProjectGraphs(
            declarationInfo.containingProjects,
            /*clearSourceMapperCache*/
            true
          );
          this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
          declarationInfo.closeSourceMapFileWatcher();
        }
      },
      2e3 /* High */,
      this.hostConfiguration.watchOptions,
      WatchType.MissingSourceMapFile
    );
    return fileWatcher;
  }
  /** @internal */
  getSourceFileLike(fileName, projectNameOrProject, declarationInfo) {
    const project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
    if (project) {
      const path = project.toPath(fileName);
      const sourceFile = project.getSourceFile(path);
      if (sourceFile && sourceFile.resolvedPath === path) return sourceFile;
    }
    const info = this.getOrCreateScriptInfoNotOpenedByClient(
      fileName,
      (project || this).currentDirectory,
      project ? project.directoryStructureHost : this.host,
      /*deferredDeleteOk*/
      false
    );
    if (!info) return void 0;
    if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
      const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
      if (sourceMapInfo) {
        (sourceMapInfo.sourceInfos ?? (sourceMapInfo.sourceInfos = /* @__PURE__ */ new Set())).add(info.path);
      }
    }
    if (info.cacheSourceFile) return info.cacheSourceFile.sourceFile;
    if (!info.sourceFileLike) {
      info.sourceFileLike = {
        get text() {
          Debug.fail("shouldnt need text");
          return "";
        },
        getLineAndCharacterOfPosition: (pos) => {
          const lineOffset = info.positionToLineOffset(pos);
          return { line: lineOffset.line - 1, character: lineOffset.offset - 1 };
        },
        getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits)
      };
    }
    return info.sourceFileLike;
  }
  /** @internal */
  setPerformanceEventHandler(performanceEventHandler) {
    this.performanceEventHandler = performanceEventHandler;
  }
  setHostConfiguration(args) {
    var _a;
    if (args.file) {
      const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file));
      if (info) {
        info.setOptions(convertFormatOptions(args.formatOptions), args.preferences);
        this.logger.info(`Host configuration update for file ${args.file}`);
      }
    } else {
      if (args.hostInfo !== void 0) {
        this.hostConfiguration.hostInfo = args.hostInfo;
        this.logger.info(`Host information ${args.hostInfo}`);
      }
      if (args.formatOptions) {
        this.hostConfiguration.formatCodeOptions = { ...this.hostConfiguration.formatCodeOptions, ...convertFormatOptions(args.formatOptions) };
        this.logger.info("Format host information updated");
      }
      if (args.preferences) {
        const {
          lazyConfiguredProjectsFromExternalProject,
          includePackageJsonAutoImports,
          includeCompletionsForModuleExports
        } = this.hostConfiguration.preferences;
        this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences };
        if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
          this.externalProjectToConfiguredProjectMap.forEach(
            (projects) => projects.forEach((project) => {
              if (!project.deferredClose && !project.isClosed() && project.pendingUpdateLevel === 2 /* Full */ && !this.hasPendingProjectUpdate(project)) {
                project.updateGraph();
              }
            })
          );
        }
        if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports || !!includeCompletionsForModuleExports !== !!args.preferences.includeCompletionsForModuleExports) {
          this.forEachProject((project) => {
            project.onAutoImportProviderSettingsChanged();
          });
        }
      }
      if (args.extraFileExtensions) {
        this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
        this.reloadProjects();
        this.logger.info("Host file extension mappings updated");
      }
      if (args.watchOptions) {
        const watchOptions = (_a = convertWatchOptions(args.watchOptions)) == null ? void 0 : _a.watchOptions;
        const substitution = handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, this.currentDirectory);
        this.hostConfiguration.watchOptions = substitution;
        this.hostConfiguration.beforeSubstitution = substitution === watchOptions ? void 0 : watchOptions;
        this.logger.info(`Host watch options changed to ${JSON.stringify(this.hostConfiguration.watchOptions)}, it will be take effect for next watches.`);
      }
    }
  }
  /** @internal */
  getWatchOptions(project) {
    return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions(), project.getCurrentDirectory());
  }
  getWatchOptionsFromProjectWatchOptions(projectOptions, basePath) {
    const hostWatchOptions = !this.hostConfiguration.beforeSubstitution ? this.hostConfiguration.watchOptions : handleWatchOptionsConfigDirTemplateSubstitution(
      this.hostConfiguration.beforeSubstitution,
      basePath
    );
    return projectOptions && hostWatchOptions ? { ...hostWatchOptions, ...projectOptions } : projectOptions || hostWatchOptions;
  }
  closeLog() {
    this.logger.close();
  }
  sendSourceFileChange(inPath) {
    this.filenameToScriptInfo.forEach((info) => {
      if (this.openFiles.has(info.path)) return;
      if (!info.fileWatcher) return;
      const eventKind = memoize(
        () => this.host.fileExists(info.fileName) ? info.deferredDelete ? 0 /* Created */ : 1 /* Changed */ : 2 /* Deleted */
      );
      if (inPath) {
        if (isScriptInfoWatchedFromNodeModules(info) || !info.path.startsWith(inPath)) return;
        if (eventKind() === 2 /* Deleted */ && info.deferredDelete) return;
        this.logger.info(`Invoking sourceFileChange on ${info.fileName}:: ${eventKind()}`);
      }
      this.onSourceFileChanged(
        info,
        eventKind()
      );
    });
  }
  /**
   * This function rebuilds the project for every file opened by the client
   * This does not reload contents of open files from disk. But we could do that if needed
   */
  reloadProjects() {
    this.logger.info("reload projects.");
    this.sendSourceFileChange(
      /*inPath*/
      void 0
    );
    this.pendingProjectUpdates.forEach((_project, projectName) => {
      this.throttledOperations.cancel(projectName);
      this.pendingProjectUpdates.delete(projectName);
    });
    this.throttledOperations.cancel(ensureProjectForOpenFileSchedule);
    this.pendingOpenFileProjectUpdates = void 0;
    this.pendingEnsureProjectForOpenFiles = false;
    this.configFileExistenceInfoCache.forEach((info) => {
      if (info.config) {
        info.config.updateLevel = 2 /* Full */;
        info.config.cachedDirectoryStructureHost.clearCache();
      }
    });
    this.configFileForOpenFiles.clear();
    this.externalProjects.forEach((project) => {
      this.clearSemanticCache(project);
      project.updateGraph();
    });
    const reloadedConfiguredProjects = /* @__PURE__ */ new Map();
    const delayReloadedConfiguredProjects = /* @__PURE__ */ new Set();
    this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => {
      const reason = `Reloading configured project in external project: ${externalProjectName}`;
      projects.forEach((project) => {
        if (this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) {
          this.reloadConfiguredProjectOptimized(project, reason, reloadedConfiguredProjects);
        } else {
          this.reloadConfiguredProjectClearingSemanticCache(
            project,
            reason,
            reloadedConfiguredProjects
          );
        }
      });
    });
    this.openFiles.forEach((_projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      if (find(info.containingProjects, isExternalProject)) return;
      this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(
        info,
        7 /* Reload */,
        reloadedConfiguredProjects,
        delayReloadedConfiguredProjects
      );
    });
    delayReloadedConfiguredProjects.forEach((p) => reloadedConfiguredProjects.set(p, 7 /* Reload */));
    this.inferredProjects.forEach((project) => this.clearSemanticCache(project));
    this.ensureProjectForOpenFiles();
    this.cleanupProjectsAndScriptInfos(
      reloadedConfiguredProjects,
      new Set(this.openFiles.keys()),
      new Set(this.externalProjectToConfiguredProjectMap.keys())
    );
    this.logger.info("After reloading projects..");
    this.printProjects();
  }
  /**
   * Remove the root of inferred project if script info is part of another project
   */
  removeRootOfInferredProjectIfNowPartOfOtherProject(info) {
    Debug.assert(info.containingProjects.length > 0);
    const firstProject = info.containingProjects[0];
    if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, (p) => p !== firstProject && !p.isOrphan())) {
      firstProject.removeFile(
        info,
        /*fileExists*/
        true,
        /*detachFromProject*/
        true
      );
    }
  }
  /**
   * This function is to update the project structure for every inferred project.
   * It is called on the premise that all the configured projects are
   * up to date.
   * This will go through open files and assign them to inferred project if open file is not part of any other project
   * After that all the inferred project graphs are updated
   */
  ensureProjectForOpenFiles() {
    this.logger.info("Before ensureProjectForOpenFiles:");
    this.printProjects();
    const pendingOpenFileProjectUpdates = this.pendingOpenFileProjectUpdates;
    this.pendingOpenFileProjectUpdates = void 0;
    pendingOpenFileProjectUpdates == null ? void 0 : pendingOpenFileProjectUpdates.forEach(
      (_config, path) => this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(
        this.getScriptInfoForPath(path),
        5 /* Create */
      )
    );
    this.openFiles.forEach((projectRootPath, path) => {
      const info = this.getScriptInfoForPath(path);
      if (info.isOrphan()) {
        this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
      } else {
        this.removeRootOfInferredProjectIfNowPartOfOtherProject(info);
      }
    });
    this.pendingEnsureProjectForOpenFiles = false;
    this.inferredProjects.forEach(updateProjectIfDirty);
    this.logger.info("After ensureProjectForOpenFiles:");
    this.printProjects();
  }
  /**
   * Open file whose contents is managed by the client
   * @param filename is absolute pathname
   * @param fileContent is a known version of the file content that is more up to date than the one on disk
   */
  openClientFile(fileName, fileContent, scriptKind, projectRootPath) {
    return this.openClientFileWithNormalizedPath(
      toNormalizedPath(fileName),
      fileContent,
      scriptKind,
      /*hasMixedContent*/
      false,
      projectRootPath ? toNormalizedPath(projectRootPath) : void 0
    );
  }
  /** @internal */
  getOriginalLocationEnsuringConfiguredProject(project, location) {
    const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName);
    const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location);
    if (!originalLocation) return void 0;
    const { fileName } = originalLocation;
    const scriptInfo = this.getScriptInfo(fileName);
    if (!scriptInfo && !this.host.fileExists(fileName)) return void 0;
    const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) };
    const configFileName = this.getConfigFileNameForFile(
      originalFileInfo,
      /*findFromCacheOnly*/
      false
    );
    if (!configFileName) return void 0;
    let configuredProject = this.findConfiguredProjectByProjectName(configFileName);
    if (!configuredProject) {
      if (project.getCompilerOptions().disableReferencedProjectLoad) {
        if (isSourceOfProjectReferenceRedirect) {
          return location;
        }
        return (scriptInfo == null ? void 0 : scriptInfo.containingProjects.length) ? originalLocation : location;
      }
      configuredProject = this.createConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`);
    }
    const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo(
      originalFileInfo,
      5 /* Create */,
      updateProjectFoundUsingFind(
        configuredProject,
        4 /* CreateOptimized */
      ),
      (project2) => `Creating project referenced in solution ${project2.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`
    );
    if (!result.defaultProject) return void 0;
    if (result.defaultProject === project) return originalLocation;
    addOriginalConfiguredProject(result.defaultProject);
    const originalScriptInfo = this.getScriptInfo(fileName);
    if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) return void 0;
    originalScriptInfo.containingProjects.forEach((project2) => {
      if (isConfiguredProject(project2)) {
        addOriginalConfiguredProject(project2);
      }
    });
    return originalLocation;
    function addOriginalConfiguredProject(originalProject) {
      (project.originalConfiguredProjects ?? (project.originalConfiguredProjects = /* @__PURE__ */ new Set())).add(originalProject.canonicalConfigFilePath);
    }
  }
  /** @internal */
  fileExists(fileName) {
    return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
  }
  findExternalProjectContainingOpenScriptInfo(info) {
    return find(this.externalProjects, (proj) => {
      updateProjectIfDirty(proj);
      return proj.containsScriptInfo(info);
    });
  }
  getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
    const info = this.getOrCreateScriptInfoWorker(
      fileName,
      projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory,
      /*openedByClient*/
      true,
      fileContent,
      scriptKind,
      !!hasMixedContent,
      /*hostToQueryFileExistsOn*/
      void 0,
      /*deferredDeleteOk*/
      true
    );
    this.openFiles.set(info.path, projectRootPath);
    return info;
  }
  assignProjectToOpenedScriptInfo(info) {
    let configFileName;
    let configFileErrors;
    const project = this.findExternalProjectContainingOpenScriptInfo(info);
    let retainProjects;
    let sentConfigDiag;
    if (!project && this.serverMode === 0 /* Semantic */) {
      const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(
        info,
        5 /* Create */
      );
      if (result) {
        retainProjects = result.seenProjects;
        sentConfigDiag = result.sentConfigDiag;
        if (result.defaultProject) {
          configFileName = result.defaultProject.getConfigFilePath();
          configFileErrors = result.defaultProject.getAllProjectErrors();
        }
      }
    }
    info.containingProjects.forEach(updateProjectIfDirty);
    if (info.isOrphan()) {
      retainProjects == null ? void 0 : retainProjects.forEach((kind, project2) => {
        if (kind !== 4 /* CreateOptimized */ && !sentConfigDiag.has(project2)) this.sendConfigFileDiagEvent(
          project2,
          info.fileName,
          /*force*/
          true
        );
      });
      Debug.assert(this.openFiles.has(info.path));
      this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
    }
    Debug.assert(!info.isOrphan());
    return { configFileName, configFileErrors, retainProjects };
  }
  /**
   * Depending on kind
   * - Find the configuedProject and return it - if allowDeferredClosed is set it will find the deferredClosed project as well
   * - Create - if the project doesnt exist, it creates one as well. If not delayLoad, the project is updated (with triggerFile if passed)
   * - Reload - if the project doesnt exist, it creates one. If not delayLoad, the project is reloaded clearing semantic cache
   *  @internal
   */
  findCreateOrReloadConfiguredProject(configFileName, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects, delayLoad, delayReloadedConfiguredProjects, projectForConfigFile) {
    let project = projectForConfigFile ?? this.findConfiguredProjectByProjectName(configFileName, allowDeferredClosed);
    let sentConfigFileDiag = false;
    let configFileExistenceInfo;
    switch (kind) {
      case 0 /* FindOptimized */:
      case 1 /* Find */:
      case 3 /* CreateReplay */:
        if (!project) return;
        break;
      case 2 /* CreateReplayOptimized */:
        if (!project) return;
        configFileExistenceInfo = configFileExistenceInfoForOptimizedReplay(project);
        break;
      case 4 /* CreateOptimized */:
      case 5 /* Create */:
        project ?? (project = this.createConfiguredProject(configFileName, reason));
        if (!delayLoad) {
          ({ sentConfigFileDiag, configFileExistenceInfo } = updateProjectFoundUsingFind(
            project,
            kind,
            triggerFile
          ));
        }
        break;
      case 6 /* ReloadOptimized */:
        project ?? (project = this.createConfiguredProject(configFileName, reloadReason(reason)));
        project.projectService.reloadConfiguredProjectOptimized(project, reason, reloadedProjects);
        configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project);
        if (configFileExistenceInfo) break;
      // falls through
      case 7 /* Reload */:
        project ?? (project = this.createConfiguredProject(configFileName, reloadReason(reason)));
        sentConfigFileDiag = !delayReloadedConfiguredProjects && this.reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects);
        if (delayReloadedConfiguredProjects && !delayReloadedConfiguredProjects.has(project) && !reloadedProjects.has(project)) {
          this.setProjectForReload(project, 2 /* Full */, reason);
          delayReloadedConfiguredProjects.add(project);
        }
        break;
      default:
        Debug.assertNever(kind);
    }
    return { project, sentConfigFileDiag, configFileExistenceInfo, reason };
  }
  /**
   * Finds the default configured project for given info
   * For any tsconfig found, it looks into that project, if not then all its references,
   * The search happens for all tsconfigs till projectRootPath
   */
  tryFindDefaultConfiguredProjectForOpenScriptInfo(info, kind, allowDeferredClosed, reloadedProjects) {
    const configFileName = this.getConfigFileNameForFile(info, kind <= 3 /* CreateReplay */);
    if (!configFileName) return;
    const optimizedKind = toConfiguredProjectLoadOptimized(kind);
    const result = this.findCreateOrReloadConfiguredProject(
      configFileName,
      optimizedKind,
      fileOpenReason(info),
      allowDeferredClosed,
      info.fileName,
      reloadedProjects
    );
    return result && this.tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo(
      info,
      kind,
      result,
      (project) => `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`,
      allowDeferredClosed,
      reloadedProjects
    );
  }
  isMatchedByConfig(configFileName, config, info) {
    if (config.fileNames.some((rootName) => this.toPath(rootName) === info.path)) return true;
    if (isSupportedSourceFileName(
      info.fileName,
      config.options,
      this.hostConfiguration.extraFileExtensions
    )) return false;
    const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = config.options.configFile.configFileSpecs;
    const basePath = toNormalizedPath(getNormalizedAbsolutePath(getDirectoryPath(configFileName), this.currentDirectory));
    if (validatedFilesSpec == null ? void 0 : validatedFilesSpec.some((fileSpec) => this.toPath(getNormalizedAbsolutePath(fileSpec, basePath)) === info.path)) return true;
    if (!(validatedIncludeSpecs == null ? void 0 : validatedIncludeSpecs.length)) return false;
    if (matchesExcludeWorker(
      info.fileName,
      validatedExcludeSpecs,
      this.host.useCaseSensitiveFileNames,
      this.currentDirectory,
      basePath
    )) return false;
    return validatedIncludeSpecs == null ? void 0 : validatedIncludeSpecs.some((includeSpec) => {
      const pattern = getPatternFromSpec(includeSpec, basePath, "files");
      return !!pattern && getRegexFromPattern(`(${pattern})$`, this.host.useCaseSensitiveFileNames).test(info.fileName);
    });
  }
  tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo(info, kind, initialConfigResult, referencedProjectReason, allowDeferredClosed, reloadedProjects) {
    const infoIsOpenScriptInfo = isOpenScriptInfo(info);
    const optimizedKind = toConfiguredProjectLoadOptimized(kind);
    const seenProjects = /* @__PURE__ */ new Map();
    let seenConfigs;
    const sentConfigDiag = /* @__PURE__ */ new Set();
    let defaultProject;
    let possiblyDefault;
    let tsconfigOfDefault;
    let tsconfigOfPossiblyDefault;
    tryFindDefaultConfiguredProject(initialConfigResult);
    return {
      defaultProject: defaultProject ?? possiblyDefault,
      tsconfigProject: tsconfigOfDefault ?? tsconfigOfPossiblyDefault,
      sentConfigDiag,
      seenProjects,
      seenConfigs
    };
    function tryFindDefaultConfiguredProject(result) {
      return isDefaultProjectOptimized(result, result.project) ?? tryFindDefaultConfiguredProjectFromReferences(result.project) ?? tryFindDefaultConfiguredProjectFromAncestor(result.project);
    }
    function isDefaultConfigFileExistenceInfo(configFileExistenceInfo, project, childConfigName, reason, tsconfigProject, canonicalConfigFilePath) {
      if (project) {
        if (seenProjects.has(project)) return;
        seenProjects.set(project, optimizedKind);
      } else {
        if (seenConfigs == null ? void 0 : seenConfigs.has(canonicalConfigFilePath)) return;
        (seenConfigs ?? (seenConfigs = /* @__PURE__ */ new Set())).add(canonicalConfigFilePath);
      }
      if (!tsconfigProject.projectService.isMatchedByConfig(
        childConfigName,
        configFileExistenceInfo.config.parsedCommandLine,
        info
      )) {
        if (tsconfigProject.languageServiceEnabled) {
          tsconfigProject.projectService.watchWildcards(
            childConfigName,
            configFileExistenceInfo,
            tsconfigProject
          );
        }
        return;
      }
      const result = project ? updateProjectFoundUsingFind(
        project,
        kind,
        info.fileName,
        reason,
        reloadedProjects
      ) : tsconfigProject.projectService.findCreateOrReloadConfiguredProject(
        childConfigName,
        kind,
        reason,
        allowDeferredClosed,
        info.fileName,
        reloadedProjects
      );
      if (!result) {
        Debug.assert(kind === 3 /* CreateReplay */);
        return void 0;
      }
      seenProjects.set(result.project, optimizedKind);
      if (result.sentConfigFileDiag) sentConfigDiag.add(result.project);
      return isDefaultProject(result.project, tsconfigProject);
    }
    function isDefaultProject(project, tsconfigProject) {
      if (seenProjects.get(project) === kind) return;
      seenProjects.set(project, kind);
      const scriptInfo = infoIsOpenScriptInfo ? info : project.projectService.getScriptInfo(info.fileName);
      const projectWithInfo = scriptInfo && project.containsScriptInfo(scriptInfo);
      if (projectWithInfo && !project.isSourceOfProjectReferenceRedirect(scriptInfo.path)) {
        tsconfigOfDefault = tsconfigProject;
        return defaultProject = project;
      }
      if (!possiblyDefault && infoIsOpenScriptInfo && projectWithInfo) {
        tsconfigOfPossiblyDefault = tsconfigProject;
        possiblyDefault = project;
      }
    }
    function isDefaultProjectOptimized(result, tsconfigProject) {
      if (result.sentConfigFileDiag) sentConfigDiag.add(result.project);
      return result.configFileExistenceInfo ? isDefaultConfigFileExistenceInfo(
        result.configFileExistenceInfo,
        result.project,
        toNormalizedPath(result.project.getConfigFilePath()),
        result.reason,
        result.project,
        result.project.canonicalConfigFilePath
      ) : isDefaultProject(result.project, tsconfigProject);
    }
    function tryFindDefaultConfiguredProjectFromReferences(project) {
      return project.parsedCommandLine && forEachResolvedProjectReferenceProjectLoad(
        project,
        project.parsedCommandLine,
        isDefaultConfigFileExistenceInfo,
        optimizedKind,
        referencedProjectReason(project),
        allowDeferredClosed,
        reloadedProjects
      );
    }
    function tryFindDefaultConfiguredProjectFromAncestor(project) {
      return infoIsOpenScriptInfo ? forEachAncestorProjectLoad(
        // If not in referenced projects, try ancestors and its references
        info,
        project,
        tryFindDefaultConfiguredProject,
        optimizedKind,
        `Creating possible configured project for ${info.fileName} to open`,
        allowDeferredClosed,
        reloadedProjects,
        /*searchOnlyPotentialSolution*/
        false
      ) : void 0;
    }
  }
  tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(info, kind, reloadedProjects, delayReloadedConfiguredProjects) {
    const allowDeferredClosed = kind === 1 /* Find */;
    const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfo(
      info,
      kind,
      allowDeferredClosed,
      reloadedProjects
    );
    if (!result) return;
    const { defaultProject, tsconfigProject, seenProjects } = result;
    if (defaultProject) {
      forEachAncestorProjectLoad(
        info,
        tsconfigProject,
        (ancestor) => {
          seenProjects.set(ancestor.project, kind);
        },
        kind,
        `Creating project possibly referencing default composite project ${defaultProject.getProjectName()} of open file ${info.fileName}`,
        allowDeferredClosed,
        reloadedProjects,
        /*searchOnlyPotentialSolution*/
        true,
        delayReloadedConfiguredProjects
      );
    }
    return result;
  }
  /** @internal */
  loadAncestorProjectTree(forProjects) {
    forProjects ?? (forProjects = new Set(
      mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.initialLoadPending ? key : void 0)
    ));
    const seenProjects = /* @__PURE__ */ new Set();
    const currentConfiguredProjects = arrayFrom(this.configuredProjects.values());
    for (const project of currentConfiguredProjects) {
      if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) {
        updateProjectIfDirty(project);
      }
      this.ensureProjectChildren(project, forProjects, seenProjects);
    }
  }
  ensureProjectChildren(project, forProjects, seenProjects) {
    var _a;
    if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) return;
    if (project.getCompilerOptions().disableReferencedProjectLoad) return;
    const children = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences();
    if (!children) return;
    for (const child of children) {
      if (!child) continue;
      const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0);
      if (!referencedProject) continue;
      const configFileName = toNormalizedPath(child.sourceFile.fileName);
      const childProject = this.findConfiguredProjectByProjectName(configFileName) ?? this.createConfiguredProject(
        configFileName,
        `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}`
      );
      updateProjectIfDirty(childProject);
      this.ensureProjectChildren(childProject, forProjects, seenProjects);
    }
  }
  cleanupConfiguredProjects(toRetainConfiguredProjects, externalProjectsRetainingConfiguredProjects, openFilesWithRetainedConfiguredProject) {
    this.getOrphanConfiguredProjects(
      toRetainConfiguredProjects,
      openFilesWithRetainedConfiguredProject,
      externalProjectsRetainingConfiguredProjects
    ).forEach((project) => this.removeProject(project));
  }
  cleanupProjectsAndScriptInfos(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) {
    this.cleanupConfiguredProjects(
      toRetainConfiguredProjects,
      externalProjectsRetainingConfiguredProjects,
      openFilesWithRetainedConfiguredProject
    );
    for (const inferredProject of this.inferredProjects.slice()) {
      if (inferredProject.isOrphan()) {
        this.removeProject(inferredProject);
      }
    }
    this.removeOrphanScriptInfos();
  }
  tryInvokeWildCardDirectories(info) {
    this.configFileExistenceInfoCache.forEach((configFileExistenceInfo, config) => {
      var _a, _b;
      if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) || contains(
        configFileExistenceInfo.config.parsedCommandLine.fileNames,
        info.fileName,
        !this.host.useCaseSensitiveFileNames ? equateStringsCaseInsensitive : equateStringsCaseSensitive
      )) {
        return;
      }
      (_b = configFileExistenceInfo.config.watchedDirectories) == null ? void 0 : _b.forEach((watcher, directory) => {
        if (containsPath(directory, info.fileName, !this.host.useCaseSensitiveFileNames)) {
          this.logger.info(`Invoking ${config}:: wildcard for open scriptInfo:: ${info.fileName}`);
          this.onWildCardDirectoryWatcherInvoke(
            directory,
            config,
            configFileExistenceInfo.config,
            watcher.watcher,
            info.fileName
          );
        }
      });
    });
  }
  openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
    const existing = this.getScriptInfoForPath(normalizedPathToPath(
      fileName,
      projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory,
      this.toCanonicalFileName
    ));
    const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
    if (!existing && info && !info.isDynamic) this.tryInvokeWildCardDirectories(info);
    const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info);
    this.cleanupProjectsAndScriptInfos(
      retainProjects,
      /* @__PURE__ */ new Set([info.path]),
      /*externalProjectsRetainingConfiguredProjects*/
      void 0
    );
    this.telemetryOnOpenFile(info);
    this.printProjects();
    return result;
  }
  /** @internal */
  getOrphanConfiguredProjects(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) {
    const toRemoveConfiguredProjects = new Set(this.configuredProjects.values());
    const markOriginalProjectsAsUsed = (project) => {
      if (project.originalConfiguredProjects && (isConfiguredProject(project) || !project.isOrphan())) {
        project.originalConfiguredProjects.forEach(
          (_value, configuredProjectPath) => {
            const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath);
            return project2 && retainConfiguredProject(project2);
          }
        );
      }
    };
    toRetainConfiguredProjects == null ? void 0 : toRetainConfiguredProjects.forEach((_, project) => retainConfiguredProject(project));
    if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects;
    this.inferredProjects.forEach(markOriginalProjectsAsUsed);
    this.externalProjects.forEach(markOriginalProjectsAsUsed);
    this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => {
      if (!(externalProjectsRetainingConfiguredProjects == null ? void 0 : externalProjectsRetainingConfiguredProjects.has(externalProjectName))) {
        projects.forEach(retainConfiguredProject);
      }
    });
    if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects;
    forEachEntry(this.openFiles, (_projectRootPath, path) => {
      if (openFilesWithRetainedConfiguredProject == null ? void 0 : openFilesWithRetainedConfiguredProject.has(path)) return;
      const info = this.getScriptInfoForPath(path);
      if (find(info.containingProjects, isExternalProject)) return;
      const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(
        info,
        1 /* Find */
      );
      if (result == null ? void 0 : result.defaultProject) {
        result == null ? void 0 : result.seenProjects.forEach((_, project) => retainConfiguredProject(project));
        if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects;
      }
    });
    if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects;
    forEachEntry(this.configuredProjects, (project) => {
      if (toRemoveConfiguredProjects.has(project)) {
        if (isPendingUpdate(project) || forEachReferencedProject(project, isRetained)) {
          retainConfiguredProject(project);
          if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects;
        }
      }
    });
    return toRemoveConfiguredProjects;
    function isRetained(project) {
      return !toRemoveConfiguredProjects.has(project) || isPendingUpdate(project);
    }
    function isPendingUpdate(project) {
      var _a, _b;
      return (project.deferredClose || project.projectService.hasPendingProjectUpdate(project)) && !!((_b = (_a = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)) == null ? void 0 : _a.openFilesImpactedByConfigFile) == null ? void 0 : _b.size);
    }
    function retainConfiguredProject(project) {
      if (!toRemoveConfiguredProjects.delete(project)) return;
      markOriginalProjectsAsUsed(project);
      forEachReferencedProject(project, retainConfiguredProject);
    }
  }
  removeOrphanScriptInfos() {
    const toRemoveScriptInfos = new Map(this.filenameToScriptInfo);
    this.filenameToScriptInfo.forEach((info) => {
      if (info.deferredDelete) return;
      if (!info.isScriptOpen() && info.isOrphan() && !scriptInfoIsContainedByDeferredClosedProject(info) && !scriptInfoIsContainedByBackgroundProject(info)) {
        if (!info.sourceMapFilePath) return;
        let sourceInfos;
        if (isString(info.sourceMapFilePath)) {
          const sourceMapInfo = this.filenameToScriptInfo.get(info.sourceMapFilePath);
          sourceInfos = sourceMapInfo == null ? void 0 : sourceMapInfo.sourceInfos;
        } else {
          sourceInfos = info.sourceMapFilePath.sourceInfos;
        }
        if (!sourceInfos) return;
        if (!forEachKey(sourceInfos, (path) => {
          const info2 = this.getScriptInfoForPath(path);
          return !!info2 && (info2.isScriptOpen() || !info2.isOrphan());
        })) {
          return;
        }
      }
      toRemoveScriptInfos.delete(info.path);
      if (info.sourceMapFilePath) {
        let sourceInfos;
        if (isString(info.sourceMapFilePath)) {
          const sourceMapInfo = this.filenameToScriptInfo.get(info.sourceMapFilePath);
          if (sourceMapInfo == null ? void 0 : sourceMapInfo.deferredDelete) {
            info.sourceMapFilePath = {
              watcher: this.addMissingSourceMapFile(sourceMapInfo.fileName, info.path),
              sourceInfos: sourceMapInfo.sourceInfos
            };
          } else {
            toRemoveScriptInfos.delete(info.sourceMapFilePath);
          }
          sourceInfos = sourceMapInfo == null ? void 0 : sourceMapInfo.sourceInfos;
        } else {
          sourceInfos = info.sourceMapFilePath.sourceInfos;
        }
        if (sourceInfos) {
          sourceInfos.forEach((_value, path) => toRemoveScriptInfos.delete(path));
        }
      }
    });
    toRemoveScriptInfos.forEach((info) => this.deleteScriptInfo(info));
  }
  telemetryOnOpenFile(scriptInfo) {
    if (this.serverMode !== 0 /* Semantic */ || !this.eventHandler || !scriptInfo.isJavaScript() || !addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) {
      return;
    }
    const project = this.ensureDefaultProjectForFile(scriptInfo);
    if (!project.languageServiceEnabled) {
      return;
    }
    const sourceFile = project.getSourceFile(scriptInfo.path);
    const checkJs = !!sourceFile && !!sourceFile.checkJsDirective;
    this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info: { checkJs } } });
  }
  closeClientFile(uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
    const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
    const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
    if (!skipAssignOrphanScriptInfosToInferredProject) {
      this.printProjects();
    }
    return result;
  }
  collectChanges(lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) {
    for (const proj of currentProjects) {
      const knownProject = find(lastKnownProjectVersions, (p) => p.projectName === proj.getProjectName());
      result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo));
    }
  }
  /** @internal */
  synchronizeProjectList(knownProjects, includeProjectReferenceRedirectInfo) {
    const files = [];
    this.collectChanges(knownProjects, this.externalProjects, includeProjectReferenceRedirectInfo, files);
    this.collectChanges(knownProjects, mapDefinedIterator(this.configuredProjects.values(), (p) => p.deferredClose ? void 0 : p), includeProjectReferenceRedirectInfo, files);
    this.collectChanges(knownProjects, this.inferredProjects, includeProjectReferenceRedirectInfo, files);
    return files;
  }
  /** @internal */
  applyChangesInOpenFiles(openFiles, changedFiles, closedFiles) {
    let existingOpenScriptInfos;
    let openScriptInfos;
    let assignOrphanScriptInfosToInferredProject = false;
    if (openFiles) {
      for (const file of openFiles) {
        (existingOpenScriptInfos ?? (existingOpenScriptInfos = [])).push(this.getScriptInfoForPath(normalizedPathToPath(
          toNormalizedPath(file.fileName),
          file.projectRootPath ? this.getNormalizedAbsolutePath(file.projectRootPath) : this.currentDirectory,
          this.toCanonicalFileName
        )));
        const info = this.getOrCreateOpenScriptInfo(
          toNormalizedPath(file.fileName),
          file.content,
          tryConvertScriptKindName(file.scriptKind),
          file.hasMixedContent,
          file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0
        );
        (openScriptInfos || (openScriptInfos = [])).push(info);
      }
    }
    if (changedFiles) {
      for (const file of changedFiles) {
        const scriptInfo = this.getScriptInfo(file.fileName);
        Debug.assert(!!scriptInfo);
        this.applyChangesToFile(scriptInfo, file.changes);
      }
    }
    if (closedFiles) {
      for (const file of closedFiles) {
        assignOrphanScriptInfosToInferredProject = this.closeClientFile(
          file,
          /*skipAssignOrphanScriptInfosToInferredProject*/
          true
        ) || assignOrphanScriptInfosToInferredProject;
      }
    }
    let retainProjects;
    forEach(
      existingOpenScriptInfos,
      (existing, index) => !existing && openScriptInfos[index] && !openScriptInfos[index].isDynamic ? this.tryInvokeWildCardDirectories(openScriptInfos[index]) : void 0
    );
    openScriptInfos == null ? void 0 : openScriptInfos.forEach(
      (info) => {
        var _a;
        return (_a = this.assignProjectToOpenedScriptInfo(info).retainProjects) == null ? void 0 : _a.forEach(
          (kind, p) => (retainProjects ?? (retainProjects = /* @__PURE__ */ new Map())).set(p, kind)
        );
      }
    );
    if (assignOrphanScriptInfosToInferredProject) {
      this.assignOrphanScriptInfosToInferredProject();
    }
    if (openScriptInfos) {
      this.cleanupProjectsAndScriptInfos(
        retainProjects,
        new Set(openScriptInfos.map((info) => info.path)),
        /*externalProjectsRetainingConfiguredProjects*/
        void 0
      );
      openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info));
      this.printProjects();
    } else if (length(closedFiles)) {
      this.printProjects();
    }
  }
  /** @internal */
  applyChangesToFile(scriptInfo, changes) {
    for (const change of changes) {
      scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
    }
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  closeExternalProject(uncheckedFileName, cleanupAfter) {
    const fileName = toNormalizedPath(uncheckedFileName);
    const projects = this.externalProjectToConfiguredProjectMap.get(fileName);
    if (projects) {
      this.externalProjectToConfiguredProjectMap.delete(fileName);
    } else {
      const externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
      if (externalProject) {
        this.removeProject(externalProject);
      }
    }
    if (cleanupAfter) {
      this.cleanupConfiguredProjects();
      this.printProjects();
    }
  }
  openExternalProjects(projects) {
    const projectsToClose = new Set(this.externalProjects.map((p) => p.getProjectName()));
    this.externalProjectToConfiguredProjectMap.forEach((_, externalProjectName) => projectsToClose.add(externalProjectName));
    for (const externalProject of projects) {
      this.openExternalProject(
        externalProject,
        /*cleanupAfter*/
        false
      );
      projectsToClose.delete(externalProject.projectFileName);
    }
    projectsToClose.forEach((externalProjectName) => this.closeExternalProject(
      externalProjectName,
      /*cleanupAfter*/
      false
    ));
    this.cleanupConfiguredProjects();
    this.printProjects();
  }
  static escapeFilenameForRegex(filename) {
    return filename.replace(this.filenameEscapeRegexp, "\\$&");
  }
  resetSafeList() {
    this.safelist = defaultTypeSafeList;
  }
  applySafeList(proj) {
    const typeAcquisition = proj.typeAcquisition;
    Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now");
    const result = this.applySafeListWorker(proj, proj.rootFiles, typeAcquisition);
    return (result == null ? void 0 : result.excludedFiles) ?? [];
  }
  applySafeListWorker(proj, rootFiles, typeAcquisition) {
    if (typeAcquisition.enable === false || typeAcquisition.disableFilenameBasedTypeAcquisition) {
      return void 0;
    }
    const typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []);
    const excludeRules = [];
    const normalizedNames = rootFiles.map((f) => normalizeSlashes(f.fileName));
    for (const name of Object.keys(this.safelist)) {
      const rule2 = this.safelist[name];
      for (const root of normalizedNames) {
        if (rule2.match.test(root)) {
          this.logger.info(`Excluding files based on rule ${name} matching file '${root}'`);
          if (rule2.types) {
            for (const type of rule2.types) {
              if (!typeAcqInclude.includes(type)) {
                typeAcqInclude.push(type);
              }
            }
          }
          if (rule2.exclude) {
            for (const exclude of rule2.exclude) {
              const processedRule = root.replace(rule2.match, (...groups) => {
                return exclude.map((groupNumberOrString) => {
                  if (typeof groupNumberOrString === "number") {
                    if (!isString(groups[groupNumberOrString])) {
                      this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`);
                      return "\\*";
                    }
                    return _ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
                  }
                  return groupNumberOrString;
                }).join("");
              });
              if (!excludeRules.includes(processedRule)) {
                excludeRules.push(processedRule);
              }
            }
          } else {
            const escaped = _ProjectService.escapeFilenameForRegex(root);
            if (!excludeRules.includes(escaped)) {
              excludeRules.push(escaped);
            }
          }
        }
      }
    }
    const excludeRegexes = excludeRules.map((e) => new RegExp(e, "i"));
    let filesToKeep;
    let excludedFiles;
    for (let i = 0; i < rootFiles.length; i++) {
      if (excludeRegexes.some((re) => re.test(normalizedNames[i]))) {
        addExcludedFile(i);
      } else {
        if (typeAcquisition.enable) {
          const baseName = getBaseFileName(toFileNameLowerCase(normalizedNames[i]));
          if (fileExtensionIs(baseName, "js")) {
            const inferredTypingName = removeFileExtension(baseName);
            const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName);
            const typeName = this.legacySafelist.get(cleanedTypingName);
            if (typeName !== void 0) {
              this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`);
              addExcludedFile(i);
              if (!typeAcqInclude.includes(typeName)) {
                typeAcqInclude.push(typeName);
              }
              continue;
            }
          }
        }
        if (/^.+[.-]min\.js$/.test(normalizedNames[i])) {
          addExcludedFile(i);
        } else {
          filesToKeep == null ? void 0 : filesToKeep.push(rootFiles[i]);
        }
      }
    }
    return excludedFiles ? {
      rootFiles: filesToKeep,
      excludedFiles
    } : void 0;
    function addExcludedFile(index) {
      if (!excludedFiles) {
        Debug.assert(!filesToKeep);
        filesToKeep = rootFiles.slice(0, index);
        excludedFiles = [];
      }
      excludedFiles.push(normalizedNames[index]);
    }
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  openExternalProject(proj, cleanupAfter) {
    const existingExternalProject = this.findExternalProjectByProjectName(proj.projectFileName);
    let configuredProjects;
    let rootFiles = [];
    for (const file of proj.rootFiles) {
      const normalized = toNormalizedPath(file.fileName);
      if (getBaseConfigFileName(normalized)) {
        if (this.serverMode === 0 /* Semantic */ && this.host.fileExists(normalized)) {
          let project = this.findConfiguredProjectByProjectName(normalized);
          if (!project) {
            project = this.createConfiguredProject(normalized, `Creating configured project in external project: ${proj.projectFileName}`);
            if (!this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) project.updateGraph();
          }
          (configuredProjects ?? (configuredProjects = /* @__PURE__ */ new Set())).add(project);
          Debug.assert(!project.isClosed());
        }
      } else {
        rootFiles.push(file);
      }
    }
    if (configuredProjects) {
      this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, configuredProjects);
      if (existingExternalProject) this.removeProject(existingExternalProject);
    } else {
      this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
      const typeAcquisition = proj.typeAcquisition || {};
      typeAcquisition.include = typeAcquisition.include || [];
      typeAcquisition.exclude = typeAcquisition.exclude || [];
      if (typeAcquisition.enable === void 0) {
        typeAcquisition.enable = hasNoTypeScriptSource(rootFiles.map((f) => f.fileName));
      }
      const excludeResult = this.applySafeListWorker(proj, rootFiles, typeAcquisition);
      const excludedFiles = (excludeResult == null ? void 0 : excludeResult.excludedFiles) ?? [];
      rootFiles = (excludeResult == null ? void 0 : excludeResult.rootFiles) ?? rootFiles;
      if (existingExternalProject) {
        existingExternalProject.excludedFiles = excludedFiles;
        const compilerOptions = convertCompilerOptions(proj.options);
        const watchOptionsAndErrors = convertWatchOptions(proj.options, existingExternalProject.getCurrentDirectory());
        const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, rootFiles, externalFilePropertyReader);
        if (lastFileExceededProgramSize) {
          existingExternalProject.disableLanguageService(lastFileExceededProgramSize);
        } else {
          existingExternalProject.enableLanguageService();
        }
        existingExternalProject.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors);
        this.updateRootAndOptionsOfNonInferredProject(existingExternalProject, rootFiles, externalFilePropertyReader, compilerOptions, typeAcquisition, proj.options.compileOnSave, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions);
        existingExternalProject.updateGraph();
      } else {
        const project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, typeAcquisition, excludedFiles);
        project.updateGraph();
      }
    }
    if (cleanupAfter) {
      this.cleanupConfiguredProjects(
        configuredProjects,
        /* @__PURE__ */ new Set([proj.projectFileName])
      );
      this.printProjects();
    }
  }
  hasDeferredExtension() {
    for (const extension of this.hostConfiguration.extraFileExtensions) {
      if (extension.scriptKind === 7 /* Deferred */) {
        return true;
      }
    }
    return false;
  }
  /**
   * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously
   * @internal
   */
  requestEnablePlugin(project, pluginConfigEntry, searchPaths) {
    if (!this.host.importPlugin && !this.host.require) {
      this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
      return;
    }
    this.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`);
    if (!pluginConfigEntry.name || isExternalModuleNameRelative(pluginConfigEntry.name) || /[\\/]\.\.?(?:$|[\\/])/.test(pluginConfigEntry.name)) {
      this.logger.info(`Skipped loading plugin ${pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)} because only package name is allowed plugin name`);
      return;
    }
    if (this.host.importPlugin) {
      const importPromise = Project2.importServicePluginAsync(
        pluginConfigEntry,
        searchPaths,
        this.host,
        (s) => this.logger.info(s)
      );
      this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map());
      let promises = this.pendingPluginEnablements.get(project);
      if (!promises) this.pendingPluginEnablements.set(project, promises = []);
      promises.push(importPromise);
      return;
    }
    this.endEnablePlugin(
      project,
      Project2.importServicePluginSync(
        pluginConfigEntry,
        searchPaths,
        this.host,
        (s) => this.logger.info(s)
      )
    );
  }
  /**
   * Performs the remaining steps of enabling a plugin after its module has been instantiated.
   */
  endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) {
    var _a;
    if (resolvedModule) {
      const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name);
      if (configurationOverride) {
        const pluginName = pluginConfigEntry.name;
        pluginConfigEntry = configurationOverride;
        pluginConfigEntry.name = pluginName;
      }
      project.enableProxy(resolvedModule, pluginConfigEntry);
    } else {
      forEach(errorLogs, (message) => this.logger.info(message));
      this.logger.info(`Couldn't find ${pluginConfigEntry.name}`);
    }
  }
  /** @internal */
  hasNewPluginEnablementRequests() {
    return !!this.pendingPluginEnablements;
  }
  /** @internal */
  hasPendingPluginEnablements() {
    return !!this.currentPluginEnablementPromise;
  }
  /**
   * Waits for any ongoing plugin enablement requests to complete.
   *
   * @internal
   */
  async waitForPendingPlugins() {
    while (this.currentPluginEnablementPromise) {
      await this.currentPluginEnablementPromise;
    }
  }
  /**
   * Starts enabling any requested plugins without waiting for the result.
   *
   * @internal
   */
  enableRequestedPlugins() {
    if (this.pendingPluginEnablements) {
      void this.enableRequestedPluginsAsync();
    }
  }
  async enableRequestedPluginsAsync() {
    if (this.currentPluginEnablementPromise) {
      await this.waitForPendingPlugins();
    }
    if (!this.pendingPluginEnablements) {
      return;
    }
    const entries = arrayFrom(this.pendingPluginEnablements.entries());
    this.pendingPluginEnablements = void 0;
    this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries);
    await this.currentPluginEnablementPromise;
  }
  async enableRequestedPluginsWorker(pendingPlugins) {
    Debug.assert(this.currentPluginEnablementPromise === void 0);
    let sendProjectsUpdatedInBackgroundEvent = false;
    await Promise.all(map(pendingPlugins, async ([project, promises]) => {
      const results = await Promise.all(promises);
      if (project.isClosed() || isProjectDeferredClose(project)) {
        this.logger.info(`Cancelling plugin enabling for ${project.getProjectName()} as it is ${project.isClosed() ? "closed" : "deferred close"}`);
        return;
      }
      sendProjectsUpdatedInBackgroundEvent = true;
      for (const result of results) {
        this.endEnablePlugin(project, result);
      }
      this.delayUpdateProjectGraph(project);
    }));
    this.currentPluginEnablementPromise = void 0;
    if (sendProjectsUpdatedInBackgroundEvent) this.sendProjectsUpdatedInBackgroundEvent();
  }
  configurePlugin(args) {
    this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration));
    this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */ new Map();
    this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
  }
  /** @internal */
  getPackageJsonsVisibleToFile(fileName, project, rootDir) {
    const packageJsonCache = this.packageJsonCache;
    const rootPath = rootDir && this.toPath(rootDir);
    const result = [];
    const processDirectory = (directory) => {
      switch (packageJsonCache.directoryHasPackageJson(directory)) {
        // Sync and check same directory again
        case 3 /* Maybe */:
          packageJsonCache.searchDirectoryAndAncestors(directory, project);
          return processDirectory(directory);
        // Check package.json
        case -1 /* True */:
          const packageJsonFileName = combinePaths(directory, "package.json");
          this.watchPackageJsonFile(packageJsonFileName, this.toPath(packageJsonFileName), project);
          const info = packageJsonCache.getInDirectory(directory);
          if (info) result.push(info);
      }
      if (rootPath && rootPath === directory) {
        return true;
      }
    };
    forEachAncestorDirectoryStoppingAtGlobalCache(
      project,
      getDirectoryPath(fileName),
      processDirectory
    );
    return result;
  }
  /** @internal */
  getNearestAncestorDirectoryWithPackageJson(fileName, project) {
    return forEachAncestorDirectoryStoppingAtGlobalCache(
      project,
      fileName,
      (directory) => {
        switch (this.packageJsonCache.directoryHasPackageJson(directory)) {
          case -1 /* True */:
            return directory;
          case 0 /* False */:
            return void 0;
          case 3 /* Maybe */:
            return this.host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0;
        }
      }
    );
  }
  watchPackageJsonFile(file, path, project) {
    Debug.assert(project !== void 0);
    let result = (this.packageJsonFilesMap ?? (this.packageJsonFilesMap = /* @__PURE__ */ new Map())).get(path);
    if (!result) {
      let watcher = this.watchFactory.watchFile(
        file,
        (fileName, eventKind) => {
          switch (eventKind) {
            case 0 /* Created */:
            case 1 /* Changed */:
              this.packageJsonCache.addOrUpdate(fileName, path);
              this.onPackageJsonChange(result);
              break;
            case 2 /* Deleted */:
              this.packageJsonCache.delete(path);
              this.onPackageJsonChange(result);
              result.projects.clear();
              result.close();
          }
        },
        250 /* Low */,
        this.hostConfiguration.watchOptions,
        WatchType.PackageJson
      );
      result = {
        projects: /* @__PURE__ */ new Set(),
        close: () => {
          var _a;
          if (result.projects.size || !watcher) return;
          watcher.close();
          watcher = void 0;
          (_a = this.packageJsonFilesMap) == null ? void 0 : _a.delete(path);
          this.packageJsonCache.invalidate(path);
        }
      };
      this.packageJsonFilesMap.set(path, result);
    }
    result.projects.add(project);
    (project.packageJsonWatches ?? (project.packageJsonWatches = /* @__PURE__ */ new Set())).add(result);
  }
  onPackageJsonChange(result) {
    result.projects.forEach((project) => {
      var _a;
      return (_a = project.onPackageJsonChange) == null ? void 0 : _a.call(project);
    });
  }
  /** @internal */
  includePackageJsonAutoImports() {
    switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) {
      case "on":
        return 1 /* On */;
      case "off":
        return 0 /* Off */;
      default:
        return 2 /* Auto */;
    }
  }
  /** @internal */
  getIncompleteCompletionsCache() {
    return this.incompleteCompletionsCache || (this.incompleteCompletionsCache = createIncompleteCompletionsCache());
  }
};
/** Makes a filename safe to insert in a RegExp */
_ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g;
var ProjectService2 = _ProjectService;
function createIncompleteCompletionsCache() {
  let info;
  return {
    get() {
      return info;
    },
    set(newInfo) {
      info = newInfo;
    },
    clear() {
      info = void 0;
    }
  };
}
function isConfigFile(config) {
  return config.kind !== void 0;
}
function printProjectWithoutFileNames(project) {
  project.print(
    /*writeProjectFileNames*/
    false,
    /*writeFileExplaination*/
    false,
    /*writeFileVersionAndText*/
    false
  );
}

// src/server/moduleSpecifierCache.ts
function createModuleSpecifierCache(host) {
  let containedNodeModulesWatchers;
  let cache;
  let currentKey;
  const result = {
    get(fromFileName, toFileName2, preferences, options) {
      if (!cache || currentKey !== key(fromFileName, preferences, options)) return void 0;
      return cache.get(toFileName2);
    },
    set(fromFileName, toFileName2, preferences, options, kind, modulePaths, moduleSpecifiers) {
      ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo(
        kind,
        modulePaths,
        moduleSpecifiers,
        /*packageName*/
        void 0,
        /*isBlockedByPackageJsonDependencies*/
        false
      ));
      if (moduleSpecifiers) {
        for (const p of modulePaths) {
          if (p.isInNodeModules) {
            const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1);
            const key2 = host.toPath(nodeModulesPath);
            if (!(containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.has(key2))) {
              (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */ new Map())).set(
                key2,
                host.watchNodeModulesForPackageJsonChanges(nodeModulesPath)
              );
            }
          }
        }
      }
    },
    setModulePaths(fromFileName, toFileName2, preferences, options, modulePaths) {
      const cache2 = ensureCache(fromFileName, preferences, options);
      const info = cache2.get(toFileName2);
      if (info) {
        info.modulePaths = modulePaths;
      } else {
        cache2.set(toFileName2, createInfo(
          /*kind*/
          void 0,
          modulePaths,
          /*moduleSpecifiers*/
          void 0,
          /*packageName*/
          void 0,
          /*isBlockedByPackageJsonDependencies*/
          void 0
        ));
      }
    },
    setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, packageName, isBlockedByPackageJsonDependencies) {
      const cache2 = ensureCache(fromFileName, preferences, options);
      const info = cache2.get(toFileName2);
      if (info) {
        info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies;
        info.packageName = packageName;
      } else {
        cache2.set(toFileName2, createInfo(
          /*kind*/
          void 0,
          /*modulePaths*/
          void 0,
          /*moduleSpecifiers*/
          void 0,
          packageName,
          isBlockedByPackageJsonDependencies
        ));
      }
    },
    clear() {
      containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach(closeFileWatcher);
      cache == null ? void 0 : cache.clear();
      containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.clear();
      currentKey = void 0;
    },
    count() {
      return cache ? cache.size : 0;
    }
  };
  if (Debug.isDebugging) {
    Object.defineProperty(result, "__cache", { get: () => cache });
  }
  return result;
  function ensureCache(fromFileName, preferences, options) {
    const newKey = key(fromFileName, preferences, options);
    if (cache && currentKey !== newKey) {
      result.clear();
    }
    currentKey = newKey;
    return cache || (cache = /* @__PURE__ */ new Map());
  }
  function key(fromFileName, preferences, options) {
    return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`;
  }
  function createInfo(kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies) {
    return { kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies };
  }
}

// src/server/packageJsonCache.ts
function createPackageJsonCache(host) {
  const packageJsons = /* @__PURE__ */ new Map();
  const directoriesWithoutPackageJson = /* @__PURE__ */ new Map();
  return {
    addOrUpdate,
    invalidate,
    delete: (fileName) => {
      packageJsons.delete(fileName);
      directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true);
    },
    getInDirectory: (directory) => {
      return packageJsons.get(host.toPath(combinePaths(directory, "package.json"))) || void 0;
    },
    directoryHasPackageJson: (directory) => directoryHasPackageJson(host.toPath(directory)),
    searchDirectoryAndAncestors: (directory, project) => {
      forEachAncestorDirectoryStoppingAtGlobalCache(
        project,
        directory,
        (ancestor) => {
          const ancestorPath = host.toPath(ancestor);
          if (directoryHasPackageJson(ancestorPath) !== 3 /* Maybe */) {
            return true;
          }
          const packageJsonFileName = combinePaths(ancestor, "package.json");
          if (tryFileExists(host, packageJsonFileName)) {
            addOrUpdate(packageJsonFileName, combinePaths(ancestorPath, "package.json"));
          } else {
            directoriesWithoutPackageJson.set(ancestorPath, true);
          }
        }
      );
    }
  };
  function addOrUpdate(fileName, path) {
    const packageJsonInfo = Debug.checkDefined(createPackageJsonInfo(fileName, host.host));
    packageJsons.set(path, packageJsonInfo);
    directoriesWithoutPackageJson.delete(getDirectoryPath(path));
  }
  function invalidate(path) {
    packageJsons.delete(path);
    directoriesWithoutPackageJson.delete(getDirectoryPath(path));
  }
  function directoryHasPackageJson(directory) {
    return packageJsons.has(combinePaths(directory, "package.json")) ? -1 /* True */ : directoriesWithoutPackageJson.has(directory) ? 0 /* False */ : 3 /* Maybe */;
  }
}

// src/server/session.ts
var nullCancellationToken = {
  isCancellationRequested: () => false,
  setRequest: () => void 0,
  resetRequest: () => void 0
};
function hrTimeToMilliseconds(time) {
  const seconds = time[0];
  const nanoseconds = time[1];
  return (1e9 * seconds + nanoseconds) / 1e6;
}
function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) {
  if ((isInferredProject(project) || isExternalProject(project)) && project.isJsOnlyProject()) {
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    return scriptInfo && !scriptInfo.isJavaScript();
  }
  return false;
}
function dtsChangeCanAffectEmit(compilationSettings) {
  return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata;
}
function formatDiag(fileName, project, diag2) {
  const scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
  return {
    start: scriptInfo.positionToLineOffset(diag2.start),
    end: scriptInfo.positionToLineOffset(diag2.start + diag2.length),
    // TODO: GH#18217
    text: flattenDiagnosticMessageText(diag2.messageText, "\n"),
    code: diag2.code,
    category: diagnosticCategoryName(diag2),
    reportsUnnecessary: diag2.reportsUnnecessary,
    reportsDeprecated: diag2.reportsDeprecated,
    source: diag2.source,
    relatedInformation: map(diag2.relatedInformation, formatRelatedInformation)
  };
}
function formatRelatedInformation(info) {
  if (!info.file) {
    return {
      message: flattenDiagnosticMessageText(info.messageText, "\n"),
      category: diagnosticCategoryName(info),
      code: info.code
    };
  }
  return {
    span: {
      start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start)),
      end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start + info.length)),
      // TODO: GH#18217
      file: info.file.fileName
    },
    message: flattenDiagnosticMessageText(info.messageText, "\n"),
    category: diagnosticCategoryName(info),
    code: info.code
  };
}
function convertToLocation(lineAndCharacter) {
  return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
}
function formatDiagnosticToProtocol(diag2, includeFileName) {
  const start = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start));
  const end = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start + diag2.length));
  const text = flattenDiagnosticMessageText(diag2.messageText, "\n");
  const { code, source } = diag2;
  const category = diagnosticCategoryName(diag2);
  const common = {
    start,
    end,
    text,
    code,
    category,
    reportsUnnecessary: diag2.reportsUnnecessary,
    reportsDeprecated: diag2.reportsDeprecated,
    source,
    relatedInformation: map(diag2.relatedInformation, formatRelatedInformation)
  };
  return includeFileName ? { ...common, fileName: diag2.file && diag2.file.fileName } : common;
}
function allEditsBeforePos(edits, pos) {
  return edits.every((edit) => textSpanEnd(edit.span) < pos);
}
var CommandNames = CommandTypes;
function formatMessage2(msg, logger, byteLength, newLine) {
  const verboseLogging = logger.hasLevel(3 /* verbose */);
  const json = JSON.stringify(msg);
  if (verboseLogging) {
    logger.info(`${msg.type}:${stringifyIndented(msg)}`);
  }
  const len = byteLength(json, "utf8");
  return `Content-Length: ${1 + len}\r
\r
${json}${newLine}`;
}
var MultistepOperation = class {
  constructor(operationHost) {
    this.operationHost = operationHost;
  }
  startNew(action) {
    this.complete();
    this.requestId = this.operationHost.getCurrentRequestId();
    this.executeAction(action);
  }
  complete() {
    if (this.requestId !== void 0) {
      this.operationHost.sendRequestCompletedEvent(this.requestId, this.performanceData);
      this.requestId = void 0;
    }
    this.setTimerHandle(void 0);
    this.setImmediateId(void 0);
    this.performanceData = void 0;
  }
  immediate(actionType, action) {
    const requestId = this.requestId;
    Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id");
    this.setImmediateId(
      this.operationHost.getServerHost().setImmediate(() => {
        this.immediateId = void 0;
        this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData);
      }, actionType)
    );
  }
  delay(actionType, ms, action) {
    const requestId = this.requestId;
    Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id");
    this.setTimerHandle(
      this.operationHost.getServerHost().setTimeout(
        () => {
          this.timerHandle = void 0;
          this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData);
        },
        ms,
        actionType
      )
    );
  }
  executeAction(action) {
    var _a, _b, _c, _d, _e, _f;
    let stop = false;
    try {
      if (this.operationHost.isCancellationRequested()) {
        stop = true;
        (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true });
      } else {
        (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { seq: this.requestId });
        action(this);
        (_c = tracing) == null ? void 0 : _c.pop();
      }
    } catch (e) {
      (_d = tracing) == null ? void 0 : _d.popAll();
      stop = true;
      if (e instanceof OperationCanceledException) {
        (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId });
      } else {
        (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: e.message });
        this.operationHost.logError(e, `delayed processing of request ${this.requestId}`);
      }
    }
    this.performanceData = this.operationHost.getPerformanceData();
    if (stop || !this.hasPendingWork()) {
      this.complete();
    }
  }
  setTimerHandle(timerHandle) {
    if (this.timerHandle !== void 0) {
      this.operationHost.getServerHost().clearTimeout(this.timerHandle);
    }
    this.timerHandle = timerHandle;
  }
  setImmediateId(immediateId) {
    if (this.immediateId !== void 0) {
      this.operationHost.getServerHost().clearImmediate(this.immediateId);
    }
    this.immediateId = immediateId;
  }
  hasPendingWork() {
    return !!this.timerHandle || !!this.immediateId;
  }
};
function toEvent(eventName, body) {
  return {
    seq: 0,
    type: "event",
    event: eventName,
    body
  };
}
function combineProjectOutput(defaultValue, getValue, projects, action) {
  const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, (project) => action(project, defaultValue));
  if (!isArray(projects) && projects.symLinkedProjects) {
    projects.symLinkedProjects.forEach((projects2, path) => {
      const value = getValue(path);
      outputs.push(...flatMap(projects2, (project) => action(project, value)));
    });
  }
  return deduplicate(outputs, equateValues);
}
function createDocumentSpanSet(useCaseSensitiveFileNames2) {
  return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, getDocumentSpansEqualityComparer(useCaseSensitiveFileNames2));
}
function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences, useCaseSensitiveFileNames2) {
  const perProjectResults = getPerProjectReferences(
    projects,
    defaultProject,
    initialLocation,
    getDefinitionLocation(
      defaultProject,
      initialLocation,
      /*isForRename*/
      true
    ),
    mapDefinitionInProject,
    (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences),
    (renameLocation, cb) => cb(documentSpanLocation(renameLocation))
  );
  if (isArray(perProjectResults)) {
    return perProjectResults;
  }
  const results = [];
  const seen = createDocumentSpanSet(useCaseSensitiveFileNames2);
  perProjectResults.forEach((projectResults, project) => {
    for (const result of projectResults) {
      if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) {
        results.push(result);
        seen.add(result);
      }
    }
  });
  return results;
}
function getDefinitionLocation(defaultProject, initialLocation, isForRename) {
  const infos = defaultProject.getLanguageService().getDefinitionAtPosition(
    initialLocation.fileName,
    initialLocation.pos,
    /*searchOtherFilesOnly*/
    false,
    /*stopAtAlias*/
    isForRename
  );
  const info = infos && firstOrUndefined(infos);
  return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : void 0;
}
function getReferencesWorker(projects, defaultProject, initialLocation, useCaseSensitiveFileNames2, logger) {
  var _a, _b;
  const perProjectResults = getPerProjectReferences(
    projects,
    defaultProject,
    initialLocation,
    getDefinitionLocation(
      defaultProject,
      initialLocation,
      /*isForRename*/
      false
    ),
    mapDefinitionInProject,
    (project, position) => {
      logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`);
      return project.getLanguageService().findReferences(position.fileName, position.pos);
    },
    (referencedSymbol, cb) => {
      cb(documentSpanLocation(referencedSymbol.definition));
      for (const ref of referencedSymbol.references) {
        cb(documentSpanLocation(ref));
      }
    }
  );
  if (isArray(perProjectResults)) {
    return perProjectResults;
  }
  const defaultProjectResults = perProjectResults.get(defaultProject);
  if (((_b = (_a = defaultProjectResults == null ? void 0 : defaultProjectResults[0]) == null ? void 0 : _a.references[0]) == null ? void 0 : _b.isDefinition) === void 0) {
    perProjectResults.forEach((projectResults) => {
      for (const referencedSymbol of projectResults) {
        for (const ref of referencedSymbol.references) {
          delete ref.isDefinition;
        }
      }
    });
  } else {
    const knownSymbolSpans = createDocumentSpanSet(useCaseSensitiveFileNames2);
    for (const referencedSymbol of defaultProjectResults) {
      for (const ref of referencedSymbol.references) {
        if (ref.isDefinition) {
          knownSymbolSpans.add(ref);
          break;
        }
      }
    }
    const updatedProjects = /* @__PURE__ */ new Set();
    while (true) {
      let progress = false;
      perProjectResults.forEach((referencedSymbols, project) => {
        if (updatedProjects.has(project)) return;
        const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans);
        if (updated) {
          updatedProjects.add(project);
          progress = true;
        }
      });
      if (!progress) break;
    }
    perProjectResults.forEach((referencedSymbols, project) => {
      if (updatedProjects.has(project)) return;
      for (const referencedSymbol of referencedSymbols) {
        for (const ref of referencedSymbol.references) {
          ref.isDefinition = false;
        }
      }
    });
  }
  const results = [];
  const seenRefs = createDocumentSpanSet(useCaseSensitiveFileNames2);
  perProjectResults.forEach((projectResults, project) => {
    for (const referencedSymbol of projectResults) {
      const mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project);
      const definition = mappedDefinitionFile === void 0 ? referencedSymbol.definition : {
        ...referencedSymbol.definition,
        textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length),
        // Why would the length be the same in the original?
        fileName: mappedDefinitionFile.fileName,
        contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project)
      };
      let symbolToAddTo = find(results, (o) => documentSpansEqual(o.definition, definition, useCaseSensitiveFileNames2));
      if (!symbolToAddTo) {
        symbolToAddTo = { definition, references: [] };
        results.push(symbolToAddTo);
      }
      for (const ref of referencedSymbol.references) {
        if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) {
          seenRefs.add(ref);
          symbolToAddTo.references.push(ref);
        }
      }
    }
  });
  return results.filter((o) => o.references.length !== 0);
}
function forEachProjectInProjects(projects, path, cb) {
  for (const project of isArray(projects) ? projects : projects.projects) {
    cb(project, path);
  }
  if (!isArray(projects) && projects.symLinkedProjects) {
    projects.symLinkedProjects.forEach((symlinkedProjects, symlinkedPath) => {
      for (const project of symlinkedProjects) {
        cb(project, symlinkedPath);
      }
    });
  }
}
function getPerProjectReferences(projects, defaultProject, initialLocation, defaultDefinition, mapDefinitionInProject2, getResultsForPosition, forPositionInResult) {
  const resultsMap = /* @__PURE__ */ new Map();
  const queue = createQueue();
  queue.enqueue({ project: defaultProject, location: initialLocation });
  forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => {
    const location = { fileName: path, pos: initialLocation.pos };
    queue.enqueue({ project, location });
  });
  const projectService = defaultProject.projectService;
  const cancellationToken = defaultProject.getCancellationToken();
  const getGeneratedDefinition = memoize(
    () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition)
  );
  const getSourceDefinition = memoize(
    () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition)
  );
  const searchedProjectKeys = /* @__PURE__ */ new Set();
  onCancellation:
    while (!queue.isEmpty()) {
      while (!queue.isEmpty()) {
        if (cancellationToken.isCancellationRequested()) break onCancellation;
        const { project, location } = queue.dequeue();
        if (resultsMap.has(project)) continue;
        if (isLocationProjectReferenceRedirect(project, location)) continue;
        updateProjectIfDirty(project);
        if (!project.containsFile(toNormalizedPath(location.fileName))) {
          continue;
        }
        const projectResults = searchPosition(project, location);
        resultsMap.set(project, projectResults ?? emptyArray2);
        searchedProjectKeys.add(getProjectKey(project));
      }
      if (defaultDefinition) {
        projectService.loadAncestorProjectTree(searchedProjectKeys);
        projectService.forEachEnabledProject((project) => {
          if (cancellationToken.isCancellationRequested()) return;
          if (resultsMap.has(project)) return;
          const location = mapDefinitionInProject2(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition);
          if (location) {
            queue.enqueue({ project, location });
          }
        });
      }
    }
  if (resultsMap.size === 1) {
    return firstIterator(resultsMap.values());
  }
  return resultsMap;
  function searchPosition(project, location) {
    const projectResults = getResultsForPosition(project, location);
    if (!projectResults || !forPositionInResult) return projectResults;
    for (const result of projectResults) {
      forPositionInResult(result, (position) => {
        const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position);
        if (!originalLocation) return;
        const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName);
        for (const project2 of originalScriptInfo.containingProjects) {
          if (!project2.isOrphan() && !resultsMap.has(project2)) {
            queue.enqueue({ project: project2, location: originalLocation });
          }
        }
        const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo);
        if (symlinkedProjectsMap) {
          symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => {
            for (const symlinkedProject of symlinkedProjects) {
              if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) {
                queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } });
              }
            }
          });
        }
      });
    }
    return projectResults;
  }
}
function mapDefinitionInProjectIfFileInProject(definition, project) {
  if (project.containsFile(toNormalizedPath(definition.fileName)) && !isLocationProjectReferenceRedirect(project, definition)) {
    return definition;
  }
}
function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) {
  const result = mapDefinitionInProjectIfFileInProject(definition, project);
  if (result) return result;
  const generatedDefinition = getGeneratedDefinition();
  if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) return generatedDefinition;
  const sourceDefinition = getSourceDefinition();
  return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : void 0;
}
function isLocationProjectReferenceRedirect(project, location) {
  if (!location) return false;
  const program = project.getLanguageService().getProgram();
  if (!program) return false;
  const sourceFile = program.getSourceFile(location.fileName);
  return !!sourceFile && sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName);
}
function getProjectKey(project) {
  return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName();
}
function documentSpanLocation({ fileName, textSpan }) {
  return { fileName, pos: textSpan.start };
}
function getMappedLocationForProject(location, project) {
  return getMappedLocation(location, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
function getMappedDocumentSpanForProject(documentSpan, project) {
  return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
function getMappedContextSpanForProject(documentSpan, project) {
  return getMappedContextSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p));
}
var invalidPartialSemanticModeCommands = [
  "openExternalProject" /* OpenExternalProject */,
  "openExternalProjects" /* OpenExternalProjects */,
  "closeExternalProject" /* CloseExternalProject */,
  "synchronizeProjectList" /* SynchronizeProjectList */,
  "emit-output" /* EmitOutput */,
  "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */,
  "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */,
  "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */,
  "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */,
  "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */,
  "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */,
  "geterrForProject" /* GeterrForProject */,
  "reload" /* Reload */,
  "reloadProjects" /* ReloadProjects */,
  "getCodeFixes" /* GetCodeFixes */,
  "getCodeFixes-full" /* GetCodeFixesFull */,
  "getCombinedCodeFix" /* GetCombinedCodeFix */,
  "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */,
  "applyCodeActionCommand" /* ApplyCodeActionCommand */,
  "getSupportedCodeFixes" /* GetSupportedCodeFixes */,
  "getApplicableRefactors" /* GetApplicableRefactors */,
  "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */,
  "getEditsForRefactor" /* GetEditsForRefactor */,
  "getEditsForRefactor-full" /* GetEditsForRefactorFull */,
  "organizeImports" /* OrganizeImports */,
  "organizeImports-full" /* OrganizeImportsFull */,
  "getEditsForFileRename" /* GetEditsForFileRename */,
  "getEditsForFileRename-full" /* GetEditsForFileRenameFull */,
  "prepareCallHierarchy" /* PrepareCallHierarchy */,
  "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */,
  "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */,
  "getPasteEdits" /* GetPasteEdits */,
  "copilotRelated" /* CopilotRelated */
];
var invalidSyntacticModeCommands = [
  ...invalidPartialSemanticModeCommands,
  "definition" /* Definition */,
  "definition-full" /* DefinitionFull */,
  "definitionAndBoundSpan" /* DefinitionAndBoundSpan */,
  "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */,
  "typeDefinition" /* TypeDefinition */,
  "implementation" /* Implementation */,
  "implementation-full" /* ImplementationFull */,
  "references" /* References */,
  "references-full" /* ReferencesFull */,
  "rename" /* Rename */,
  "renameLocations-full" /* RenameLocationsFull */,
  "rename-full" /* RenameInfoFull */,
  "quickinfo" /* Quickinfo */,
  "quickinfo-full" /* QuickinfoFull */,
  "completionInfo" /* CompletionInfo */,
  "completions" /* Completions */,
  "completions-full" /* CompletionsFull */,
  "completionEntryDetails" /* CompletionDetails */,
  "completionEntryDetails-full" /* CompletionDetailsFull */,
  "signatureHelp" /* SignatureHelp */,
  "signatureHelp-full" /* SignatureHelpFull */,
  "navto" /* Navto */,
  "navto-full" /* NavtoFull */,
  "documentHighlights" /* DocumentHighlights */,
  "documentHighlights-full" /* DocumentHighlightsFull */,
  "preparePasteEdits" /* PreparePasteEdits */
];
var Session3 = class _Session {
  constructor(opts) {
    this.changeSeq = 0;
    // Minimum number of lines for attempting to use region diagnostics for a file.
    /** @internal */
    this.regionDiagLineCountThreshold = 500;
    this.handlers = new Map(Object.entries({
      // TODO(jakebailey): correctly type the handlers
      ["status" /* Status */]: () => {
        const response = { version };
        return this.requiredResponse(response);
      },
      ["openExternalProject" /* OpenExternalProject */]: (request) => {
        this.projectService.openExternalProject(
          request.arguments,
          /*cleanupAfter*/
          true
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["openExternalProjects" /* OpenExternalProjects */]: (request) => {
        this.projectService.openExternalProjects(request.arguments.projects);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["closeExternalProject" /* CloseExternalProject */]: (request) => {
        this.projectService.closeExternalProject(
          request.arguments.projectFileName,
          /*cleanupAfter*/
          true
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["synchronizeProjectList" /* SynchronizeProjectList */]: (request) => {
        const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo);
        if (!result.some((p) => p.projectErrors && p.projectErrors.length !== 0)) {
          return this.requiredResponse(result);
        }
        const converted = map(result, (p) => {
          if (!p.projectErrors || p.projectErrors.length === 0) {
            return p;
          }
          return {
            info: p.info,
            changes: p.changes,
            files: p.files,
            projectErrors: this.convertToDiagnosticsWithLinePosition(
              p.projectErrors,
              /*scriptInfo*/
              void 0
            )
          };
        });
        return this.requiredResponse(converted);
      },
      ["updateOpen" /* UpdateOpen */]: (request) => {
        this.changeSeq++;
        this.projectService.applyChangesInOpenFiles(
          request.arguments.openFiles && mapIterator(request.arguments.openFiles, (file) => ({
            fileName: file.file,
            content: file.fileContent,
            scriptKind: file.scriptKindName,
            projectRootPath: file.projectRootPath
          })),
          request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({
            fileName: file.fileName,
            changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), (change) => {
              const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName));
              const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
              const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
              return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : void 0;
            })
          })),
          request.arguments.closedFiles
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: (request) => {
        this.changeSeq++;
        this.projectService.applyChangesInOpenFiles(
          request.arguments.openFiles,
          request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({
            fileName: file.fileName,
            // apply changes in reverse order
            changes: arrayReverseIterator(file.changes)
          })),
          request.arguments.closedFiles
        );
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["exit" /* Exit */]: () => {
        this.exit();
        return this.notRequired(
          /*request*/
          void 0
        );
      },
      ["definition" /* Definition */]: (request) => {
        return this.requiredResponse(this.getDefinition(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["definition-full" /* DefinitionFull */]: (request) => {
        return this.requiredResponse(this.getDefinition(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: (request) => {
        return this.requiredResponse(this.getDefinitionAndBoundSpan(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: (request) => {
        return this.requiredResponse(this.getDefinitionAndBoundSpan(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["findSourceDefinition" /* FindSourceDefinition */]: (request) => {
        return this.requiredResponse(this.findSourceDefinition(request.arguments));
      },
      ["emit-output" /* EmitOutput */]: (request) => {
        return this.requiredResponse(this.getEmitOutput(request.arguments));
      },
      ["typeDefinition" /* TypeDefinition */]: (request) => {
        return this.requiredResponse(this.getTypeDefinition(request.arguments));
      },
      ["implementation" /* Implementation */]: (request) => {
        return this.requiredResponse(this.getImplementation(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["implementation-full" /* ImplementationFull */]: (request) => {
        return this.requiredResponse(this.getImplementation(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["references" /* References */]: (request) => {
        return this.requiredResponse(this.getReferences(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["references-full" /* ReferencesFull */]: (request) => {
        return this.requiredResponse(this.getReferences(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["rename" /* Rename */]: (request) => {
        return this.requiredResponse(this.getRenameLocations(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["renameLocations-full" /* RenameLocationsFull */]: (request) => {
        return this.requiredResponse(this.getRenameLocations(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["rename-full" /* RenameInfoFull */]: (request) => {
        return this.requiredResponse(this.getRenameInfo(request.arguments));
      },
      ["open" /* Open */]: (request) => {
        this.openClientFile(
          toNormalizedPath(request.arguments.file),
          request.arguments.fileContent,
          convertScriptKindName(request.arguments.scriptKindName),
          // TODO: GH#18217
          request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0
        );
        return this.notRequired(request);
      },
      ["quickinfo" /* Quickinfo */]: (request) => {
        return this.requiredResponse(this.getQuickInfoWorker(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["quickinfo-full" /* QuickinfoFull */]: (request) => {
        return this.requiredResponse(this.getQuickInfoWorker(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getOutliningSpans" /* GetOutliningSpans */]: (request) => {
        return this.requiredResponse(this.getOutliningSpans(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["outliningSpans" /* GetOutliningSpansFull */]: (request) => {
        return this.requiredResponse(this.getOutliningSpans(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["todoComments" /* TodoComments */]: (request) => {
        return this.requiredResponse(this.getTodoComments(request.arguments));
      },
      ["indentation" /* Indentation */]: (request) => {
        return this.requiredResponse(this.getIndentation(request.arguments));
      },
      ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: (request) => {
        return this.requiredResponse(this.getNameOrDottedNameSpan(request.arguments));
      },
      ["breakpointStatement" /* BreakpointStatement */]: (request) => {
        return this.requiredResponse(this.getBreakpointStatement(request.arguments));
      },
      ["braceCompletion" /* BraceCompletion */]: (request) => {
        return this.requiredResponse(this.isValidBraceCompletion(request.arguments));
      },
      ["docCommentTemplate" /* DocCommentTemplate */]: (request) => {
        return this.requiredResponse(this.getDocCommentTemplate(request.arguments));
      },
      ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: (request) => {
        return this.requiredResponse(this.getSpanOfEnclosingComment(request.arguments));
      },
      ["fileReferences" /* FileReferences */]: (request) => {
        return this.requiredResponse(this.getFileReferences(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["fileReferences-full" /* FileReferencesFull */]: (request) => {
        return this.requiredResponse(this.getFileReferences(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["format" /* Format */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForRange(request.arguments));
      },
      ["formatonkey" /* Formatonkey */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsAfterKeystroke(request.arguments));
      },
      ["format-full" /* FormatFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForDocumentFull(request.arguments));
      },
      ["formatonkey-full" /* FormatonkeyFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsAfterKeystrokeFull(request.arguments));
      },
      ["formatRange-full" /* FormatRangeFull */]: (request) => {
        return this.requiredResponse(this.getFormattingEditsForRangeFull(request.arguments));
      },
      ["completionInfo" /* CompletionInfo */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completionInfo" /* CompletionInfo */));
      },
      ["completions" /* Completions */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completions" /* Completions */));
      },
      ["completions-full" /* CompletionsFull */]: (request) => {
        return this.requiredResponse(this.getCompletions(request.arguments, "completions-full" /* CompletionsFull */));
      },
      ["completionEntryDetails" /* CompletionDetails */]: (request) => {
        return this.requiredResponse(this.getCompletionEntryDetails(
          request.arguments,
          /*fullResult*/
          false
        ));
      },
      ["completionEntryDetails-full" /* CompletionDetailsFull */]: (request) => {
        return this.requiredResponse(this.getCompletionEntryDetails(
          request.arguments,
          /*fullResult*/
          true
        ));
      },
      ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: (request) => {
        return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments));
      },
      ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: (request) => {
        return this.requiredResponse(this.emitFile(request.arguments));
      },
      ["signatureHelp" /* SignatureHelp */]: (request) => {
        return this.requiredResponse(this.getSignatureHelpItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["signatureHelp-full" /* SignatureHelpFull */]: (request) => {
        return this.requiredResponse(this.getSignatureHelpItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: (request) => {
        return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments));
      },
      ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: (request) => {
        return this.requiredResponse(this.getEncodedSyntacticClassifications(request.arguments));
      },
      ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: (request) => {
        return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments));
      },
      ["cleanup" /* Cleanup */]: () => {
        this.cleanup();
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments));
      },
      ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments));
      },
      ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: (request) => {
        return this.requiredResponse(this.getSuggestionDiagnosticsSync(request.arguments));
      },
      ["geterr" /* Geterr */]: (request) => {
        this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files));
        return this.notRequired(
          /*request*/
          void 0
        );
      },
      ["geterrForProject" /* GeterrForProject */]: (request) => {
        this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file));
        return this.notRequired(
          /*request*/
          void 0
        );
      },
      ["change" /* Change */]: (request) => {
        this.change(request.arguments);
        return this.notRequired(request);
      },
      ["configure" /* Configure */]: (request) => {
        this.projectService.setHostConfiguration(request.arguments);
        return this.notRequired(request);
      },
      ["reload" /* Reload */]: (request) => {
        this.reload(request.arguments);
        return this.requiredResponse({ reloadFinished: true });
      },
      ["saveto" /* Saveto */]: (request) => {
        const savetoArgs = request.arguments;
        this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
        return this.notRequired(request);
      },
      ["close" /* Close */]: (request) => {
        const closeArgs = request.arguments;
        this.closeClientFile(closeArgs.file);
        return this.notRequired(request);
      },
      ["navto" /* Navto */]: (request) => {
        return this.requiredResponse(this.getNavigateToItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navto-full" /* NavtoFull */]: (request) => {
        return this.requiredResponse(this.getNavigateToItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["brace" /* Brace */]: (request) => {
        return this.requiredResponse(this.getBraceMatching(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["brace-full" /* BraceFull */]: (request) => {
        return this.requiredResponse(this.getBraceMatching(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["navbar" /* NavBar */]: (request) => {
        return this.requiredResponse(this.getNavigationBarItems(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navbar-full" /* NavBarFull */]: (request) => {
        return this.requiredResponse(this.getNavigationBarItems(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["navtree" /* NavTree */]: (request) => {
        return this.requiredResponse(this.getNavigationTree(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["navtree-full" /* NavTreeFull */]: (request) => {
        return this.requiredResponse(this.getNavigationTree(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["documentHighlights" /* DocumentHighlights */]: (request) => {
        return this.requiredResponse(this.getDocumentHighlights(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["documentHighlights-full" /* DocumentHighlightsFull */]: (request) => {
        return this.requiredResponse(this.getDocumentHighlights(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: (request) => {
        this.setCompilerOptionsForInferredProjects(request.arguments);
        return this.requiredResponse(
          /*response*/
          true
        );
      },
      ["projectInfo" /* ProjectInfo */]: (request) => {
        return this.requiredResponse(this.getProjectInfo(request.arguments));
      },
      ["reloadProjects" /* ReloadProjects */]: (request) => {
        this.projectService.reloadProjects();
        return this.notRequired(request);
      },
      ["jsxClosingTag" /* JsxClosingTag */]: (request) => {
        return this.requiredResponse(this.getJsxClosingTag(request.arguments));
      },
      ["linkedEditingRange" /* LinkedEditingRange */]: (request) => {
        return this.requiredResponse(this.getLinkedEditingRange(request.arguments));
      },
      ["getCodeFixes" /* GetCodeFixes */]: (request) => {
        return this.requiredResponse(this.getCodeFixes(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getCodeFixes-full" /* GetCodeFixesFull */]: (request) => {
        return this.requiredResponse(this.getCodeFixes(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getCombinedCodeFix" /* GetCombinedCodeFix */]: (request) => {
        return this.requiredResponse(this.getCombinedCodeFix(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: (request) => {
        return this.requiredResponse(this.getCombinedCodeFix(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: (request) => {
        return this.requiredResponse(this.applyCodeActionCommand(request.arguments));
      },
      ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: (request) => {
        return this.requiredResponse(this.getSupportedCodeFixes(request.arguments));
      },
      ["getApplicableRefactors" /* GetApplicableRefactors */]: (request) => {
        return this.requiredResponse(this.getApplicableRefactors(request.arguments));
      },
      ["getEditsForRefactor" /* GetEditsForRefactor */]: (request) => {
        return this.requiredResponse(this.getEditsForRefactor(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => {
        return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments));
      },
      ["preparePasteEdits" /* PreparePasteEdits */]: (request) => {
        return this.requiredResponse(this.preparePasteEdits(request.arguments));
      },
      ["getPasteEdits" /* GetPasteEdits */]: (request) => {
        return this.requiredResponse(this.getPasteEdits(request.arguments));
      },
      ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => {
        return this.requiredResponse(this.getEditsForRefactor(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["organizeImports" /* OrganizeImports */]: (request) => {
        return this.requiredResponse(this.organizeImports(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["organizeImports-full" /* OrganizeImportsFull */]: (request) => {
        return this.requiredResponse(this.organizeImports(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["getEditsForFileRename" /* GetEditsForFileRename */]: (request) => {
        return this.requiredResponse(this.getEditsForFileRename(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: (request) => {
        return this.requiredResponse(this.getEditsForFileRename(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["configurePlugin" /* ConfigurePlugin */]: (request) => {
        this.configurePlugin(request.arguments);
        return this.notRequired(request);
      },
      ["selectionRange" /* SelectionRange */]: (request) => {
        return this.requiredResponse(this.getSmartSelectionRange(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["selectionRange-full" /* SelectionRangeFull */]: (request) => {
        return this.requiredResponse(this.getSmartSelectionRange(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["prepareCallHierarchy" /* PrepareCallHierarchy */]: (request) => {
        return this.requiredResponse(this.prepareCallHierarchy(request.arguments));
      },
      ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: (request) => {
        return this.requiredResponse(this.provideCallHierarchyIncomingCalls(request.arguments));
      },
      ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: (request) => {
        return this.requiredResponse(this.provideCallHierarchyOutgoingCalls(request.arguments));
      },
      ["toggleLineComment" /* ToggleLineComment */]: (request) => {
        return this.requiredResponse(this.toggleLineComment(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["toggleLineComment-full" /* ToggleLineCommentFull */]: (request) => {
        return this.requiredResponse(this.toggleLineComment(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["toggleMultilineComment" /* ToggleMultilineComment */]: (request) => {
        return this.requiredResponse(this.toggleMultilineComment(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: (request) => {
        return this.requiredResponse(this.toggleMultilineComment(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["commentSelection" /* CommentSelection */]: (request) => {
        return this.requiredResponse(this.commentSelection(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["commentSelection-full" /* CommentSelectionFull */]: (request) => {
        return this.requiredResponse(this.commentSelection(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["uncommentSelection" /* UncommentSelection */]: (request) => {
        return this.requiredResponse(this.uncommentSelection(
          request.arguments,
          /*simplifiedResult*/
          true
        ));
      },
      ["uncommentSelection-full" /* UncommentSelectionFull */]: (request) => {
        return this.requiredResponse(this.uncommentSelection(
          request.arguments,
          /*simplifiedResult*/
          false
        ));
      },
      ["provideInlayHints" /* ProvideInlayHints */]: (request) => {
        return this.requiredResponse(this.provideInlayHints(request.arguments));
      },
      ["mapCode" /* MapCode */]: (request) => {
        return this.requiredResponse(this.mapCode(request.arguments));
      },
      ["copilotRelated" /* CopilotRelated */]: () => {
        return this.requiredResponse(this.getCopilotRelatedInfo());
      }
    }));
    this.host = opts.host;
    this.cancellationToken = opts.cancellationToken;
    this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
    this.byteLength = opts.byteLength;
    this.hrtime = opts.hrtime;
    this.logger = opts.logger;
    this.canUseEvents = opts.canUseEvents;
    this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents;
    this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate;
    const { throttleWaitMilliseconds } = opts;
    this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0;
    const multistepOperationHost = {
      executeWithRequestId: (requestId, action, performanceData) => this.executeWithRequestId(requestId, action, performanceData),
      getCurrentRequestId: () => this.currentRequestId,
      getPerformanceData: () => this.performanceData,
      getServerHost: () => this.host,
      logError: (err, cmd) => this.logError(err, cmd),
      sendRequestCompletedEvent: (requestId, performanceData) => this.sendRequestCompletedEvent(requestId, performanceData),
      isCancellationRequested: () => this.cancellationToken.isCancellationRequested()
    };
    this.errorCheck = new MultistepOperation(multistepOperationHost);
    const settings = {
      host: this.host,
      logger: this.logger,
      cancellationToken: this.cancellationToken,
      useSingleInferredProject: opts.useSingleInferredProject,
      useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot,
      typingsInstaller: this.typingsInstaller,
      throttleWaitMilliseconds,
      eventHandler: this.eventHandler,
      suppressDiagnosticEvents: this.suppressDiagnosticEvents,
      globalPlugins: opts.globalPlugins,
      pluginProbeLocations: opts.pluginProbeLocations,
      allowLocalPluginLoads: opts.allowLocalPluginLoads,
      typesMapLocation: opts.typesMapLocation,
      serverMode: opts.serverMode,
      session: this,
      canUseWatchEvents: opts.canUseWatchEvents,
      incrementalVerifier: opts.incrementalVerifier
    };
    this.projectService = new ProjectService2(settings);
    this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this));
    this.gcTimer = new GcTimer(
      this.host,
      /*delay*/
      7e3,
      this.logger
    );
    switch (this.projectService.serverMode) {
      case 0 /* Semantic */:
        break;
      case 1 /* PartialSemantic */:
        invalidPartialSemanticModeCommands.forEach(
          (commandName) => this.handlers.set(commandName, (request) => {
            throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`);
          })
        );
        break;
      case 2 /* Syntactic */:
        invalidSyntacticModeCommands.forEach(
          (commandName) => this.handlers.set(commandName, (request) => {
            throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`);
          })
        );
        break;
      default:
        Debug.assertNever(this.projectService.serverMode);
    }
  }
  sendRequestCompletedEvent(requestId, performanceData) {
    this.event(
      {
        request_seq: requestId,
        performanceData: performanceData && toProtocolPerformanceData(performanceData)
      },
      "requestCompleted"
    );
  }
  addPerformanceData(key, value) {
    if (!this.performanceData) {
      this.performanceData = {};
    }
    this.performanceData[key] = (this.performanceData[key] ?? 0) + value;
  }
  addDiagnosticsPerformanceData(file, kind, duration) {
    var _a, _b;
    if (!this.performanceData) {
      this.performanceData = {};
    }
    let fileDiagnosticDuration = (_a = this.performanceData.diagnosticsDuration) == null ? void 0 : _a.get(file);
    if (!fileDiagnosticDuration) ((_b = this.performanceData).diagnosticsDuration ?? (_b.diagnosticsDuration = /* @__PURE__ */ new Map())).set(file, fileDiagnosticDuration = {});
    fileDiagnosticDuration[kind] = duration;
  }
  performanceEventHandler(event) {
    switch (event.kind) {
      case "UpdateGraph":
        this.addPerformanceData("updateGraphDurationMs", event.durationMs);
        break;
      case "CreatePackageJsonAutoImportProvider":
        this.addPerformanceData("createAutoImportProviderProgramDurationMs", event.durationMs);
        break;
    }
  }
  defaultEventHandler(event) {
    switch (event.eventName) {
      case ProjectsUpdatedInBackgroundEvent:
        this.projectsUpdatedInBackgroundEvent(event.data.openFiles);
        break;
      case ProjectLoadingStartEvent:
        this.event({
          projectName: event.data.project.getProjectName(),
          reason: event.data.reason
        }, event.eventName);
        break;
      case ProjectLoadingFinishEvent:
        this.event({
          projectName: event.data.project.getProjectName()
        }, event.eventName);
        break;
      case LargeFileReferencedEvent:
      case CreateFileWatcherEvent:
      case CreateDirectoryWatcherEvent:
      case CloseFileWatcherEvent:
        this.event(event.data, event.eventName);
        break;
      case ConfigFileDiagEvent:
        this.event({
          triggerFile: event.data.triggerFile,
          configFile: event.data.configFileName,
          diagnostics: map(event.data.diagnostics, (diagnostic) => formatDiagnosticToProtocol(
            diagnostic,
            /*includeFileName*/
            true
          ))
        }, event.eventName);
        break;
      case ProjectLanguageServiceStateEvent: {
        this.event({
          projectName: event.data.project.getProjectName(),
          languageServiceEnabled: event.data.languageServiceEnabled
        }, event.eventName);
        break;
      }
      case ProjectInfoTelemetryEvent: {
        const eventName = "telemetry";
        this.event({
          telemetryEventName: event.eventName,
          payload: event.data
        }, eventName);
        break;
      }
    }
  }
  projectsUpdatedInBackgroundEvent(openFiles) {
    this.projectService.logger.info(`got projects updated in background ${openFiles}`);
    if (openFiles.length) {
      if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) {
        this.projectService.logger.info(`Queueing diagnostics update for ${openFiles}`);
        this.errorCheck.startNew((next) => this.updateErrorCheck(
          next,
          openFiles,
          100,
          /*requireOpen*/
          true
        ));
      }
      this.event({
        openFiles
      }, ProjectsUpdatedInBackgroundEvent);
    }
  }
  logError(err, cmd) {
    this.logErrorWorker(err, cmd);
  }
  logErrorWorker(err, cmd, fileRequest) {
    let msg = "Exception on executing command " + cmd;
    if (err.message) {
      msg += ":\n" + indent2(err.message);
      if (err.stack) {
        msg += "\n" + indent2(err.stack);
      }
    }
    if (this.logger.hasLevel(3 /* verbose */)) {
      if (fileRequest) {
        try {
          const { file, project } = this.getFileAndProject(fileRequest);
          const scriptInfo = project.getScriptInfoForNormalizedPath(file);
          if (scriptInfo) {
            const text = getSnapshotText(scriptInfo.getSnapshot());
            msg += `

File text of ${fileRequest.file}:${indent2(text)}
`;
          }
        } catch {
        }
      }
      if (err.ProgramFiles) {
        msg += `

Program files: ${JSON.stringify(err.ProgramFiles)}
`;
        msg += `

Projects::
`;
        let counter = 0;
        const addProjectInfo = (project) => {
          msg += `
Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter}
`;
          msg += project.filesToString(
            /*writeProjectFileNames*/
            true
          );
          msg += "\n-----------------------------------------------\n";
          counter++;
        };
        this.projectService.externalProjects.forEach(addProjectInfo);
        this.projectService.configuredProjects.forEach(addProjectInfo);
        this.projectService.inferredProjects.forEach(addProjectInfo);
      }
    }
    this.logger.msg(msg, "Err" /* Err */);
  }
  send(msg) {
    if (msg.type === "event" && !this.canUseEvents) {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`Session does not support events: ignored event: ${stringifyIndented(msg)}`);
      }
      return;
    }
    this.writeMessage(msg);
  }
  writeMessage(msg) {
    const msgText = formatMessage2(msg, this.logger, this.byteLength, this.host.newLine);
    this.host.write(msgText);
  }
  event(body, eventName) {
    this.send(toEvent(eventName, body));
  }
  /** @internal */
  doOutput(info, cmdName, reqSeq, success, performanceData, message) {
    const res = {
      seq: 0,
      type: "response",
      command: cmdName,
      request_seq: reqSeq,
      success,
      performanceData: performanceData && toProtocolPerformanceData(performanceData)
    };
    if (success) {
      let metadata;
      if (isArray(info)) {
        res.body = info;
        metadata = info.metadata;
        delete info.metadata;
      } else if (typeof info === "object") {
        if (info.metadata) {
          const { metadata: infoMetadata, ...body } = info;
          res.body = body;
          metadata = infoMetadata;
        } else {
          res.body = info;
        }
      } else {
        res.body = info;
      }
      if (metadata) res.metadata = metadata;
    } else {
      Debug.assert(info === void 0);
    }
    if (message) {
      res.message = message;
    }
    this.send(res);
  }
  semanticCheck(file, project) {
    var _a, _b;
    const diagnosticsStartTime = timestamp();
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath });
    const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file);
    this.sendDiagnosticsEvent(file, project, diags, "semanticDiag", diagnosticsStartTime);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  syntacticCheck(file, project) {
    var _a, _b;
    const diagnosticsStartTime = timestamp();
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath });
    this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag", diagnosticsStartTime);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  suggestionCheck(file, project) {
    var _a, _b;
    const diagnosticsStartTime = timestamp();
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath });
    this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag", diagnosticsStartTime);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  regionSemanticCheck(file, project, ranges) {
    var _a, _b, _c;
    const diagnosticsStartTime = timestamp();
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "regionSemanticCheck", { file, configFilePath: project.canonicalConfigFilePath });
    let diagnosticsResult;
    if (!this.shouldDoRegionCheck(file) || !(diagnosticsResult = project.getLanguageService().getRegionSemanticDiagnostics(file, ranges))) {
      (_b = tracing) == null ? void 0 : _b.pop();
      return;
    }
    this.sendDiagnosticsEvent(file, project, diagnosticsResult.diagnostics, "regionSemanticDiag", diagnosticsStartTime, diagnosticsResult.spans);
    (_c = tracing) == null ? void 0 : _c.pop();
    return;
  }
  // We should only do the region-based semantic check if we think it would be
  // considerably faster than a whole-file semantic check.
  /** @internal */
  shouldDoRegionCheck(file) {
    var _a;
    const lineCount = (_a = this.projectService.getScriptInfoForNormalizedPath(file)) == null ? void 0 : _a.textStorage.getLineInfo().getLineCount();
    return !!(lineCount && lineCount >= this.regionDiagLineCountThreshold);
  }
  sendDiagnosticsEvent(file, project, diagnostics, kind, diagnosticsStartTime, spans) {
    try {
      const scriptInfo = Debug.checkDefined(project.getScriptInfo(file));
      const duration = timestamp() - diagnosticsStartTime;
      const body = {
        file,
        diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)),
        spans: spans == null ? void 0 : spans.map((span) => toProtocolTextSpan(span, scriptInfo))
      };
      this.event(
        body,
        kind
      );
      this.addDiagnosticsPerformanceData(file, kind, duration);
    } catch (err) {
      this.logError(err, kind);
    }
  }
  /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
  updateErrorCheck(next, checkList, ms, requireOpen = true) {
    if (checkList.length === 0) {
      return;
    }
    Debug.assert(!this.suppressDiagnosticEvents);
    const seq = this.changeSeq;
    const followMs = Math.min(ms, 200);
    let index = 0;
    const goNext = () => {
      index++;
      if (checkList.length > index) {
        return next.delay("checkOne", followMs, checkOne);
      }
    };
    const doSemanticCheck = (fileName, project) => {
      this.semanticCheck(fileName, project);
      if (this.changeSeq !== seq) {
        return;
      }
      if (this.getPreferences(fileName).disableSuggestions) {
        return goNext();
      }
      next.immediate("suggestionCheck", () => {
        this.suggestionCheck(fileName, project);
        goNext();
      });
    };
    const checkOne = () => {
      if (this.changeSeq !== seq) {
        return;
      }
      let ranges;
      let item = checkList[index];
      if (isString(item)) {
        item = this.toPendingErrorCheck(item);
      } else if ("ranges" in item) {
        ranges = item.ranges;
        item = this.toPendingErrorCheck(item.file);
      }
      if (!item) {
        return goNext();
      }
      const { fileName, project } = item;
      updateProjectIfDirty(project);
      if (!project.containsFile(fileName, requireOpen)) {
        return;
      }
      this.syntacticCheck(fileName, project);
      if (this.changeSeq !== seq) {
        return;
      }
      if (project.projectService.serverMode !== 0 /* Semantic */) {
        return goNext();
      }
      if (ranges) {
        return next.immediate("regionSemanticCheck", () => {
          const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(fileName);
          if (scriptInfo) {
            this.regionSemanticCheck(fileName, project, ranges.map((range) => this.getRange({ file: fileName, ...range }, scriptInfo)));
          }
          if (this.changeSeq !== seq) {
            return;
          }
          next.immediate("semanticCheck", () => doSemanticCheck(fileName, project));
        });
      }
      next.immediate("semanticCheck", () => doSemanticCheck(fileName, project));
    };
    if (checkList.length > index && this.changeSeq === seq) {
      next.delay("checkOne", ms, checkOne);
    }
  }
  cleanProjects(caption, projects) {
    if (!projects) {
      return;
    }
    this.logger.info(`cleaning ${caption}`);
    for (const p of projects) {
      p.getLanguageService(
        /*ensureSynchronized*/
        false
      ).cleanupSemanticCache();
      p.cleanupProgram();
    }
  }
  cleanup() {
    this.cleanProjects("inferred projects", this.projectService.inferredProjects);
    this.cleanProjects("configured projects", arrayFrom(this.projectService.configuredProjects.values()));
    this.cleanProjects("external projects", this.projectService.externalProjects);
    if (this.host.gc) {
      this.logger.info(`host.gc()`);
      this.host.gc();
    }
  }
  getEncodedSyntacticClassifications(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    return languageService.getEncodedSyntacticClassifications(file, args);
  }
  getEncodedSemanticClassifications(args) {
    const { file, project } = this.getFileAndProject(args);
    const format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */;
    return project.getLanguageService().getEncodedSemanticClassifications(file, args, format);
  }
  getProject(projectFileName) {
    return projectFileName === void 0 ? void 0 : this.projectService.findProject(projectFileName);
  }
  getConfigFileAndProject(args) {
    const project = this.getProject(args.projectFileName);
    const file = toNormalizedPath(args.file);
    return {
      configFile: project && project.hasConfigFile(file) ? file : void 0,
      project
    };
  }
  getConfigFileDiagnostics(configFile, project, includeLinePosition) {
    const projectErrors = project.getAllProjectErrors();
    const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics();
    const diagnosticsForConfigFile = filter(
      concatenate(projectErrors, optionsErrors),
      (diagnostic) => !!diagnostic.file && diagnostic.file.fileName === configFile
    );
    return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map(
      diagnosticsForConfigFile,
      (diagnostic) => formatDiagnosticToProtocol(
        diagnostic,
        /*includeFileName*/
        false
      )
    );
  }
  convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) {
    return diagnostics.map((d) => ({
      message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
      start: d.start,
      // TODO: GH#18217
      length: d.length,
      // TODO: GH#18217
      category: diagnosticCategoryName(d),
      code: d.code,
      source: d.source,
      startLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start)),
      // TODO: GH#18217
      endLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start + d.length)),
      // TODO: GH#18217
      reportsUnnecessary: d.reportsUnnecessary,
      reportsDeprecated: d.reportsDeprecated,
      relatedInformation: map(d.relatedInformation, formatRelatedInformation)
    }));
  }
  getCompilerOptionsDiagnostics(args) {
    const project = this.getProject(args.projectFileName);
    return this.convertToDiagnosticsWithLinePosition(
      filter(
        project.getLanguageService().getCompilerOptionsDiagnostics(),
        (diagnostic) => !diagnostic.file
      ),
      /*scriptInfo*/
      void 0
    );
  }
  convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) {
    return diagnostics.map(
      (d) => ({
        message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
        start: d.start,
        length: d.length,
        category: diagnosticCategoryName(d),
        code: d.code,
        source: d.source,
        startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start),
        // TODO: GH#18217
        endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length),
        reportsUnnecessary: d.reportsUnnecessary,
        reportsDeprecated: d.reportsDeprecated,
        relatedInformation: map(d.relatedInformation, formatRelatedInformation)
      })
    );
  }
  getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition) {
    const { project, file } = this.getFileAndProject(args);
    if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) {
      return emptyArray2;
    }
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const diagnostics = selector(project, file);
    return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map((d) => formatDiag(file, project, d));
  }
  getDefinition(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray2, project);
    return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(_Session.mapToOriginalLocation);
  }
  mapDefinitionInfoLocations(definitions, project) {
    return definitions.map((info) => {
      const newDocumentSpan = getMappedDocumentSpanForProject(info, project);
      return !newDocumentSpan ? info : {
        ...newDocumentSpan,
        containerKind: info.containerKind,
        containerName: info.containerName,
        kind: info.kind,
        name: info.name,
        failedAliasResolution: info.failedAliasResolution,
        ...info.unverified && { unverified: info.unverified }
      };
    });
  }
  getDefinitionAndBoundSpan(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const scriptInfo = Debug.checkDefined(project.getScriptInfo(file));
    const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position);
    if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
      return {
        definitions: emptyArray2,
        textSpan: void 0
        // TODO: GH#18217
      };
    }
    const definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
    const { textSpan } = unmappedDefinitionAndBoundSpan;
    if (simplifiedResult) {
      return {
        definitions: this.mapDefinitionInfo(definitions, project),
        textSpan: toProtocolTextSpan(textSpan, scriptInfo)
      };
    }
    return {
      definitions: definitions.map(_Session.mapToOriginalLocation),
      textSpan
    };
  }
  findSourceDefinition(args) {
    var _a;
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const unmappedDefinitions = project.getLanguageService().getDefinitionAtPosition(file, position);
    let definitions = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray2, project).slice();
    const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, (d) => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, (d) => !!d.failedAliasResolution));
    if (needsJsResolution) {
      const definitionSet = createSet(
        (d) => d.textSpan.start,
        getDocumentSpansEqualityComparer(this.host.useCaseSensitiveFileNames)
      );
      definitions == null ? void 0 : definitions.forEach((d) => definitionSet.add(d));
      const noDtsProject = project.getNoDtsResolutionProject(file);
      const ls = noDtsProject.getLanguageService();
      const jsDefinitions = (_a = ls.getDefinitionAtPosition(
        file,
        position,
        /*searchOtherFilesOnly*/
        true,
        /*stopAtAlias*/
        false
      )) == null ? void 0 : _a.filter((d) => toNormalizedPath(d.fileName) !== file);
      if (some(jsDefinitions)) {
        for (const jsDefinition of jsDefinitions) {
          if (jsDefinition.unverified) {
            const refined = tryRefineDefinition(jsDefinition, project.getLanguageService().getProgram(), ls.getProgram());
            if (some(refined)) {
              for (const def of refined) {
                definitionSet.add(def);
              }
              continue;
            }
          }
          definitionSet.add(jsDefinition);
        }
      } else {
        const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient);
        for (const candidate of some(ambientCandidates) ? ambientCandidates : getAmbientCandidatesByClimbingAccessChain()) {
          const fileNameToSearch = findImplementationFileFromDtsFileName(candidate.fileName, file, noDtsProject);
          if (!fileNameToSearch) continue;
          const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(
            fileNameToSearch,
            noDtsProject.currentDirectory,
            noDtsProject.directoryStructureHost,
            /*deferredDeleteOk*/
            false
          );
          if (!info) continue;
          if (!noDtsProject.containsScriptInfo(info)) {
            noDtsProject.addRoot(info);
            noDtsProject.updateGraph();
          }
          const noDtsProgram = ls.getProgram();
          const fileToSearch = Debug.checkDefined(noDtsProgram.getSourceFile(fileNameToSearch));
          for (const match of searchForDeclaration(candidate.name, fileToSearch, noDtsProgram)) {
            definitionSet.add(match);
          }
        }
      }
      definitions = arrayFrom(definitionSet.values());
    }
    definitions = definitions.filter((d) => !d.isAmbient && !d.failedAliasResolution);
    return this.mapDefinitionInfo(definitions, project);
    function findImplementationFileFromDtsFileName(fileName, resolveFromFile, auxiliaryProject) {
      var _a2, _b, _c;
      const nodeModulesPathParts = getNodeModulePathParts(fileName);
      if (nodeModulesPathParts && fileName.lastIndexOf(nodeModulesPathPart) === nodeModulesPathParts.topLevelNodeModulesIndex) {
        const packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex);
        const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache();
        const compilerOptions = project.getCompilationSettings();
        const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory, project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
        if (!packageJson) return void 0;
        const entrypoints = getEntrypointsFromPackageJsonInfo(
          packageJson,
          { moduleResolution: 2 /* Node10 */ },
          project,
          project.getModuleResolutionCache()
        );
        const packageNamePathPart = fileName.substring(
          nodeModulesPathParts.topLevelPackageNameIndex + 1,
          nodeModulesPathParts.packageRootIndex
        );
        const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart));
        const path = project.toPath(fileName);
        if (entrypoints && some(entrypoints, (e) => project.toPath(e) === path)) {
          return (_b = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(packageName, resolveFromFile).resolvedModule) == null ? void 0 : _b.resolvedFileName;
        } else {
          const pathToFileInPackage = fileName.substring(nodeModulesPathParts.packageRootIndex + 1);
          const specifier = `${packageName}/${removeFileExtension(pathToFileInPackage)}`;
          return (_c = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(specifier, resolveFromFile).resolvedModule) == null ? void 0 : _c.resolvedFileName;
        }
      }
      return void 0;
    }
    function getAmbientCandidatesByClimbingAccessChain() {
      const ls = project.getLanguageService();
      const program = ls.getProgram();
      const initialNode = getTouchingPropertyName(program.getSourceFile(file), position);
      if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) {
        return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => {
          var _a2;
          if (nameInChain === initialNode) return void 0;
          const candidates = (_a2 = ls.getDefinitionAtPosition(
            file,
            nameInChain.getStart(),
            /*searchOtherFilesOnly*/
            true,
            /*stopAtAlias*/
            false
          )) == null ? void 0 : _a2.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient).map((d) => ({
            fileName: d.fileName,
            name: getTextOfIdentifierOrLiteral(initialNode)
          }));
          if (some(candidates)) {
            return candidates;
          }
        }) || emptyArray2;
      }
      return emptyArray2;
    }
    function tryRefineDefinition(definition, program, noDtsProgram) {
      var _a2;
      const fileToSearch = noDtsProgram.getSourceFile(definition.fileName);
      if (!fileToSearch) {
        return void 0;
      }
      const initialNode = getTouchingPropertyName(program.getSourceFile(file), position);
      const symbol = program.getTypeChecker().getSymbolAtLocation(initialNode);
      const importSpecifier = symbol && getDeclarationOfKind(symbol, 276 /* ImportSpecifier */);
      if (!importSpecifier) return void 0;
      const nameToSearch = ((_a2 = importSpecifier.propertyName) == null ? void 0 : _a2.text) || importSpecifier.name.text;
      return searchForDeclaration(nameToSearch, fileToSearch, noDtsProgram);
    }
    function searchForDeclaration(declarationName, fileToSearch, noDtsProgram) {
      const matches = ts_FindAllReferences_exports.Core.getTopMostDeclarationNamesInFile(declarationName, fileToSearch);
      return mapDefined(matches, (match) => {
        const symbol = noDtsProgram.getTypeChecker().getSymbolAtLocation(match);
        const decl = getDeclarationFromName(match);
        if (symbol && decl) {
          return ts_GoToDefinition_exports.createDefinitionInfo(
            decl,
            noDtsProgram.getTypeChecker(),
            symbol,
            decl,
            /*unverified*/
            true
          );
        }
      });
    }
  }
  getEmitOutput(args) {
    const { file, project } = this.getFileAndProject(args);
    if (!project.shouldEmitFile(project.getScriptInfo(file))) {
      return { emitSkipped: true, outputFiles: [], diagnostics: [] };
    }
    const result = project.getLanguageService().getEmitOutput(file);
    return args.richResponse ? {
      ...result,
      diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map((d) => formatDiagnosticToProtocol(
        d,
        /*includeFileName*/
        true
      ))
    } : result;
  }
  mapJSDocTagInfo(tags, project, richResponse) {
    return tags ? tags.map((tag) => {
      var _a;
      return {
        ...tag,
        text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map((part) => part.text).join("")
      };
    }) : [];
  }
  mapDisplayParts(parts, project) {
    if (!parts) {
      return [];
    }
    return parts.map(
      (part) => part.kind !== "linkName" ? part : {
        ...part,
        target: this.toFileSpan(part.target.fileName, part.target.textSpan, project)
      }
    );
  }
  mapSignatureHelpItems(items, project, richResponse) {
    return items.map((item) => ({
      ...item,
      documentation: this.mapDisplayParts(item.documentation, project),
      parameters: item.parameters.map((p) => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })),
      tags: this.mapJSDocTagInfo(item.tags, project, richResponse)
    }));
  }
  mapDefinitionInfo(definitions, project) {
    return definitions.map((def) => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } }));
  }
  /*
   * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
   * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
   * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
   * set of additional fields, and does the reverse for VS (store the .d.ts location where
   * it used to be and stores the .ts location in the additional fields).
   */
  static mapToOriginalLocation(def) {
    if (def.originalFileName) {
      Debug.assert(def.originalTextSpan !== void 0, "originalTextSpan should be present if originalFileName is");
      return {
        ...def,
        fileName: def.originalFileName,
        textSpan: def.originalTextSpan,
        targetFileName: def.fileName,
        targetTextSpan: def.textSpan,
        contextSpan: def.originalContextSpan,
        targetContextSpan: def.contextSpan
      };
    }
    return def;
  }
  toFileSpan(fileName, textSpan, project) {
    const ls = project.getLanguageService();
    const start = ls.toLineColumnOffset(fileName, textSpan.start);
    const end = ls.toLineColumnOffset(fileName, textSpanEnd(textSpan));
    return {
      file: fileName,
      start: { line: start.line + 1, offset: start.character + 1 },
      end: { line: end.line + 1, offset: end.character + 1 }
    };
  }
  toFileSpanWithContext(fileName, textSpan, contextSpan, project) {
    const fileSpan = this.toFileSpan(fileName, textSpan, project);
    const context = contextSpan && this.toFileSpan(fileName, contextSpan, project);
    return context ? { ...fileSpan, contextStart: context.start, contextEnd: context.end } : fileSpan;
  }
  getTypeDefinition(args) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || emptyArray2, project);
    return this.mapDefinitionInfo(definitions, project);
  }
  mapImplementationLocations(implementations, project) {
    return implementations.map((info) => {
      const newDocumentSpan = getMappedDocumentSpanForProject(info, project);
      return !newDocumentSpan ? info : {
        ...newDocumentSpan,
        kind: info.kind,
        displayParts: info.displayParts
      };
    });
  }
  getImplementation(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray2, project);
    return simplifiedResult ? implementations.map(({ fileName, textSpan, contextSpan }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(_Session.mapToOriginalLocation);
  }
  getSyntacticDiagnosticsSync(args) {
    const { configFile } = this.getConfigFileAndProject(args);
    if (configFile) {
      return emptyArray2;
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      false,
      (project, file) => project.getLanguageService().getSyntacticDiagnostics(file),
      !!args.includeLinePosition
    );
  }
  getSemanticDiagnosticsSync(args) {
    const { configFile, project } = this.getConfigFileAndProject(args);
    if (configFile) {
      return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition);
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      true,
      (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file),
      !!args.includeLinePosition
    );
  }
  getSuggestionDiagnosticsSync(args) {
    const { configFile } = this.getConfigFileAndProject(args);
    if (configFile) {
      return emptyArray2;
    }
    return this.getDiagnosticsWorker(
      args,
      /*isSemantic*/
      true,
      (project, file) => project.getLanguageService().getSuggestionDiagnostics(file),
      !!args.includeLinePosition
    );
  }
  getJsxClosingTag(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const tag = languageService.getJsxClosingTagAtPosition(file, position);
    return tag === void 0 ? void 0 : { newText: tag.newText, caretOffset: 0 };
  }
  getLinkedEditingRange(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const linkedEditInfo = languageService.getLinkedEditingRangeAtPosition(file, position);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    if (scriptInfo === void 0 || linkedEditInfo === void 0) return void 0;
    return convertLinkedEditInfoToRanges(linkedEditInfo, scriptInfo);
  }
  getDocumentHighlights(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch);
    if (!documentHighlights) return emptyArray2;
    if (!simplifiedResult) return documentHighlights;
    return documentHighlights.map(({ fileName, highlightSpans }) => {
      const scriptInfo = project.getScriptInfo(fileName);
      return {
        file: fileName,
        highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({
          ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo),
          kind
        }))
      };
    });
  }
  provideInlayHints(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file));
    return hints.map((hint) => {
      const { position, displayParts } = hint;
      return {
        ...hint,
        position: scriptInfo.positionToLineOffset(position),
        displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => {
          if (span) {
            Debug.assertIsDefined(file2, "Target file should be defined together with its span.");
            const scriptInfo2 = this.projectService.getScriptInfo(file2);
            return {
              text,
              span: {
                start: scriptInfo2.positionToLineOffset(span.start),
                end: scriptInfo2.positionToLineOffset(span.start + span.length),
                file: file2
              }
            };
          } else {
            return { text };
          }
        })
      };
    });
  }
  mapCode(args) {
    var _a;
    const formatOptions = this.getHostFormatOptions();
    const preferences = this.getHostPreferences();
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const focusLocations = (_a = args.mapping.focusLocations) == null ? void 0 : _a.map((spans) => {
      return spans.map((loc) => {
        const start = scriptInfo.lineOffsetToPosition(loc.start.line, loc.start.offset);
        const end = scriptInfo.lineOffsetToPosition(loc.end.line, loc.end.offset);
        return {
          start,
          length: end - start
        };
      });
    });
    const changes = languageService.mapCode(file, args.mapping.contents, focusLocations, formatOptions, preferences);
    return this.mapTextChangesToCodeEdits(changes);
  }
  getCopilotRelatedInfo() {
    return {
      relatedFiles: []
    };
  }
  setCompilerOptionsForInferredProjects(args) {
    this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
  }
  getProjectInfo(args) {
    return this.getProjectInfoWorker(
      args.file,
      args.projectFileName,
      args.needFileNameList,
      args.needDefaultConfiguredProjectInfo,
      /*excludeConfigFiles*/
      false
    );
  }
  getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, needDefaultConfiguredProjectInfo, excludeConfigFiles) {
    const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName);
    updateProjectIfDirty(project);
    const projectInfo = {
      configFileName: project.getProjectName(),
      languageServiceDisabled: !project.languageServiceEnabled,
      fileNames: needFileNameList ? project.getFileNames(
        /*excludeFilesFromExternalLibraries*/
        false,
        excludeConfigFiles
      ) : void 0,
      configuredProjectInfo: needDefaultConfiguredProjectInfo ? this.getDefaultConfiguredProjectInfo(uncheckedFileName) : void 0
    };
    return projectInfo;
  }
  getDefaultConfiguredProjectInfo(uncheckedFileName) {
    var _a;
    const info = this.projectService.getScriptInfo(uncheckedFileName);
    if (!info) return;
    const result = this.projectService.findDefaultConfiguredProjectWorker(
      info,
      3 /* CreateReplay */
    );
    if (!result) return void 0;
    let notMatchedByConfig;
    let notInProject;
    result.seenProjects.forEach((kind, project) => {
      if (project !== result.defaultProject) {
        if (kind !== 3 /* CreateReplay */) {
          (notMatchedByConfig ?? (notMatchedByConfig = [])).push(toNormalizedPath(project.getConfigFilePath()));
        } else {
          (notInProject ?? (notInProject = [])).push(toNormalizedPath(project.getConfigFilePath()));
        }
      }
    });
    (_a = result.seenConfigs) == null ? void 0 : _a.forEach((config) => (notMatchedByConfig ?? (notMatchedByConfig = [])).push(config));
    return {
      notMatchedByConfig,
      notInProject,
      defaultProject: result.defaultProject && toNormalizedPath(result.defaultProject.getConfigFilePath())
    };
  }
  getRenameInfo(args) {
    const { file, project } = this.getFileAndProject(args);
    const position = this.getPositionInFile(args, file);
    const preferences = this.getPreferences(file);
    return project.getLanguageService().getRenameInfo(file, position, preferences);
  }
  getProjects(args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
    let projects;
    let symLinkedProjects;
    if (args.projectFileName) {
      const project = this.getProject(args.projectFileName);
      if (project) {
        projects = [project];
      }
    } else {
      const scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file);
      if (!scriptInfo) {
        if (ignoreNoProjectError) return emptyArray2;
        this.projectService.logErrorForScriptInfoNotFound(args.file);
        return Errors.ThrowNoProject();
      } else if (!getScriptInfoEnsuringProjectsUptoDate) {
        this.projectService.ensureDefaultProjectForFile(scriptInfo);
      }
      projects = scriptInfo.containingProjects;
      symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo);
    }
    projects = filter(projects, (p) => p.languageServiceEnabled && !p.isOrphan());
    if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
      this.projectService.logErrorForScriptInfoNotFound(args.file ?? args.projectFileName);
      return Errors.ThrowNoProject();
    }
    return symLinkedProjects ? { projects, symLinkedProjects } : projects;
  }
  getDefaultProject(args) {
    if (args.projectFileName) {
      const project = this.getProject(args.projectFileName);
      if (project) {
        return project;
      }
      if (!args.file) {
        return Errors.ThrowNoProject();
      }
    }
    const info = this.projectService.getScriptInfo(args.file);
    return info.getDefaultProject();
  }
  getRenameLocations(args, simplifiedResult) {
    const file = toNormalizedPath(args.file);
    const position = this.getPositionInFile(args, file);
    const projects = this.getProjects(args);
    const defaultProject = this.getDefaultProject(args);
    const preferences = this.getPreferences(file);
    const renameInfo = this.mapRenameInfo(
      defaultProject.getLanguageService().getRenameInfo(file, position, preferences),
      Debug.checkDefined(this.projectService.getScriptInfo(file))
    );
    if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : [];
    const locations = getRenameLocationsWorker(
      projects,
      defaultProject,
      { fileName: args.file, pos: position },
      !!args.findInStrings,
      !!args.findInComments,
      preferences,
      this.host.useCaseSensitiveFileNames
    );
    if (!simplifiedResult) return locations;
    return { info: renameInfo, locs: this.toSpanGroups(locations) };
  }
  mapRenameInfo(info, scriptInfo) {
    if (info.canRename) {
      const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info;
      return identity(
        { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) }
      );
    } else {
      return info;
    }
  }
  toSpanGroups(locations) {
    const map2 = /* @__PURE__ */ new Map();
    for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) {
      let group2 = map2.get(fileName);
      if (!group2) map2.set(fileName, group2 = { file: fileName, locs: [] });
      const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName));
      group2.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText });
    }
    return arrayFrom(map2.values());
  }
  getReferences(args, simplifiedResult) {
    const file = toNormalizedPath(args.file);
    const projects = this.getProjects(args);
    const position = this.getPositionInFile(args, file);
    const references = getReferencesWorker(
      projects,
      this.getDefaultProject(args),
      { fileName: args.file, pos: position },
      this.host.useCaseSensitiveFileNames,
      this.logger
    );
    if (!simplifiedResult) return references;
    const preferences = this.getPreferences(file);
    const defaultProject = this.getDefaultProject(args);
    const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
    const nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position);
    const symbolDisplayString = nameInfo ? displayPartsToString(nameInfo.displayParts) : "";
    const nameSpan = nameInfo && nameInfo.textSpan;
    const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0;
    const symbolName2 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : "";
    const refs = flatMap(references, (referencedSymbol) => {
      return referencedSymbol.references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences));
    });
    return { refs, symbolName: symbolName2, symbolStartOffset, symbolDisplayString };
  }
  getFileReferences(args, simplifiedResult) {
    const projects = this.getProjects(args);
    const fileName = toNormalizedPath(args.file);
    const preferences = this.getPreferences(fileName);
    const initialLocation = { fileName, pos: 0 };
    const perProjectResults = getPerProjectReferences(
      projects,
      this.getDefaultProject(args),
      initialLocation,
      initialLocation,
      mapDefinitionInProjectIfFileInProject,
      (project) => {
        this.logger.info(`Finding references to file ${fileName} in project ${project.getProjectName()}`);
        return project.getLanguageService().getFileReferences(fileName);
      }
    );
    let references;
    if (isArray(perProjectResults)) {
      references = perProjectResults;
    } else {
      references = [];
      const seen = createDocumentSpanSet(this.host.useCaseSensitiveFileNames);
      perProjectResults.forEach((projectOutputs) => {
        for (const referenceEntry of projectOutputs) {
          if (!seen.has(referenceEntry)) {
            references.push(referenceEntry);
            seen.add(referenceEntry);
          }
        }
      });
    }
    if (!simplifiedResult) return references;
    const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences));
    return {
      refs,
      symbolName: `"${args.file}"`
    };
  }
  /**
   * @param fileName is the name of the file to be opened
   * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
   */
  openClientFile(fileName, fileContent, scriptKind, projectRootPath) {
    this.projectService.openClientFileWithNormalizedPath(
      fileName,
      fileContent,
      scriptKind,
      /*hasMixedContent*/
      false,
      projectRootPath
    );
  }
  getPosition(args, scriptInfo) {
    return args.position !== void 0 ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
  }
  getPositionInFile(args, file) {
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    return this.getPosition(args, scriptInfo);
  }
  getFileAndProject(args) {
    return this.getFileAndProjectWorker(args.file, args.projectFileName);
  }
  getFileAndLanguageServiceForSyntacticOperation(args) {
    const { file, project } = this.getFileAndProject(args);
    return {
      file,
      languageService: project.getLanguageService(
        /*ensureSynchronized*/
        false
      )
    };
  }
  getFileAndProjectWorker(uncheckedFileName, projectFileName) {
    const file = toNormalizedPath(uncheckedFileName);
    const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file);
    return { file, project };
  }
  getOutliningSpans(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const spans = languageService.getOutliningSpans(file);
    if (simplifiedResult) {
      const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
      return spans.map((s) => ({
        textSpan: toProtocolTextSpan(s.textSpan, scriptInfo),
        hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo),
        bannerText: s.bannerText,
        autoCollapse: s.autoCollapse,
        kind: s.kind
      }));
    } else {
      return spans;
    }
  }
  getTodoComments(args) {
    const { file, project } = this.getFileAndProject(args);
    return project.getLanguageService().getTodoComments(file, args.descriptors);
  }
  getDocCommentTemplate(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file));
  }
  getSpanOfEnclosingComment(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const onlyMultiLine = args.onlyMultiLine;
    const position = this.getPositionInFile(args, file);
    return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine);
  }
  getIndentation(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    const indentation = languageService.getIndentationAtPosition(file, position, options);
    return { position, indentation };
  }
  getBreakpointStatement(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getBreakpointStatementAtPosition(file, position);
  }
  getNameOrDottedNameSpan(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.getNameOrDottedNameSpan(file, position, position);
  }
  isValidBraceCompletion(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const position = this.getPositionInFile(args, file);
    return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0));
  }
  getQuickInfoWorker(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo));
    if (!quickInfo) {
      return void 0;
    }
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    if (simplifiedResult) {
      const displayString = displayPartsToString(quickInfo.displayParts);
      return {
        kind: quickInfo.kind,
        kindModifiers: quickInfo.kindModifiers,
        start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start),
        end: scriptInfo.positionToLineOffset(textSpanEnd(quickInfo.textSpan)),
        displayString,
        documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : displayPartsToString(quickInfo.documentation),
        tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts)
      };
    } else {
      return useDisplayParts ? quickInfo : {
        ...quickInfo,
        tags: this.mapJSDocTagInfo(
          quickInfo.tags,
          project,
          /*richResponse*/
          false
        )
      };
    }
  }
  getFormattingEditsForRange(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
    const edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file));
    if (!edits) {
      return void 0;
    }
    return edits.map((edit) => this.convertTextChangeToCodeEdit(edit, scriptInfo));
  }
  getFormattingEditsForRangeFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options);
  }
  getFormattingEditsForDocumentFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsForDocument(file, options);
  }
  getFormattingEditsAfterKeystrokeFull(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file);
    return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
  }
  getFormattingEditsAfterKeystroke(args) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const formatOptions = this.getFormatOptions(file);
    const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
    if (args.key === "\n" && (!edits || edits.length === 0 || allEditsBeforePos(edits, position))) {
      const { lineText, absolutePosition } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line);
      if (lineText && lineText.search("\\S") < 0) {
        const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions);
        let hasIndent = 0;
        let i, len;
        for (i = 0, len = lineText.length; i < len; i++) {
          if (lineText.charAt(i) === " ") {
            hasIndent++;
          } else if (lineText.charAt(i) === "	") {
            hasIndent += formatOptions.tabSize;
          } else {
            break;
          }
        }
        if (preferredIndent !== hasIndent) {
          const firstNoWhiteSpacePosition = absolutePosition + i;
          edits.push({
            span: createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition),
            newText: ts_formatting_exports.getIndentationString(preferredIndent, formatOptions)
          });
        }
      }
    }
    if (!edits) {
      return void 0;
    }
    return edits.map((edit) => {
      return {
        start: scriptInfo.positionToLineOffset(edit.span.start),
        end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)),
        newText: edit.newText ? edit.newText : ""
      };
    });
  }
  getCompletions(args, kind) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const completions = project.getLanguageService().getCompletionsAtPosition(
      file,
      position,
      {
        ...convertUserPreferences(this.getPreferences(file)),
        triggerCharacter: args.triggerCharacter,
        triggerKind: args.triggerKind,
        includeExternalModuleExports: args.includeExternalModuleExports,
        includeInsertTextCompletions: args.includeInsertTextCompletions
      },
      project.projectService.getFormatCodeOptions(file)
    );
    if (completions === void 0) return void 0;
    if (kind === "completions-full" /* CompletionsFull */) return completions;
    const prefix = args.prefix || "";
    const entries = mapDefined(completions.entries, (entry) => {
      if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
        const convertedSpan = entry.replacementSpan ? toProtocolTextSpan(entry.replacementSpan, scriptInfo) : void 0;
        return {
          ...entry,
          replacementSpan: convertedSpan,
          hasAction: entry.hasAction || void 0,
          symbol: void 0
        };
      }
    });
    if (kind === "completions" /* Completions */) {
      if (completions.metadata) entries.metadata = completions.metadata;
      return entries;
    }
    const res = {
      ...completions,
      optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo),
      entries
    };
    return res;
  }
  getCompletionEntryDetails(args, fullResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const formattingOptions = project.projectService.getFormatCodeOptions(file);
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    const result = mapDefined(args.entryNames, (entryName) => {
      const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: void 0, data: void 0 } : entryName;
      return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : void 0);
    });
    return fullResult ? useDisplayParts ? result : result.map((details) => ({ ...details, tags: this.mapJSDocTagInfo(
      details.tags,
      project,
      /*richResponse*/
      false
    ) })) : result.map((details) => ({
      ...details,
      codeActions: map(details.codeActions, (action) => this.mapCodeAction(action)),
      documentation: this.mapDisplayParts(details.documentation, project),
      tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts)
    }));
  }
  getCompileOnSaveAffectedFileList(args) {
    const projects = this.getProjects(
      args,
      /*getScriptInfoEnsuringProjectsUptoDate*/
      true,
      /*ignoreNoProjectError*/
      true
    );
    const info = this.projectService.getScriptInfo(args.file);
    if (!info) {
      return emptyArray2;
    }
    return combineProjectOutput(
      info,
      (path) => this.projectService.getScriptInfoForPath(path),
      projects,
      (project, info2) => {
        if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) {
          return void 0;
        }
        const compilationSettings = project.getCompilationSettings();
        if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) {
          return void 0;
        }
        return {
          projectFileName: project.getProjectName(),
          fileNames: project.getCompileOnSaveAffectedFileList(info2),
          projectUsesOutFile: !!compilationSettings.outFile
        };
      }
    );
  }
  emitFile(args) {
    const { file, project } = this.getFileAndProject(args);
    if (!project) {
      Errors.ThrowNoProject();
    }
    if (!project.languageServiceEnabled) {
      return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false;
    }
    const scriptInfo = project.getScriptInfo(file);
    const { emitSkipped, diagnostics } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark));
    return args.richResponse ? {
      emitSkipped,
      diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map((d) => formatDiagnosticToProtocol(
        d,
        /*includeFileName*/
        true
      ))
    } : !emitSkipped;
  }
  getSignatureHelpItems(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args);
    const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc;
    if (helpItems && simplifiedResult) {
      const span = helpItems.applicableSpan;
      return {
        ...helpItems,
        applicableSpan: {
          start: scriptInfo.positionToLineOffset(span.start),
          end: scriptInfo.positionToLineOffset(span.start + span.length)
        },
        items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts)
      };
    } else if (useDisplayParts || !helpItems) {
      return helpItems;
    } else {
      return {
        ...helpItems,
        items: helpItems.items.map((item) => ({ ...item, tags: this.mapJSDocTagInfo(
          item.tags,
          project,
          /*richResponse*/
          false
        ) }))
      };
    }
  }
  toPendingErrorCheck(uncheckedFileName) {
    const fileName = toNormalizedPath(uncheckedFileName);
    const project = this.projectService.tryGetDefaultProjectForFile(fileName);
    return project && { fileName, project };
  }
  getDiagnostics(next, delay, fileArgs) {
    if (this.suppressDiagnosticEvents) {
      return;
    }
    if (fileArgs.length > 0) {
      this.updateErrorCheck(next, fileArgs, delay);
    }
  }
  change(args) {
    const scriptInfo = this.projectService.getScriptInfo(args.file);
    Debug.assert(!!scriptInfo);
    scriptInfo.textStorage.switchToScriptVersionCache();
    const start = scriptInfo.lineOffsetToPosition(args.line, args.offset);
    const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
    if (start >= 0) {
      this.changeSeq++;
      this.projectService.applyChangesToFile(
        scriptInfo,
        singleIterator({
          span: { start, length: end - start },
          newText: args.insertString
          // TODO: GH#18217
        })
      );
    }
  }
  reload(args) {
    const file = toNormalizedPath(args.file);
    const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile);
    const info = this.projectService.getScriptInfoForNormalizedPath(file);
    if (info) {
      this.changeSeq++;
      info.reloadFromFile(tempFileName);
    }
  }
  saveToTmp(fileName, tempFileName) {
    const scriptInfo = this.projectService.getScriptInfo(fileName);
    if (scriptInfo) {
      scriptInfo.saveTo(tempFileName);
    }
  }
  closeClientFile(fileName) {
    if (!fileName) {
      return;
    }
    const file = normalizePath(fileName);
    this.projectService.closeClientFile(file);
  }
  mapLocationNavigationBarItems(items, scriptInfo) {
    return map(items, (item) => ({
      text: item.text,
      kind: item.kind,
      kindModifiers: item.kindModifiers,
      spans: item.spans.map((span) => toProtocolTextSpan(span, scriptInfo)),
      childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo),
      indent: item.indent
    }));
  }
  getNavigationBarItems(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const items = languageService.getNavigationBarItems(file);
    return !items ? void 0 : simplifiedResult ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items;
  }
  toLocationNavigationTree(tree, scriptInfo) {
    return {
      text: tree.text,
      kind: tree.kind,
      kindModifiers: tree.kindModifiers,
      spans: tree.spans.map((span) => toProtocolTextSpan(span, scriptInfo)),
      nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo),
      childItems: map(tree.childItems, (item) => this.toLocationNavigationTree(item, scriptInfo))
    };
  }
  getNavigationTree(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const tree = languageService.getNavigationTree(file);
    return !tree ? void 0 : simplifiedResult ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree;
  }
  getNavigateToItems(args, simplifiedResult) {
    const full = this.getFullNavigateToItems(args);
    return !simplifiedResult ? flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap(
      full,
      ({ project, navigateToItems }) => navigateToItems.map((navItem) => {
        const scriptInfo = project.getScriptInfo(navItem.fileName);
        const bakedItem = {
          name: navItem.name,
          kind: navItem.kind,
          kindModifiers: navItem.kindModifiers,
          isCaseSensitive: navItem.isCaseSensitive,
          matchKind: navItem.matchKind,
          file: navItem.fileName,
          start: scriptInfo.positionToLineOffset(navItem.textSpan.start),
          end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan))
        };
        if (navItem.kindModifiers && navItem.kindModifiers !== "") {
          bakedItem.kindModifiers = navItem.kindModifiers;
        }
        if (navItem.containerName && navItem.containerName.length > 0) {
          bakedItem.containerName = navItem.containerName;
        }
        if (navItem.containerKind && navItem.containerKind.length > 0) {
          bakedItem.containerKind = navItem.containerKind;
        }
        return bakedItem;
      })
    );
  }
  getFullNavigateToItems(args) {
    const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args;
    if (currentFileOnly) {
      Debug.assertIsDefined(args.file);
      const { file, project } = this.getFileAndProject(args);
      return [{ project, navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }];
    }
    const preferences = this.getHostPreferences();
    const outputs = [];
    const seenItems = /* @__PURE__ */ new Map();
    if (!args.file && !projectFileName) {
      this.projectService.loadAncestorProjectTree();
      this.projectService.forEachEnabledProject((project) => addItemsForProject(project));
    } else {
      const projects = this.getProjects(args);
      forEachProjectInProjects(
        projects,
        /*path*/
        void 0,
        (project) => addItemsForProject(project)
      );
    }
    return outputs;
    function addItemsForProject(project) {
      const projectItems = project.getLanguageService().getNavigateToItems(
        searchValue,
        maxResultCount,
        /*fileName*/
        void 0,
        /*excludeDts*/
        project.isNonTsProject(),
        /*excludeLibFiles*/
        preferences.excludeLibrarySymbolsInNavTo
      );
      const unseenItems = filter(projectItems, (item) => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project));
      if (unseenItems.length) {
        outputs.push({ project, navigateToItems: unseenItems });
      }
    }
    function tryAddSeenItem(item) {
      const name = item.name;
      if (!seenItems.has(name)) {
        seenItems.set(name, [item]);
        return true;
      }
      const seen = seenItems.get(name);
      for (const seenItem of seen) {
        if (navigateToItemIsEqualTo(seenItem, item)) {
          return false;
        }
      }
      seen.push(item);
      return true;
    }
    function navigateToItemIsEqualTo(a, b) {
      if (a === b) {
        return true;
      }
      if (!a || !b) {
        return false;
      }
      return a.containerKind === b.containerKind && a.containerName === b.containerName && a.fileName === b.fileName && a.isCaseSensitive === b.isCaseSensitive && a.kind === b.kind && a.kindModifiers === b.kindModifiers && a.matchKind === b.matchKind && a.name === b.name && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length;
    }
  }
  getSupportedCodeFixes(args) {
    if (!args) return getSupportedCodeFixes();
    if (args.file) {
      const { file, project: project2 } = this.getFileAndProject(args);
      return project2.getLanguageService().getSupportedCodeFixes(file);
    }
    const project = this.getProject(args.projectFileName);
    if (!project) Errors.ThrowNoProject();
    return project.getLanguageService().getSupportedCodeFixes();
  }
  isLocation(locationOrSpan) {
    return locationOrSpan.line !== void 0;
  }
  extractPositionOrRange(args, scriptInfo) {
    let position;
    let textRange;
    if (this.isLocation(args)) {
      position = getPosition(args);
    } else {
      textRange = this.getRange(args, scriptInfo);
    }
    return Debug.checkDefined(position === void 0 ? textRange : position);
    function getPosition(loc) {
      return loc.position !== void 0 ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
    }
  }
  getRange(args, scriptInfo) {
    const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
    return { pos: startPosition, end: endPosition };
  }
  getApplicableRefactors(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const result = project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions);
    return result.map((result2) => ({ ...result2, actions: result2.actions.map((action) => ({ ...action, range: action.range ? { start: convertToLocation({ line: action.range.start.line, character: action.range.start.offset }), end: convertToLocation({ line: action.range.end.line, character: action.range.end.offset }) } : void 0 })) }));
  }
  getEditsForRefactor(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const result = project.getLanguageService().getEditsForRefactor(
      file,
      this.getFormatOptions(file),
      this.extractPositionOrRange(args, scriptInfo),
      args.refactor,
      args.action,
      this.getPreferences(file),
      args.interactiveRefactorArguments
    );
    if (result === void 0) {
      return {
        edits: []
      };
    }
    if (simplifiedResult) {
      const { renameFilename, renameLocation, edits } = result;
      let mappedRenameLocation;
      if (renameFilename !== void 0 && renameLocation !== void 0) {
        const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename));
        mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits);
      }
      return {
        renameLocation: mappedRenameLocation,
        renameFilename,
        edits: this.mapTextChangesToCodeEdits(edits),
        notApplicableReason: result.notApplicableReason
      };
    }
    return result;
  }
  getMoveToRefactoringFileSuggestions(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file));
  }
  preparePasteEdits(args) {
    const { file, project } = this.getFileAndProject(args);
    return project.getLanguageService().preparePasteEditsForFile(file, args.copiedTextSpan.map((copies) => this.getRange({ file, startLine: copies.start.line, startOffset: copies.start.offset, endLine: copies.end.line, endOffset: copies.end.offset }, this.projectService.getScriptInfoForNormalizedPath(file))));
  }
  getPasteEdits(args) {
    const { file, project } = this.getFileAndProject(args);
    if (isDynamicFileName(file)) return void 0;
    const copiedFrom = args.copiedFrom ? { file: args.copiedFrom.file, range: args.copiedFrom.spans.map((copies) => this.getRange({ file: args.copiedFrom.file, startLine: copies.start.line, startOffset: copies.start.offset, endLine: copies.end.line, endOffset: copies.end.offset }, project.getScriptInfoForNormalizedPath(toNormalizedPath(args.copiedFrom.file)))) } : void 0;
    const result = project.getLanguageService().getPasteEdits(
      {
        targetFile: file,
        pastedText: args.pastedText,
        pasteLocations: args.pasteLocations.map((paste) => this.getRange({ file, startLine: paste.start.line, startOffset: paste.start.offset, endLine: paste.end.line, endOffset: paste.end.offset }, project.getScriptInfoForNormalizedPath(file))),
        copiedFrom,
        preferences: this.getPreferences(file)
      },
      this.getFormatOptions(file)
    );
    return result && this.mapPasteEditsAction(result);
  }
  organizeImports(args, simplifiedResult) {
    Debug.assert(args.scope.type === "file");
    const { file, project } = this.getFileAndProject(args.scope.args);
    const changes = project.getLanguageService().organizeImports(
      {
        fileName: file,
        mode: args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0),
        type: "file"
      },
      this.getFormatOptions(file),
      this.getPreferences(file)
    );
    if (simplifiedResult) {
      return this.mapTextChangesToCodeEdits(changes);
    } else {
      return changes;
    }
  }
  getEditsForFileRename(args, simplifiedResult) {
    const oldPath = toNormalizedPath(args.oldFilePath);
    const newPath = toNormalizedPath(args.newFilePath);
    const formatOptions = this.getHostFormatOptions();
    const preferences = this.getHostPreferences();
    const seenFiles = /* @__PURE__ */ new Set();
    const textChanges2 = [];
    this.projectService.loadAncestorProjectTree();
    this.projectService.forEachEnabledProject((project) => {
      const projectTextChanges = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences);
      const projectFiles = [];
      for (const textChange of projectTextChanges) {
        if (!seenFiles.has(textChange.fileName)) {
          textChanges2.push(textChange);
          projectFiles.push(textChange.fileName);
        }
      }
      for (const file of projectFiles) {
        seenFiles.add(file);
      }
    });
    return simplifiedResult ? textChanges2.map((c) => this.mapTextChangeToCodeEdit(c)) : textChanges2;
  }
  getCodeFixes(args, simplifiedResult) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = project.getScriptInfoForNormalizedPath(file);
    const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
    let codeActions;
    try {
      codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file));
    } catch (e) {
      const ls = project.getLanguageService();
      const existingDiagCodes = [
        ...ls.getSyntacticDiagnostics(file),
        ...ls.getSemanticDiagnostics(file),
        ...ls.getSuggestionDiagnostics(file)
      ].map(
        (d) => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code
      );
      const badCode = args.errorCodes.find((c) => !existingDiagCodes.includes(c));
      if (badCode !== void 0) {
        e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error:
${e.message}`;
      }
      throw e;
    }
    return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions;
  }
  getCombinedCodeFix({ scope, fixId: fixId56 }, simplifiedResult) {
    Debug.assert(scope.type === "file");
    const { file, project } = this.getFileAndProject(scope.args);
    const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId56, this.getFormatOptions(file), this.getPreferences(file));
    if (simplifiedResult) {
      return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands };
    } else {
      return res;
    }
  }
  applyCodeActionCommand(args) {
    const commands = args.command;
    for (const command of toArray(commands)) {
      const { file, project } = this.getFileAndProject(command);
      project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(
        (_result) => {
        },
        (_error) => {
        }
      );
    }
    return {};
  }
  getStartAndEndPosition(args, scriptInfo) {
    let startPosition, endPosition;
    if (args.startPosition !== void 0) {
      startPosition = args.startPosition;
    } else {
      startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
      args.startPosition = startPosition;
    }
    if (args.endPosition !== void 0) {
      endPosition = args.endPosition;
    } else {
      endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
      args.endPosition = endPosition;
    }
    return { startPosition, endPosition };
  }
  mapCodeAction({ description: description3, changes, commands }) {
    return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands };
  }
  mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId56, fixAllDescription }) {
    return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId56, fixAllDescription };
  }
  mapPasteEditsAction({ edits, fixId: fixId56 }) {
    return { edits: this.mapTextChangesToCodeEdits(edits), fixId: fixId56 };
  }
  mapTextChangesToCodeEdits(textChanges2) {
    return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change));
  }
  mapTextChangeToCodeEdit(textChanges2) {
    const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges2.fileName);
    if (!!textChanges2.isNewFile === !!scriptInfo) {
      if (!scriptInfo) {
        this.projectService.logErrorForScriptInfoNotFound(textChanges2.fileName);
      }
      Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges2.isNewFile, hasScriptInfo: !!scriptInfo }));
    }
    return scriptInfo ? { fileName: textChanges2.fileName, textChanges: textChanges2.textChanges.map((textChange) => convertTextChangeToCodeEdit(textChange, scriptInfo)) } : convertNewFileTextChangeToCodeEdit(textChanges2);
  }
  convertTextChangeToCodeEdit(change, scriptInfo) {
    return {
      start: scriptInfo.positionToLineOffset(change.span.start),
      end: scriptInfo.positionToLineOffset(change.span.start + change.span.length),
      newText: change.newText ? change.newText : ""
    };
  }
  getBraceMatching(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const position = this.getPosition(args, scriptInfo);
    const spans = languageService.getBraceMatchingAtPosition(file, position);
    return !spans ? void 0 : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans;
  }
  getDiagnosticsForProject(next, delay, fileName) {
    if (this.suppressDiagnosticEvents) {
      return;
    }
    const { fileNames, languageServiceDisabled } = this.getProjectInfoWorker(
      fileName,
      /*projectFileName*/
      void 0,
      /*needFileNameList*/
      true,
      /*needDefaultConfiguredProjectInfo*/
      void 0,
      /*excludeConfigFiles*/
      true
    );
    if (languageServiceDisabled) return;
    const fileNamesInProject = fileNames.filter((value) => !value.includes("lib.d.ts"));
    if (fileNamesInProject.length === 0) return;
    const highPriorityFiles = [];
    const mediumPriorityFiles = [];
    const lowPriorityFiles = [];
    const veryLowPriorityFiles = [];
    const normalizedFileName = toNormalizedPath(fileName);
    const project = this.projectService.ensureDefaultProjectForFile(normalizedFileName);
    for (const fileNameInProject of fileNamesInProject) {
      if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) {
        highPriorityFiles.push(fileNameInProject);
      } else {
        const info = this.projectService.getScriptInfo(fileNameInProject);
        if (!info.isScriptOpen()) {
          if (isDeclarationFileName(fileNameInProject)) {
            veryLowPriorityFiles.push(fileNameInProject);
          } else {
            lowPriorityFiles.push(fileNameInProject);
          }
        } else {
          mediumPriorityFiles.push(fileNameInProject);
        }
      }
    }
    const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
    const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
    this.updateErrorCheck(
      next,
      checkList,
      delay,
      /*requireOpen*/
      false
    );
  }
  configurePlugin(args) {
    this.projectService.configurePlugin(args);
  }
  getSmartSelectionRange(args, simplifiedResult) {
    const { locations } = args;
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file));
    return map(locations, (location) => {
      const pos = this.getPosition(location, scriptInfo);
      const selectionRange = languageService.getSmartSelectionRange(file, pos);
      return simplifiedResult ? this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange;
    });
  }
  toggleLineComment(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfo(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.toggleLineComment(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  toggleMultilineComment(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.toggleMultilineComment(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  commentSelection(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.commentSelection(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  uncommentSelection(args, simplifiedResult) {
    const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    const textRange = this.getRange(args, scriptInfo);
    const textChanges2 = languageService.uncommentSelection(file, textRange);
    if (simplifiedResult) {
      const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file);
      return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2));
    }
    return textChanges2;
  }
  mapSelectionRange(selectionRange, scriptInfo) {
    const result = {
      textSpan: toProtocolTextSpan(selectionRange.textSpan, scriptInfo)
    };
    if (selectionRange.parent) {
      result.parent = this.mapSelectionRange(selectionRange.parent, scriptInfo);
    }
    return result;
  }
  getScriptInfoFromProjectService(file) {
    const normalizedFile = toNormalizedPath(file);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(normalizedFile);
    if (!scriptInfo) {
      this.projectService.logErrorForScriptInfoNotFound(normalizedFile);
      return Errors.ThrowNoProject();
    }
    return scriptInfo;
  }
  toProtocolCallHierarchyItem(item) {
    const scriptInfo = this.getScriptInfoFromProjectService(item.file);
    return {
      name: item.name,
      kind: item.kind,
      kindModifiers: item.kindModifiers,
      file: item.file,
      containerName: item.containerName,
      span: toProtocolTextSpan(item.span, scriptInfo),
      selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo)
    };
  }
  toProtocolCallHierarchyIncomingCall(incomingCall) {
    const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file);
    return {
      from: this.toProtocolCallHierarchyItem(incomingCall.from),
      fromSpans: incomingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo))
    };
  }
  toProtocolCallHierarchyOutgoingCall(outgoingCall, scriptInfo) {
    return {
      to: this.toProtocolCallHierarchyItem(outgoingCall.to),
      fromSpans: outgoingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo))
    };
  }
  prepareCallHierarchy(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
    if (scriptInfo) {
      const position = this.getPosition(args, scriptInfo);
      const result = project.getLanguageService().prepareCallHierarchy(file, position);
      return result && mapOneOrMany(result, (item) => this.toProtocolCallHierarchyItem(item));
    }
    return void 0;
  }
  provideCallHierarchyIncomingCalls(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.getScriptInfoFromProjectService(file);
    const incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo));
    return incomingCalls.map((call) => this.toProtocolCallHierarchyIncomingCall(call));
  }
  provideCallHierarchyOutgoingCalls(args) {
    const { file, project } = this.getFileAndProject(args);
    const scriptInfo = this.getScriptInfoFromProjectService(file);
    const outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo));
    return outgoingCalls.map((call) => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo));
  }
  getCanonicalFileName(fileName) {
    const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName);
    return normalizePath(name);
  }
  exit() {
  }
  notRequired(request) {
    if (request) this.doOutput(
      /*info*/
      void 0,
      request.command,
      request.seq,
      /*success*/
      true,
      this.performanceData
    );
    return { responseRequired: false, performanceData: this.performanceData };
  }
  requiredResponse(response) {
    return { response, responseRequired: true, performanceData: this.performanceData };
  }
  addProtocolHandler(command, handler) {
    if (this.handlers.has(command)) {
      throw new Error(`Protocol handler already exists for command "${command}"`);
    }
    this.handlers.set(command, handler);
  }
  setCurrentRequest(requestId) {
    Debug.assert(this.currentRequestId === void 0);
    this.currentRequestId = requestId;
    this.cancellationToken.setRequest(requestId);
  }
  resetCurrentRequest(requestId) {
    Debug.assert(this.currentRequestId === requestId);
    this.currentRequestId = void 0;
    this.cancellationToken.resetRequest(requestId);
  }
  // eslint-disable-line @typescript-eslint/unified-signatures
  executeWithRequestId(requestId, f, perfomanceData) {
    const currentPerformanceData = this.performanceData;
    try {
      this.performanceData = perfomanceData;
      this.setCurrentRequest(requestId);
      return f();
    } finally {
      this.resetCurrentRequest(requestId);
      this.performanceData = currentPerformanceData;
    }
  }
  executeCommand(request) {
    const handler = this.handlers.get(request.command);
    if (handler) {
      const response = this.executeWithRequestId(
        request.seq,
        () => handler(request),
        /*perfomanceData*/
        void 0
      );
      this.projectService.enableRequestedPlugins();
      return response;
    } else {
      this.logger.msg(`Unrecognized JSON command:${stringifyIndented(request)}`, "Err" /* Err */);
      this.doOutput(
        /*info*/
        void 0,
        "unknown" /* Unknown */,
        request.seq,
        /*success*/
        false,
        /*performanceData*/
        void 0,
        `Unrecognized JSON command: ${request.command}`
      );
      return { responseRequired: false };
    }
  }
  onMessage(message) {
    var _a, _b, _c, _d, _e, _f, _g;
    this.gcTimer.scheduleCollect();
    let start;
    const currentPerformanceData = this.performanceData;
    if (this.logger.hasLevel(2 /* requestTime */)) {
      start = this.hrtime();
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`request:${indent2(this.toStringMessage(message))}`);
      }
    }
    let request;
    let relevantFile;
    try {
      request = this.parseMessage(message);
      relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0;
      (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command });
      (_b = tracing) == null ? void 0 : _b.push(
        tracing.Phase.Session,
        "executeCommand",
        { seq: request.seq, command: request.command },
        /*separateBeginAndEnd*/
        true
      );
      const { response, responseRequired, performanceData } = this.executeCommand(request);
      (_c = tracing) == null ? void 0 : _c.pop();
      if (this.logger.hasLevel(2 /* requestTime */)) {
        const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4);
        if (responseRequired) {
          this.logger.perftrc(`${request.seq}::${request.command}: elapsed time (in milliseconds) ${elapsedTime}`);
        } else {
          this.logger.perftrc(`${request.seq}::${request.command}: async elapsed time (in milliseconds) ${elapsedTime}`);
        }
      }
      (_d = tracing) == null ? void 0 : _d.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response });
      if (response) {
        this.doOutput(
          response,
          request.command,
          request.seq,
          /*success*/
          true,
          performanceData
        );
      } else if (responseRequired) {
        this.doOutput(
          /*info*/
          void 0,
          request.command,
          request.seq,
          /*success*/
          false,
          performanceData,
          "No content available."
        );
      }
    } catch (err) {
      (_e = tracing) == null ? void 0 : _e.popAll();
      if (err instanceof OperationCanceledException) {
        (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command });
        this.doOutput(
          { canceled: true },
          request.command,
          request.seq,
          /*success*/
          true,
          this.performanceData
        );
        return;
      }
      this.logErrorWorker(err, this.toStringMessage(message), relevantFile);
      (_g = tracing) == null ? void 0 : _g.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message });
      this.doOutput(
        /*info*/
        void 0,
        request ? request.command : "unknown" /* Unknown */,
        request ? request.seq : 0,
        /*success*/
        false,
        this.performanceData,
        "Error processing request. " + err.message + "\n" + err.stack
      );
    } finally {
      this.performanceData = currentPerformanceData;
    }
  }
  parseMessage(message) {
    return JSON.parse(message);
  }
  toStringMessage(message) {
    return message;
  }
  getFormatOptions(file) {
    return this.projectService.getFormatCodeOptions(file);
  }
  getPreferences(file) {
    return this.projectService.getPreferences(file);
  }
  getHostFormatOptions() {
    return this.projectService.getHostFormatCodeOptions();
  }
  getHostPreferences() {
    return this.projectService.getHostPreferences();
  }
};
function toProtocolPerformanceData(performanceData) {
  const diagnosticsDuration = performanceData.diagnosticsDuration && arrayFrom(performanceData.diagnosticsDuration, ([file, data]) => ({ ...data, file }));
  return { ...performanceData, diagnosticsDuration };
}
function toProtocolTextSpan(textSpan, scriptInfo) {
  return {
    start: scriptInfo.positionToLineOffset(textSpan.start),
    end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan))
  };
}
function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) {
  const textSpan = toProtocolTextSpan(span, scriptInfo);
  const contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo);
  return contextTextSpan ? { ...textSpan, contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end } : textSpan;
}
function convertTextChangeToCodeEdit(change, scriptInfo) {
  return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText };
}
function positionToLineOffset(info, position) {
  return isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position);
}
function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) {
  const ranges = linkedEdit.ranges.map(
    (r) => {
      return {
        start: scriptInfo.positionToLineOffset(r.start),
        end: scriptInfo.positionToLineOffset(r.start + r.length)
      };
    }
  );
  if (!linkedEdit.wordPattern) return { ranges };
  return { ranges, wordPattern: linkedEdit.wordPattern };
}
function locationFromLineAndCharacter(lc) {
  return { line: lc.line + 1, offset: lc.character + 1 };
}
function convertNewFileTextChangeToCodeEdit(textChanges2) {
  Debug.assert(textChanges2.textChanges.length === 1);
  const change = first(textChanges2.textChanges);
  Debug.assert(change.span.start === 0 && change.span.length === 0);
  return { fileName: textChanges2.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
}
function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) {
  const newText = applyEdits(oldText, renameFilename, edits);
  const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation);
  return { line: line + 1, offset: character + 1 };
}
function applyEdits(text, textFilename, edits) {
  for (const { fileName, textChanges: textChanges2 } of edits) {
    if (fileName !== textFilename) {
      continue;
    }
    for (let i = textChanges2.length - 1; i >= 0; i--) {
      const { newText, span: { start, length: length2 } } = textChanges2[i];
      text = text.slice(0, start) + newText + text.slice(start + length2);
    }
  }
  return text;
}
function referenceEntryToReferencesResponseItem(projectService, { fileName, textSpan, contextSpan, isWriteAccess: isWriteAccess2, isDefinition }, { disableLineTextInReferences }) {
  const scriptInfo = Debug.checkDefined(projectService.getScriptInfo(fileName));
  const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo);
  const lineText = disableLineTextInReferences ? void 0 : getLineText(scriptInfo, span);
  return {
    file: fileName,
    ...span,
    lineText,
    isWriteAccess: isWriteAccess2,
    isDefinition
  };
}
function getLineText(scriptInfo, span) {
  const lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1);
  return scriptInfo.getSnapshot().getText(lineSpan.start, textSpanEnd(lineSpan)).replace(/\r|\n/g, "");
}
function isCompletionEntryData(data) {
  return data === void 0 || data && typeof data === "object" && typeof data.exportName === "string" && (data.fileName === void 0 || typeof data.fileName === "string") && (data.ambientModuleName === void 0 || typeof data.ambientModuleName === "string" && (data.isPackageJsonImport === void 0 || typeof data.isPackageJsonImport === "boolean"));
}

// src/server/scriptVersionCache.ts
var lineCollectionCapacity = 4;
var CharRangeSection = /* @__PURE__ */ ((CharRangeSection2) => {
  CharRangeSection2[CharRangeSection2["PreStart"] = 0] = "PreStart";
  CharRangeSection2[CharRangeSection2["Start"] = 1] = "Start";
  CharRangeSection2[CharRangeSection2["Entire"] = 2] = "Entire";
  CharRangeSection2[CharRangeSection2["Mid"] = 3] = "Mid";
  CharRangeSection2[CharRangeSection2["End"] = 4] = "End";
  CharRangeSection2[CharRangeSection2["PostEnd"] = 5] = "PostEnd";
  return CharRangeSection2;
})(CharRangeSection || {});
var EditWalker = class {
  constructor() {
    this.goSubtree = true;
    this.lineIndex = new LineIndex();
    this.endBranch = [];
    this.state = 2 /* Entire */;
    this.initialText = "";
    this.trailingText = "";
    this.lineIndex.root = new LineNode();
    this.startPath = [this.lineIndex.root];
    this.stack = [this.lineIndex.root];
  }
  get done() {
    return false;
  }
  insertLines(insertedText, suppressTrailingText) {
    if (suppressTrailingText) {
      this.trailingText = "";
    }
    if (insertedText) {
      insertedText = this.initialText + insertedText + this.trailingText;
    } else {
      insertedText = this.initialText + this.trailingText;
    }
    const lm = LineIndex.linesFromText(insertedText);
    const lines = lm.lines;
    if (lines.length > 1 && lines[lines.length - 1] === "") {
      lines.pop();
    }
    let branchParent;
    let lastZeroCount;
    for (let k = this.endBranch.length - 1; k >= 0; k--) {
      this.endBranch[k].updateCounts();
      if (this.endBranch[k].charCount() === 0) {
        lastZeroCount = this.endBranch[k];
        if (k > 0) {
          branchParent = this.endBranch[k - 1];
        } else {
          branchParent = this.branchNode;
        }
      }
    }
    if (lastZeroCount) {
      branchParent.remove(lastZeroCount);
    }
    const leafNode = this.startPath[this.startPath.length - 1];
    if (lines.length > 0) {
      leafNode.text = lines[0];
      if (lines.length > 1) {
        let insertedNodes = new Array(lines.length - 1);
        let startNode2 = leafNode;
        for (let i = 1; i < lines.length; i++) {
          insertedNodes[i - 1] = new LineLeaf(lines[i]);
        }
        let pathIndex = this.startPath.length - 2;
        while (pathIndex >= 0) {
          const insertionNode = this.startPath[pathIndex];
          insertedNodes = insertionNode.insertAt(startNode2, insertedNodes);
          pathIndex--;
          startNode2 = insertionNode;
        }
        let insertedNodesLen = insertedNodes.length;
        while (insertedNodesLen > 0) {
          const newRoot = new LineNode();
          newRoot.add(this.lineIndex.root);
          insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes);
          insertedNodesLen = insertedNodes.length;
          this.lineIndex.root = newRoot;
        }
        this.lineIndex.root.updateCounts();
      } else {
        for (let j = this.startPath.length - 2; j >= 0; j--) {
          this.startPath[j].updateCounts();
        }
      }
    } else {
      const insertionNode = this.startPath[this.startPath.length - 2];
      insertionNode.remove(leafNode);
      for (let j = this.startPath.length - 2; j >= 0; j--) {
        this.startPath[j].updateCounts();
      }
    }
    return this.lineIndex;
  }
  post(_relativeStart, _relativeLength, lineCollection) {
    if (lineCollection === this.lineCollectionAtBranch) {
      this.state = 4 /* End */;
    }
    this.stack.pop();
  }
  pre(_relativeStart, _relativeLength, lineCollection, _parent, nodeType) {
    const currentNode = this.stack[this.stack.length - 1];
    if (this.state === 2 /* Entire */ && nodeType === 1 /* Start */) {
      this.state = 1 /* Start */;
      this.branchNode = currentNode;
      this.lineCollectionAtBranch = lineCollection;
    }
    let child;
    function fresh(node) {
      if (node.isLeaf()) {
        return new LineLeaf("");
      } else return new LineNode();
    }
    switch (nodeType) {
      case 0 /* PreStart */:
        this.goSubtree = false;
        if (this.state !== 4 /* End */) {
          currentNode.add(lineCollection);
        }
        break;
      case 1 /* Start */:
        if (this.state === 4 /* End */) {
          this.goSubtree = false;
        } else {
          child = fresh(lineCollection);
          currentNode.add(child);
          this.startPath.push(child);
        }
        break;
      case 2 /* Entire */:
        if (this.state !== 4 /* End */) {
          child = fresh(lineCollection);
          currentNode.add(child);
          this.startPath.push(child);
        } else {
          if (!lineCollection.isLeaf()) {
            child = fresh(lineCollection);
            currentNode.add(child);
            this.endBranch.push(child);
          }
        }
        break;
      case 3 /* Mid */:
        this.goSubtree = false;
        break;
      case 4 /* End */:
        if (this.state !== 4 /* End */) {
          this.goSubtree = false;
        } else {
          if (!lineCollection.isLeaf()) {
            child = fresh(lineCollection);
            currentNode.add(child);
            this.endBranch.push(child);
          }
        }
        break;
      case 5 /* PostEnd */:
        this.goSubtree = false;
        if (this.state !== 1 /* Start */) {
          currentNode.add(lineCollection);
        }
        break;
    }
    if (this.goSubtree) {
      this.stack.push(child);
    }
  }
  // just gather text from the leaves
  leaf(relativeStart, relativeLength, ll) {
    if (this.state === 1 /* Start */) {
      this.initialText = ll.text.substring(0, relativeStart);
    } else if (this.state === 2 /* Entire */) {
      this.initialText = ll.text.substring(0, relativeStart);
      this.trailingText = ll.text.substring(relativeStart + relativeLength);
    } else {
      this.trailingText = ll.text.substring(relativeStart + relativeLength);
    }
  }
};
var TextChange9 = class {
  constructor(pos, deleteLen, insertedText) {
    this.pos = pos;
    this.deleteLen = deleteLen;
    this.insertedText = insertedText;
  }
  getTextChangeRange() {
    return createTextChangeRange(createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0);
  }
};
var _ScriptVersionCache = class _ScriptVersionCache {
  constructor() {
    this.changes = [];
    this.versions = new Array(_ScriptVersionCache.maxVersions);
    this.minVersion = 0;
    // no versions earlier than min version will maintain change history
    this.currentVersion = 0;
  }
  versionToIndex(version2) {
    if (version2 < this.minVersion || version2 > this.currentVersion) {
      return void 0;
    }
    return version2 % _ScriptVersionCache.maxVersions;
  }
  currentVersionToIndex() {
    return this.currentVersion % _ScriptVersionCache.maxVersions;
  }
  // REVIEW: can optimize by coalescing simple edits
  edit(pos, deleteLen, insertedText) {
    this.changes.push(new TextChange9(pos, deleteLen, insertedText));
    if (this.changes.length > _ScriptVersionCache.changeNumberThreshold || deleteLen > _ScriptVersionCache.changeLengthThreshold || insertedText && insertedText.length > _ScriptVersionCache.changeLengthThreshold) {
      this.getSnapshot();
    }
  }
  getSnapshot() {
    return this._getSnapshot();
  }
  _getSnapshot() {
    let snap = this.versions[this.currentVersionToIndex()];
    if (this.changes.length > 0) {
      let snapIndex = snap.index;
      for (const change of this.changes) {
        snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText);
      }
      snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes);
      this.currentVersion = snap.version;
      this.versions[this.currentVersionToIndex()] = snap;
      this.changes = [];
      if (this.currentVersion - this.minVersion >= _ScriptVersionCache.maxVersions) {
        this.minVersion = this.currentVersion - _ScriptVersionCache.maxVersions + 1;
      }
    }
    return snap;
  }
  getSnapshotVersion() {
    return this._getSnapshot().version;
  }
  getAbsolutePositionAndLineText(oneBasedLine) {
    return this._getSnapshot().index.lineNumberToInfo(oneBasedLine);
  }
  lineOffsetToPosition(line, column) {
    return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1);
  }
  positionToLineOffset(position) {
    return this._getSnapshot().index.positionToLineOffset(position);
  }
  lineToTextSpan(line) {
    const index = this._getSnapshot().index;
    const { lineText, absolutePosition } = index.lineNumberToInfo(line + 1);
    const len = lineText !== void 0 ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition;
    return createTextSpan(absolutePosition, len);
  }
  getTextChangesBetweenVersions(oldVersion, newVersion) {
    if (oldVersion < newVersion) {
      if (oldVersion >= this.minVersion) {
        const textChangeRanges = [];
        for (let i = oldVersion + 1; i <= newVersion; i++) {
          const snap = this.versions[this.versionToIndex(i)];
          for (const textChange of snap.changesSincePreviousVersion) {
            textChangeRanges.push(textChange.getTextChangeRange());
          }
        }
        return collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges);
      } else {
        return void 0;
      }
    } else {
      return unchangedTextChangeRange;
    }
  }
  getLineCount() {
    return this._getSnapshot().index.getLineCount();
  }
  static fromString(script) {
    const svc = new _ScriptVersionCache();
    const snap = new LineIndexSnapshot(0, svc, new LineIndex());
    svc.versions[svc.currentVersion] = snap;
    const lm = LineIndex.linesFromText(script);
    snap.index.load(lm.lines);
    return svc;
  }
};
_ScriptVersionCache.changeNumberThreshold = 8;
_ScriptVersionCache.changeLengthThreshold = 256;
_ScriptVersionCache.maxVersions = 8;
var ScriptVersionCache = _ScriptVersionCache;
var LineIndexSnapshot = class _LineIndexSnapshot {
  constructor(version2, cache, index, changesSincePreviousVersion = emptyArray2) {
    this.version = version2;
    this.cache = cache;
    this.index = index;
    this.changesSincePreviousVersion = changesSincePreviousVersion;
  }
  getText(rangeStart, rangeEnd) {
    return this.index.getText(rangeStart, rangeEnd - rangeStart);
  }
  getLength() {
    return this.index.getLength();
  }
  getChangeRange(oldSnapshot) {
    if (oldSnapshot instanceof _LineIndexSnapshot && this.cache === oldSnapshot.cache) {
      if (this.version <= oldSnapshot.version) {
        return unchangedTextChangeRange;
      } else {
        return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version);
      }
    }
  }
};
var LineIndex = class _LineIndex {
  constructor() {
    // set this to true to check each edit for accuracy
    this.checkEdits = false;
  }
  absolutePositionOfStartOfLine(oneBasedLine) {
    return this.lineNumberToInfo(oneBasedLine).absolutePosition;
  }
  positionToLineOffset(position) {
    const { oneBasedLine, zeroBasedColumn } = this.root.charOffsetToLineInfo(1, position);
    return { line: oneBasedLine, offset: zeroBasedColumn + 1 };
  }
  positionToColumnAndLineText(position) {
    return this.root.charOffsetToLineInfo(1, position);
  }
  getLineCount() {
    return this.root.lineCount();
  }
  lineNumberToInfo(oneBasedLine) {
    const lineCount = this.getLineCount();
    if (oneBasedLine <= lineCount) {
      const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0);
      return { absolutePosition: position, lineText: leaf && leaf.text };
    } else {
      return { absolutePosition: this.root.charCount(), lineText: void 0 };
    }
  }
  load(lines) {
    if (lines.length > 0) {
      const leaves = [];
      for (let i = 0; i < lines.length; i++) {
        leaves[i] = new LineLeaf(lines[i]);
      }
      this.root = _LineIndex.buildTreeFromBottom(leaves);
    } else {
      this.root = new LineNode();
    }
  }
  walk(rangeStart, rangeLength, walkFns) {
    this.root.walk(rangeStart, rangeLength, walkFns);
  }
  getText(rangeStart, rangeLength) {
    let accum = "";
    if (rangeLength > 0 && rangeStart < this.root.charCount()) {
      this.walk(rangeStart, rangeLength, {
        goSubtree: true,
        done: false,
        leaf: (relativeStart, relativeLength, ll) => {
          accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength));
        }
      });
    }
    return accum;
  }
  getLength() {
    return this.root.charCount();
  }
  every(f, rangeStart, rangeEnd) {
    if (!rangeEnd) {
      rangeEnd = this.root.charCount();
    }
    const walkFns = {
      goSubtree: true,
      done: false,
      leaf(relativeStart, relativeLength, ll) {
        if (!f(ll, relativeStart, relativeLength)) {
          this.done = true;
        }
      }
    };
    this.walk(rangeStart, rangeEnd - rangeStart, walkFns);
    return !walkFns.done;
  }
  edit(pos, deleteLength, newText) {
    if (this.root.charCount() === 0) {
      Debug.assert(deleteLength === 0);
      if (newText !== void 0) {
        this.load(_LineIndex.linesFromText(newText).lines);
        return this;
      }
      return void 0;
    } else {
      let checkText;
      if (this.checkEdits) {
        const source = this.getText(0, this.root.charCount());
        checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength);
      }
      const walker = new EditWalker();
      let suppressTrailingText = false;
      if (pos >= this.root.charCount()) {
        pos = this.root.charCount() - 1;
        const endString = this.getText(pos, 1);
        if (newText) {
          newText = endString + newText;
        } else {
          newText = endString;
        }
        deleteLength = 0;
        suppressTrailingText = true;
      } else if (deleteLength > 0) {
        const e = pos + deleteLength;
        const { zeroBasedColumn, lineText } = this.positionToColumnAndLineText(e);
        if (zeroBasedColumn === 0) {
          deleteLength += lineText.length;
          newText = newText ? newText + lineText : lineText;
        }
      }
      this.root.walk(pos, deleteLength, walker);
      walker.insertLines(newText, suppressTrailingText);
      if (this.checkEdits) {
        const updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength());
        Debug.assert(checkText === updatedText, "buffer edit mismatch");
      }
      return walker.lineIndex;
    }
  }
  static buildTreeFromBottom(nodes) {
    if (nodes.length < lineCollectionCapacity) {
      return new LineNode(nodes);
    }
    const interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity));
    let nodeIndex = 0;
    for (let i = 0; i < interiorNodes.length; i++) {
      const end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length);
      interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end));
      nodeIndex = end;
    }
    return this.buildTreeFromBottom(interiorNodes);
  }
  static linesFromText(text) {
    const lineMap = computeLineStarts(text);
    if (lineMap.length === 0) {
      return { lines: [], lineMap };
    }
    const lines = new Array(lineMap.length);
    const lc = lineMap.length - 1;
    for (let lmi = 0; lmi < lc; lmi++) {
      lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]);
    }
    const endText = text.substring(lineMap[lc]);
    if (endText.length > 0) {
      lines[lc] = endText;
    } else {
      lines.pop();
    }
    return { lines, lineMap };
  }
};
var LineNode = class _LineNode {
  constructor(children = []) {
    this.children = children;
    this.totalChars = 0;
    this.totalLines = 0;
    if (children.length) this.updateCounts();
  }
  isLeaf() {
    return false;
  }
  updateCounts() {
    this.totalChars = 0;
    this.totalLines = 0;
    for (const child of this.children) {
      this.totalChars += child.charCount();
      this.totalLines += child.lineCount();
    }
  }
  execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType) {
    if (walkFns.pre) {
      walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
    }
    if (walkFns.goSubtree) {
      this.children[childIndex].walk(rangeStart, rangeLength, walkFns);
      if (walkFns.post) {
        walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType);
      }
    } else {
      walkFns.goSubtree = true;
    }
    return walkFns.done;
  }
  skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType) {
    if (walkFns.pre && !walkFns.done) {
      walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType);
      walkFns.goSubtree = true;
    }
  }
  walk(rangeStart, rangeLength, walkFns) {
    if (this.children.length === 0) return;
    let childIndex = 0;
    let childCharCount = this.children[childIndex].charCount();
    let adjustedStart = rangeStart;
    while (adjustedStart >= childCharCount) {
      this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */);
      adjustedStart -= childCharCount;
      childIndex++;
      childCharCount = this.children[childIndex].charCount();
    }
    if (adjustedStart + rangeLength <= childCharCount) {
      if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) {
        return;
      }
    } else {
      if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) {
        return;
      }
      let adjustedLength = rangeLength - (childCharCount - adjustedStart);
      childIndex++;
      const child = this.children[childIndex];
      childCharCount = child.charCount();
      while (adjustedLength > childCharCount) {
        if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) {
          return;
        }
        adjustedLength -= childCharCount;
        childIndex++;
        childCharCount = this.children[childIndex].charCount();
      }
      if (adjustedLength > 0) {
        if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) {
          return;
        }
      }
    }
    if (walkFns.pre) {
      const clen = this.children.length;
      if (childIndex < clen - 1) {
        for (let ej = childIndex + 1; ej < clen; ej++) {
          this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */);
        }
      }
    }
  }
  // Input position is relative to the start of this node.
  // Output line number is absolute.
  charOffsetToLineInfo(lineNumberAccumulator, relativePosition) {
    if (this.children.length === 0) {
      return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: void 0 };
    }
    for (const child of this.children) {
      if (child.charCount() > relativePosition) {
        if (child.isLeaf()) {
          return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text };
        } else {
          return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition);
        }
      } else {
        relativePosition -= child.charCount();
        lineNumberAccumulator += child.lineCount();
      }
    }
    const lineCount = this.lineCount();
    if (lineCount === 0) {
      return { oneBasedLine: 1, zeroBasedColumn: 0, lineText: void 0 };
    }
    const leaf = Debug.checkDefined(this.lineNumberToInfo(lineCount, 0).leaf);
    return { oneBasedLine: lineCount, zeroBasedColumn: leaf.charCount(), lineText: void 0 };
  }
  /**
   * Input line number is relative to the start of this node.
   * Output line number is relative to the child.
   * positionAccumulator will be an absolute position once relativeLineNumber reaches 0.
   */
  lineNumberToInfo(relativeOneBasedLine, positionAccumulator) {
    for (const child of this.children) {
      const childLineCount = child.lineCount();
      if (childLineCount >= relativeOneBasedLine) {
        return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator);
      } else {
        relativeOneBasedLine -= childLineCount;
        positionAccumulator += child.charCount();
      }
    }
    return { position: positionAccumulator, leaf: void 0 };
  }
  splitAfter(childIndex) {
    let splitNode;
    const clen = this.children.length;
    childIndex++;
    const endLength = childIndex;
    if (childIndex < clen) {
      splitNode = new _LineNode();
      while (childIndex < clen) {
        splitNode.add(this.children[childIndex]);
        childIndex++;
      }
      splitNode.updateCounts();
    }
    this.children.length = endLength;
    return splitNode;
  }
  remove(child) {
    const childIndex = this.findChildIndex(child);
    const clen = this.children.length;
    if (childIndex < clen - 1) {
      for (let i = childIndex; i < clen - 1; i++) {
        this.children[i] = this.children[i + 1];
      }
    }
    this.children.pop();
  }
  findChildIndex(child) {
    const childIndex = this.children.indexOf(child);
    Debug.assert(childIndex !== -1);
    return childIndex;
  }
  insertAt(child, nodes) {
    let childIndex = this.findChildIndex(child);
    const clen = this.children.length;
    const nodeCount = nodes.length;
    if (clen < lineCollectionCapacity && childIndex === clen - 1 && nodeCount === 1) {
      this.add(nodes[0]);
      this.updateCounts();
      return [];
    } else {
      const shiftNode = this.splitAfter(childIndex);
      let nodeIndex = 0;
      childIndex++;
      while (childIndex < lineCollectionCapacity && nodeIndex < nodeCount) {
        this.children[childIndex] = nodes[nodeIndex];
        childIndex++;
        nodeIndex++;
      }
      let splitNodes = [];
      let splitNodeCount = 0;
      if (nodeIndex < nodeCount) {
        splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity);
        splitNodes = new Array(splitNodeCount);
        let splitNodeIndex = 0;
        for (let i = 0; i < splitNodeCount; i++) {
          splitNodes[i] = new _LineNode();
        }
        let splitNode = splitNodes[0];
        while (nodeIndex < nodeCount) {
          splitNode.add(nodes[nodeIndex]);
          nodeIndex++;
          if (splitNode.children.length === lineCollectionCapacity) {
            splitNodeIndex++;
            splitNode = splitNodes[splitNodeIndex];
          }
        }
        for (let i = splitNodes.length - 1; i >= 0; i--) {
          if (splitNodes[i].children.length === 0) {
            splitNodes.pop();
          }
        }
      }
      if (shiftNode) {
        splitNodes.push(shiftNode);
      }
      this.updateCounts();
      for (let i = 0; i < splitNodeCount; i++) {
        splitNodes[i].updateCounts();
      }
      return splitNodes;
    }
  }
  // assume there is room for the item; return true if more room
  add(collection) {
    this.children.push(collection);
    Debug.assert(this.children.length <= lineCollectionCapacity);
  }
  charCount() {
    return this.totalChars;
  }
  lineCount() {
    return this.totalLines;
  }
};
var LineLeaf = class {
  constructor(text) {
    this.text = text;
  }
  isLeaf() {
    return true;
  }
  walk(rangeStart, rangeLength, walkFns) {
    walkFns.leaf(rangeStart, rangeLength, this);
  }
  charCount() {
    return this.text.length;
  }
  lineCount() {
    return 1;
  }
};

// src/server/typingInstallerAdapter.ts
var _TypingsInstallerAdapter = class _TypingsInstallerAdapter {
  constructor(telemetryEnabled, logger, host, globalTypingsCacheLocation, event, maxActiveRequestCount) {
    this.telemetryEnabled = telemetryEnabled;
    this.logger = logger;
    this.host = host;
    this.globalTypingsCacheLocation = globalTypingsCacheLocation;
    this.event = event;
    this.maxActiveRequestCount = maxActiveRequestCount;
    this.activeRequestCount = 0;
    this.requestQueue = createQueue();
    this.requestMap = /* @__PURE__ */ new Map();
    // Maps project name to newest requestQueue entry for that project
    /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */
    this.requestedRegistry = false;
    this.packageInstallId = 0;
  }
  isKnownTypesPackageName(name) {
    var _a;
    const validationResult = ts_JsTyping_exports.validatePackageName(name);
    if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) {
      return false;
    }
    if (!this.requestedRegistry) {
      this.requestedRegistry = true;
      this.installer.send({ kind: "typesRegistry" });
    }
    return !!((_a = this.typesRegistryCache) == null ? void 0 : _a.has(name));
  }
  installPackage(options) {
    this.packageInstallId++;
    const request = { kind: "installPackage", ...options, id: this.packageInstallId };
    const promise = new Promise((resolve, reject) => {
      (this.packageInstalledPromise ?? (this.packageInstalledPromise = /* @__PURE__ */ new Map())).set(this.packageInstallId, { resolve, reject });
    });
    this.installer.send(request);
    return promise;
  }
  attach(projectService) {
    this.projectService = projectService;
    this.installer = this.createInstallerProcess();
  }
  onProjectClosed(p) {
    this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
  }
  enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports) {
    const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Scheduling throttled operation:${stringifyIndented(request)}`);
    }
    if (this.activeRequestCount < this.maxActiveRequestCount) {
      this.scheduleRequest(request);
    } else {
      if (this.logger.hasLevel(3 /* verbose */)) {
        this.logger.info(`TIAdapter:: Deferring request for: ${request.projectName}`);
      }
      this.requestQueue.enqueue(request);
      this.requestMap.set(request.projectName, request);
    }
  }
  handleMessage(response) {
    var _a, _b;
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Received response:${stringifyIndented(response)}`);
    }
    switch (response.kind) {
      case EventTypesRegistry:
        this.typesRegistryCache = new Map(Object.entries(response.typesRegistry));
        break;
      case ActionPackageInstalled: {
        const promise = (_a = this.packageInstalledPromise) == null ? void 0 : _a.get(response.id);
        Debug.assertIsDefined(promise, "Should find the promise for package install");
        (_b = this.packageInstalledPromise) == null ? void 0 : _b.delete(response.id);
        if (response.success) {
          promise.resolve({ successMessage: response.message });
        } else {
          promise.reject(response.message);
        }
        this.projectService.updateTypingsForProject(response);
        this.event(response, "setTypings");
        break;
      }
      case EventInitializationFailed: {
        const body = {
          message: response.message
        };
        const eventName = "typesInstallerInitializationFailed";
        this.event(body, eventName);
        break;
      }
      case EventBeginInstallTypes: {
        const body = {
          eventId: response.eventId,
          packages: response.packagesToInstall
        };
        const eventName = "beginInstallTypes";
        this.event(body, eventName);
        break;
      }
      case EventEndInstallTypes: {
        if (this.telemetryEnabled) {
          const body2 = {
            telemetryEventName: "typingsInstalled",
            payload: {
              installedPackages: response.packagesToInstall.join(","),
              installSuccess: response.installSuccess,
              typingsInstallerVersion: response.typingsInstallerVersion
            }
          };
          const eventName2 = "telemetry";
          this.event(body2, eventName2);
        }
        const body = {
          eventId: response.eventId,
          packages: response.packagesToInstall,
          success: response.installSuccess
        };
        const eventName = "endInstallTypes";
        this.event(body, eventName);
        break;
      }
      case ActionInvalidate: {
        this.projectService.updateTypingsForProject(response);
        break;
      }
      case ActionSet: {
        if (this.activeRequestCount > 0) {
          this.activeRequestCount--;
        } else {
          Debug.fail("TIAdapter:: Received too many responses");
        }
        while (!this.requestQueue.isEmpty()) {
          const queuedRequest = this.requestQueue.dequeue();
          if (this.requestMap.get(queuedRequest.projectName) === queuedRequest) {
            this.requestMap.delete(queuedRequest.projectName);
            this.scheduleRequest(queuedRequest);
            break;
          }
          if (this.logger.hasLevel(3 /* verbose */)) {
            this.logger.info(`TIAdapter:: Skipping defunct request for: ${queuedRequest.projectName}`);
          }
        }
        this.projectService.updateTypingsForProject(response);
        this.event(response, "setTypings");
        break;
      }
      case ActionWatchTypingLocations:
        this.projectService.watchTypingLocations(response);
        break;
      default:
        assertType(response);
    }
  }
  scheduleRequest(request) {
    if (this.logger.hasLevel(3 /* verbose */)) {
      this.logger.info(`TIAdapter:: Scheduling request for: ${request.projectName}`);
    }
    this.activeRequestCount++;
    this.host.setTimeout(
      () => {
        if (this.logger.hasLevel(3 /* verbose */)) {
          this.logger.info(`TIAdapter:: Sending request:${stringifyIndented(request)}`);
        }
        this.installer.send(request);
      },
      _TypingsInstallerAdapter.requestDelayMillis,
      `${request.projectName}::${request.kind}`
    );
  }
};
// This number is essentially arbitrary.  Processing more than one typings request
// at a time makes sense, but having too many in the pipe results in a hang
// (see https://github.com/nodejs/node/issues/7657).
// It would be preferable to base our limit on the amount of space left in the
// buffer, but we have yet to find a way to retrieve that value.
_TypingsInstallerAdapter.requestDelayMillis = 100;
var TypingsInstallerAdapter = _TypingsInstallerAdapter;

// src/typescript/_namespaces/ts.server.ts
var ts_server_exports4 = {};
__export(ts_server_exports4, {
  ActionInvalidate: () => ActionInvalidate,
  ActionPackageInstalled: () => ActionPackageInstalled,
  ActionSet: () => ActionSet,
  ActionWatchTypingLocations: () => ActionWatchTypingLocations,
  Arguments: () => Arguments,
  AutoImportProviderProject: () => AutoImportProviderProject,
  AuxiliaryProject: () => AuxiliaryProject,
  CharRangeSection: () => CharRangeSection,
  CloseFileWatcherEvent: () => CloseFileWatcherEvent,
  CommandNames: () => CommandNames,
  ConfigFileDiagEvent: () => ConfigFileDiagEvent,
  ConfiguredProject: () => ConfiguredProject2,
  ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind,
  CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent,
  CreateFileWatcherEvent: () => CreateFileWatcherEvent,
  Errors: () => Errors,
  EventBeginInstallTypes: () => EventBeginInstallTypes,
  EventEndInstallTypes: () => EventEndInstallTypes,
  EventInitializationFailed: () => EventInitializationFailed,
  EventTypesRegistry: () => EventTypesRegistry,
  ExternalProject: () => ExternalProject,
  GcTimer: () => GcTimer,
  InferredProject: () => InferredProject2,
  LargeFileReferencedEvent: () => LargeFileReferencedEvent,
  LineIndex: () => LineIndex,
  LineLeaf: () => LineLeaf,
  LineNode: () => LineNode,
  LogLevel: () => LogLevel2,
  Msg: () => Msg,
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
  Project: () => Project2,
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
  ProjectKind: () => ProjectKind,
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
  ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent,
  ProjectLoadingStartEvent: () => ProjectLoadingStartEvent,
  ProjectService: () => ProjectService2,
  ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent,
  ScriptInfo: () => ScriptInfo,
  ScriptVersionCache: () => ScriptVersionCache,
  Session: () => Session3,
  TextStorage: () => TextStorage,
  ThrottledOperations: () => ThrottledOperations,
  TypingsInstallerAdapter: () => TypingsInstallerAdapter,
  allFilesAreJsOrDts: () => allFilesAreJsOrDts,
  allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts,
  asNormalizedPath: () => asNormalizedPath,
  convertCompilerOptions: () => convertCompilerOptions,
  convertFormatOptions: () => convertFormatOptions,
  convertScriptKindName: () => convertScriptKindName,
  convertTypeAcquisition: () => convertTypeAcquisition,
  convertUserPreferences: () => convertUserPreferences,
  convertWatchOptions: () => convertWatchOptions,
  countEachFileTypes: () => countEachFileTypes,
  createInstallTypingsRequest: () => createInstallTypingsRequest,
  createModuleSpecifierCache: () => createModuleSpecifierCache,
  createNormalizedPathMap: () => createNormalizedPathMap,
  createPackageJsonCache: () => createPackageJsonCache,
  createSortedArray: () => createSortedArray2,
  emptyArray: () => emptyArray2,
  findArgument: () => findArgument,
  formatDiagnosticToProtocol: () => formatDiagnosticToProtocol,
  formatMessage: () => formatMessage2,
  getBaseConfigFileName: () => getBaseConfigFileName,
  getDetailWatchInfo: () => getDetailWatchInfo,
  getLocationInNewDocument: () => getLocationInNewDocument,
  hasArgument: () => hasArgument,
  hasNoTypeScriptSource: () => hasNoTypeScriptSource,
  indent: () => indent2,
  isBackgroundProject: () => isBackgroundProject,
  isConfigFile: () => isConfigFile,
  isConfiguredProject: () => isConfiguredProject,
  isDynamicFileName: () => isDynamicFileName,
  isExternalProject: () => isExternalProject,
  isInferredProject: () => isInferredProject,
  isInferredProjectName: () => isInferredProjectName,
  isProjectDeferredClose: () => isProjectDeferredClose,
  makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName,
  makeAuxiliaryProjectName: () => makeAuxiliaryProjectName,
  makeInferredProjectName: () => makeInferredProjectName,
  maxFileSize: () => maxFileSize,
  maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles,
  normalizedPathToPath: () => normalizedPathToPath,
  nowString: () => nowString,
  nullCancellationToken: () => nullCancellationToken,
  nullTypingsInstaller: () => nullTypingsInstaller,
  protocol: () => ts_server_protocol_exports,
  scriptInfoIsContainedByBackgroundProject: () => scriptInfoIsContainedByBackgroundProject,
  scriptInfoIsContainedByDeferredClosedProject: () => scriptInfoIsContainedByDeferredClosedProject,
  stringifyIndented: () => stringifyIndented,
  toEvent: () => toEvent,
  toNormalizedPath: () => toNormalizedPath,
  tryConvertScriptKindName: () => tryConvertScriptKindName,
  typingsInstaller: () => ts_server_typingsInstaller_exports,
  updateProjectIfDirty: () => updateProjectIfDirty
});

// src/typescript/typescript.ts
if (typeof console !== "undefined") {
  Debug.loggingHost = {
    log(level, s) {
      switch (level) {
        case 1 /* Error */:
          return console.error(s);
        case 2 /* Warning */:
          return console.warn(s);
        case 3 /* Info */:
          return console.log(s);
        case 4 /* Verbose */:
          return console.log(s);
      }
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ANONYMOUS,
  AccessFlags,
  AssertionLevel,
  AssignmentDeclarationKind,
  AssignmentKind,
  Associativity,
  BreakpointResolver,
  BuilderFileEmit,
  BuilderProgramKind,
  BuilderState,
  CallHierarchy,
  CharacterCodes,
  CheckFlags,
  CheckMode,
  ClassificationType,
  ClassificationTypeNames,
  CommentDirectiveType,
  Comparison,
  CompletionInfoFlags,
  CompletionTriggerKind,
  Completions,
  ContainerFlags,
  ContextFlags,
  Debug,
  DiagnosticCategory,
  Diagnostics,
  DocumentHighlights,
  ElementFlags,
  EmitFlags,
  EmitHint,
  EmitOnly,
  EndOfLineState,
  ExitStatus,
  ExportKind,
  Extension,
  ExternalEmitHelpers,
  FileIncludeKind,
  FilePreprocessingDiagnosticsKind,
  FileSystemEntryKind,
  FileWatcherEventKind,
  FindAllReferences,
  FlattenLevel,
  FlowFlags,
  ForegroundColorEscapeSequences,
  FunctionFlags,
  GeneratedIdentifierFlags,
  GetLiteralTextFlags,
  GoToDefinition,
  HighlightSpanKind,
  IdentifierNameMap,
  ImportKind,
  ImportsNotUsedAsValues,
  IndentStyle,
  IndexFlags,
  IndexKind,
  InferenceFlags,
  InferencePriority,
  InlayHintKind,
  InlayHints,
  InternalEmitFlags,
  InternalNodeBuilderFlags,
  InternalSymbolName,
  IntersectionFlags,
  InvalidatedProjectKind,
  JSDocParsingMode,
  JsDoc,
  JsTyping,
  JsxEmit,
  JsxFlags,
  JsxReferenceKind,
  LanguageFeatureMinimumTarget,
  LanguageServiceMode,
  LanguageVariant,
  LexicalEnvironmentFlags,
  ListFormat,
  LogLevel,
  MapCode,
  MemberOverrideStatus,
  ModifierFlags,
  ModuleDetectionKind,
  ModuleInstanceState,
  ModuleKind,
  ModuleResolutionKind,
  ModuleSpecifierEnding,
  NavigateTo,
  NavigationBar,
  NewLineKind,
  NodeBuilderFlags,
  NodeCheckFlags,
  NodeFactoryFlags,
  NodeFlags,
  NodeResolutionFeatures,
  ObjectFlags,
  OperationCanceledException,
  OperatorPrecedence,
  OrganizeImports,
  OrganizeImportsMode,
  OuterExpressionKinds,
  OutliningElementsCollector,
  OutliningSpanKind,
  OutputFileType,
  PackageJsonAutoImportPreference,
  PackageJsonDependencyGroup,
  PatternMatchKind,
  PollingInterval,
  PollingWatchKind,
  PragmaKindFlags,
  PredicateSemantics,
  PreparePasteEdits,
  PrivateIdentifierKind,
  ProcessLevel,
  ProgramUpdateLevel,
  QuotePreference,
  RegularExpressionFlags,
  RelationComparisonResult,
  Rename,
  ScriptElementKind,
  ScriptElementKindModifier,
  ScriptKind,
  ScriptSnapshot,
  ScriptTarget,
  SemanticClassificationFormat,
  SemanticMeaning,
  SemicolonPreference,
  SignatureCheckMode,
  SignatureFlags,
  SignatureHelp,
  SignatureInfo,
  SignatureKind,
  SmartSelectionRange,
  SnippetKind,
  StatisticType,
  StructureIsReused,
  SymbolAccessibility,
  SymbolDisplay,
  SymbolDisplayPartKind,
  SymbolFlags,
  SymbolFormatFlags,
  SyntaxKind,
  Ternary,
  ThrottledCancellationToken,
  TokenClass,
  TokenFlags,
  TransformFlags,
  TypeFacts,
  TypeFlags,
  TypeFormatFlags,
  TypeMapKind,
  TypePredicateKind,
  TypeReferenceSerializationKind,
  UnionReduction,
  UpToDateStatusType,
  VarianceFlags,
  Version,
  VersionRange,
  WatchDirectoryFlags,
  WatchDirectoryKind,
  WatchFileKind,
  WatchLogLevel,
  WatchType,
  accessPrivateIdentifier,
  addEmitFlags,
  addEmitHelper,
  addEmitHelpers,
  addInternalEmitFlags,
  addNodeFactoryPatcher,
  addObjectAllocatorPatcher,
  addRange,
  addRelatedInfo,
  addSyntheticLeadingComment,
  addSyntheticTrailingComment,
  addToSeen,
  advancedAsyncSuperHelper,
  affectsDeclarationPathOptionDeclarations,
  affectsEmitOptionDeclarations,
  allKeysStartWithDot,
  altDirectorySeparator,
  and,
  append,
  appendIfUnique,
  arrayFrom,
  arrayIsEqualTo,
  arrayIsHomogeneous,
  arrayOf,
  arrayReverseIterator,
  arrayToMap,
  arrayToMultiMap,
  arrayToNumericMap,
  assertType,
  assign,
  asyncSuperHelper,
  attachFileToDiagnostics,
  base64decode,
  base64encode,
  binarySearch,
  binarySearchKey,
  bindSourceFile,
  breakIntoCharacterSpans,
  breakIntoWordSpans,
  buildLinkParts,
  buildOpts,
  buildOverload,
  bundlerModuleNameResolver,
  canBeConvertedToAsync,
  canHaveDecorators,
  canHaveExportModifier,
  canHaveFlowNode,
  canHaveIllegalDecorators,
  canHaveIllegalModifiers,
  canHaveIllegalType,
  canHaveIllegalTypeParameters,
  canHaveJSDoc,
  canHaveLocals,
  canHaveModifiers,
  canHaveModuleSpecifier,
  canHaveSymbol,
  canIncludeBindAndCheckDiagnostics,
  canJsonReportNoInputFiles,
  canProduceDiagnostics,
  canUsePropertyAccess,
  canWatchAffectingLocation,
  canWatchAtTypes,
  canWatchDirectoryOrFile,
  canWatchDirectoryOrFilePath,
  cartesianProduct,
  cast,
  chainBundle,
  chainDiagnosticMessages,
  changeAnyExtension,
  changeCompilerHostLikeToUseCache,
  changeExtension,
  changeFullExtension,
  changesAffectModuleResolution,
  changesAffectingProgramStructure,
  characterCodeToRegularExpressionFlag,
  childIsDecorated,
  classElementOrClassElementParameterIsDecorated,
  classHasClassThisAssignment,
  classHasDeclaredOrExplicitlyAssignedName,
  classHasExplicitlyAssignedName,
  classOrConstructorParameterIsDecorated,
  classicNameResolver,
  classifier,
  cleanExtendedConfigCache,
  clear,
  clearMap,
  clearSharedExtendedConfigFileWatcher,
  climbPastPropertyAccess,
  clone,
  cloneCompilerOptions,
  closeFileWatcher,
  closeFileWatcherOf,
  codefix,
  collapseTextChangeRangesAcrossMultipleVersions,
  collectExternalModuleInfo,
  combine,
  combinePaths,
  commandLineOptionOfCustomType,
  commentPragmas,
  commonOptionsWithBuild,
  compact,
  compareBooleans,
  compareDataObjects,
  compareDiagnostics,
  compareEmitHelpers,
  compareNumberOfDirectorySeparators,
  comparePaths,
  comparePathsCaseInsensitive,
  comparePathsCaseSensitive,
  comparePatternKeys,
  compareProperties,
  compareStringsCaseInsensitive,
  compareStringsCaseInsensitiveEslintCompatible,
  compareStringsCaseSensitive,
  compareStringsCaseSensitiveUI,
  compareTextSpans,
  compareValues,
  compilerOptionsAffectDeclarationPath,
  compilerOptionsAffectEmit,
  compilerOptionsAffectSemanticDiagnostics,
  compilerOptionsDidYouMeanDiagnostics,
  compilerOptionsIndicateEsModules,
  computeCommonSourceDirectoryOfFilenames,
  computeLineAndCharacterOfPosition,
  computeLineOfPosition,
  computeLineStarts,
  computePositionOfLineAndCharacter,
  computeSignatureWithDiagnostics,
  computeSuggestionDiagnostics,
  computedOptions,
  concatenate,
  concatenateDiagnosticMessageChains,
  consumesNodeCoreModules,
  contains,
  containsIgnoredPath,
  containsObjectRestOrSpread,
  containsParseError,
  containsPath,
  convertCompilerOptionsForTelemetry,
  convertCompilerOptionsFromJson,
  convertJsonOption,
  convertToBase64,
  convertToJson,
  convertToObject,
  convertToOptionsWithAbsolutePaths,
  convertToRelativePath,
  convertToTSConfig,
  convertTypeAcquisitionFromJson,
  copyComments,
  copyEntries,
  copyLeadingComments,
  copyProperties,
  copyTrailingAsLeadingComments,
  copyTrailingComments,
  couldStartTrivia,
  countWhere,
  createAbstractBuilder,
  createAccessorPropertyBackingField,
  createAccessorPropertyGetRedirector,
  createAccessorPropertySetRedirector,
  createBaseNodeFactory,
  createBinaryExpressionTrampoline,
  createBuilderProgram,
  createBuilderProgramUsingIncrementalBuildInfo,
  createBuilderStatusReporter,
  createCacheableExportInfoMap,
  createCachedDirectoryStructureHost,
  createClassifier,
  createCommentDirectivesMap,
  createCompilerDiagnostic,
  createCompilerDiagnosticForInvalidCustomType,
  createCompilerDiagnosticFromMessageChain,
  createCompilerHost,
  createCompilerHostFromProgramHost,
  createCompilerHostWorker,
  createDetachedDiagnostic,
  createDiagnosticCollection,
  createDiagnosticForFileFromMessageChain,
  createDiagnosticForNode,
  createDiagnosticForNodeArray,
  createDiagnosticForNodeArrayFromMessageChain,
  createDiagnosticForNodeFromMessageChain,
  createDiagnosticForNodeInSourceFile,
  createDiagnosticForRange,
  createDiagnosticMessageChainFromDiagnostic,
  createDiagnosticReporter,
  createDocumentPositionMapper,
  createDocumentRegistry,
  createDocumentRegistryInternal,
  createEmitAndSemanticDiagnosticsBuilderProgram,
  createEmitHelperFactory,
  createEmptyExports,
  createEvaluator,
  createExpressionForJsxElement,
  createExpressionForJsxFragment,
  createExpressionForObjectLiteralElementLike,
  createExpressionForPropertyName,
  createExpressionFromEntityName,
  createExternalHelpersImportDeclarationIfNeeded,
  createFileDiagnostic,
  createFileDiagnosticFromMessageChain,
  createFlowNode,
  createForOfBindingStatement,
  createFutureSourceFile,
  createGetCanonicalFileName,
  createGetIsolatedDeclarationErrors,
  createGetSourceFile,
  createGetSymbolAccessibilityDiagnosticForNode,
  createGetSymbolAccessibilityDiagnosticForNodeName,
  createGetSymbolWalker,
  createIncrementalCompilerHost,
  createIncrementalProgram,
  createJsxFactoryExpression,
  createLanguageService,
  createLanguageServiceSourceFile,
  createMemberAccessForPropertyName,
  createModeAwareCache,
  createModeAwareCacheKey,
  createModeMismatchDetails,
  createModuleNotFoundChain,
  createModuleResolutionCache,
  createModuleResolutionLoader,
  createModuleResolutionLoaderUsingGlobalCache,
  createModuleSpecifierResolutionHost,
  createMultiMap,
  createNameResolver,
  createNodeConverters,
  createNodeFactory,
  createOptionNameMap,
  createOverload,
  createPackageJsonImportFilter,
  createPackageJsonInfo,
  createParenthesizerRules,
  createPatternMatcher,
  createPrinter,
  createPrinterWithDefaults,
  createPrinterWithRemoveComments,
  createPrinterWithRemoveCommentsNeverAsciiEscape,
  createPrinterWithRemoveCommentsOmitTrailingSemicolon,
  createProgram,
  createProgramHost,
  createPropertyNameNodeForIdentifierOrLiteral,
  createQueue,
  createRange,
  createRedirectedBuilderProgram,
  createResolutionCache,
  createRuntimeTypeSerializer,
  createScanner,
  createSemanticDiagnosticsBuilderProgram,
  createSet,
  createSolutionBuilder,
  createSolutionBuilderHost,
  createSolutionBuilderWithWatch,
  createSolutionBuilderWithWatchHost,
  createSortedArray,
  createSourceFile,
  createSourceMapGenerator,
  createSourceMapSource,
  createSuperAccessVariableStatement,
  createSymbolTable,
  createSymlinkCache,
  createSyntacticTypeNodeBuilder,
  createSystemWatchFunctions,
  createTextChange,
  createTextChangeFromStartLength,
  createTextChangeRange,
  createTextRangeFromNode,
  createTextRangeFromSpan,
  createTextSpan,
  createTextSpanFromBounds,
  createTextSpanFromNode,
  createTextSpanFromRange,
  createTextSpanFromStringLiteralLikeContent,
  createTextWriter,
  createTokenRange,
  createTypeChecker,
  createTypeReferenceDirectiveResolutionCache,
  createTypeReferenceResolutionLoader,
  createWatchCompilerHost,
  createWatchCompilerHostOfConfigFile,
  createWatchCompilerHostOfFilesAndCompilerOptions,
  createWatchFactory,
  createWatchHost,
  createWatchProgram,
  createWatchStatusReporter,
  createWriteFileMeasuringIO,
  declarationNameToString,
  decodeMappings,
  decodedTextSpanIntersectsWith,
  deduplicate,
  defaultInitCompilerOptions,
  defaultMaximumTruncationLength,
  diagnosticCategoryName,
  diagnosticToString,
  diagnosticsEqualityComparer,
  directoryProbablyExists,
  directorySeparator,
  displayPart,
  displayPartsToString,
  disposeEmitNodes,
  documentSpansEqual,
  dumpTracingLegend,
  elementAt,
  elideNodes,
  emitDetachedComments,
  emitFiles,
  emitFilesAndReportErrors,
  emitFilesAndReportErrorsAndGetExitStatus,
  emitModuleKindIsNonNodeESM,
  emitNewLineBeforeLeadingCommentOfPosition,
  emitResolverSkipsTypeChecking,
  emitSkippedWithNoDiagnostics,
  emptyArray,
  emptyFileSystemEntries,
  emptyMap,
  emptyOptions,
  endsWith,
  ensurePathIsNonModuleName,
  ensureScriptKind,
  ensureTrailingDirectorySeparator,
  entityNameToString,
  enumerateInsertsAndDeletes,
  equalOwnProperties,
  equateStringsCaseInsensitive,
  equateStringsCaseSensitive,
  equateValues,
  escapeJsxAttributeString,
  escapeLeadingUnderscores,
  escapeNonAsciiString,
  escapeSnippetText,
  escapeString,
  escapeTemplateSubstitution,
  evaluatorResult,
  every,
  exclusivelyPrefixedNodeCoreModules,
  executeCommandLine,
  expandPreOrPostfixIncrementOrDecrementExpression,
  explainFiles,
  explainIfFileIsRedirectAndImpliedFormat,
  exportAssignmentIsAlias,
  expressionResultIsUnused,
  extend,
  extensionFromPath,
  extensionIsTS,
  extensionsNotSupportingExtensionlessResolution,
  externalHelpersModuleNameText,
  factory,
  fileExtensionIs,
  fileExtensionIsOneOf,
  fileIncludeReasonToDiagnostics,
  fileShouldUseJavaScriptRequire,
  filter,
  filterMutate,
  filterSemanticDiagnostics,
  find,
  findAncestor,
  findBestPatternMatch,
  findChildOfKind,
  findComputedPropertyNameCacheAssignment,
  findConfigFile,
  findConstructorDeclaration,
  findContainingList,
  findDiagnosticForNode,
  findFirstNonJsxWhitespaceToken,
  findIndex,
  findLast,
  findLastIndex,
  findListItemInfo,
  findModifier,
  findNextToken,
  findPackageJson,
  findPackageJsons,
  findPrecedingMatchingToken,
  findPrecedingToken,
  findSuperStatementIndexPath,
  findTokenOnLeftOfPosition,
  findUseStrictPrologue,
  first,
  firstDefined,
  firstDefinedIterator,
  firstIterator,
  firstOrOnly,
  firstOrUndefined,
  firstOrUndefinedIterator,
  fixupCompilerOptions,
  flatMap,
  flatMapIterator,
  flatMapToMutable,
  flatten,
  flattenCommaList,
  flattenDestructuringAssignment,
  flattenDestructuringBinding,
  flattenDiagnosticMessageText,
  forEach,
  forEachAncestor,
  forEachAncestorDirectory,
  forEachAncestorDirectoryStoppingAtGlobalCache,
  forEachChild,
  forEachChildRecursively,
  forEachDynamicImportOrRequireCall,
  forEachEmittedFile,
  forEachEnclosingBlockScopeContainer,
  forEachEntry,
  forEachExternalModuleToImportFrom,
  forEachImportClauseDeclaration,
  forEachKey,
  forEachLeadingCommentRange,
  forEachNameInAccessChainWalkingLeft,
  forEachNameOfDefaultExport,
  forEachPropertyAssignment,
  forEachResolvedProjectReference,
  forEachReturnStatement,
  forEachRight,
  forEachTrailingCommentRange,
  forEachTsConfigPropArray,
  forEachUnique,
  forEachYieldExpression,
  formatColorAndReset,
  formatDiagnostic,
  formatDiagnostics,
  formatDiagnosticsWithColorAndContext,
  formatGeneratedName,
  formatGeneratedNamePart,
  formatLocation,
  formatMessage,
  formatStringFromArgs,
  formatting,
  generateDjb2Hash,
  generateTSConfig,
  getAdjustedReferenceLocation,
  getAdjustedRenameLocation,
  getAliasDeclarationFromName,
  getAllAccessorDeclarations,
  getAllDecoratorsOfClass,
  getAllDecoratorsOfClassElement,
  getAllJSDocTags,
  getAllJSDocTagsOfKind,
  getAllKeys,
  getAllProjectOutputs,
  getAllSuperTypeNodes,
  getAllowImportingTsExtensions,
  getAllowJSCompilerOption,
  getAllowSyntheticDefaultImports,
  getAncestor,
  getAnyExtensionFromPath,
  getAreDeclarationMapsEnabled,
  getAssignedExpandoInitializer,
  getAssignedName,
  getAssignmentDeclarationKind,
  getAssignmentDeclarationPropertyAccessKind,
  getAssignmentTargetKind,
  getAutomaticTypeDirectiveNames,
  getBaseFileName,
  getBinaryOperatorPrecedence,
  getBuildInfo,
  getBuildInfoFileVersionMap,
  getBuildInfoText,
  getBuildOrderFromAnyBuildOrder,
  getBuilderCreationParameters,
  getBuilderFileEmit,
  getCanonicalDiagnostic,
  getCheckFlags,
  getClassExtendsHeritageElement,
  getClassLikeDeclarationOfSymbol,
  getCombinedLocalAndExportSymbolFlags,
  getCombinedModifierFlags,
  getCombinedNodeFlags,
  getCombinedNodeFlagsAlwaysIncludeJSDoc,
  getCommentRange,
  getCommonSourceDirectory,
  getCommonSourceDirectoryOfConfig,
  getCompilerOptionValue,
  getCompilerOptionsDiffValue,
  getConditions,
  getConfigFileParsingDiagnostics,
  getConstantValue,
  getContainerFlags,
  getContainerNode,
  getContainingClass,
  getContainingClassExcludingClassDecorators,
  getContainingClassStaticBlock,
  getContainingFunction,
  getContainingFunctionDeclaration,
  getContainingFunctionOrClassStaticBlock,
  getContainingNodeArray,
  getContainingObjectLiteralElement,
  getContextualTypeFromParent,
  getContextualTypeFromParentOrAncestorTypeNode,
  getDeclarationDiagnostics,
  getDeclarationEmitExtensionForPath,
  getDeclarationEmitOutputFilePath,
  getDeclarationEmitOutputFilePathWorker,
  getDeclarationFileExtension,
  getDeclarationFromName,
  getDeclarationModifierFlagsFromSymbol,
  getDeclarationOfKind,
  getDeclarationsOfKind,
  getDeclaredExpandoInitializer,
  getDecorators,
  getDefaultCompilerOptions,
  getDefaultFormatCodeSettings,
  getDefaultLibFileName,
  getDefaultLibFilePath,
  getDefaultLikeExportInfo,
  getDefaultLikeExportNameFromDeclaration,
  getDefaultResolutionModeForFileWorker,
  getDiagnosticText,
  getDiagnosticsWithinSpan,
  getDirectoryPath,
  getDirectoryToWatchFailedLookupLocation,
  getDirectoryToWatchFailedLookupLocationFromTypeRoot,
  getDocumentPositionMapper,
  getDocumentSpansEqualityComparer,
  getESModuleInterop,
  getEditsForFileRename,
  getEffectiveBaseTypeNode,
  getEffectiveConstraintOfTypeParameter,
  getEffectiveContainerForJSDocTemplateTag,
  getEffectiveImplementsTypeNodes,
  getEffectiveInitializer,
  getEffectiveJSDocHost,
  getEffectiveModifierFlags,
  getEffectiveModifierFlagsAlwaysIncludeJSDoc,
  getEffectiveModifierFlagsNoCache,
  getEffectiveReturnTypeNode,
  getEffectiveSetAccessorTypeAnnotationNode,
  getEffectiveTypeAnnotationNode,
  getEffectiveTypeParameterDeclarations,
  getEffectiveTypeRoots,
  getElementOrPropertyAccessArgumentExpressionOrName,
  getElementOrPropertyAccessName,
  getElementsOfBindingOrAssignmentPattern,
  getEmitDeclarations,
  getEmitFlags,
  getEmitHelpers,
  getEmitModuleDetectionKind,
  getEmitModuleFormatOfFileWorker,
  getEmitModuleKind,
  getEmitModuleResolutionKind,
  getEmitScriptTarget,
  getEmitStandardClassFields,
  getEnclosingBlockScopeContainer,
  getEnclosingContainer,
  getEncodedSemanticClassifications,
  getEncodedSyntacticClassifications,
  getEndLinePosition,
  getEntityNameFromTypeNode,
  getEntrypointsFromPackageJsonInfo,
  getErrorCountForSummary,
  getErrorSpanForNode,
  getErrorSummaryText,
  getEscapedTextOfIdentifierOrLiteral,
  getEscapedTextOfJsxAttributeName,
  getEscapedTextOfJsxNamespacedName,
  getExpandoInitializer,
  getExportAssignmentExpression,
  getExportInfoMap,
  getExportNeedsImportStarHelper,
  getExpressionAssociativity,
  getExpressionPrecedence,
  getExternalHelpersModuleName,
  getExternalModuleImportEqualsDeclarationExpression,
  getExternalModuleName,
  getExternalModuleNameFromDeclaration,
  getExternalModuleNameFromPath,
  getExternalModuleNameLiteral,
  getExternalModuleRequireArgument,
  getFallbackOptions,
  getFileEmitOutput,
  getFileMatcherPatterns,
  getFileNamesFromConfigSpecs,
  getFileWatcherEventKind,
  getFilesInErrorForSummary,
  getFirstConstructorWithBody,
  getFirstIdentifier,
  getFirstNonSpaceCharacterPosition,
  getFirstProjectOutput,
  getFixableErrorSpanExpression,
  getFormatCodeSettingsForWriting,
  getFullWidth,
  getFunctionFlags,
  getHeritageClause,
  getHostSignatureFromJSDoc,
  getIdentifierAutoGenerate,
  getIdentifierGeneratedImportReference,
  getIdentifierTypeArguments,
  getImmediatelyInvokedFunctionExpression,
  getImpliedNodeFormatForEmitWorker,
  getImpliedNodeFormatForFile,
  getImpliedNodeFormatForFileWorker,
  getImportNeedsImportDefaultHelper,
  getImportNeedsImportStarHelper,
  getIndentString,
  getInferredLibraryNameResolveFrom,
  getInitializedVariables,
  getInitializerOfBinaryExpression,
  getInitializerOfBindingOrAssignmentElement,
  getInterfaceBaseTypeNodes,
  getInternalEmitFlags,
  getInvokedExpression,
  getIsFileExcluded,
  getIsolatedModules,
  getJSDocAugmentsTag,
  getJSDocClassTag,
  getJSDocCommentRanges,
  getJSDocCommentsAndTags,
  getJSDocDeprecatedTag,
  getJSDocDeprecatedTagNoCache,
  getJSDocEnumTag,
  getJSDocHost,
  getJSDocImplementsTags,
  getJSDocOverloadTags,
  getJSDocOverrideTagNoCache,
  getJSDocParameterTags,
  getJSDocParameterTagsNoCache,
  getJSDocPrivateTag,
  getJSDocPrivateTagNoCache,
  getJSDocProtectedTag,
  getJSDocProtectedTagNoCache,
  getJSDocPublicTag,
  getJSDocPublicTagNoCache,
  getJSDocReadonlyTag,
  getJSDocReadonlyTagNoCache,
  getJSDocReturnTag,
  getJSDocReturnType,
  getJSDocRoot,
  getJSDocSatisfiesExpressionType,
  getJSDocSatisfiesTag,
  getJSDocTags,
  getJSDocTemplateTag,
  getJSDocThisTag,
  getJSDocType,
  getJSDocTypeAliasName,
  getJSDocTypeAssertionType,
  getJSDocTypeParameterDeclarations,
  getJSDocTypeParameterTags,
  getJSDocTypeParameterTagsNoCache,
  getJSDocTypeTag,
  getJSXImplicitImportBase,
  getJSXRuntimeImport,
  getJSXTransformEnabled,
  getKeyForCompilerOptions,
  getLanguageVariant,
  getLastChild,
  getLeadingCommentRanges,
  getLeadingCommentRangesOfNode,
  getLeftmostAccessExpression,
  getLeftmostExpression,
  getLibraryNameFromLibFileName,
  getLineAndCharacterOfPosition,
  getLineInfo,
  getLineOfLocalPosition,
  getLineStartPositionForPosition,
  getLineStarts,
  getLinesBetweenPositionAndNextNonWhitespaceCharacter,
  getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter,
  getLinesBetweenPositions,
  getLinesBetweenRangeEndAndRangeStart,
  getLinesBetweenRangeEndPositions,
  getLiteralText,
  getLocalNameForExternalImport,
  getLocalSymbolForExportDefault,
  getLocaleSpecificMessage,
  getLocaleTimeString,
  getMappedContextSpan,
  getMappedDocumentSpan,
  getMappedLocation,
  getMatchedFileSpec,
  getMatchedIncludeSpec,
  getMeaningFromDeclaration,
  getMeaningFromLocation,
  getMembersOfDeclaration,
  getModeForFileReference,
  getModeForResolutionAtIndex,
  getModeForUsageLocation,
  getModifiedTime,
  getModifiers,
  getModuleInstanceState,
  getModuleNameStringLiteralAt,
  getModuleSpecifierEndingPreference,
  getModuleSpecifierResolverHost,
  getNameForExportedSymbol,
  getNameFromImportAttribute,
  getNameFromIndexInfo,
  getNameFromPropertyName,
  getNameOfAccessExpression,
  getNameOfCompilerOptionValue,
  getNameOfDeclaration,
  getNameOfExpando,
  getNameOfJSDocTypedef,
  getNameOfScriptTarget,
  getNameOrArgument,
  getNameTable,
  getNamespaceDeclarationNode,
  getNewLineCharacter,
  getNewLineKind,
  getNewLineOrDefaultFromHost,
  getNewTargetContainer,
  getNextJSDocCommentLocation,
  getNodeChildren,
  getNodeForGeneratedName,
  getNodeId,
  getNodeKind,
  getNodeModifiers,
  getNodeModulePathParts,
  getNonAssignedNameOfDeclaration,
  getNonAssignmentOperatorForCompoundAssignment,
  getNonAugmentationDeclaration,
  getNonDecoratorTokenPosOfNode,
  getNonIncrementalBuildInfoRoots,
  getNonModifierTokenPosOfNode,
  getNormalizedAbsolutePath,
  getNormalizedAbsolutePathWithoutRoot,
  getNormalizedPathComponents,
  getObjectFlags,
  getOperatorAssociativity,
  getOperatorPrecedence,
  getOptionFromName,
  getOptionsForLibraryResolution,
  getOptionsNameMap,
  getOrCreateEmitNode,
  getOrUpdate,
  getOriginalNode,
  getOriginalNodeId,
  getOutputDeclarationFileName,
  getOutputDeclarationFileNameWorker,
  getOutputExtension,
  getOutputFileNames,
  getOutputJSFileNameWorker,
  getOutputPathsFor,
  getOwnEmitOutputFilePath,
  getOwnKeys,
  getOwnValues,
  getPackageJsonTypesVersionsPaths,
  getPackageNameFromTypesPackageName,
  getPackageScopeForPath,
  getParameterSymbolFromJSDoc,
  getParentNodeInSpan,
  getParseTreeNode,
  getParsedCommandLineOfConfigFile,
  getPathComponents,
  getPathFromPathComponents,
  getPathUpdater,
  getPathsBasePath,
  getPatternFromSpec,
  getPendingEmitKindWithSeen,
  getPositionOfLineAndCharacter,
  getPossibleGenericSignatures,
  getPossibleOriginalInputExtensionForExtension,
  getPossibleOriginalInputPathWithoutChangingExt,
  getPossibleTypeArgumentsInfo,
  getPreEmitDiagnostics,
  getPrecedingNonSpaceCharacterPosition,
  getPrivateIdentifier,
  getProperties,
  getProperty,
  getPropertyArrayElementValue,
  getPropertyAssignmentAliasLikeExpression,
  getPropertyNameForPropertyNameNode,
  getPropertyNameFromType,
  getPropertyNameOfBindingOrAssignmentElement,
  getPropertySymbolFromBindingElement,
  getPropertySymbolsFromContextualType,
  getQuoteFromPreference,
  getQuotePreference,
  getRangesWhere,
  getRefactorContextSpan,
  getReferencedFileLocation,
  getRegexFromPattern,
  getRegularExpressionForWildcard,
  getRegularExpressionsForWildcards,
  getRelativePathFromDirectory,
  getRelativePathFromFile,
  getRelativePathToDirectoryOrUrl,
  getRenameLocation,
  getReplacementSpanForContextToken,
  getResolutionDiagnostic,
  getResolutionModeOverride,
  getResolveJsonModule,
  getResolvePackageJsonExports,
  getResolvePackageJsonImports,
  getResolvedExternalModuleName,
  getResolvedModuleFromResolution,
  getResolvedTypeReferenceDirectiveFromResolution,
  getRestIndicatorOfBindingOrAssignmentElement,
  getRestParameterElementType,
  getRightMostAssignedExpression,
  getRootDeclaration,
  getRootDirectoryOfResolutionCache,
  getRootLength,
  getScriptKind,
  getScriptKindFromFileName,
  getScriptTargetFeatures,
  getSelectedEffectiveModifierFlags,
  getSelectedSyntacticModifierFlags,
  getSemanticClassifications,
  getSemanticJsxChildren,
  getSetAccessorTypeAnnotationNode,
  getSetAccessorValueParameter,
  getSetExternalModuleIndicator,
  getShebang,
  getSingleVariableOfVariableStatement,
  getSnapshotText,
  getSnippetElement,
  getSourceFileOfModule,
  getSourceFileOfNode,
  getSourceFilePathInNewDir,
  getSourceFileVersionAsHashFromText,
  getSourceFilesToEmit,
  getSourceMapRange,
  getSourceMapper,
  getSourceTextOfNodeFromSourceFile,
  getSpanOfTokenAtPosition,
  getSpellingSuggestion,
  getStartPositionOfLine,
  getStartPositionOfRange,
  getStartsOnNewLine,
  getStaticPropertiesAndClassStaticBlock,
  getStrictOptionValue,
  getStringComparer,
  getSubPatternFromSpec,
  getSuperCallFromStatement,
  getSuperContainer,
  getSupportedCodeFixes,
  getSupportedExtensions,
  getSupportedExtensionsWithJsonIfResolveJsonModule,
  getSwitchedType,
  getSymbolId,
  getSymbolNameForPrivateIdentifier,
  getSymbolTarget,
  getSyntacticClassifications,
  getSyntacticModifierFlags,
  getSyntacticModifierFlagsNoCache,
  getSynthesizedDeepClone,
  getSynthesizedDeepCloneWithReplacements,
  getSynthesizedDeepClones,
  getSynthesizedDeepClonesWithReplacements,
  getSyntheticLeadingComments,
  getSyntheticTrailingComments,
  getTargetLabel,
  getTargetOfBindingOrAssignmentElement,
  getTemporaryModuleResolutionState,
  getTextOfConstantValue,
  getTextOfIdentifierOrLiteral,
  getTextOfJSDocComment,
  getTextOfJsxAttributeName,
  getTextOfJsxNamespacedName,
  getTextOfNode,
  getTextOfNodeFromSourceText,
  getTextOfPropertyName,
  getThisContainer,
  getThisParameter,
  getTokenAtPosition,
  getTokenPosOfNode,
  getTokenSourceMapRange,
  getTouchingPropertyName,
  getTouchingToken,
  getTrailingCommentRanges,
  getTrailingSemicolonDeferringWriter,
  getTransformers,
  getTsBuildInfoEmitOutputFilePath,
  getTsConfigObjectLiteralExpression,
  getTsConfigPropArrayElementValue,
  getTypeAnnotationNode,
  getTypeArgumentOrTypeParameterList,
  getTypeKeywordOfTypeOnlyImport,
  getTypeNode,
  getTypeNodeIfAccessible,
  getTypeParameterFromJsDoc,
  getTypeParameterOwner,
  getTypesPackageName,
  getUILocale,
  getUniqueName,
  getUniqueSymbolId,
  getUseDefineForClassFields,
  getWatchErrorSummaryDiagnosticMessage,
  getWatchFactory,
  group,
  groupBy,
  guessIndentation,
  handleNoEmitOptions,
  handleWatchOptionsConfigDirTemplateSubstitution,
  hasAbstractModifier,
  hasAccessorModifier,
  hasAmbientModifier,
  hasChangesInResolutions,
  hasContextSensitiveParameters,
  hasDecorators,
  hasDocComment,
  hasDynamicName,
  hasEffectiveModifier,
  hasEffectiveModifiers,
  hasEffectiveReadonlyModifier,
  hasExtension,
  hasImplementationTSFileExtension,
  hasIndexSignature,
  hasInferredType,
  hasInitializer,
  hasInvalidEscape,
  hasJSDocNodes,
  hasJSDocParameterTags,
  hasJSFileExtension,
  hasJsonModuleEmitEnabled,
  hasOnlyExpressionInitializer,
  hasOverrideModifier,
  hasPossibleExternalModuleReference,
  hasProperty,
  hasPropertyAccessExpressionWithName,
  hasQuestionToken,
  hasRecordedExternalHelpers,
  hasResolutionModeOverride,
  hasRestParameter,
  hasScopeMarker,
  hasStaticModifier,
  hasSyntacticModifier,
  hasSyntacticModifiers,
  hasTSFileExtension,
  hasTabstop,
  hasTrailingDirectorySeparator,
  hasType,
  hasTypeArguments,
  hasZeroOrOneAsteriskCharacter,
  hostGetCanonicalFileName,
  hostUsesCaseSensitiveFileNames,
  idText,
  identifierIsThisKeyword,
  identifierToKeywordKind,
  identity,
  identitySourceMapConsumer,
  ignoreSourceNewlines,
  ignoredPaths,
  importFromModuleSpecifier,
  importSyntaxAffectsModuleResolution,
  indexOfAnyCharCode,
  indexOfNode,
  indicesOf,
  inferredTypesContainingFile,
  injectClassNamedEvaluationHelperBlockIfMissing,
  injectClassThisAssignmentIfMissing,
  insertImports,
  insertSorted,
  insertStatementAfterCustomPrologue,
  insertStatementAfterStandardPrologue,
  insertStatementsAfterCustomPrologue,
  insertStatementsAfterStandardPrologue,
  intersperse,
  intrinsicTagNameToString,
  introducesArgumentsExoticObject,
  inverseJsxOptionMap,
  isAbstractConstructorSymbol,
  isAbstractModifier,
  isAccessExpression,
  isAccessibilityModifier,
  isAccessor,
  isAccessorModifier,
  isAliasableExpression,
  isAmbientModule,
  isAmbientPropertyDeclaration,
  isAnyDirectorySeparator,
  isAnyImportOrBareOrAccessedRequire,
  isAnyImportOrReExport,
  isAnyImportOrRequireStatement,
  isAnyImportSyntax,
  isAnySupportedFileExtension,
  isApplicableVersionedTypesKey,
  isArgumentExpressionOfElementAccess,
  isArray,
  isArrayBindingElement,
  isArrayBindingOrAssignmentElement,
  isArrayBindingOrAssignmentPattern,
  isArrayBindingPattern,
  isArrayLiteralExpression,
  isArrayLiteralOrObjectLiteralDestructuringPattern,
  isArrayTypeNode,
  isArrowFunction,
  isAsExpression,
  isAssertClause,
  isAssertEntry,
  isAssertionExpression,
  isAssertsKeyword,
  isAssignmentDeclaration,
  isAssignmentExpression,
  isAssignmentOperator,
  isAssignmentPattern,
  isAssignmentTarget,
  isAsteriskToken,
  isAsyncFunction,
  isAsyncModifier,
  isAutoAccessorPropertyDeclaration,
  isAwaitExpression,
  isAwaitKeyword,
  isBigIntLiteral,
  isBinaryExpression,
  isBinaryLogicalOperator,
  isBinaryOperatorToken,
  isBindableObjectDefinePropertyCall,
  isBindableStaticAccessExpression,
  isBindableStaticElementAccessExpression,
  isBindableStaticNameExpression,
  isBindingElement,
  isBindingElementOfBareOrAccessedRequire,
  isBindingName,
  isBindingOrAssignmentElement,
  isBindingOrAssignmentPattern,
  isBindingPattern,
  isBlock,
  isBlockLike,
  isBlockOrCatchScoped,
  isBlockScope,
  isBlockScopedContainerTopLevel,
  isBooleanLiteral,
  isBreakOrContinueStatement,
  isBreakStatement,
  isBuildCommand,
  isBuildInfoFile,
  isBuilderProgram,
  isBundle,
  isCallChain,
  isCallExpression,
  isCallExpressionTarget,
  isCallLikeExpression,
  isCallLikeOrFunctionLikeExpression,
  isCallOrNewExpression,
  isCallOrNewExpressionTarget,
  isCallSignatureDeclaration,
  isCallToHelper,
  isCaseBlock,
  isCaseClause,
  isCaseKeyword,
  isCaseOrDefaultClause,
  isCatchClause,
  isCatchClauseVariableDeclaration,
  isCatchClauseVariableDeclarationOrBindingElement,
  isCheckJsEnabledForFile,
  isCircularBuildOrder,
  isClassDeclaration,
  isClassElement,
  isClassExpression,
  isClassInstanceProperty,
  isClassLike,
  isClassMemberModifier,
  isClassNamedEvaluationHelperBlock,
  isClassOrTypeElement,
  isClassStaticBlockDeclaration,
  isClassThisAssignmentBlock,
  isColonToken,
  isCommaExpression,
  isCommaListExpression,
  isCommaSequence,
  isCommaToken,
  isComment,
  isCommonJsExportPropertyAssignment,
  isCommonJsExportedExpression,
  isCompoundAssignment,
  isComputedNonLiteralName,
  isComputedPropertyName,
  isConciseBody,
  isConditionalExpression,
  isConditionalTypeNode,
  isConstAssertion,
  isConstTypeReference,
  isConstructSignatureDeclaration,
  isConstructorDeclaration,
  isConstructorTypeNode,
  isContextualKeyword,
  isContinueStatement,
  isCustomPrologue,
  isDebuggerStatement,
  isDeclaration,
  isDeclarationBindingElement,
  isDeclarationFileName,
  isDeclarationName,
  isDeclarationNameOfEnumOrNamespace,
  isDeclarationReadonly,
  isDeclarationStatement,
  isDeclarationWithTypeParameterChildren,
  isDeclarationWithTypeParameters,
  isDecorator,
  isDecoratorTarget,
  isDefaultClause,
  isDefaultImport,
  isDefaultModifier,
  isDefaultedExpandoInitializer,
  isDeleteExpression,
  isDeleteTarget,
  isDeprecatedDeclaration,
  isDestructuringAssignment,
  isDiskPathRoot,
  isDoStatement,
  isDocumentRegistryEntry,
  isDotDotDotToken,
  isDottedName,
  isDynamicName,
  isEffectiveExternalModule,
  isEffectiveStrictModeSourceFile,
  isElementAccessChain,
  isElementAccessExpression,
  isEmittedFileOfProgram,
  isEmptyArrayLiteral,
  isEmptyBindingElement,
  isEmptyBindingPattern,
  isEmptyObjectLiteral,
  isEmptyStatement,
  isEmptyStringLiteral,
  isEntityName,
  isEntityNameExpression,
  isEnumConst,
  isEnumDeclaration,
  isEnumMember,
  isEqualityOperatorKind,
  isEqualsGreaterThanToken,
  isExclamationToken,
  isExcludedFile,
  isExclusivelyTypeOnlyImportOrExport,
  isExpandoPropertyDeclaration,
  isExportAssignment,
  isExportDeclaration,
  isExportModifier,
  isExportName,
  isExportNamespaceAsDefaultDeclaration,
  isExportOrDefaultModifier,
  isExportSpecifier,
  isExportsIdentifier,
  isExportsOrModuleExportsOrAlias,
  isExpression,
  isExpressionNode,
  isExpressionOfExternalModuleImportEqualsDeclaration,
  isExpressionOfOptionalChainRoot,
  isExpressionStatement,
  isExpressionWithTypeArguments,
  isExpressionWithTypeArgumentsInClassExtendsClause,
  isExternalModule,
  isExternalModuleAugmentation,
  isExternalModuleImportEqualsDeclaration,
  isExternalModuleIndicator,
  isExternalModuleNameRelative,
  isExternalModuleReference,
  isExternalModuleSymbol,
  isExternalOrCommonJsModule,
  isFileLevelReservedGeneratedIdentifier,
  isFileLevelUniqueName,
  isFileProbablyExternalModule,
  isFirstDeclarationOfSymbolParameter,
  isFixablePromiseHandler,
  isForInOrOfStatement,
  isForInStatement,
  isForInitializer,
  isForOfStatement,
  isForStatement,
  isFullSourceFile,
  isFunctionBlock,
  isFunctionBody,
  isFunctionDeclaration,
  isFunctionExpression,
  isFunctionExpressionOrArrowFunction,
  isFunctionLike,
  isFunctionLikeDeclaration,
  isFunctionLikeKind,
  isFunctionLikeOrClassStaticBlockDeclaration,
  isFunctionOrConstructorTypeNode,
  isFunctionOrModuleBlock,
  isFunctionSymbol,
  isFunctionTypeNode,
  isGeneratedIdentifier,
  isGeneratedPrivateIdentifier,
  isGetAccessor,
  isGetAccessorDeclaration,
  isGetOrSetAccessorDeclaration,
  isGlobalScopeAugmentation,
  isGlobalSourceFile,
  isGrammarError,
  isHeritageClause,
  isHoistedFunction,
  isHoistedVariableStatement,
  isIdentifier,
  isIdentifierANonContextualKeyword,
  isIdentifierName,
  isIdentifierOrThisTypeNode,
  isIdentifierPart,
  isIdentifierStart,
  isIdentifierText,
  isIdentifierTypePredicate,
  isIdentifierTypeReference,
  isIfStatement,
  isIgnoredFileFromWildCardWatching,
  isImplicitGlob,
  isImportAttribute,
  isImportAttributeName,
  isImportAttributes,
  isImportCall,
  isImportClause,
  isImportDeclaration,
  isImportEqualsDeclaration,
  isImportKeyword,
  isImportMeta,
  isImportOrExportSpecifier,
  isImportOrExportSpecifierName,
  isImportSpecifier,
  isImportTypeAssertionContainer,
  isImportTypeNode,
  isImportable,
  isInComment,
  isInCompoundLikeAssignment,
  isInExpressionContext,
  isInJSDoc,
  isInJSFile,
  isInJSXText,
  isInJsonFile,
  isInNonReferenceComment,
  isInReferenceComment,
  isInRightSideOfInternalImportEqualsDeclaration,
  isInString,
  isInTemplateString,
  isInTopLevelContext,
  isInTypeQuery,
  isIncrementalBuildInfo,
  isIncrementalBundleEmitBuildInfo,
  isIncrementalCompilation,
  isIndexSignatureDeclaration,
  isIndexedAccessTypeNode,
  isInferTypeNode,
  isInfinityOrNaNString,
  isInitializedProperty,
  isInitializedVariable,
  isInsideJsxElement,
  isInsideJsxElementOrAttribute,
  isInsideNodeModules,
  isInsideTemplateLiteral,
  isInstanceOfExpression,
  isInstantiatedModule,
  isInterfaceDeclaration,
  isInternalDeclaration,
  isInternalModuleImportEqualsDeclaration,
  isInternalName,
  isIntersectionTypeNode,
  isIntrinsicJsxName,
  isIterationStatement,
  isJSDoc,
  isJSDocAllType,
  isJSDocAugmentsTag,
  isJSDocAuthorTag,
  isJSDocCallbackTag,
  isJSDocClassTag,
  isJSDocCommentContainingNode,
  isJSDocConstructSignature,
  isJSDocDeprecatedTag,
  isJSDocEnumTag,
  isJSDocFunctionType,
  isJSDocImplementsTag,
  isJSDocImportTag,
  isJSDocIndexSignature,
  isJSDocLikeText,
  isJSDocLink,
  isJSDocLinkCode,
  isJSDocLinkLike,
  isJSDocLinkPlain,
  isJSDocMemberName,
  isJSDocNameReference,
  isJSDocNamepathType,
  isJSDocNamespaceBody,
  isJSDocNode,
  isJSDocNonNullableType,
  isJSDocNullableType,
  isJSDocOptionalParameter,
  isJSDocOptionalType,
  isJSDocOverloadTag,
  isJSDocOverrideTag,
  isJSDocParameterTag,
  isJSDocPrivateTag,
  isJSDocPropertyLikeTag,
  isJSDocPropertyTag,
  isJSDocProtectedTag,
  isJSDocPublicTag,
  isJSDocReadonlyTag,
  isJSDocReturnTag,
  isJSDocSatisfiesExpression,
  isJSDocSatisfiesTag,
  isJSDocSeeTag,
  isJSDocSignature,
  isJSDocTag,
  isJSDocTemplateTag,
  isJSDocThisTag,
  isJSDocThrowsTag,
  isJSDocTypeAlias,
  isJSDocTypeAssertion,
  isJSDocTypeExpression,
  isJSDocTypeLiteral,
  isJSDocTypeTag,
  isJSDocTypedefTag,
  isJSDocUnknownTag,
  isJSDocUnknownType,
  isJSDocVariadicType,
  isJSXTagName,
  isJsonEqual,
  isJsonSourceFile,
  isJsxAttribute,
  isJsxAttributeLike,
  isJsxAttributeName,
  isJsxAttributes,
  isJsxCallLike,
  isJsxChild,
  isJsxClosingElement,
  isJsxClosingFragment,
  isJsxElement,
  isJsxExpression,
  isJsxFragment,
  isJsxNamespacedName,
  isJsxOpeningElement,
  isJsxOpeningFragment,
  isJsxOpeningLikeElement,
  isJsxOpeningLikeElementTagName,
  isJsxSelfClosingElement,
  isJsxSpreadAttribute,
  isJsxTagNameExpression,
  isJsxText,
  isJumpStatementTarget,
  isKeyword,
  isKeywordOrPunctuation,
  isKnownSymbol,
  isLabelName,
  isLabelOfLabeledStatement,
  isLabeledStatement,
  isLateVisibilityPaintedStatement,
  isLeftHandSideExpression,
  isLet,
  isLineBreak,
  isLiteralComputedPropertyDeclarationName,
  isLiteralExpression,
  isLiteralExpressionOfObject,
  isLiteralImportTypeNode,
  isLiteralKind,
  isLiteralNameOfPropertyDeclarationOrIndexAccess,
  isLiteralTypeLiteral,
  isLiteralTypeNode,
  isLocalName,
  isLogicalOperator,
  isLogicalOrCoalescingAssignmentExpression,
  isLogicalOrCoalescingAssignmentOperator,
  isLogicalOrCoalescingBinaryExpression,
  isLogicalOrCoalescingBinaryOperator,
  isMappedTypeNode,
  isMemberName,
  isMetaProperty,
  isMethodDeclaration,
  isMethodOrAccessor,
  isMethodSignature,
  isMinusToken,
  isMissingDeclaration,
  isMissingPackageJsonInfo,
  isModifier,
  isModifierKind,
  isModifierLike,
  isModuleAugmentationExternal,
  isModuleBlock,
  isModuleBody,
  isModuleDeclaration,
  isModuleExportName,
  isModuleExportsAccessExpression,
  isModuleIdentifier,
  isModuleName,
  isModuleOrEnumDeclaration,
  isModuleReference,
  isModuleSpecifierLike,
  isModuleWithStringLiteralName,
  isNameOfFunctionDeclaration,
  isNameOfModuleDeclaration,
  isNamedDeclaration,
  isNamedEvaluation,
  isNamedEvaluationSource,
  isNamedExportBindings,
  isNamedExports,
  isNamedImportBindings,
  isNamedImports,
  isNamedImportsOrExports,
  isNamedTupleMember,
  isNamespaceBody,
  isNamespaceExport,
  isNamespaceExportDeclaration,
  isNamespaceImport,
  isNamespaceReexportDeclaration,
  isNewExpression,
  isNewExpressionTarget,
  isNewScopeNode,
  isNoSubstitutionTemplateLiteral,
  isNodeArray,
  isNodeArrayMultiLine,
  isNodeDescendantOf,
  isNodeKind,
  isNodeLikeSystem,
  isNodeModulesDirectory,
  isNodeWithPossibleHoistedDeclaration,
  isNonContextualKeyword,
  isNonGlobalAmbientModule,
  isNonNullAccess,
  isNonNullChain,
  isNonNullExpression,
  isNonStaticMethodOrAccessorWithPrivateName,
  isNotEmittedStatement,
  isNullishCoalesce,
  isNumber,
  isNumericLiteral,
  isNumericLiteralName,
  isObjectBindingElementWithoutPropertyName,
  isObjectBindingOrAssignmentElement,
  isObjectBindingOrAssignmentPattern,
  isObjectBindingPattern,
  isObjectLiteralElement,
  isObjectLiteralElementLike,
  isObjectLiteralExpression,
  isObjectLiteralMethod,
  isObjectLiteralOrClassExpressionMethodOrAccessor,
  isObjectTypeDeclaration,
  isOmittedExpression,
  isOptionalChain,
  isOptionalChainRoot,
  isOptionalDeclaration,
  isOptionalJSDocPropertyLikeTag,
  isOptionalTypeNode,
  isOuterExpression,
  isOutermostOptionalChain,
  isOverrideModifier,
  isPackageJsonInfo,
  isPackedArrayLiteral,
  isParameter,
  isParameterPropertyDeclaration,
  isParameterPropertyModifier,
  isParenthesizedExpression,
  isParenthesizedTypeNode,
  isParseTreeNode,
  isPartOfParameterDeclaration,
  isPartOfTypeNode,
  isPartOfTypeOnlyImportOrExportDeclaration,
  isPartOfTypeQuery,
  isPartiallyEmittedExpression,
  isPatternMatch,
  isPinnedComment,
  isPlainJsFile,
  isPlusToken,
  isPossiblyTypeArgumentPosition,
  isPostfixUnaryExpression,
  isPrefixUnaryExpression,
  isPrimitiveLiteralValue,
  isPrivateIdentifier,
  isPrivateIdentifierClassElementDeclaration,
  isPrivateIdentifierPropertyAccessExpression,
  isPrivateIdentifierSymbol,
  isProgramUptoDate,
  isPrologueDirective,
  isPropertyAccessChain,
  isPropertyAccessEntityNameExpression,
  isPropertyAccessExpression,
  isPropertyAccessOrQualifiedName,
  isPropertyAccessOrQualifiedNameOrImportTypeNode,
  isPropertyAssignment,
  isPropertyDeclaration,
  isPropertyName,
  isPropertyNameLiteral,
  isPropertySignature,
  isPrototypeAccess,
  isPrototypePropertyAssignment,
  isPunctuation,
  isPushOrUnshiftIdentifier,
  isQualifiedName,
  isQuestionDotToken,
  isQuestionOrExclamationToken,
  isQuestionOrPlusOrMinusToken,
  isQuestionToken,
  isReadonlyKeyword,
  isReadonlyKeywordOrPlusOrMinusToken,
  isRecognizedTripleSlashComment,
  isReferenceFileLocation,
  isReferencedFile,
  isRegularExpressionLiteral,
  isRequireCall,
  isRequireVariableStatement,
  isRestParameter,
  isRestTypeNode,
  isReturnStatement,
  isReturnStatementWithFixablePromiseHandler,
  isRightSideOfAccessExpression,
  isRightSideOfInstanceofExpression,
  isRightSideOfPropertyAccess,
  isRightSideOfQualifiedName,
  isRightSideOfQualifiedNameOrPropertyAccess,
  isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName,
  isRootedDiskPath,
  isSameEntityName,
  isSatisfiesExpression,
  isSemicolonClassElement,
  isSetAccessor,
  isSetAccessorDeclaration,
  isShiftOperatorOrHigher,
  isShorthandAmbientModuleSymbol,
  isShorthandPropertyAssignment,
  isSideEffectImport,
  isSignedNumericLiteral,
  isSimpleCopiableExpression,
  isSimpleInlineableExpression,
  isSimpleParameterList,
  isSingleOrDoubleQuote,
  isSolutionConfig,
  isSourceElement,
  isSourceFile,
  isSourceFileFromLibrary,
  isSourceFileJS,
  isSourceFileNotJson,
  isSourceMapping,
  isSpecialPropertyDeclaration,
  isSpreadAssignment,
  isSpreadElement,
  isStatement,
  isStatementButNotDeclaration,
  isStatementOrBlock,
  isStatementWithLocals,
  isStatic,
  isStaticModifier,
  isString,
  isStringANonContextualKeyword,
  isStringAndEmptyAnonymousObjectIntersection,
  isStringDoubleQuoted,
  isStringLiteral,
  isStringLiteralLike,
  isStringLiteralOrJsxExpression,
  isStringLiteralOrTemplate,
  isStringOrNumericLiteralLike,
  isStringOrRegularExpressionOrTemplateLiteral,
  isStringTextContainingNode,
  isSuperCall,
  isSuperKeyword,
  isSuperProperty,
  isSupportedSourceFileName,
  isSwitchStatement,
  isSyntaxList,
  isSyntheticExpression,
  isSyntheticReference,
  isTagName,
  isTaggedTemplateExpression,
  isTaggedTemplateTag,
  isTemplateExpression,
  isTemplateHead,
  isTemplateLiteral,
  isTemplateLiteralKind,
  isTemplateLiteralToken,
  isTemplateLiteralTypeNode,
  isTemplateLiteralTypeSpan,
  isTemplateMiddle,
  isTemplateMiddleOrTemplateTail,
  isTemplateSpan,
  isTemplateTail,
  isTextWhiteSpaceLike,
  isThis,
  isThisContainerOrFunctionBlock,
  isThisIdentifier,
  isThisInTypeQuery,
  isThisInitializedDeclaration,
  isThisInitializedObjectBindingExpression,
  isThisProperty,
  isThisTypeNode,
  isThisTypeParameter,
  isThisTypePredicate,
  isThrowStatement,
  isToken,
  isTokenKind,
  isTraceEnabled,
  isTransientSymbol,
  isTrivia,
  isTryStatement,
  isTupleTypeNode,
  isTypeAlias,
  isTypeAliasDeclaration,
  isTypeAssertionExpression,
  isTypeDeclaration,
  isTypeElement,
  isTypeKeyword,
  isTypeKeywordTokenOrIdentifier,
  isTypeLiteralNode,
  isTypeNode,
  isTypeNodeKind,
  isTypeOfExpression,
  isTypeOnlyExportDeclaration,
  isTypeOnlyImportDeclaration,
  isTypeOnlyImportOrExportDeclaration,
  isTypeOperatorNode,
  isTypeParameterDeclaration,
  isTypePredicateNode,
  isTypeQueryNode,
  isTypeReferenceNode,
  isTypeReferenceType,
  isTypeUsableAsPropertyName,
  isUMDExportSymbol,
  isUnaryExpression,
  isUnaryExpressionWithWrite,
  isUnicodeIdentifierStart,
  isUnionTypeNode,
  isUrl,
  isValidBigIntString,
  isValidESSymbolDeclaration,
  isValidTypeOnlyAliasUseSite,
  isValueSignatureDeclaration,
  isVarAwaitUsing,
  isVarConst,
  isVarConstLike,
  isVarUsing,
  isVariableDeclaration,
  isVariableDeclarationInVariableStatement,
  isVariableDeclarationInitializedToBareOrAccessedRequire,
  isVariableDeclarationInitializedToRequire,
  isVariableDeclarationList,
  isVariableLike,
  isVariableStatement,
  isVoidExpression,
  isWatchSet,
  isWhileStatement,
  isWhiteSpaceLike,
  isWhiteSpaceSingleLine,
  isWithStatement,
  isWriteAccess,
  isWriteOnlyAccess,
  isYieldExpression,
  jsxModeNeedsExplicitImport,
  keywordPart,
  last,
  lastOrUndefined,
  length,
  libMap,
  libs,
  lineBreakPart,
  loadModuleFromGlobalCache,
  loadWithModeAwareCache,
  makeIdentifierFromModuleName,
  makeImport,
  makeStringLiteral,
  mangleScopedPackageName,
  map,
  mapAllOrFail,
  mapDefined,
  mapDefinedIterator,
  mapEntries,
  mapIterator,
  mapOneOrMany,
  mapToDisplayParts,
  matchFiles,
  matchPatternOrExact,
  matchedText,
  matchesExclude,
  matchesExcludeWorker,
  maxBy,
  maybeBind,
  maybeSetLocalizedDiagnosticMessages,
  memoize,
  memoizeOne,
  min,
  minAndMax,
  missingFileModifiedTime,
  modifierToFlag,
  modifiersToFlags,
  moduleExportNameIsDefault,
  moduleExportNameTextEscaped,
  moduleExportNameTextUnescaped,
  moduleOptionDeclaration,
  moduleResolutionIsEqualTo,
  moduleResolutionNameAndModeGetter,
  moduleResolutionOptionDeclarations,
  moduleResolutionSupportsPackageJsonExportsAndImports,
  moduleResolutionUsesNodeModules,
  moduleSpecifierToValidIdentifier,
  moduleSpecifiers,
  moduleSymbolToValidIdentifier,
  moveEmitHelpers,
  moveRangeEnd,
  moveRangePastDecorators,
  moveRangePastModifiers,
  moveRangePos,
  moveSyntheticComments,
  mutateMap,
  mutateMapSkippingNewValues,
  needsParentheses,
  needsScopeMarker,
  newCaseClauseTracker,
  newPrivateEnvironment,
  noEmitNotification,
  noEmitSubstitution,
  noTransformers,
  noTruncationMaximumTruncationLength,
  nodeCanBeDecorated,
  nodeCoreModules,
  nodeHasName,
  nodeIsDecorated,
  nodeIsMissing,
  nodeIsPresent,
  nodeIsSynthesized,
  nodeModuleNameResolver,
  nodeModulesPathPart,
  nodeNextJsonConfigResolver,
  nodeOrChildIsDecorated,
  nodeOverlapsWithStartEnd,
  nodePosToString,
  nodeSeenTracker,
  nodeStartsNewLexicalEnvironment,
  noop,
  noopFileWatcher,
  normalizePath,
  normalizeSlashes,
  normalizeSpans,
  not,
  notImplemented,
  notImplementedResolver,
  nullNodeConverters,
  nullParenthesizerRules,
  nullTransformationContext,
  objectAllocator,
  operatorPart,
  optionDeclarations,
  optionMapToObject,
  optionsAffectingProgramStructure,
  optionsForBuild,
  optionsForWatch,
  optionsHaveChanges,
  or,
  orderedRemoveItem,
  orderedRemoveItemAt,
  packageIdToPackageName,
  packageIdToString,
  parameterIsThisKeyword,
  parameterNamePart,
  parseBaseNodeFactory,
  parseBigInt,
  parseBuildCommand,
  parseCommandLine,
  parseCommandLineWorker,
  parseConfigFileTextToJson,
  parseConfigFileWithSystem,
  parseConfigHostFromCompilerHostLike,
  parseCustomTypeOption,
  parseIsolatedEntityName,
  parseIsolatedJSDocComment,
  parseJSDocTypeExpressionForTests,
  parseJsonConfigFileContent,
  parseJsonSourceFileConfigFileContent,
  parseJsonText,
  parseListTypeOption,
  parseNodeFactory,
  parseNodeModuleFromPath,
  parsePackageName,
  parsePseudoBigInt,
  parseValidBigInt,
  pasteEdits,
  patchWriteFileEnsuringDirectory,
  pathContainsNodeModules,
  pathIsAbsolute,
  pathIsBareSpecifier,
  pathIsRelative,
  patternText,
  performIncrementalCompilation,
  performance,
  positionBelongsToNode,
  positionIsASICandidate,
  positionIsSynthesized,
  positionsAreOnSameLine,
  preProcessFile,
  probablyUsesSemicolons,
  processCommentPragmas,
  processPragmasIntoFields,
  processTaggedTemplateExpression,
  programContainsEsModules,
  programContainsModules,
  projectReferenceIsEqualTo,
  propertyNamePart,
  pseudoBigIntToString,
  punctuationPart,
  pushIfUnique,
  quote,
  quotePreferenceFromString,
  rangeContainsPosition,
  rangeContainsPositionExclusive,
  rangeContainsRange,
  rangeContainsRangeExclusive,
  rangeContainsStartEnd,
  rangeEndIsOnSameLineAsRangeStart,
  rangeEndPositionsAreOnSameLine,
  rangeEquals,
  rangeIsOnSingleLine,
  rangeOfNode,
  rangeOfTypeParameters,
  rangeOverlapsWithStartEnd,
  rangeStartIsOnSameLineAsRangeEnd,
  rangeStartPositionsAreOnSameLine,
  readBuilderProgram,
  readConfigFile,
  readJson,
  readJsonConfigFile,
  readJsonOrUndefined,
  reduceEachLeadingCommentRange,
  reduceEachTrailingCommentRange,
  reduceLeft,
  reduceLeftIterator,
  reducePathComponents,
  refactor,
  regExpEscape,
  regularExpressionFlagToCharacterCode,
  relativeComplement,
  removeAllComments,
  removeEmitHelper,
  removeExtension,
  removeFileExtension,
  removeIgnoredPath,
  removeMinAndVersionNumbers,
  removePrefix,
  removeSuffix,
  removeTrailingDirectorySeparator,
  repeatString,
  replaceElement,
  replaceFirstStar,
  resolutionExtensionIsTSOrJson,
  resolveConfigFileProjectName,
  resolveJSModule,
  resolveLibrary,
  resolveModuleName,
  resolveModuleNameFromCache,
  resolvePackageNameToPackageJson,
  resolvePath,
  resolveProjectReferencePath,
  resolveTripleslashReference,
  resolveTypeReferenceDirective,
  resolvingEmptyArray,
  returnFalse,
  returnNoopFileWatcher,
  returnTrue,
  returnUndefined,
  returnsPromise,
  rewriteModuleSpecifier,
  sameFlatMap,
  sameMap,
  sameMapping,
  scanTokenAtPosition,
  scanner,
  semanticDiagnosticsOptionDeclarations,
  serializeCompilerOptions,
  server,
  servicesVersion,
  setCommentRange,
  setConfigFileInOptions,
  setConstantValue,
  setEmitFlags,
  setGetSourceFileAsHashVersioned,
  setIdentifierAutoGenerate,
  setIdentifierGeneratedImportReference,
  setIdentifierTypeArguments,
  setInternalEmitFlags,
  setLocalizedDiagnosticMessages,
  setNodeChildren,
  setNodeFlags,
  setObjectAllocator,
  setOriginalNode,
  setParent,
  setParentRecursive,
  setPrivateIdentifier,
  setSnippetElement,
  setSourceMapRange,
  setStackTraceLimit,
  setStartsOnNewLine,
  setSyntheticLeadingComments,
  setSyntheticTrailingComments,
  setSys,
  setSysLog,
  setTextRange,
  setTextRangeEnd,
  setTextRangePos,
  setTextRangePosEnd,
  setTextRangePosWidth,
  setTokenSourceMapRange,
  setTypeNode,
  setUILocale,
  setValueDeclaration,
  shouldAllowImportingTsExtension,
  shouldPreserveConstEnums,
  shouldRewriteModuleSpecifier,
  shouldUseUriStyleNodeCoreModules,
  showModuleSpecifier,
  signatureHasRestParameter,
  signatureToDisplayParts,
  single,
  singleElementArray,
  singleIterator,
  singleOrMany,
  singleOrUndefined,
  skipAlias,
  skipConstraint,
  skipOuterExpressions,
  skipParentheses,
  skipPartiallyEmittedExpressions,
  skipTrivia,
  skipTypeChecking,
  skipTypeCheckingIgnoringNoCheck,
  skipTypeParentheses,
  skipWhile,
  sliceAfter,
  some,
  sortAndDeduplicate,
  sortAndDeduplicateDiagnostics,
  sourceFileAffectingCompilerOptions,
  sourceFileMayBeEmitted,
  sourceMapCommentRegExp,
  sourceMapCommentRegExpDontCareLineStart,
  spacePart,
  spanMap,
  startEndContainsRange,
  startEndOverlapsWithStartEnd,
  startOnNewLine,
  startTracing,
  startsWith,
  startsWithDirectory,
  startsWithUnderscore,
  startsWithUseStrict,
  stringContainsAt,
  stringToToken,
  stripQuotes,
  supportedDeclarationExtensions,
  supportedJSExtensionsFlat,
  supportedLocaleDirectories,
  supportedTSExtensionsFlat,
  supportedTSImplementationExtensions,
  suppressLeadingAndTrailingTrivia,
  suppressLeadingTrivia,
  suppressTrailingTrivia,
  symbolEscapedNameNoDefault,
  symbolName,
  symbolNameNoDefault,
  symbolToDisplayParts,
  sys,
  sysLog,
  tagNamesAreEquivalent,
  takeWhile,
  targetOptionDeclaration,
  targetToLibMap,
  testFormatSettings,
  textChangeRangeIsUnchanged,
  textChangeRangeNewSpan,
  textChanges,
  textOrKeywordPart,
  textPart,
  textRangeContainsPositionInclusive,
  textRangeContainsTextSpan,
  textRangeIntersectsWithTextSpan,
  textSpanContainsPosition,
  textSpanContainsTextRange,
  textSpanContainsTextSpan,
  textSpanEnd,
  textSpanIntersection,
  textSpanIntersectsWith,
  textSpanIntersectsWithPosition,
  textSpanIntersectsWithTextSpan,
  textSpanIsEmpty,
  textSpanOverlap,
  textSpanOverlapsWith,
  textSpansEqual,
  textToKeywordObj,
  timestamp,
  toArray,
  toBuilderFileEmit,
  toBuilderStateFileInfoForMultiEmit,
  toEditorSettings,
  toFileNameLowerCase,
  toPath,
  toProgramEmitPending,
  toSorted,
  tokenIsIdentifierOrKeyword,
  tokenIsIdentifierOrKeywordOrGreaterThan,
  tokenToString,
  trace,
  tracing,
  tracingEnabled,
  transferSourceFileChildren,
  transform,
  transformClassFields,
  transformDeclarations,
  transformECMAScriptModule,
  transformES2015,
  transformES2016,
  transformES2017,
  transformES2018,
  transformES2019,
  transformES2020,
  transformES2021,
  transformESDecorators,
  transformESNext,
  transformGenerators,
  transformImpliedNodeFormatDependentModule,
  transformJsx,
  transformLegacyDecorators,
  transformModule,
  transformNamedEvaluation,
  transformNodes,
  transformSystemModule,
  transformTypeScript,
  transpile,
  transpileDeclaration,
  transpileModule,
  transpileOptionValueCompilerOptions,
  tryAddToSet,
  tryAndIgnoreErrors,
  tryCast,
  tryDirectoryExists,
  tryExtractTSExtension,
  tryFileExists,
  tryGetClassExtendingExpressionWithTypeArguments,
  tryGetClassImplementingOrExtendingExpressionWithTypeArguments,
  tryGetDirectories,
  tryGetExtensionFromPath,
  tryGetImportFromModuleSpecifier,
  tryGetJSDocSatisfiesTypeNode,
  tryGetModuleNameFromFile,
  tryGetModuleSpecifierFromDeclaration,
  tryGetNativePerformanceHooks,
  tryGetPropertyAccessOrIdentifierToString,
  tryGetPropertyNameOfBindingOrAssignmentElement,
  tryGetSourceMappingURL,
  tryGetTextOfPropertyName,
  tryParseJson,
  tryParsePattern,
  tryParsePatterns,
  tryParseRawSourceMap,
  tryReadDirectory,
  tryReadFile,
  tryRemoveDirectoryPrefix,
  tryRemoveExtension,
  tryRemovePrefix,
  tryRemoveSuffix,
  tscBuildOption,
  typeAcquisitionDeclarations,
  typeAliasNamePart,
  typeDirectiveIsEqualTo,
  typeKeywords,
  typeParameterNamePart,
  typeToDisplayParts,
  unchangedPollThresholds,
  unchangedTextChangeRange,
  unescapeLeadingUnderscores,
  unmangleScopedPackageName,
  unorderedRemoveItem,
  unprefixedNodeCoreModules,
  unreachableCodeIsError,
  unsetNodeChildren,
  unusedLabelIsError,
  unwrapInnermostStatementOfLabel,
  unwrapParenthesizedExpression,
  updateErrorForNoInputFiles,
  updateLanguageServiceSourceFile,
  updateMissingFilePathsWatch,
  updateResolutionField,
  updateSharedExtendedConfigFileWatcher,
  updateSourceFile,
  updateWatchingWildcardDirectories,
  usingSingleLineStringWriter,
  utf16EncodeAsString,
  validateLocaleAndSetLanguage,
  version,
  versionMajorMinor,
  visitArray,
  visitCommaListElements,
  visitEachChild,
  visitFunctionBody,
  visitIterationBody,
  visitLexicalEnvironment,
  visitNode,
  visitNodes,
  visitParameterList,
  walkUpBindingElementsAndPatterns,
  walkUpOuterExpressions,
  walkUpParenthesizedExpressions,
  walkUpParenthesizedTypes,
  walkUpParenthesizedTypesAndGetParentAndChild,
  whitespaceOrMapCommentRegExp,
  writeCommentRange,
  writeFile,
  writeFileEnsuringDirectories,
  zipWith
});
})({ get exports() { return ts; }, set exports(v) { ts = v; if (typeof module !== "undefined" && module.exports) { module.exports = v; } } })
//# sourceMappingURL=typescript.js.map
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         //# 1 ".xml2js.eobjs/jsoo/xml2js.bc.runtime.js"
// Generated by js_of_ocaml
//# buildInfo:effects=false, kind=unknown, use-js-string=true, version=5.2.0+git-0e29f0e-dirty
//# 3 ".xml2js.eobjs/jsoo/xml2js.bc.runtime.js"

//# 7 ".xml2js.eobjs/jsoo/xml2js.bc.runtime.js"
(function
  (Object){
   typeof globalThis !== "object"
   &&
    (this
      ? get()
      : (Object.defineProperty
         (Object.prototype, "_T_", {configurable: true, get: get}),
        _T_));
   function get(){
    var global = this || self;
    global.globalThis = global;
    delete Object.prototype._T_;
   }
  }
  (Object));
(function(globalThis){
   "use strict";
   function caml_int64_is_zero(x){return + x.isZero();}
   function caml_str_repeat(n, s){
    if(n == 0) return "";
    if(s.repeat) return s.repeat(n);
    var r = "", l = 0;
    for(;;){
     if(n & 1) r += s;
     n >>= 1;
     if(n == 0) return r;
     s += s;
     l++;
     if(l == 9) s.slice(0, 1);
    }
   }
   var caml_int64_offset = Math.pow(2, - 24);
   function caml_raise_constant(tag){throw tag;}
   var caml_global_data = [0];
   function caml_raise_zero_divide(){
    caml_raise_constant(caml_global_data.Division_by_zero);
   }
   function MlInt64(lo, mi, hi){
    this.lo = lo & 0xffffff;
    this.mi = mi & 0xffffff;
    this.hi = hi & 0xffff;
   }
   MlInt64.prototype.caml_custom = "_j";
   MlInt64.prototype.copy =
    function(){return new MlInt64(this.lo, this.mi, this.hi);};
   MlInt64.prototype.ucompare =
    function(x){
     if(this.hi > x.hi) return 1;
     if(this.hi < x.hi) return - 1;
     if(this.mi > x.mi) return 1;
     if(this.mi < x.mi) return - 1;
     if(this.lo > x.lo) return 1;
     if(this.lo < x.lo) return - 1;
     return 0;
    };
   MlInt64.prototype.compare =
    function(x){
     var hi = this.hi << 16, xhi = x.hi << 16;
     if(hi > xhi) return 1;
     if(hi < xhi) return - 1;
     if(this.mi > x.mi) return 1;
     if(this.mi < x.mi) return - 1;
     if(this.lo > x.lo) return 1;
     if(this.lo < x.lo) return - 1;
     return 0;
    };
   MlInt64.prototype.neg =
    function(){
     var
      lo = - this.lo,
      mi = - this.mi + (lo >> 24),
      hi = - this.hi + (mi >> 24);
     return new MlInt64(lo, mi, hi);
    };
   MlInt64.prototype.add =
    function(x){
     var
      lo = this.lo + x.lo,
      mi = this.mi + x.mi + (lo >> 24),
      hi = this.hi + x.hi + (mi >> 24);
     return new MlInt64(lo, mi, hi);
    };
   MlInt64.prototype.sub =
    function(x){
     var
      lo = this.lo - x.lo,
      mi = this.mi - x.mi + (lo >> 24),
      hi = this.hi - x.hi + (mi >> 24);
     return new MlInt64(lo, mi, hi);
    };
   MlInt64.prototype.mul =
    function(x){
     var
      lo = this.lo * x.lo,
      mi = (lo * caml_int64_offset | 0) + this.mi * x.lo + this.lo * x.mi,
      hi =
        (mi * caml_int64_offset | 0) + this.hi * x.lo + this.mi * x.mi
        + this.lo * x.hi;
     return new MlInt64(lo, mi, hi);
    };
   MlInt64.prototype.isZero =
    function(){return (this.lo | this.mi | this.hi) == 0;};
   MlInt64.prototype.isNeg = function(){return this.hi << 16 < 0;};
   MlInt64.prototype.and =
    function(x){
     return new MlInt64(this.lo & x.lo, this.mi & x.mi, this.hi & x.hi);
    };
   MlInt64.prototype.or =
    function(x){
     return new MlInt64(this.lo | x.lo, this.mi | x.mi, this.hi | x.hi);
    };
   MlInt64.prototype.xor =
    function(x){
     return new MlInt64(this.lo ^ x.lo, this.mi ^ x.mi, this.hi ^ x.hi);
    };
   MlInt64.prototype.shift_left =
    function(s){
     s = s & 63;
     if(s == 0) return this;
     if(s < 24)
      return new
              MlInt64
              (this.lo << s,
               this.mi << s | this.lo >> 24 - s,
               this.hi << s | this.mi >> 24 - s);
     if(s < 48)
      return new
              MlInt64
              (0, this.lo << s - 24, this.mi << s - 24 | this.lo >> 48 - s);
     return new MlInt64(0, 0, this.lo << s - 48);
    };
   MlInt64.prototype.shift_right_unsigned =
    function(s){
     s = s & 63;
     if(s == 0) return this;
     if(s < 24)
      return new
              MlInt64
              (this.lo >> s | this.mi << 24 - s,
               this.mi >> s | this.hi << 24 - s,
               this.hi >> s);
     if(s < 48)
      return new
              MlInt64
              (this.mi >> s - 24 | this.hi << 48 - s, this.hi >> s - 24, 0);
     return new MlInt64(this.hi >> s - 48, 0, 0);
    };
   MlInt64.prototype.shift_right =
    function(s){
     s = s & 63;
     if(s == 0) return this;
     var h = this.hi << 16 >> 16;
     if(s < 24)
      return new
              MlInt64
              (this.lo >> s | this.mi << 24 - s,
               this.mi >> s | h << 24 - s,
               this.hi << 16 >> s >>> 16);
     var sign = this.hi << 16 >> 31;
     if(s < 48)
      return new
              MlInt64
              (this.mi >> s - 24 | this.hi << 48 - s,
               this.hi << 16 >> s - 24 >> 16,
               sign & 0xffff);
     return new MlInt64(this.hi << 16 >> s - 32, sign, sign);
    };
   MlInt64.prototype.lsl1 =
    function(){
     this.hi = this.hi << 1 | this.mi >> 23;
     this.mi = (this.mi << 1 | this.lo >> 23) & 0xffffff;
     this.lo = this.lo << 1 & 0xffffff;
    };
   MlInt64.prototype.lsr1 =
    function(){
     this.lo = (this.lo >>> 1 | this.mi << 23) & 0xffffff;
     this.mi = (this.mi >>> 1 | this.hi << 23) & 0xffffff;
     this.hi = this.hi >>> 1;
    };
   MlInt64.prototype.udivmod =
    function(x){
     var
      offset = 0,
      modulus = this.copy(),
      divisor = x.copy(),
      quotient = new MlInt64(0, 0, 0);
     while(modulus.ucompare(divisor) > 0){offset++; divisor.lsl1();}
     while(offset >= 0){
      offset--;
      quotient.lsl1();
      if(modulus.ucompare(divisor) >= 0){
       quotient.lo++;
       modulus = modulus.sub(divisor);
      }
      divisor.lsr1();
     }
     return {quotient: quotient, modulus: modulus};
    };
   MlInt64.prototype.div =
    function(y){
     var x = this;
     if(y.isZero()) caml_raise_zero_divide();
     var sign = x.hi ^ y.hi;
     if(x.hi & 0x8000) x = x.neg();
     if(y.hi & 0x8000) y = y.neg();
     var q = x.udivmod(y).quotient;
     if(sign & 0x8000) q = q.neg();
     return q;
    };
   MlInt64.prototype.mod =
    function(y){
     var x = this;
     if(y.isZero()) caml_raise_zero_divide();
     var sign = x.hi;
     if(x.hi & 0x8000) x = x.neg();
     if(y.hi & 0x8000) y = y.neg();
     var r = x.udivmod(y).modulus;
     if(sign & 0x8000) r = r.neg();
     return r;
    };
   MlInt64.prototype.toInt = function(){return this.lo | this.mi << 24;};
   MlInt64.prototype.toFloat =
    function(){
     return (this.hi << 16) * Math.pow(2, 32) + this.mi * Math.pow(2, 24)
            + this.lo;
    };
   MlInt64.prototype.toArray =
    function(){
     return [this.hi >> 8,
             this.hi & 0xff,
             this.mi >> 16,
             this.mi >> 8 & 0xff,
             this.mi & 0xff,
             this.lo >> 16,
             this.lo >> 8 & 0xff,
             this.lo & 0xff];
    };
   MlInt64.prototype.lo32 =
    function(){return this.lo | (this.mi & 0xff) << 24;};
   MlInt64.prototype.hi32 =
    function(){return this.mi >>> 8 & 0xffff | this.hi << 16;};
   function caml_int64_of_int32(x){
    return new MlInt64(x & 0xffffff, x >> 24 & 0xffffff, x >> 31 & 0xffff);
   }
   function caml_int64_to_int32(x){return x.toInt();}
   function caml_int64_is_negative(x){return + x.isNeg();}
   function caml_int64_neg(x){return x.neg();}
   function caml_jsbytes_of_string(x){return x;}
   function jsoo_sys_getenv(n){
    var process = globalThis.process;
    if(process && process.env && process.env[n] != undefined)
     return process.env[n];
    if(globalThis.jsoo_static_env && globalThis.jsoo_static_env[n])
     return globalThis.jsoo_static_env[n];
   }
   var caml_record_backtrace_flag = 0;
   (function(){
      var r = jsoo_sys_getenv("OCAMLRUNPARAM");
      if(r !== undefined){
       var l = r.split(",");
       for(var i = 0; i < l.length; i++)
        if(l[i] == "b"){
         caml_record_backtrace_flag = 1;
         break;
        }
        else if(l[i].startsWith("b="))
         caml_record_backtrace_flag = + l[i].slice(2);
        else
         continue;
      }
     }
     ());
   function caml_exn_with_js_backtrace(exn, force){
    if(! exn.js_error || force || exn[0] == 248)
     exn.js_error = new globalThis.Error("Js exception containing backtrace");
    return exn;
   }
   function caml_maybe_attach_backtrace(exn, force){
    return caml_record_backtrace_flag
            ? caml_exn_with_js_backtrace(exn, force)
            : exn;
   }
   function caml_raise_with_arg(tag, arg){
    throw caml_maybe_attach_backtrace([0, tag, arg]);
   }
   function caml_string_of_jsbytes(x){return x;}
   function caml_raise_with_string(tag, msg){
    caml_raise_with_arg(tag, caml_string_of_jsbytes(msg));
   }
   function caml_invalid_argument(msg){
    caml_raise_with_string(caml_global_data.Invalid_argument, msg);
   }
   function caml_parse_format(fmt){
    fmt = caml_jsbytes_of_string(fmt);
    var len = fmt.length;
    if(len > 31) caml_invalid_argument("format_int: format too long");
    var
     f =
       {justify: "+",
        signstyle: "-",
        filler: " ",
        alternate: false,
        base: 0,
        signedconv: false,
        width: 0,
        uppercase: false,
        sign: 1,
        prec: - 1,
        conv: "f"};
    for(var i = 0; i < len; i++){
     var c = fmt.charAt(i);
     switch(c){
       case "-":
        f.justify = "-"; break;
       case "+":
       case " ":
        f.signstyle = c; break;
       case "0":
        f.filler = "0"; break;
       case "#":
        f.alternate = true; break;
       case "1":
       case "2":
       case "3":
       case "4":
       case "5":
       case "6":
       case "7":
       case "8":
       case "9":
        f.width = 0;
        while(c = fmt.charCodeAt(i) - 48, c >= 0 && c <= 9){f.width = f.width * 10 + c; i++;}
        i--;
        break;
       case ".":
        f.prec = 0;
        i++;
        while(c = fmt.charCodeAt(i) - 48, c >= 0 && c <= 9){f.prec = f.prec * 10 + c; i++;}
        i--;
       case "d":
       case "i":
        f.signedconv = true;
       case "u":
        f.base = 10; break;
       case "x":
        f.base = 16; break;
       case "X":
        f.base = 16; f.uppercase = true; break;
       case "o":
        f.base = 8; break;
       case "e":
       case "f":
       case "g":
        f.signedconv = true; f.conv = c; break;
       case "E":
       case "F":
       case "G":
        f.signedconv = true;
        f.uppercase = true;
        f.conv = c.toLowerCase();
        break;
     }
    }
    return f;
   }
   function caml_finish_formatting(f, rawbuffer){
    if(f.uppercase) rawbuffer = rawbuffer.toUpperCase();
    var len = rawbuffer.length;
    if(f.signedconv && (f.sign < 0 || f.signstyle != "-")) len++;
    if(f.alternate){if(f.base == 8) len += 1; if(f.base == 16) len += 2;}
    var buffer = "";
    if(f.justify == "+" && f.filler == " ")
     for(var i = len; i < f.width; i++) buffer += " ";
    if(f.signedconv)
     if(f.sign < 0)
      buffer += "-";
     else if(f.signstyle != "-") buffer += f.signstyle;
    if(f.alternate && f.base == 8) buffer += "0";
    if(f.alternate && f.base == 16) buffer += f.uppercase ? "0X" : "0x";
    if(f.justify == "+" && f.filler == "0")
     for(var i = len; i < f.width; i++) buffer += "0";
    buffer += rawbuffer;
    if(f.justify == "-") for(var i = len; i < f.width; i++) buffer += " ";
    return caml_string_of_jsbytes(buffer);
   }
   function caml_int64_format(fmt, x){
    var f = caml_parse_format(fmt);
    if(f.signedconv && caml_int64_is_negative(x)){f.sign = - 1; x = caml_int64_neg(x);}
    var
     buffer = "",
     wbase = caml_int64_of_int32(f.base),
     cvtbl = "0123456789abcdef";
    do{
     var p = x.udivmod(wbase);
     x = p.quotient;
     buffer = cvtbl.charAt(caml_int64_to_int32(p.modulus)) + buffer;
    }
    while
     (! caml_int64_is_zero(x));
    if(f.prec >= 0){
     f.filler = " ";
     var n = f.prec - buffer.length;
     if(n > 0) buffer = caml_str_repeat(n, "0") + buffer;
    }
    return caml_finish_formatting(f, buffer);
   }
   function caml_expm1_float(x){return Math.expm1(x);}
   function caml_ml_condition_broadcast(t){return 0;}
   function jsoo_is_ascii(s){
    if(s.length < 24){
     for(var i = 0; i < s.length; i++) if(s.charCodeAt(i) > 127) return false;
     return true;
    }
    else
     return ! /[^\x00-\x7f]/.test(s);
   }
   function caml_utf16_of_utf8(s){
    for(var b = "", t = "", c, c1, c2, v, i = 0, l = s.length; i < l; i++){
     c1 = s.charCodeAt(i);
     if(c1 < 0x80){
      for(var j = i + 1; j < l && (c1 = s.charCodeAt(j)) < 0x80; j++) ;
      if(j - i > 512){
       t.substr(0, 1);
       b += t;
       t = "";
       b += s.slice(i, j);
      }
      else
       t += s.slice(i, j);
      if(j == l) break;
      i = j;
     }
     v = 1;
     if(++i < l && ((c2 = s.charCodeAt(i)) & - 64) == 128){
      c = c2 + (c1 << 6);
      if(c1 < 0xe0){
       v = c - 0x3080;
       if(v < 0x80) v = 1;
      }
      else{
       v = 2;
       if(++i < l && ((c2 = s.charCodeAt(i)) & - 64) == 128){
        c = c2 + (c << 6);
        if(c1 < 0xf0){
         v = c - 0xe2080;
         if(v < 0x800 || v >= 0xd7ff && v < 0xe000) v = 2;
        }
        else{
         v = 3;
         if(++i < l && ((c2 = s.charCodeAt(i)) & - 64) == 128 && c1 < 0xf5){
          v = c2 - 0x3c82080 + (c << 6);
          if(v < 0x10000 || v > 0x10ffff) v = 3;
         }
        }
       }
      }
     }
     if(v < 4){
      i -= v;
      t += "\ufffd";
     }
     else if(v > 0xffff)
      t += String.fromCharCode(0xd7c0 + (v >> 10), 0xdc00 + (v & 0x3FF));
     else
      t += String.fromCharCode(v);
     if(t.length > 1024){t.substr(0, 1); b += t; t = "";}
    }
    return b + t;
   }
   function caml_jsstring_of_string(s){
    if(jsoo_is_ascii(s)) return s;
    return caml_utf16_of_utf8(s);
   }
   function fs_node_supported(){
    return typeof globalThis.process !== "undefined"
           && typeof globalThis.process.versions !== "undefined"
           && typeof globalThis.process.versions.node !== "undefined";
   }
   function make_path_is_absolute(){
    function posix(path){
     if(path.charAt(0) === "/") return ["", path.substring(1)];
     return;
    }
    function win32(path){
     var
      splitDeviceRe =
        /^([a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?([\\/])?([\s\S]*?)$/,
      result = splitDeviceRe.exec(path),
      device = result[1] || "",
      isUnc = Boolean(device && device.charAt(1) !== ":");
     if(Boolean(result[2] || isUnc)){
      var root = result[1] || "", sep = result[2] || "";
      return [root, path.substring(root.length + sep.length)];
     }
     return;
    }
    return fs_node_supported() && globalThis.process
            && globalThis.process.platform
            ? globalThis.process.platform === "win32" ? win32 : posix
            : posix;
   }
   var path_is_absolute = make_path_is_absolute();
   function caml_trailing_slash(name){
    return name.slice(- 1) !== "/" ? name + "/" : name;
   }
   if(fs_node_supported() && globalThis.process && globalThis.process.cwd)
    var caml_current_dir = globalThis.process.cwd().replace(/\\/g, "/");
   else
    var caml_current_dir = "/static";
   caml_current_dir = caml_trailing_slash(caml_current_dir);
   function caml_make_path(name){
    name = caml_jsstring_of_string(name);
    if(! path_is_absolute(name)) name = caml_current_dir + name;
    var
     comp0 = path_is_absolute(name),
     comp = comp0[1].split("/"),
     ncomp = [];
    for(var i = 0; i < comp.length; i++)
     switch(comp[i]){
       case "..":
        if(ncomp.length > 1) ncomp.pop(); break;
       case ".": break;
       case "": break;
       default: ncomp.push(comp[i]); break;
     }
    ncomp.unshift(comp0[0]);
    ncomp.orig = name;
    return ncomp;
   }
   function caml_utf8_of_utf16(s){
    for(var b = "", t = b, c, d, i = 0, l = s.length; i < l; i++){
     c = s.charCodeAt(i);
     if(c < 0x80){
      for(var j = i + 1; j < l && (c = s.charCodeAt(j)) < 0x80; j++) ;
      if(j - i > 512){
       t.substr(0, 1);
       b += t;
       t = "";
       b += s.slice(i, j);
      }
      else
       t += s.slice(i, j);
      if(j == l) break;
      i = j;
     }
     if(c < 0x800){
      t += String.fromCharCode(0xc0 | c >> 6);
      t += String.fromCharCode(0x80 | c & 0x3f);
     }
     else if(c < 0xd800 || c >= 0xdfff)
      t +=
       String.fromCharCode
        (0xe0 | c >> 12, 0x80 | c >> 6 & 0x3f, 0x80 | c & 0x3f);
     else if
      (c >= 0xdbff || i + 1 == l || (d = s.charCodeAt(i + 1)) < 0xdc00
       || d > 0xdfff)
      t += "\xef\xbf\xbd";
     else{
      i++;
      c = (c << 10) + d - 0x35fdc00;
      t +=
       String.fromCharCode
        (0xf0 | c >> 18,
         0x80 | c >> 12 & 0x3f,
         0x80 | c >> 6 & 0x3f,
         0x80 | c & 0x3f);
     }
     if(t.length > 1024){t.substr(0, 1); b += t; t = "";}
    }
    return b + t;
   }
   function caml_string_of_jsstring(s){
    return jsoo_is_ascii(s)
            ? caml_string_of_jsbytes(s)
            : caml_string_of_jsbytes(caml_utf8_of_utf16(s));
   }
   var
    unix_error =
      ["E2BIG",
       "EACCES",
       "EAGAIN",
       "EBADF",
       "EBUSY",
       "ECHILD",
       "EDEADLK",
       "EDOM",
       "EEXIST",
       "EFAULT",
       "EFBIG",
       "EINTR",
       "EINVAL",
       "EIO",
       "EISDIR",
       "EMFILE",
       "EMLINK",
       "ENAMETOOLONG",
       "ENFILE",
       "ENODEV",
       "ENOENT",
       "ENOEXEC",
       "ENOLCK",
       "ENOMEM",
       "ENOSPC",
       "ENOSYS",
       "ENOTDIR",
       "ENOTEMPTY",
       "ENOTTY",
       "ENXIO",
       "EPERM",
       "EPIPE",
       "ERANGE",
       "EROFS",
       "ESPIPE",
       "ESRCH",
       "EXDEV",
       "EWOULDBLOCK",
       "EINPROGRESS",
       "EALREADY",
       "ENOTSOCK",
       "EDESTADDRREQ",
       "EMSGSIZE",
       "EPROTOTYPE",
       "ENOPROTOOPT",
       "EPROTONOSUPPORT",
       "ESOCKTNOSUPPORT",
       "EOPNOTSUPP",
       "EPFNOSUPPORT",
       "EAFNOSUPPORT",
       "EADDRINUSE",
       "EADDRNOTAVAIL",
       "ENETDOWN",
       "ENETUNREACH",
       "ENETRESET",
       "ECONNABORTED",
       "ECONNRESET",
       "ENOBUFS",
       "EISCONN",
       "ENOTCONN",
       "ESHUTDOWN",
       "ETOOMANYREFS",
       "ETIMEDOUT",
       "ECONNREFUSED",
       "EHOSTDOWN",
       "EHOSTUNREACH",
       "ELOOP",
       "EOVERFLOW"];
   function make_unix_err_args(code, syscall, path, errno){
    var variant = unix_error.indexOf(code);
    if(variant < 0){if(errno == null) errno = - 9999; variant = [0, errno];}
    var
     args =
       [variant,
        caml_string_of_jsstring(syscall || ""),
        caml_string_of_jsstring(path || "")];
    return args;
   }
   var caml_named_values = {};
   function caml_named_value(nm){return caml_named_values[nm];}
   function caml_raise_with_args(tag, args){
    throw caml_maybe_attach_backtrace([0, tag].concat(args));
   }
   function caml_subarray_to_jsbytes(a, i, len){
    var f = String.fromCharCode;
    if(i == 0 && len <= 4096 && len == a.length) return f.apply(null, a);
    var s = "";
    for(; 0 < len; i += 1024, len -= 1024)
     s += f.apply(null, a.slice(i, i + Math.min(len, 1024)));
    return s;
   }
   function caml_convert_string_to_bytes(s){
    if(s.t == 2)
     s.c += caml_str_repeat(s.l - s.c.length, "\0");
    else
     s.c = caml_subarray_to_jsbytes(s.c, 0, s.c.length);
    s.t = 0;
   }
   function MlBytes(tag, contents, length){
    this.t = tag;
    this.c = contents;
    this.l = length;
   }
   MlBytes.prototype.toString =
    function(){
     switch(this.t){
       case 9:
        return this.c;
       default: caml_convert_string_to_bytes(this);
       case 0:
        if(jsoo_is_ascii(this.c)){this.t = 9; return this.c;} this.t = 8;
       case 8:
        return this.c;
     }
    };
   MlBytes.prototype.toUtf16 =
    function(){
     var r = this.toString();
     if(this.t == 9) return r;
     return caml_utf16_of_utf8(r);
    };
   MlBytes.prototype.slice =
    function(){
     var content = this.t == 4 ? this.c.slice() : this.c;
     return new MlBytes(this.t, content, this.l);
    };
   function caml_is_ml_bytes(s){return s instanceof MlBytes;}
   function caml_is_ml_string(s){
    return typeof s === "string" && ! /[^\x00-\xff]/.test(s);
   }
   function caml_bytes_of_array(a){
    if(! (a instanceof Uint8Array)) a = new Uint8Array(a);
    return new MlBytes(4, a, a.length);
   }
   function caml_bytes_of_jsbytes(s){return new MlBytes(0, s, s.length);}
   function caml_bytes_of_string(s){
    return caml_bytes_of_jsbytes(caml_jsbytes_of_string(s));
   }
   function caml_raise_sys_error(msg){
    caml_raise_with_string(caml_global_data.Sys_error, msg);
   }
   function caml_raise_no_such_file(name){
    caml_raise_sys_error(name + ": No such file or directory");
   }
   function caml_convert_bytes_to_array(s){
    var a = new Uint8Array(s.l), b = s.c, l = b.length, i = 0;
    for(; i < l; i++) a[i] = b.charCodeAt(i);
    for(l = s.l; i < l; i++) a[i] = 0;
    s.c = a;
    s.t = 4;
    return a;
   }
   function caml_uint8_array_of_bytes(s){
    if(s.t != 4) caml_convert_bytes_to_array(s);
    return s.c;
   }
   function caml_create_bytes(len){
    if(len < 0) caml_invalid_argument("Bytes.create");
    return new MlBytes(len ? 2 : 9, "", len);
   }
   function caml_ml_bytes_length(s){return s.l;}
   function caml_blit_bytes(s1, i1, s2, i2, len){
    if(len == 0) return 0;
    if(i2 == 0 && (len >= s2.l || s2.t == 2 && len >= s2.c.length)){
     s2.c =
      s1.t == 4
       ? caml_subarray_to_jsbytes(s1.c, i1, len)
       : i1 == 0 && s1.c.length == len ? s1.c : s1.c.substr(i1, len);
     s2.t = s2.c.length == s2.l ? 0 : 2;
    }
    else if(s2.t == 2 && i2 == s2.c.length){
     s2.c +=
      s1.t == 4
       ? caml_subarray_to_jsbytes(s1.c, i1, len)
       : i1 == 0 && s1.c.length == len ? s1.c : s1.c.substr(i1, len);
     s2.t = s2.c.length == s2.l ? 0 : 2;
    }
    else{
     if(s2.t != 4) caml_convert_bytes_to_array(s2);
     var c1 = s1.c, c2 = s2.c;
     if(s1.t == 4)
      if(i2 <= i1)
       for(var i = 0; i < len; i++) c2[i2 + i] = c1[i1 + i];
      else
       for(var i = len - 1; i >= 0; i--) c2[i2 + i] = c1[i1 + i];
     else{
      var l = Math.min(len, c1.length - i1);
      for(var i = 0; i < l; i++) c2[i2 + i] = c1.charCodeAt(i1 + i);
      for(; i < len; i++) c2[i2 + i] = 0;
     }
    }
    return 0;
   }
   function MlFile(){}
   function MlFakeFile(content){this.data = content;}
   MlFakeFile.prototype = new MlFile();
   MlFakeFile.prototype.constructor = MlFakeFile;
   MlFakeFile.prototype.truncate =
    function(len){
     var old = this.data;
     this.data = caml_create_bytes(len | 0);
     caml_blit_bytes(old, 0, this.data, 0, len);
    };
   MlFakeFile.prototype.length =
    function(){return caml_ml_bytes_length(this.data);};
   MlFakeFile.prototype.write =
    function(offset, buf, pos, len){
     var clen = this.length();
     if(offset + len >= clen){
      var new_str = caml_create_bytes(offset + len), old_data = this.data;
      this.data = new_str;
      caml_blit_bytes(old_data, 0, this.data, 0, clen);
     }
     caml_blit_bytes(caml_bytes_of_array(buf), pos, this.data, offset, len);
     return 0;
    };
   MlFakeFile.prototype.read =
    function(offset, buf, pos, len){
     var clen = this.length();
     if(offset + len >= clen) len = clen - offset;
     if(len){
      var data = caml_create_bytes(len | 0);
      caml_blit_bytes(this.data, offset, data, 0, len);
      buf.set(caml_uint8_array_of_bytes(data), pos);
     }
     return len;
    };
   function MlFakeFd(name, file, flags){
    this.file = file;
    this.name = name;
    this.flags = flags;
   }
   MlFakeFd.prototype.err_closed =
    function(){
     caml_raise_sys_error(this.name + ": file descriptor already closed");
    };
   MlFakeFd.prototype.length =
    function(){if(this.file) return this.file.length(); this.err_closed();};
   MlFakeFd.prototype.write =
    function(offset, buf, pos, len){
     if(this.file) return this.file.write(offset, buf, pos, len);
     this.err_closed();
    };
   MlFakeFd.prototype.read =
    function(offset, buf, pos, len){
     if(this.file) return this.file.read(offset, buf, pos, len);
     this.err_closed();
    };
   MlFakeFd.prototype.close = function(){this.file = undefined;};
   function MlFakeDevice(root, f){
    this.content = {};
    this.root = root;
    this.lookupFun = f;
   }
   MlFakeDevice.prototype.nm = function(name){return this.root + name;};
   MlFakeDevice.prototype.create_dir_if_needed =
    function(name){
     var comp = name.split("/"), res = "";
     for(var i = 0; i < comp.length - 1; i++){
      res += comp[i] + "/";
      if(this.content[res]) continue;
      this.content[res] = Symbol("directory");
     }
    };
   MlFakeDevice.prototype.slash =
    function(name){return /\/$/.test(name) ? name : name + "/";};
   MlFakeDevice.prototype.lookup =
    function(name){
     if(! this.content[name] && this.lookupFun){
      var
       res =
         this.lookupFun
          (caml_string_of_jsbytes(this.root), caml_string_of_jsbytes(name));
      if(res !== 0){
       this.create_dir_if_needed(name);
       this.content[name] = new MlFakeFile(caml_bytes_of_string(res[1]));
      }
     }
    };
   MlFakeDevice.prototype.exists =
    function(name){
     if(name == "") return 1;
     var name_slash = this.slash(name);
     if(this.content[name_slash]) return 1;
     this.lookup(name);
     return this.content[name] ? 1 : 0;
    };
   MlFakeDevice.prototype.isFile =
    function(name){return this.exists(name) && ! this.is_dir(name) ? 1 : 0;};
   MlFakeDevice.prototype.mkdir =
    function(name, mode, raise_unix){
     var unix_error = raise_unix && caml_named_value("Unix.Unix_error");
     if(this.exists(name))
      if(unix_error)
       caml_raise_with_args
        (unix_error, make_unix_err_args("EEXIST", "mkdir", this.nm(name)));
      else
       caml_raise_sys_error(name + ": File exists");
     var parent = /^(.*)\/[^/]+/.exec(name);
     parent = parent && parent[1] || "";
     if(! this.exists(parent))
      if(unix_error)
       caml_raise_with_args
        (unix_error, make_unix_err_args("ENOENT", "mkdir", this.nm(parent)));
      else
       caml_raise_sys_error(parent + ": No such file or directory");
     if(! this.is_dir(parent))
      if(unix_error)
       caml_raise_with_args
        (unix_error, make_unix_err_args("ENOTDIR", "mkdir", this.nm(parent)));
      else
       caml_raise_sys_error(parent + ": Not a directory");
     this.create_dir_if_needed(this.slash(name));
    };
   MlFakeDevice.prototype.rmdir =
    function(name, raise_unix){
     var
      unix_error = raise_unix && caml_named_value("Unix.Unix_error"),
      name_slash = name == "" ? "" : this.slash(name),
      r = new RegExp("^" + name_slash + "([^/]+)");
     if(! this.exists(name))
      if(unix_error)
       caml_raise_with_args
        (unix_error, make_unix_err_args("ENOENT", "rmdir", this.nm(name)));
      else
       caml_raise_sys_error(name + ": No such file or directory");
     if(! this.is_dir(name))
      if(unix_error)
       caml_raise_with_args
        (unix_error, make_unix_err_args("ENOTDIR", "rmdir", this.nm(name)));
      else
       caml_raise_sys_error(name + ": Not a directory");
     for(var n in this.content)
      if(n.match(r))
       if(unix_error)
        caml_raise_with_args
         (unix_error, make_unix_err_args("ENOTEMPTY", "rmdir", this.nm(name)));
       else
        caml_raise_sys_error(this.nm(name) + ": Directory not empty");
     delete this.content[name_slash];
    };
   MlFakeDevice.prototype.readdir =
    function(name){
     var name_slash = name == "" ? "" : this.slash(name);
     if(! this.exists(name))
      caml_raise_sys_error(name + ": No such file or directory");
     if(! this.is_dir(name)) caml_raise_sys_error(name + ": Not a directory");
     var r = new RegExp("^" + name_slash + "([^/]+)"), seen = {}, a = [];
     for(var n in this.content){
      var m = n.match(r);
      if(m && ! seen[m[1]]){seen[m[1]] = true; a.push(m[1]);}
     }
     return a;
    };
   MlFakeDevice.prototype.opendir =
    function(name, raise_unix){
     var
      unix_error = raise_unix && caml_named_value("Unix.Unix_error"),
      a = this.readdir(name),
      c = false,
      i = 0;
     return {readSync:
             function(){
              if(c)
               if(unix_error)
                caml_raise_with_args
                 (unix_error,
                  make_unix_err_args("EBADF", "closedir", this.nm(name)));
               else
                caml_raise_sys_error(name + ": closedir failed");
              if(i == a.length) return null;
              var entry = a[i];
              i++;
              return {name: entry};
             },
             closeSync:
             function(){
              if(c)
               if(unix_error)
                caml_raise_with_args
                 (unix_error,
                  make_unix_err_args("EBADF", "closedir", this.nm(name)));
               else
                caml_raise_sys_error(name + ": closedir failed");
              c = true;
              a = [];
             }};
    };
   MlFakeDevice.prototype.is_dir =
    function(name){
     if(name == "") return true;
     var name_slash = this.slash(name);
     return this.content[name_slash] ? 1 : 0;
    };
   MlFakeDevice.prototype.unlink =
    function(name){
     var ok = this.content[name] ? true : false;
     delete this.content[name];
     return ok;
    };
   MlFakeDevice.prototype.open =
    function(name, f){
     var file;
     if(f.rdonly && f.wronly)
      caml_raise_sys_error
       (this.nm(name)
        + " : flags Open_rdonly and Open_wronly are not compatible");
     if(f.text && f.binary)
      caml_raise_sys_error
       (this.nm(name)
        + " : flags Open_text and Open_binary are not compatible");
     this.lookup(name);
     if(this.content[name]){
      if(this.is_dir(name))
       caml_raise_sys_error(this.nm(name) + " : is a directory");
      if(f.create && f.excl)
       caml_raise_sys_error(this.nm(name) + " : file already exists");
      file = this.content[name];
      if(f.truncate) file.truncate();
     }
     else if(f.create){
      this.create_dir_if_needed(name);
      this.content[name] = new MlFakeFile(caml_create_bytes(0));
      file = this.content[name];
     }
     else
      caml_raise_no_such_file(this.nm(name));
     return new MlFakeFd(this.nm(name), file, f);
    };
   MlFakeDevice.prototype.open =
    function(name, f){
     var file;
     if(f.rdonly && f.wronly)
      caml_raise_sys_error
       (this.nm(name)
        + " : flags Open_rdonly and Open_wronly are not compatible");
     if(f.text && f.binary)
      caml_raise_sys_error
       (this.nm(name)
        + " : flags Open_text and Open_binary are not compatible");
     this.lookup(name);
     if(this.content[name]){
      if(this.is_dir(name))
       caml_raise_sys_error(this.nm(name) + " : is a directory");
      if(f.create && f.excl)
       caml_raise_sys_error(this.nm(name) + " : file already exists");
      file = this.content[name];
      if(f.truncate) file.truncate();
     }
     else if(f.create){
      this.create_dir_if_needed(name);
      this.content[name] = new MlFakeFile(caml_create_bytes(0));
      file = this.content[name];
     }
     else
      caml_raise_no_such_file(this.nm(name));
     return new MlFakeFd(this.nm(name), file, f);
    };
   MlFakeDevice.prototype.register =
    function(name, content){
     var file;
     if(this.content[name])
      caml_raise_sys_error(this.nm(name) + " : file already exists");
     if(caml_is_ml_bytes(content)) file = new MlFakeFile(content);
     if(caml_is_ml_string(content))
      file = new MlFakeFile(caml_bytes_of_string(content));
     else if(content instanceof Array)
      file = new MlFakeFile(caml_bytes_of_array(content));
     else if(typeof content === "string")
      file = new MlFakeFile(caml_bytes_of_jsbytes(content));
     else if(content.toString){
      var
       bytes =
         caml_bytes_of_string(caml_string_of_jsstring(content.toString()));
      file = new MlFakeFile(bytes);
     }
     if(file){
      this.create_dir_if_needed(name);
      this.content[name] = file;
     }
     else
      caml_raise_sys_error
       (this.nm(name) + " : registering file with invalid content type");
    };
   MlFakeDevice.prototype.constructor = MlFakeDevice;
   function caml_ml_string_length(s){return s.length;}
   function caml_string_unsafe_get(s, i){return s.charCodeAt(i);}
   function caml_uint8_array_of_string(s){
    var l = caml_ml_string_length(s), a = new Array(l), i = 0;
    for(; i < l; i++) a[i] = caml_string_unsafe_get(s, i);
    return a;
   }
   function caml_bytes_bound_error(){
    caml_invalid_argument("index out of bounds");
   }
   function caml_bytes_unsafe_set(s, i, c){
    c &= 0xff;
    if(s.t != 4){
     if(i == s.c.length){
      s.c += String.fromCharCode(c);
      if(i + 1 == s.l) s.t = 0;
      return 0;
     }
     caml_convert_bytes_to_array(s);
    }
    s.c[i] = c;
    return 0;
   }
   function caml_bytes_set(s, i, c){
    if(i >>> 0 >= s.l) caml_bytes_bound_error();
    return caml_bytes_unsafe_set(s, i, c);
   }
   function MlNodeFd(fd, flags){
    this.fs = require("fs");
    this.fd = fd;
    this.flags = flags;
   }
   MlNodeFd.prototype = new MlFile();
   MlNodeFd.prototype.constructor = MlNodeFd;
   MlNodeFd.prototype.truncate =
    function(len){
     try{this.fs.ftruncateSync(this.fd, len | 0);}
     catch(err){caml_raise_sys_error(err.toString());}
    };
   MlNodeFd.prototype.length =
    function(){
     try{return this.fs.fstatSync(this.fd).size;}
     catch(err){caml_raise_sys_error(err.toString());}
    };
   MlNodeFd.prototype.write =
    function(offset, buf, buf_offset, len){
     try{
      if(this.flags.isCharacterDevice)
       this.fs.writeSync(this.fd, buf, buf_offset, len);
      else
       this.fs.writeSync(this.fd, buf, buf_offset, len, offset);
     }
     catch(err){caml_raise_sys_error(err.toString());}
     return 0;
    };
   MlNodeFd.prototype.read =
    function(offset, a, buf_offset, len){
     try{
      if(this.flags.isCharacterDevice)
       var read = this.fs.readSync(this.fd, a, buf_offset, len);
      else
       var read = this.fs.readSync(this.fd, a, buf_offset, len, offset);
      return read;
     }
     catch(err){caml_raise_sys_error(err.toString());}
    };
   MlNodeFd.prototype.close =
    function(){
     try{this.fs.closeSync(this.fd); return 0;}
     catch(err){caml_raise_sys_error(err.toString());}
    };
   function MlNodeDevice(root){this.fs = require("fs"); this.root = root;}
   MlNodeDevice.prototype.nm = function(name){return this.root + name;};
   MlNodeDevice.prototype.exists =
    function(name){
     try{return this.fs.existsSync(this.nm(name)) ? 1 : 0;}
     catch(err){return 0;}
    };
   MlNodeDevice.prototype.isFile =
    function(name){
     try{return this.fs.statSync(this.nm(name)).isFile() ? 1 : 0;}
     catch(err){caml_raise_sys_error(err.toString());}
    };
   MlNodeDevice.prototype.mkdir =
    function(name, mode, raise_unix){
     try{this.fs.mkdirSync(this.nm(name), {mode: mode}); return 0;}
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.rmdir =
    function(name, raise_unix){
     try{this.fs.rmdirSync(this.nm(name)); return 0;}
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.readdir =
    function(name, raise_unix){
     try{return this.fs.readdirSync(this.nm(name));}
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.is_dir =
    function(name){
     try{return this.fs.statSync(this.nm(name)).isDirectory() ? 1 : 0;}
     catch(err){caml_raise_sys_error(err.toString());}
    };
   MlNodeDevice.prototype.unlink =
    function(name, raise_unix){
     try{
      var b = this.fs.existsSync(this.nm(name)) ? 1 : 0;
      this.fs.unlinkSync(this.nm(name));
      return b;
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.open =
    function(name, f, raise_unix){
     var consts = require("constants"), res = 0;
     for(var key in f)
      switch(key){
        case "rdonly":
         res |= consts.O_RDONLY; break;
        case "wronly":
         res |= consts.O_WRONLY; break;
        case "append":
         res |= consts.O_WRONLY | consts.O_APPEND; break;
        case "create":
         res |= consts.O_CREAT; break;
        case "truncate":
         res |= consts.O_TRUNC; break;
        case "excl":
         res |= consts.O_EXCL; break;
        case "binary":
         res |= consts.O_BINARY; break;
        case "text":
         res |= consts.O_TEXT; break;
        case "nonblock":
         res |= consts.O_NONBLOCK; break;
      }
     try{
      var
       fd = this.fs.openSync(this.nm(name), res),
       isCharacterDevice =
         this.fs.lstatSync(this.nm(name)).isCharacterDevice();
      f.isCharacterDevice = isCharacterDevice;
      return new MlNodeFd(fd, f);
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.rename =
    function(o, n, raise_unix){
     try{this.fs.renameSync(this.nm(o), this.nm(n));}
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.stat =
    function(name, raise_unix){
     try{
      var js_stats = this.fs.statSync(this.nm(name));
      return this.stats_from_js(js_stats);
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.lstat =
    function(name, raise_unix){
     try{
      var js_stats = this.fs.lstatSync(this.nm(name));
      return this.stats_from_js(js_stats);
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.symlink =
    function(to_dir, target, path, raise_unix){
     try{
      this.fs.symlinkSync
       (this.nm(target), this.nm(path), to_dir ? "dir" : "file");
      return 0;
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.readlink =
    function(name, raise_unix){
     try{
      var link = this.fs.readlinkSync(this.nm(name), "utf8");
      return caml_string_of_jsstring(link);
     }
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.opendir =
    function(name, raise_unix){
     try{return this.fs.opendirSync(this.nm(name));}
     catch(err){this.raise_nodejs_error(err, raise_unix);}
    };
   MlNodeDevice.prototype.raise_nodejs_error =
    function(err, raise_unix){
     var unix_error = caml_named_value("Unix.Unix_error");
     if(raise_unix && unix_error){
      var
       args = make_unix_err_args(err.code, err.syscall, err.path, err.errno);
      caml_raise_with_args(unix_error, args);
     }
     else
      caml_raise_sys_error(err.toString());
    };
   MlNodeDevice.prototype.stats_from_js =
    function(js_stats){
     var file_kind;
     if(js_stats.isFile())
      file_kind = 0;
     else if(js_stats.isDirectory())
      file_kind = 1;
     else if(js_stats.isCharacterDevice())
      file_kind = 2;
     else if(js_stats.isBlockDevice())
      file_kind = 3;
     else if(js_stats.isSymbolicLink())
      file_kind = 4;
     else if(js_stats.isFIFO())
      file_kind = 5;
     else if(js_stats.isSocket()) file_kind = 6;
     return [0,
             js_stats.dev,
             js_stats.ino,
             file_kind,
             js_stats.mode,
             js_stats.nlink,
             js_stats.uid,
             js_stats.gid,
             js_stats.rdev,
             js_stats.size,
             js_stats.atimeMs,
             js_stats.mtimeMs,
             js_stats.ctimeMs];
    };
   MlNodeDevice.prototype.constructor = MlNodeDevice;
   function caml_get_root(path){
    var x = path_is_absolute(path);
    if(! x) return;
    return x[0] + "/";
   }
   function caml_failwith(msg){
    if(! caml_global_data.Failure)
     caml_global_data.Failure = [248, caml_string_of_jsbytes("Failure"), - 3];
    caml_raise_with_string(caml_global_data.Failure, msg);
   }
   var
    caml_root =
      caml_get_root(caml_current_dir)
      || caml_failwith("unable to compute caml_root"),
    jsoo_mount_point = [];
   if(fs_node_supported())
    jsoo_mount_point.push
     ({path: caml_root, device: new MlNodeDevice(caml_root)});
   else
    jsoo_mount_point.push
     ({path: caml_root, device: new MlFakeDevice(caml_root)});
   jsoo_mount_point.push
    ({path: "/static/", device: new MlFakeDevice("/static/")});
   function resolve_fs_device(name){
    var
     path = caml_make_path(name),
     name = path.join("/"),
     name_slash = caml_trailing_slash(name),
     res;
    for(var i = 0; i < jsoo_mount_point.length; i++){
     var m = jsoo_mount_point[i];
     if
      (name_slash.search(m.path) == 0
       && (! res || res.path.length < m.path.length))
      res =
       {path: m.path,
        device: m.device,
        rest: name.substring(m.path.length, name.length)};
    }
    if(! res && fs_node_supported()){
     var root = caml_get_root(name);
     if(root && root.match(/^[a-zA-Z]:\/$/)){
      var m = {path: root, device: new MlNodeDevice(root)};
      jsoo_mount_point.push(m);
      res =
       {path: m.path,
        device: m.device,
        rest: name.substring(m.path.length, name.length)};
     }
    }
    if(res) return res;
    caml_raise_sys_error("no device found for " + name_slash);
   }
   function caml_sys_is_directory(name){
    var root = resolve_fs_device(name), a = root.device.is_dir(root.rest);
    return a ? 1 : 0;
   }
   function caml_raise_not_found(){
    caml_raise_constant(caml_global_data.Not_found);
   }
   function caml_sys_getenv(name){
    var r = jsoo_sys_getenv(caml_jsstring_of_string(name));
    if(r === undefined) caml_raise_not_found();
    return caml_string_of_jsstring(r);
   }
   function shift_right_nat(nat1, ofs1, len1, nat2, ofs2, nbits){
    if(nbits == 0){nat2.data[ofs2] = 0; return 0;}
    var wrap = 0;
    for(var i = len1 - 1; i >= 0; i--){
     var a = nat1.data[ofs1 + i] >>> 0;
     nat1.data[ofs1 + i] = a >>> nbits | wrap;
     wrap = a << 32 - nbits;
    }
    nat2.data[ofs2] = wrap;
    return 0;
   }
   var caml_gr_state;
   function caml_gr_state_get(){
    if(caml_gr_state) return caml_gr_state;
    throw caml_maybe_attach_backtrace
           ([0,
             caml_named_value("Graphics.Graphic_failure"),
             caml_string_of_jsbytes("Not initialized")]);
   }
   function caml_gr_point_color(x, y){
    var
     s = caml_gr_state_get(),
     im = s.context.getImageData(x, s.height - y, 1, 1),
     d = im.data;
    return (d[0] << 16) + (d[1] << 8) + d[2];
   }
   function caml_runtime_events_user_resolve(){return 0;}
   var MlObjectTable;
   if(typeof globalThis.Map === "undefined")
    MlObjectTable =
     function(){
       function NaiveLookup(objs){this.objs = objs;}
       NaiveLookup.prototype.get =
        function(v){
         for(var i = 0; i < this.objs.length; i++)
          if(this.objs[i] === v) return i;
        };
       NaiveLookup.prototype.set = function(){};
       return function(){
        this.objs = [];
        this.lookup = new NaiveLookup(this.objs);};
      }
      ();
   else
    MlObjectTable =
     function(){this.objs = []; this.lookup = new globalThis.Map();};
   MlObjectTable.prototype.store =
    function(v){this.lookup.set(v, this.objs.length); this.objs.push(v);};
   MlObjectTable.prototype.recall =
    function(v){
     var i = this.lookup.get(v);
     return i === undefined ? undefined : this.objs.length - i;
    };
   function caml_sys_rename(o, n){
    var o_root = resolve_fs_device(o), n_root = resolve_fs_device(n);
    if(o_root.device != n_root.device)
     caml_failwith("caml_sys_rename: cannot move file between two filesystem");
    if(! o_root.device.rename)
     caml_failwith("caml_sys_rename: no implemented");
    o_root.device.rename(o_root.rest, n_root.rest);
   }
   function caml_log10_float(x){return Math.log10(x);}
   var caml_runtime_warnings = 0;
   function caml_ml_enable_runtime_warnings(bool){caml_runtime_warnings = bool; return 0;
   }
   function caml_classify_float(x){
    if(isFinite(x)){
     if(Math.abs(x) >= 2.2250738585072014e-308) return 0;
     if(x != 0) return 1;
     return 2;
    }
    return isNaN(x) ? 4 : 3;
   }
   var caml_ml_channels = new Array();
   function caml_refill(chan){
    if(chan.refill != null){
     var str = chan.refill(), str_a = caml_uint8_array_of_string(str);
     if(str_a.length == 0)
      chan.refill = null;
     else{
      if(chan.buffer.length < chan.buffer_max + str_a.length){
       var b = new Uint8Array(chan.buffer_max + str_a.length);
       b.set(chan.buffer);
       chan.buffer = b;
      }
      chan.buffer.set(str_a, chan.buffer_max);
      chan.offset += str_a.length;
      chan.buffer_max += str_a.length;
     }
    }
    else{
     var
      nread =
        chan.file.read
         (chan.offset,
          chan.buffer,
          chan.buffer_max,
          chan.buffer.length - chan.buffer_max);
     chan.offset += nread;
     chan.buffer_max += nread;
    }
   }
   function caml_array_bound_error(){
    caml_invalid_argument("index out of bounds");
   }
   function caml_ml_input_scan_line(chanid){
    var chan = caml_ml_channels[chanid], p = chan.buffer_curr;
    do
     if(p >= chan.buffer_max){
      if(chan.buffer_curr > 0){
       chan.buffer.set(chan.buffer.subarray(chan.buffer_curr), 0);
       p -= chan.buffer_curr;
       chan.buffer_max -= chan.buffer_curr;
       chan.buffer_curr = 0;
      }
      if(chan.buffer_max >= chan.buffer.length) return - chan.buffer_max | 0;
      var prev_max = chan.buffer_max;
      caml_refill(chan);
      if(prev_max == chan.buffer_max) return - chan.buffer_max | 0;
     }
    while
     (chan.buffer[p++] != 10);
    return p - chan.buffer_curr | 0;
   }
   function caml_gc_minor(unit){
    if(typeof globalThis.gc == "function") globalThis.gc(true);
    return 0;
   }
   function caml_ml_condition_new(unit){return {condition: 1};}
   function caml_int64_of_bytes(a){
    return new
            MlInt64
            (a[7] << 0 | a[6] << 8 | a[5] << 16,
             a[4] << 0 | a[3] << 8 | a[2] << 16,
             a[1] << 0 | a[0] << 8);
   }
   function caml_ba_uint8_get64(ba, i0){
    var ofs = ba.offset(i0);
    if(ofs + 7 >= ba.data.length) caml_array_bound_error();
    var
     b1 = ba.get(ofs + 0),
     b2 = ba.get(ofs + 1),
     b3 = ba.get(ofs + 2),
     b4 = ba.get(ofs + 3),
     b5 = ba.get(ofs + 4),
     b6 = ba.get(ofs + 5),
     b7 = ba.get(ofs + 6),
     b8 = ba.get(ofs + 7);
    return caml_int64_of_bytes([b8, b7, b6, b5, b4, b3, b2, b1]);
   }
   function caml_int64_to_bytes(x){return x.toArray();}
   function caml_int64_marshal(writer, v, sizes){
    var b = caml_int64_to_bytes(v);
    for(var i = 0; i < 8; i++) writer.write(8, b[i]);
    sizes[0] = 8;
    sizes[1] = 8;
   }
   function caml_ba_num_dims(ba){return ba.dims.length;}
   function caml_wrap_exception(e){
    {
     if(e instanceof Array) return e;
     var exn;
     if
      (globalThis.RangeError && e instanceof globalThis.RangeError
       && e.message
       && e.message.match(/maximum call stack/i))
      exn = caml_global_data.Stack_overflow;
     else if
      (globalThis.InternalError && e instanceof globalThis.InternalError
       && e.message
       && e.message.match(/too much recursion/i))
      exn = caml_global_data.Stack_overflow;
     else if(e instanceof globalThis.Error && caml_named_value("jsError"))
      exn = [0, caml_named_value("jsError"), e];
     else
      exn = [0, caml_global_data.Failure, caml_string_of_jsstring(String(e))];
     if(e instanceof globalThis.Error) exn.js_error = e;
     return exn;
    }
   }
   function caml_create_file(name, content){
    var root = resolve_fs_device(name);
    if(! root.device.register) caml_failwith("cannot register file");
    root.device.register(root.rest, content);
    return 0;
   }
   function jsoo_create_file(name, content){
    var
     name = caml_string_of_jsbytes(name),
     content = caml_string_of_jsbytes(content);
    return caml_create_file(name, content);
   }
   function caml_fs_init(){
    var tmp = globalThis.caml_fs_tmp;
    if(tmp)
     for(var i = 0; i < tmp.length; i++)
      jsoo_create_file(tmp[i].name, tmp[i].content);
    globalThis.jsoo_create_file = jsoo_create_file;
    globalThis.caml_fs_tmp = [];
    return 0;
   }
   function caml_get_continuation_callstack(){return [0];}
   var caml_parser_trace = 0;
   function caml_set_parser_trace(bool){
    var oldflag = caml_parser_trace;
    caml_parser_trace = bool;
    return oldflag;
   }
   function caml_list_of_js_array(a){
    var l = 0;
    for(var i = a.length - 1; i >= 0; i--){var e = a[i]; l = [0, e, l];}
    return l;
   }
   function caml_mul(a, b){return Math.imul(a, b);}
   function caml_hash_mix_int(h, d){
    d = caml_mul(d, 0xcc9e2d51 | 0);
    d = d << 15 | d >>> 32 - 15;
    d = caml_mul(d, 0x1b873593);
    h ^= d;
    h = h << 13 | h >>> 32 - 13;
    return (h + (h << 2) | 0) + (0xe6546b64 | 0) | 0;
   }
   function num_digits_nat(nat, ofs, len){
    for(var i = len - 1; i >= 0; i--) if(nat.data[ofs + i] != 0) return i + 1;
    return 1;
   }
   function caml_hash_nat(x){
    var len = num_digits_nat(x, 0, x.data.length), h = 0;
    for(var i = 0; i < len; i++) h = caml_hash_mix_int(h, x.data[i]);
    return h;
   }
   function caml_call_gen(f, args){
    var
     n = f.l >= 0 ? f.l : f.l = f.length,
     argsLen = args.length,
     d = n - argsLen;
    if(d == 0)
     return f.apply(null, args);
    else if(d < 0){
     var g = f.apply(null, args.slice(0, n));
     if(typeof g !== "function") return g;
     return caml_call_gen(g, args.slice(n));
    }
    else{
     switch(d){
       case 1:
        {
         var
          g =
            function(x){
             var nargs = new Array(argsLen + 1);
             for(var i = 0; i < argsLen; i++) nargs[i] = args[i];
             nargs[argsLen] = x;
             return f.apply(null, nargs);
            };
         break;
        }
       case 2:
        {
         var
          g =
            function(x, y){
             var nargs = new Array(argsLen + 2);
             for(var i = 0; i < argsLen; i++) nargs[i] = args[i];
             nargs[argsLen] = x;
             nargs[argsLen + 1] = y;
             return f.apply(null, nargs);
            };
         break;
        }
       default:
        var
         g =
           function(){
            var
             extra_args = arguments.length == 0 ? 1 : arguments.length,
             nargs = new Array(args.length + extra_args);
            for(var i = 0; i < args.length; i++) nargs[i] = args[i];
            for(var i = 0; i < arguments.length; i++)
             nargs[args.length + i] = arguments[i];
            return caml_call_gen(f, nargs);
           };
     }
     g.l = d;
     return g;
    }
   }
   var caml_callback = caml_call_gen;
   function caml_js_wrap_callback_arguments(f){
    return function(){
     var len = arguments.length, args = new Array(len);
     for(var i = 0; i < len; i++) args[i] = arguments[i];
     return caml_callback(f, [args]);};
   }
   function caml_sys_chdir(dir){
    var root = resolve_fs_device(dir);
    if(root.device.exists(root.rest)){
     if(root.rest)
      caml_current_dir = caml_trailing_slash(root.path + root.rest);
     else
      caml_current_dir = root.path;
     return 0;
    }
    else
     caml_raise_no_such_file(caml_jsbytes_of_string(dir));
   }
   function caml_obj_tag(x){
    if(x instanceof Array && x[0] == x[0] >>> 0)
     return x[0];
    else if(caml_is_ml_bytes(x))
     return 252;
    else if(caml_is_ml_string(x))
     return 252;
    else if(x instanceof Function || typeof x == "function")
     return 247;
    else if(x && x.caml_custom) return 255; else return 1000;
   }
   function caml_obj_update_tag(b, o, n){
    if(b[0] == o){b[0] = n; return 1;}
    return 0;
   }
   var caml_ml_domain_unique_token_ = [0];
   function caml_ml_domain_unique_token(unit){return caml_ml_domain_unique_token_;
   }
   function caml_lazy_update_to_forcing(o){
    var t = caml_obj_tag(o);
    if(t != 246 && t != 250 && t != 244) return 4;
    if(caml_obj_update_tag(o, 246, 244))
     return 0;
    else{
     var field0 = o[1];
     t = o[0];
     if(t == 244)
      return field0 == caml_ml_domain_unique_token(0) ? 1 : 2;
     else if(t == 250) return 3; else return 2;
    }
   }
   function caml_gc_counters(){return [254, 0, 0, 0];}
   function caml_gr_synchronize(){
    caml_failwith("caml_gr_synchronize not Implemented");
   }
   function caml_unix_closedir(dir_handle){
    try{dir_handle.pointer.closeSync();}
    catch(e){
     var unix_error = caml_named_value("Unix.Unix_error");
     caml_raise_with_args
      (unix_error, make_unix_err_args("EBADF", "closedir", dir_handle.path));
    }
   }
   function caml_unix_opendir(path){
    var root = resolve_fs_device(path);
    if(! root.device.opendir)
     caml_failwith("caml_unix_opendir: not implemented");
    var dir_handle = root.device.opendir(root.rest, true);
    return {pointer: dir_handle, path: path};
   }
   function caml_unix_rewinddir(dir_handle){
    caml_unix_closedir(dir_handle);
    var new_dir_handle = caml_unix_opendir(dir_handle.path);
    dir_handle.pointer = new_dir_handle.pointer;
    return 0;
   }
   function caml_raise_end_of_file(){
    caml_raise_constant(caml_global_data.End_of_file);
   }
   function caml_unix_readdir(dir_handle){
    var entry;
    try{entry = dir_handle.pointer.readSync();}
    catch(e){
     var unix_error = caml_named_value("Unix.Unix_error");
     caml_raise_with_args
      (unix_error, make_unix_err_args("EBADF", "readdir", dir_handle.path));
    }
    if(entry === null)
     caml_raise_end_of_file();
    else
     return caml_string_of_jsstring(entry.name);
   }
   function caml_unix_findfirst(path){
    var path_js = caml_jsstring_of_string(path);
    path_js = path_js.replace(/(^|[\\\/])\*\.\*$/, "");
    path = caml_string_of_jsstring(path_js);
    var
     dir_handle = caml_unix_opendir(path),
     first_entry = caml_unix_readdir(dir_handle);
    return [0, first_entry, dir_handle];
   }
   function caml_is_continuation_tag(t){return 0;}
   var log2_ok = Math.log2 && Math.log2(1.1235582092889474E+307) == 1020;
   function jsoo_floor_log2(x){
    if(log2_ok) return Math.floor(Math.log2(x));
    var i = 0;
    if(x == 0) return - Infinity;
    if(x >= 1) while(x >= 2){x /= 2; i++;} else while(x < 1){x *= 2; i--;}
    return i;
   }
   function caml_int32_bits_of_float(x){
    var float32a = new Float32Array(1);
    float32a[0] = x;
    var int32a = new Int32Array(float32a.buffer);
    return int32a[0] | 0;
   }
   function caml_int64_create_lo_mi_hi(lo, mi, hi){return new MlInt64(lo, mi, hi);
   }
   function caml_int64_bits_of_float(x){
    if(! isFinite(x)){
     if(isNaN(x)) return caml_int64_create_lo_mi_hi(1, 0, 0x7ff0);
     return x > 0
             ? caml_int64_create_lo_mi_hi(0, 0, 0x7ff0)
             : caml_int64_create_lo_mi_hi(0, 0, 0xfff0);
    }
    var sign = x == 0 && 1 / x == - Infinity ? 0x8000 : x >= 0 ? 0 : 0x8000;
    if(sign) x = - x;
    var exp = jsoo_floor_log2(x) + 1023;
    if(exp <= 0){
     exp = 0;
     x /= Math.pow(2, - 1026);
    }
    else{
     x /= Math.pow(2, exp - 1027);
     if(x < 16){x *= 2; exp -= 1;}
     if(exp == 0) x /= 2;
    }
    var k = Math.pow(2, 24), r3 = x | 0;
    x = (x - r3) * k;
    var r2 = x | 0;
    x = (x - r2) * k;
    var r1 = x | 0;
    r3 = r3 & 0xf | sign | exp << 4;
    return caml_int64_create_lo_mi_hi(r1, r2, r3);
   }
   function caml_ba_serialize(writer, ba, sz){
    writer.write(32, ba.dims.length);
    writer.write(32, ba.kind | ba.layout << 8);
    if(ba.caml_custom == "_bigarr02")
     for(var i = 0; i < ba.dims.length; i++)
      if(ba.dims[i] < 0xffff)
       writer.write(16, ba.dims[i]);
      else{
       writer.write(16, 0xffff);
       writer.write(32, 0);
       writer.write(32, ba.dims[i]);
      }
    else
     for(var i = 0; i < ba.dims.length; i++) writer.write(32, ba.dims[i]);
    switch(ba.kind){
      case 2:
      case 3:
      case 12:
       for(var i = 0; i < ba.data.length; i++) writer.write(8, ba.data[i]);
       break;
      case 4:
      case 5:
       for(var i = 0; i < ba.data.length; i++) writer.write(16, ba.data[i]);
       break;
      case 6:
       for(var i = 0; i < ba.data.length; i++) writer.write(32, ba.data[i]);
       break;
      case 8:
      case 9:
       writer.write(8, 0);
       for(var i = 0; i < ba.data.length; i++) writer.write(32, ba.data[i]);
       break;
      case 7:
       for(var i = 0; i < ba.data.length / 2; i++){
        var b = caml_int64_to_bytes(ba.get(i));
        for(var j = 0; j < 8; j++) writer.write(8, b[j]);
       }
       break;
      case 1:
       for(var i = 0; i < ba.data.length; i++){
        var b = caml_int64_to_bytes(caml_int64_bits_of_float(ba.get(i)));
        for(var j = 0; j < 8; j++) writer.write(8, b[j]);
       }
       break;
      case 0:
       for(var i = 0; i < ba.data.length; i++){
        var b = caml_int32_bits_of_float(ba.get(i));
        writer.write(32, b);
       }
       break;
      case 10:
       for(var i = 0; i < ba.data.length / 2; i++){
        var j = ba.get(i);
        writer.write(32, caml_int32_bits_of_float(j[1]));
        writer.write(32, caml_int32_bits_of_float(j[2]));
       }
       break;
      case 11:
       for(var i = 0; i < ba.data.length / 2; i++){
        var
         complex = ba.get(i),
         b = caml_int64_to_bytes(caml_int64_bits_of_float(complex[1]));
        for(var j = 0; j < 8; j++) writer.write(8, b[j]);
        var b = caml_int64_to_bytes(caml_int64_bits_of_float(complex[2]));
        for(var j = 0; j < 8; j++) writer.write(8, b[j]);
       }
       break;
    }
    sz[0] = (4 + ba.dims.length) * 4;
    sz[1] = (4 + ba.dims.length) * 8;
   }
   function caml_ba_get_size_per_element(kind){
    switch(kind){case 7:case 10:case 11: return 2;default: return 1;
    }
   }
   function caml_ba_create_buffer(kind, size){
    var view;
    switch(kind){
      case 0:
       view = Float32Array; break;
      case 1:
       view = Float64Array; break;
      case 2:
       view = Int8Array; break;
      case 3:
       view = Uint8Array; break;
      case 4:
       view = Int16Array; break;
      case 5:
       view = Uint16Array; break;
      case 6:
       view = Int32Array; break;
      case 7:
       view = Int32Array; break;
      case 8:
       view = Int32Array; break;
      case 9:
       view = Int32Array; break;
      case 10:
       view = Float32Array; break;
      case 11:
       view = Float64Array; break;
      case 12:
       view = Uint8Array; break;
    }
    if(! view) caml_invalid_argument("Bigarray.create: unsupported kind");
    var data = new view(size * caml_ba_get_size_per_element(kind));
    return data;
   }
   function caml_int32_float_of_bits(x){
    var int32a = new Int32Array(1);
    int32a[0] = x;
    var float32a = new Float32Array(int32a.buffer);
    return float32a[0];
   }
   function caml_int64_float_of_bits(x){
    var lo = x.lo, mi = x.mi, hi = x.hi, exp = (hi & 0x7fff) >> 4;
    if(exp == 2047)
     return (lo | mi | hi & 0xf) == 0
             ? hi & 0x8000 ? - Infinity : Infinity
             : NaN;
    var k = Math.pow(2, - 24), res = (lo * k + mi) * k + (hi & 0xf);
    if(exp > 0){
     res += 16;
     res *= Math.pow(2, exp - 1027);
    }
    else
     res *= Math.pow(2, - 1026);
    if(hi & 0x8000) res = - res;
    return res;
   }
   function caml_ba_get_size(dims){
    var n_dims = dims.length, size = 1;
    for(var i = 0; i < n_dims; i++){
     if(dims[i] < 0)
      caml_invalid_argument("Bigarray.create: negative dimension");
     size = size * dims[i];
    }
    return size;
   }
   function caml_int64_create_lo_hi(lo, hi){
    return new
            MlInt64
            (lo & 0xffffff,
             lo >>> 24 & 0xff | (hi & 0xffff) << 8,
             hi >>> 16 & 0xffff);
   }
   function caml_int64_hi32(v){return v.hi32();}
   function caml_int64_lo32(v){return v.lo32();}
   var caml_ba_custom_name = "_bigarr02";
   function Ml_Bigarray(kind, layout, dims, buffer){
    this.kind = kind;
    this.layout = layout;
    this.dims = dims;
    this.data = buffer;
   }
   Ml_Bigarray.prototype.caml_custom = caml_ba_custom_name;
   Ml_Bigarray.prototype.offset =
    function(arg){
     var ofs = 0;
     if(typeof arg === "number") arg = [arg];
     if(! (arg instanceof Array))
      caml_invalid_argument("bigarray.js: invalid offset");
     if(this.dims.length != arg.length)
      caml_invalid_argument("Bigarray.get/set: bad number of dimensions");
     if(this.layout == 0)
      for(var i = 0; i < this.dims.length; i++){
       if(arg[i] < 0 || arg[i] >= this.dims[i]) caml_array_bound_error();
       ofs = ofs * this.dims[i] + arg[i];
      }
     else
      for(var i = this.dims.length - 1; i >= 0; i--){
       if(arg[i] < 1 || arg[i] > this.dims[i]) caml_array_bound_error();
       ofs = ofs * this.dims[i] + (arg[i] - 1);
      }
     return ofs;
    };
   Ml_Bigarray.prototype.get =
    function(ofs){
     switch(this.kind){
       case 7:
        var l = this.data[ofs * 2 + 0], h = this.data[ofs * 2 + 1];
        return caml_int64_create_lo_hi(l, h);
       case 10:
       case 11:
        var r = this.data[ofs * 2 + 0], i = this.data[ofs * 2 + 1];
        return [254, r, i];
       default: return this.data[ofs];
     }
    };
   Ml_Bigarray.prototype.set =
    function(ofs, v){
     switch(this.kind){
       case 7:
        this.data[ofs * 2 + 0] = caml_int64_lo32(v);
        this.data[ofs * 2 + 1] = caml_int64_hi32(v);
        break;
       case 10:
       case 11:
        this.data[ofs * 2 + 0] = v[1]; this.data[ofs * 2 + 1] = v[2]; break;
       default: this.data[ofs] = v; break;
     }
     return 0;
    };
   Ml_Bigarray.prototype.fill =
    function(v){
     switch(this.kind){
       case 7:
        var a = caml_int64_lo32(v), b = caml_int64_hi32(v);
        if(a == b)
         this.data.fill(a);
        else
         for(var i = 0; i < this.data.length; i++)
          this.data[i] = i % 2 == 0 ? a : b;
        break;
       case 10:
       case 11:
        var im = v[1], re = v[2];
        if(im == re)
         this.data.fill(im);
        else
         for(var i = 0; i < this.data.length; i++)
          this.data[i] = i % 2 == 0 ? im : re;
        break;
       default: this.data.fill(v); break;
     }
    };
   Ml_Bigarray.prototype.compare =
    function(b, total){
     if(this.layout != b.layout || this.kind != b.kind){
      var k1 = this.kind | this.layout << 8, k2 = b.kind | b.layout << 8;
      return k2 - k1;
     }
     if(this.dims.length != b.dims.length)
      return b.dims.length - this.dims.length;
     for(var i = 0; i < this.dims.length; i++)
      if(this.dims[i] != b.dims[i]) return this.dims[i] < b.dims[i] ? - 1 : 1;
     switch(this.kind){
       case 0:
       case 1:
       case 10:
       case 11:
        var x, y;
        for(var i = 0; i < this.data.length; i++){
         x = this.data[i];
         y = b.data[i];
         if(x < y) return - 1;
         if(x > y) return 1;
         if(x != y){
          if(! total) return NaN;
          if(x == x) return 1;
          if(y == y) return - 1;
         }
        }
        break;
       case 7:
        for(var i = 0; i < this.data.length; i += 2){
         if(this.data[i + 1] < b.data[i + 1]) return - 1;
         if(this.data[i + 1] > b.data[i + 1]) return 1;
         if(this.data[i] >>> 0 < b.data[i] >>> 0) return - 1;
         if(this.data[i] >>> 0 > b.data[i] >>> 0) return 1;
        }
        break;
       case 2:
       case 3:
       case 4:
       case 5:
       case 6:
       case 8:
       case 9:
       case 12:
        for(var i = 0; i < this.data.length; i++){
         if(this.data[i] < b.data[i]) return - 1;
         if(this.data[i] > b.data[i]) return 1;
        }
        break;
     }
     return 0;
    };
   function Ml_Bigarray_c_1_1(kind, layout, dims, buffer){
    this.kind = kind;
    this.layout = layout;
    this.dims = dims;
    this.data = buffer;
   }
   Ml_Bigarray_c_1_1.prototype = new Ml_Bigarray();
   Ml_Bigarray_c_1_1.prototype.offset =
    function(arg){
     if(typeof arg !== "number")
      if(arg instanceof Array && arg.length == 1)
       arg = arg[0];
      else
       caml_invalid_argument("Ml_Bigarray_c_1_1.offset");
     if(arg < 0 || arg >= this.dims[0]) caml_array_bound_error();
     return arg;
    };
   Ml_Bigarray_c_1_1.prototype.get = function(ofs){return this.data[ofs];};
   Ml_Bigarray_c_1_1.prototype.set =
    function(ofs, v){this.data[ofs] = v; return 0;};
   Ml_Bigarray_c_1_1.prototype.fill =
    function(v){this.data.fill(v); return 0;};
   function caml_ba_create_unsafe(kind, layout, dims, data){
    var size_per_element = caml_ba_get_size_per_element(kind);
    if(caml_ba_get_size(dims) * size_per_element != data.length)
     caml_invalid_argument("length doesn't match dims");
    if(layout == 0 && dims.length == 1 && size_per_element == 1)
     return new Ml_Bigarray_c_1_1(kind, layout, dims, data);
    return new Ml_Bigarray(kind, layout, dims, data);
   }
   function caml_ba_deserialize(reader, sz, name){
    var num_dims = reader.read32s();
    if(num_dims < 0 || num_dims > 16)
     caml_failwith("input_value: wrong number of bigarray dimensions");
    var
     tag = reader.read32s(),
     kind = tag & 0xff,
     layout = tag >> 8 & 1,
     dims = [];
    if(name == "_bigarr02")
     for(var i = 0; i < num_dims; i++){
      var size_dim = reader.read16u();
      if(size_dim == 0xffff){
       var size_dim_hi = reader.read32u(), size_dim_lo = reader.read32u();
       if(size_dim_hi != 0)
        caml_failwith("input_value: bigarray dimension overflow in 32bit");
       size_dim = size_dim_lo;
      }
      dims.push(size_dim);
     }
    else
     for(var i = 0; i < num_dims; i++) dims.push(reader.read32u());
    var
     size = caml_ba_get_size(dims),
     data = caml_ba_create_buffer(kind, size),
     ba = caml_ba_create_unsafe(kind, layout, dims, data);
    switch(kind){
      case 2:
       for(var i = 0; i < size; i++) data[i] = reader.read8s(); break;
      case 3:
      case 12:
       for(var i = 0; i < size; i++) data[i] = reader.read8u(); break;
      case 4:
       for(var i = 0; i < size; i++) data[i] = reader.read16s(); break;
      case 5:
       for(var i = 0; i < size; i++) data[i] = reader.read16u(); break;
      case 6:
       for(var i = 0; i < size; i++) data[i] = reader.read32s(); break;
      case 8:
      case 9:
       var sixty = reader.read8u();
       if(sixty)
        caml_failwith
         ("input_value: cannot read bigarray with 64-bit OCaml ints");
       for(var i = 0; i < size; i++) data[i] = reader.read32s();
       break;
      case 7:
       var t = new Array(8);
       for(var i = 0; i < size; i++){
        for(var j = 0; j < 8; j++) t[j] = reader.read8u();
        var int64 = caml_int64_of_bytes(t);
        ba.set(i, int64);
       }
       break;
      case 1:
       var t = new Array(8);
       for(var i = 0; i < size; i++){
        for(var j = 0; j < 8; j++) t[j] = reader.read8u();
        var f = caml_int64_float_of_bits(caml_int64_of_bytes(t));
        ba.set(i, f);
       }
       break;
      case 0:
       for(var i = 0; i < size; i++){
        var f = caml_int32_float_of_bits(reader.read32s());
        ba.set(i, f);
       }
       break;
      case 10:
       for(var i = 0; i < size; i++){
        var
         re = caml_int32_float_of_bits(reader.read32s()),
         im = caml_int32_float_of_bits(reader.read32s());
        ba.set(i, [254, re, im]);
       }
       break;
      case 11:
       var t = new Array(8);
       for(var i = 0; i < size; i++){
        for(var j = 0; j < 8; j++) t[j] = reader.read8u();
        var re = caml_int64_float_of_bits(caml_int64_of_bytes(t));
        for(var j = 0; j < 8; j++) t[j] = reader.read8u();
        var im = caml_int64_float_of_bits(caml_int64_of_bytes(t));
        ba.set(i, [254, re, im]);
       }
       break;
    }
    sz[0] = (4 + num_dims) * 4;
    return caml_ba_create_unsafe(kind, layout, dims, data);
   }
   function caml_ba_compare(a, b, total){return a.compare(b, total);}
   function caml_hash_mix_int64(h, v){
    h = caml_hash_mix_int(h, caml_int64_lo32(v));
    h = caml_hash_mix_int(h, caml_int64_hi32(v));
    return h;
   }
   function caml_hash_mix_float(h, v0){
    return caml_hash_mix_int64(h, caml_int64_bits_of_float(v0));
   }
   function caml_ba_hash(ba){
    var num_elts = caml_ba_get_size(ba.dims), h = 0;
    switch(ba.kind){
      case 2:
      case 3:
      case 12:
       if(num_elts > 256) num_elts = 256;
       var w = 0, i = 0;
       for(i = 0; i + 4 <= ba.data.length; i += 4){
        w =
         ba.data[i + 0] | ba.data[i + 1] << 8 | ba.data[i + 2] << 16
         | ba.data[i + 3] << 24;
        h = caml_hash_mix_int(h, w);
       }
       w = 0;
       switch(num_elts & 3){
         case 3:
          w = ba.data[i + 2] << 16;
         case 2:
          w |= ba.data[i + 1] << 8;
         case 1:
          w |= ba.data[i + 0]; h = caml_hash_mix_int(h, w);
       }
       break;
      case 4:
      case 5:
       if(num_elts > 128) num_elts = 128;
       var w = 0, i = 0;
       for(i = 0; i + 2 <= ba.data.length; i += 2){
        w = ba.data[i + 0] | ba.data[i + 1] << 16;
        h = caml_hash_mix_int(h, w);
       }
       if((num_elts & 1) != 0) h = caml_hash_mix_int(h, ba.data[i]);
       break;
      case 6:
       if(num_elts > 64) num_elts = 64;
       for(var i = 0; i < num_elts; i++) h = caml_hash_mix_int(h, ba.data[i]);
       break;
      case 8:
      case 9:
       if(num_elts > 64) num_elts = 64;
       for(var i = 0; i < num_elts; i++) h = caml_hash_mix_int(h, ba.data[i]);
       break;
      case 7:
       if(num_elts > 32) num_elts = 32;
       num_elts *= 2;
       for(var i = 0; i < num_elts; i++) h = caml_hash_mix_int(h, ba.data[i]);
       break;
      case 10:
       num_elts *= 2;
      case 0:
       if(num_elts > 64) num_elts = 64;
       for(var i = 0; i < num_elts; i++)
        h = caml_hash_mix_float(h, ba.data[i]);
       break;
      case 11:
       num_elts *= 2;
      case 1:
       if(num_elts > 32) num_elts = 32;
       for(var i = 0; i < num_elts; i++)
        h = caml_hash_mix_float(h, ba.data[i]);
       break;
    }
    return h;
   }
   function caml_int32_unmarshal(reader, size){size[0] = 4; return reader.read32s();
   }
   function caml_nativeint_unmarshal(reader, size){
    switch(reader.read8u()){
      case 1:
       size[0] = 4; return reader.read32s();
      case 2:
       caml_failwith("input_value: native integer value too large");
      default: caml_failwith("input_value: ill-formed native integer");
    }
   }
   function caml_int64_unmarshal(reader, size){
    var t = new Array(8);
    for(var j = 0; j < 8; j++) t[j] = reader.read8u();
    size[0] = 8;
    return caml_int64_of_bytes(t);
   }
   function caml_int64_compare(x, y, total){return x.compare(y);}
   function caml_int64_hash(v){return v.lo32() ^ v.hi32();}
   var
    caml_custom_ops =
      {"_j":
       {deserialize: caml_int64_unmarshal,
        serialize: caml_int64_marshal,
        fixed_length: 8,
        compare: caml_int64_compare,
        hash: caml_int64_hash},
       "_i": {deserialize: caml_int32_unmarshal, fixed_length: 4},
       "_n": {deserialize: caml_nativeint_unmarshal, fixed_length: 4},
       "_bigarray":
       {deserialize:
        function(reader, sz){
         return caml_ba_deserialize(reader, sz, "_bigarray");
        },
        serialize: caml_ba_serialize,
        compare: caml_ba_compare,
        hash: caml_ba_hash},
       "_bigarr02":
       {deserialize:
        function(reader, sz){
         return caml_ba_deserialize(reader, sz, "_bigarr02");
        },
        serialize: caml_ba_serialize,
        compare: caml_ba_compare,
        hash: caml_ba_hash}};
   function caml_compare_val_get_custom(a){
    return caml_custom_ops[a.caml_custom]
           && caml_custom_ops[a.caml_custom].compare;
   }
   function caml_compare_val_number_custom(num, custom, swap, total){
    var comp = caml_compare_val_get_custom(custom);
    if(comp){
     var x = swap > 0 ? comp(custom, num, total) : comp(num, custom, total);
     if(total && x != x) return swap;
     if(+ x != + x) return + x;
     if((x | 0) != 0) return x | 0;
    }
    return swap;
   }
   function caml_compare_val_tag(a){
    if(typeof a === "number")
     return 1000;
    else if(caml_is_ml_bytes(a))
     return 252;
    else if(caml_is_ml_string(a))
     return 1252;
    else if(a instanceof Array && a[0] === a[0] >>> 0 && a[0] <= 255){var tag = a[0] | 0; return tag == 254 ? 0 : tag;}
    else if(a instanceof String)
     return 12520;
    else if(typeof a == "string")
     return 12520;
    else if(a instanceof Number)
     return 1000;
    else if(a && a.caml_custom)
     return 1255;
    else if(a && a.compare)
     return 1256;
    else if(typeof a == "function")
     return 1247;
    else if(typeof a == "symbol") return 1251;
    return 1001;
   }
   function caml_int_compare(a, b){
    if(a < b) return - 1;
    if(a == b) return 0;
    return 1;
   }
   function caml_string_compare(s1, s2){
    return s1 < s2 ? - 1 : s1 > s2 ? 1 : 0;
   }
   function caml_bytes_compare(s1, s2){
    s1.t & 6 && caml_convert_string_to_bytes(s1);
    s2.t & 6 && caml_convert_string_to_bytes(s2);
    return s1.c < s2.c ? - 1 : s1.c > s2.c ? 1 : 0;
   }
   function caml_compare_val(a, b, total){
    var stack = [];
    for(;;){
     if(! (total && a === b)){
      var tag_a = caml_compare_val_tag(a);
      if(tag_a == 250){a = a[1]; continue;}
      var tag_b = caml_compare_val_tag(b);
      if(tag_b == 250){b = b[1]; continue;}
      if(tag_a !== tag_b){
       if(tag_a == 1000){
        if(tag_b == 1255)
         return caml_compare_val_number_custom(a, b, - 1, total);
        return - 1;
       }
       if(tag_b == 1000){
        if(tag_a == 1255)
         return caml_compare_val_number_custom(b, a, 1, total);
        return 1;
       }
       return tag_a < tag_b ? - 1 : 1;
      }
      switch(tag_a){
        case 247:
         caml_invalid_argument("compare: functional value"); break;
        case 248:
         var x = caml_int_compare(a[2], b[2]); if(x != 0) return x | 0; break;
        case 249:
         caml_invalid_argument("compare: functional value"); break;
        case 250:
         caml_invalid_argument("equal: got Forward_tag, should not happen");
         break;
        case 251:
         caml_invalid_argument("equal: abstract value"); break;
        case 252:
         if(a !== b){
          var x = caml_bytes_compare(a, b);
          if(x != 0) return x | 0;
         }
         break;
        case 253:
         caml_invalid_argument("equal: got Double_tag, should not happen");
         break;
        case 254:
         caml_invalid_argument
          ("equal: got Double_array_tag, should not happen");
         break;
        case 255:
         caml_invalid_argument("equal: got Custom_tag, should not happen");
         break;
        case 1247:
         caml_invalid_argument("compare: functional value"); break;
        case 1255:
         var comp = caml_compare_val_get_custom(a);
         if(comp != caml_compare_val_get_custom(b))
          return a.caml_custom < b.caml_custom ? - 1 : 1;
         if(! comp) caml_invalid_argument("compare: abstract value");
         var x = comp(a, b, total);
         if(x != x) return total ? - 1 : x;
         if(x !== (x | 0)) return - 1;
         if(x != 0) return x | 0;
         break;
        case 1256:
         var x = a.compare(b, total);
         if(x != x) return total ? - 1 : x;
         if(x !== (x | 0)) return - 1;
         if(x != 0) return x | 0;
         break;
        case 1000:
         a = + a;
         b = + b;
         if(a < b) return - 1;
         if(a > b) return 1;
         if(a != b){
          if(! total) return NaN;
          if(a == a) return 1;
          if(b == b) return - 1;
         }
         break;
        case 1001:
         if(a < b) return - 1;
         if(a > b) return 1;
         if(a != b){
          if(! total) return NaN;
          if(a == a) return 1;
          if(b == b) return - 1;
         }
         break;
        case 1251:
         if(a !== b){if(! total) return NaN; return 1;} break;
        case 1252:
         var a = caml_jsbytes_of_string(a), b = caml_jsbytes_of_string(b);
         if(a !== b){if(a < b) return - 1; if(a > b) return 1;}
         break;
        case 12520:
         var a = a.toString(), b = b.toString();
         if(a !== b){if(a < b) return - 1; if(a > b) return 1;}
         break;
        case 246:
        case 254:
        default:
         if(caml_is_continuation_tag(tag_a)){
          caml_invalid_argument("compare: continuation value");
          break;
         }
         if(a.length != b.length) return a.length < b.length ? - 1 : 1;
         if(a.length > 1) stack.push(a, b, 1);
         break;
      }
     }
     if(stack.length == 0) return 0;
     var i = stack.pop();
     b = stack.pop();
     a = stack.pop();
     if(i + 1 < a.length) stack.push(a, b, i + 1);
     a = a[i];
     b = b[i];
    }
   }
   function caml_greaterthan(x, y){
    return + (caml_compare_val(x, y, false) > 0);
   }
   function div_helper(a, b, c){
    var
     x = a * 65536 + (b >>> 16),
     y = Math.floor(x / c) * 65536,
     z = x % c * 65536,
     w = z + (b & 0x0000FFFF);
    return [y + Math.floor(w / c), w % c];
   }
   function div_digit_nat(natq, ofsq, natr, ofsr, nat1, ofs1, len, nat2, ofs2){
    var rem = nat1.data[ofs1 + len - 1] >>> 0;
    for(var i = len - 2; i >= 0; i--){
     var
      x = div_helper(rem, nat1.data[ofs1 + i] >>> 0, nat2.data[ofs2] >>> 0);
     natq.data[ofsq + i] = x[0];
     rem = x[1];
    }
    natr.data[ofsr] = rem;
    return 0;
   }
   function num_leading_zero_bits_in_digit(nat, ofs){
    var a = nat.data[ofs], b = 0;
    if(a & 0xFFFF0000){b += 16; a >>>= 16;}
    if(a & 0xFF00){b += 8; a >>>= 8;}
    if(a & 0xF0){b += 4; a >>>= 4;}
    if(a & 12){b += 2; a >>>= 2;}
    if(a & 2){b += 1; a >>>= 1;}
    if(a & 1) b += 1;
    return 32 - b;
   }
   function shift_left_nat(nat1, ofs1, len1, nat2, ofs2, nbits){
    if(nbits == 0){nat2.data[ofs2] = 0; return 0;}
    var wrap = 0;
    for(var i = 0; i < len1; i++){
     var a = nat1.data[ofs1 + i] >>> 0;
     nat1.data[ofs1 + i] = a << nbits | wrap;
     wrap = a >>> 32 - nbits;
    }
    nat2.data[ofs2] = wrap;
    return 0;
   }
   function MlNat(x){
    this.data = new Int32Array(x);
    this.length = this.data.length + 2;
   }
   MlNat.prototype.caml_custom = "_nat";
   function create_nat(size){
    var arr = new MlNat(size);
    for(var i = 0; i < size; i++) arr.data[i] = - 1;
    return arr;
   }
   function set_to_zero_nat(nat, ofs, len){
    for(var i = 0; i < len; i++) nat.data[ofs + i] = 0;
    return 0;
   }
   function incr_nat(nat, ofs, len, carry_in){
    var carry = carry_in;
    for(var i = 0; i < len; i++){
     var x = (nat.data[ofs + i] >>> 0) + carry;
     nat.data[ofs + i] = x | 0;
     if(x == x >>> 0){carry = 0; break;} else carry = 1;
    }
    return carry;
   }
   function add_nat(nat1, ofs1, len1, nat2, ofs2, len2, carry_in){
    var carry = carry_in;
    for(var i = 0; i < len2; i++){
     var
      x = (nat1.data[ofs1 + i] >>> 0) + (nat2.data[ofs2 + i] >>> 0) + carry;
     nat1.data[ofs1 + i] = x;
     if(x == x >>> 0) carry = 0; else carry = 1;
    }
    return incr_nat(nat1, ofs1 + len2, len1 - len2, carry);
   }
   function nat_of_array(l){return new MlNat(l);}
   function mult_digit_nat(nat1, ofs1, len1, nat2, ofs2, len2, nat3, ofs3){
    var carry = 0, a = nat3.data[ofs3] >>> 0;
    for(var i = 0; i < len2; i++){
     var
      x1 =
        (nat1.data[ofs1 + i] >>> 0)
        + (nat2.data[ofs2 + i] >>> 0) * (a & 0x0000FFFF)
        + carry,
      x2 = (nat2.data[ofs2 + i] >>> 0) * (a >>> 16);
     carry = Math.floor(x2 / 65536);
     var x3 = x1 + x2 % 65536 * 65536;
     nat1.data[ofs1 + i] = x3;
     carry += Math.floor(x3 / 4294967296);
    }
    return len2 < len1 && carry
            ? add_nat
              (nat1, ofs1 + len2, len1 - len2, nat_of_array([carry]), 0, 1, 0)
            : carry;
   }
   function decr_nat(nat, ofs, len, carry_in){
    var borrow = carry_in == 1 ? 0 : 1;
    for(var i = 0; i < len; i++){
     var x = (nat.data[ofs + i] >>> 0) - borrow;
     nat.data[ofs + i] = x;
     if(x >= 0){borrow = 0; break;} else borrow = 1;
    }
    return borrow == 1 ? 0 : 1;
   }
   function sub_nat(nat1, ofs1, len1, nat2, ofs2, len2, carry_in){
    var borrow = carry_in == 1 ? 0 : 1;
    for(var i = 0; i < len2; i++){
     var
      x = (nat1.data[ofs1 + i] >>> 0) - (nat2.data[ofs2 + i] >>> 0) - borrow;
     nat1.data[ofs1 + i] = x;
     if(x >= 0) borrow = 0; else borrow = 1;
    }
    return decr_nat(nat1, ofs1 + len2, len1 - len2, borrow == 1 ? 0 : 1);
   }
   function compare_nat(nat1, ofs1, len1, nat2, ofs2, len2){
    var
     a = num_digits_nat(nat1, ofs1, len1),
     b = num_digits_nat(nat2, ofs2, len2);
    if(a > b) return 1;
    if(a < b) return - 1;
    for(var i = len1 - 1; i >= 0; i--){
     if(nat1.data[ofs1 + i] >>> 0 > nat2.data[ofs2 + i] >>> 0) return 1;
     if(nat1.data[ofs1 + i] >>> 0 < nat2.data[ofs2 + i] >>> 0) return - 1;
    }
    return 0;
   }
   function div_nat(nat1, ofs1, len1, nat2, ofs2, len2){
    if(len2 == 1){
     div_digit_nat(nat1, ofs1 + 1, nat1, ofs1, nat1, ofs1, len1, nat2, ofs2);
     return 0;
    }
    var s = num_leading_zero_bits_in_digit(nat2, ofs2 + len2 - 1);
    shift_left_nat(nat2, ofs2, len2, nat_of_array([0]), 0, s);
    shift_left_nat(nat1, ofs1, len1, nat_of_array([0]), 0, s);
    var d = (nat2.data[ofs2 + len2 - 1] >>> 0) + 1, a = create_nat(len2 + 1);
    for(var i = len1 - 1; i >= len2; i--){
     var
      quo =
        d == 4294967296
         ? nat1.data[ofs1 + i] >>> 0
         : div_helper
            (nat1.data[ofs1 + i] >>> 0, nat1.data[ofs1 + i - 1] >>> 0, d)
           [0];
     set_to_zero_nat(a, 0, len2 + 1);
     mult_digit_nat(a, 0, len2 + 1, nat2, ofs2, len2, nat_of_array([quo]), 0);
     sub_nat(nat1, ofs1 + i - len2, len2 + 1, a, 0, len2 + 1, 1);
     while
     (nat1.data[ofs1 + i] != 0
      || compare_nat(nat1, ofs1 + i - len2, len2, nat2, ofs2, len2) >= 0){
      quo = quo + 1;
      sub_nat(nat1, ofs1 + i - len2, len2 + 1, nat2, ofs2, len2, 1);
     }
     nat1.data[ofs1 + i] = quo;
    }
    shift_right_nat(nat1, ofs1, len2, nat_of_array([0]), 0, s);
    shift_right_nat(nat2, ofs2, len2, nat_of_array([0]), 0, s);
    return 0;
   }
   function caml_ba_blit(src, dst){
    if(dst.dims.length != src.dims.length)
     caml_invalid_argument("Bigarray.blit: dimension mismatch");
    for(var i = 0; i < dst.dims.length; i++)
     if(dst.dims[i] != src.dims[i])
      caml_invalid_argument("Bigarray.blit: dimension mismatch");
    dst.data.set(src.data);
    return 0;
   }
   function is_digit_int(nat, ofs){if(nat.data[ofs] >= 0) return 1; return 0;}
   function caml_int64_div(x, y){return x.div(y);}
   function caml_js_html_entities(s){
    var entity = /^&#?[0-9a-zA-Z]+;$/;
    if(s.match(entity)){
     var str, temp = document.createElement("p");
     temp.innerHTML = s;
     str = temp.textContent || temp.innerText;
     temp = null;
     return str;
    }
    else
     caml_failwith("Invalid entity " + s);
   }
   function caml_string_unsafe_set(s, i, c){
    caml_failwith("caml_string_unsafe_set");
   }
   function caml_int64_of_float(x){
    if(x < 0) x = Math.ceil(x);
    return new
            MlInt64
            (x & 0xffffff,
             Math.floor(x * caml_int64_offset) & 0xffffff,
             Math.floor(x * caml_int64_offset * caml_int64_offset) & 0xffff);
   }
   function caml_ml_channel_size_64(chanid){
    var chan = caml_ml_channels[chanid];
    return caml_int64_of_float(chan.file.length());
   }
   function caml_ba_set_2(ba, i0, i1, v){
    ba.set(ba.offset([i0, i1]), v);
    return 0;
   }
   var
    caml_argv =
      function(){
        var process = globalThis.process, main = "a.out", args = [];
        if(process && process.argv && process.argv.length > 1){
         var argv = process.argv;
         main = argv[1];
         args = argv.slice(2);
        }
        var p = caml_string_of_jsstring(main), args2 = [0, p];
        for(var i = 0; i < args.length; i++)
         args2.push(caml_string_of_jsstring(args[i]));
        return args2;
       }
       (),
    caml_executable_name = caml_argv[1];
   function caml_js_eval_string(s){return eval(caml_jsstring_of_string(s));}
   function serialize_nat(writer, nat, sz){
    var len = nat.data.length;
    writer.write(32, len);
    for(var i = 0; i < len; i++) writer.write(32, nat.data[i]);
    sz[0] = len * 4;
    sz[1] = len * 8;
   }
   function caml_memprof_set(_control){return 0;}
   function caml_sys_exit(code){
    if(globalThis.quit) globalThis.quit(code);
    if(globalThis.process && globalThis.process.exit)
     globalThis.process.exit(code);
    caml_invalid_argument("Function 'exit' not implemented");
   }
   function caml_channel_descriptor(chanid){
    var chan = caml_ml_channels[chanid];
    return chan.fd;
   }
   function caml_js_from_array(a){return a.slice(1);}
   function caml_ba_reshape(ba, vind){
    vind = caml_js_from_array(vind);
    var new_dim = [], num_dims = vind.length;
    if(num_dims < 0 || num_dims > 16)
     caml_invalid_argument("Bigarray.reshape: bad number of dimensions");
    var num_elts = 1;
    for(var i = 0; i < num_dims; i++){
     new_dim[i] = vind[i];
     if(new_dim[i] < 0)
      caml_invalid_argument("Bigarray.reshape: negative dimension");
     num_elts = num_elts * new_dim[i];
    }
    var size = caml_ba_get_size(ba.dims);
    if(num_elts != size)
     caml_invalid_argument("Bigarray.reshape: size mismatch");
    return caml_ba_create_unsafe(ba.kind, ba.layout, new_dim, ba.data);
   }
   var caml_oo_last_id = 0;
   function caml_set_oo_id(b){b[2] = caml_oo_last_id++; return b;}
   function caml_gr_fill_rect(x, y, w, h){
    var s = caml_gr_state_get();
    s.context.fillRect(x, s.height - y, w, - h);
    return 0;
   }
   function caml_bigstring_blit_string_to_ba(str1, pos1, ba2, pos2, len){
    if(12 != ba2.kind)
     caml_invalid_argument("caml_bigstring_blit_string_to_ba: kind mismatch");
    if(len == 0) return 0;
    var ofs2 = ba2.offset(pos2);
    if(pos1 + len > caml_ml_string_length(str1)) caml_array_bound_error();
    if(ofs2 + len > ba2.data.length) caml_array_bound_error();
    var slice = caml_uint8_array_of_string(str1).slice(pos1, pos1 + len);
    ba2.data.set(slice, ofs2);
    return 0;
   }
   function caml_gr_set_window_title(name){
    var s = caml_gr_state_get();
    s.title = name;
    var jsname = caml_jsstring_of_string(name);
    if(s.set_title) s.set_title(jsname);
    return 0;
   }
   function caml_get_global_data(){return caml_global_data;}
   function caml_int64_shift_right_unsigned(x, s){return x.shift_right_unsigned(s);
   }
   function caml_ba_uint8_get16(ba, i0){
    var ofs = ba.offset(i0);
    if(ofs + 1 >= ba.data.length) caml_array_bound_error();
    var b1 = ba.get(ofs), b2 = ba.get(ofs + 1);
    return b1 | b2 << 8;
   }
   function caml_compare(a, b){return caml_compare_val(a, b, true);}
   var
    caml_MD5Transform =
      function(){
        function add(x, y){return x + y | 0;}
        function xx(q, a, b, x, s, t){
         a = add(add(a, q), add(x, t));
         return add(a << s | a >>> 32 - s, b);
        }
        function ff(a, b, c, d, x, s, t){
         return xx(b & c | ~ b & d, a, b, x, s, t);
        }
        function gg(a, b, c, d, x, s, t){
         return xx(b & d | c & ~ d, a, b, x, s, t);
        }
        function hh(a, b, c, d, x, s, t){return xx(b ^ c ^ d, a, b, x, s, t);}
        function ii(a, b, c, d, x, s, t){
         return xx(c ^ (b | ~ d), a, b, x, s, t);
        }
        return function(w, buffer){
         var a = w[0], b = w[1], c = w[2], d = w[3];
         a = ff(a, b, c, d, buffer[0], 7, 0xD76AA478);
         d = ff(d, a, b, c, buffer[1], 12, 0xE8C7B756);
         c = ff(c, d, a, b, buffer[2], 17, 0x242070DB);
         b = ff(b, c, d, a, buffer[3], 22, 0xC1BDCEEE);
         a = ff(a, b, c, d, buffer[4], 7, 0xF57C0FAF);
         d = ff(d, a, b, c, buffer[5], 12, 0x4787C62A);
         c = ff(c, d, a, b, buffer[6], 17, 0xA8304613);
         b = ff(b, c, d, a, buffer[7], 22, 0xFD469501);
         a = ff(a, b, c, d, buffer[8], 7, 0x698098D8);
         d = ff(d, a, b, c, buffer[9], 12, 0x8B44F7AF);
         c = ff(c, d, a, b, buffer[10], 17, 0xFFFF5BB1);
         b = ff(b, c, d, a, buffer[11], 22, 0x895CD7BE);
         a = ff(a, b, c, d, buffer[12], 7, 0x6B901122);
         d = ff(d, a, b, c, buffer[13], 12, 0xFD987193);
         c = ff(c, d, a, b, buffer[14], 17, 0xA679438E);
         b = ff(b, c, d, a, buffer[15], 22, 0x49B40821);
         a = gg(a, b, c, d, buffer[1], 5, 0xF61E2562);
         d = gg(d, a, b, c, buffer[6], 9, 0xC040B340);
         c = gg(c, d, a, b, buffer[11], 14, 0x265E5A51);
         b = gg(b, c, d, a, buffer[0], 20, 0xE9B6C7AA);
         a = gg(a, b, c, d, buffer[5], 5, 0xD62F105D);
         d = gg(d, a, b, c, buffer[10], 9, 0x02441453);
         c = gg(c, d, a, b, buffer[15], 14, 0xD8A1E681);
         b = gg(b, c, d, a, buffer[4], 20, 0xE7D3FBC8);
         a = gg(a, b, c, d, buffer[9], 5, 0x21E1CDE6);
         d = gg(d, a, b, c, buffer[14], 9, 0xC33707D6);
         c = gg(c, d, a, b, buffer[3], 14, 0xF4D50D87);
         b = gg(b, c, d, a, buffer[8], 20, 0x455A14ED);
         a = gg(a, b, c, d, buffer[13], 5, 0xA9E3E905);
         d = gg(d, a, b, c, buffer[2], 9, 0xFCEFA3F8);
         c = gg(c, d, a, b, buffer[7], 14, 0x676F02D9);
         b = gg(b, c, d, a, buffer[12], 20, 0x8D2A4C8A);
         a = hh(a, b, c, d, buffer[5], 4, 0xFFFA3942);
         d = hh(d, a, b, c, buffer[8], 11, 0x8771F681);
         c = hh(c, d, a, b, buffer[11], 16, 0x6D9D6122);
         b = hh(b, c, d, a, buffer[14], 23, 0xFDE5380C);
         a = hh(a, b, c, d, buffer[1], 4, 0xA4BEEA44);
         d = hh(d, a, b, c, buffer[4], 11, 0x4BDECFA9);
         c = hh(c, d, a, b, buffer[7], 16, 0xF6BB4B60);
         b = hh(b, c, d, a, buffer[10], 23, 0xBEBFBC70);
         a = hh(a, b, c, d, buffer[13], 4, 0x289B7EC6);
         d = hh(d, a, b, c, buffer[0], 11, 0xEAA127FA);
         c = hh(c, d, a, b, buffer[3], 16, 0xD4EF3085);
         b = hh(b, c, d, a, buffer[6], 23, 0x04881D05);
         a = hh(a, b, c, d, buffer[9], 4, 0xD9D4D039);
         d = hh(d, a, b, c, buffer[12], 11, 0xE6DB99E5);
         c = hh(c, d, a, b, buffer[15], 16, 0x1FA27CF8);
         b = hh(b, c, d, a, buffer[2], 23, 0xC4AC5665);
         a = ii(a, b, c, d, buffer[0], 6, 0xF4292244);
         d = ii(d, a, b, c, buffer[7], 10, 0x432AFF97);
         c = ii(c, d, a, b, buffer[14], 15, 0xAB9423A7);
         b = ii(b, c, d, a, buffer[5], 21, 0xFC93A039);
         a = ii(a, b, c, d, buffer[12], 6, 0x655B59C3);
         d = ii(d, a, b, c, buffer[3], 10, 0x8F0CCC92);
         c = ii(c, d, a, b, buffer[10], 15, 0xFFEFF47D);
         b = ii(b, c, d, a, buffer[1], 21, 0x85845DD1);
         a = ii(a, b, c, d, buffer[8], 6, 0x6FA87E4F);
         d = ii(d, a, b, c, buffer[15], 10, 0xFE2CE6E0);
         c = ii(c, d, a, b, buffer[6], 15, 0xA3014314);
         b = ii(b, c, d, a, buffer[13], 21, 0x4E0811A1);
         a = ii(a, b, c, d, buffer[4], 6, 0xF7537E82);
         d = ii(d, a, b, c, buffer[11], 10, 0xBD3AF235);
         c = ii(c, d, a, b, buffer[2], 15, 0x2AD7D2BB);
         b = ii(b, c, d, a, buffer[9], 21, 0xEB86D391);
         w[0] = add(a, w[0]);
         w[1] = add(b, w[1]);
         w[2] = add(c, w[2]);
         w[3] = add(d, w[3]);};
       }
       ();
   function caml_MD5Update(ctx, input, input_len){
    var in_buf = ctx.len & 0x3f, input_pos = 0;
    ctx.len += input_len;
    if(in_buf){
     var missing = 64 - in_buf;
     if(input_len < missing){
      ctx.b8.set(input.subarray(0, input_len), in_buf);
      return;
     }
     ctx.b8.set(input.subarray(0, missing), in_buf);
     caml_MD5Transform(ctx.w, ctx.b32);
     input_len -= missing;
     input_pos += missing;
    }
    while(input_len >= 64){
     ctx.b8.set(input.subarray(input_pos, input_pos + 64), 0);
     caml_MD5Transform(ctx.w, ctx.b32);
     input_len -= 64;
     input_pos += 64;
    }
    if(input_len)
     ctx.b8.set(input.subarray(input_pos, input_pos + input_len), 0);
   }
   function caml_runtime_events_read_poll(cursor, callbacks, num){return 0;}
   function caml_fresh_oo_id(){return caml_oo_last_id++;}
   function caml_int64_to_float(x){return x.toFloat();}
   function caml_ba_get_1(ba, i0){return ba.get(ba.offset(i0));}
   function caml_bigstring_memcmp(s1, pos1, s2, pos2, len){
    for(var i = 0; i < len; i++){
     var a = caml_ba_get_1(s1, pos1 + i), b = caml_ba_get_1(s2, pos2 + i);
     if(a < b) return - 1;
     if(a > b) return 1;
    }
    return 0;
   }
   function caml_new_string(s){return caml_string_of_jsbytes(s);}
   function caml_erf_float(x){
    var
     a1 = 0.254829592,
     a2 = - 0.284496736,
     a3 = 1.421413741,
     a4 = - 1.453152027,
     a5 = 1.061405429,
     p = 0.3275911,
     sign = 1;
    if(x < 0) sign = - 1;
    x = Math.abs(x);
    var
     t = 1.0 / (1.0 + p * x),
     y =
       1.0
       -
        ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t
        * Math.exp(- (x * x));
    return sign * y;
   }
   function caml_ba_uint8_get32(ba, i0){
    var ofs = ba.offset(i0);
    if(ofs + 3 >= ba.data.length) caml_array_bound_error();
    var
     b1 = ba.get(ofs + 0),
     b2 = ba.get(ofs + 1),
     b3 = ba.get(ofs + 2),
     b4 = ba.get(ofs + 3);
    return b1 << 0 | b2 << 8 | b3 << 16 | b4 << 24;
   }
   function caml_raw_backtrace_length(){return 0;}
   function caml_str_initialize(unit){return 0;}
   function caml_obj_block(tag, size){
    var o = new Array(size + 1);
    o[0] = tag;
    for(var i = 1; i <= size; i++) o[i] = 0;
    return o;
   }
   function caml_gr_clear_graph(){
    var s = caml_gr_state_get();
    s.canvas.width = s.width;
    s.canvas.height = s.height;
    return 0;
   }
   function bigstring_to_array_buffer(bs){return bs.data.buffer;}
   function caml_sys_const_naked_pointers_checked(_unit){return 0;}
   function lxor_digit_nat(nat1, ofs1, nat2, ofs2){nat1.data[ofs1] ^= nat2.data[ofs2]; return 0;
   }
   function caml_obj_add_offset(v, offset){
    caml_failwith("Obj.add_offset is not supported");
   }
   function caml_final_release(){return 0;}
   var caml_marshal_header_size = 20;
   function caml_js_to_array(a){
    var len = a.length, b = new Array(len + 1);
    b[0] = 0;
    for(var i = 0; i < len; i++) b[i + 1] = a[i];
    return b;
   }
   function caml_sys_is_regular_file(name){
    var root = resolve_fs_device(name);
    return root.device.isFile(root.rest);
   }
   function caml_gr_plot(x, y){
    var
     s = caml_gr_state_get(),
     im = s.context.createImageData(1, 1),
     d = im.data,
     color = s.color;
    d[0] = color >> 16 & 0xff;
    d[1] = color >> 8 & 0xff, d[2] = color >> 0 & 0xff;
    d[3] = 0xFF;
    s.x = x;
    s.y = y;
    s.context.putImageData(im, x, s.height - y);
    return 0;
   }
   function caml_bytes_set64(s, i, i64){
    if(i >>> 0 >= s.l - 7) caml_bytes_bound_error();
    var a = caml_int64_to_bytes(i64);
    for(var j = 0; j < 8; j++) caml_bytes_unsafe_set(s, i + 7 - j, a[j]);
    return 0;
   }
   function caml_string_set16(s, i, i16){caml_failwith("caml_string_set16");}
   function caml_int64_bswap(x){
    var y = caml_int64_to_bytes(x);
    return caml_int64_of_bytes
            ([y[7], y[6], y[5], y[4], y[3], y[2], y[1], y[0]]);
   }
   function caml_gc_major(unit){
    if(typeof globalThis.gc == "function") globalThis.gc();
    return 0;
   }
   function caml_lex_array(s){
    s = caml_jsbytes_of_string(s);
    var l = s.length / 2, a = new Array(l);
    for(var i = 0; i < l; i++)
     a[i] = (s.charCodeAt(2 * i) | s.charCodeAt(2 * i + 1) << 8) << 16 >> 16;
    return a;
   }
   function caml_lex_engine(tbl, start_state, lexbuf){
    var
     lex_buffer = 2,
     lex_buffer_len = 3,
     lex_start_pos = 5,
     lex_curr_pos = 6,
     lex_last_pos = 7,
     lex_last_action = 8,
     lex_eof_reached = 9,
     lex_base = 1,
     lex_backtrk = 2,
     lex_default = 3,
     lex_trans = 4,
     lex_check = 5;
    if(! tbl.lex_default){
     tbl.lex_base = caml_lex_array(tbl[lex_base]);
     tbl.lex_backtrk = caml_lex_array(tbl[lex_backtrk]);
     tbl.lex_check = caml_lex_array(tbl[lex_check]);
     tbl.lex_trans = caml_lex_array(tbl[lex_trans]);
     tbl.lex_default = caml_lex_array(tbl[lex_default]);
    }
    var
     c,
     state = start_state,
     buffer = caml_uint8_array_of_bytes(lexbuf[lex_buffer]);
    if(state >= 0){
     lexbuf[lex_last_pos] = lexbuf[lex_start_pos] = lexbuf[lex_curr_pos];
     lexbuf[lex_last_action] = - 1;
    }
    else
     state = - state - 1;
    for(;;){
     var base = tbl.lex_base[state];
     if(base < 0) return - base - 1;
     var backtrk = tbl.lex_backtrk[state];
     if(backtrk >= 0){
      lexbuf[lex_last_pos] = lexbuf[lex_curr_pos];
      lexbuf[lex_last_action] = backtrk;
     }
     if(lexbuf[lex_curr_pos] >= lexbuf[lex_buffer_len])
      if(lexbuf[lex_eof_reached] == 0) return - state - 1; else c = 256;
     else{c = buffer[lexbuf[lex_curr_pos]]; lexbuf[lex_curr_pos]++;}
     if(tbl.lex_check[base + c] == state)
      state = tbl.lex_trans[base + c];
     else
      state = tbl.lex_default[state];
     if(state < 0){
      lexbuf[lex_curr_pos] = lexbuf[lex_last_pos];
      if(lexbuf[lex_last_action] == - 1)
       caml_failwith("lexing: empty token");
      else
       return lexbuf[lex_last_action];
     }
     else if(c == 256) lexbuf[lex_eof_reached] = 0;
    }
   }
   function caml_sys_file_exists(name){
    var root = resolve_fs_device(name);
    return root.device.exists(root.rest);
   }
   function caml_convert_raw_backtrace_slot(){
    caml_failwith("caml_convert_raw_backtrace_slot");
   }
   function caml_array_sub(a, i, len){
    var a2 = new Array(len + 1);
    a2[0] = 0;
    for(var i2 = 1, i1 = i + 1; i2 <= len; i2++, i1++) a2[i2] = a[i1];
    return a2;
   }
   function caml_bytes_equal(s1, s2){
    if(s1 === s2) return 1;
    s1.t & 6 && caml_convert_string_to_bytes(s1);
    s2.t & 6 && caml_convert_string_to_bytes(s2);
    return s1.c == s2.c ? 1 : 0;
   }
   function caml_gr_size_x(){var s = caml_gr_state_get(); return s.width;}
   function caml_ml_debug_info_status(){return 0;}
   function caml_atomic_fetch_add(ref, i){
    var old = ref[1];
    ref[1] += i;
    return old;
   }
   var
    os_type =
      globalThis.process && globalThis.process.platform
       && globalThis.process.platform == "win32"
       ? "Cygwin"
       : "Unix";
   function caml_sys_const_ostype_cygwin(){return os_type == "Cygwin" ? 1 : 0;
   }
   function caml_cosh_float(x){return Math.cosh(x);}
   function MlMutex(){this.locked = false;}
   function caml_ml_mutex_new(unit){return new MlMutex();}
   var caml_ephe_key_offset = 3;
   function caml_ephe_check_key(x, i){
    var weak = x[caml_ephe_key_offset + i];
    if(globalThis.WeakRef && weak instanceof globalThis.WeakRef)
     weak = weak.deref();
    return weak === undefined ? 0 : 1;
   }
   function caml_hash_mix_final(h){
    h ^= h >>> 16;
    h = caml_mul(h, 0x85ebca6b | 0);
    h ^= h >>> 13;
    h = caml_mul(h, 0xc2b2ae35 | 0);
    h ^= h >>> 16;
    return h;
   }
   function caml_gr_text_size(txt){
    var
     s = caml_gr_state_get(),
     w = s.context.measureText(caml_jsstring_of_string(txt)).width;
    return [0, w, s.text_size];
   }
   function caml_lex_run_mem(s, i, mem, curr_pos){
    for(;;){
     var dst = s.charCodeAt(i);
     i++;
     if(dst == 0xff) return;
     var src = s.charCodeAt(i);
     i++;
     if(src == 0xff)
      mem[dst + 1] = curr_pos;
     else
      mem[dst + 1] = mem[src + 1];
    }
   }
   function caml_lex_run_tag(s, i, mem){
    for(;;){
     var dst = s.charCodeAt(i);
     i++;
     if(dst == 0xff) return;
     var src = s.charCodeAt(i);
     i++;
     if(src == 0xff) mem[dst + 1] = - 1; else mem[dst + 1] = mem[src + 1];
    }
   }
   function caml_new_lex_engine(tbl, start_state, lexbuf){
    var
     lex_buffer = 2,
     lex_buffer_len = 3,
     lex_start_pos = 5,
     lex_curr_pos = 6,
     lex_last_pos = 7,
     lex_last_action = 8,
     lex_eof_reached = 9,
     lex_mem = 10,
     lex_base = 1,
     lex_backtrk = 2,
     lex_default = 3,
     lex_trans = 4,
     lex_check = 5,
     lex_base_code = 6,
     lex_backtrk_code = 7,
     lex_default_code = 8,
     lex_trans_code = 9,
     lex_check_code = 10,
     lex_code = 11;
    if(! tbl.lex_default){
     tbl.lex_base = caml_lex_array(tbl[lex_base]);
     tbl.lex_backtrk = caml_lex_array(tbl[lex_backtrk]);
     tbl.lex_check = caml_lex_array(tbl[lex_check]);
     tbl.lex_trans = caml_lex_array(tbl[lex_trans]);
     tbl.lex_default = caml_lex_array(tbl[lex_default]);
    }
    if(! tbl.lex_default_code){
     tbl.lex_base_code = caml_lex_array(tbl[lex_base_code]);
     tbl.lex_backtrk_code = caml_lex_array(tbl[lex_backtrk_code]);
     tbl.lex_check_code = caml_lex_array(tbl[lex_check_code]);
     tbl.lex_trans_code = caml_lex_array(tbl[lex_trans_code]);
     tbl.lex_default_code = caml_lex_array(tbl[lex_default_code]);
    }
    if(tbl.lex_code == null)
     tbl.lex_code = caml_jsbytes_of_string(tbl[lex_code]);
    var
     c,
     state = start_state,
     buffer = caml_uint8_array_of_bytes(lexbuf[lex_buffer]);
    if(state >= 0){
     lexbuf[lex_last_pos] = lexbuf[lex_start_pos] = lexbuf[lex_curr_pos];
     lexbuf[lex_last_action] = - 1;
    }
    else
     state = - state - 1;
    for(;;){
     var base = tbl.lex_base[state];
     if(base < 0){
      var pc_off = tbl.lex_base_code[state];
      caml_lex_run_tag(tbl.lex_code, pc_off, lexbuf[lex_mem]);
      return - base - 1;
     }
     var backtrk = tbl.lex_backtrk[state];
     if(backtrk >= 0){
      var pc_off = tbl.lex_backtrk_code[state];
      caml_lex_run_tag(tbl.lex_code, pc_off, lexbuf[lex_mem]);
      lexbuf[lex_last_pos] = lexbuf[lex_curr_pos];
      lexbuf[lex_last_action] = backtrk;
     }
     if(lexbuf[lex_curr_pos] >= lexbuf[lex_buffer_len])
      if(lexbuf[lex_eof_reached] == 0) return - state - 1; else c = 256;
     else{c = buffer[lexbuf[lex_curr_pos]]; lexbuf[lex_curr_pos]++;}
     var pstate = state;
     if(tbl.lex_check[base + c] == state)
      state = tbl.lex_trans[base + c];
     else
      state = tbl.lex_default[state];
     if(state < 0){
      lexbuf[lex_curr_pos] = lexbuf[lex_last_pos];
      if(lexbuf[lex_last_action] == - 1)
       caml_failwith("lexing: empty token");
      else
       return lexbuf[lex_last_action];
     }
     else{
      var base_code = tbl.lex_base_code[pstate], pc_off;
      if(tbl.lex_check_code[base_code + c] == pstate)
       pc_off = tbl.lex_trans_code[base_code + c];
      else
       pc_off = tbl.lex_default_code[pstate];
      if(pc_off > 0)
       caml_lex_run_mem
        (tbl.lex_code, pc_off, lexbuf[lex_mem], lexbuf[lex_curr_pos]);
      if(c == 256) lexbuf[lex_eof_reached] = 0;
     }
    }
   }
   function caml_ba_uint8_set64(ba, i0, v){
    var ofs = ba.offset(i0);
    if(ofs + 7 >= ba.data.length) caml_array_bound_error();
    var v = caml_int64_to_bytes(v);
    for(var i = 0; i < 8; i++) ba.set(ofs + i, v[7 - i]);
    return 0;
   }
   function caml_sys_executable_name(a){return caml_executable_name;}
   function caml_lessequal(x, y){
    return + (caml_compare_val(x, y, false) <= 0);
   }
   function caml_acosh_float(x){return Math.acosh(x);}
   function caml_MD5Init(){
    var
     buffer = new ArrayBuffer(64),
     b32 = new Uint32Array(buffer),
     b8 = new Uint8Array(buffer);
    return {len: 0,
            w:
            new Uint32Array([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476]),
            b32: b32,
            b8: b8};
   }
   function caml_ml_flush(chanid){
    var chan = caml_ml_channels[chanid];
    if(! chan.opened) caml_raise_sys_error("Cannot flush a closed channel");
    if(! chan.buffer || chan.buffer_curr == 0) return 0;
    if(chan.output)
     chan.output(caml_subarray_to_jsbytes(chan.buffer, 0, chan.buffer_curr));
    else
     chan.file.write(chan.offset, chan.buffer, 0, chan.buffer_curr);
    chan.offset += chan.buffer_curr;
    chan.buffer_curr = 0;
    return 0;
   }
   function caml_seek_out(chanid, pos){
    caml_ml_flush(chanid);
    var chan = caml_ml_channels[chanid];
    chan.offset = pos;
    return 0;
   }
   function caml_ml_seek_out_64(chanid, pos){
    var pos = caml_int64_to_float(pos);
    return caml_seek_out(chanid, pos);
   }
   function compare_nat_real(nat1, nat2){
    return compare_nat(nat1, 0, nat1.data.length, nat2, 0, nat2.data.length);
   }
   function caml_gc_set(_control){return 0;}
   function caml_js_get(o, f){return o[f];}
   function caml_unix_isatty(fileDescriptor){
    if(fs_node_supported()){
     var tty = require("tty");
     return tty.isatty(fileDescriptor) ? 1 : 0;
    }
    else
     return 0;
   }
   function caml_ml_set_buffered(chanid, v){
    caml_ml_channels[chanid].buffered = v;
    if(! v) caml_ml_flush(chanid);
    return 0;
   }
   function caml_gc_compaction(){return 0;}
   function caml_ephe_get_key(x, i){
    if(i < 0 || caml_ephe_key_offset + i >= x.length)
     caml_invalid_argument("Weak.get_key");
    var weak = x[caml_ephe_key_offset + i];
    if(globalThis.WeakRef && weak instanceof globalThis.WeakRef)
     weak = weak.deref();
    return weak === undefined ? 0 : [0, weak];
   }
   function caml_unix_localtime(t){
    var
     d = new Date(t * 1000),
     d_num = d.getTime(),
     januaryfirst = new Date(d.getFullYear(), 0, 1).getTime(),
     doy = Math.floor((d_num - januaryfirst) / 86400000),
     jan = new Date(d.getFullYear(), 0, 1),
     jul = new Date(d.getFullYear(), 6, 1),
     stdTimezoneOffset =
       Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
    return [0,
            d.getSeconds(),
            d.getMinutes(),
            d.getHours(),
            d.getDate(),
            d.getMonth(),
            d.getFullYear() - 1900,
            d.getDay(),
            doy,
            d.getTimezoneOffset() < stdTimezoneOffset | 0];
   }
   function caml_unix_mktime(tm){
    var
     d = new Date(tm[6] + 1900, tm[5], tm[4], tm[3], tm[2], tm[1]).getTime(),
     t = Math.floor(d / 1000),
     tm2 = caml_unix_localtime(t);
    return [0, t, tm2];
   }
   function caml_bigstring_blit_bytes_to_ba(str1, pos1, ba2, pos2, len){
    if(12 != ba2.kind)
     caml_invalid_argument("caml_bigstring_blit_string_to_ba: kind mismatch");
    if(len == 0) return 0;
    var ofs2 = ba2.offset(pos2);
    if(pos1 + len > caml_ml_bytes_length(str1)) caml_array_bound_error();
    if(ofs2 + len > ba2.data.length) caml_array_bound_error();
    var slice = caml_uint8_array_of_bytes(str1).slice(pos1, pos1 + len);
    ba2.data.set(slice, ofs2);
    return 0;
   }
   var caml_sys_fds = new Array(3);
   function caml_sys_close(fd){
    var file = caml_sys_fds[fd];
    if(file) file.close();
    delete caml_sys_fds[fd];
    return 0;
   }
   function caml_ml_close_channel(chanid){
    var chan = caml_ml_channels[chanid];
    chan.opened = false;
    caml_sys_close(chan.fd);
    return 0;
   }
   function caml_atomic_exchange(ref, v){
    var r = ref[1];
    ref[1] = v;
    return r;
   }
   function caml_sys_isatty(_chan){return 0;}
   function is_digit_zero(nat, ofs){
    if(nat.data[ofs] == 0) return 1;
    return 0;
   }
   function caml_unix_lstat(name){
    var root = resolve_fs_device(name);
    if(! root.device.lstat) caml_failwith("caml_unix_lstat: not implemented");
    return root.device.lstat(root.rest, true);
   }
   function caml_unix_lstat_64(name){
    var r = caml_unix_lstat(name);
    r[9] = caml_int64_of_int32(r[9]);
   }
   function caml_js_set(o, f, v){o[f] = v; return 0;}
   function caml_array_get(array, index){
    if(index < 0 || index >= array.length - 1) caml_array_bound_error();
    return array[index + 1];
   }
   function caml_continuation_use_noexc(cont){
    var stack = cont[1];
    cont[1] = 0;
    return stack;
   }
   function caml_unix_rmdir(name){
    var root = resolve_fs_device(name);
    if(! root.device.rmdir) caml_failwith("caml_unix_rmdir: not implemented");
    return root.device.rmdir(root.rest, true);
   }
   function caml_log2_float(x){return Math.log2(x);}
   function caml_gc_huge_fallback_count(unit){return 0;}
   function caml_runtime_events_resume(){return 0;}
   function caml_spacetime_only_works_for_native_code(){
    caml_failwith("Spacetime profiling only works for native code");
   }
   function caml_int64_sub(x, y){return x.sub(y);}
   function caml_seek_in(chanid, pos){
    var chan = caml_ml_channels[chanid];
    if(chan.refill != null) caml_raise_sys_error("Illegal seek");
    if
     (pos >= chan.offset - chan.buffer_max && pos <= chan.offset
      && chan.file.flags.binary)
     chan.buffer_curr = chan.buffer_max - (chan.offset - pos);
    else{chan.offset = pos; chan.buffer_curr = 0; chan.buffer_max = 0;}
    return 0;
   }
   function caml_ml_seek_in_64(chanid, pos){
    var pos = caml_int64_to_float(pos);
    return caml_seek_in(chanid, pos);
   }
   var caml_domain_id = 0;
   function caml_ml_mutex_unlock(t){t.locked = false; return 0;}
   var caml_domain_latest_idx = 1;
   function caml_domain_spawn(f, mutex){
    var id = caml_domain_latest_idx++, old = caml_domain_id;
    caml_domain_id = id;
    caml_callback(f, [0]);
    caml_domain_id = old;
    caml_ml_mutex_unlock(mutex);
    return id;
   }
   function caml_unix_mkdir(name, perm){
    var root = resolve_fs_device(name);
    if(! root.device.mkdir) caml_failwith("caml_unix_mkdir: not implemented");
    return root.device.mkdir(root.rest, perm, true);
   }
   function caml_int64_shift_left(x, s){return x.shift_left(s);}
   function caml_notequal(x, y){
    return + (caml_compare_val(x, y, false) != 0);
   }
   function caml_sys_const_int_size(){return 32;}
   function caml_js_wrap_callback(f){
    return function(){
     var len = arguments.length;
     if(len > 0){
      var args = new Array(len);
      for(var i = 0; i < len; i++) args[i] = arguments[i];
     }
     else
      args = [undefined];
     var res = caml_callback(f, args);
     return res instanceof Function ? caml_js_wrap_callback(res) : res;};
   }
   function caml_js_wrap_meth_callback(f){
    return function(){
     var len = arguments.length, args = new Array(len + 1);
     args[0] = this;
     for(var i = 0; i < len; i++) args[i + 1] = arguments[i];
     var res = caml_callback(f, args);
     return res instanceof Function ? caml_js_wrap_callback(res) : res;};
   }
   function caml_is_js(){return 1;}
   function caml_lazy_update_to_forward(o){
    caml_obj_update_tag(o, 244, 250);
    return 0;
   }
   function caml_ba_dim(ba, i){
    if(i < 0 || i >= ba.dims.length) caml_invalid_argument("Bigarray.dim");
    return ba.dims[i];
   }
   function caml_ba_dim_1(ba){return caml_ba_dim(ba, 0);}
   function caml_js_meth_call(o, f, args){
    return o[caml_jsstring_of_string(f)].apply(o, caml_js_from_array(args));
   }
   var caml_ephe_data_offset = 2;
   function caml_weak_create(n){
    if(n < 0) caml_invalid_argument("Weak.create");
    var x = [251, "caml_ephe_list_head"];
    x.length = caml_ephe_key_offset + n;
    return x;
   }
   function caml_ephe_create(n){var x = caml_weak_create(n); return x;}
   function caml_js_to_byte_string(s){return caml_string_of_jsbytes(s);}
   function caml_trampoline(res){
    var c = 1;
    while(res && res.joo_tramp){
     res = res.joo_tramp.apply(null, res.joo_args);
     c++;
    }
    return res;
   }
   function caml_maybe_print_stats(unit){return 0;}
   function caml_bytes_unsafe_get(s, i){
    switch(s.t & 6){
      default: if(i >= s.c.length) return 0;
      case 0:
       return s.c.charCodeAt(i);
      case 4:
       return s.c[i];
    }
   }
   function caml_bytes_get64(s, i){
    if(i >>> 0 >= s.l - 7) caml_bytes_bound_error();
    var a = new Array(8);
    for(var j = 0; j < 8; j++) a[7 - j] = caml_bytes_unsafe_get(s, i + j);
    return caml_int64_of_bytes(a);
   }
   var caml_custom_event_index = 0;
   function caml_runtime_events_user_register
   (event_name, event_tag, event_type){
    caml_custom_event_index += 1;
    return [0, caml_custom_event_index, event_name, event_type, event_tag];
   }
   function caml_unix_has_symlink(unit){return fs_node_supported() ? 1 : 0;}
   function caml_ephe_set_key(x, i, v){
    if(i < 0 || caml_ephe_key_offset + i >= x.length)
     caml_invalid_argument("Weak.set");
    if(v instanceof Object && globalThis.WeakRef){
     if(x[1].register) x[1].register(v, undefined, v);
     x[caml_ephe_key_offset + i] = new globalThis.WeakRef(v);
    }
    else
     x[caml_ephe_key_offset + i] = v;
    return 0;
   }
   function caml_ephe_unset_key(x, i){
    if(i < 0 || caml_ephe_key_offset + i >= x.length)
     caml_invalid_argument("Weak.set");
    if
     (globalThis.WeakRef
      && x[caml_ephe_key_offset + i] instanceof globalThis.WeakRef
      && x[1].unregister){
     var old = x[caml_ephe_key_offset + i].deref();
     if(old !== undefined){
      var count = 0;
      for(var j = caml_ephe_key_offset; j < x.length; j++){
       var key = x[j];
       if(key instanceof globalThis.WeakRef){
        key = key.deref();
        if(key === old) count++;
       }
      }
      if(count == 1) x[1].unregister(old);
     }
    }
    x[caml_ephe_key_offset + i] = undefined;
    return 0;
   }
   function caml_weak_set(x, i, v){
    if(v == 0) caml_ephe_unset_key(x, i); else caml_ephe_set_key(x, i, v[1]);
    return 0;
   }
   function caml_sys_remove(name){
    var root = resolve_fs_device(name), ok = root.device.unlink(root.rest);
    if(ok == 0) caml_raise_no_such_file(caml_jsbytes_of_string(name));
    return 0;
   }
   function caml_string_bound_error(){
    caml_invalid_argument("index out of bounds");
   }
   function caml_string_get32(s, i){
    if(i >>> 0 >= caml_ml_string_length(s) - 3) caml_string_bound_error();
    var
     b1 = caml_string_unsafe_get(s, i),
     b2 = caml_string_unsafe_get(s, i + 1),
     b3 = caml_string_unsafe_get(s, i + 2),
     b4 = caml_string_unsafe_get(s, i + 3);
    return b4 << 24 | b3 << 16 | b2 << 8 | b1;
   }
   function caml_bytes_get(s, i){
    if(i >>> 0 >= s.l) caml_bytes_bound_error();
    return caml_bytes_unsafe_get(s, i);
   }
   function caml_hypot_float(x, y){return Math.hypot(x, y);}
   function caml_js_call(f, o, args){
    return f.apply(o, caml_js_from_array(args));
   }
   function caml_sys_const_max_wosize(){return 0x7FFFFFFF / 4 | 0;}
   function caml_unix_inet_addr_of_string(){return 0;}
   function caml_hash_mix_bytes_arr(h, s){
    var len = s.length, i, w;
    for(i = 0; i + 4 <= len; i += 4){
     w = s[i] | s[i + 1] << 8 | s[i + 2] << 16 | s[i + 3] << 24;
     h = caml_hash_mix_int(h, w);
    }
    w = 0;
    switch(len & 3){
      case 3:
       w = s[i + 2] << 16;
      case 2:
       w |= s[i + 1] << 8;
      case 1:
       w |= s[i]; h = caml_hash_mix_int(h, w);
    }
    h ^= len;
    return h;
   }
   function caml_hash_mix_jsbytes(h, s){
    var len = s.length, i, w;
    for(i = 0; i + 4 <= len; i += 4){
     w =
      s.charCodeAt(i) | s.charCodeAt(i + 1) << 8 | s.charCodeAt(i + 2) << 16
      | s.charCodeAt(i + 3) << 24;
     h = caml_hash_mix_int(h, w);
    }
    w = 0;
    switch(len & 3){
      case 3:
       w = s.charCodeAt(i + 2) << 16;
      case 2:
       w |= s.charCodeAt(i + 1) << 8;
      case 1:
       w |= s.charCodeAt(i); h = caml_hash_mix_int(h, w);
    }
    h ^= len;
    return h;
   }
   function caml_ml_bytes_content(s){
    switch(s.t & 6){
      default: caml_convert_string_to_bytes(s);
      case 0:
       return s.c;
      case 4:
       return s.c;
    }
   }
   function caml_hash_mix_bytes(h, v){
    var content = caml_ml_bytes_content(v);
    return typeof content === "string"
            ? caml_hash_mix_jsbytes(h, content)
            : caml_hash_mix_bytes_arr(h, content);
   }
   function caml_bytes_lessthan(s1, s2){
    s1.t & 6 && caml_convert_string_to_bytes(s1);
    s2.t & 6 && caml_convert_string_to_bytes(s2);
    return s1.c < s2.c ? 1 : 0;
   }
   function caml_erfc_float(x){return 1 - caml_erf_float(x);}
   function caml_gr_fill_poly(ar){
    var s = caml_gr_state_get();
    s.context.beginPath();
    s.context.moveTo(ar[1][1], s.height - ar[1][2]);
    for(var i = 2; i < ar.length; i++)
     s.context.lineTo(ar[i][1], s.height - ar[i][2]);
    s.context.lineTo(ar[1][1], s.height - ar[1][2]);
    s.context.fill();
    return 0;
   }
   function caml_gc_quick_stat(){
    return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
   }
   function caml_ml_input_char(chanid){
    var chan = caml_ml_channels[chanid];
    if(chan.buffer_curr >= chan.buffer_max){
     chan.buffer_curr = 0;
     chan.buffer_max = 0;
     caml_refill(chan);
    }
    if(chan.buffer_curr >= chan.buffer_max) caml_raise_end_of_file();
    var res = chan.buffer[chan.buffer_curr];
    chan.buffer_curr++;
    return res;
   }
   function caml_ml_input_int(chanid){
    var chan = caml_ml_channels[chanid], res = 0;
    for(var i = 0; i < 4; i++)
     res = (res << 8) + caml_ml_input_char(chanid) | 0;
    return res | 0;
   }
   function caml_gr_display_mode(){
    caml_failwith("caml_gr_display_mode not Implemented");
   }
   function caml_obj_reachable_words(o){return 0;}
   function nth_digit_nat(nat, ofs){return nat.data[ofs];}
   function caml_array_blit(a1, i1, a2, i2, len){
    if(i2 <= i1)
     for(var j = 1; j <= len; j++) a2[i2 + j] = a1[i1 + j];
    else
     for(var j = len; j >= 1; j--) a2[i2 + j] = a1[i1 + j];
    return 0;
   }
   function caml_float_of_string(s){
    var res;
    s = caml_jsbytes_of_string(s);
    res = + s;
    if(s.length > 0 && res === res) return res;
    s = s.replace(/_/g, "");
    res = + s;
    if(s.length > 0 && res === res || /^[+-]?nan$/i.test(s)) return res;
    var m = /^ *([+-]?)0x([0-9a-f]+)\.?([0-9a-f]*)(p([+-]?[0-9]+))?/i.exec(s);
    if(m){
     var
      m3 = m[3].replace(/0+$/, ""),
      mantissa = parseInt(m[1] + m[2] + m3, 16),
      exponent = (m[5] | 0) - 4 * m3.length;
     res = mantissa * Math.pow(2, exponent);
     return res;
    }
    if(/^\+?inf(inity)?$/i.test(s)) return Infinity;
    if(/^-inf(inity)?$/i.test(s)) return - Infinity;
    caml_failwith("float_of_string");
   }
   function caml_sys_getcwd(){
    return caml_string_of_jsbytes(caml_current_dir);
   }
   function caml_int64_add(x, y){return x.add(y);}
   function caml_int64_mul(x, y){return x.mul(y);}
   function caml_int64_ult(x, y){return x.ucompare(y) < 0;}
   function caml_parse_sign_and_base(s){
    var i = 0, len = caml_ml_string_length(s), base = 10, sign = 1;
    if(len > 0)
     switch(caml_string_unsafe_get(s, i)){
       case 45:
        i++; sign = - 1; break;
       case 43:
        i++; sign = 1; break;
     }
    if(i + 1 < len && caml_string_unsafe_get(s, i) == 48)
     switch(caml_string_unsafe_get(s, i + 1)){
       case 120:
       case 88:
        base = 16; i += 2; break;
       case 111:
       case 79:
        base = 8; i += 2; break;
       case 98:
       case 66:
        base = 2; i += 2; break;
       case 117:
       case 85:
        i += 2; break;
     }
    return [i, sign, base];
   }
   function caml_parse_digit(c){
    if(c >= 48 && c <= 57) return c - 48;
    if(c >= 65 && c <= 90) return c - 55;
    if(c >= 97 && c <= 122) return c - 87;
    return - 1;
   }
   function caml_int64_of_string(s){
    var
     r = caml_parse_sign_and_base(s),
     i = r[0],
     sign = r[1],
     base = r[2],
     base64 = caml_int64_of_int32(base),
     threshold =
       new MlInt64(0xffffff, 0xfffffff, 0xffff).udivmod(base64).quotient,
     c = caml_string_unsafe_get(s, i),
     d = caml_parse_digit(c);
    if(d < 0 || d >= base) caml_failwith("int_of_string");
    var res = caml_int64_of_int32(d);
    for(;;){
     i++;
     c = caml_string_unsafe_get(s, i);
     if(c == 95) continue;
     d = caml_parse_digit(c);
     if(d < 0 || d >= base) break;
     if(caml_int64_ult(threshold, res)) caml_failwith("int_of_string");
     d = caml_int64_of_int32(d);
     res = caml_int64_add(caml_int64_mul(base64, res), d);
     if(caml_int64_ult(res, d)) caml_failwith("int_of_string");
    }
    if(i != caml_ml_string_length(s)) caml_failwith("int_of_string");
    if(base == 10 && caml_int64_ult(new MlInt64(0, 0, 0x8000), res))
     caml_failwith("int_of_string");
    if(sign < 0) res = caml_int64_neg(res);
    return res;
   }
   function caml_ba_set_1(ba, i0, v){ba.set(ba.offset(i0), v); return 0;}
   function caml_int64_xor(x, y){return x.xor(y);}
   function caml_int64_or(x, y){return x.or(y);}
   function caml_lxm_next(v){
    function shift_l(x, k){return caml_int64_shift_left(x, k);}
    function shift_r(x, k){return caml_int64_shift_right_unsigned(x, k);}
    function or(a, b){return caml_int64_or(a, b);}
    function xor(a, b){return caml_int64_xor(a, b);}
    function add(a, b){return caml_int64_add(a, b);}
    function mul(a, b){return caml_int64_mul(a, b);}
    function rotl(x, k){return or(shift_l(x, k), shift_r(x, 64 - k));}
    function get(a, i){return caml_ba_get_1(a, i);}
    function set(a, i, x){return caml_ba_set_1(a, i, x);}
    var
     M = caml_int64_of_string(caml_new_string("0xd1342543de82ef95")),
     daba = caml_int64_of_string(caml_new_string("0xdaba0b6eb09322e3")),
     z,
     q0,
     q1,
     st = v,
     a = get(st, 0),
     s = get(st, 1),
     x0 = get(st, 2),
     x1 = get(st, 3);
    z = add(s, x0);
    z = mul(xor(z, shift_r(z, 32)), daba);
    z = mul(xor(z, shift_r(z, 32)), daba);
    z = xor(z, shift_r(z, 32));
    set(st, 1, add(mul(s, M), a));
    var q0 = x0, q1 = x1;
    q1 = xor(q1, q0);
    q0 = rotl(q0, 24);
    q0 = xor(xor(q0, q1), shift_l(q1, 16));
    q1 = rotl(q1, 37);
    set(st, 2, q0);
    set(st, 3, q1);
    return z;
   }
   function caml_sys_const_big_endian(){return 0;}
   function caml_list_to_js_array(l){
    var a = [];
    for(; l !== 0; l = l[2]) a.push(l[1]);
    return a;
   }
   var
    caml_output_val =
      function(){
        function Writer(){this.chunk = [];}
        Writer.prototype =
         {chunk_idx: 20,
          block_len: 0,
          obj_counter: 0,
          size_32: 0,
          size_64: 0,
          write:
          function(size, value){
           for(var i = size - 8; i >= 0; i -= 8)
            this.chunk[this.chunk_idx++] = value >> i & 0xFF;
          },
          write_at:
          function(pos, size, value){
           var pos = pos;
           for(var i = size - 8; i >= 0; i -= 8)
            this.chunk[pos++] = value >> i & 0xFF;
          },
          write_code:
          function(size, code, value){
           this.chunk[this.chunk_idx++] = code;
           for(var i = size - 8; i >= 0; i -= 8)
            this.chunk[this.chunk_idx++] = value >> i & 0xFF;
          },
          write_shared:
          function(offset){
           if(offset < 1 << 8)
            this.write_code(8, 0x04, offset);
           else if(offset < 1 << 16)
            this.write_code(16, 0x05, offset);
           else
            this.write_code(32, 0x06, offset);
          },
          pos: function(){return this.chunk_idx;},
          finalize:
          function(){
           this.block_len = this.chunk_idx - 20;
           this.chunk_idx = 0;
           this.write(32, 0x8495A6BE);
           this.write(32, this.block_len);
           this.write(32, this.obj_counter);
           this.write(32, this.size_32);
           this.write(32, this.size_64);
           return this.chunk;
          }};
        return function(v, flags){
         flags = caml_list_to_js_array(flags);
         var
          no_sharing = flags.indexOf(0) !== - 1,
          closures = flags.indexOf(1) !== - 1;
         if(closures)
          console.warn
           ("in caml_output_val: flag Marshal.Closures is not supported.");
         var
          writer = new Writer(),
          stack = [],
          intern_obj_table = no_sharing ? null : new MlObjectTable();
         function memo(v){
          if(no_sharing) return false;
          var existing_offset = intern_obj_table.recall(v);
          if(existing_offset){
           writer.write_shared(existing_offset);
           return true;
          }
          else{intern_obj_table.store(v); return false;}
         }
         function extern_rec(v){
          if(v.caml_custom){
           if(memo(v)) return;
           var
            name = v.caml_custom,
            ops = caml_custom_ops[name],
            sz_32_64 = [0, 0];
           if(! ops.serialize)
            caml_invalid_argument("output_value: abstract value (Custom)");
           if(ops.fixed_length == undefined){
            writer.write(8, 0x18);
            for(var i = 0; i < name.length; i++)
             writer.write(8, name.charCodeAt(i));
            writer.write(8, 0);
            var header_pos = writer.pos();
            for(var i = 0; i < 12; i++) writer.write(8, 0);
            ops.serialize(writer, v, sz_32_64);
            writer.write_at(header_pos, 32, sz_32_64[0]);
            writer.write_at(header_pos + 4, 32, 0);
            writer.write_at(header_pos + 8, 32, sz_32_64[1]);
           }
           else{
            writer.write(8, 0x19);
            for(var i = 0; i < name.length; i++)
             writer.write(8, name.charCodeAt(i));
            writer.write(8, 0);
            var old_pos = writer.pos();
            ops.serialize(writer, v, sz_32_64);
            if(ops.fixed_length != writer.pos() - old_pos)
             caml_failwith
              ("output_value: incorrect fixed sizes specified by " + name);
           }
           writer.size_32 += 2 + (sz_32_64[0] + 3 >> 2);
           writer.size_64 += 2 + (sz_32_64[1] + 7 >> 3);
          }
          else if(v instanceof Array && v[0] === (v[0] | 0)){
           if(v[0] == 251)
            caml_failwith("output_value: abstract value (Abstract)");
           if(caml_is_continuation_tag(v[0]))
            caml_invalid_argument("output_value: continuation value");
           if(v.length > 1 && memo(v)) return;
           if(v[0] < 16 && v.length - 1 < 8)
            writer.write(8, 0x80 + v[0] + (v.length - 1 << 4));
           else
            writer.write_code(32, 0x08, v.length - 1 << 10 | v[0]);
           writer.size_32 += v.length;
           writer.size_64 += v.length;
           if(v.length > 1) stack.push(v, 1);
          }
          else if(caml_is_ml_bytes(v)){
           if(! caml_is_ml_bytes(caml_string_of_jsbytes("")))
            caml_failwith
             ("output_value: [Bytes.t] cannot safely be marshaled with [--enable use-js-string]");
           if(memo(v)) return;
           var len = caml_ml_bytes_length(v);
           if(len < 0x20)
            writer.write(8, 0x20 + len);
           else if(len < 0x100)
            writer.write_code(8, 0x09, len);
           else
            writer.write_code(32, 0x0A, len);
           for(var i = 0; i < len; i++)
            writer.write(8, caml_bytes_unsafe_get(v, i));
           writer.size_32 += 1 + ((len + 4) / 4 | 0);
           writer.size_64 += 1 + ((len + 8) / 8 | 0);
          }
          else if(caml_is_ml_string(v)){
           if(memo(v)) return;
           var len = caml_ml_string_length(v);
           if(len < 0x20)
            writer.write(8, 0x20 + len);
           else if(len < 0x100)
            writer.write_code(8, 0x09, len);
           else
            writer.write_code(32, 0x0A, len);
           for(var i = 0; i < len; i++)
            writer.write(8, caml_string_unsafe_get(v, i));
           writer.size_32 += 1 + ((len + 4) / 4 | 0);
           writer.size_64 += 1 + ((len + 8) / 8 | 0);
          }
          else if(v != (v | 0)){
           var type_of_v = typeof v;
           caml_failwith("output_value: abstract value (" + type_of_v + ")");
          }
          else if(v >= 0 && v < 0x40)
           writer.write(8, 0X40 + v);
          else if(v >= - (1 << 7) && v < 1 << 7)
           writer.write_code(8, 0x00, v);
          else if(v >= - (1 << 15) && v < 1 << 15)
           writer.write_code(16, 0x01, v);
          else
           writer.write_code(32, 0x02, v);
         }
         extern_rec(v);
         while(stack.length > 0){
          var i = stack.pop(), v = stack.pop();
          if(i + 1 < v.length) stack.push(v, i + 1);
          extern_rec(v[i]);
         }
         if(intern_obj_table)
          writer.obj_counter = intern_obj_table.objs.length;
         writer.finalize();
         return writer.chunk;};
       }
       ();
   function caml_string_of_array(a){
    return caml_string_of_jsbytes(caml_subarray_to_jsbytes(a, 0, a.length));
   }
   function caml_output_value_to_string(v, flags){
    return caml_string_of_array(caml_output_val(v, flags));
   }
   function caml_raise_not_a_dir(name){
    caml_raise_sys_error(name + ": Not a directory");
   }
   function caml_sys_system_command(cmd){
    var cmd = caml_jsstring_of_string(cmd);
    if(typeof require != "undefined"){
     var child_process = require("child_process");
     if(child_process && child_process.execSync)
      try{child_process.execSync(cmd, {stdio: "inherit"}); return 0;}
      catch(e){return 1;}
    }
    else
     return 127;
   }
   function caml_js_error_of_exception(exn){
    if(exn.js_error) return exn.js_error;
    return null;
   }
   function caml_unix_getuid(unit){
    if(globalThis.process && globalThis.process.getuid)
     return globalThis.process.getuid();
    caml_raise_not_found();
   }
   function deserialize_nat(reader, sz){
    var len = reader.read32s(), nat = new MlNat(len);
    for(var i = 0; i < len; i++) nat.data[i] = reader.read32s();
    sz[0] = len * 4;
    return nat;
   }
   function initialize_nat(){
    caml_custom_ops["_nat"] =
     {deserialize: deserialize_nat,
      serialize: serialize_nat,
      hash: caml_hash_nat};
   }
   function caml_bytes_of_utf16_jsstring(s){
    var tag = 9;
    if(! jsoo_is_ascii(s)) tag = 8, s = caml_utf8_of_utf16(s);
    return new MlBytes(tag, s, s.length);
   }
   function caml_gr_open_subwindow(a, b, c, d){
    caml_failwith("caml_gr_open_subwindow not Implemented");
   }
   function UInt8ArrayReader(s, i){this.s = s; this.i = i;}
   UInt8ArrayReader.prototype =
    {read8u: function(){return this.s[this.i++];},
     read8s: function(){return this.s[this.i++] << 24 >> 24;},
     read16u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return s[i] << 8 | s[i + 1];
     },
     read16s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return s[i] << 24 >> 16 | s[i + 1];
     },
     read32u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return (s[i] << 24 | s[i + 1] << 16 | s[i + 2] << 8 | s[i + 3]) >>> 0;
     },
     read32s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return s[i] << 24 | s[i + 1] << 16 | s[i + 2] << 8 | s[i + 3];
     },
     readstr:
     function(len){
      var i = this.i;
      this.i = i + len;
      return caml_string_of_array(this.s.subarray(i, i + len));
     },
     readuint8array:
     function(len){
      var i = this.i;
      this.i = i + len;
      return this.s.subarray(i, i + len);
     }};
   function caml_marshal_data_size(s, ofs){
    var r = new UInt8ArrayReader(caml_uint8_array_of_bytes(s), ofs);
    function readvlq(overflow){
     var c = r.read8u(), n = c & 0x7F;
     while((c & 0x80) != 0){
      c = r.read8u();
      var n7 = n << 7;
      if(n != n7 >> 7) overflow[0] = true;
      n = n7 | c & 0x7F;
     }
     return n;
    }
    switch(r.read32u()){
      case 0x8495A6BE:
       var header_len = 20, data_len = r.read32u(); break;
      case 0x8495A6BD:
       var
        header_len = r.read8u() & 0x3F,
        overflow = [false],
        data_len = readvlq(overflow);
       if(overflow[0])
        caml_failwith
         ("Marshal.data_size: object too large to be read back on this platform");
       break;
      case 0x8495A6BF:
      default: caml_failwith("Marshal.data_size: bad object"); break;
    }
    return header_len - caml_marshal_header_size + data_len;
   }
   function MlStringReader(s, i){
    this.s = caml_jsbytes_of_string(s);
    this.i = i;
   }
   MlStringReader.prototype =
    {read8u: function(){return this.s.charCodeAt(this.i++);},
     read8s: function(){return this.s.charCodeAt(this.i++) << 24 >> 24;},
     read16u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return s.charCodeAt(i) << 8 | s.charCodeAt(i + 1);
     },
     read16s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return s.charCodeAt(i) << 24 >> 16 | s.charCodeAt(i + 1);
     },
     read32u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return (s.charCodeAt(i) << 24 | s.charCodeAt(i + 1) << 16
             | s.charCodeAt(i + 2) << 8
             | s.charCodeAt(i + 3))
             >>> 0;
     },
     read32s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return s.charCodeAt(i) << 24 | s.charCodeAt(i + 1) << 16
             | s.charCodeAt(i + 2) << 8
             | s.charCodeAt(i + 3);
     },
     readstr:
     function(len){
      var i = this.i;
      this.i = i + len;
      return caml_string_of_jsbytes(this.s.substring(i, i + len));
     },
     readuint8array:
     function(len){
      var b = new Uint8Array(len), s = this.s, i = this.i;
      for(var j = 0; j < len; j++) b[j] = s.charCodeAt(i + j);
      this.i = i + len;
      return b;
     }};
   var
    zstd_decompress =
      function(){
        "use strict";
        var
         ab = ArrayBuffer,
         u8 = Uint8Array,
         u16 = Uint16Array,
         i16 = Int16Array,
         u32 = Uint32Array,
         i32 = Int32Array;
        function slc(v, s, e){
         if(u8.prototype.slice) return u8.prototype.slice.call(v, s, e);
         if(s == null || s < 0) s = 0;
         if(e == null || e > v.length) e = v.length;
         var n = new u8(e - s);
         n.set(v.subarray(s, e));
         return n;
        }
        function fill(v, n, s, e){
         if(u8.prototype.fill) return u8.prototype.fill.call(v, n, s, e);
         if(s == null || s < 0) s = 0;
         if(e == null || e > v.length) e = v.length;
         for(; s < e; ++s) v[s] = n;
         return v;
        }
        function cpw(v, t, s, e){
         if(u8.prototype.copyWithin)
          return u8.prototype.copyWithin.call(v, t, s, e);
         if(s == null || s < 0) s = 0;
         if(e == null || e > v.length) e = v.length;
         while(s < e) v[t++] = v[s++];
        }
        var
         ec =
           ["invalid zstd data",
            "window size too large (>2046MB)",
            "invalid block type",
            "FSE accuracy too high",
            "match distance too far back",
            "unexpected EOF"];
        function err(ind, msg, nt){
         var e = new Error(msg || ec[ind]);
         e.code = ind;
         if(! nt) throw e;
         return e;
        }
        function rb(d, b, n){
         var i = 0, o = 0;
         for(; i < n; ++i) o |= d[b++] << (i << 3);
         return o;
        }
        function b4(d, b){
         return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
        }
        function rzfh(dat, w){
         var n3 = dat[0] | dat[1] << 8 | dat[2] << 16;
         if(n3 == 0x2FB528 && dat[3] == 253){
          var
           flg = dat[4],
           ss = flg >> 5 & 1,
           cc = flg >> 2 & 1,
           df = flg & 3,
           fcf = flg >> 6;
          if(flg & 8) err(0);
          var bt = 6 - ss, db = df == 3 ? 4 : df, di = rb(dat, bt, db);
          bt += db;
          var
           fsb = fcf ? 1 << fcf : ss,
           fss = rb(dat, bt, fsb) + (fcf == 1 && 256),
           ws = fss;
          if(! ss){
           var wb = 1 << 10 + (dat[5] >> 3);
           ws = wb + (wb >> 3) * (dat[5] & 7);
          }
          if(ws > 2145386496) err(1);
          var buf = new u8((w == 1 ? fss || ws : w ? 0 : ws) + 12);
          buf[0] = 1, buf[4] = 4, buf[8] = 8;
          return {b: bt + fsb,
                  y: 0,
                  l: 0,
                  d: di,
                  w: w && w != 1 ? w : buf.subarray(12),
                  e: ws,
                  o: new i32(buf.buffer, 0, 3),
                  u: fss,
                  c: cc,
                  m: Math.min(131072, ws)};
         }
         else if((n3 >> 4 | dat[3] << 20) == 0x184D2A5) return b4(dat, 4) + 8;
         err(0);
        }
        function msb(val){
         var bits = 0;
         for(; 1 << bits <= val; ++bits) ;
         return bits - 1;
        }
        function rfse(dat, bt, mal){
         var tpos = (bt << 3) + 4, al = (dat[bt] & 15) + 5;
         if(al > mal) err(3);
         var
          sz = 1 << al,
          probs = sz,
          sym = - 1,
          re = - 1,
          i = - 1,
          ht = sz,
          buf = new ab(512 + (sz << 2)),
          freq = new i16(buf, 0, 256),
          dstate = new u16(buf, 0, 256),
          nstate = new u16(buf, 512, sz),
          bb1 = 512 + (sz << 1),
          syms = new u8(buf, bb1, sz),
          nbits = new u8(buf, bb1 + sz);
         while(sym < 255 && probs > 0){
          var
           bits = msb(probs + 1),
           cbt = tpos >> 3,
           msk = (1 << bits + 1) - 1,
           val =
             (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (tpos & 7)
             & msk,
           msk1fb = (1 << bits) - 1,
           msv = msk - probs - 1,
           sval = val & msk1fb;
          if(sval < msv)
           tpos += bits, val = sval;
          else{tpos += bits + 1; if(val > msk1fb) val -= msv;}
          freq[++sym] = --val;
          if(val == - 1){probs += val; syms[--ht] = sym;} else probs -= val;
          if(! val)
           do{
            var rbt = tpos >> 3;
            re = (dat[rbt] | dat[rbt + 1] << 8) >> (tpos & 7) & 3;
            tpos += 2;
            sym += re;
           }
           while
            (re == 3);
         }
         if(sym > 255 || probs) err(0);
         var sympos = 0, sstep = (sz >> 1) + (sz >> 3) + 3, smask = sz - 1;
         for(var s = 0; s <= sym; ++s){
          var sf = freq[s];
          if(sf < 1){dstate[s] = - sf; continue;}
          for(i = 0; i < sf; ++i){
           syms[sympos] = s;
           do sympos = sympos + sstep & smask;while(sympos >= ht);
          }
         }
         if(sympos) err(0);
         for(i = 0; i < sz; ++i){
          var ns = dstate[syms[i]]++, nb = nbits[i] = al - msb(ns);
          nstate[i] = (ns << nb) - sz;
         }
         return [tpos + 7 >> 3, {b: al, s: syms, n: nbits, t: nstate}];
        }
        function rhu(dat, bt){
         var
          i = 0,
          wc = - 1,
          buf = new u8(292),
          hb = dat[bt],
          hw = buf.subarray(0, 256),
          rc = buf.subarray(256, 268),
          ri = new u16(buf.buffer, 268);
         if(hb < 128){
          var _a = rfse(dat, bt + 1, 6), ebt = _a[0], fdt = _a[1];
          bt += hb;
          var epos = ebt << 3, lb = dat[bt];
          if(! lb) err(0);
          var
           st1 = 0,
           st2 = 0,
           btr1 = fdt.b,
           btr2 = btr1,
           fpos = (++bt << 3) - 8 + msb(lb);
          for(;;){
           fpos -= btr1;
           if(fpos < epos) break;
           var cbt = fpos >> 3;
           st1 +=
            (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr1) - 1;
           hw[++wc] = fdt.s[st1];
           fpos -= btr2;
           if(fpos < epos) break;
           cbt = fpos >> 3;
           st2 +=
            (dat[cbt] | dat[cbt + 1] << 8) >> (fpos & 7) & (1 << btr2) - 1;
           hw[++wc] = fdt.s[st2];
           btr1 = fdt.n[st1];
           st1 = fdt.t[st1];
           btr2 = fdt.n[st2];
           st2 = fdt.t[st2];
          }
          if(++wc > 255) err(0);
         }
         else{
          wc = hb - 127;
          for(; i < wc; i += 2){
           var byte = dat[++bt];
           hw[i] = byte >> 4;
           hw[i + 1] = byte & 15;
          }
          ++bt;
         }
         var wes = 0;
         for(i = 0; i < wc; ++i){
          var wt = hw[i];
          if(wt > 11) err(0);
          wes += wt && 1 << wt - 1;
         }
         var mb = msb(wes) + 1, ts = 1 << mb, rem = ts - wes;
         if(rem & rem - 1) err(0);
         hw[wc++] = msb(rem) + 1;
         for(i = 0; i < wc; ++i){
          var wt = hw[i];
          ++rc[hw[i] = wt && mb + 1 - wt];
         }
         var
          hbuf = new u8(ts << 1),
          syms = hbuf.subarray(0, ts),
          nb = hbuf.subarray(ts);
         ri[mb] = 0;
         for(i = mb; i > 0; --i){
          var pv = ri[i];
          fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << mb - i));
         }
         if(ri[0] != ts) err(0);
         for(i = 0; i < wc; ++i){
          var bits = hw[i];
          if(bits){
           var code = ri[bits];
           fill(syms, i, code, ri[bits] = code + (1 << mb - bits));
          }
         }
         return [bt, {n: nb, b: mb, s: syms}];
        }
        var
         dllt =
           rfse
             (new
               u8
               ([81,
                 16,
                 99,
                 140,
                 49,
                 198,
                 24,
                 99,
                 12,
                 33,
                 196,
                 24,
                 99,
                 102,
                 102,
                 134,
                 70,
                 146,
                 4]),
              0,
              6)
            [1],
         dmlt =
           rfse
             (new
               u8
               ([33,
                 20,
                 196,
                 24,
                 99,
                 140,
                 33,
                 132,
                 16,
                 66,
                 8,
                 33,
                 132,
                 16,
                 66,
                 8,
                 33,
                 68,
                 68,
                 68,
                 68,
                 68,
                 68,
                 68,
                 68,
                 36,
                 9]),
              0,
              6)
            [1],
         doct =
           rfse
             (new u8([32, 132, 16, 66, 102, 70, 68, 68, 68, 68, 36, 73, 2]),
              0,
              5)
            [1];
        function b2bl(b, s){
         var len = b.length, bl = new i32(len);
         for(var i = 0; i < len; ++i){bl[i] = s; s += 1 << b[i];}
         return bl;
        }
        var
         llb =
           new
            u8
            (new
              i32
              ([0,
                0,
                0,
                0,
                16843009,
                50528770,
                134678020,
                202050057,
                269422093]).buffer,
             0,
             36),
         llbl = b2bl(llb, 0),
         mlb =
           new
            u8
            (new
              i32
              ([0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                16843009,
                50528770,
                117769220,
                185207048,
                252579084,
                16]).buffer,
             0,
             53),
         mlbl = b2bl(mlb, 3);
        function dhu(dat, out, hu){
         var
          len = dat.length,
          ss = out.length,
          lb = dat[len - 1],
          msk = (1 << hu.b) - 1,
          eb = - hu.b;
         if(! lb) err(0);
         var
          st = 0,
          btr = hu.b,
          pos = (len << 3) - 8 + msb(lb) - btr,
          i = - 1;
         for(; pos > eb && i < ss;){
          var
           cbt = pos >> 3,
           val =
             (dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16) >> (pos & 7);
          st = (st << btr | val) & msk;
          out[++i] = hu.s[st];
          pos -= btr = hu.n[st];
         }
         if(pos != eb || i + 1 != ss) err(0);
        }
        function dhu4(dat, out, hu){
         var
          bt = 6,
          ss = out.length,
          sz1 = ss + 3 >> 2,
          sz2 = sz1 << 1,
          sz3 = sz1 + sz2;
         dhu
          (dat.subarray(bt, bt += dat[0] | dat[1] << 8),
           out.subarray(0, sz1),
           hu);
         dhu
          (dat.subarray(bt, bt += dat[2] | dat[3] << 8),
           out.subarray(sz1, sz2),
           hu);
         dhu
          (dat.subarray(bt, bt += dat[4] | dat[5] << 8),
           out.subarray(sz2, sz3),
           hu);
         dhu(dat.subarray(bt), out.subarray(sz3), hu);
        }
        function rzb(dat, st, out){
         var _a, bt = st.b, b0 = dat[bt], btype = b0 >> 1 & 3;
         st.l = b0 & 1;
         var
          sz = b0 >> 3 | dat[bt + 1] << 5 | dat[bt + 2] << 13,
          ebt = (bt += 3) + sz;
         if(btype == 1){
          if(bt >= dat.length) return;
          st.b = bt + 1;
          if(out){fill(out, dat[bt], st.y, st.y += sz); return out;}
          return fill(new u8(sz), dat[bt]);
         }
         if(ebt > dat.length) return;
         if(btype == 0){
          st.b = ebt;
          if(out){
           out.set(dat.subarray(bt, ebt), st.y);
           st.y += sz;
           return out;
          }
          return slc(dat, bt, ebt);
         }
         if(btype == 2){
          var
           b3 = dat[bt],
           lbt = b3 & 3,
           sf = b3 >> 2 & 3,
           lss = b3 >> 4,
           lcs = 0,
           s4 = 0;
          if(lbt < 2)
           if(sf & 1)
            lss |= dat[++bt] << 4 | (sf & 2 && dat[++bt] << 12);
           else
            lss = b3 >> 3;
          else{
           s4 = sf;
           if(sf < 2)
            lss |= (dat[++bt] & 63) << 4, lcs = dat[bt] >> 6 | dat[++bt] << 2;
           else if(sf == 2)
            lss |= dat[++bt] << 4 | (dat[++bt] & 3) << 12,
            lcs = dat[bt] >> 2 | dat[++bt] << 6;
           else
            lss |= dat[++bt] << 4 | (dat[++bt] & 63) << 12,
            lcs = dat[bt] >> 6 | dat[++bt] << 2 | dat[++bt] << 10;
          }
          ++bt;
          var
           buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m),
           spl = buf.length - lss;
          if(lbt == 0)
           buf.set(dat.subarray(bt, bt += lss), spl);
          else if(lbt == 1)
           fill(buf, dat[bt++], spl);
          else{
           var hu = st.h;
           if(lbt == 2){
            var hud = rhu(dat, bt);
            lcs += bt - (bt = hud[0]);
            st.h = hu = hud[1];
           }
           else if(! hu) err(0);
           (s4 ? dhu4 : dhu)
            (dat.subarray(bt, bt += lcs), buf.subarray(spl), hu);
          }
          var ns = dat[bt++];
          if(ns){
           if(ns == 255)
            ns = (dat[bt++] | dat[bt++] << 8) + 0x7F00;
           else if(ns > 127) ns = ns - 128 << 8 | dat[bt++];
           var scm = dat[bt++];
           if(scm & 3) err(0);
           var dts = [dmlt, doct, dllt];
           for(var i = 2; i > - 1; --i){
            var md = scm >> (i << 1) + 2 & 3;
            if(md == 1){
             var rbuf = new u8([0, 0, dat[bt++]]);
             dts[i] =
              {s: rbuf.subarray(2, 3),
               n: rbuf.subarray(0, 1),
               t: new u16(rbuf.buffer, 0, 1),
               b: 0};
            }
            else if(md == 2)
             _a = rfse(dat, bt, 9 - (i & 1)), bt = _a[0], dts[i] = _a[1];
            else if(md == 3){if(! st.t) err(0); dts[i] = st.t[i];}
           }
           var
            _b = st.t = dts,
            mlt = _b[0],
            oct = _b[1],
            llt = _b[2],
            lb = dat[ebt - 1];
           if(! lb) err(0);
           var
            spos = (ebt << 3) - 8 + msb(lb) - llt.b,
            cbt = spos >> 3,
            oubt = 0,
            lst =
              (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << llt.b) - 1;
           cbt = (spos -= oct.b) >> 3;
           var
            ost =
              (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << oct.b) - 1;
           cbt = (spos -= mlt.b) >> 3;
           var
            mst =
              (dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mlt.b) - 1;
           for(++ns; --ns;){
            var
             llc = llt.s[lst],
             lbtr = llt.n[lst],
             mlc = mlt.s[mst],
             mbtr = mlt.n[mst],
             ofc = oct.s[ost],
             obtr = oct.n[ost];
            cbt = (spos -= ofc) >> 3;
            var
             ofp = 1 << ofc,
             off =
               ofp
               +
                ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16
                | dat[cbt + 3] << 24)
                >>> (spos & 7)
                & ofp - 1);
            cbt = (spos -= mlb[mlc]) >> 3;
            var
             ml =
               mlbl[mlc]
               +
                ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16)
                >> (spos & 7)
                & (1 << mlb[mlc]) - 1);
            cbt = (spos -= llb[llc]) >> 3;
            var
             ll =
               llbl[llc]
               +
                ((dat[cbt] | dat[cbt + 1] << 8 | dat[cbt + 2] << 16)
                >> (spos & 7)
                & (1 << llb[llc]) - 1);
            cbt = (spos -= lbtr) >> 3;
            lst =
             llt.t[lst]
             +
              ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << lbtr) - 1);
            cbt = (spos -= mbtr) >> 3;
            mst =
             mlt.t[mst]
             +
              ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << mbtr) - 1);
            cbt = (spos -= obtr) >> 3;
            ost =
             oct.t[ost]
             +
              ((dat[cbt] | dat[cbt + 1] << 8) >> (spos & 7) & (1 << obtr) - 1);
            if(off > 3){
             st.o[2] = st.o[1];
             st.o[1] = st.o[0];
             st.o[0] = off -= 3;
            }
            else{
             var idx = off - (ll != 0);
             if(idx){
              off = idx == 3 ? st.o[0] - 1 : st.o[idx];
              if(idx > 1) st.o[2] = st.o[1];
              st.o[1] = st.o[0];
              st.o[0] = off;
             }
             else
              off = st.o[0];
            }
            for(var i = 0; i < ll; ++i) buf[oubt + i] = buf[spl + i];
            oubt += ll, spl += ll;
            var stin = oubt - off;
            if(stin < 0){
             var len = - stin, bs = st.e + stin;
             if(len > ml) len = ml;
             for(var i = 0; i < len; ++i) buf[oubt + i] = st.w[bs + i];
             oubt += len, ml -= len, stin = 0;
            }
            for(var i = 0; i < ml; ++i) buf[oubt + i] = buf[stin + i];
            oubt += ml;
           }
           if(oubt != spl)
            while(spl < buf.length) buf[oubt++] = buf[spl++];
           else
            oubt = buf.length;
           if(out) st.y += oubt; else buf = slc(buf, 0, oubt);
          }
          else if(out){
           st.y += lss;
           if(spl) for(var i = 0; i < lss; ++i) buf[i] = buf[spl + i];
          }
          else if(spl) buf = slc(buf, spl);
          st.b = ebt;
          return buf;
         }
         err(2);
        }
        function cct(bufs, ol){
         if(bufs.length == 1) return bufs[0];
         var buf = new u8(ol);
         for(var i = 0, b = 0; i < bufs.length; ++i){
          var chk = bufs[i];
          buf.set(chk, b);
          b += chk.length;
         }
         return buf;
        }
        return function(dat, buf){
         var bt = 0, bufs = [], nb = + ! buf, ol = 0;
         for(; dat.length;){
          var st = rzfh(dat, nb || buf);
          if(typeof st == "object"){
           if(nb){
            buf = null;
            if(st.w.length == st.u){bufs.push(buf = st.w); ol += st.u;}
           }
           else{bufs.push(buf); st.e = 0;}
           for(; ! st.l;){
            var blk = rzb(dat, st, buf);
            if(! blk) err(5);
            if(buf)
             st.e = st.y;
            else{
             bufs.push(blk);
             ol += blk.length;
             cpw(st.w, 0, blk.length);
             st.w.set(blk, st.w.length - blk.length);
            }
           }
           bt = st.b + st.c * 4;
          }
          else
           bt = st;
          dat = dat.subarray(bt);
         }
         return cct(bufs, ol);};
       }
       ();
   function caml_float_of_bytes(a){
    return caml_int64_float_of_bits(caml_int64_of_bytes(a));
   }
   function caml_input_value_from_reader(reader, ofs){
    function readvlq(overflow){
     var c = reader.read8u(), n = c & 0x7F;
     while((c & 0x80) != 0){
      c = reader.read8u();
      var n7 = n << 7;
      if(n != n7 >> 7) overflow[0] = true;
      n = n7 | c & 0x7F;
     }
     return n;
    }
    var magic = reader.read32u();
    switch(magic){
      case 0x8495A6BE:
       var
        header_len = 20,
        compressed = 0,
        data_len = reader.read32u(),
        uncompressed_data_len = data_len,
        num_objects = reader.read32u(),
        _size_32 = reader.read32u(),
        _size_64 = reader.read32u();
       break;
      case 0x8495A6BD:
       var
        header_len = reader.read8u() & 0x3F,
        compressed = 1,
        overflow = [false],
        data_len = readvlq(overflow),
        uncompressed_data_len = readvlq(overflow),
        num_objects = readvlq(overflow),
        _size_32 = readvlq(overflow),
        _size_64 = readvlq(overflow);
       if(overflow[0])
        caml_failwith
         ("caml_input_value_from_reader: object too large to be read back on this platform");
       break;
      case 0x8495A6BF:
       caml_failwith
        ("caml_input_value_from_reader: object too large to be read back on a 32-bit platform");
       break;
      default:
       caml_failwith("caml_input_value_from_reader: bad object"); break;
    }
    var
     stack = [],
     intern_obj_table = num_objects > 0 ? [] : null,
     obj_counter = 0;
    function intern_rec(reader){
     var code = reader.read8u();
     if(code >= 0x40)
      if(code >= 0x80){
       var tag = code & 0xF, size = code >> 4 & 0x7, v = [tag];
       if(size == 0) return v;
       if(intern_obj_table) intern_obj_table[obj_counter++] = v;
       stack.push(v, size);
       return v;
      }
      else
       return code & 0x3F;
     else if(code >= 0x20){
      var len = code & 0x1F, v = reader.readstr(len);
      if(intern_obj_table) intern_obj_table[obj_counter++] = v;
      return v;
     }
     else
      switch(code){
        case 0x00:
         return reader.read8s();
        case 0x01:
         return reader.read16s();
        case 0x02:
         return reader.read32s();
        case 0x03:
         caml_failwith("input_value: integer too large"); break;
        case 0x04:
         var offset = reader.read8u();
         if(compressed == 0) offset = obj_counter - offset;
         return intern_obj_table[offset];
        case 0x05:
         var offset = reader.read16u();
         if(compressed == 0) offset = obj_counter - offset;
         return intern_obj_table[offset];
        case 0x06:
         var offset = reader.read32u();
         if(compressed == 0) offset = obj_counter - offset;
         return intern_obj_table[offset];
        case 0x08:
         var
          header = reader.read32u(),
          tag = header & 0xFF,
          size = header >> 10,
          v = [tag];
         if(size == 0) return v;
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         stack.push(v, size);
         return v;
        case 0x13:
         caml_failwith("input_value: data block too large"); break;
        case 0x09:
         var len = reader.read8u(), v = reader.readstr(len);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         return v;
        case 0x0A:
         var len = reader.read32u(), v = reader.readstr(len);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         return v;
        case 0x0C:
         var t = new Array(8);
         for(var i = 0; i < 8; i++) t[7 - i] = reader.read8u();
         var v = caml_float_of_bytes(t);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         return v;
        case 0x0B:
         var t = new Array(8);
         for(var i = 0; i < 8; i++) t[i] = reader.read8u();
         var v = caml_float_of_bytes(t);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         return v;
        case 0x0E:
         var len = reader.read8u(), v = new Array(len + 1);
         v[0] = 254;
         var t = new Array(8);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         for(var i = 1; i <= len; i++){
          for(var j = 0; j < 8; j++) t[7 - j] = reader.read8u();
          v[i] = caml_float_of_bytes(t);
         }
         return v;
        case 0x0D:
         var len = reader.read8u(), v = new Array(len + 1);
         v[0] = 254;
         var t = new Array(8);
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         for(var i = 1; i <= len; i++){
          for(var j = 0; j < 8; j++) t[j] = reader.read8u();
          v[i] = caml_float_of_bytes(t);
         }
         return v;
        case 0x07:
         var len = reader.read32u(), v = new Array(len + 1);
         v[0] = 254;
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         var t = new Array(8);
         for(var i = 1; i <= len; i++){
          for(var j = 0; j < 8; j++) t[7 - j] = reader.read8u();
          v[i] = caml_float_of_bytes(t);
         }
         return v;
        case 0x0F:
         var len = reader.read32u(), v = new Array(len + 1);
         v[0] = 254;
         var t = new Array(8);
         for(var i = 1; i <= len; i++){
          for(var j = 0; j < 8; j++) t[j] = reader.read8u();
          v[i] = caml_float_of_bytes(t);
         }
         return v;
        case 0x10:
        case 0x11:
         caml_failwith("input_value: code pointer"); break;
        case 0x12:
        case 0x18:
        case 0x19:
         var c, s = "";
         while((c = reader.read8u()) != 0) s += String.fromCharCode(c);
         var ops = caml_custom_ops[s], expected_size;
         if(! ops)
          caml_failwith("input_value: unknown custom block identifier");
         switch(code){
           case 0x12: break;
           case 0x19:
            if(! ops.fixed_length)
             caml_failwith("input_value: expected a fixed-size custom block");
            expected_size = ops.fixed_length;
            break;
           case 0x18:
            expected_size = reader.read32u();
            reader.read32s();
            reader.read32s();
            break;
         }
         var
          old_pos = reader.i,
          size = [0],
          v = ops.deserialize(reader, size);
         if(expected_size != undefined)
          if(expected_size != size[0])
           caml_failwith
            ("input_value: incorrect length of serialized custom block");
         if(intern_obj_table) intern_obj_table[obj_counter++] = v;
         return v;
        default: caml_failwith("input_value: ill-formed message");
      }
    }
    if(compressed)
     var
      data = reader.readuint8array(data_len),
      res = new Uint8Array(uncompressed_data_len),
      res = zstd_decompress(data, res),
      reader = new UInt8ArrayReader(res, 0);
    var res = intern_rec(reader);
    while(stack.length > 0){
     var size = stack.pop(), v = stack.pop(), d = v.length;
     if(d < size) stack.push(v, size);
     v[d] = intern_rec(reader);
    }
    if(typeof ofs != "number") ofs[0] = reader.i;
    return res;
   }
   function caml_string_of_bytes(s){
    s.t & 6 && caml_convert_string_to_bytes(s);
    return caml_string_of_jsbytes(s.c);
   }
   function caml_input_value_from_bytes(s, ofs){
    var
     reader =
       new
        MlStringReader
        (caml_string_of_bytes(s), typeof ofs == "number" ? ofs : ofs[0]);
    return caml_input_value_from_reader(reader, ofs);
   }
   function caml_input_value(chanid){
    var
     chan = caml_ml_channels[chanid],
     header = new Uint8Array(caml_marshal_header_size);
    function block(buffer, offset, n){
     var r = 0;
     while(r < n){
      if(chan.buffer_curr >= chan.buffer_max){
       chan.buffer_curr = 0;
       chan.buffer_max = 0;
       caml_refill(chan);
      }
      if(chan.buffer_curr >= chan.buffer_max) break;
      buffer[offset + r] = chan.buffer[chan.buffer_curr];
      chan.buffer_curr++;
      r++;
     }
     return r;
    }
    var r = block(header, 0, caml_marshal_header_size);
    if(r == 0)
     caml_raise_end_of_file();
    else if(r < caml_marshal_header_size)
     caml_failwith("input_value: truncated object");
    var
     len = caml_marshal_data_size(caml_bytes_of_array(header), 0),
     buf = new Uint8Array(len + caml_marshal_header_size);
    buf.set(header, 0);
    var r = block(buf, caml_marshal_header_size, len);
    if(r < len)
     caml_failwith("input_value: truncated object " + r + "  " + len);
    var
     offset = [0],
     res = caml_input_value_from_bytes(caml_bytes_of_array(buf), offset);
    chan.offset = chan.offset + offset[0];
    return res;
   }
   function caml_input_value_to_outside_heap(c){return caml_input_value(c);}
   function caml_atomic_cas(ref, o, n){
    if(ref[1] === o){ref[1] = n; return 1;}
    return 0;
   }
   function caml_copysign_float(x, y){
    if(y == 0) y = 1 / y;
    x = Math.abs(x);
    return y < 0 ? - x : x;
   }
   function caml_gr_set_text_size(size){
    var s = caml_gr_state_get();
    s.text_size = size;
    s.context.font = s.text_size + "px " + caml_jsstring_of_string(s.font);
    return 0;
   }
   function caml_atomic_load(ref){return ref[1];}
   function caml_MD5Final(ctx){
    var in_buf = ctx.len & 0x3f;
    ctx.b8[in_buf] = 0x80;
    in_buf++;
    if(in_buf > 56){
     for(var j = in_buf; j < 64; j++) ctx.b8[j] = 0;
     caml_MD5Transform(ctx.w, ctx.b32);
     for(var j = 0; j < 56; j++) ctx.b8[j] = 0;
    }
    else
     for(var j = in_buf; j < 56; j++) ctx.b8[j] = 0;
    ctx.b32[14] = ctx.len << 3;
    ctx.b32[15] = ctx.len >> 29 & 0x1FFFFFFF;
    caml_MD5Transform(ctx.w, ctx.b32);
    var t = new Uint8Array(16);
    for(var i = 0; i < 4; i++)
     for(var j = 0; j < 4; j++) t[i * 4 + j] = ctx.w[i] >> 8 * j & 0xFF;
    return t;
   }
   function caml_md5_bytes(s, ofs, len){
    var ctx = caml_MD5Init(), a = caml_uint8_array_of_bytes(s);
    caml_MD5Update(ctx, a.subarray(ofs, ofs + len), len);
    return caml_string_of_array(caml_MD5Final(ctx));
   }
   function caml_ba_set_generic(ba, i, v){
    ba.set(ba.offset(caml_js_from_array(i)), v);
    return 0;
   }
   function caml_ml_condition_wait(t, mutext){return 0;}
   function caml_string_lessequal(s1, s2){return s1 <= s2 ? 1 : 0;}
   function caml_string_greaterequal(s1, s2){return caml_string_lessequal(s2, s1);
   }
   function caml_nextafter_float(x, y){
    if(isNaN(x) || isNaN(y)) return NaN;
    if(x == y) return y;
    if(x == 0) return y < 0 ? - Math.pow(2, - 1074) : Math.pow(2, - 1074);
    var bits = caml_int64_bits_of_float(x), one = caml_int64_of_int32(1);
    if(x < y == x > 0)
     bits = caml_int64_add(bits, one);
    else
     bits = caml_int64_sub(bits, one);
    return caml_int64_float_of_bits(bits);
   }
   function caml_gr_size_y(){var s = caml_gr_state_get(); return s.height;}
   function caml_pos_in(chanid){
    var chan = caml_ml_channels[chanid];
    return chan.offset - (chan.buffer_max - chan.buffer_curr) | 0;
   }
   function caml_ml_pos_in(chanid){return caml_pos_in(chanid);}
   function caml_int64_and(x, y){return x.and(y);}
   function caml_sys_const_word_size(){return 32;}
   function caml_runtime_events_pause(){return 0;}
   function caml_unix_unlink(name){
    var root = resolve_fs_device(name);
    if(! root.device.unlink)
     caml_failwith("caml_unix_unlink: not implemented");
    return root.device.unlink(root.rest, true);
   }
   function caml_sys_open_for_node(fd, flags){
    if(flags.name)
     try{
      var fs = require("fs"), fd2 = fs.openSync(flags.name, "rs");
      return new MlNodeFd(fd2, flags);
     }
     catch(e){}
    return new MlNodeFd(fd, flags);
   }
   function MlFakeFd_out(fd, flags){
    MlFakeFile.call(this, caml_create_bytes(0));
    this.log = function(s){return 0;};
    if(fd == 1 && typeof console.log == "function")
     this.log = console.log;
    else if(fd == 2 && typeof console.error == "function")
     this.log = console.error;
    else if(typeof console.log == "function") this.log = console.log;
    this.flags = flags;
   }
   MlFakeFd_out.prototype.length = function(){return 0;};
   MlFakeFd_out.prototype.write =
    function(offset, buf, pos, len){
     if(this.log){
      if
       (len > 0 && pos >= 0 && pos + len <= buf.length
        && buf[pos + len - 1] == 10)
       len--;
      var src = caml_create_bytes(len);
      caml_blit_bytes(caml_bytes_of_array(buf), pos, src, 0, len);
      this.log(src.toUtf16());
      return 0;
     }
     caml_raise_sys_error(this.fd + ": file descriptor already closed");
    };
   MlFakeFd_out.prototype.read =
    function(offset, buf, pos, len){
     caml_raise_sys_error(this.fd + ": file descriptor is write only");
    };
   MlFakeFd_out.prototype.close = function(){this.log = undefined;};
   function caml_sys_open_internal(file, idx){
    if(idx == undefined) idx = caml_sys_fds.length;
    caml_sys_fds[idx] = file;
    return idx | 0;
   }
   function caml_sys_open(name, flags, _perms){
    var f = {};
    while(flags){
     switch(flags[1]){
       case 0:
        f.rdonly = 1; break;
       case 1:
        f.wronly = 1; break;
       case 2:
        f.append = 1; break;
       case 3:
        f.create = 1; break;
       case 4:
        f.truncate = 1; break;
       case 5:
        f.excl = 1; break;
       case 6:
        f.binary = 1; break;
       case 7:
        f.text = 1; break;
       case 8:
        f.nonblock = 1; break;
     }
     flags = flags[2];
    }
    if(f.rdonly && f.wronly)
     caml_raise_sys_error
      (caml_jsbytes_of_string(name)
       + " : flags Open_rdonly and Open_wronly are not compatible");
    if(f.text && f.binary)
     caml_raise_sys_error
      (caml_jsbytes_of_string(name)
       + " : flags Open_text and Open_binary are not compatible");
    var root = resolve_fs_device(name), file = root.device.open(root.rest, f);
    return caml_sys_open_internal(file, undefined);
   }
   (function(){
      function file(fd, flags){
       return fs_node_supported()
               ? caml_sys_open_for_node(fd, flags)
               : new MlFakeFd_out(fd, flags);
      }
      caml_sys_open_internal
       (file(0, {rdonly: 1, altname: "/dev/stdin", isCharacterDevice: true}),
        0);
      caml_sys_open_internal
       (file(1, {buffered: 2, wronly: 1, isCharacterDevice: true}), 1);
      caml_sys_open_internal
       (file(2, {buffered: 2, wronly: 1, isCharacterDevice: true}), 2);
     }
     ());
   function caml_string_get(s, i){
    if(i >>> 0 >= caml_ml_string_length(s)) caml_string_bound_error();
    return caml_string_unsafe_get(s, i);
   }
   var
    re_match =
      function(){
        var
         re_word_letters =
           [0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0xFF,
            0x03,
            0xFE,
            0xFF,
            0xFF,
            0x87,
            0xFE,
            0xFF,
            0xFF,
            0x07,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0xFF,
            0xFF,
            0x7F,
            0xFF,
            0xFF,
            0xFF,
            0x7F,
            0xFF],
         opcodes =
           {CHAR: 0,
            CHARNORM: 1,
            STRING: 2,
            STRINGNORM: 3,
            CHARCLASS: 4,
            BOL: 5,
            EOL: 6,
            WORDBOUNDARY: 7,
            BEGGROUP: 8,
            ENDGROUP: 9,
            REFGROUP: 10,
            ACCEPT: 11,
            SIMPLEOPT: 12,
            SIMPLESTAR: 13,
            SIMPLEPLUS: 14,
            GOTO: 15,
            PUSHBACK: 16,
            SETMARK: 17,
            CHECKPROGRESS: 18};
        function is_word_letter(c){
         return re_word_letters[c >> 3] >> (c & 7) & 1;
        }
        function in_bitset(s, i){
         return caml_string_get(s, i >> 3) >> (i & 7) & 1;
        }
        function re_match_impl(re, s, pos, partial){
         var
          prog = caml_js_from_array(re[1]),
          cpool = caml_js_from_array(re[2]),
          normtable = caml_jsbytes_of_string(re[3]),
          numgroups = re[4] | 0,
          numregisters = re[5] | 0,
          startchars = re[6] | 0,
          s = caml_uint8_array_of_string(s),
          pc = 0,
          quit = false,
          stack = [],
          groups = new Array(numgroups),
          re_register = new Array(numregisters);
         for(var i = 0; i < groups.length; i++)
          groups[i] = {start: - 1, end: - 1};
         groups[0].start = pos;
         function backtrack(){
          while(stack.length){
           var item = stack.pop();
           if(item.undo)
            item.undo.obj[item.undo.prop] = item.undo.value;
           else if(item.pos){pc = item.pos.pc; pos = item.pos.txt; return;}
          }
          quit = true;
         }
         function push(item){stack.push(item);}
         function accept(){
          groups[0].end = pos;
          var result = new Array(1 + groups.length * 2);
          result[0] = 0;
          for(var i = 0; i < groups.length; i++){
           var g = groups[i];
           if(g.start < 0 || g.end < 0) g.start = g.end = - 1;
           result[2 * i + 1] = g.start;
           result[2 * i + 1 + 1] = g.end;
          }
          return result;
         }
         function prefix_match(){
          if(partial) return accept(); else backtrack();
         }
         while(! quit){
          var
           op = prog[pc] & 0xff,
           sarg = prog[pc] >> 8,
           uarg = sarg & 0xff,
           c = s[pos],
           group;
          pc++;
          switch(op){
            case opcodes.CHAR:
             if(pos === s.length){prefix_match(); break;}
             if(c === uarg) pos++; else backtrack();
             break;
            case opcodes.CHARNORM:
             if(pos === s.length){prefix_match(); break;}
             if(normtable.charCodeAt(c) === uarg) pos++; else backtrack();
             break;
            case opcodes.STRING:
             for
             (var arg = caml_jsbytes_of_string(cpool[uarg]), i = 0;
              i < arg.length;
              i++){
              if(pos === s.length){prefix_match(); break;}
              if(c === arg.charCodeAt(i))
               c = s[++pos];
              else{backtrack(); break;}
             }
             break;
            case opcodes.STRINGNORM:
             for
             (var arg = caml_jsbytes_of_string(cpool[uarg]), i = 0;
              i < arg.length;
              i++){
              if(pos === s.length){prefix_match(); break;}
              if(normtable.charCodeAt(c) === arg.charCodeAt(i))
               c = s[++pos];
              else{backtrack(); break;}
             }
             break;
            case opcodes.CHARCLASS:
             if(pos === s.length){prefix_match(); break;}
             if(in_bitset(cpool[uarg], c)) pos++; else backtrack();
             break;
            case opcodes.BOL:
             if(pos > 0 && s[pos - 1] != 10) backtrack(); break;
            case opcodes.EOL:
             if(pos < s.length && s[pos] != 10) backtrack(); break;
            case opcodes.WORDBOUNDARY:
             if(pos == 0){
              if(pos === s.length){prefix_match(); break;}
              if(is_word_letter(s[0])) break;
              backtrack();
             }
             else if(pos === s.length){
              if(is_word_letter(s[pos - 1])) break;
              backtrack();
             }
             else{
              if(is_word_letter(s[pos - 1]) != is_word_letter(s[pos])) break;
              backtrack();
             }
             break;
            case opcodes.BEGGROUP:
             group = groups[uarg];
             push({undo: {obj: group, prop: "start", value: group.start}});
             group.start = pos;
             break;
            case opcodes.ENDGROUP:
             group = groups[uarg];
             push({undo: {obj: group, prop: "end", value: group.end}});
             group.end = pos;
             break;
            case opcodes.REFGROUP:
             group = groups[uarg];
             if(group.start < 0 || group.end < 0){backtrack(); break;}
             for(var i = group.start; i < group.end; i++){
              if(pos === s.length){prefix_match(); break;}
              if(s[i] != s[pos]){backtrack(); break;}
              pos++;
             }
             break;
            case opcodes.SIMPLEOPT:
             if(in_bitset(cpool[uarg], c)) pos++; break;
            case opcodes.SIMPLESTAR:
             while(in_bitset(cpool[uarg], c)) c = s[++pos]; break;
            case opcodes.SIMPLEPLUS:
             if(pos === s.length){prefix_match(); break;}
             if(in_bitset(cpool[uarg], c))
              do c = s[++pos];while(in_bitset(cpool[uarg], c));
             else
              backtrack();
             break;
            case opcodes.ACCEPT: return accept();
            case opcodes.GOTO:
             pc = pc + sarg; break;
            case opcodes.PUSHBACK:
             push({pos: {pc: pc + sarg, txt: pos}}); break;
            case opcodes.SETMARK:
             push
              ({undo: {obj: re_register, prop: uarg, value: re_register[uarg]}});
             re_register[uarg] = pos;
             break;
            case opcodes.CHECKPROGRESS:
             if(re_register[uarg] === pos) backtrack(); break;
            default: throw new Error("Invalid bytecode");
          }
         }
         return 0;
        }
        return re_match_impl;
       }
       ();
   function re_search_backward(re, s, pos){
    if(pos < 0 || pos > caml_ml_string_length(s))
     caml_invalid_argument("Str.search_backward");
    while(pos >= 0){
     var res = re_match(re, s, pos, 0);
     if(res) return res;
     pos--;
    }
    return [0];
   }
   function caml_js_from_string(s){return caml_jsstring_of_string(s);}
   function caml_ba_sub(ba, ofs, len){
    var changed_dim, mul = 1;
    if(ba.layout == 0){
     for(var i = 1; i < ba.dims.length; i++) mul = mul * ba.dims[i];
     changed_dim = 0;
    }
    else{
     for(var i = 0; i < ba.dims.length - 1; i++) mul = mul * ba.dims[i];
     changed_dim = ba.dims.length - 1;
     ofs = ofs - 1;
    }
    if(ofs < 0 || len < 0 || ofs + len > ba.dims[changed_dim])
     caml_invalid_argument("Bigarray.sub: bad sub-array");
    var new_dims = [];
    for(var i = 0; i < ba.dims.length; i++) new_dims[i] = ba.dims[i];
    new_dims[changed_dim] = len;
    mul *= caml_ba_get_size_per_element(ba.kind);
    var new_data = ba.data.subarray(ofs * mul, (ofs + len) * mul);
    return caml_ba_create_unsafe(ba.kind, ba.layout, new_dims, new_data);
   }
   function caml_gc_full_major(unit){
    if(typeof globalThis.gc == "function") globalThis.gc();
    return 0;
   }
   function caml_ml_mutex_try_lock(t){
    if(! t.locked){t.locked = true; return 1;}
    return 0;
   }
   function caml_bytes_set32(s, i, i32){
    if(i >>> 0 >= s.l - 3) caml_bytes_bound_error();
    var
     b4 = 0xFF & i32 >> 24,
     b3 = 0xFF & i32 >> 16,
     b2 = 0xFF & i32 >> 8,
     b1 = 0xFF & i32;
    caml_bytes_unsafe_set(s, i + 0, b1);
    caml_bytes_unsafe_set(s, i + 1, b2);
    caml_bytes_unsafe_set(s, i + 2, b3);
    caml_bytes_unsafe_set(s, i + 3, b4);
    return 0;
   }
   function caml_gr_sigio_signal(){return 0;}
   function caml_ba_uint8_set32(ba, i0, v){
    var ofs = ba.offset(i0);
    if(ofs + 3 >= ba.data.length) caml_array_bound_error();
    ba.set(ofs + 0, v & 0xff);
    ba.set(ofs + 1, v >>> 8 & 0xff);
    ba.set(ofs + 2, v >>> 16 & 0xff);
    ba.set(ofs + 3, v >>> 24 & 0xff);
    return 0;
   }
   function caml_sys_const_ostype_unix(){return os_type == "Unix" ? 1 : 0;}
   function caml_unix_gmtime(t){
    var
     d = new Date(t * 1000),
     d_num = d.getTime(),
     januaryfirst = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)).getTime(),
     doy = Math.floor((d_num - januaryfirst) / 86400000);
    return [0,
            d.getUTCSeconds(),
            d.getUTCMinutes(),
            d.getUTCHours(),
            d.getUTCDate(),
            d.getUTCMonth(),
            d.getUTCFullYear() - 1900,
            d.getUTCDay(),
            doy,
            false | 0];
   }
   function caml_signbit_float(x){if(x == 0) x = 1 / x; return x < 0 ? 1 : 0;}
   function caml_gr_current_x(){var s = caml_gr_state_get(); return s.x;}
   function caml_gr_set_line_width(w){
    var s = caml_gr_state_get();
    s.line_width = w;
    s.context.lineWidth = w;
    return 0;
   }
   function caml_gr_set_font(f){
    var s = caml_gr_state_get();
    s.font = f;
    s.context.font = s.text_size + "px " + caml_jsstring_of_string(s.font);
    return 0;
   }
   function caml_gr_set_color(color){
    var s = caml_gr_state_get();
    function convert(number){
     var str = "" + number.toString(16);
     while(str.length < 2) str = "0" + str;
     return str;
    }
    var r = color >> 16 & 0xff, g = color >> 8 & 0xff, b = color >> 0 & 0xff;
    s.color = color;
    var c_str = "#" + convert(r) + convert(g) + convert(b);
    s.context.fillStyle = c_str;
    s.context.strokeStyle = c_str;
    return 0;
   }
   function caml_gr_moveto(x, y){
    var s = caml_gr_state_get();
    s.x = x;
    s.y = y;
    return 0;
   }
   function caml_gr_resize_window(w, h){
    var s = caml_gr_state_get();
    s.width = w;
    s.height = h;
    s.canvas.width = w;
    s.canvas.height = h;
    return 0;
   }
   function caml_gr_state_init(){
    caml_gr_moveto(caml_gr_state.x, caml_gr_state.y);
    caml_gr_resize_window(caml_gr_state.width, caml_gr_state.height);
    caml_gr_set_line_width(caml_gr_state.line_width);
    caml_gr_set_text_size(caml_gr_state.text_size);
    caml_gr_set_font(caml_gr_state.font);
    caml_gr_set_color(caml_gr_state.color);
    caml_gr_set_window_title(caml_gr_state.title);
    caml_gr_state.context.textBaseline = "bottom";
   }
   function caml_ba_kind_of_typed_array(ta){
    var kind;
    if(ta instanceof Float32Array)
     kind = 0;
    else if(ta instanceof Float64Array)
     kind = 1;
    else if(ta instanceof Int8Array)
     kind = 2;
    else if(ta instanceof Uint8Array)
     kind = 3;
    else if(ta instanceof Int16Array)
     kind = 4;
    else if(ta instanceof Uint16Array)
     kind = 5;
    else if(ta instanceof Int32Array)
     kind = 6;
    else if(ta instanceof Uint32Array)
     kind = 6;
    else
     caml_invalid_argument("caml_ba_kind_of_typed_array: unsupported kind");
    return kind;
   }
   function caml_ba_from_typed_array(ta){
    var kind = caml_ba_kind_of_typed_array(ta);
    return caml_ba_create_unsafe(kind, 0, [ta.length], ta);
   }
   function caml_ml_seek_out(chanid, pos){return caml_seek_out(chanid, pos);}
   function caml_js_typeof(o){return typeof o;}
   function caml_hash_mix_string(h, v){
    return caml_hash_mix_jsbytes(h, caml_jsbytes_of_string(v));
   }
   function caml_string_hash(h, v){
    var h = caml_hash_mix_string(h, v), h = caml_hash_mix_final(h);
    return h & 0x3FFFFFFF;
   }
   function caml_restore_raw_backtrace(exn, bt){return 0;}
   function caml_gr_lineto(x, y){
    var s = caml_gr_state_get();
    s.context.beginPath();
    s.context.moveTo(s.x, s.height - s.y);
    s.context.lineTo(x, s.height - y);
    s.context.stroke();
    s.x = x;
    s.y = y;
    return 0;
   }
   function caml_js_function_arity(f){return f.l >= 0 ? f.l : f.l = f.length;}
   function caml_js_wrap_meth_callback_unsafe(f){
    return function(){
     var len = caml_js_function_arity(f) - 1, args = new Array(len + 1);
     args[0] = this;
     for(var i = 0; i < len; i++) args[i + 1] = arguments[i];
     return caml_callback(f, args);};
   }
   function caml_ba_dim_3(ba){return caml_ba_dim(ba, 2);}
   function caml_is_special_exception(exn){
    switch(exn[2]){case - 8:case - 11:case - 12: return 1;default: return 0;
    }
   }
   function caml_format_exception(exn){
    var r = "";
    if(exn[0] == 0){
     r += exn[1][1];
     if
      (exn.length == 3 && exn[2][0] == 0 && caml_is_special_exception(exn[1]))
      var bucket = exn[2], start = 1;
     else
      var start = 2, bucket = exn;
     r += "(";
     for(var i = start; i < bucket.length; i++){
      if(i > start) r += ", ";
      var v = bucket[i];
      if(typeof v == "number")
       r += v.toString();
      else if(v instanceof MlBytes)
       r += '"' + v.toString() + '"';
      else if(typeof v == "string")
       r += '"' + v.toString() + '"';
      else
       r += "_";
     }
     r += ")";
    }
    else if(exn[0] == 248) r += exn[1];
    return r;
   }
   function caml_fatal_uncaught_exception(err){
    if(err instanceof Array && (err[0] == 0 || err[0] == 248)){
     var handler = caml_named_value("Printexc.handle_uncaught_exception");
     if(handler)
      caml_callback(handler, [err, false]);
     else{
      var
       msg = caml_format_exception(err),
       at_exit = caml_named_value("Pervasives.do_at_exit");
      if(at_exit) caml_callback(at_exit, [0]);
      console.error("Fatal error: exception " + msg + "\n");
      if(err.js_error) throw err.js_error;
     }
    }
    else
     throw err;
   }
   function caml_ephe_check_data(x){
    return x[caml_ephe_data_offset] === undefined ? 0 : 1;
   }
   function caml_bytes_get16(s, i){
    if(i >>> 0 >= s.l - 1) caml_bytes_bound_error();
    var
     b1 = caml_bytes_unsafe_get(s, i),
     b2 = caml_bytes_unsafe_get(s, i + 1);
    return b2 << 8 | b1;
   }
   function caml_obj_make_forward(b, v){b[0] = 250; b[1] = v; return 0;}
   function caml_js_from_bool(x){return ! ! x;}
   function caml_ml_set_channel_name(chanid, name){
    var chan = caml_ml_channels[chanid];
    chan.name = name;
    return 0;
   }
   function caml_exp2_float(x){return Math.pow(2, x);}
   function caml_gr_close_graph(){
    var s = caml_gr_state_get();
    s.canvas.width = 0;
    s.canvas.height = 0;
    return 0;
   }
   function caml_ml_domain_cpu_relax(unit){return 0;}
   function caml_create_string(len){caml_invalid_argument("String.create");}
   function caml_ml_input_block(chanid, ba, i, l){
    var
     chan = caml_ml_channels[chanid],
     n = l,
     avail = chan.buffer_max - chan.buffer_curr;
    if(l <= avail){
     ba.set(chan.buffer.subarray(chan.buffer_curr, chan.buffer_curr + l), i);
     chan.buffer_curr += l;
    }
    else if(avail > 0){
     ba.set
      (chan.buffer.subarray(chan.buffer_curr, chan.buffer_curr + avail), i);
     chan.buffer_curr += avail;
     n = avail;
    }
    else{
     chan.buffer_curr = 0;
     chan.buffer_max = 0;
     caml_refill(chan);
     var avail = chan.buffer_max - chan.buffer_curr;
     if(n > avail) n = avail;
     ba.set(chan.buffer.subarray(chan.buffer_curr, chan.buffer_curr + n), i);
     chan.buffer_curr += n;
    }
    return n | 0;
   }
   function caml_md5_chan(chanid, toread){
    var ctx = caml_MD5Init(), buffer = new Uint8Array(4096);
    if(toread < 0)
     while(true){
      var read = caml_ml_input_block(chanid, buffer, 0, buffer.length);
      if(read == 0) break;
      caml_MD5Update(ctx, buffer.subarray(0, read), read);
     }
    else
     while(toread > 0){
      var
       read =
         caml_ml_input_block
          (chanid, buffer, 0, toread > buffer.length ? buffer.length : toread);
      if(read == 0) caml_raise_end_of_file();
      caml_MD5Update(ctx, buffer.subarray(0, read), read);
      toread -= read;
     }
    return caml_string_of_array(caml_MD5Final(ctx));
   }
   function caml_atanh_float(x){return Math.atanh(x);}
   function caml_ml_condition_signal(t){return 0;}
   function caml_unix_findnext(dir_handle){return caml_unix_readdir(dir_handle);
   }
   function caml_ml_output_bytes(chanid, buffer, offset, len){
    var chan = caml_ml_channels[chanid];
    if(! chan.opened)
     caml_raise_sys_error("Cannot output to a closed channel");
    var buffer = caml_uint8_array_of_bytes(buffer);
    buffer = buffer.subarray(offset, offset + len);
    if(chan.buffer_curr + buffer.length > chan.buffer.length){
     var b = new Uint8Array(chan.buffer_curr + buffer.length);
     b.set(chan.buffer);
     chan.buffer = b;
    }
    switch(chan.buffered){
      case 0:
       chan.buffer.set(buffer, chan.buffer_curr);
       chan.buffer_curr += buffer.length;
       caml_ml_flush(chanid);
       break;
      case 1:
       chan.buffer.set(buffer, chan.buffer_curr);
       chan.buffer_curr += buffer.length;
       if(chan.buffer_curr >= chan.buffer.length) caml_ml_flush(chanid);
       break;
      case 2:
       var id = buffer.lastIndexOf(10);
       if(id < 0){
        chan.buffer.set(buffer, chan.buffer_curr);
        chan.buffer_curr += buffer.length;
        if(chan.buffer_curr >= chan.buffer.length) caml_ml_flush(chanid);
       }
       else{
        chan.buffer.set(buffer.subarray(0, id + 1), chan.buffer_curr);
        chan.buffer_curr += id + 1;
        caml_ml_flush(chanid);
        chan.buffer.set(buffer.subarray(id + 1), chan.buffer_curr);
        chan.buffer_curr += buffer.length - id - 1;
       }
       break;
    }
    return 0;
   }
   function caml_ml_output(chanid, buffer, offset, len){
    return caml_ml_output_bytes
            (chanid, caml_bytes_of_string(buffer), offset, len);
   }
   function caml_ml_domain_id(unit){return caml_domain_id;}
   function caml_ephe_get_data(x){
    return x[caml_ephe_data_offset] === undefined
            ? 0
            : [0, x[caml_ephe_data_offset]];
   }
   function caml_xmlhttprequest_create(unit){
    if(typeof globalThis.XMLHttpRequest !== "undefined")
     try{return new globalThis.XMLHttpRequest();}catch(e){}
    if(typeof globalThis.activeXObject !== "undefined"){
     try{return new globalThis.activeXObject("Msxml2.XMLHTTP");}catch(e){}
     try{return new globalThis.activeXObject("Msxml3.XMLHTTP");}catch(e){}
     try{return new globalThis.activeXObject("Microsoft.XMLHTTP");}catch(e){}
    }
    caml_failwith("Cannot create a XMLHttpRequest");
   }
   function caml_trampoline_return(f, args){return {joo_tramp: f, joo_args: args};
   }
   function caml_ml_is_buffered(chanid){
    return caml_ml_channels[chanid].buffered ? 1 : 0;
   }
   function caml_array_append(a1, a2){
    var l1 = a1.length, l2 = a2.length, l = l1 + l2 - 1, a = new Array(l);
    a[0] = 0;
    var i = 1, j = 1;
    for(; i < l1; i++) a[i] = a1[i];
    for(; i < l; i++, j++) a[i] = a2[j];
    return a;
   }
   function caml_unix_gettimeofday(){return new Date().getTime() / 1000;}
   function caml_unix_time(){return Math.floor(caml_unix_gettimeofday());}
   function caml_ml_set_channel_refill(chanid, f){
    caml_ml_channels[chanid].refill = f;
    return 0;
   }
   function caml_runtime_events_create_cursor(target){return {};}
   function caml_fill_bytes(s, i, l, c){
    if(l > 0)
     if(i == 0 && (l >= s.l || s.t == 2 && l >= s.c.length))
      if(c == 0){
       s.c = "";
       s.t = 2;
      }
      else{
       s.c = caml_str_repeat(l, String.fromCharCode(c));
       s.t = l == s.l ? 0 : 2;
      }
     else{
      if(s.t != 4) caml_convert_bytes_to_array(s);
      for(l += i; i < l; i++) s.c[i] = c;
     }
    return 0;
   }
   function caml_js_expr(s){
    console.error("caml_js_expr: fallback to runtime evaluation\n");
    return eval(caml_jsstring_of_string(s));
   }
   function caml_ml_runtime_warnings_enabled(_unit){return caml_runtime_warnings;
   }
   function caml_output_value_to_bytes(v, flags){
    return caml_bytes_of_array(caml_output_val(v, flags));
   }
   function caml_eventlog_resume(unit){return 0;}
   function caml_md5_string(s, ofs, len){
    return caml_md5_bytes(caml_bytes_of_string(s), ofs, len);
   }
   function caml_array_of_string(x){return caml_uint8_array_of_string(x);}
   function caml_string_equal(s1, s2){if(s1 === s2) return 1; return 0;}
   function caml_jsoo_flags_use_js_string(unit){return 1;}
   function caml_output_value_to_buffer(s, ofs, len, v, flags){
    var t = caml_output_val(v, flags);
    if(t.length > len) caml_failwith("Marshal.to_buffer: buffer overflow");
    caml_blit_bytes(t, 0, s, ofs, t.length);
    return 0;
   }
   function re_replacement_text(repl, groups, orig){
    var
     repl = caml_jsbytes_of_string(repl),
     len = repl.length,
     orig = caml_jsbytes_of_string(orig),
     res = "",
     n = 0,
     cur,
     start,
     end,
     c;
    while(n < len){
     cur = repl.charAt(n++);
     if(cur != "\\")
      res += cur;
     else{
      if(n == len) caml_failwith("Str.replace: illegal backslash sequence");
      cur = repl.charAt(n++);
      switch(cur){
        case "\\":
         res += cur; break;
        case "0":
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
         c = + cur;
         if(c * 2 >= groups.length - 1)
          caml_failwith("Str.replace: reference to unmatched group");
         start = caml_array_get(groups, c * 2);
         end = caml_array_get(groups, c * 2 + 1);
         if(start == - 1)
          caml_failwith("Str.replace: reference to unmatched group");
         res += orig.slice(start, end);
         break;
        default: res += "\\" + cur;
      }
     }
    }
    return caml_string_of_jsbytes(res);
   }
   function caml_pure_js_expr(s){
    console.error("caml_pure_js_expr: fallback to runtime evaluation\n");
    return eval(caml_jsstring_of_string(s));
   }
   function caml_blit_string(a, b, c, d, e){
    caml_blit_bytes(caml_bytes_of_string(a), b, c, d, e);
    return 0;
   }
   function blit_nat(nat1, ofs1, nat2, ofs2, len){
    for(var i = 0; i < len; i++) nat1.data[ofs1 + i] = nat2.data[ofs2 + i];
    return 0;
   }
   function caml_bigstring_blit_ba_to_bytes(ba1, pos1, bytes2, pos2, len){
    if(12 != ba1.kind)
     caml_invalid_argument("caml_bigstring_blit_string_to_ba: kind mismatch");
    if(len == 0) return 0;
    var ofs1 = ba1.offset(pos1);
    if(ofs1 + len > ba1.data.length) caml_array_bound_error();
    if(pos2 + len > caml_ml_bytes_length(bytes2)) caml_array_bound_error();
    var slice = ba1.data.slice(ofs1, ofs1 + len);
    caml_blit_bytes(caml_bytes_of_array(slice), 0, bytes2, pos2, len);
    return 0;
   }
   function caml_unix_stat(name){
    var root = resolve_fs_device(name);
    if(! root.device.stat) caml_failwith("caml_unix_stat: not implemented");
    return root.device.stat(root.rest, true);
   }
   function caml_register_named_value(nm, v){
    caml_named_values[caml_jsbytes_of_string(nm)] = v;
    return 0;
   }
   function jsoo_create_file_extern(name, content){
    if(globalThis.jsoo_create_file)
     globalThis.jsoo_create_file(name, content);
    else{
     if(! globalThis.caml_fs_tmp) globalThis.caml_fs_tmp = [];
     globalThis.caml_fs_tmp.push({name: name, content: content});
    }
    return 0;
   }
   function caml_unix_stat_64(name){
    var r = caml_unix_stat(name);
    r[9] = caml_int64_of_int32(r[9]);
   }
   function caml_to_js_string(s){return caml_jsstring_of_string(s);}
   function caml_ml_mutex_lock(t){
    if(t.locked)
     caml_failwith("Mutex.lock: mutex already locked. Cannot wait.");
    else
     t.locked = true;
    return 0;
   }
   function re_search_forward(re, s, pos){
    if(pos < 0 || pos > caml_ml_string_length(s))
     caml_invalid_argument("Str.search_forward");
    while(pos <= caml_ml_string_length(s)){
     var res = re_match(re, s, pos, 0);
     if(res) return res;
     pos++;
    }
    return [0];
   }
   function caml_make_vect(len, init){
    if(len < 0) caml_array_bound_error();
    var len = len + 1 | 0, b = new Array(len);
    b[0] = 0;
    for(var i = 1; i < len; i++) b[i] = init;
    return b;
   }
   function caml_ml_seek_in(chanid, pos){return caml_seek_in(chanid, pos);}
   function caml_sys_read_directory(name){
    var
     root = resolve_fs_device(name),
     a = root.device.readdir(root.rest),
     l = new Array(a.length + 1);
    l[0] = 0;
    for(var i = 0; i < a.length; i++) l[i + 1] = caml_string_of_jsbytes(a[i]);
    return l;
   }
   function caml_ml_output_char(chanid, c){
    var s = caml_string_of_jsbytes(String.fromCharCode(c));
    caml_ml_output(chanid, s, 0, 1);
    return 0;
   }
   function caml_sys_const_ostype_win32(){return os_type == "Win32" ? 1 : 0;}
   function caml_obj_is_block(x){return + (x instanceof Array);}
   function caml_obj_set_raw_field(o, i, v){return o[i + 1] = v;}
   function caml_js_var(x){
    var x = caml_jsstring_of_string(x);
    if(! x.match(/^[a-zA-Z_$][a-zA-Z_$0-9]*(\.[a-zA-Z_$][a-zA-Z_$0-9]*)*$/))
     console.error
      ('caml_js_var: "' + x
       + '" is not a valid JavaScript variable. continuing ..');
    return eval(x);
   }
   function caml_trunc_float(x){return Math.trunc(x);}
   function caml_ephe_unset_data(x){
    if(globalThis.FinalizationRegistry && globalThis.WeakRef)
     if(x[1] instanceof globalThis.FinalizationRegistry)
      for(var j = caml_ephe_key_offset; j < x.length; j++){
       var key = x[j];
       if(key instanceof globalThis.WeakRef){
        key = key.deref();
        if(key) x[1].unregister(key);
       }
      }
    x[caml_ephe_data_offset] = undefined;
    return 0;
   }
   function caml_ephe_set_data(x, data){
    if(globalThis.FinalizationRegistry && globalThis.WeakRef)
     if(! (x[1] instanceof globalThis.FinalizationRegistry)){
      x[1] =
       new
        globalThis.FinalizationRegistry
        (function(){caml_ephe_unset_data(x);});
      for(var j = caml_ephe_key_offset; j < x.length; j++){
       var key = x[j];
       if(key instanceof globalThis.WeakRef){
        key = key.deref();
        if(key) x[1].register(key, undefined, key);
       }
      }
     }
    x[caml_ephe_data_offset] = data;
    return 0;
   }
   function caml_ephe_blit_data(src, dst){
    var n = src[caml_ephe_data_offset];
    if(n === undefined)
     caml_ephe_unset_data(dst);
    else
     caml_ephe_set_data(dst, n);
    return 0;
   }
   function caml_is_printable(c){return + (c > 31 && c < 127);}
   function caml_bytes_lessequal(s1, s2){
    s1.t & 6 && caml_convert_string_to_bytes(s1);
    s2.t & 6 && caml_convert_string_to_bytes(s2);
    return s1.c <= s2.c ? 1 : 0;
   }
   function caml_array_of_bytes(x){return caml_uint8_array_of_bytes(x);}
   function caml_equal(x, y){return + (caml_compare_val(x, y, false) == 0);}
   function re_partial_match(re, s, pos){
    if(pos < 0 || pos > caml_ml_string_length(s))
     caml_invalid_argument("Str.partial_match");
    var res = re_match(re, s, pos, 1);
    return res ? res : [0];
   }
   function caml_sys_random_seed(){
    if(globalThis.crypto)
     if(typeof globalThis.crypto.getRandomValues === "function"){
      var a = new Uint32Array(1);
      globalThis.crypto.getRandomValues(a);
      return [0, a[0]];
     }
     else if(globalThis.crypto.randomBytes === "function"){
      var buff = globalThis.crypto.randomBytes(4), a = new Uint32Array(buff);
      return [0, a[0]];
     }
    var now = new Date().getTime(), x = now ^ 0xffffffff * Math.random();
    return [0, x];
   }
   var all_finalizers = new globalThis.Set();
   function caml_final_register_called_without_value(cb, a){
    if(globalThis.FinalizationRegistry && a instanceof Object){
     var
      x =
        new
         globalThis.FinalizationRegistry
         (function(x){all_finalizers.delete(x); cb(0); return;});
     x.register(a, x);
     all_finalizers.add(x);
    }
    return 0;
   }
   function caml_ba_get_2(ba, i0, i1){return ba.get(ba.offset([i0, i1]));}
   function caml_ba_uint8_set16(ba, i0, v){
    var ofs = ba.offset(i0);
    if(ofs + 1 >= ba.data.length) caml_array_bound_error();
    ba.set(ofs + 0, v & 0xff);
    ba.set(ofs + 1, v >>> 8 & 0xff);
    return 0;
   }
   function caml_lazy_reset_to_lazy(o){
    caml_obj_update_tag(o, 244, 246);
    return 0;
   }
   function caml_js_delete(o, f){delete o[f]; return 0;}
   function caml_int_of_string(s){
    var
     r = caml_parse_sign_and_base(s),
     i = r[0],
     sign = r[1],
     base = r[2],
     len = caml_ml_string_length(s),
     threshold = - 1 >>> 0,
     c = i < len ? caml_string_unsafe_get(s, i) : 0,
     d = caml_parse_digit(c);
    if(d < 0 || d >= base) caml_failwith("int_of_string");
    var res = d;
    for(i++; i < len; i++){
     c = caml_string_unsafe_get(s, i);
     if(c == 95) continue;
     d = caml_parse_digit(c);
     if(d < 0 || d >= base) break;
     res = base * res + d;
     if(res > threshold) caml_failwith("int_of_string");
    }
    if(i != len) caml_failwith("int_of_string");
    res = sign * res;
    if(base == 10 && (res | 0) != res) caml_failwith("int_of_string");
    return res | 0;
   }
   function caml_list_mount_point(){
    var prev = 0;
    for(var i = 0; i < jsoo_mount_point.length; i++){
     var old = prev;
     prev = [0, caml_string_of_jsbytes(jsoo_mount_point[i].path), old];
    }
    return prev;
   }
   var
    caml_marshal_constants =
      {PREFIX_SMALL_BLOCK: 0x80,
       PREFIX_SMALL_INT: 0x40,
       PREFIX_SMALL_STRING: 0x20,
       CODE_INT8: 0x00,
       CODE_INT16: 0x01,
       CODE_INT32: 0x02,
       CODE_INT64: 0x03,
       CODE_SHARED8: 0x04,
       CODE_SHARED16: 0x05,
       CODE_SHARED32: 0x06,
       CODE_BLOCK32: 0x08,
       CODE_BLOCK64: 0x13,
       CODE_STRING8: 0x09,
       CODE_STRING32: 0x0A,
       CODE_DOUBLE_BIG: 0x0B,
       CODE_DOUBLE_LITTLE: 0x0C,
       CODE_DOUBLE_ARRAY8_BIG: 0x0D,
       CODE_DOUBLE_ARRAY8_LITTLE: 0x0E,
       CODE_DOUBLE_ARRAY32_BIG: 0x0F,
       CODE_DOUBLE_ARRAY32_LITTLE: 0x07,
       CODE_CODEPOINTER: 0x10,
       CODE_INFIXPOINTER: 0x11,
       CODE_CUSTOM: 0x12,
       CODE_CUSTOM_LEN: 0x18,
       CODE_CUSTOM_FIXED: 0x19};
   function caml_obj_raw_field(o, i){return o[i + 1];}
   function caml_js_equals(x, y){return + (x == y);}
   function caml_obj_compare_and_swap(x, i, old, n){
    if(x[i + 1] == old){x[i + 1] = n; return 1;}
    return 0;
   }
   function bigstring_to_typed_array(bs){return bs.data;}
   function caml_gr_arc_aux(ctx, cx, cy, ry, rx, a1, a2){
    while(a1 > a2) a2 += 360;
    a1 /= 180;
    a2 /= 180;
    var
     rot = 0,
     xPos,
     yPos,
     xPos_prev,
     yPos_prev,
     space = 2,
     num = (a2 - a1) * Math.PI * ((rx + ry) / 2) / space | 0,
     delta = (a2 - a1) * Math.PI / num,
     i = a1 * Math.PI;
    for(var j = 0; j <= num; j++){
     xPos =
      cx - rx * Math.sin(i) * Math.sin(rot * Math.PI)
      + ry * Math.cos(i) * Math.cos(rot * Math.PI);
     xPos = xPos.toFixed(2);
     yPos =
      cy + ry * Math.cos(i) * Math.sin(rot * Math.PI)
      + rx * Math.sin(i) * Math.cos(rot * Math.PI);
     yPos = yPos.toFixed(2);
     if(j == 0)
      ctx.moveTo(xPos, yPos);
     else if(xPos_prev != xPos || yPos_prev != yPos) ctx.lineTo(xPos, yPos);
     xPos_prev = xPos;
     yPos_prev = yPos;
     i -= delta;
    }
    return 0;
   }
   function caml_gr_fill_arc(x, y, rx, ry, a1, a2){
    var s = caml_gr_state_get();
    s.context.beginPath();
    caml_gr_arc_aux(s.context, x, s.height - y, rx, ry, a1, a2);
    s.context.fill();
    return 0;
   }
   function caml_ba_slice(ba, vind){
    vind = caml_js_from_array(vind);
    var num_inds = vind.length, index = [], sub_dims = [], ofs;
    if(num_inds > ba.dims.length)
     caml_invalid_argument("Bigarray.slice: too many indices");
    if(ba.layout == 0){
     for(var i = 0; i < num_inds; i++) index[i] = vind[i];
     for(; i < ba.dims.length; i++) index[i] = 0;
     sub_dims = ba.dims.slice(num_inds);
    }
    else{
     for(var i = 0; i < num_inds; i++)
      index[ba.dims.length - num_inds + i] = vind[i];
     for(var i = 0; i < ba.dims.length - num_inds; i++) index[i] = 1;
     sub_dims = ba.dims.slice(0, ba.dims.length - num_inds);
    }
    ofs = ba.offset(index);
    var
     size = caml_ba_get_size(sub_dims),
     size_per_element = caml_ba_get_size_per_element(ba.kind),
     new_data =
       ba.data.subarray
        (ofs * size_per_element, (ofs + size) * size_per_element);
    return caml_ba_create_unsafe(ba.kind, ba.layout, sub_dims, new_data);
   }
   function caml_js_wrap_callback_unsafe(f){
    return function(){
     var len = caml_js_function_arity(f), args = new Array(len);
     for(var i = 0; i < len; i++) args[i] = arguments[i];
     return caml_callback(f, args);};
   }
   function caml_ba_kind(ba){return ba.kind;}
   function caml_alloc_dummy_infix(){
    return function f(x){return caml_call_gen(f.fun, [x]);};
   }
   function caml_js_fun_call(f, a){
    switch(a.length){
      case 1:
       return f();
      case 2:
       return f(a[1]);
      case 3:
       return f(a[1], a[2]);
      case 4:
       return f(a[1], a[2], a[3]);
      case 5:
       return f(a[1], a[2], a[3], a[4]);
      case 6:
       return f(a[1], a[2], a[3], a[4], a[5]);
      case 7:
       return f(a[1], a[2], a[3], a[4], a[5], a[6]);
      case 8:
       return f(a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
    }
    return f.apply(null, caml_js_from_array(a));
   }
   function caml_gc_major_slice(work){return 0;}
   function caml_js_pure_expr(f){return caml_callback(f, [0]);}
   function compare_digits_nat(nat1, ofs1, nat2, ofs2){
    if(nat1.data[ofs1] > nat2.data[ofs2]) return 1;
    if(nat1.data[ofs1] < nat2.data[ofs2]) return - 1;
    return 0;
   }
   function caml_ml_input(chanid, b, i, l){
    var ba = caml_uint8_array_of_bytes(b);
    return caml_ml_input_block(chanid, ba, i, l);
   }
   function caml_gr_wait_event(_evl){
    caml_failwith
     ("caml_gr_wait_event not Implemented: use Graphics_js instead");
   }
   function caml_gr_sigio_handler(){return 0;}
   function caml_hash_mix_bigstring(h, bs){
    return caml_hash_mix_bytes_arr(h, bs.data);
   }
   function caml_record_backtrace(b){
    caml_record_backtrace_flag = b;
    return 0;
   }
   function caml_unix_cleanup(){}
   function caml_sys_get_config(){
    return [0, caml_string_of_jsbytes(os_type), 32, 0];
   }
   function caml_sys_const_backend_type(){
    return [0, caml_string_of_jsbytes("js_of_ocaml")];
   }
   function caml_obj_is_shared(x){return 1;}
   function caml_ml_out_channels_list(){
    var l = 0;
    for(var c = 0; c < caml_ml_channels.length; c++)
     if
      (caml_ml_channels[c] && caml_ml_channels[c].opened
       && caml_ml_channels[c].out)
      l = [0, caml_ml_channels[c].fd, l];
    return l;
   }
   function caml_asinh_float(x){return Math.asinh(x);}
   function caml_pos_out(chanid){
    var chan = caml_ml_channels[chanid];
    return chan.offset + chan.buffer_curr;
   }
   function bigstring_of_array_buffer(ab){
    var ta = new Uint8Array(ab);
    return caml_ba_create_unsafe(12, 0, [ta.length], ta);
   }
   function caml_mod(x, y){if(y == 0) caml_raise_zero_divide(); return x % y;}
   function caml_ba_init(){return 0;}
   function caml_unix_filedescr_of_fd(x){return x;}
   function re_string_match(re, s, pos){
    if(pos < 0 || pos > caml_ml_string_length(s))
     caml_invalid_argument("Str.string_match");
    var res = re_match(re, s, pos, 0);
    return res ? res : [0];
   }
   function BigStringReader(bs, i){this.s = bs; this.i = i;}
   BigStringReader.prototype =
    {read8u: function(){return caml_ba_get_1(this.s, this.i++);},
     read8s: function(){return caml_ba_get_1(this.s, this.i++) << 24 >> 24;},
     read16u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return caml_ba_get_1(s, i) << 8 | caml_ba_get_1(s, i + 1);
     },
     read16s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 2;
      return caml_ba_get_1(s, i) << 24 >> 16 | caml_ba_get_1(s, i + 1);
     },
     read32u:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return (caml_ba_get_1(s, i) << 24 | caml_ba_get_1(s, i + 1) << 16
             | caml_ba_get_1(s, i + 2) << 8
             | caml_ba_get_1(s, i + 3))
             >>> 0;
     },
     read32s:
     function(){
      var s = this.s, i = this.i;
      this.i = i + 4;
      return caml_ba_get_1(s, i) << 24 | caml_ba_get_1(s, i + 1) << 16
             | caml_ba_get_1(s, i + 2) << 8
             | caml_ba_get_1(s, i + 3);
     },
     readstr:
     function(len){
      var i = this.i, arr = new Array(len);
      for(var j = 0; j < len; j++) arr[j] = caml_ba_get_1(this.s, i + j);
      this.i = i + len;
      return caml_string_of_array(arr);
     },
     readuint8array:
     function(len){
      var i = this.i, offset = this.offset(i);
      this.i = i + len;
      return this.s.data.subarray(offset, offset + len);
     }};
   function caml_gr_dump_image(im){
    var data = [0];
    for(var i = 0; i < im.height; i++){
     data[i + 1] = [0];
     for(var j = 0; j < im.width; j++){
      var
       o = i * (im.width * 4) + j * 4,
       r = im.data[o + 0],
       g = im.data[o + 1],
       b = im.data[o + 2];
      data[i + 1][j + 1] = (r << 16) + (g << 8) + b;
     }
    }
    return data;
   }
   function caml_ba_get_generic(ba, i){
    var ofs = ba.offset(caml_js_from_array(i));
    return ba.get(ofs);
   }
   function caml_unix_startup(){}
   function caml_get_exception_backtrace(){return 0;}
   function caml_format_float(fmt, x){
    function toFixed(x, dp){
     if(Math.abs(x) < 1.0)
      return x.toFixed(dp);
     else{
      var e = parseInt(x.toString().split("+")[1]);
      if(e > 20){
       e -= 20;
       x /= Math.pow(10, e);
       x += new Array(e + 1).join("0");
       if(dp > 0) x = x + "." + new Array(dp + 1).join("0");
       return x;
      }
      else
       return x.toFixed(dp);
     }
    }
    var s, f = caml_parse_format(fmt), prec = f.prec < 0 ? 6 : f.prec;
    if(x < 0 || x == 0 && 1 / x == - Infinity){f.sign = - 1; x = - x;}
    if(isNaN(x)){
     s = "nan";
     f.filler = " ";
    }
    else if(! isFinite(x)){
     s = "inf";
     f.filler = " ";
    }
    else
     switch(f.conv){
       case "e":
        var s = x.toExponential(prec), i = s.length;
        if(s.charAt(i - 3) == "e")
         s = s.slice(0, i - 1) + "0" + s.slice(i - 1);
        break;
       case "f":
        s = toFixed(x, prec); break;
       case "g":
        prec = prec ? prec : 1;
        s = x.toExponential(prec - 1);
        var j = s.indexOf("e"), exp = + s.slice(j + 1);
        if(exp < - 4 || x >= 1e21 || x.toFixed(0).length > prec){
         var i = j - 1;
         while(s.charAt(i) == "0") i--;
         if(s.charAt(i) == ".") i--;
         s = s.slice(0, i + 1) + s.slice(j);
         i = s.length;
         if(s.charAt(i - 3) == "e")
          s = s.slice(0, i - 1) + "0" + s.slice(i - 1);
         break;
        }
        else{
         var p = prec;
         if(exp < 0){
          p -= exp + 1;
          s = x.toFixed(p);
         }
         else
          while(s = x.toFixed(p), s.length > prec + 1) p--;
         if(p){
          var i = s.length - 1;
          while(s.charAt(i) == "0") i--;
          if(s.charAt(i) == ".") i--;
          s = s.slice(0, i + 1);
         }
        }
        break;
     }
    return caml_finish_formatting(f, s);
   }
   function caml_mount_autoload(name, f){
    var
     path = caml_make_path(name),
     name = caml_trailing_slash(path.join("/"));
    jsoo_mount_point.push({path: name, device: new MlFakeDevice(name, f)});
    return 0;
   }
   function caml_string_lessthan(s1, s2){return s1 < s2 ? 1 : 0;}
   function caml_string_greaterthan(s1, s2){return caml_string_lessthan(s2, s1);
   }
   function caml_div(x, y){
    if(y == 0) caml_raise_zero_divide();
    return x / y | 0;
   }
   function caml_obj_dup(x){
    var l = x.length, a = new Array(l);
    for(var i = 0; i < l; i++) a[i] = x[i];
    return a;
   }
   function caml_ephe_get_data_copy(x){
    return x[caml_ephe_data_offset] === undefined
            ? 0
            : [0, caml_obj_dup(x[caml_ephe_data_offset])];
   }
   function caml_memprof_start(rate, stack_size, tracker){return 0;}
   function caml_sys_get_argv(a){return [0, caml_argv[1], caml_argv];}
   function caml_ml_domain_set_name(_name){return 0;}
   function caml_js_to_bool(x){return + x;}
   function caml_gr_create_image(x, y){
    var s = caml_gr_state_get();
    return s.context.createImageData(x, y);
   }
   function caml_ephe_get_key_copy(x, i){
    if(i < 0 || caml_ephe_key_offset + i >= x.length)
     caml_invalid_argument("Weak.get_copy");
    var y = caml_ephe_get_key(x, i);
    if(y === 0) return y;
    var z = y[1];
    if(z instanceof Array) return [0, caml_obj_dup(z)];
    return y;
   }
   function caml_lessthan(x, y){return + (caml_compare_val(x, y, false) < 0);}
   function caml_raw_backtrace_next_slot(){return 0;}
   function caml_build_symbols(toc){
    var symb;
    while(toc)
     if(caml_jsstring_of_string(toc[1][1]) == "SYJS"){symb = toc[1][2]; break;}
     else
      toc = toc[2];
    var r = {};
    if(symb)
     for(var i = 1; i < symb.length; i++)
      r[caml_jsstring_of_string(symb[i][1])] = symb[i][2];
    return r;
   }
   function caml_register_global(n, v, name_opt){
    if(name_opt){
     var name = name_opt;
     if(globalThis.toplevelReloc)
      n = caml_callback(globalThis.toplevelReloc, [name]);
     else if(caml_global_data.toc){
      if(! caml_global_data.symbols)
       caml_global_data.symbols = caml_build_symbols(caml_global_data.toc);
      var nid = caml_global_data.symbols[name];
      if(nid >= 0)
       n = nid;
      else
       caml_failwith("caml_register_global: cannot locate " + name);
     }
    }
    caml_global_data[n + 1] = v;
    if(name_opt) caml_global_data[name_opt] = v;
   }
   function mult_nat(nat1, ofs1, len1, nat2, ofs2, len2, nat3, ofs3, len3){
    var carry = 0;
    for(var i = 0; i < len3; i++)
     carry +=
      mult_digit_nat
       (nat1, ofs1 + i, len1 - i, nat2, ofs2, len2, nat3, ofs3 + i);
    return carry;
   }
   function square_nat(nat1, ofs1, len1, nat2, ofs2, len2){
    var carry = 0;
    carry += add_nat(nat1, ofs1, len1, nat1, ofs1, len1, 0);
    carry += mult_nat(nat1, ofs1, len1, nat2, ofs2, len2, nat2, ofs2, len2);
    return carry;
   }
   function caml_js_from_float(x){return x;}
   function caml_floatarray_create(len){
    if(len < 0) caml_array_bound_error();
    var len = len + 1 | 0, b = new Array(len);
    b[0] = 254;
    for(var i = 1; i < len; i++) b[i] = 0;
    return b;
   }
   function caml_gc_stat(){
    return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
   }
   function caml_get_major_credit(n){return 0;}
   function caml_sys_modify_argv(arg){caml_argv = arg; return 0;}
   var caml_method_cache = [];
   function caml_get_public_method(obj, tag, cacheid){
    var meths = obj[1], ofs = caml_method_cache[cacheid];
    if(ofs === undefined)
     for(var i = caml_method_cache.length; i < cacheid; i++)
      caml_method_cache[i] = 0;
    else if(meths[ofs] === tag) return meths[ofs - 1];
    var li = 3, hi = meths[1] * 2 + 1, mi;
    while(li < hi){
     mi = li + hi >> 1 | 1;
     if(tag < meths[mi + 1]) hi = mi - 2; else li = mi;
    }
    caml_method_cache[cacheid] = li + 1;
    return tag == meths[li + 1] ? meths[li] : 0;
   }
   function caml_js_get_console(){
    var
     c = console,
     m =
       ["log",
        "debug",
        "info",
        "warn",
        "error",
        "assert",
        "dir",
        "dirxml",
        "trace",
        "group",
        "groupCollapsed",
        "groupEnd",
        "time",
        "timeEnd"];
    function f(){}
    for(var i = 0; i < m.length; i++) if(! c[m[i]]) c[m[i]] = f;
    return c;
   }
   function caml_sys_unsafe_getenv(name){return caml_sys_getenv(name);}
   function caml_ml_open_descriptor_in(fd){
    var file = caml_sys_fds[fd];
    if(file.flags.wronly) caml_raise_sys_error("fd " + fd + " is writeonly");
    var
     refill = null,
     channel =
       {file: file,
        offset: file.flags.append ? file.length() : 0,
        fd: fd,
        opened: true,
        out: false,
        buffer_curr: 0,
        buffer_max: 0,
        buffer: new Uint8Array(65536),
        refill: refill};
    caml_ml_channels[channel.fd] = channel;
    return channel.fd;
   }
   function bigstring_of_typed_array(ba){
    var
     ta =
       new
        Uint8Array
        (ba.buffer, ba.byteOffset, ba.length * ba.BYTES_PER_ELEMENT);
    return caml_ba_create_unsafe(12, 0, [ta.length], ta);
   }
   function caml_round_float(x){return Math.round(x);}
   function caml_ojs_new_arr(c, a){
    switch(a.length){
      case 0:
       return new c();
      case 1:
       return new c(a[0]);
      case 2:
       return new c(a[0], a[1]);
      case 3:
       return new c(a[0], a[1], a[2]);
      case 4:
       return new c(a[0], a[1], a[2], a[3]);
      case 5:
       return new c(a[0], a[1], a[2], a[3], a[4]);
      case 6:
       return new c(a[0], a[1], a[2], a[3], a[4], a[5]);
      case 7:
       return new c(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
    }
    function F(){return c.apply(this, a);}
    F.prototype = c.prototype;
    return new F();
   }
   function complement_nat(nat, ofs, len){
    for(var i = 0; i < len; i++)
     nat.data[ofs + i] = (- 1 >>> 0) - (nat.data[ofs + i] >>> 0);
   }
   var caml_domain_dls = [0];
   function caml_domain_dls_set(a){caml_domain_dls = a;}
   function caml_lazy_read_result(o){
    return caml_obj_tag(o) == 250 ? o[1] : o;
   }
   var caml_js_regexps = {amp: /&/g, lt: /</g, quot: /\"/g, all: /[&<\"]/};
   function caml_js_html_escape(s){
    if(! caml_js_regexps.all.test(s)) return s;
    return s.replace(caml_js_regexps.amp, "&amp;").replace
             (caml_js_regexps.lt, "&lt;").replace
            (caml_js_regexps.quot, "&quot;");
   }
   function caml_ba_dim_2(ba){return caml_ba_dim(ba, 1);}
   function caml_js_wrap_meth_callback_arguments(f){
    return function(){
     var len = arguments.length, args = new Array(len);
     for(var i = 0; i < len; i++) args[i] = arguments[i];
     return caml_callback(f, [this, args]);};
   }
   function caml_sinh_float(x){return Math.sinh(x);}
   function caml_ldexp_float(x, exp){
    exp |= 0;
    if(exp > 1023){
     exp -= 1023;
     x *= Math.pow(2, 1023);
     if(exp > 1023){exp -= 1023; x *= Math.pow(2, 1023);}
    }
    if(exp < - 1023){exp += 1023; x *= Math.pow(2, - 1023);}
    x *= Math.pow(2, exp);
    return x;
   }
   function caml_gr_state_set(ctx){
    caml_gr_state = ctx;
    caml_gr_state_init();
    return 0;
   }
   function caml_js_wrap_callback_strict(arity, f){
    return function(){
     var
      n = arguments.length,
      args = new Array(arity),
      len = Math.min(arguments.length, arity);
     for(var i = 0; i < len; i++) args[i] = arguments[i];
     return caml_callback(f, args);};
   }
   function caml_gc_minor_words(unit){return 0;}
   function caml_get_current_callstack(){return [0];}
   function land_digit_nat(nat1, ofs1, nat2, ofs2){nat1.data[ofs1] &= nat2.data[ofs2]; return 0;
   }
   function caml_int64_mod(x, y){return x.mod(y);}
   function caml_obj_set_tag(x, tag){x[0] = tag; return 0;}
   function caml_int32_bswap(x){
    return (x & 0x000000FF) << 24 | (x & 0x0000FF00) << 8
           | (x & 0x00FF0000) >>> 8
           | (x & 0xFF000000) >>> 24;
   }
   function caml_ba_set_3(ba, i0, i1, i2, v){
    ba.set(ba.offset([i0, i1, i2]), v);
    return 0;
   }
   function caml_js_instanceof(o, c){return o instanceof c ? 1 : 0;}
   function caml_get_major_bucket(n){return 0;}
   function nth_digit_nat_native(nat, ofs){return nat.data[ofs];}
   function set_digit_nat_native(nat, ofs, digit){nat.data[ofs] = digit; return 0;
   }
   function caml_string_set64(s, i, i64){caml_failwith("caml_string_set64");}
   function caml_gr_state_create(canvas, w, h){
    var context = canvas.getContext("2d");
    return {context: context,
            canvas: canvas,
            x: 0,
            y: 0,
            width: w,
            height: h,
            line_width: 1,
            font: caml_string_of_jsbytes("fixed"),
            text_size: 26,
            color: 0x000000,
            title: caml_string_of_jsbytes("")};
   }
   function caml_gr_draw_arc(x, y, rx, ry, a1, a2){
    var s = caml_gr_state_get();
    s.context.beginPath();
    caml_gr_arc_aux(s.context, x, s.height - y, rx, ry, a1, a2);
    s.context.stroke();
    return 0;
   }
   function caml_ba_map_file(vfd, kind, layout, shared, dims, pos){caml_failwith("caml_ba_map_file not implemented");
   }
   function caml_ba_map_file_bytecode(argv, argn){
    return caml_ba_map_file
            (argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
   }
   function caml_ba_create_from(data1, data2, jstyp, kind, layout, dims){
    if(data2 || caml_ba_get_size_per_element(kind) == 2)
     caml_invalid_argument
      ("caml_ba_create_from: use return caml_ba_create_unsafe");
    return caml_ba_create_unsafe(kind, layout, dims, data1);
   }
   function caml_tanh_float(x){return Math.tanh(x);}
   function caml_runtime_events_start(){return 0;}
   function caml_gr_draw_str(str){
    var s = caml_gr_state_get(), m = s.context.measureText(str), dx = m.width;
    s.context.fillText(str, s.x, s.height - s.y);
    s.x += dx | 0;
    return 0;
   }
   function caml_gr_draw_string(str){
    caml_gr_draw_str(caml_jsstring_of_string(str));
    return 0;
   }
   function caml_gr_draw_char(c){
    caml_gr_draw_str(String.fromCharCode(c));
    return 0;
   }
   function caml_unmount(name){
    var
     path = caml_make_path(name),
     name = caml_trailing_slash(path.join("/")),
     idx = - 1;
    for(var i = 0; i < jsoo_mount_point.length; i++)
     if(jsoo_mount_point[i].path == name) idx = i;
    if(idx > - 1) jsoo_mount_point.splice(idx, 1);
    return 0;
   }
   function caml_bigstring_blit_ba_to_ba(ba1, pos1, ba2, pos2, len){
    if(12 != ba1.kind)
     caml_invalid_argument("caml_bigstring_blit_ba_to_ba: kind mismatch");
    if(12 != ba2.kind)
     caml_invalid_argument("caml_bigstring_blit_ba_to_ba: kind mismatch");
    if(len == 0) return 0;
    var ofs1 = ba1.offset(pos1), ofs2 = ba2.offset(pos2);
    if(ofs1 + len > ba1.data.length) caml_array_bound_error();
    if(ofs2 + len > ba2.data.length) caml_array_bound_error();
    var slice = ba1.data.subarray(ofs1, ofs1 + len);
    ba2.data.set(slice, pos2);
    return 0;
   }
   function caml_input_value_from_string(s, ofs){
    var reader = new MlStringReader(s, typeof ofs == "number" ? ofs : ofs[0]);
    return caml_input_value_from_reader(reader, ofs);
   }
   function caml_ml_pos_in_64(chanid){
    return caml_int64_of_float(caml_pos_in(chanid));
   }
   function caml_gr_draw_image(im, x, y){
    var s = caml_gr_state_get();
    if(! im.image){
     var canvas = document.createElement("canvas");
     canvas.width = s.width;
     canvas.height = s.height;
     canvas.getContext("2d").putImageData(im, 0, 0);
     var image = new globalThis.Image();
     image.onload =
      function(){
       s.context.drawImage(image, x, s.height - im.height - y);
       im.image = image;
      };
     image.src = canvas.toDataURL("image/png");
    }
    else
     s.context.drawImage(im.image, x, s.height - im.height - y);
    return 0;
   }
   function caml_register_channel_for_spacetime(_channel){return 0;}
   function caml_string_set(s, i, c){caml_failwith("caml_string_set");}
   function caml_sys_rmdir(name){
    var root = resolve_fs_device(name);
    root.device.rmdir(root.rest);
    return 0;
   }
   function caml_unix_symlink(to_dir, src, dst){
    var src_root = resolve_fs_device(src), dst_root = resolve_fs_device(dst);
    if(src_root.device != dst_root.device)
     caml_failwith
      ("caml_unix_symlink: cannot symlink between two filesystems");
    if(! src_root.device.symlink)
     caml_failwith("caml_unix_symlink: not implemented");
    return src_root.device.symlink(to_dir, src_root.rest, dst_root.rest, true);
   }
   function caml_ml_pos_out(chanid){return caml_pos_out(chanid);}
   function caml_spacetime_enabled(_unit){return 0;}
   function caml_bytes_notequal(s1, s2){return 1 - caml_bytes_equal(s1, s2);}
   function caml_runtime_parameters(_unit){return caml_string_of_jsbytes("");}
   function caml_js_object(a){
    var o = {};
    for(var i = 1; i < a.length; i++){
     var p = a[i];
     o[caml_jsstring_of_string(p[1])] = p[2];
    }
    return o;
   }
   function caml_ba_create(kind, layout, dims_ml){
    var
     dims = caml_js_from_array(dims_ml),
     data = caml_ba_create_buffer(kind, caml_ba_get_size(dims));
    return caml_ba_create_unsafe(kind, layout, dims, data);
   }
   function caml_gr_remember_mode(){
    caml_failwith("caml_gr_remember_mode not Implemented");
   }
   function caml_fma_float(x, y, z){
    var
     SPLIT = Math.pow(2, 27) + 1,
     MIN_VALUE = Math.pow(2, - 1022),
     EPSILON = Math.pow(2, - 52),
     C = 416,
     A = Math.pow(2, + C),
     B = Math.pow(2, - C);
    function multiply(a, b){
     var
      at = SPLIT * a,
      ahi = at - (at - a),
      alo = a - ahi,
      bt = SPLIT * b,
      bhi = bt - (bt - b),
      blo = b - bhi,
      p = a * b,
      e = ahi * bhi - p + ahi * blo + alo * bhi + alo * blo;
     return {p: p, e: e};
    }
    function add(a, b){
     var s = a + b, v = s - a, e = a - (s - v) + (b - v);
     return {s: s, e: e};
    }
    function adjust(x, y){
     return x !== 0 && y !== 0 && SPLIT * x - (SPLIT * x - x) === x
             ? x * (1 + (x < 0 ? - 1 : + 1) * (y < 0 ? - 1 : + 1) * EPSILON)
             : x;
    }
    if
     (x === 0 || x !== x || x === + (1 / 0) || x === - (1 / 0) || y === 0
      || y !== y
      || y === + (1 / 0)
      || y === - (1 / 0))
     return x * y + z;
    if(z === 0) return x * y;
    if(z !== z || z === + (1 / 0) || z === - (1 / 0)) return z;
    var scale = 1;
    while(Math.abs(x) > A){scale *= A; x *= B;}
    while(Math.abs(y) > A){scale *= A; y *= B;}
    if(scale === 1 / 0) return x * y * scale;
    while(Math.abs(x) < B){scale *= B; x *= A;}
    while(Math.abs(y) < B){scale *= B; y *= A;}
    if(scale === 0) return z;
    var xs = x, ys = y, zs = z / scale;
    if(Math.abs(zs) > Math.abs(xs * ys) * 4 / EPSILON) return z;
    if(Math.abs(zs) < Math.abs(xs * ys) * EPSILON / 4 * EPSILON / 4)
     zs = (z < 0 ? - 1 : + 1) * MIN_VALUE;
    var
     xy = multiply(xs, ys),
     s = add(xy.p, zs),
     u = add(xy.e, s.e),
     i = add(s.s, u.s),
     f = i.s + adjust(i.e, u.e);
    if(f === 0) return f;
    var fs = f * scale;
    if(Math.abs(fs) > MIN_VALUE) return fs;
    return fs + adjust(f - fs / scale, i.e) * scale;
   }
   function caml_recommended_domain_count(unit){return 1;}
   function caml_bswap16(x){return (x & 0x00FF) << 8 | (x & 0xFF00) >> 8;}
   function caml_ml_set_binary_mode(chanid, mode){
    var chan = caml_ml_channels[chanid];
    chan.file.flags.text = ! mode;
    chan.file.flags.binary = mode;
    return 0;
   }
   function caml_final_register(){return 0;}
   function caml_gr_draw_rect(x, y, w, h){
    var s = caml_gr_state_get();
    s.context.strokeRect(x, s.height - y, w, - h);
    return 0;
   }
   function caml_string_get16(s, i){
    if(i >>> 0 >= caml_ml_string_length(s) - 1) caml_string_bound_error();
    var
     b1 = caml_string_unsafe_get(s, i),
     b2 = caml_string_unsafe_get(s, i + 1);
    return b2 << 8 | b1;
   }
   function caml_output_value(chanid, v, flags){
    var s = caml_output_value_to_string(v, flags);
    caml_ml_output(chanid, s, 0, caml_ml_string_length(s));
    return 0;
   }
   function caml_ba_get_3(ba, i0, i1, i2){
    return ba.get(ba.offset([i0, i1, i2]));
   }
   function caml_ephe_blit_key(a1, i1, a2, i2, len){
    caml_array_blit
     (a1,
      caml_ephe_key_offset + i1 - 1,
      a2,
      caml_ephe_key_offset + i2 - 1,
      len);
    return 0;
   }
   var caml_initial_time = new Date().getTime() * 0.001;
   function caml_sys_time(){
    var now = new Date().getTime();
    return now * 0.001 - caml_initial_time;
   }
   function caml_sys_time_include_children(b){return caml_sys_time();}
   function caml_check_bound(array, index){
    if(index >>> 0 >= array.length - 1) caml_array_bound_error();
    return array;
   }
   function caml_unix_getpwuid(unit){caml_raise_not_found();}
   function caml_hash(count, limit, seed, obj){
    var queue, rd, wr, sz, num, h, v, i, len;
    sz = limit;
    if(sz < 0 || sz > 256) sz = 256;
    num = count;
    h = seed;
    queue = [obj];
    rd = 0;
    wr = 1;
    while(rd < wr && num > 0){
     v = queue[rd++];
     if(v && v.caml_custom){
      if
       (caml_custom_ops[v.caml_custom] && caml_custom_ops[v.caml_custom].hash){
       var hh = caml_custom_ops[v.caml_custom].hash(v);
       h = caml_hash_mix_int(h, hh);
       num--;
      }
     }
     else if(v instanceof Array && v[0] === (v[0] | 0))
      switch(v[0]){
        case 248:
         h = caml_hash_mix_int(h, v[2]); num--; break;
        case 250:
         queue[--rd] = v[1]; break;
        default:
         if(caml_is_continuation_tag(v[0])) break;
         var tag = v.length - 1 << 10 | v[0];
         h = caml_hash_mix_int(h, tag);
         for(i = 1, len = v.length; i < len; i++){if(wr >= sz) break; queue[wr++] = v[i];
         }
         break;
      }
     else if(caml_is_ml_bytes(v)){
      h = caml_hash_mix_bytes(h, v);
      num--;
     }
     else if(caml_is_ml_string(v)){
      h = caml_hash_mix_string(h, v);
      num--;
     }
     else if(typeof v === "string"){
      h = caml_hash_mix_jsbytes(h, v);
      num--;
     }
     else if(v === (v | 0)){
      h = caml_hash_mix_int(h, v + v + 1);
      num--;
     }
     else if(v === + v){h = caml_hash_mix_float(h, v); num--;}
    }
    h = caml_hash_mix_final(h);
    return h & 0x3FFFFFFF;
   }
   function caml_ba_to_typed_array(ba){return ba.data;}
   function caml_domain_dls_get(unit){return caml_domain_dls;}
   function caml_bytes_get32(s, i){
    if(i >>> 0 >= s.l - 3) caml_bytes_bound_error();
    var
     b1 = caml_bytes_unsafe_get(s, i),
     b2 = caml_bytes_unsafe_get(s, i + 1),
     b3 = caml_bytes_unsafe_get(s, i + 2),
     b4 = caml_bytes_unsafe_get(s, i + 3);
    return b4 << 24 | b3 << 16 | b2 << 8 | b1;
   }
   function caml_frexp_float(x){
    if(x == 0 || ! isFinite(x)) return [0, x, 0];
    var neg = x < 0;
    if(neg) x = - x;
    var exp = Math.max(- 1023, jsoo_floor_log2(x) + 1);
    x *= Math.pow(2, - exp);
    while(x < 0.5){x *= 2; exp--;}
    while(x >= 1){x *= 0.5; exp++;}
    if(neg) x = - x;
    return [0, x, exp];
   }
   function caml_string_get64(s, i){
    if(i >>> 0 >= caml_ml_string_length(s) - 7) caml_string_bound_error();
    var a = new Array(8);
    for(var j = 0; j < 8; j++) a[7 - j] = caml_string_unsafe_get(s, i + j);
    return caml_int64_of_bytes(a);
   }
   function caml_js_error_option_of_exception(exn){
    if(exn.js_error) return [0, exn.js_error];
    return 0;
   }
   function caml_ml_pos_out_64(chanid){
    return caml_int64_of_float(caml_pos_out(chanid));
   }
   function caml_unix_findclose(dir_handle){return caml_unix_closedir(dir_handle);
   }
   function caml_gr_close_subwindow(a){
    caml_failwith("caml_gr_close_subwindow not Implemented");
   }
   function caml_floatarray_blit(a1, i1, a2, i2, len){
    if(i2 <= i1)
     for(var j = 1; j <= len; j++) a2[i2 + j] = a1[i1 + j];
    else
     for(var j = len; j >= 1; j--) a2[i2 + j] = a1[i1 + j];
    return 0;
   }
   function caml_get_minor_free(unit){return 0;}
   function caml_set_static_env(k, v){
    if(! globalThis.jsoo_static_env) globalThis.jsoo_static_env = {};
    globalThis.jsoo_static_env[k] = v;
    return 0;
   }
   function caml_ba_change_layout(ba, layout){
    if(ba.layout == layout) return ba;
    var new_dims = [];
    for(var i = 0; i < ba.dims.length; i++)
     new_dims[i] = ba.dims[ba.dims.length - i - 1];
    return caml_ba_create_unsafe(ba.kind, layout, new_dims, ba.data);
   }
   function caml_js_new(c, a){
    switch(a.length){
      case 1:
       return new c();
      case 2:
       return new c(a[1]);
      case 3:
       return new c(a[1], a[2]);
      case 4:
       return new c(a[1], a[2], a[3]);
      case 5:
       return new c(a[1], a[2], a[3], a[4]);
      case 6:
       return new c(a[1], a[2], a[3], a[4], a[5]);
      case 7:
       return new c(a[1], a[2], a[3], a[4], a[5], a[6]);
      case 8:
       return new c(a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
    }
    function F(){return c.apply(this, caml_js_from_array(a));}
    F.prototype = c.prototype;
    return new F();
   }
   function caml_gr_current_y(){var s = caml_gr_state_get(); return s.y;}
   function caml_format_int(fmt, i){
    if(caml_jsbytes_of_string(fmt) == "%d")
     return caml_string_of_jsbytes("" + i);
    var f = caml_parse_format(fmt);
    if(i < 0) if(f.signedconv){f.sign = - 1; i = - i;} else i >>>= 0;
    var s = i.toString(f.base);
    if(f.prec >= 0){
     f.filler = " ";
     var n = f.prec - s.length;
     if(n > 0) s = caml_str_repeat(n, "0") + s;
    }
    return caml_finish_formatting(f, s);
   }
   function jsoo_effect_not_supported(){
    caml_failwith("Effect handlers are not supported");
   }
   function caml_continuation_use_and_update_handler_noexc
   (cont, hval, hexn, heff){
    var stack = caml_continuation_use_noexc(cont);
    stack[3] = [0, hval, hexn, heff];
    return stack;
   }
   function caml_obj_truncate(x, s){
    if(s <= 0 || s + 1 > x.length) caml_invalid_argument("Obj.truncate");
    if(x.length != s + 1) x.length = s + 1;
    return 0;
   }
   function caml_js_to_string(s){return caml_string_of_jsstring(s);}
   function is_digit_odd(nat, ofs){if(nat.data[ofs] & 1) return 1; return 0;}
   function caml_runtime_variant(_unit){return caml_string_of_jsbytes("");}
   function caml_ml_open_descriptor_out(fd){
    var file = caml_sys_fds[fd];
    if(file.flags.rdonly) caml_raise_sys_error("fd " + fd + " is readonly");
    var
     buffered = file.flags.buffered !== undefined ? file.flags.buffered : 1,
     channel =
       {file: file,
        offset: file.flags.append ? file.length() : 0,
        fd: fd,
        opened: true,
        out: true,
        buffer_curr: 0,
        buffer: new Uint8Array(65536),
        buffered: buffered};
    caml_ml_channels[channel.fd] = channel;
    return channel.fd;
   }
   function caml_array_concat(l){
    var a = [0];
    while(l !== 0){
     var b = l[1];
     for(var i = 1; i < b.length; i++) a.push(b[i]);
     l = l[2];
    }
    return a;
   }
   function caml_gr_open_graph(info){
    var info = caml_jsstring_of_string(info);
    function get(name){
     var res = info.match("(^|,) *" + name + " *= *([a-zA-Z0-9_]+) *(,|$)");
     if(res) return res[2];
    }
    var specs = [];
    if(! (info == "")) specs.push(info);
    var target = get("target");
    if(! target) target = "";
    var status = get("status");
    if(! status) specs.push("status=1");
    var w = get("width");
    w = w ? parseInt(w) : 200;
    specs.push("width=" + w);
    var h = get("height");
    h = h ? parseInt(h) : 200;
    specs.push("height=" + h);
    var win = globalThis.open("about:blank", target, specs.join(","));
    if(! win) caml_failwith("Graphics.open_graph: cannot open the window");
    var doc = win.document, canvas = doc.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    var ctx = caml_gr_state_create(canvas, w, h);
    ctx.set_title = function(title){doc.title = title;};
    caml_gr_state_set(ctx);
    var body = doc.body;
    body.style.margin = "0px";
    body.appendChild(canvas);
    return 0;
   }
   function caml_make_float_vect(len){
    if(len < 0) caml_array_bound_error();
    var len = len + 1 | 0, b = new Array(len);
    b[0] = 254;
    for(var i = 1; i < len; i++) b[i] = 0;
    return b;
   }
   function caml_cbrt_float(x){return Math.cbrt(x);}
   function caml_eventlog_pause(unit){return 0;}
   function caml_memprof_stop(unit){return 0;}
   function caml_greaterequal(x, y){
    return + (caml_compare_val(x, y, false) >= 0);
   }
   function caml_get_exception_raw_backtrace(){return [0];}
   function caml_log1p_float(x){return Math.log1p(x);}
   function caml_runtime_events_free_cursor(cursor){return 0;}
   function caml_lazy_make_forward(v){return [250, v];}
   function lor_digit_nat(nat1, ofs1, nat2, ofs2){nat1.data[ofs1] |= nat2.data[ofs2]; return 0;
   }
   function caml_gr_blit_image(im, x, y){
    var
     s = caml_gr_state_get(),
     im2 =
       s.context.getImageData
        (x, s.height - im.height - y, im.width, im.height);
    for(var i = 0; i < im2.data.length; i += 4){
     im.data[i] = im2.data[i];
     im.data[i + 1] = im2.data[i + 1];
     im.data[i + 2] = im2.data[i + 2];
     im.data[i + 3] = im2.data[i + 3];
    }
    return 0;
   }
   function caml_gr_window_id(a){
    caml_failwith("caml_gr_window_id not Implemented");
   }
   function caml_js_on_ie(){
    var ua = globalThis.navigator ? globalThis.navigator.userAgent : "";
    return ua.indexOf("MSIE") != - 1 && ua.indexOf("Opera") != 0;
   }
   function caml_int64_shift_right(x, s){return x.shift_right(s);}
   function caml_ba_layout(ba){return ba.layout;}
   function caml_convert_raw_backtrace(){return [0];}
   function caml_array_set(array, index, newval){
    if(index < 0 || index >= array.length - 1) caml_array_bound_error();
    array[index + 1] = newval;
    return 0;
   }
   function caml_alloc_stack(hv, hx, hf){return 0;}
   function caml_bytes_greaterequal(s1, s2){return caml_bytes_lessequal(s2, s1);
   }
   function set_digit_nat(nat, ofs, digit){nat.data[ofs] = digit; return 0;}
   function caml_bytes_set16(s, i, i16){
    if(i >>> 0 >= s.l - 1) caml_bytes_bound_error();
    var b2 = 0xFF & i16 >> 8, b1 = 0xFF & i16;
    caml_bytes_unsafe_set(s, i + 0, b1);
    caml_bytes_unsafe_set(s, i + 1, b2);
    return 0;
   }
   function caml_gr_doc_of_state(state){
    if(state.canvas.ownerDocument) return state.canvas.ownerDocument;
   }
   function caml_ml_output_int(chanid, i){
    var
     arr = [i >> 24 & 0xFF, i >> 16 & 0xFF, i >> 8 & 0xFF, i & 0xFF],
     s = caml_string_of_array(arr);
    caml_ml_output(chanid, s, 0, 4);
    return 0;
   }
   function caml_obj_with_tag(tag, x){
    var l = x.length, a = new Array(l);
    a[0] = tag;
    for(var i = 1; i < l; i++) a[i] = x[i];
    return a;
   }
   function caml_ml_channel_size(chanid){
    var chan = caml_ml_channels[chanid];
    return chan.file.length();
   }
   function caml_raw_backtrace_slot(){
    caml_invalid_argument
     ("Printexc.get_raw_backtrace_slot: index out of bounds");
   }
   function caml_hexstring_of_float(x, prec, style){
    if(! isFinite(x)){
     if(isNaN(x)) return caml_string_of_jsstring("nan");
     return caml_string_of_jsstring(x > 0 ? "infinity" : "-infinity");
    }
    var sign = x == 0 && 1 / x == - Infinity ? 1 : x >= 0 ? 0 : 1;
    if(sign) x = - x;
    var exp = 0;
    if(x == 0)
     ;
    else if(x < 1)
     while(x < 1 && exp > - 1022){x *= 2; exp--;}
    else
     while(x >= 2){x /= 2; exp++;}
    var exp_sign = exp < 0 ? "" : "+", sign_str = "";
    if(sign)
     sign_str = "-";
    else
     switch(style){
       case 43:
        sign_str = "+"; break;
       case 32:
        sign_str = " "; break;
       default: break;
     }
    if(prec >= 0 && prec < 13){
     var cst = Math.pow(2, prec * 4);
     x = Math.round(x * cst) / cst;
    }
    var x_str = x.toString(16);
    if(prec >= 0){
     var idx = x_str.indexOf(".");
     if(idx < 0)
      x_str += "." + caml_str_repeat(prec, "0");
     else{
      var size = idx + 1 + prec;
      if(x_str.length < size)
       x_str += caml_str_repeat(size - x_str.length, "0");
      else
       x_str = x_str.substr(0, size);
     }
    }
    return caml_string_of_jsstring
            (sign_str + "0x" + x_str + "p" + exp_sign + exp.toString(10));
   }
   function caml_runtime_events_user_write(event, event_content){return 0;}
   function caml_js_wrap_meth_callback_strict(arity, f){
    return function(){
     var args = new Array(arity + 1), len = Math.min(arguments.length, arity);
     args[0] = this;
     for(var i = 0; i < len; i++) args[i + 1] = arguments[i];
     return caml_callback(f, args);};
   }
   function caml_unix_readlink(name){
    var root = resolve_fs_device(name);
    if(! root.device.readlink)
     caml_failwith("caml_unix_readlink: not implemented");
    return root.device.readlink(root.rest, true);
   }
   function caml_backtrace_status(_unit){
    return caml_record_backtrace_flag ? 1 : 0;
   }
   function caml_install_signal_handler(){return 0;}
   function caml_sys_argv(a){return caml_argv;}
   function caml_ba_fill(ba, v){ba.fill(v); return 0;}
   function caml_modf_float(x){
    if(isFinite(x)){
     var neg = 1 / x < 0;
     x = Math.abs(x);
     var i = Math.floor(x), f = x - i;
     if(neg){i = - i; f = - f;}
     return [0, f, i];
    }
    if(isNaN(x)) return [0, NaN, NaN];
    return [0, 1 / x, x];
   }
   function caml_gc_get(){return [0, 0, 0, 0, 0, 0, 0, 0, 0];}
   function caml_float_compare(x, y){
    if(x === y) return 0;
    if(x < y) return - 1;
    if(x > y) return 1;
    if(x === x) return 1;
    if(y === y) return - 1;
    return 0;
   }
   function caml_string_set32(s, i, i32){caml_failwith("caml_string_set32");}
   function caml_parse_engine(tables, env, cmd, arg){
    var
     ERRCODE = 256,
     loop = 6,
     testshift = 7,
     shift = 8,
     shift_recover = 9,
     reduce = 10,
     READ_TOKEN = 0,
     RAISE_PARSE_ERROR = 1,
     GROW_STACKS_1 = 2,
     GROW_STACKS_2 = 3,
     COMPUTE_SEMANTIC_ACTION = 4,
     CALL_ERROR_FUNCTION = 5,
     env_s_stack = 1,
     env_v_stack = 2,
     env_symb_start_stack = 3,
     env_symb_end_stack = 4,
     env_stacksize = 5,
     env_stackbase = 6,
     env_curr_char = 7,
     env_lval = 8,
     env_symb_start = 9,
     env_symb_end = 10,
     env_asp = 11,
     env_rule_len = 12,
     env_rule_number = 13,
     env_sp = 14,
     env_state = 15,
     env_errflag = 16,
     tbl_transl_const = 2,
     tbl_transl_block = 3,
     tbl_lhs = 4,
     tbl_len = 5,
     tbl_defred = 6,
     tbl_dgoto = 7,
     tbl_sindex = 8,
     tbl_rindex = 9,
     tbl_gindex = 10,
     tbl_tablesize = 11,
     tbl_table = 12,
     tbl_check = 13,
     tbl_names_const = 15,
     tbl_names_block = 16;
    function log(x){
     var s = caml_string_of_jsbytes(x + "\n");
     caml_ml_output(2, s, 0, caml_ml_string_length(s));
    }
    function token_name(names, number){
     var str = caml_jsstring_of_string(names);
     if(str[0] == "\x00") return "<unknown token>";
     return str.split("\x00")[number];
    }
    function print_token(state, tok){
     var token, kind;
     if(tok instanceof Array){
      token = token_name(tables[tbl_names_block], tok[0]);
      if(typeof tok[1] == "number")
       kind = "" + tok[1];
      else if(typeof tok[1] == "string")
       kind = tok[1];
      else if(tok[1] instanceof MlBytes)
       kind = caml_jsbytes_of_string(tok[1]);
      else
       kind = "_";
      log("State " + state + ": read token " + token + "(" + kind + ")");
     }
     else{
      token = token_name(tables[tbl_names_const], tok);
      log("State " + state + ": read token " + token);
     }
    }
    if(! tables.dgoto){
     tables.defred = caml_lex_array(tables[tbl_defred]);
     tables.sindex = caml_lex_array(tables[tbl_sindex]);
     tables.check = caml_lex_array(tables[tbl_check]);
     tables.rindex = caml_lex_array(tables[tbl_rindex]);
     tables.table = caml_lex_array(tables[tbl_table]);
     tables.len = caml_lex_array(tables[tbl_len]);
     tables.lhs = caml_lex_array(tables[tbl_lhs]);
     tables.gindex = caml_lex_array(tables[tbl_gindex]);
     tables.dgoto = caml_lex_array(tables[tbl_dgoto]);
    }
    var
     res = 0,
     n,
     n1,
     n2,
     state1,
     sp = env[env_sp],
     state = env[env_state],
     errflag = env[env_errflag];
    exit:
    for(;;)
     next:
     switch(cmd){
       case 0:
        state = 0; errflag = 0;
       case 6:
        n = tables.defred[state];
        if(n != 0){cmd = reduce; break;}
        if(env[env_curr_char] >= 0){cmd = testshift; break;}
        res = READ_TOKEN;
        break exit;
       case 1:
        if(arg instanceof Array){
         env[env_curr_char] = tables[tbl_transl_block][arg[0] + 1];
         env[env_lval] = arg[1];
        }
        else{
         env[env_curr_char] = tables[tbl_transl_const][arg + 1];
         env[env_lval] = 0;
        }
        if(caml_parser_trace) print_token(state, arg);
       case 7:
        n1 = tables.sindex[state];
        n2 = n1 + env[env_curr_char];
        if
         (n1 != 0 && n2 >= 0 && n2 <= tables[tbl_tablesize]
          && tables.check[n2] == env[env_curr_char]){cmd = shift; break;}
        n1 = tables.rindex[state];
        n2 = n1 + env[env_curr_char];
        if
         (n1 != 0 && n2 >= 0 && n2 <= tables[tbl_tablesize]
          && tables.check[n2] == env[env_curr_char]){
         n = tables.table[n2];
         cmd = reduce;
         break;
        }
        if(errflag <= 0){res = CALL_ERROR_FUNCTION; break exit;}
       case 5:
        if(errflag < 3){
         errflag = 3;
         for(;;){
          state1 = env[env_s_stack][sp + 1];
          n1 = tables.sindex[state1];
          n2 = n1 + ERRCODE;
          if
           (n1 != 0 && n2 >= 0 && n2 <= tables[tbl_tablesize]
            && tables.check[n2] == ERRCODE){
           if(caml_parser_trace) log("Recovering in state " + state1);
           cmd = shift_recover;
           break next;
          }
          else{
           if(caml_parser_trace) log("Discarding state " + state1);
           if(sp <= env[env_stackbase]){
            if(caml_parser_trace) log("No more states to discard");
            return RAISE_PARSE_ERROR;
           }
           sp--;
          }
         }
        }
        else{
         if(env[env_curr_char] == 0) return RAISE_PARSE_ERROR;
         if(caml_parser_trace) log("Discarding last token read");
         env[env_curr_char] = - 1;
         cmd = loop;
         break;
        }
       case 8:
        env[env_curr_char] = - 1; if(errflag > 0) errflag--;
       case 9:
        if(caml_parser_trace)
         log("State " + state + ": shift to state " + tables.table[n2]);
        state = tables.table[n2];
        sp++;
        if(sp >= env[env_stacksize]){res = GROW_STACKS_1; break exit;}
       case 2:
        env[env_s_stack][sp + 1] = state;
        env[env_v_stack][sp + 1] = env[env_lval];
        env[env_symb_start_stack][sp + 1] = env[env_symb_start];
        env[env_symb_end_stack][sp + 1] = env[env_symb_end];
        cmd = loop;
        break;
       case 10:
        if(caml_parser_trace) log("State " + state + ": reduce by rule " + n);
        var m = tables.len[n];
        env[env_asp] = sp;
        env[env_rule_number] = n;
        env[env_rule_len] = m;
        sp = sp - m + 1;
        m = tables.lhs[n];
        state1 = env[env_s_stack][sp];
        n1 = tables.gindex[m];
        n2 = n1 + state1;
        if
         (n1 != 0 && n2 >= 0 && n2 <= tables[tbl_tablesize]
          && tables.check[n2] == state1)
         state = tables.table[n2];
        else
         state = tables.dgoto[m];
        if(sp >= env[env_stacksize]){res = GROW_STACKS_2; break exit;}
       case 3:
        res = COMPUTE_SEMANTIC_ACTION; break exit;
       case 4:
        env[env_s_stack][sp + 1] = state;
        env[env_v_stack][sp + 1] = arg;
        var asp = env[env_asp];
        env[env_symb_end_stack][sp + 1] = env[env_symb_end_stack][asp + 1];
        if(sp > asp)
         env[env_symb_start_stack][sp + 1] = env[env_symb_end_stack][asp + 1];
        cmd = loop;
        break;
       default: return RAISE_PARSE_ERROR;
     }
    env[env_sp] = sp;
    env[env_state] = state;
    env[env_errflag] = errflag;
    return res;
   }
   function caml_jsoo_flags_effects(unit){return 0;}
   function caml_update_dummy(x, y){
    if(typeof y === "function"){x.fun = y; return 0;}
    if(y.fun){x.fun = y.fun; return 0;}
    var i = y.length;
    while(i--) x[i] = y[i];
    return 0;
   }
   function caml_array_fill(array, ofs, len, v){
    for(var i = 0; i < len; i++) array[ofs + i + 1] = v;
    return 0;
   }
   function caml_sys_mkdir(name, perm){
    var root = resolve_fs_device(name);
    root.device.mkdir(root.rest, perm);
    return 0;
   }
   function caml_string_notequal(s1, s2){
    return 1 - caml_string_equal(s1, s2);
   }
   function caml_bytes_greaterthan(s1, s2){return caml_bytes_lessthan(s2, s1);
   }
   function caml_gr_make_image(arr){
    var
     s = caml_gr_state_get(),
     h = arr.length - 1,
     w = arr[1].length - 1,
     im = s.context.createImageData(w, h);
    for(var i = 0; i < h; i++)
     for(var j = 0; j < w; j++){
      var c = arr[i + 1][j + 1], o = i * (w * 4) + j * 4;
      if(c == - 1){
       im.data[o + 0] = 0;
       im.data[o + 1] = 0;
       im.data[o + 2] = 0;
       im.data[o + 3] = 0;
      }
      else{
       im.data[o + 0] = c >> 16 & 0xff;
       im.data[o + 1] = c >> 8 & 0xff;
       im.data[o + 2] = c >> 0 & 0Xff;
       im.data[o + 3] = 0xff;
      }
     }
    return im;
   }
   function caml_ml_set_channel_output(chanid, f){
    var chan = caml_ml_channels[chanid];
    chan.output = function(s){f(s);};
    return 0;
   }
   function caml_read_file_content(name){
    var
     name = typeof name == "string" ? caml_string_of_jsbytes(name) : name,
     root = resolve_fs_device(name);
    if(root.device.exists(root.rest)){
     var
      file = root.device.open(root.rest, {rdonly: 1}),
      len = file.length(),
      buf = new Uint8Array(len);
     file.read(0, buf, 0, len);
     return caml_string_of_array(buf);
    }
    caml_raise_no_such_file(caml_jsbytes_of_string(name));
   }
   function caml_js_to_float(x){return x;}
   function caml_setup_uncaught_exception_handler(){
    var process = globalThis.process;
    if(process && process.on)
     process.on
      ("uncaughtException",
       function(err, origin){
        caml_fatal_uncaught_exception(err);
        process.exit(2);
       });
    else if(globalThis.addEventListener)
     globalThis.addEventListener
      ("error",
       function(event){
        if(event.error) caml_fatal_uncaught_exception(event.error);
       });
   }
   caml_setup_uncaught_exception_handler();
   globalThis.jsoo_runtime =
    {caml_runtime_events_read_poll: caml_runtime_events_read_poll,
     caml_runtime_events_free_cursor: caml_runtime_events_free_cursor,
     caml_runtime_events_create_cursor: caml_runtime_events_create_cursor,
     caml_runtime_events_resume: caml_runtime_events_resume,
     caml_runtime_events_pause: caml_runtime_events_pause,
     caml_runtime_events_start: caml_runtime_events_start,
     caml_runtime_events_user_resolve: caml_runtime_events_user_resolve,
     caml_runtime_events_user_write: caml_runtime_events_user_write,
     caml_runtime_events_user_register: caml_runtime_events_user_register,
     caml_custom_event_index: caml_custom_event_index,
     zstd_decompress: zstd_decompress,
     jsoo_effect_not_supported: jsoo_effect_not_supported,
     caml_ml_condition_signal: caml_ml_condition_signal,
     caml_ml_condition_broadcast: caml_ml_condition_broadcast,
     caml_ml_condition_wait: caml_ml_condition_wait,
     caml_ml_condition_new: caml_ml_condition_new,
     caml_get_continuation_callstack: caml_get_continuation_callstack,
     caml_continuation_use_and_update_handler_noexc:
     caml_continuation_use_and_update_handler_noexc,
     caml_continuation_use_noexc: caml_continuation_use_noexc,
     caml_alloc_stack: caml_alloc_stack,
     caml_ml_mutex_unlock: caml_ml_mutex_unlock,
     caml_ml_mutex_try_lock: caml_ml_mutex_try_lock,
     caml_ml_mutex_lock: caml_ml_mutex_lock,
     caml_ml_mutex_new: caml_ml_mutex_new,
     MlMutex: MlMutex,
     caml_lxm_next: caml_lxm_next,
     caml_ml_domain_cpu_relax: caml_ml_domain_cpu_relax,
     caml_ml_domain_id: caml_ml_domain_id,
     caml_domain_spawn: caml_domain_spawn,
     caml_domain_id: caml_domain_id,
     caml_recommended_domain_count: caml_recommended_domain_count,
     caml_ml_domain_set_name: caml_ml_domain_set_name,
     caml_ml_domain_unique_token: caml_ml_domain_unique_token,
     caml_atomic_exchange: caml_atomic_exchange,
     caml_atomic_fetch_add: caml_atomic_fetch_add,
     caml_atomic_cas: caml_atomic_cas,
     caml_atomic_load: caml_atomic_load,
     caml_domain_dls_get: caml_domain_dls_get,
     caml_domain_dls_set: caml_domain_dls_set,
     caml_domain_dls: caml_domain_dls,
     caml_ephe_check_data: caml_ephe_check_data,
     caml_ephe_unset_data: caml_ephe_unset_data,
     caml_ephe_set_data: caml_ephe_set_data,
     caml_ephe_get_data_copy: caml_ephe_get_data_copy,
     caml_ephe_get_data: caml_ephe_get_data,
     caml_ephe_blit_data: caml_ephe_blit_data,
     caml_ephe_blit_key: caml_ephe_blit_key,
     caml_ephe_check_key: caml_ephe_check_key,
     caml_ephe_get_key_copy: caml_ephe_get_key_copy,
     caml_ephe_get_key: caml_ephe_get_key,
     caml_weak_set: caml_weak_set,
     caml_weak_create: caml_weak_create,
     caml_ephe_create: caml_ephe_create,
     caml_ephe_unset_key: caml_ephe_unset_key,
     caml_ephe_set_key: caml_ephe_set_key,
     caml_ephe_data_offset: caml_ephe_data_offset,
     caml_ephe_key_offset: caml_ephe_key_offset,
     caml_unix_inet_addr_of_string: caml_unix_inet_addr_of_string,
     caml_unix_findclose: caml_unix_findclose,
     caml_unix_findnext: caml_unix_findnext,
     caml_unix_findfirst: caml_unix_findfirst,
     caml_unix_rewinddir: caml_unix_rewinddir,
     caml_unix_closedir: caml_unix_closedir,
     caml_unix_readdir: caml_unix_readdir,
     caml_unix_opendir: caml_unix_opendir,
     caml_unix_has_symlink: caml_unix_has_symlink,
     caml_unix_getpwuid: caml_unix_getpwuid,
     caml_unix_getuid: caml_unix_getuid,
     caml_unix_unlink: caml_unix_unlink,
     caml_unix_readlink: caml_unix_readlink,
     caml_unix_symlink: caml_unix_symlink,
     caml_unix_rmdir: caml_unix_rmdir,
     caml_unix_mkdir: caml_unix_mkdir,
     caml_unix_lstat_64: caml_unix_lstat_64,
     caml_unix_lstat: caml_unix_lstat,
     caml_unix_stat_64: caml_unix_stat_64,
     caml_unix_stat: caml_unix_stat,
     make_unix_err_args: make_unix_err_args,
     caml_unix_isatty: caml_unix_isatty,
     caml_unix_filedescr_of_fd: caml_unix_filedescr_of_fd,
     caml_unix_cleanup: caml_unix_cleanup,
     caml_unix_startup: caml_unix_startup,
     caml_unix_mktime: caml_unix_mktime,
     caml_unix_localtime: caml_unix_localtime,
     caml_unix_gmtime: caml_unix_gmtime,
     caml_unix_time: caml_unix_time,
     caml_unix_gettimeofday: caml_unix_gettimeofday,
     caml_str_initialize: caml_str_initialize,
     re_replacement_text: re_replacement_text,
     re_partial_match: re_partial_match,
     re_string_match: re_string_match,
     re_search_backward: re_search_backward,
     re_search_forward: re_search_forward,
     re_match: re_match,
     caml_sys_is_regular_file: caml_sys_is_regular_file,
     caml_spacetime_only_works_for_native_code:
     caml_spacetime_only_works_for_native_code,
     caml_register_channel_for_spacetime: caml_register_channel_for_spacetime,
     caml_sys_const_naked_pointers_checked:
     caml_sys_const_naked_pointers_checked,
     caml_spacetime_enabled: caml_spacetime_enabled,
     caml_ml_runtime_warnings_enabled: caml_ml_runtime_warnings_enabled,
     caml_ml_enable_runtime_warnings: caml_ml_enable_runtime_warnings,
     caml_runtime_warnings: caml_runtime_warnings,
     caml_install_signal_handler: caml_install_signal_handler,
     caml_runtime_parameters: caml_runtime_parameters,
     caml_runtime_variant: caml_runtime_variant,
     caml_sys_isatty: caml_sys_isatty,
     caml_sys_get_config: caml_sys_get_config,
     os_type: os_type,
     caml_sys_const_backend_type: caml_sys_const_backend_type,
     caml_sys_const_ostype_cygwin: caml_sys_const_ostype_cygwin,
     caml_sys_const_ostype_win32: caml_sys_const_ostype_win32,
     caml_sys_const_ostype_unix: caml_sys_const_ostype_unix,
     caml_sys_const_max_wosize: caml_sys_const_max_wosize,
     caml_sys_const_int_size: caml_sys_const_int_size,
     caml_sys_const_word_size: caml_sys_const_word_size,
     caml_sys_const_big_endian: caml_sys_const_big_endian,
     caml_sys_random_seed: caml_sys_random_seed,
     caml_sys_time_include_children: caml_sys_time_include_children,
     caml_sys_time: caml_sys_time,
     caml_sys_system_command: caml_sys_system_command,
     caml_sys_executable_name: caml_sys_executable_name,
     caml_sys_modify_argv: caml_sys_modify_argv,
     caml_sys_argv: caml_sys_argv,
     caml_sys_get_argv: caml_sys_get_argv,
     caml_executable_name: caml_executable_name,
     caml_argv: caml_argv,
     caml_sys_unsafe_getenv: caml_sys_unsafe_getenv,
     caml_sys_getenv: caml_sys_getenv,
     jsoo_sys_getenv: jsoo_sys_getenv,
     caml_set_static_env: caml_set_static_env,
     caml_fatal_uncaught_exception: caml_fatal_uncaught_exception,
     caml_format_exception: caml_format_exception,
     caml_is_special_exception: caml_is_special_exception,
     caml_sys_exit: caml_sys_exit,
     caml_raise_sys_error: caml_raise_sys_error,
     caml_maybe_print_stats: caml_maybe_print_stats,
     caml_is_printable: caml_is_printable,
     caml_get_global_data: caml_get_global_data,
     caml_register_global: caml_register_global,
     caml_build_symbols: caml_build_symbols,
     caml_global_data: caml_global_data,
     caml_named_value: caml_named_value,
     caml_register_named_value: caml_register_named_value,
     caml_named_values: caml_named_values,
     caml_call_gen: caml_call_gen,
     caml_set_parser_trace: caml_set_parser_trace,
     caml_parse_engine: caml_parse_engine,
     caml_parser_trace: caml_parser_trace,
     caml_is_continuation_tag: caml_is_continuation_tag,
     caml_lazy_read_result: caml_lazy_read_result,
     caml_lazy_reset_to_lazy: caml_lazy_reset_to_lazy,
     caml_lazy_update_to_forward: caml_lazy_update_to_forward,
     caml_lazy_update_to_forcing: caml_lazy_update_to_forcing,
     caml_obj_update_tag: caml_obj_update_tag,
     caml_obj_add_offset: caml_obj_add_offset,
     caml_obj_reachable_words: caml_obj_reachable_words,
     caml_obj_set_raw_field: caml_obj_set_raw_field,
     caml_obj_raw_field: caml_obj_raw_field,
     caml_fresh_oo_id: caml_fresh_oo_id,
     caml_set_oo_id: caml_set_oo_id,
     caml_oo_last_id: caml_oo_last_id,
     caml_get_public_method: caml_get_public_method,
     caml_lazy_make_forward: caml_lazy_make_forward,
     caml_obj_is_shared: caml_obj_is_shared,
     caml_obj_compare_and_swap: caml_obj_compare_and_swap,
     caml_obj_make_forward: caml_obj_make_forward,
     caml_obj_truncate: caml_obj_truncate,
     caml_obj_dup: caml_obj_dup,
     caml_obj_with_tag: caml_obj_with_tag,
     caml_obj_block: caml_obj_block,
     caml_obj_set_tag: caml_obj_set_tag,
     caml_obj_tag: caml_obj_tag,
     caml_obj_is_block: caml_obj_is_block,
     caml_alloc_dummy_infix: caml_alloc_dummy_infix,
     caml_update_dummy: caml_update_dummy,
     deserialize_nat: deserialize_nat,
     serialize_nat: serialize_nat,
     lxor_digit_nat: lxor_digit_nat,
     lor_digit_nat: lor_digit_nat,
     land_digit_nat: land_digit_nat,
     compare_nat_real: compare_nat_real,
     compare_nat: compare_nat,
     compare_digits_nat: compare_digits_nat,
     shift_right_nat: shift_right_nat,
     div_nat: div_nat,
     div_digit_nat: div_digit_nat,
     div_helper: div_helper,
     shift_left_nat: shift_left_nat,
     square_nat: square_nat,
     mult_nat: mult_nat,
     mult_digit_nat: mult_digit_nat,
     sub_nat: sub_nat,
     decr_nat: decr_nat,
     complement_nat: complement_nat,
     add_nat: add_nat,
     incr_nat: incr_nat,
     is_digit_odd: is_digit_odd,
     is_digit_zero: is_digit_zero,
     is_digit_int: is_digit_int,
     num_leading_zero_bits_in_digit: num_leading_zero_bits_in_digit,
     num_digits_nat: num_digits_nat,
     nth_digit_nat_native: nth_digit_nat_native,
     set_digit_nat_native: set_digit_nat_native,
     nth_digit_nat: nth_digit_nat,
     set_digit_nat: set_digit_nat,
     blit_nat: blit_nat,
     set_to_zero_nat: set_to_zero_nat,
     create_nat: create_nat,
     nat_of_array: nat_of_array,
     caml_hash_nat: caml_hash_nat,
     MlNat: MlNat,
     initialize_nat: initialize_nat,
     caml_array_of_bytes: caml_array_of_bytes,
     caml_array_of_string: caml_array_of_string,
     caml_js_to_string: caml_js_to_string,
     caml_to_js_string: caml_to_js_string,
     caml_js_from_string: caml_js_from_string,
     caml_new_string: caml_new_string,
     caml_js_to_byte_string: caml_js_to_byte_string,
     caml_is_ml_string: caml_is_ml_string,
     caml_ml_bytes_content: caml_ml_bytes_content,
     caml_is_ml_bytes: caml_is_ml_bytes,
     caml_bytes_of_jsbytes: caml_bytes_of_jsbytes,
     caml_string_of_jsstring: caml_string_of_jsstring,
     caml_jsstring_of_string: caml_jsstring_of_string,
     caml_jsbytes_of_string: caml_jsbytes_of_string,
     caml_string_of_jsbytes: caml_string_of_jsbytes,
     caml_bytes_of_string: caml_bytes_of_string,
     caml_string_of_bytes: caml_string_of_bytes,
     caml_string_lessthan: caml_string_lessthan,
     caml_string_lessequal: caml_string_lessequal,
     caml_string_equal: caml_string_equal,
     caml_string_compare: caml_string_compare,
     caml_ml_string_length: caml_ml_string_length,
     caml_string_unsafe_set: caml_string_unsafe_set,
     caml_string_unsafe_get: caml_string_unsafe_get,
     caml_ml_bytes_length: caml_ml_bytes_length,
     caml_blit_string: caml_blit_string,
     caml_blit_bytes: caml_blit_bytes,
     caml_fill_bytes: caml_fill_bytes,
     caml_bytes_greaterthan: caml_bytes_greaterthan,
     caml_string_greaterthan: caml_string_greaterthan,
     caml_bytes_greaterequal: caml_bytes_greaterequal,
     caml_string_greaterequal: caml_string_greaterequal,
     caml_bytes_lessthan: caml_bytes_lessthan,
     caml_bytes_lessequal: caml_bytes_lessequal,
     caml_bytes_notequal: caml_bytes_notequal,
     caml_string_notequal: caml_string_notequal,
     caml_bytes_equal: caml_bytes_equal,
     caml_bytes_compare: caml_bytes_compare,
     caml_bytes_of_array: caml_bytes_of_array,
     caml_string_of_array: caml_string_of_array,
     caml_create_bytes: caml_create_bytes,
     caml_create_string: caml_create_string,
     caml_uint8_array_of_string: caml_uint8_array_of_string,
     caml_uint8_array_of_bytes: caml_uint8_array_of_bytes,
     caml_convert_bytes_to_array: caml_convert_bytes_to_array,
     caml_convert_string_to_bytes: caml_convert_string_to_bytes,
     MlBytes: MlBytes,
     caml_bytes_of_utf16_jsstring: caml_bytes_of_utf16_jsstring,
     caml_bytes_set: caml_bytes_set,
     caml_string_set64: caml_string_set64,
     caml_bytes_set64: caml_bytes_set64,
     caml_string_set32: caml_string_set32,
     caml_bytes_set32: caml_bytes_set32,
     caml_string_set16: caml_string_set16,
     caml_bytes_set16: caml_bytes_set16,
     caml_string_set: caml_string_set,
     caml_bytes_get: caml_bytes_get,
     caml_bytes_get64: caml_bytes_get64,
     caml_string_get64: caml_string_get64,
     caml_bytes_get32: caml_bytes_get32,
     caml_string_get32: caml_string_get32,
     caml_bytes_get16: caml_bytes_get16,
     caml_string_get16: caml_string_get16,
     caml_string_get: caml_string_get,
     caml_bytes_bound_error: caml_bytes_bound_error,
     caml_string_bound_error: caml_string_bound_error,
     caml_bytes_unsafe_set: caml_bytes_unsafe_set,
     caml_bytes_unsafe_get: caml_bytes_unsafe_get,
     jsoo_is_ascii: jsoo_is_ascii,
     caml_utf16_of_utf8: caml_utf16_of_utf8,
     caml_utf8_of_utf16: caml_utf8_of_utf16,
     caml_subarray_to_jsbytes: caml_subarray_to_jsbytes,
     caml_str_repeat: caml_str_repeat,
     caml_md5_bytes: caml_md5_bytes,
     caml_MD5Final: caml_MD5Final,
     caml_MD5Update: caml_MD5Update,
     caml_MD5Init: caml_MD5Init,
     caml_MD5Transform: caml_MD5Transform,
     caml_md5_string: caml_md5_string,
     caml_md5_chan: caml_md5_chan,
     caml_output_value_to_buffer: caml_output_value_to_buffer,
     caml_output_value_to_bytes: caml_output_value_to_bytes,
     caml_output_value_to_string: caml_output_value_to_string,
     caml_output_val: caml_output_val,
     MlObjectTable: MlObjectTable,
     caml_marshal_data_size: caml_marshal_data_size,
     caml_marshal_header_size: caml_marshal_header_size,
     caml_input_value_from_reader: caml_input_value_from_reader,
     caml_custom_ops: caml_custom_ops,
     caml_nativeint_unmarshal: caml_nativeint_unmarshal,
     caml_int32_unmarshal: caml_int32_unmarshal,
     caml_int64_marshal: caml_int64_marshal,
     caml_int64_unmarshal: caml_int64_unmarshal,
     caml_input_value_from_bytes: caml_input_value_from_bytes,
     caml_input_value_from_string: caml_input_value_from_string,
     caml_float_of_bytes: caml_float_of_bytes,
     BigStringReader: BigStringReader,
     MlStringReader: MlStringReader,
     UInt8ArrayReader: UInt8ArrayReader,
     caml_marshal_constants: caml_marshal_constants,
     caml_new_lex_engine: caml_new_lex_engine,
     caml_lex_engine: caml_lex_engine,
     caml_lex_array: caml_lex_array,
     caml_js_error_of_exception: caml_js_error_of_exception,
     caml_xmlhttprequest_create: caml_xmlhttprequest_create,
     caml_js_get_console: caml_js_get_console,
     caml_js_html_entities: caml_js_html_entities,
     caml_js_html_escape: caml_js_html_escape,
     caml_js_on_ie: caml_js_on_ie,
     caml_js_object: caml_js_object,
     caml_pure_js_expr: caml_pure_js_expr,
     caml_js_expr: caml_js_expr,
     caml_js_eval_string: caml_js_eval_string,
     caml_js_equals: caml_js_equals,
     caml_js_function_arity: caml_js_function_arity,
     caml_js_wrap_meth_callback_unsafe: caml_js_wrap_meth_callback_unsafe,
     caml_js_wrap_meth_callback_strict: caml_js_wrap_meth_callback_strict,
     caml_js_wrap_meth_callback_arguments:
     caml_js_wrap_meth_callback_arguments,
     caml_js_wrap_meth_callback: caml_js_wrap_meth_callback,
     caml_js_wrap_callback_unsafe: caml_js_wrap_callback_unsafe,
     caml_js_wrap_callback_strict: caml_js_wrap_callback_strict,
     caml_js_wrap_callback_arguments: caml_js_wrap_callback_arguments,
     caml_js_wrap_callback: caml_js_wrap_callback,
     caml_ojs_new_arr: caml_ojs_new_arr,
     caml_js_new: caml_js_new,
     caml_js_meth_call: caml_js_meth_call,
     caml_js_fun_call: caml_js_fun_call,
     caml_js_call: caml_js_call,
     caml_js_var: caml_js_var,
     caml_list_to_js_array: caml_list_to_js_array,
     caml_list_of_js_array: caml_list_of_js_array,
     caml_js_to_array: caml_js_to_array,
     caml_js_from_array: caml_js_from_array,
     caml_js_to_float: caml_js_to_float,
     caml_js_from_float: caml_js_from_float,
     caml_js_to_bool: caml_js_to_bool,
     caml_js_from_bool: caml_js_from_bool,
     caml_js_error_option_of_exception: caml_js_error_option_of_exception,
     caml_exn_with_js_backtrace: caml_exn_with_js_backtrace,
     caml_maybe_attach_backtrace: caml_maybe_attach_backtrace,
     caml_wrap_exception: caml_wrap_exception,
     caml_jsoo_flags_effects: caml_jsoo_flags_effects,
     caml_jsoo_flags_use_js_string: caml_jsoo_flags_use_js_string,
     caml_is_js: caml_is_js,
     caml_callback: caml_callback,
     caml_trampoline_return: caml_trampoline_return,
     caml_trampoline: caml_trampoline,
     caml_js_typeof: caml_js_typeof,
     caml_js_instanceof: caml_js_instanceof,
     caml_js_delete: caml_js_delete,
     caml_js_get: caml_js_get,
     caml_js_set: caml_js_set,
     caml_js_pure_expr: caml_js_pure_expr,
     caml_ml_set_buffered: caml_ml_set_buffered,
     caml_ml_is_buffered: caml_ml_is_buffered,
     caml_ml_output_int: caml_ml_output_int,
     caml_ml_pos_out_64: caml_ml_pos_out_64,
     caml_ml_pos_out: caml_ml_pos_out,
     caml_pos_out: caml_pos_out,
     caml_ml_seek_out_64: caml_ml_seek_out_64,
     caml_ml_seek_out: caml_ml_seek_out,
     caml_seek_out: caml_seek_out,
     caml_output_value: caml_output_value,
     caml_ml_output_char: caml_ml_output_char,
     caml_ml_output: caml_ml_output,
     caml_ml_output_bytes: caml_ml_output_bytes,
     caml_ml_flush: caml_ml_flush,
     caml_ml_input_scan_line: caml_ml_input_scan_line,
     caml_ml_pos_in_64: caml_ml_pos_in_64,
     caml_ml_pos_in: caml_ml_pos_in,
     caml_pos_in: caml_pos_in,
     caml_ml_seek_in_64: caml_ml_seek_in_64,
     caml_ml_seek_in: caml_ml_seek_in,
     caml_seek_in: caml_seek_in,
     caml_ml_input_int: caml_ml_input_int,
     caml_ml_input_char: caml_ml_input_char,
     caml_input_value_to_outside_heap: caml_input_value_to_outside_heap,
     caml_input_value: caml_input_value,
     caml_ml_input_block: caml_ml_input_block,
     caml_ml_input: caml_ml_input,
     caml_refill: caml_refill,
     caml_ml_set_channel_refill: caml_ml_set_channel_refill,
     caml_ml_set_channel_output: caml_ml_set_channel_output,
     caml_ml_channel_size_64: caml_ml_channel_size_64,
     caml_ml_channel_size: caml_ml_channel_size,
     caml_ml_close_channel: caml_ml_close_channel,
     caml_ml_set_binary_mode: caml_ml_set_binary_mode,
     caml_channel_descriptor: caml_channel_descriptor,
     caml_ml_open_descriptor_in: caml_ml_open_descriptor_in,
     caml_ml_open_descriptor_out: caml_ml_open_descriptor_out,
     caml_ml_out_channels_list: caml_ml_out_channels_list,
     caml_ml_channels: caml_ml_channels,
     caml_ml_set_channel_name: caml_ml_set_channel_name,
     caml_sys_open: caml_sys_open,
     caml_sys_close: caml_sys_close,
     caml_sys_fds: caml_sys_fds,
     caml_int64_bswap: caml_int64_bswap,
     caml_int32_bswap: caml_int32_bswap,
     caml_bswap16: caml_bswap16,
     caml_mod: caml_mod,
     caml_div: caml_div,
     caml_mul: caml_mul,
     caml_int_of_string: caml_int_of_string,
     caml_parse_digit: caml_parse_digit,
     caml_parse_sign_and_base: caml_parse_sign_and_base,
     caml_format_int: caml_format_int,
     caml_int64_hash: caml_int64_hash,
     caml_int64_to_bytes: caml_int64_to_bytes,
     caml_int64_of_bytes: caml_int64_of_bytes,
     caml_int64_hi32: caml_int64_hi32,
     caml_int64_lo32: caml_int64_lo32,
     caml_int64_create_lo_hi: caml_int64_create_lo_hi,
     caml_int64_create_lo_mi_hi: caml_int64_create_lo_mi_hi,
     caml_int64_of_string: caml_int64_of_string,
     caml_int64_format: caml_int64_format,
     caml_int64_of_float: caml_int64_of_float,
     caml_int64_to_float: caml_int64_to_float,
     caml_int64_to_int32: caml_int64_to_int32,
     caml_int64_of_int32: caml_int64_of_int32,
     caml_int64_mod: caml_int64_mod,
     caml_int64_div: caml_int64_div,
     caml_int64_shift_right: caml_int64_shift_right,
     caml_int64_shift_right_unsigned: caml_int64_shift_right_unsigned,
     caml_int64_shift_left: caml_int64_shift_left,
     caml_int64_xor: caml_int64_xor,
     caml_int64_or: caml_int64_or,
     caml_int64_and: caml_int64_and,
     caml_int64_is_negative: caml_int64_is_negative,
     caml_int64_is_zero: caml_int64_is_zero,
     caml_int64_mul: caml_int64_mul,
     caml_int64_sub: caml_int64_sub,
     caml_int64_add: caml_int64_add,
     caml_int64_neg: caml_int64_neg,
     caml_int64_compare: caml_int64_compare,
     caml_int64_ult: caml_int64_ult,
     MlInt64: MlInt64,
     caml_int64_offset: caml_int64_offset,
     caml_float_of_string: caml_float_of_string,
     caml_format_float: caml_format_float,
     caml_fma_float: caml_fma_float,
     caml_erfc_float: caml_erfc_float,
     caml_erf_float: caml_erf_float,
     caml_cbrt_float: caml_cbrt_float,
     caml_round_float: caml_round_float,
     caml_atanh_float: caml_atanh_float,
     caml_tanh_float: caml_tanh_float,
     caml_asinh_float: caml_asinh_float,
     caml_sinh_float: caml_sinh_float,
     caml_acosh_float: caml_acosh_float,
     caml_cosh_float: caml_cosh_float,
     caml_log10_float: caml_log10_float,
     caml_hypot_float: caml_hypot_float,
     caml_log2_float: caml_log2_float,
     caml_log1p_float: caml_log1p_float,
     caml_exp2_float: caml_exp2_float,
     caml_expm1_float: caml_expm1_float,
     caml_signbit_float: caml_signbit_float,
     caml_copysign_float: caml_copysign_float,
     caml_float_compare: caml_float_compare,
     caml_frexp_float: caml_frexp_float,
     caml_ldexp_float: caml_ldexp_float,
     caml_modf_float: caml_modf_float,
     caml_classify_float: caml_classify_float,
     caml_int32_float_of_bits: caml_int32_float_of_bits,
     caml_trunc_float: caml_trunc_float,
     caml_nextafter_float: caml_nextafter_float,
     caml_int64_float_of_bits: caml_int64_float_of_bits,
     caml_hexstring_of_float: caml_hexstring_of_float,
     caml_int32_bits_of_float: caml_int32_bits_of_float,
     caml_int64_bits_of_float: caml_int64_bits_of_float,
     jsoo_floor_log2: jsoo_floor_log2,
     caml_string_hash: caml_string_hash,
     caml_hash: caml_hash,
     caml_hash_mix_string: caml_hash_mix_string,
     caml_hash_mix_bytes: caml_hash_mix_bytes,
     caml_hash_mix_bytes_arr: caml_hash_mix_bytes_arr,
     caml_hash_mix_jsbytes: caml_hash_mix_jsbytes,
     caml_hash_mix_int64: caml_hash_mix_int64,
     caml_hash_mix_float: caml_hash_mix_float,
     caml_hash_mix_final: caml_hash_mix_final,
     caml_hash_mix_int: caml_hash_mix_int,
     caml_gr_close_subwindow: caml_gr_close_subwindow,
     caml_gr_open_subwindow: caml_gr_open_subwindow,
     caml_gr_window_id: caml_gr_window_id,
     caml_gr_display_mode: caml_gr_display_mode,
     caml_gr_remember_mode: caml_gr_remember_mode,
     caml_gr_synchronize: caml_gr_synchronize,
     caml_gr_wait_event: caml_gr_wait_event,
     caml_gr_sigio_signal: caml_gr_sigio_signal,
     caml_gr_sigio_handler: caml_gr_sigio_handler,
     caml_gr_blit_image: caml_gr_blit_image,
     caml_gr_create_image: caml_gr_create_image,
     caml_gr_draw_image: caml_gr_draw_image,
     caml_gr_dump_image: caml_gr_dump_image,
     caml_gr_make_image: caml_gr_make_image,
     caml_gr_text_size: caml_gr_text_size,
     caml_gr_set_text_size: caml_gr_set_text_size,
     caml_gr_set_font: caml_gr_set_font,
     caml_gr_draw_string: caml_gr_draw_string,
     caml_gr_draw_char: caml_gr_draw_char,
     caml_gr_draw_str: caml_gr_draw_str,
     caml_gr_fill_arc: caml_gr_fill_arc,
     caml_gr_fill_poly: caml_gr_fill_poly,
     caml_gr_fill_rect: caml_gr_fill_rect,
     caml_gr_set_line_width: caml_gr_set_line_width,
     caml_gr_draw_arc: caml_gr_draw_arc,
     caml_gr_arc_aux: caml_gr_arc_aux,
     caml_gr_draw_rect: caml_gr_draw_rect,
     caml_gr_lineto: caml_gr_lineto,
     caml_gr_current_y: caml_gr_current_y,
     caml_gr_current_x: caml_gr_current_x,
     caml_gr_moveto: caml_gr_moveto,
     caml_gr_point_color: caml_gr_point_color,
     caml_gr_plot: caml_gr_plot,
     caml_gr_set_color: caml_gr_set_color,
     caml_gr_size_y: caml_gr_size_y,
     caml_gr_size_x: caml_gr_size_x,
     caml_gr_clear_graph: caml_gr_clear_graph,
     caml_gr_resize_window: caml_gr_resize_window,
     caml_gr_set_window_title: caml_gr_set_window_title,
     caml_gr_close_graph: caml_gr_close_graph,
     caml_gr_doc_of_state: caml_gr_doc_of_state,
     caml_gr_state_create: caml_gr_state_create,
     caml_gr_state_init: caml_gr_state_init,
     caml_gr_open_graph: caml_gr_open_graph,
     caml_gr_state_set: caml_gr_state_set,
     caml_gr_state_get: caml_gr_state_get,
     caml_gr_state: caml_gr_state,
     caml_get_major_credit: caml_get_major_credit,
     caml_get_major_bucket: caml_get_major_bucket,
     caml_get_minor_free: caml_get_minor_free,
     caml_gc_minor_words: caml_gc_minor_words,
     caml_gc_major_slice: caml_gc_major_slice,
     caml_gc_huge_fallback_count: caml_gc_huge_fallback_count,
     caml_eventlog_pause: caml_eventlog_pause,
     caml_eventlog_resume: caml_eventlog_resume,
     caml_memprof_stop: caml_memprof_stop,
     caml_memprof_start: caml_memprof_start,
     caml_final_release: caml_final_release,
     caml_final_register_called_without_value:
     caml_final_register_called_without_value,
     caml_final_register: caml_final_register,
     caml_memprof_set: caml_memprof_set,
     caml_gc_get: caml_gc_get,
     caml_gc_set: caml_gc_set,
     caml_gc_stat: caml_gc_stat,
     caml_gc_quick_stat: caml_gc_quick_stat,
     caml_gc_counters: caml_gc_counters,
     caml_gc_compaction: caml_gc_compaction,
     caml_gc_full_major: caml_gc_full_major,
     caml_gc_major: caml_gc_major,
     caml_gc_minor: caml_gc_minor,
     caml_sys_open_for_node: caml_sys_open_for_node,
     MlNodeFd: MlNodeFd,
     MlNodeDevice: MlNodeDevice,
     fs_node_supported: fs_node_supported,
     MlFakeFd: MlFakeFd,
     MlFakeFd_out: MlFakeFd_out,
     MlFakeFile: MlFakeFile,
     MlFakeDevice: MlFakeDevice,
     caml_read_file_content: caml_read_file_content,
     jsoo_create_file: jsoo_create_file,
     caml_create_file: caml_create_file,
     caml_fs_init: caml_fs_init,
     jsoo_create_file_extern: jsoo_create_file_extern,
     caml_ba_map_file_bytecode: caml_ba_map_file_bytecode,
     caml_ba_map_file: caml_ba_map_file,
     caml_sys_rmdir: caml_sys_rmdir,
     caml_sys_mkdir: caml_sys_mkdir,
     caml_sys_rename: caml_sys_rename,
     caml_sys_is_directory: caml_sys_is_directory,
     caml_sys_remove: caml_sys_remove,
     caml_sys_read_directory: caml_sys_read_directory,
     caml_sys_file_exists: caml_sys_file_exists,
     caml_raise_not_a_dir: caml_raise_not_a_dir,
     caml_raise_no_such_file: caml_raise_no_such_file,
     caml_sys_chdir: caml_sys_chdir,
     caml_sys_getcwd: caml_sys_getcwd,
     caml_unmount: caml_unmount,
     caml_mount_autoload: caml_mount_autoload,
     resolve_fs_device: resolve_fs_device,
     caml_list_mount_point: caml_list_mount_point,
     jsoo_mount_point: jsoo_mount_point,
     caml_make_path: caml_make_path,
     path_is_absolute: path_is_absolute,
     MlFile: MlFile,
     caml_root: caml_root,
     caml_get_root: caml_get_root,
     caml_current_dir: caml_current_dir,
     caml_trailing_slash: caml_trailing_slash,
     caml_finish_formatting: caml_finish_formatting,
     caml_parse_format: caml_parse_format,
     caml_array_bound_error: caml_array_bound_error,
     caml_raise_not_found: caml_raise_not_found,
     caml_raise_zero_divide: caml_raise_zero_divide,
     caml_raise_end_of_file: caml_raise_end_of_file,
     caml_invalid_argument: caml_invalid_argument,
     caml_failwith: caml_failwith,
     caml_raise_with_string: caml_raise_with_string,
     caml_raise_with_args: caml_raise_with_args,
     caml_raise_with_arg: caml_raise_with_arg,
     caml_raise_constant: caml_raise_constant,
     caml_lessthan: caml_lessthan,
     caml_lessequal: caml_lessequal,
     caml_greaterthan: caml_greaterthan,
     caml_greaterequal: caml_greaterequal,
     caml_notequal: caml_notequal,
     caml_equal: caml_equal,
     caml_int_compare: caml_int_compare,
     caml_compare: caml_compare,
     caml_compare_val: caml_compare_val,
     caml_compare_val_number_custom: caml_compare_val_number_custom,
     caml_compare_val_get_custom: caml_compare_val_get_custom,
     caml_compare_val_tag: caml_compare_val_tag,
     caml_bigstring_blit_ba_to_bytes: caml_bigstring_blit_ba_to_bytes,
     caml_bigstring_blit_bytes_to_ba: caml_bigstring_blit_bytes_to_ba,
     caml_bigstring_blit_string_to_ba: caml_bigstring_blit_string_to_ba,
     caml_bigstring_blit_ba_to_ba: caml_bigstring_blit_ba_to_ba,
     caml_bigstring_memcmp: caml_bigstring_memcmp,
     bigstring_of_typed_array: bigstring_of_typed_array,
     bigstring_of_array_buffer: bigstring_of_array_buffer,
     bigstring_to_typed_array: bigstring_to_typed_array,
     bigstring_to_array_buffer: bigstring_to_array_buffer,
     caml_hash_mix_bigstring: caml_hash_mix_bigstring,
     caml_ba_from_typed_array: caml_ba_from_typed_array,
     caml_ba_kind_of_typed_array: caml_ba_kind_of_typed_array,
     caml_ba_to_typed_array: caml_ba_to_typed_array,
     caml_ba_hash: caml_ba_hash,
     caml_ba_create_from: caml_ba_create_from,
     caml_ba_deserialize: caml_ba_deserialize,
     caml_ba_serialize: caml_ba_serialize,
     caml_ba_reshape: caml_ba_reshape,
     caml_ba_slice: caml_ba_slice,
     caml_ba_sub: caml_ba_sub,
     caml_ba_blit: caml_ba_blit,
     caml_ba_fill: caml_ba_fill,
     caml_ba_set_3: caml_ba_set_3,
     caml_ba_set_2: caml_ba_set_2,
     caml_ba_set_1: caml_ba_set_1,
     caml_ba_uint8_set64: caml_ba_uint8_set64,
     caml_ba_uint8_set32: caml_ba_uint8_set32,
     caml_ba_uint8_set16: caml_ba_uint8_set16,
     caml_ba_set_generic: caml_ba_set_generic,
     caml_ba_get_3: caml_ba_get_3,
     caml_ba_get_2: caml_ba_get_2,
     caml_ba_get_1: caml_ba_get_1,
     caml_ba_uint8_get64: caml_ba_uint8_get64,
     caml_ba_uint8_get32: caml_ba_uint8_get32,
     caml_ba_uint8_get16: caml_ba_uint8_get16,
     caml_ba_get_generic: caml_ba_get_generic,
     caml_ba_dim_3: caml_ba_dim_3,
     caml_ba_dim_2: caml_ba_dim_2,
     caml_ba_dim_1: caml_ba_dim_1,
     caml_ba_dim: caml_ba_dim,
     caml_ba_num_dims: caml_ba_num_dims,
     caml_ba_layout: caml_ba_layout,
     caml_ba_kind: caml_ba_kind,
     caml_ba_change_layout: caml_ba_change_layout,
     caml_ba_create: caml_ba_create,
     caml_ba_create_unsafe: caml_ba_create_unsafe,
     caml_ba_compare: caml_ba_compare,
     Ml_Bigarray_c_1_1: Ml_Bigarray_c_1_1,
     Ml_Bigarray: Ml_Bigarray,
     caml_ba_custom_name: caml_ba_custom_name,
     caml_ba_create_buffer: caml_ba_create_buffer,
     caml_ba_get_size_per_element: caml_ba_get_size_per_element,
     caml_ba_get_size: caml_ba_get_size,
     caml_ba_init: caml_ba_init,
     caml_convert_raw_backtrace_slot: caml_convert_raw_backtrace_slot,
     caml_get_current_callstack: caml_get_current_callstack,
     caml_restore_raw_backtrace: caml_restore_raw_backtrace,
     caml_raw_backtrace_slot: caml_raw_backtrace_slot,
     caml_raw_backtrace_next_slot: caml_raw_backtrace_next_slot,
     caml_raw_backtrace_length: caml_raw_backtrace_length,
     caml_convert_raw_backtrace: caml_convert_raw_backtrace,
     caml_record_backtrace: caml_record_backtrace,
     caml_get_exception_raw_backtrace: caml_get_exception_raw_backtrace,
     caml_get_exception_backtrace: caml_get_exception_backtrace,
     caml_backtrace_status: caml_backtrace_status,
     caml_ml_debug_info_status: caml_ml_debug_info_status,
     caml_record_backtrace_flag: caml_record_backtrace_flag,
     caml_floatarray_create: caml_floatarray_create,
     caml_make_float_vect: caml_make_float_vect,
     caml_make_vect: caml_make_vect,
     caml_check_bound: caml_check_bound,
     caml_array_fill: caml_array_fill,
     caml_array_get: caml_array_get,
     caml_array_set: caml_array_set,
     caml_floatarray_blit: caml_floatarray_blit,
     caml_array_blit: caml_array_blit,
     caml_array_concat: caml_array_concat,
     caml_array_append: caml_array_append,
     caml_array_sub: caml_array_sub};
   var
    cst_Assert_failure = "Assert_failure",
    cst_Division_by_zero = "Division_by_zero",
    cst_End_of_file = "End_of_file",
    cst_Failure = "Failure",
    cst_Invalid_argument = "Invalid_argument",
    cst_Match_failure = "Match_failure",
    cst_Not_found = "Not_found",
    cst_Out_of_memory = "Out_of_memory",
    cst_Stack_overflow = "Stack_overflow",
    cst_Sys_blocked_io = "Sys_blocked_io",
    cst_Sys_error = "Sys_error",
    cst_Undefined_recursive_module = "Undefined_recursive_module";
   caml_fs_init();
   caml_register_global(0, [248, cst_Out_of_memory, -1], cst_Out_of_memory);
   caml_register_global(1, [248, cst_Sys_error, -2], cst_Sys_error);
   caml_register_global(2, [248, cst_Failure, -3], cst_Failure);
   caml_register_global
    (3, [248, cst_Invalid_argument, -4], cst_Invalid_argument);
   caml_register_global(4, [248, cst_End_of_file, -5], cst_End_of_file);
   caml_register_global
    (5, [248, cst_Division_by_zero, -6], cst_Division_by_zero);
   caml_register_global(6, [248, cst_Not_found, -7], cst_Not_found);
   caml_register_global(7, [248, cst_Match_failure, -8], cst_Match_failure);
   caml_register_global(8, [248, cst_Stack_overflow, -9], cst_Stack_overflow);
   caml_register_global(9, [248, cst_Sys_blocked_io, -10], cst_Sys_blocked_io);
   caml_register_global
    (10, [248, cst_Assert_failure, -11], cst_Assert_failure);
   caml_register_global
    (11,
     [248, cst_Undefined_recursive_module, -12],
     cst_Undefined_recursive_module);
   return;
  }
  (globalThis));


(function(a){"use strict";var
ai="Js_of_ocaml__Dom_events",bl="Js_of_ocaml__EventSource",ah="Sys_blocked_io",ag="Js_of_ocaml__Worker",bk="Js_of_ocaml__File",bj="Stdlib__Fun",ad=110,ae="Stdlib__MoreLabels",af="Std_exit",bi="Stdlib__Seq",bg="Stdlib__Weak",bh="Js_of_ocaml__Url",ac="Dune__exe",ab="Stdlib__Queue",aa="Stdlib__Parsing",bf="Stdlib__BytesLabels",$="Stdlib__Obj",be="Stdlib__ArrayLabels",_=112,bd="Stdlib__Buffer",Z="Js_of_ocaml__Json",bc="Js_of_ocaml__ResizeObserver",Y="Js_of_ocaml",W="Jsoo_runtime__",X="CamlinternalMod",a$="Stdlib__Printf",ba="Stdlib__Out_channel",bb=105,a8=102,a9="CamlinternalLazy",a_="Js_of_ocaml__Dom_svg",V="Js_of_ocaml__Js",a7="Stdlib__String",a6="Stdlib__Result",T="Stdlib__Bigarray",U=104,a5="Stdlib__Either",S="CamlinternalAtomic",R="Invalid_argument",a4="Js_of_ocaml__Import",P=113,Q=106,a2="Stdlib__Sys",a3="Stdlib__Random",N="Stdlib__Format",O="Match_failure",M="Stdlib__Scanf",a0="Stdlib__Oo",a1="Failure",L="Js_of_ocaml__Dom_html",aZ="Stdlib__Pervasives",K="Js_of_ocaml__",aY="CamlinternalOO",aX="Stdlib__Array",G="Stdlib__Bool",H="Jsoo_runtime",I=101,J="Division_by_zero",aW="Stdlib__Genlex",aU="Js_of_ocaml__Dom",aV=111,F="Js_of_ocaml__Firebug",aT="Not_found",E="Stdlib__Arg",aR="Stdlib__Lazy",aS="Js_of_ocaml__PerformanceObserver",D=107,aP="Stdlib__Map",aQ="Stdlib__Char",B="Stdlib__StringLabels",C="CamlinternalFormatBasics",aO="Stdlib__Digest",A="Js_of_ocaml__XmlHttpRequest",aM="Stdlib__Ephemeron",aN="Stdlib__Callback",z="Jsoo_runtime__Runtime_version",aL="Js_of_ocaml__Form",y="Stdlib__Uchar",x="Stdlib__List",aK="Stdlib__In_channel",w="Stdlib__Atomic",aJ="Stdlib",v=100,aI="Stdlib__Printexc",t="Stdlib__Int64",u=109,s="Sys_error",aG="Js_of_ocaml__CSS",aH="Js_of_ocaml__Geolocation",q="Stdlib__Lexing",r="CamlinternalFormat",p="Stdlib__Gc",aC="Stdlib__Bytes",aD="Js_of_ocaml__Typed_array",aE="Js_of_ocaml__Lib_version",aF=103,o="Stdlib__Int",l="Stdlib__Hashtbl",m="Stdlib__ListLabels",n="Js_of_ocaml__Jstable",ay="Stdlib__Unit",az="Stdlib__Option",aA="Js_of_ocaml__IntersectionObserver",aB="Dune__exe__Xml2js",j="Stdlib__Int32",k="End_of_file",ax="Out_of_memory",aw="Js_of_ocaml__Intl",i="Stdlib__Stack",av="Js_of_ocaml__Sys_js",h="Stack_overflow",aq="Stdlib__Stream",ar="Stdlib__Float",as="Stdlib__Complex",at="Dune__exe__Parser",au="Stdlib__StdLabels",g="Stdlib__Nativeint",ao="Js_of_ocaml__WebGL",ap="Stdlib__Filename",e="Js_of_ocaml__WebSockets",f=108,al="Stdlib__Marshal",am="Assert_failure",an="Js_of_ocaml__MutationObserver",d="Undefined_recursive_module",ak="Js_of_ocaml__Regexp",c="Xmlm",aj="Stdlib__Set",bm=a.jsoo_runtime,b=bm.caml_get_global_data();b.prim_count=845;var
bn=[2,X],bo=[2,aB],bp=[2,Y],bq=[2,ai],br=[0,0,[2,bl],U,0,1],bs=[2,a_],bt=[2,F],bu=[2,aH],bv=[0,0,[2,aw],f,0,1],bw=[2,aA],bx=[2,n],by=[0,0,[2,Z],v,0,1],bz=[2,an],bA=[2,bh],bB=[2,af],bC=[2,bf],bD=[2,ap],bE=[2,aW],bF=[2,aK],bG=[2,m],bH=[2,ae],bI=[2,au];b.toc=[0,[0,"SYMB",[0,114,[0,[0,[0,[0,[0,[0,0,[2,am],0,0,1],[2,S],13,[0,0,[2,r],46,0,1],2],[2,C],12,[0,[0,0,[2,a9],19,[0,[0,0,bn,62,0,1],[2,aY],60,0,2],3],[2,J],1,[0,[0,0,[2,ac],ad,0,1],[2,at],aV,[0,[0,0,bo,_,0,1],[2,k],2,0,2],3],4],5],[2,a1],3,[0,[0,[0,[0,0,[2,R],4,[0,0,bp,u,0,1],2],[2,K],80,[0,0,[2,aG],I,0,1],3],[2,aU],83,[0,[0,[0,0,bq,a8,0,1],[2,L],86,[0,0,bs,aF,br,2],3],[2,bk],85,[0,[0,0,bt,bb,0,1],[2,aL],87,[0,0,bu,Q,0,1],2],4],5],[2,a4],81,[0,[0,[0,[0,0,bw,D,bv,2],[2,V],82,[0,by,bx,99,0,2],3],[2,aE],94,[0,[0,0,bz,98,0,1],[2,aS],97,0,2],4],[2,ak],92,[0,[0,0,[2,bc],96,0,1],[2,av],95,0,2],5],6],7],[2,aD],84,[0,[0,[0,[0,[0,[0,0,bA,93,0,1],[2,ao],91,0,2],[2,e],90,0,3],[2,ag],89,[0,0,[2,A],88,0,1],4],[2,H],79,[0,[0,0,[2,W],77,[0,0,[2,z],78,0,1],2],[2,O],5,[0,[0,0,[2,aT],6,0,1],[2,ax],7,[0,0,[2,h],8,[0,0,bB,P,0,1],2],3],4],5],[2,aJ],14,[0,[0,[0,0,[2,E],48,0,1],[2,aX],33,[0,[0,0,[2,be],67,0,1],[2,w],49,[0,0,[2,T],73,0,1],2],3],[2,G],24,[0,[0,[0,0,[2,bd],45,0,1],[2,aC],29,[0,[0,0,bC,69,0,1],[2,aN],59,0,2],3],[2,aQ],25,[0,[0,0,[2,as],66,0,1],[2,aO],53,0,2],4],5],6],8],[2,a5],16,[0,[0,[0,[0,[0,[0,0,[2,aM],64,[0,0,bD,65,0,1],2],[2,ar],34,[0,0,[2,N],57,0,1],3],[2,bj],51,[0,0,[2,p],52,[0,[0,0,bE,63,0,1],[2,l],55,[0,0,bF,74,0,1],2],3],4],[2,o],28,[0,0,[2,j],35,[0,0,[2,t],36,0,1],2],5],[2,aR],20,[0,[0,[0,0,[2,q],38,0,1],[2,x],27,[0,[0,[0,0,bG,68,0,1],[2,aP],41,0,2],[2,al],32,[0,[0,0,bH,71,0,1],[2,g],37,0,2],3],4],[2,$],18,[0,[0,0,[2,a0],61,0,1],[2,az],22,[0,[0,0,[2,ba],75,0,1],[2,aa],39,0,2],3],5],6],[2,aZ],15,[0,[0,[0,[0,[0,0,[2,aI],50,0,1],[2,a$],47,0,2],[2,ab],43,[0,[0,0,[2,a3],54,0,1],[2,a6],23,[0,0,[2,M],58,0,1],2],3],[2,bi],21,[0,[0,0,[2,aj],40,0,1],[2,i],42,[0,[0,[0,0,bI,72,0,1],[2,aq],44,0,2],[2,a7],30,[0,0,[2,B],70,0,1],3],4],5],[2,a2],17,[0,[0,0,[2,y],26,[0,0,[2,ay],31,[0,0,[2,bg],56,0,1],2],3],[2,ah],9,[0,0,[2,s],10,[0,0,[2,d],11,[0,0,[2,c],76,0,1],2],3],4],6],7],9]]],[0,[0,"SYJS",[0,[0,c,76],[0,d,11],[0,s,10],[0,ah,9],[0,bg,56],[0,ay,31],[0,y,26],[0,a2,17],[0,B,70],[0,a7,30],[0,aq,44],[0,au,72],[0,i,42],[0,aj,40],[0,bi,21],[0,M,58],[0,a6,23],[0,a3,54],[0,ab,43],[0,a$,47],[0,aI,50],[0,aZ,15],[0,aa,39],[0,ba,75],[0,az,22],[0,a0,61],[0,$,18],[0,g,37],[0,ae,71],[0,al,32],[0,aP,41],[0,m,68],[0,x,27],[0,q,38],[0,aR,20],[0,t,36],[0,j,35],[0,o,28],[0,aK,74],[0,l,55],[0,aW,63],[0,p,52],[0,bj,51],[0,N,57],[0,ar,34],[0,ap,65],[0,aM,64],[0,a5,16],[0,aO,53],[0,as,66],[0,aQ,25],[0,aN,59],[0,bf,69],[0,aC,29],[0,bd,45],[0,G,24],[0,T,73],[0,w,49],[0,be,67],[0,aX,33],[0,E,48],[0,aJ,14],[0,af,P],[0,h,8],[0,ax,7],[0,aT,6],[0,O,5],[0,z,78],[0,W,77],[0,H,79],[0,A,88],[0,ag,89],[0,e,90],[0,ao,91],[0,bh,93],[0,aD,84],[0,av,95],[0,bc,96],[0,ak,92],[0,aS,97],[0,an,98],[0,aE,94],[0,n,99],[0,Z,v],[0,V,82],[0,aw,f],[0,aA,D],[0,a4,81],[0,aH,Q],[0,aL,87],[0,F,bb],[0,bk,85],[0,bl,U],[0,a_,aF],[0,L,86],[0,ai,a8],[0,aU,83],[0,aG,I],[0,K,80],[0,Y,u],[0,R,4],[0,a1,3],[0,k,2],[0,aB,_],[0,at,aV],[0,ac,ad],[0,J,1],[0,aY,60],[0,X,62],[0,a9,19],[0,C,12],[0,r,46],[0,S,13],[0,am,0]]],[0,[0,"CRCS",0],[0,[0,"PRIM","%caml_format_int_special\0%direct_int_div\0%direct_int_mod\0%direct_int_mul\0%identity\0%int_add\0%int_and\0%int_asr\0%int_div\0%int_lsl\0%int_lsr\0%int_mod\0%int_mul\0%int_neg\0%int_or\0%int_sub\0%int_xor\0BigStringReader\0MlBytes\0MlFakeDevice\0MlFakeFd\0MlFakeFd_out\0MlFakeFile\0MlFile\0MlInt64\0MlMutex\0MlNat\0MlNodeDevice\0MlNodeFd\0MlObjectTable\0MlStringReader\0Ml_Bigarray\0Ml_Bigarray_c_1_1\0UInt8ArrayReader\0add_nat\0bigstring_of_array_buffer\0bigstring_of_typed_array\0bigstring_to_array_buffer\0bigstring_to_typed_array\0blit_nat\0caml_MD5Final\0caml_MD5Init\0caml_MD5Transform\0caml_MD5Update\0caml_abs_float\0caml_acos_float\0caml_acosh_float\0caml_add_float\0caml_alloc_dummy\0caml_alloc_dummy_float\0caml_alloc_dummy_infix\0caml_alloc_stack\0caml_argv\0caml_array_append\0caml_array_blit\0caml_array_bound_error\0caml_array_concat\0caml_array_fill\0caml_array_get\0caml_array_get_addr\0caml_array_get_float\0caml_array_of_bytes\0caml_array_of_string\0caml_array_set\0caml_array_set_addr\0caml_array_set_float\0caml_array_sub\0caml_array_unsafe_get\0caml_array_unsafe_get_float\0caml_array_unsafe_set\0caml_array_unsafe_set_float\0caml_asin_float\0caml_asinh_float\0caml_atan2_float\0caml_atan_float\0caml_atanh_float\0caml_atomic_cas\0caml_atomic_exchange\0caml_atomic_fetch_add\0caml_atomic_load\0caml_ba_blit\0caml_ba_change_layout\0caml_ba_compare\0caml_ba_create\0caml_ba_create_buffer\0caml_ba_create_from\0caml_ba_create_unsafe\0caml_ba_custom_name\0caml_ba_deserialize\0caml_ba_dim\0caml_ba_dim_1\0caml_ba_dim_2\0caml_ba_dim_3\0caml_ba_fill\0caml_ba_from_typed_array\0caml_ba_get_1\0caml_ba_get_2\0caml_ba_get_3\0caml_ba_get_generic\0caml_ba_get_size\0caml_ba_get_size_per_element\0caml_ba_hash\0caml_ba_init\0caml_ba_kind\0caml_ba_kind_of_typed_array\0caml_ba_layout\0caml_ba_map_file\0caml_ba_map_file_bytecode\0caml_ba_num_dims\0caml_ba_reshape\0caml_ba_serialize\0caml_ba_set_1\0caml_ba_set_2\0caml_ba_set_3\0caml_ba_set_generic\0caml_ba_slice\0caml_ba_sub\0caml_ba_to_typed_array\0caml_ba_uint8_get16\0caml_ba_uint8_get32\0caml_ba_uint8_get64\0caml_ba_uint8_set16\0caml_ba_uint8_set32\0caml_ba_uint8_set64\0caml_backtrace_status\0caml_bigstring_blit_ba_to_ba\0caml_bigstring_blit_ba_to_bytes\0caml_bigstring_blit_bytes_to_ba\0caml_bigstring_blit_string_to_ba\0caml_bigstring_memcmp\0caml_blit_bytes\0caml_blit_string\0caml_bswap16\0caml_build_symbols\0caml_bytes_bound_error\0caml_bytes_compare\0caml_bytes_equal\0caml_bytes_get\0caml_bytes_get16\0caml_bytes_get32\0caml_bytes_get64\0caml_bytes_greaterequal\0caml_bytes_greaterthan\0caml_bytes_lessequal\0caml_bytes_lessthan\0caml_bytes_notequal\0caml_bytes_of_array\0caml_bytes_of_jsbytes\0caml_bytes_of_string\0caml_bytes_of_utf16_jsstring\0caml_bytes_set\0caml_bytes_set16\0caml_bytes_set32\0caml_bytes_set64\0caml_bytes_unsafe_get\0caml_bytes_unsafe_set\0caml_call_gen\0caml_callback\0caml_cbrt_float\0caml_ceil_float\0caml_channel_descriptor\0caml_check_bound\0caml_classify_float\0caml_compare\0caml_compare_val\0caml_compare_val_get_custom\0caml_compare_val_number_custom\0caml_compare_val_tag\0caml_continuation_use_and_update_handler_noexc\0caml_continuation_use_noexc\0caml_convert_bytes_to_array\0caml_convert_raw_backtrace\0caml_convert_raw_backtrace_slot\0caml_convert_string_to_bytes\0caml_copysign_float\0caml_cos_float\0caml_cosh_float\0caml_create_bytes\0caml_create_file\0caml_create_string\0caml_current_dir\0caml_custom_event_index\0caml_custom_ops\0caml_div\0caml_div_float\0caml_domain_dls\0caml_domain_dls_get\0caml_domain_dls_set\0caml_domain_id\0caml_domain_spawn\0caml_ensure_stack_capacity\0caml_ephe_blit_data\0caml_ephe_blit_key\0caml_ephe_check_data\0caml_ephe_check_key\0caml_ephe_create\0caml_ephe_data_offset\0caml_ephe_get_data\0caml_ephe_get_data_copy\0caml_ephe_get_key\0caml_ephe_get_key_copy\0caml_ephe_key_offset\0caml_ephe_set_data\0caml_ephe_set_key\0caml_ephe_unset_data\0caml_ephe_unset_key\0caml_eq_float\0caml_equal\0caml_erf_float\0caml_erfc_float\0caml_eventlog_pause\0caml_eventlog_resume\0caml_executable_name\0caml_exn_with_js_backtrace\0caml_exp2_float\0caml_exp_float\0caml_expm1_float\0caml_failwith\0caml_fatal_uncaught_exception\0caml_fill_bytes\0caml_fill_string\0caml_final_register\0caml_final_register_called_without_value\0caml_final_release\0caml_finish_formatting\0caml_float_compare\0caml_float_of_bytes\0caml_float_of_int\0caml_float_of_string\0caml_floatarray_blit\0caml_floatarray_create\0caml_floatarray_get\0caml_floatarray_set\0caml_floatarray_unsafe_get\0caml_floatarray_unsafe_set\0caml_floor_float\0caml_fma_float\0caml_fmod_float\0caml_format_exception\0caml_format_float\0caml_format_int\0caml_fresh_oo_id\0caml_frexp_float\0caml_fs_init\0caml_gc_compaction\0caml_gc_counters\0caml_gc_full_major\0caml_gc_get\0caml_gc_huge_fallback_count\0caml_gc_major\0caml_gc_major_slice\0caml_gc_minor\0caml_gc_minor_words\0caml_gc_quick_stat\0caml_gc_set\0caml_gc_stat\0caml_ge_float\0caml_get_continuation_callstack\0caml_get_current_callstack\0caml_get_exception_backtrace\0caml_get_exception_raw_backtrace\0caml_get_global_data\0caml_get_major_bucket\0caml_get_major_credit\0caml_get_minor_free\0caml_get_public_method\0caml_get_root\0caml_global_data\0caml_gr_arc_aux\0caml_gr_blit_image\0caml_gr_clear_graph\0caml_gr_close_graph\0caml_gr_close_subwindow\0caml_gr_create_image\0caml_gr_current_x\0caml_gr_current_y\0caml_gr_display_mode\0caml_gr_doc_of_state\0caml_gr_draw_arc\0caml_gr_draw_char\0caml_gr_draw_image\0caml_gr_draw_rect\0caml_gr_draw_str\0caml_gr_draw_string\0caml_gr_dump_image\0caml_gr_fill_arc\0caml_gr_fill_poly\0caml_gr_fill_rect\0caml_gr_lineto\0caml_gr_make_image\0caml_gr_moveto\0caml_gr_open_graph\0caml_gr_open_subwindow\0caml_gr_plot\0caml_gr_point_color\0caml_gr_remember_mode\0caml_gr_resize_window\0caml_gr_set_color\0caml_gr_set_font\0caml_gr_set_line_width\0caml_gr_set_text_size\0caml_gr_set_window_title\0caml_gr_sigio_handler\0caml_gr_sigio_signal\0caml_gr_size_x\0caml_gr_size_y\0caml_gr_state\0caml_gr_state_create\0caml_gr_state_get\0caml_gr_state_init\0caml_gr_state_set\0caml_gr_synchronize\0caml_gr_text_size\0caml_gr_wait_event\0caml_gr_window_id\0caml_greaterequal\0caml_greaterthan\0caml_gt_float\0caml_hash\0caml_hash_mix_bigstring\0caml_hash_mix_bytes\0caml_hash_mix_bytes_arr\0caml_hash_mix_final\0caml_hash_mix_float\0caml_hash_mix_int\0caml_hash_mix_int64\0caml_hash_mix_jsbytes\0caml_hash_mix_string\0caml_hash_nat\0caml_hexstring_of_float\0caml_hypot_float\0caml_input_value\0caml_input_value_from_bytes\0caml_input_value_from_reader\0caml_input_value_from_string\0caml_input_value_to_outside_heap\0caml_install_signal_handler\0caml_int32_add\0caml_int32_and\0caml_int32_bits_of_float\0caml_int32_bswap\0caml_int32_compare\0caml_int32_div\0caml_int32_float_of_bits\0caml_int32_format\0caml_int32_mod\0caml_int32_mul\0caml_int32_neg\0caml_int32_of_float\0caml_int32_of_int\0caml_int32_of_string\0caml_int32_or\0caml_int32_shift_left\0caml_int32_shift_right\0caml_int32_shift_right_unsigned\0caml_int32_sub\0caml_int32_to_float\0caml_int32_to_int\0caml_int32_unmarshal\0caml_int32_xor\0caml_int64_add\0caml_int64_and\0caml_int64_bits_of_float\0caml_int64_bswap\0caml_int64_compare\0caml_int64_create_lo_hi\0caml_int64_create_lo_mi_hi\0caml_int64_div\0caml_int64_float_of_bits\0caml_int64_format\0caml_int64_hash\0caml_int64_hi32\0caml_int64_is_negative\0caml_int64_is_zero\0caml_int64_lo32\0caml_int64_marshal\0caml_int64_mod\0caml_int64_mul\0caml_int64_neg\0caml_int64_of_bytes\0caml_int64_of_float\0caml_int64_of_int\0caml_int64_of_int32\0caml_int64_of_nativeint\0caml_int64_of_string\0caml_int64_offset\0caml_int64_or\0caml_int64_shift_left\0caml_int64_shift_right\0caml_int64_shift_right_unsigned\0caml_int64_sub\0caml_int64_to_bytes\0caml_int64_to_float\0caml_int64_to_int\0caml_int64_to_int32\0caml_int64_to_nativeint\0caml_int64_ult\0caml_int64_unmarshal\0caml_int64_xor\0caml_int_compare\0caml_int_of_float\0caml_int_of_string\0caml_invalid_argument\0caml_is_continuation_tag\0caml_is_js\0caml_is_ml_bytes\0caml_is_ml_string\0caml_is_printable\0caml_is_special_exception\0caml_js_call\0caml_js_delete\0caml_js_equals\0caml_js_error_of_exception\0caml_js_error_option_of_exception\0caml_js_eval_string\0caml_js_expr\0caml_js_from_array\0caml_js_from_bool\0caml_js_from_float\0caml_js_from_string\0caml_js_fun_call\0caml_js_function_arity\0caml_js_get\0caml_js_get_console\0caml_js_html_entities\0caml_js_html_escape\0caml_js_instanceof\0caml_js_meth_call\0caml_js_new\0caml_js_object\0caml_js_on_ie\0caml_js_pure_expr\0caml_js_set\0caml_js_to_array\0caml_js_to_bool\0caml_js_to_byte_string\0caml_js_to_float\0caml_js_to_string\0caml_js_typeof\0caml_js_var\0caml_js_wrap_callback\0caml_js_wrap_callback_arguments\0caml_js_wrap_callback_strict\0caml_js_wrap_callback_unsafe\0caml_js_wrap_meth_callback\0caml_js_wrap_meth_callback_arguments\0caml_js_wrap_meth_callback_strict\0caml_js_wrap_meth_callback_unsafe\0caml_jsbytes_of_string\0caml_jsoo_flags_effects\0caml_jsoo_flags_use_js_string\0caml_jsstring_of_string\0caml_lazy_make_forward\0caml_lazy_read_result\0caml_lazy_reset_to_lazy\0caml_lazy_update_to_forcing\0caml_lazy_update_to_forward\0caml_ldexp_float\0caml_le_float\0caml_lessequal\0caml_lessthan\0caml_lex_array\0caml_lex_engine\0caml_list_mount_point\0caml_list_of_js_array\0caml_list_to_js_array\0caml_log10_float\0caml_log1p_float\0caml_log2_float\0caml_log_float\0caml_lt_float\0caml_lxm_next\0caml_make_array\0caml_make_float_vect\0caml_make_path\0caml_make_vect\0caml_marshal_constants\0caml_marshal_data_size\0caml_marshal_header_size\0caml_maybe_attach_backtrace\0caml_maybe_print_stats\0caml_md5_bytes\0caml_md5_chan\0caml_md5_string\0caml_memprof_set\0caml_memprof_start\0caml_memprof_stop\0caml_ml_bytes_content\0caml_ml_bytes_length\0caml_ml_channel_size\0caml_ml_channel_size_64\0caml_ml_channels\0caml_ml_close_channel\0caml_ml_condition_broadcast\0caml_ml_condition_new\0caml_ml_condition_signal\0caml_ml_condition_wait\0caml_ml_debug_info_status\0caml_ml_domain_cpu_relax\0caml_ml_domain_id\0caml_ml_domain_set_name\0caml_ml_domain_unique_token\0caml_ml_enable_runtime_warnings\0caml_ml_flush\0caml_ml_input\0caml_ml_input_block\0caml_ml_input_char\0caml_ml_input_int\0caml_ml_input_scan_line\0caml_ml_is_buffered\0caml_ml_mutex_lock\0caml_ml_mutex_new\0caml_ml_mutex_try_lock\0caml_ml_mutex_unlock\0caml_ml_open_descriptor_in\0caml_ml_open_descriptor_out\0caml_ml_out_channels_list\0caml_ml_output\0caml_ml_output_bytes\0caml_ml_output_char\0caml_ml_output_int\0caml_ml_pos_in\0caml_ml_pos_in_64\0caml_ml_pos_out\0caml_ml_pos_out_64\0caml_ml_runtime_warnings_enabled\0caml_ml_seek_in\0caml_ml_seek_in_64\0caml_ml_seek_out\0caml_ml_seek_out_64\0caml_ml_set_binary_mode\0caml_ml_set_buffered\0caml_ml_set_channel_name\0caml_ml_set_channel_output\0caml_ml_set_channel_refill\0caml_ml_string_length\0caml_mod\0caml_modf_float\0caml_mount_autoload\0caml_mul\0caml_mul_float\0caml_named_value\0caml_named_values\0caml_nativeint_add\0caml_nativeint_and\0caml_nativeint_bswap\0caml_nativeint_compare\0caml_nativeint_div\0caml_nativeint_format\0caml_nativeint_mod\0caml_nativeint_mul\0caml_nativeint_neg\0caml_nativeint_of_float\0caml_nativeint_of_int\0caml_nativeint_of_int32\0caml_nativeint_of_string\0caml_nativeint_or\0caml_nativeint_shift_left\0caml_nativeint_shift_right\0caml_nativeint_shift_right_unsigned\0caml_nativeint_sub\0caml_nativeint_to_float\0caml_nativeint_to_int\0caml_nativeint_to_int32\0caml_nativeint_unmarshal\0caml_nativeint_xor\0caml_neg_float\0caml_neq_float\0caml_new_lex_engine\0caml_new_string\0caml_nextafter_float\0caml_notequal\0caml_obj_add_offset\0caml_obj_block\0caml_obj_compare_and_swap\0caml_obj_dup\0caml_obj_is_block\0caml_obj_is_shared\0caml_obj_make_forward\0caml_obj_raw_field\0caml_obj_reachable_words\0caml_obj_set_raw_field\0caml_obj_set_tag\0caml_obj_tag\0caml_obj_truncate\0caml_obj_update_tag\0caml_obj_with_tag\0caml_ojs_new_arr\0caml_oo_last_id\0caml_output_val\0caml_output_value\0caml_output_value_to_buffer\0caml_output_value_to_bytes\0caml_output_value_to_string\0caml_parse_digit\0caml_parse_engine\0caml_parse_format\0caml_parse_sign_and_base\0caml_parser_trace\0caml_pos_in\0caml_pos_out\0caml_power_float\0caml_pure_js_expr\0caml_raise_constant\0caml_raise_end_of_file\0caml_raise_no_such_file\0caml_raise_not_a_dir\0caml_raise_not_found\0caml_raise_sys_error\0caml_raise_with_arg\0caml_raise_with_args\0caml_raise_with_string\0caml_raise_zero_divide\0caml_raw_backtrace_length\0caml_raw_backtrace_next_slot\0caml_raw_backtrace_slot\0caml_read_file_content\0caml_recommended_domain_count\0caml_record_backtrace\0caml_record_backtrace_flag\0caml_refill\0caml_register_channel_for_spacetime\0caml_register_global\0caml_register_named_value\0caml_restore_raw_backtrace\0caml_root\0caml_round_float\0caml_runtime_events_create_cursor\0caml_runtime_events_free_cursor\0caml_runtime_events_pause\0caml_runtime_events_read_poll\0caml_runtime_events_resume\0caml_runtime_events_start\0caml_runtime_events_user_register\0caml_runtime_events_user_resolve\0caml_runtime_events_user_write\0caml_runtime_parameters\0caml_runtime_variant\0caml_runtime_warnings\0caml_seek_in\0caml_seek_out\0caml_set_oo_id\0caml_set_parser_trace\0caml_set_static_env\0caml_signbit_float\0caml_sin_float\0caml_sinh_float\0caml_spacetime_enabled\0caml_spacetime_only_works_for_native_code\0caml_sqrt_float\0caml_str_initialize\0caml_str_repeat\0caml_string_bound_error\0caml_string_compare\0caml_string_equal\0caml_string_get\0caml_string_get16\0caml_string_get32\0caml_string_get64\0caml_string_greaterequal\0caml_string_greaterthan\0caml_string_hash\0caml_string_lessequal\0caml_string_lessthan\0caml_string_notequal\0caml_string_of_array\0caml_string_of_bytes\0caml_string_of_jsbytes\0caml_string_of_jsstring\0caml_string_set\0caml_string_set16\0caml_string_set32\0caml_string_set64\0caml_string_unsafe_get\0caml_string_unsafe_set\0caml_sub_float\0caml_subarray_to_jsbytes\0caml_sys_argv\0caml_sys_chdir\0caml_sys_close\0caml_sys_const_backend_type\0caml_sys_const_big_endian\0caml_sys_const_int_size\0caml_sys_const_max_wosize\0caml_sys_const_naked_pointers_checked\0caml_sys_const_ostype_cygwin\0caml_sys_const_ostype_unix\0caml_sys_const_ostype_win32\0caml_sys_const_word_size\0caml_sys_executable_name\0caml_sys_exit\0caml_sys_fds\0caml_sys_file_exists\0caml_sys_get_argv\0caml_sys_get_config\0caml_sys_getcwd\0caml_sys_getenv\0caml_sys_is_directory\0caml_sys_is_regular_file\0caml_sys_isatty\0caml_sys_mkdir\0caml_sys_modify_argv\0caml_sys_open\0caml_sys_open_for_node\0caml_sys_random_seed\0caml_sys_read_directory\0caml_sys_remove\0caml_sys_rename\0caml_sys_rmdir\0caml_sys_system_command\0caml_sys_time\0caml_sys_time_include_children\0caml_sys_unsafe_getenv\0caml_tan_float\0caml_tanh_float\0caml_to_js_string\0caml_trailing_slash\0caml_trampoline\0caml_trampoline_return\0caml_trunc_float\0caml_uint8_array_of_bytes\0caml_uint8_array_of_string\0caml_unix_cleanup\0caml_unix_closedir\0caml_unix_filedescr_of_fd\0caml_unix_findclose\0caml_unix_findfirst\0caml_unix_findnext\0caml_unix_getpwuid\0caml_unix_gettimeofday\0caml_unix_getuid\0caml_unix_gmtime\0caml_unix_has_symlink\0caml_unix_inet_addr_of_string\0caml_unix_isatty\0caml_unix_localtime\0caml_unix_lstat\0caml_unix_lstat_64\0caml_unix_mkdir\0caml_unix_mktime\0caml_unix_opendir\0caml_unix_readdir\0caml_unix_readlink\0caml_unix_rewinddir\0caml_unix_rmdir\0caml_unix_startup\0caml_unix_stat\0caml_unix_stat_64\0caml_unix_symlink\0caml_unix_time\0caml_unix_unlink\0caml_unmount\0caml_update_dummy\0caml_utf16_of_utf8\0caml_utf8_of_utf16\0caml_weak_blit\0caml_weak_check\0caml_weak_create\0caml_weak_get\0caml_weak_get_copy\0caml_weak_set\0caml_wrap_exception\0caml_xmlhttprequest_create\0compare_digits_nat\0compare_nat\0compare_nat_real\0complement_nat\0create_nat\0decr_nat\0deserialize_nat\0div_digit_nat\0div_helper\0div_nat\0fs_node_supported\0incr_nat\0initialize_nat\0is_digit_int\0is_digit_odd\0is_digit_zero\0jsoo_create_file\0jsoo_create_file_extern\0jsoo_effect_not_supported\0jsoo_floor_log2\0jsoo_is_ascii\0jsoo_mount_point\0jsoo_sys_getenv\0land_digit_nat\0lor_digit_nat\0lxor_digit_nat\0make_unix_err_args\0mult_digit_nat\0mult_nat\0nat_of_array\0nth_digit_nat\0nth_digit_nat_native\0num_digits_nat\0num_leading_zero_bits_in_digit\0os_type\0path_is_absolute\0re_match\0re_partial_match\0re_replacement_text\0re_search_backward\0re_search_forward\0re_string_match\0resolve_fs_device\0serialize_nat\0set_digit_nat\0set_digit_nat_native\0set_to_zero_nat\0shift_left_nat\0shift_right_nat\0square_nat\0sub_nat\0unix_closedir\0unix_getpwuid\0unix_gettimeofday\0unix_getuid\0unix_gmtime\0unix_has_symlink\0unix_inet_addr_of_string\0unix_isatty\0unix_localtime\0unix_lstat\0unix_lstat_64\0unix_mkdir\0unix_mktime\0unix_opendir\0unix_readdir\0unix_readlink\0unix_rewinddir\0unix_rmdir\0unix_stat\0unix_stat_64\0unix_symlink\0unix_time\0unix_unlink\0win_cleanup\0win_filedescr_of_channel\0win_findclose\0win_findfirst\0win_findnext\0win_handle_fd\0win_startup\0zstd_decompress\0"],0]]]];return}(globalThis));
//# 1 "../.js/default/stdlib/stdlib.cma.js"
// Generated by js_of_ocaml
//# 3 "../.js/default/stdlib/stdlib.cma.js"

//# 5 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var runtime = globalThis.jsoo_runtime;
   function erase_rel(param){
    if(typeof param === "number") return 0;
    switch(param[0]){
      case 0:
       var rest = param[1]; return [0, erase_rel(rest)];
      case 1:
       var rest$0 = param[1]; return [1, erase_rel(rest$0)];
      case 2:
       var rest$1 = param[1]; return [2, erase_rel(rest$1)];
      case 3:
       var rest$2 = param[1]; return [3, erase_rel(rest$2)];
      case 4:
       var rest$3 = param[1]; return [4, erase_rel(rest$3)];
      case 5:
       var rest$4 = param[1]; return [5, erase_rel(rest$4)];
      case 6:
       var rest$5 = param[1]; return [6, erase_rel(rest$5)];
      case 7:
       var rest$6 = param[1]; return [7, erase_rel(rest$6)];
      case 8:
       var rest$7 = param[2], ty = param[1];
       return [8, ty, erase_rel(rest$7)];
      case 9:
       var rest$8 = param[3], ty1 = param[1];
       return [9, ty1, ty1, erase_rel(rest$8)];
      case 10:
       var rest$9 = param[1]; return [10, erase_rel(rest$9)];
      case 11:
       var rest$10 = param[1]; return [11, erase_rel(rest$10)];
      case 12:
       var rest$11 = param[1]; return [12, erase_rel(rest$11)];
      case 13:
       var rest$12 = param[1]; return [13, erase_rel(rest$12)];
      default: var rest$13 = param[1]; return [14, erase_rel(rest$13)];
    }
   }
   function concat_fmtty(fmtty1, fmtty2){
    if(typeof fmtty1 === "number") return fmtty2;
    switch(fmtty1[0]){
      case 0:
       var rest = fmtty1[1]; return [0, concat_fmtty(rest, fmtty2)];
      case 1:
       var rest$0 = fmtty1[1]; return [1, concat_fmtty(rest$0, fmtty2)];
      case 2:
       var rest$1 = fmtty1[1]; return [2, concat_fmtty(rest$1, fmtty2)];
      case 3:
       var rest$2 = fmtty1[1]; return [3, concat_fmtty(rest$2, fmtty2)];
      case 4:
       var rest$3 = fmtty1[1]; return [4, concat_fmtty(rest$3, fmtty2)];
      case 5:
       var rest$4 = fmtty1[1]; return [5, concat_fmtty(rest$4, fmtty2)];
      case 6:
       var rest$5 = fmtty1[1]; return [6, concat_fmtty(rest$5, fmtty2)];
      case 7:
       var rest$6 = fmtty1[1]; return [7, concat_fmtty(rest$6, fmtty2)];
      case 8:
       var rest$7 = fmtty1[2], ty = fmtty1[1];
       return [8, ty, concat_fmtty(rest$7, fmtty2)];
      case 9:
       var rest$8 = fmtty1[3], ty2 = fmtty1[2], ty1 = fmtty1[1];
       return [9, ty1, ty2, concat_fmtty(rest$8, fmtty2)];
      case 10:
       var rest$9 = fmtty1[1]; return [10, concat_fmtty(rest$9, fmtty2)];
      case 11:
       var rest$10 = fmtty1[1]; return [11, concat_fmtty(rest$10, fmtty2)];
      case 12:
       var rest$11 = fmtty1[1]; return [12, concat_fmtty(rest$11, fmtty2)];
      case 13:
       var rest$12 = fmtty1[1]; return [13, concat_fmtty(rest$12, fmtty2)];
      default:
       var rest$13 = fmtty1[1]; return [14, concat_fmtty(rest$13, fmtty2)];
    }
   }
   function concat_fmt(fmt1, fmt2){
    if(typeof fmt1 === "number") return fmt2;
    switch(fmt1[0]){
      case 0:
       var rest = fmt1[1]; return [0, concat_fmt(rest, fmt2)];
      case 1:
       var rest$0 = fmt1[1]; return [1, concat_fmt(rest$0, fmt2)];
      case 2:
       var rest$1 = fmt1[2], pad = fmt1[1];
       return [2, pad, concat_fmt(rest$1, fmt2)];
      case 3:
       var rest$2 = fmt1[2], pad$0 = fmt1[1];
       return [3, pad$0, concat_fmt(rest$2, fmt2)];
      case 4:
       var rest$3 = fmt1[4], prec = fmt1[3], pad$1 = fmt1[2], iconv = fmt1[1];
       return [4, iconv, pad$1, prec, concat_fmt(rest$3, fmt2)];
      case 5:
       var
        rest$4 = fmt1[4],
        prec$0 = fmt1[3],
        pad$2 = fmt1[2],
        iconv$0 = fmt1[1];
       return [5, iconv$0, pad$2, prec$0, concat_fmt(rest$4, fmt2)];
      case 6:
       var
        rest$5 = fmt1[4],
        prec$1 = fmt1[3],
        pad$3 = fmt1[2],
        iconv$1 = fmt1[1];
       return [6, iconv$1, pad$3, prec$1, concat_fmt(rest$5, fmt2)];
      case 7:
       var
        rest$6 = fmt1[4],
        prec$2 = fmt1[3],
        pad$4 = fmt1[2],
        iconv$2 = fmt1[1];
       return [7, iconv$2, pad$4, prec$2, concat_fmt(rest$6, fmt2)];
      case 8:
       var
        rest$7 = fmt1[4],
        prec$3 = fmt1[3],
        pad$5 = fmt1[2],
        fconv = fmt1[1];
       return [8, fconv, pad$5, prec$3, concat_fmt(rest$7, fmt2)];
      case 9:
       var rest$8 = fmt1[2], pad$6 = fmt1[1];
       return [9, pad$6, concat_fmt(rest$8, fmt2)];
      case 10:
       var rest$9 = fmt1[1]; return [10, concat_fmt(rest$9, fmt2)];
      case 11:
       var rest$10 = fmt1[2], str = fmt1[1];
       return [11, str, concat_fmt(rest$10, fmt2)];
      case 12:
       var rest$11 = fmt1[2], chr = fmt1[1];
       return [12, chr, concat_fmt(rest$11, fmt2)];
      case 13:
       var rest$12 = fmt1[3], fmtty = fmt1[2], pad$7 = fmt1[1];
       return [13, pad$7, fmtty, concat_fmt(rest$12, fmt2)];
      case 14:
       var rest$13 = fmt1[3], fmtty$0 = fmt1[2], pad$8 = fmt1[1];
       return [14, pad$8, fmtty$0, concat_fmt(rest$13, fmt2)];
      case 15:
       var rest$14 = fmt1[1]; return [15, concat_fmt(rest$14, fmt2)];
      case 16:
       var rest$15 = fmt1[1]; return [16, concat_fmt(rest$15, fmt2)];
      case 17:
       var rest$16 = fmt1[2], fmting_lit = fmt1[1];
       return [17, fmting_lit, concat_fmt(rest$16, fmt2)];
      case 18:
       var rest$17 = fmt1[2], fmting_gen = fmt1[1];
       return [18, fmting_gen, concat_fmt(rest$17, fmt2)];
      case 19:
       var rest$18 = fmt1[1]; return [19, concat_fmt(rest$18, fmt2)];
      case 20:
       var rest$19 = fmt1[3], char_set = fmt1[2], width_opt = fmt1[1];
       return [20, width_opt, char_set, concat_fmt(rest$19, fmt2)];
      case 21:
       var rest$20 = fmt1[2], counter = fmt1[1];
       return [21, counter, concat_fmt(rest$20, fmt2)];
      case 22:
       var rest$21 = fmt1[1]; return [22, concat_fmt(rest$21, fmt2)];
      case 23:
       var rest$22 = fmt1[2], ign = fmt1[1];
       return [23, ign, concat_fmt(rest$22, fmt2)];
      default:
       var rest$23 = fmt1[3], f = fmt1[2], arity = fmt1[1];
       return [24, arity, f, concat_fmt(rest$23, fmt2)];
    }
   }
   var CamlinternalFormatBasics = [0, concat_fmtty, erase_rel, concat_fmt];
   runtime.caml_register_global
    (0, CamlinternalFormatBasics, "CamlinternalFormatBasics");
   return;
  }
  (globalThis));

//# 179 "../.js/default/stdlib/stdlib.cma.js"
(function(globalThis){
   "use strict";
   var runtime = globalThis.jsoo_runtime;
   function make(v){return [0, v];}
   function get(r){return r[1];}
   function set(r, v){r[1] = v; return 0;}
   function exchange(r, v){var cur = r[1]; r[1] = v; return cur;}
   function compare_and_set(r, seen, v){
    var cur = r[1];
    return cur === seen ? (r[1] = v, 1) : 0;
   }
   function fetch_and_add(r, n){
    var cur = r[1];
    r[1] = cur + n | 0;
    return cur;
   }
   function incr(r){fetch_and_add(r, 1); return 0;}
   function decr(r){fetch_and_add(r, -1); return 0;}
   var
    CamlinternalAtomic =
      [0,
       make,
       get,
       set,
       exchange,
       compare_and_set,
       fetch_and_add,
       incr,
       decr];
   runtime.caml_register_global(0, CamlinternalAtomic, "CamlinternalAtomic");
   return;
  }
  (globalThis));

//# 215 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst_false$0 = "false",
    cst_true$0 = "true",
    caml_blit_string = runtime.caml_blit_string,
    caml_create_bytes = runtime.caml_create_bytes,
    caml_float_of_string = runtime.caml_float_of_string,
    caml_int64_float_of_bits = runtime.caml_int64_float_of_bits,
    caml_int_of_string = runtime.caml_int_of_string,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_ml_bytes_length = runtime.caml_ml_bytes_length,
    caml_ml_channel_size = runtime.caml_ml_channel_size,
    caml_ml_channel_size_64 = runtime.caml_ml_channel_size_64,
    caml_ml_close_channel = runtime.caml_ml_close_channel,
    caml_ml_flush = runtime.caml_ml_flush,
    caml_ml_input = runtime.caml_ml_input,
    caml_ml_input_char = runtime.caml_ml_input_char,
    caml_ml_open_descriptor_in = runtime.caml_ml_open_descriptor_in,
    caml_ml_open_descriptor_out = runtime.caml_ml_open_descriptor_out,
    caml_ml_output = runtime.caml_ml_output,
    caml_ml_output_bytes = runtime.caml_ml_output_bytes,
    caml_ml_output_char = runtime.caml_ml_output_char,
    caml_ml_set_binary_mode = runtime.caml_ml_set_binary_mode,
    caml_ml_set_channel_name = runtime.caml_ml_set_channel_name,
    caml_ml_string_length = runtime.caml_ml_string_length,
    caml_string_notequal = runtime.caml_string_notequal,
    caml_string_of_bytes = runtime.caml_string_of_bytes,
    caml_sys_open = runtime.caml_sys_open,
    caml_wrap_exception = runtime.caml_wrap_exception;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   function caml_call3(f, a0, a1, a2){
    return (f.l >= 0 ? f.l : f.l = f.length) == 3
            ? f(a0, a1, a2)
            : runtime.caml_call_gen(f, [a0, a1, a2]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    cst$0 = "%,",
    cst = ".",
    CamlinternalAtomic = global_data.CamlinternalAtomic,
    CamlinternalFormatBasics = global_data.CamlinternalFormatBasics,
    Invalid_argument = global_data.Invalid_argument,
    Failure = global_data.Failure,
    Match_failure = global_data.Match_failure,
    Assert_failure = global_data.Assert_failure,
    Not_found = global_data.Not_found,
    Out_of_memory = global_data.Out_of_memory,
    Stack_overflow = global_data.Stack_overflow,
    Sys_error = global_data.Sys_error,
    End_of_file = global_data.End_of_file,
    Division_by_zero = global_data.Division_by_zero,
    Sys_blocked_io = global_data.Sys_blocked_io,
    Undefined_recursive_module = global_data.Undefined_recursive_module,
    cst_really_input = "really_input",
    cst_input = "input",
    _l_ = [0, 0, [0, 6, 0]],
    _k_ = [0, 0, [0, 7, 0]],
    cst_output_substring = "output_substring",
    cst_output = "output",
    _j_ = [0, 1, [0, 3, [0, 4, [0, 6, 0]]]],
    _i_ = [0, 1, [0, 3, [0, 4, [0, 7, 0]]]],
    _g_ = [0, 1],
    _h_ = [0, 0],
    cst_bool_of_string = "bool_of_string",
    cst_true = cst_true$0,
    cst_false = cst_false$0,
    cst_char_of_int = "char_of_int",
    cst_Stdlib_Exit = "Stdlib.Exit",
    _a_ = runtime.caml_int64_create_lo_mi_hi(0, 0, 32752),
    _b_ = runtime.caml_int64_create_lo_mi_hi(0, 0, 65520),
    _c_ = runtime.caml_int64_create_lo_mi_hi(1, 0, 32752),
    _d_ = runtime.caml_int64_create_lo_mi_hi(16777215, 16777215, 32751),
    _e_ = runtime.caml_int64_create_lo_mi_hi(0, 0, 16),
    _f_ = runtime.caml_int64_create_lo_mi_hi(0, 0, 15536);
   function failwith(s){
    throw caml_maybe_attach_backtrace([0, Failure, s], 1);
   }
   function invalid_arg(s){
    throw caml_maybe_attach_backtrace([0, Invalid_argument, s], 1);
   }
   var Exit = [248, cst_Stdlib_Exit, runtime.caml_fresh_oo_id(0)];
   function min(x, y){return runtime.caml_lessequal(x, y) ? x : y;}
   function max(x, y){return runtime.caml_greaterequal(x, y) ? x : y;}
   function abs(x){return 0 <= x ? x : - x | 0;}
   function lnot(x){return x ^ -1;}
   var
    infinity = caml_int64_float_of_bits(_a_),
    neg_infinity = caml_int64_float_of_bits(_b_),
    nan = caml_int64_float_of_bits(_c_),
    max_float = caml_int64_float_of_bits(_d_),
    min_float = caml_int64_float_of_bits(_e_),
    epsilon_float = caml_int64_float_of_bits(_f_),
    max_int = 2147483647,
    min_int = -2147483648;
   function symbol(s1, s2){
    var
     l1 = caml_ml_string_length(s1),
     l2 = caml_ml_string_length(s2),
     s = caml_create_bytes(l1 + l2 | 0);
    caml_blit_string(s1, 0, s, 0, l1);
    caml_blit_string(s2, 0, s, l1, l2);
    return caml_string_of_bytes(s);
   }
   function char_of_int(n){
    if(0 <= n && 255 >= n) return n;
    return invalid_arg(cst_char_of_int);
   }
   function string_of_bool(b){return b ? cst_true : cst_false;}
   function bool_of_string(param){
    return caml_string_notequal(param, cst_false$0)
            ? caml_string_notequal
               (param, cst_true$0)
              ? invalid_arg(cst_bool_of_string)
              : 1
            : 0;
   }
   function bool_of_string_opt(param){
    return caml_string_notequal(param, cst_false$0)
            ? caml_string_notequal(param, cst_true$0) ? 0 : _g_
            : _h_;
   }
   function string_of_int(n){return "" + n;}
   function int_of_string_opt(s){
    try{var _B_ = [0, caml_int_of_string(s)]; return _B_;}
    catch(_C_){
     var _A_ = caml_wrap_exception(_C_);
     if(_A_[1] === Failure) return 0;
     throw caml_maybe_attach_backtrace(_A_, 0);
    }
   }
   function valid_float_lexem(s){
    var l = caml_ml_string_length(s), i = 0;
    for(;;){
     if(l <= i) return symbol(s, cst);
     var match = runtime.caml_string_get(s, i), switch$0 = 0;
     if(48 <= match){
      if(58 > match) switch$0 = 1;
     }
     else if(45 === match) switch$0 = 1;
     if(! switch$0) return s;
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function string_of_float(f){
    return valid_float_lexem(runtime.caml_format_float("%.12g", f));
   }
   function float_of_string_opt(s){
    try{var _y_ = [0, caml_float_of_string(s)]; return _y_;}
    catch(_z_){
     var _x_ = caml_wrap_exception(_z_);
     if(_x_[1] === Failure) return 0;
     throw caml_maybe_attach_backtrace(_x_, 0);
    }
   }
   function symbol$0(l1, l2){
    if(! l1) return l2;
    var tl = l1[2], hd = l1[1];
    return [0, hd, symbol$0(tl, l2)];
   }
   var
    stdin = caml_ml_open_descriptor_in(0),
    stdout = caml_ml_open_descriptor_out(1),
    stderr = caml_ml_open_descriptor_out(2);
   function open_out_gen(mode, perm, name){
    var c = caml_ml_open_descriptor_out(caml_sys_open(name, mode, perm));
    caml_ml_set_channel_name(c, name);
    return c;
   }
   function open_out(name){return open_out_gen(_i_, 438, name);}
   function open_out_bin(name){return open_out_gen(_j_, 438, name);}
   function flush_all(param){
    var param$0 = runtime.caml_ml_out_channels_list(0);
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], a = param$0[1];
     try{caml_ml_flush(a);}
     catch(_w_){
      var _v_ = caml_wrap_exception(_w_);
      if(_v_[1] !== Sys_error) throw caml_maybe_attach_backtrace(_v_, 0);
     }
     var param$0 = l;
    }
   }
   function output_bytes(oc, s){
    return caml_ml_output_bytes(oc, s, 0, caml_ml_bytes_length(s));
   }
   function output_string(oc, s){
    return caml_ml_output(oc, s, 0, caml_ml_string_length(s));
   }
   function output(oc, s, ofs, len){
    if(0 <= ofs && 0 <= len && (caml_ml_bytes_length(s) - len | 0) >= ofs)
     return caml_ml_output_bytes(oc, s, ofs, len);
    return invalid_arg(cst_output);
   }
   function output_substring(oc, s, ofs, len){
    if(0 <= ofs && 0 <= len && (caml_ml_string_length(s) - len | 0) >= ofs)
     return caml_ml_output(oc, s, ofs, len);
    return invalid_arg(cst_output_substring);
   }
   function output_value(chan, v){
    return runtime.caml_output_value(chan, v, 0);
   }
   function close_out(oc){
    caml_ml_flush(oc);
    return caml_ml_close_channel(oc);
   }
   function close_out_noerr(oc){
    try{caml_ml_flush(oc);}catch(_u_){}
    try{var _s_ = caml_ml_close_channel(oc); return _s_;}catch(_t_){return 0;}
   }
   function open_in_gen(mode, perm, name){
    var c = caml_ml_open_descriptor_in(caml_sys_open(name, mode, perm));
    caml_ml_set_channel_name(c, name);
    return c;
   }
   function open_in(name){return open_in_gen(_k_, 0, name);}
   function open_in_bin(name){return open_in_gen(_l_, 0, name);}
   function input(ic, s, ofs, len){
    if(0 <= ofs && 0 <= len && (caml_ml_bytes_length(s) - len | 0) >= ofs)
     return caml_ml_input(ic, s, ofs, len);
    return invalid_arg(cst_input);
   }
   function unsafe_really_input(ic, s, ofs, len){
    var ofs$0 = ofs, len$0 = len;
    for(;;){
     if(0 >= len$0) return 0;
     var r = caml_ml_input(ic, s, ofs$0, len$0);
     if(0 === r) throw caml_maybe_attach_backtrace(End_of_file, 1);
     var
      len$1 = len$0 - r | 0,
      ofs$1 = ofs$0 + r | 0,
      ofs$0 = ofs$1,
      len$0 = len$1;
    }
   }
   function really_input(ic, s, ofs, len){
    if(0 <= ofs && 0 <= len && (caml_ml_bytes_length(s) - len | 0) >= ofs)
     return unsafe_really_input(ic, s, ofs, len);
    return invalid_arg(cst_really_input);
   }
   function really_input_string(ic, len){
    var s = caml_create_bytes(len);
    really_input(ic, s, 0, len);
    return caml_string_of_bytes(s);
   }
   function input_line(chan){
    function build_result(buf, pos, param){
     var pos$0 = pos, param$0 = param;
     for(;;){
      if(! param$0) return buf;
      var tl = param$0[2], hd = param$0[1], len = caml_ml_bytes_length(hd);
      runtime.caml_blit_bytes(hd, 0, buf, pos$0 - len | 0, len);
      var pos$1 = pos$0 - len | 0, pos$0 = pos$1, param$0 = tl;
     }
    }
    var accu = 0, len = 0;
    for(;;){
     var n = runtime.caml_ml_input_scan_line(chan);
     if(0 === n){
      if(! accu) throw caml_maybe_attach_backtrace(End_of_file, 1);
      var _r_ = build_result(caml_create_bytes(len), len, accu);
     }
     else{
      if(0 >= n){
       var beg = caml_create_bytes(- n | 0);
       caml_ml_input(chan, beg, 0, - n | 0);
       var
        len$1 = len - n | 0,
        accu$0 = [0, beg, accu],
        accu = accu$0,
        len = len$1;
       continue;
      }
      var res = caml_create_bytes(n - 1 | 0);
      caml_ml_input(chan, res, 0, n - 1 | 0);
      caml_ml_input_char(chan);
      if(accu)
       var
        len$0 = (len + n | 0) - 1 | 0,
        _r_ = build_result(caml_create_bytes(len$0), len$0, [0, res, accu]);
      else
       var _r_ = res;
     }
     return caml_string_of_bytes(_r_);
    }
   }
   function close_in_noerr(ic){
    try{var _p_ = caml_ml_close_channel(ic); return _p_;}catch(_q_){return 0;}
   }
   function print_char(c){return caml_ml_output_char(stdout, c);}
   function print_string(s){return output_string(stdout, s);}
   function print_bytes(s){return output_bytes(stdout, s);}
   function print_int(i){return output_string(stdout, "" + i);}
   function print_float(f){return output_string(stdout, string_of_float(f));}
   function print_endline(s){
    output_string(stdout, s);
    caml_ml_output_char(stdout, 10);
    return caml_ml_flush(stdout);
   }
   function print_newline(param){
    caml_ml_output_char(stdout, 10);
    return caml_ml_flush(stdout);
   }
   function prerr_char(c){return caml_ml_output_char(stderr, c);}
   function prerr_string(s){return output_string(stderr, s);}
   function prerr_bytes(s){return output_bytes(stderr, s);}
   function prerr_int(i){return output_string(stderr, "" + i);}
   function prerr_float(f){return output_string(stderr, string_of_float(f));}
   function prerr_endline(s){
    output_string(stderr, s);
    caml_ml_output_char(stderr, 10);
    return caml_ml_flush(stderr);
   }
   function prerr_newline(param){
    caml_ml_output_char(stderr, 10);
    return caml_ml_flush(stderr);
   }
   function read_line(param){caml_ml_flush(stdout); return input_line(stdin);}
   function read_int(param){return caml_int_of_string(read_line(0));}
   function read_int_opt(param){return int_of_string_opt(read_line(0));}
   function read_float(param){return caml_float_of_string(read_line(0));}
   function read_float_opt(param){return float_of_string_opt(read_line(0));}
   function string_of_format(param){var str = param[2]; return str;}
   function symbol$1(param, _n_){
    var
     str2 = _n_[2],
     fmt2 = _n_[1],
     str1 = param[2],
     fmt1 = param[1],
     _o_ = symbol(str1, symbol(cst$0, str2));
    return [0, caml_call2(CamlinternalFormatBasics[3], fmt1, fmt2), _o_];
   }
   var exit_function = caml_call1(CamlinternalAtomic[1], flush_all);
   function at_exit(f){
    for(;;){
     var
      f_yet_to_run = caml_call1(CamlinternalAtomic[1], 1),
      old_exit = caml_call1(CamlinternalAtomic[2], exit_function),
      new_exit$0 =
        function(f_yet_to_run, old_exit){
         function new_exit(param){
          if(caml_call3(CamlinternalAtomic[5], f_yet_to_run, 1, 0))
           caml_call1(f, 0);
          return caml_call1(old_exit, 0);
         }
         return new_exit;
        },
      new_exit = new_exit$0(f_yet_to_run, old_exit),
      success =
        caml_call3(CamlinternalAtomic[5], exit_function, old_exit, new_exit),
      _m_ = 1 - success;
     if(_m_) continue;
     return _m_;
    }
   }
   function do_at_exit(param){
    return caml_call1(caml_call1(CamlinternalAtomic[2], exit_function), 0);
   }
   function exit(retcode){
    do_at_exit(0);
    return runtime.caml_sys_exit(retcode);
   }
   runtime.caml_register_named_value("Pervasives.do_at_exit", do_at_exit);
   var
    Stdlib =
      [0,
       invalid_arg,
       failwith,
       Exit,
       Match_failure,
       Assert_failure,
       Invalid_argument,
       Failure,
       Not_found,
       Out_of_memory,
       Stack_overflow,
       Sys_error,
       End_of_file,
       Division_by_zero,
       Sys_blocked_io,
       Undefined_recursive_module,
       min,
       max,
       abs,
       max_int,
       min_int,
       lnot,
       infinity,
       neg_infinity,
       nan,
       max_float,
       min_float,
       epsilon_float,
       symbol,
       char_of_int,
       string_of_bool,
       bool_of_string_opt,
       bool_of_string,
       string_of_int,
       int_of_string_opt,
       string_of_float,
       float_of_string_opt,
       symbol$0,
       stdin,
       stdout,
       stderr,
       print_char,
       print_string,
       print_bytes,
       print_int,
       print_float,
       print_endline,
       print_newline,
       prerr_char,
       prerr_string,
       prerr_bytes,
       prerr_int,
       prerr_float,
       prerr_endline,
       prerr_newline,
       read_line,
       read_int_opt,
       read_int,
       read_float_opt,
       read_float,
       open_out,
       open_out_bin,
       open_out_gen,
       caml_ml_flush,
       flush_all,
       caml_ml_output_char,
       output_string,
       output_bytes,
       output,
       output_substring,
       caml_ml_output_char,
       runtime.caml_ml_output_int,
       output_value,
       runtime.caml_ml_seek_out,
       runtime.caml_ml_pos_out,
       caml_ml_channel_size,
       close_out,
       close_out_noerr,
       caml_ml_set_binary_mode,
       open_in,
       open_in_bin,
       open_in_gen,
       caml_ml_input_char,
       input_line,
       input,
       really_input,
       really_input_string,
       caml_ml_input_char,
       runtime.caml_ml_input_int,
       runtime.caml_input_value,
       runtime.caml_ml_seek_in,
       runtime.caml_ml_pos_in,
       caml_ml_channel_size,
       caml_ml_close_channel,
       close_in_noerr,
       caml_ml_set_binary_mode,
       [0,
        runtime.caml_ml_seek_out_64,
        runtime.caml_ml_pos_out_64,
        caml_ml_channel_size_64,
        runtime.caml_ml_seek_in_64,
        runtime.caml_ml_pos_in_64,
        caml_ml_channel_size_64],
       string_of_format,
       symbol$1,
       exit,
       at_exit,
       valid_float_lexem,
       unsafe_really_input,
       do_at_exit];
   runtime.caml_register_global(46, Stdlib, "Stdlib");
   return;
  }
  (globalThis));

//# 996 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_wrap_exception = runtime.caml_wrap_exception,
    global_data = runtime.caml_get_global_data(),
    ocaml_version = "4.14.1",
    ocaml_release = [0, 4, 14, 1, 0],
    Stdlib = global_data.Stdlib,
    executable_name = runtime.caml_sys_executable_name(0),
    os_type = runtime.caml_sys_get_config(0)[1],
    backend_type = [0, "js_of_ocaml"],
    unix = runtime.caml_sys_const_ostype_unix(0),
    win32 = runtime.caml_sys_const_ostype_win32(0),
    cygwin = runtime.caml_sys_const_ostype_cygwin(0),
    max_array_length = runtime.caml_sys_const_max_wosize(0),
    max_floatarray_length = max_array_length / 2 | 0,
    max_string_length = (4 * max_array_length | 0) - 1 | 0,
    cst_Stdlib_Sys_Break = "Stdlib.Sys.Break",
    big_endian = 0,
    word_size = 32,
    int_size = 32;
   function getenv_opt(s){
    try{var _d_ = [0, runtime.caml_sys_getenv(s)]; return _d_;}
    catch(_e_){
     var _c_ = caml_wrap_exception(_e_);
     if(_c_ === Stdlib[8]) return 0;
     throw caml_maybe_attach_backtrace(_c_, 0);
    }
   }
   var interactive = [0, 0];
   function set_signal(sig_num, sig_beh){return 0;}
   var
    Break = [248, cst_Stdlib_Sys_Break, runtime.caml_fresh_oo_id(0)],
    sigabrt = -1,
    sigalrm = -2,
    sigfpe = -3,
    sighup = -4,
    sigill = -5,
    sigint = -6,
    sigkill = -7,
    sigpipe = -8,
    sigquit = -9,
    sigsegv = -10,
    sigterm = -11,
    sigusr1 = -12,
    sigusr2 = -13,
    sigchld = -14,
    sigcont = -15,
    sigstop = -16,
    sigtstp = -17,
    sigttin = -18,
    sigttou = -19,
    sigvtalrm = -20,
    sigprof = -21,
    sigbus = -22,
    sigpoll = -23,
    sigsys = -24,
    sigtrap = -25,
    sigurg = -26,
    sigxcpu = -27,
    sigxfsz = -28;
   function catch_break(on){return on ? 0 : 0;}
   var development_version = 0;
   function Make(_b_, _a_){return [0, 1];}
   var
    Immediate64 = [0, Make],
    Stdlib_Sys =
      [0,
       executable_name,
       getenv_opt,
       interactive,
       os_type,
       backend_type,
       unix,
       win32,
       cygwin,
       word_size,
       int_size,
       big_endian,
       max_string_length,
       max_array_length,
       max_floatarray_length,
       set_signal,
       sigabrt,
       sigalrm,
       sigfpe,
       sighup,
       sigill,
       sigint,
       sigkill,
       sigpipe,
       sigquit,
       sigsegv,
       sigterm,
       sigusr1,
       sigusr2,
       sigchld,
       sigcont,
       sigstop,
       sigtstp,
       sigttin,
       sigttou,
       sigvtalrm,
       sigprof,
       sigbus,
       sigpoll,
       sigsys,
       sigtrap,
       sigurg,
       sigxcpu,
       sigxfsz,
       Break,
       catch_break,
       ocaml_version,
       development_version,
       ocaml_release,
       runtime.caml_ml_enable_runtime_warnings,
       runtime.caml_ml_runtime_warnings_enabled,
       Immediate64];
   runtime.caml_register_global(4, Stdlib_Sys, "Stdlib__Sys");
   return;
  }
  (globalThis));

//# 1125 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst_Obj_extension_constructor$1 = "Obj.extension_constructor",
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_obj_tag = runtime.caml_obj_tag;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Stdlib = global_data.Stdlib,
    Assert_failure = global_data.Assert_failure,
    Stdlib_Sys = global_data.Stdlib__Sys,
    cst_Obj_Ephemeron_blit_key = "Obj.Ephemeron.blit_key",
    cst_Obj_Ephemeron_check_key = "Obj.Ephemeron.check_key",
    cst_Obj_Ephemeron_unset_key = "Obj.Ephemeron.unset_key",
    cst_Obj_Ephemeron_set_key = "Obj.Ephemeron.set_key",
    cst_Obj_Ephemeron_get_key_copy = "Obj.Ephemeron.get_key_copy",
    cst_Obj_Ephemeron_get_key = "Obj.Ephemeron.get_key",
    cst_Obj_Ephemeron_create = "Obj.Ephemeron.create",
    cst_Obj_extension_constructor$0 = cst_Obj_extension_constructor$1,
    cst_Obj_extension_constructor = cst_Obj_extension_constructor$1,
    _a_ = [0, "obj.ml", 95, 4];
   function is_block(a){return 1 - (typeof a === "number" ? 1 : 0);}
   var
    double_field = runtime.caml_array_get,
    set_double_field = runtime.caml_array_set,
    first_non_constant_constructor = 0,
    last_non_constant_constructor_ = 245,
    lazy_tag = 246,
    closure_tag = 247,
    object_tag = 248,
    infix_tag = 249,
    forward_tag = 250,
    no_scan_tag = 251,
    abstract_tag = 251,
    string_tag = 252,
    double_tag = 253,
    double_array_tag = 254,
    custom_tag = 255,
    int_tag = 1000,
    out_of_heap_tag = 1001,
    unaligned_tag = 1002;
   function info(obj){
    if(caml_obj_tag(obj) !== 247)
     throw caml_maybe_attach_backtrace([0, Assert_failure, _a_], 1);
    var
     info = runtime.caml_obj_raw_field(obj, 1),
     arity = 64 === Stdlib_Sys[9] ? info >> 56 : info >> 24,
     start_env = info << 8 >>> 9 | 0;
    return [0, arity, start_env];
   }
   function of_val(x){
    var switch$0 = 0;
    if(is_block(x) && caml_obj_tag(x) !== 248 && 1 <= x.length - 1){var slot = x[1]; switch$0 = 1;}
    if(! switch$0) var slot = x;
    var switch$1 = 0;
    if(is_block(slot) && caml_obj_tag(slot) === 248){var name = slot[1]; switch$1 = 1;}
    if(! switch$1)
     var name = caml_call1(Stdlib[1], cst_Obj_extension_constructor$0);
    return caml_obj_tag(name) === 252
            ? slot
            : caml_call1(Stdlib[1], cst_Obj_extension_constructor);
   }
   function name(slot){return slot[1];}
   function id(slot){return slot[2];}
   var
    Extension_constructor = [0, of_val, name, id],
    extension_constructor = Extension_constructor[1],
    extension_name = Extension_constructor[2],
    extension_id = Extension_constructor[3],
    max_ephe_length = Stdlib_Sys[13] - 2 | 0;
   function create(l){
    var _g_ = 0 <= l ? 1 : 0, _h_ = _g_ ? l <= max_ephe_length ? 1 : 0 : _g_;
    if(1 - _h_) caml_call1(Stdlib[1], cst_Obj_Ephemeron_create);
    return runtime.caml_ephe_create(l);
   }
   function length(x){return x.length - 1 - 2 | 0;}
   function raise_if_invalid_offset(e, o, msg){
    var
     _d_ = 0 <= o ? 1 : 0,
     _e_ = _d_ ? o < length(e) ? 1 : 0 : _d_,
     _f_ = 1 - _e_;
    return _f_ ? caml_call1(Stdlib[1], msg) : _f_;
   }
   function get_key(e, o){
    raise_if_invalid_offset(e, o, cst_Obj_Ephemeron_get_key);
    return runtime.caml_ephe_get_key(e, o);
   }
   function get_key_copy(e, o){
    raise_if_invalid_offset(e, o, cst_Obj_Ephemeron_get_key_copy);
    return runtime.caml_ephe_get_key_copy(e, o);
   }
   function set_key(e, o, x){
    raise_if_invalid_offset(e, o, cst_Obj_Ephemeron_set_key);
    return runtime.caml_ephe_set_key(e, o, x);
   }
   function unset_key(e, o){
    raise_if_invalid_offset(e, o, cst_Obj_Ephemeron_unset_key);
    return runtime.caml_ephe_unset_key(e, o);
   }
   function check_key(e, o){
    raise_if_invalid_offset(e, o, cst_Obj_Ephemeron_check_key);
    return runtime.caml_ephe_check_key(e, o);
   }
   function blit_key(e1, o1, e2, o2, l){
    if
     (0 <= l
      &&
       0 <= o1
       && (length(e1) - l | 0) >= o1 && 0 <= o2 && (length(e2) - l | 0) >= o2){
     var
      _b_ = 0 !== l ? 1 : 0,
      _c_ = _b_ ? runtime.caml_ephe_blit_key(e1, o1, e2, o2, l) : _b_;
     return _c_;
    }
    return caml_call1(Stdlib[1], cst_Obj_Ephemeron_blit_key);
   }
   var
    Stdlib_Obj =
      [0,
       is_block,
       double_field,
       set_double_field,
       first_non_constant_constructor,
       last_non_constant_constructor_,
       lazy_tag,
       closure_tag,
       object_tag,
       infix_tag,
       forward_tag,
       no_scan_tag,
       abstract_tag,
       string_tag,
       double_tag,
       double_array_tag,
       custom_tag,
       custom_tag,
       int_tag,
       out_of_heap_tag,
       unaligned_tag,
       [0, info],
       Extension_constructor,
       extension_constructor,
       extension_name,
       extension_id,
       [0,
        create,
        length,
        get_key,
        get_key_copy,
        set_key,
        unset_key,
        check_key,
        blit_key,
        runtime.caml_ephe_get_data,
        runtime.caml_ephe_get_data_copy,
        runtime.caml_ephe_set_data,
        runtime.caml_ephe_unset_data,
        runtime.caml_ephe_check_data,
        runtime.caml_ephe_blit_data,
        max_ephe_length]];
   runtime.caml_register_global(13, Stdlib_Obj, "Stdlib__Obj");
   return;
  }
  (globalThis));

//# 1299 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_obj_make_forward = runtime.caml_obj_make_forward,
    caml_obj_tag = runtime.caml_obj_tag,
    caml_wrap_exception = runtime.caml_wrap_exception;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Stdlib_Obj = global_data.Stdlib__Obj,
    Undefined =
      [248, "CamlinternalLazy.Undefined", runtime.caml_fresh_oo_id(0)];
   function raise_undefined(param){
    throw caml_maybe_attach_backtrace(Undefined, 1);
   }
   function force_lazy_block(blk){
    var closure = blk[1];
    blk[1] = raise_undefined;
    try{
     var result = caml_call1(closure, 0);
     caml_obj_make_forward(blk, result);
     return result;
    }
    catch(e$0){
     var e = caml_wrap_exception(e$0);
     blk[1] = function(param){throw caml_maybe_attach_backtrace(e, 0);};
     throw caml_maybe_attach_backtrace(e, 0);
    }
   }
   function force_val_lazy_block(blk){
    var closure = blk[1];
    blk[1] = raise_undefined;
    var result = caml_call1(closure, 0);
    caml_obj_make_forward(blk, result);
    return result;
   }
   function force(lzv){
    var t = caml_obj_tag(lzv);
    return t === Stdlib_Obj[10]
            ? lzv[1]
            : t !== Stdlib_Obj[6] ? lzv : force_lazy_block(lzv);
   }
   function force_val(lzv){
    var t = caml_obj_tag(lzv);
    return t === Stdlib_Obj[10]
            ? lzv[1]
            : t !== Stdlib_Obj[6] ? lzv : force_val_lazy_block(lzv);
   }
   var
    CamlinternalLazy =
      [0, Undefined, force_lazy_block, force_val_lazy_block, force, force_val];
   runtime.caml_register_global(2, CamlinternalLazy, "CamlinternalLazy");
   return;
  }
  (globalThis));

//# 1364 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var runtime = globalThis.jsoo_runtime, caml_obj_tag = runtime.caml_obj_tag;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    CamlinternalLazy = global_data.CamlinternalLazy,
    Stdlib_Obj = global_data.Stdlib__Obj,
    Undefined = CamlinternalLazy[1],
    force_val = CamlinternalLazy[5];
   function from_fun(f){
    var x = runtime.caml_obj_block(Stdlib_Obj[6], 1);
    x[1] = f;
    return x;
   }
   function from_val(v){
    var t = caml_obj_tag(v);
    if(t !== Stdlib_Obj[10] && t !== Stdlib_Obj[6] && t !== Stdlib_Obj[14])
     return v;
    return runtime.caml_lazy_make_forward(v);
   }
   function is_val(l){
    var _i_ = Stdlib_Obj[6];
    return caml_obj_tag(l) !== _i_ ? 1 : 0;
   }
   function map(f, x){
    return [246,
            function(_f_){
             var
              _g_ = caml_obj_tag(x),
              _h_ =
                250 === _g_
                 ? x[1]
                 : 246 === _g_ ? caml_call1(CamlinternalLazy[2], x) : x;
             return caml_call1(f, _h_);
            }];
   }
   function map_val(f, x){
    if(! is_val(x))
     return [246,
             function(_c_){
              var
               _d_ = caml_obj_tag(x),
               _e_ =
                 250 === _d_
                  ? x[1]
                  : 246 === _d_ ? caml_call1(CamlinternalLazy[2], x) : x;
              return caml_call1(f, _e_);
             }];
    var
     _a_ = caml_obj_tag(x),
     _b_ =
       250 === _a_
        ? x[1]
        : 246 === _a_ ? caml_call1(CamlinternalLazy[2], x) : x;
    return from_val(caml_call1(f, _b_));
   }
   var
    Stdlib_Lazy =
      [0,
       Undefined,
       map,
       is_val,
       from_val,
       map_val,
       from_fun,
       force_val,
       from_fun,
       from_val,
       is_val];
   runtime.caml_register_global(2, Stdlib_Lazy, "Stdlib__Lazy");
   return;
  }
  (globalThis));

//# 1446 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   function caml_call3(f, a0, a1, a2){
    return (f.l >= 0 ? f.l : f.l = f.length) == 3
            ? f(a0, a1, a2)
            : runtime.caml_call_gen(f, [a0, a1, a2]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Assert_failure = global_data.Assert_failure,
    CamlinternalAtomic = global_data.CamlinternalAtomic,
    CamlinternalLazy = global_data.CamlinternalLazy,
    Stdlib = global_data.Stdlib,
    Stdlib_Lazy = global_data.Stdlib__Lazy,
    _a_ = [0, "seq.ml", 596, 4],
    cst_Seq_drop = "Seq.drop",
    cst_Seq_take = "Seq.take",
    cst_Seq_init = "Seq.init",
    cst_Stdlib_Seq_Forced_twice = "Stdlib.Seq.Forced_twice";
   function empty(param){return 0;}
   function return$0(x, param){return [0, x, empty];}
   function cons(x, next, param){return [0, x, next];}
   function append(seq1, seq2, param){
    var match = caml_call1(seq1, 0);
    if(! match) return caml_call1(seq2, 0);
    var next = match[2], x = match[1];
    return [0, x, function(_aM_){return append(next, seq2, _aM_);}];
   }
   function map(f, seq, param){
    var match = caml_call1(seq, 0);
    if(! match) return 0;
    var next = match[2], x = match[1];
    function _aK_(_aL_){return map(f, next, _aL_);}
    return [0, caml_call1(f, x), _aK_];
   }
   function filter_map(f, seq, param){
    var seq$0 = seq;
    for(;;){
     var match = caml_call1(seq$0, 0);
     if(! match) return 0;
     var next = match[2], x = match[1], match$0 = caml_call1(f, x);
     if(match$0){
      var y = match$0[1];
      return [0, y, function(_aJ_){return filter_map(f, next, _aJ_);}];
     }
     var seq$0 = next;
    }
   }
   function filter(f, seq, param){
    var seq$0 = seq;
    for(;;){
     var match = caml_call1(seq$0, 0);
     if(! match) return 0;
     var next = match[2], x = match[1];
     if(caml_call1(f, x))
      return [0, x, function(_aI_){return filter(f, next, _aI_);}];
     var seq$0 = next;
    }
   }
   function concat(seq, param){
    var match = caml_call1(seq, 0);
    if(! match) return 0;
    var next = match[2], x = match[1], _aG_ = 0;
    return append(x, function(_aH_){return concat(next, _aH_);}, _aG_);
   }
   function flat_map(f, seq, param){
    var match = caml_call1(seq, 0);
    if(! match) return 0;
    var next = match[2], x = match[1], _aD_ = 0;
    function _aE_(_aF_){return flat_map(f, next, _aF_);}
    return append(caml_call1(f, x), _aE_, _aD_);
   }
   function fold_left(f, acc, seq){
    var acc$0 = acc, seq$0 = seq;
    for(;;){
     var match = caml_call1(seq$0, 0);
     if(! match) return acc$0;
     var
      next = match[2],
      x = match[1],
      acc$1 = caml_call2(f, acc$0, x),
      acc$0 = acc$1,
      seq$0 = next;
    }
   }
   function iter(f, seq){
    var seq$0 = seq;
    for(;;){
     var match = caml_call1(seq$0, 0);
     if(! match) return 0;
     var next = match[2], x = match[1];
     caml_call1(f, x);
     var seq$0 = next;
    }
   }
   function unfold(f, u, param){
    var match = caml_call1(f, u);
    if(! match) return 0;
    var match$0 = match[1], u$0 = match$0[2], x = match$0[1];
    return [0, x, function(_aC_){return unfold(f, u$0, _aC_);}];
   }
   function is_empty(xs){return caml_call1(xs, 0) ? 0 : 1;}
   function uncons(xs){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1];
    return [0, [0, x, xs$0]];
   }
   function length(xs$1){
    var accu = 0, xs = xs$1;
    for(;;){
     var match = caml_call1(xs, 0);
     if(! match) return accu;
     var xs$0 = match[2], accu$0 = accu + 1 | 0, accu = accu$0, xs = xs$0;
    }
   }
   function iteri(f, xs$1){
    var i = 0, xs = xs$1;
    for(;;){
     var match = caml_call1(xs, 0);
     if(! match) return 0;
     var xs$0 = match[2], x = match[1];
     caml_call2(f, i, x);
     var i$0 = i + 1 | 0, i = i$0, xs = xs$0;
    }
   }
   function fold_lefti(f, accu$1, xs$1){
    var accu = accu$1, i = 0, xs = xs$1;
    for(;;){
     var match = caml_call1(xs, 0);
     if(! match) return accu;
     var
      xs$0 = match[2],
      x = match[1],
      accu$0 = caml_call3(f, accu, i, x),
      i$0 = i + 1 | 0,
      accu = accu$0,
      i = i$0,
      xs = xs$0;
    }
   }
   function for_all(p, xs){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 1;
     var xs$1 = match[2], x = match[1], _aB_ = caml_call1(p, x);
     if(! _aB_) return _aB_;
     var xs$0 = xs$1;
    }
   }
   function exists(p, xs){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], _aA_ = caml_call1(p, x);
     if(_aA_) return _aA_;
     var xs$0 = xs$1;
    }
   }
   function find(p, xs){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1];
     if(caml_call1(p, x)) return [0, x];
     var xs$0 = xs$1;
    }
   }
   function find_map(f, xs){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], result = caml_call1(f, x);
     if(result) return result;
     var xs$0 = xs$1;
    }
   }
   function iter2(f, xs, ys){
    var xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(ys$0, 0);
     if(! match$0) return 0;
     var ys$1 = match$0[2], y = match$0[1];
     caml_call2(f, x, y);
     var xs$0 = xs$1, ys$0 = ys$1;
    }
   }
   function fold_left2(f, accu, xs, ys){
    var accu$0 = accu, xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return accu$0;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(ys$0, 0);
     if(! match$0) return accu$0;
     var
      ys$1 = match$0[2],
      y = match$0[1],
      accu$1 = caml_call3(f, accu$0, x, y),
      accu$0 = accu$1,
      xs$0 = xs$1,
      ys$0 = ys$1;
    }
   }
   function for_all2(f, xs, ys){
    var xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 1;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(ys$0, 0);
     if(! match$0) return 1;
     var ys$1 = match$0[2], y = match$0[1], _az_ = caml_call2(f, x, y);
     if(! _az_) return _az_;
     var xs$0 = xs$1, ys$0 = ys$1;
    }
   }
   function exists2(f, xs, ys){
    var xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(ys$0, 0);
     if(! match$0) return 0;
     var ys$1 = match$0[2], y = match$0[1], _ay_ = caml_call2(f, x, y);
     if(_ay_) return _ay_;
     var xs$0 = xs$1, ys$0 = ys$1;
    }
   }
   function equal(eq, xs, ys){
    var xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0), match$0 = caml_call1(ys$0, 0);
     if(match){
      if(match$0){
       var
        ys$1 = match$0[2],
        y = match$0[1],
        xs$1 = match[2],
        x = match[1],
        _ax_ = caml_call2(eq, x, y);
       if(! _ax_) return _ax_;
       var xs$0 = xs$1, ys$0 = ys$1;
       continue;
      }
     }
     else if(! match$0) return 1;
     return 0;
    }
   }
   function compare(cmp, xs, ys){
    var xs$0 = xs, ys$0 = ys;
    for(;;){
     var match = caml_call1(xs$0, 0), match$0 = caml_call1(ys$0, 0);
     if(! match) return match$0 ? -1 : 0;
     var xs$1 = match[2], x = match[1];
     if(! match$0) return 1;
     var ys$1 = match$0[2], y = match$0[1], c = caml_call2(cmp, x, y);
     if(0 !== c) return c;
     var xs$0 = xs$1, ys$0 = ys$1;
    }
   }
   function init_aux(f, i, j, param){
    if(i >= j) return 0;
    var _au_ = i + 1 | 0;
    function _av_(_aw_){return init_aux(f, _au_, j, _aw_);}
    return [0, caml_call1(f, i), _av_];
   }
   function init(n, f){
    if(0 > n) return caml_call1(Stdlib[1], cst_Seq_init);
    var _as_ = 0;
    return function(_at_){return init_aux(f, _as_, n, _at_);};
   }
   function repeat(x, param){
    return [0, x, function(_ar_){return repeat(x, _ar_);}];
   }
   function forever(f, param){
    function _ap_(_aq_){return forever(f, _aq_);}
    return [0, caml_call1(f, 0), _ap_];
   }
   function cycle_nonempty(xs, param){
    var _an_ = 0;
    return append(xs, function(_ao_){return cycle_nonempty(xs, _ao_);}, _an_);
   }
   function cycle(xs, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1];
    function _ak_(_am_){return cycle_nonempty(xs, _am_);}
    return [0, x, function(_al_){return append(xs$0, _ak_, _al_);}];
   }
   function iterate1(f, x, param){
    var y = caml_call1(f, x);
    return [0, y, function(_aj_){return iterate1(f, y, _aj_);}];
   }
   function iterate(f, x){
    function _ag_(_ai_){return iterate1(f, x, _ai_);}
    return function(_ah_){return [0, x, _ag_];};
   }
   function mapi_aux(f, i, xs, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1], _ad_ = i + 1 | 0;
    function _ae_(_af_){return mapi_aux(f, _ad_, xs$0, _af_);}
    return [0, caml_call2(f, i, x), _ae_];
   }
   function mapi(f, xs){
    var _ab_ = 0;
    return function(_ac_){return mapi_aux(f, _ab_, xs, _ac_);};
   }
   function tail_scan(f, s, xs, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1], s$0 = caml_call2(f, s, x);
    return [0, s$0, function(_aa_){return tail_scan(f, s$0, xs$0, _aa_);}];
   }
   function scan(f, s, xs){
    function _Z_(_$_){return tail_scan(f, s, xs, _$_);}
    return function(___){return [0, s, _Z_];};
   }
   function take_aux(n, xs){
    return 0 === n
            ? empty
            : function
             (param){
              var match = caml_call1(xs, 0);
              if(! match) return 0;
              var xs$0 = match[2], x = match[1];
              return [0, x, take_aux(n - 1 | 0, xs$0)];
             };
   }
   function take(n, xs){
    if(n < 0) caml_call1(Stdlib[1], cst_Seq_take);
    return take_aux(n, xs);
   }
   function drop(n, xs){
    return 0 <= n
            ? 0
              === n
              ? xs
              : function
               (param){
                var n$0 = n, xs$0 = xs;
                for(;;){
                 var match = caml_call1(xs$0, 0);
                 if(! match) return 0;
                 var xs$1 = match[2], n$1 = n$0 - 1 | 0;
                 if(0 === n$1) return caml_call1(xs$1, 0);
                 var n$0 = n$1, xs$0 = xs$1;
                }
               }
            : caml_call1(Stdlib[1], cst_Seq_drop);
   }
   function take_while(p, xs, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1];
    return caml_call1(p, x)
            ? [0, x, function(_Y_){return take_while(p, xs$0, _Y_);}]
            : 0;
   }
   function drop_while(p, xs, param){
    var xs$0 = xs;
    for(;;){
     var node = caml_call1(xs$0, 0);
     if(! node) return 0;
     var xs$1 = node[2], x = node[1];
     if(! caml_call1(p, x)) return node;
     var xs$0 = xs$1;
    }
   }
   function group(eq, xs, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1], _P_ = caml_call1(eq, x);
    function _Q_(_X_){return drop_while(_P_, xs$0, _X_);}
    function _R_(_W_){return group(eq, _Q_, _W_);}
    var _S_ = caml_call1(eq, x);
    function _T_(_V_){return take_while(_S_, xs$0, _V_);}
    return [0, function(_U_){return [0, x, _T_];}, _R_];
   }
   var
    Forced_twice =
      [248, cst_Stdlib_Seq_Forced_twice, runtime.caml_fresh_oo_id(0)],
    to_lazy = Stdlib_Lazy[6];
   function failure(param){
    throw caml_maybe_attach_backtrace(Forced_twice, 1);
   }
   function memoize(xs){
    function s$0(param){
     var match = caml_call1(xs, 0);
     if(! match) return 0;
     var xs$0 = match[2], x = match[1];
     return [0, x, memoize(xs$0)];
    }
    var s = caml_call1(to_lazy, s$0);
    return function(_O_){
     var _N_ = runtime.caml_obj_tag(s);
     return 250 === _N_
             ? s[1]
             : 246 === _N_ ? caml_call1(CamlinternalLazy[2], s) : s;};
   }
   function once(xs){
    function f(param){
     var match = caml_call1(xs, 0);
     if(! match) return 0;
     var xs$0 = match[2], x = match[1];
     return [0, x, once(xs$0)];
    }
    var action = caml_call1(CamlinternalAtomic[1], f);
    return function(param){
     var f = caml_call2(CamlinternalAtomic[4], action, failure);
     return caml_call1(f, 0);};
   }
   function zip(xs, ys, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1], match$0 = caml_call1(ys, 0);
    if(! match$0) return 0;
    var ys$0 = match$0[2], y = match$0[1];
    return [0, [0, x, y], function(_M_){return zip(xs$0, ys$0, _M_);}];
   }
   function map2(f, xs, ys, param){
    var match = caml_call1(xs, 0);
    if(! match) return 0;
    var xs$0 = match[2], x = match[1], match$0 = caml_call1(ys, 0);
    if(! match$0) return 0;
    var ys$0 = match$0[2], y = match$0[1];
    function _K_(_L_){return map2(f, xs$0, ys$0, _L_);}
    return [0, caml_call2(f, x, y), _K_];
   }
   function interleave(xs, ys, param){
    var match = caml_call1(xs, 0);
    if(! match) return caml_call1(ys, 0);
    var xs$0 = match[2], x = match[1];
    return [0, x, function(_J_){return interleave(ys, xs$0, _J_);}];
   }
   function sorted_merge1(cmp, x, xs, y, ys){
    return 0 < caml_call2(cmp, x, y)
            ? [0,
              y,
              function(_H_){
               var match = caml_call1(ys, 0);
               if(! match) return [0, x, xs];
               var ys$0 = match[2], y = match[1];
               return sorted_merge1(cmp, x, xs, y, ys$0);
              }]
            : [0,
              x,
              function(_I_){
               var match = caml_call1(xs, 0);
               if(! match) return [0, y, ys];
               var xs$0 = match[2], x = match[1];
               return sorted_merge1(cmp, x, xs$0, y, ys);
              }];
   }
   function sorted_merge(cmp, xs, ys, param){
    var match = caml_call1(xs, 0), match$0 = caml_call1(ys, 0);
    if(match){
     if(match$0){
      var ys$0 = match$0[2], y = match$0[1], xs$0 = match[2], x = match[1];
      return sorted_merge1(cmp, x, xs$0, y, ys$0);
     }
     var c = match;
    }
    else{if(! match$0) return 0; var c = match$0;}
    return c;
   }
   function map_fst(xys, param){
    var match = caml_call1(xys, 0);
    if(! match) return 0;
    var xys$0 = match[2], x = match[1][1];
    return [0, x, function(_G_){return map_fst(xys$0, _G_);}];
   }
   function map_snd(xys, param){
    var match = caml_call1(xys, 0);
    if(! match) return 0;
    var xys$0 = match[2], y = match[1][2];
    return [0, y, function(_F_){return map_snd(xys$0, _F_);}];
   }
   function unzip(xys){
    function _C_(_E_){return map_snd(xys, _E_);}
    return [0, function(_D_){return map_fst(xys, _D_);}, _C_];
   }
   function filter_map_find_left_map(f, xs, param){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(f, x);
     if(0 === match$0[0]){
      var y = match$0[1];
      return [0,
              y,
              function(_B_){return filter_map_find_left_map(f, xs$1, _B_);}];
     }
     var xs$0 = xs$1;
    }
   }
   function filter_map_find_right_map(f, xs, param){
    var xs$0 = xs;
    for(;;){
     var match = caml_call1(xs$0, 0);
     if(! match) return 0;
     var xs$1 = match[2], x = match[1], match$0 = caml_call1(f, x);
     if(0 === match$0[0]){var xs$0 = xs$1; continue;}
     var z = match$0[1];
     return [0,
             z,
             function(_A_){return filter_map_find_right_map(f, xs$1, _A_);}];
    }
   }
   function partition_map(f, xs){
    function _x_(_z_){return filter_map_find_right_map(f, xs, _z_);}
    return [0,
            function(_y_){return filter_map_find_left_map(f, xs, _y_);},
            _x_];
   }
   function partition(p, xs){
    function _t_(x){return 1 - caml_call1(p, x);}
    function _u_(_w_){return filter(_t_, xs, _w_);}
    return [0, function(_v_){return filter(p, xs, _v_);}, _u_];
   }
   function peel(xss){
    return unzip(function(_s_){return filter_map(uncons, xss, _s_);});
   }
   function transpose(xss, param){
    var match = peel(xss), tails = match[2], heads = match[1];
    if(! is_empty(heads))
     return [0, heads, function(_r_){return transpose(tails, _r_);}];
    if(is_empty(tails)) return 0;
    throw caml_maybe_attach_backtrace([0, Assert_failure, _a_], 1);
   }
   function _b_(remainders, xss, param){
    var match = caml_call1(xss, 0);
    if(! match) return transpose(remainders, 0);
    var xss$0 = match[2], xs = match[1], match$0 = caml_call1(xs, 0);
    if(match$0){
     var
      xs$0 = match$0[2],
      x = match$0[1],
      match$1 = peel(remainders),
      tails = match$1[2],
      heads = match$1[1],
      _l_ = function(_q_){return [0, xs$0, tails];},
      _m_ = function(_p_){return _b_(_l_, xss$0, _p_);};
     return [0, function(_o_){return [0, x, heads];}, _m_];
    }
    var
     match$2 = peel(remainders),
     tails$0 = match$2[2],
     heads$0 = match$2[1];
    return [0, heads$0, function(_n_){return _b_(tails$0, xss$0, _n_);}];
   }
   function map_product(f, xs, ys){
    function _f_(x){
     function _j_(y){return caml_call2(f, x, y);}
     return function(_k_){return map(_j_, ys, _k_);};
    }
    function xss(_i_){return map(_f_, xs, _i_);}
    function _e_(_h_){return _b_(empty, xss, _h_);}
    return function(_g_){return concat(_e_, _g_);};
   }
   function product(xs, ys){
    return map_product(function(x, y){return [0, x, y];}, xs, ys);
   }
   function of_dispenser(it){
    function c(param){
     var match = caml_call1(it, 0);
     if(! match) return 0;
     var x = match[1];
     return [0, x, c];
    }
    return c;
   }
   function to_dispenser(xs){
    var s = [0, xs];
    return function(param){
     var match = caml_call1(s[1], 0);
     if(! match) return 0;
     var xs = match[2], x = match[1];
     s[1] = xs;
     return [0, x];};
   }
   function ints(i, param){
    var _c_ = i + 1 | 0;
    return [0, i, function(_d_){return ints(_c_, _d_);}];
   }
   var
    Stdlib_Seq =
      [0,
       is_empty,
       uncons,
       length,
       iter,
       fold_left,
       iteri,
       fold_lefti,
       for_all,
       exists,
       find,
       find_map,
       iter2,
       fold_left2,
       for_all2,
       exists2,
       equal,
       compare,
       empty,
       return$0,
       cons,
       init,
       unfold,
       repeat,
       forever,
       cycle,
       iterate,
       map,
       mapi,
       filter,
       filter_map,
       scan,
       take,
       drop,
       take_while,
       drop_while,
       group,
       memoize,
       Forced_twice,
       once,
       transpose,
       append,
       concat,
       flat_map,
       flat_map,
       zip,
       map2,
       interleave,
       sorted_merge,
       product,
       map_product,
       unzip,
       unzip,
       partition_map,
       partition,
       of_dispenser,
       to_dispenser,
       ints];
   runtime.caml_register_global(10, Stdlib_Seq, "Stdlib__Seq");
   return;
  }
  (globalThis));

//# 2119 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var runtime = globalThis.jsoo_runtime;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Stdlib_Seq = global_data.Stdlib__Seq,
    Stdlib = global_data.Stdlib,
    cst_option_is_None = "option is None",
    none = 0;
   function some(v){return [0, v];}
   function value(o, default$0){
    if(! o) return default$0;
    var v = o[1];
    return v;
   }
   function get(param){
    if(! param) return caml_call1(Stdlib[1], cst_option_is_None);
    var v = param[1];
    return v;
   }
   function bind(o, f){
    if(! o) return 0;
    var v = o[1];
    return caml_call1(f, v);
   }
   function join(param){if(! param) return 0; var o = param[1]; return o;}
   function map(f, o){
    if(! o) return 0;
    var v = o[1];
    return [0, caml_call1(f, v)];
   }
   function fold(none, some, param){
    if(! param) return none;
    var v = param[1];
    return caml_call1(some, v);
   }
   function iter(f, param){
    if(! param) return 0;
    var v = param[1];
    return caml_call1(f, v);
   }
   function is_none(param){return param ? 0 : 1;}
   function is_some(param){return param ? 1 : 0;}
   function equal(eq, o0, o1){
    if(o0){
     if(o1){var v1 = o1[1], v0 = o0[1]; return caml_call2(eq, v0, v1);}
    }
    else if(! o1) return 1;
    return 0;
   }
   function compare(cmp, o0, o1){
    if(! o0) return o1 ? -1 : 0;
    var v0 = o0[1];
    if(! o1) return 1;
    var v1 = o1[1];
    return caml_call2(cmp, v0, v1);
   }
   function to_result(none, param){
    if(! param) return [1, none];
    var v = param[1];
    return [0, v];
   }
   function to_list(param){
    if(! param) return 0;
    var v = param[1];
    return [0, v, 0];
   }
   function to_seq(param){
    if(! param) return Stdlib_Seq[18];
    var v = param[1];
    return caml_call1(Stdlib_Seq[19], v);
   }
   var
    Stdlib_Option =
      [0,
       none,
       some,
       value,
       get,
       bind,
       join,
       map,
       fold,
       iter,
       is_none,
       is_some,
       equal,
       compare,
       to_result,
       to_list,
       to_seq];
   runtime.caml_register_global(3, Stdlib_Option, "Stdlib__Option");
   return;
  }
  (globalThis));

//# 2391 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    caml_bytes_unsafe_set = runtime.caml_bytes_unsafe_set,
    caml_create_bytes = runtime.caml_create_bytes,
    caml_string_of_bytes = runtime.caml_string_of_bytes;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    cst = "\\\\",
    cst$0 = "\\'",
    Stdlib = global_data.Stdlib,
    cst_b = "\\b",
    cst_t = "\\t",
    cst_n = "\\n",
    cst_r = "\\r",
    cst_Char_chr = "Char.chr";
   function chr(n){
    if(0 <= n && 255 >= n) return n;
    return caml_call1(Stdlib[1], cst_Char_chr);
   }
   function escaped(c){
    var switch$0 = 0;
    if(40 <= c){
     if(92 === c) return cst;
     if(127 > c) switch$0 = 1;
    }
    else if(32 <= c){
     if(39 <= c) return cst$0;
     switch$0 = 1;
    }
    else if(14 > c)
     switch(c){
       case 8:
        return cst_b;
       case 9:
        return cst_t;
       case 10:
        return cst_n;
       case 13:
        return cst_r;
     }
    if(switch$0){
     var s$0 = caml_create_bytes(1);
     caml_bytes_unsafe_set(s$0, 0, c);
     return caml_string_of_bytes(s$0);
    }
    var s = caml_create_bytes(4);
    caml_bytes_unsafe_set(s, 0, 92);
    caml_bytes_unsafe_set(s, 1, 48 + (c / 100 | 0) | 0);
    caml_bytes_unsafe_set(s, 2, 48 + ((c / 10 | 0) % 10 | 0) | 0);
    caml_bytes_unsafe_set(s, 3, 48 + (c % 10 | 0) | 0);
    return caml_string_of_bytes(s);
   }
   function lowercase(c){
    var _b_ = c - 192 | 0, switch$0 = 0;
    if(30 < _b_ >>> 0){
     if(25 >= _b_ + 127 >>> 0) switch$0 = 1;
    }
    else if(23 !== _b_) switch$0 = 1;
    return switch$0 ? c + 32 | 0 : c;
   }
   function uppercase(c){
    var _a_ = c - 224 | 0, switch$0 = 0;
    if(30 < _a_ >>> 0){
     if(25 >= _a_ + 127 >>> 0) switch$0 = 1;
    }
    else if(23 !== _a_) switch$0 = 1;
    return switch$0 ? c - 32 | 0 : c;
   }
   function lowercase_ascii(c){return 25 < c - 65 >>> 0 ? c : c + 32 | 0;}
   function uppercase_ascii(c){return 25 < c - 97 >>> 0 ? c : c - 32 | 0;}
   function compare(c1, c2){return c1 - c2 | 0;}
   function equal(c1, c2){return 0 === (c1 - c2 | 0) ? 1 : 0;}
   var
    Stdlib_Char =
      [0,
       chr,
       escaped,
       lowercase,
       uppercase,
       lowercase_ascii,
       uppercase_ascii,
       compare,
       equal];
   runtime.caml_register_global(8, Stdlib_Char, "Stdlib__Char");
   return;
  }
  (globalThis));

//# 2489 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst_uchar_ml = "uchar.ml",
    caml_format_int = runtime.caml_format_int,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    err_no_pred = "U+0000 has no predecessor",
    err_no_succ = "U+10FFFF has no successor",
    Assert_failure = global_data.Assert_failure,
    Stdlib = global_data.Stdlib,
    _d_ = [0, cst_uchar_ml, 88, 18],
    _c_ = [0, cst_uchar_ml, 91, 7],
    _b_ = [0, cst_uchar_ml, 80, 18],
    _a_ = [0, cst_uchar_ml, 85, 7],
    cst_is_not_a_latin1_character = " is not a latin1 character",
    cst_U = "U+",
    cst_is_not_an_Unicode_scalar_v = " is not an Unicode scalar value",
    min = 0,
    max = 1114111,
    lo_bound = 55295,
    hi_bound = 57344,
    bom = 65279,
    rep = 65533;
   function succ(u){
    return u === 55295
            ? hi_bound
            : u === 1114111 ? caml_call1(Stdlib[1], err_no_succ) : u + 1 | 0;
   }
   function pred(u){
    return u === 57344
            ? lo_bound
            : u === 0 ? caml_call1(Stdlib[1], err_no_pred) : u - 1 | 0;
   }
   function is_valid(i){
    var _o_ = 0 <= i ? 1 : 0, _p_ = _o_ ? i <= 55295 ? 1 : 0 : _o_;
    if(_p_)
     var _q_ = _p_;
    else
     var _r_ = 57344 <= i ? 1 : 0, _q_ = _r_ ? i <= 1114111 ? 1 : 0 : _r_;
    return _q_;
   }
   function of_int(i){
    if(is_valid(i)) return i;
    var
     _n_ =
       caml_call2
        (Stdlib[28], caml_format_int("%X", i), cst_is_not_an_Unicode_scalar_v);
    return caml_call1(Stdlib[1], _n_);
   }
   function is_char(u){return u < 256 ? 1 : 0;}
   function of_char(c){return c;}
   function to_char(u){
    if(255 >= u) return u;
    var
     _l_ =
       caml_call2
        (Stdlib[28],
         caml_format_int("%04X", u),
         cst_is_not_a_latin1_character),
     _m_ = caml_call2(Stdlib[28], cst_U, _l_);
    return caml_call1(Stdlib[1], _m_);
   }
   function unsafe_to_char(_k_){return _k_;}
   function equal(_j_, _i_){return _j_ === _i_ ? 1 : 0;}
   var compare = runtime.caml_int_compare;
   function hash(_h_){return _h_;}
   function utf_decode_is_valid(d){return 1 === (d >>> 27 | 0) ? 1 : 0;}
   function utf_decode_length(d){return (d >>> 24 | 0) & 7;}
   function utf_decode_uchar(d){return d & 16777215;}
   function utf_decode(n, u){return (8 | n) << 24 | u;}
   function utf_decode_invalid(n){return n << 24 | 65533;}
   function utf_8_byte_length(u){
    if(0 > u) throw caml_maybe_attach_backtrace([0, Assert_failure, _b_], 1);
    if(127 >= u) return 1;
    if(2047 >= u) return 2;
    if(65535 >= u) return 3;
    if(1114111 < u)
     throw caml_maybe_attach_backtrace([0, Assert_failure, _a_], 1);
    return 4;
   }
   function utf_16_byte_length(u){
    if(0 > u) throw caml_maybe_attach_backtrace([0, Assert_failure, _d_], 1);
    if(65535 >= u) return 2;
    if(1114111 < u)
     throw caml_maybe_attach_backtrace([0, Assert_failure, _c_], 1);
    return 4;
   }
   function _e_(_g_){return _g_;}
   var
    Stdlib_Uchar =
      [0,
       min,
       max,
       bom,
       rep,
       succ,
       pred,
       is_valid,
       of_int,
       function(_f_){return _f_;},
       _e_,
       is_char,
       of_char,
       to_char,
       unsafe_to_char,
       equal,
       compare,
       hash,
       utf_decode_is_valid,
       utf_decode_uchar,
       utf_decode_length,
       utf_decode,
       utf_decode_invalid,
       utf_8_byte_length,
       utf_16_byte_length];
   runtime.caml_register_global(13, Stdlib_Uchar, "Stdlib__Uchar");
   return;
  }
  (globalThis));

//# 2625 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst_List_nth$1 = "List.nth",
    caml_compare = runtime.caml_compare,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   function caml_call3(f, a0, a1, a2){
    return (f.l >= 0 ? f.l : f.l = f.length) == 3
            ? f(a0, a1, a2)
            : runtime.caml_call_gen(f, [a0, a1, a2]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Stdlib = global_data.Stdlib,
    Stdlib_Seq = global_data.Stdlib__Seq,
    Stdlib_Sys = global_data.Stdlib__Sys,
    cst_List_map2 = "List.map2",
    cst_List_iter2 = "List.iter2",
    cst_List_fold_left2 = "List.fold_left2",
    cst_List_fold_right2 = "List.fold_right2",
    cst_List_for_all2 = "List.for_all2",
    cst_List_exists2 = "List.exists2",
    _b_ = [0, 0, 0],
    cst_List_combine = "List.combine",
    cst_List_rev_map2 = "List.rev_map2",
    cst_List_init = "List.init",
    cst_List_nth$0 = cst_List_nth$1,
    cst_nth = "nth",
    cst_List_nth = cst_List_nth$1,
    cst_tl = "tl",
    cst_hd = "hd";
   function length(l$0){
    var len = 0, param = l$0;
    for(;;){
     if(! param) return len;
     var l = param[2], len$0 = len + 1 | 0, len = len$0, param = l;
    }
   }
   function cons(a, l){return [0, a, l];}
   function hd(param){
    if(! param) return caml_call1(Stdlib[2], cst_hd);
    var a = param[1];
    return a;
   }
   function tl(param){
    if(! param) return caml_call1(Stdlib[2], cst_tl);
    var l = param[2];
    return l;
   }
   function nth(l, n){
    if(0 > n) return caml_call1(Stdlib[1], cst_List_nth);
    var l$0 = l, n$0 = n;
    for(;;){
     if(! l$0) return caml_call1(Stdlib[2], cst_nth);
     var l$1 = l$0[2], a = l$0[1];
     if(0 === n$0) return a;
     var n$1 = n$0 - 1 | 0, l$0 = l$1, n$0 = n$1;
    }
   }
   function nth_opt(l, n){
    if(0 > n) return caml_call1(Stdlib[1], cst_List_nth$0);
    var l$0 = l, n$0 = n;
    for(;;){
     if(! l$0) return 0;
     var l$1 = l$0[2], a = l$0[1];
     if(0 === n$0) return [0, a];
     var n$1 = n$0 - 1 | 0, l$0 = l$1, n$0 = n$1;
    }
   }
   var append = Stdlib[37];
   function rev_append(l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(! l1$0) return l2$0;
     var
      l1$1 = l1$0[2],
      a = l1$0[1],
      l2$1 = [0, a, l2$0],
      l1$0 = l1$1,
      l2$0 = l2$1;
    }
   }
   function rev(l){return rev_append(l, 0);}
   function init_aux(i, n, f){
    if(n <= i) return 0;
    var r = caml_call1(f, i);
    return [0, r, init_aux(i + 1 | 0, n, f)];
   }
   var rev_init_threshold = typeof Stdlib_Sys[5] === "number" ? 10000 : 50;
   function init(len, f){
    if(0 > len) return caml_call1(Stdlib[1], cst_List_init);
    if(rev_init_threshold >= len) return init_aux(0, len, f);
    var acc = 0, i = 0;
    for(;;){
     if(len <= i) return rev(acc);
     var
      i$0 = i + 1 | 0,
      acc$0 = [0, caml_call1(f, i), acc],
      acc = acc$0,
      i = i$0;
    }
   }
   function flatten(param){
    if(! param) return 0;
    var r = param[2], l = param[1], _J_ = flatten(r);
    return caml_call2(Stdlib[37], l, _J_);
   }
   function map(f, param){
    if(! param) return 0;
    var l = param[2], a = param[1], r = caml_call1(f, a);
    return [0, r, map(f, l)];
   }
   function _a_(i, f, param){
    if(! param) return 0;
    var l = param[2], a = param[1], r = caml_call2(f, i, a);
    return [0, r, _a_(i + 1 | 0, f, l)];
   }
   function mapi(f, l){return _a_(0, f, l);}
   function rev_map(f, l){
    var accu = 0, param = l;
    for(;;){
     if(! param) return accu;
     var
      l$0 = param[2],
      a = param[1],
      accu$0 = [0, caml_call1(f, a), accu],
      accu = accu$0,
      param = l$0;
    }
   }
   function iter(f, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], a = param$0[1];
     caml_call1(f, a);
     var param$0 = l;
    }
   }
   function iteri(f, l$0){
    var i = 0, param = l$0;
    for(;;){
     if(! param) return 0;
     var l = param[2], a = param[1];
     caml_call2(f, i, a);
     var i$0 = i + 1 | 0, i = i$0, param = l;
    }
   }
   function fold_left(f, accu, l){
    var accu$0 = accu, l$0 = l;
    for(;;){
     if(! l$0) return accu$0;
     var
      l$1 = l$0[2],
      a = l$0[1],
      accu$1 = caml_call2(f, accu$0, a),
      accu$0 = accu$1,
      l$0 = l$1;
    }
   }
   function fold_right(f, l, accu){
    if(! l) return accu;
    var l$0 = l[2], a = l[1];
    return caml_call2(f, a, fold_right(f, l$0, accu));
   }
   function map2(f, l1, l2){
    if(l1){
     if(l2){
      var
       l2$0 = l2[2],
       a2 = l2[1],
       l1$0 = l1[2],
       a1 = l1[1],
       r = caml_call2(f, a1, a2);
      return [0, r, map2(f, l1$0, l2$0)];
     }
    }
    else if(! l2) return 0;
    return caml_call1(Stdlib[1], cst_List_map2);
   }
   function rev_map2(f, l1, l2){
    var accu = 0, l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var
        l2$1 = l2$0[2],
        a2 = l2$0[1],
        l1$1 = l1$0[2],
        a1 = l1$0[1],
        accu$0 = [0, caml_call2(f, a1, a2), accu],
        accu = accu$0,
        l1$0 = l1$1,
        l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return accu;
     return caml_call1(Stdlib[1], cst_List_rev_map2);
    }
   }
   function iter2(f, l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var l2$1 = l2$0[2], a2 = l2$0[1], l1$1 = l1$0[2], a1 = l1$0[1];
       caml_call2(f, a1, a2);
       var l1$0 = l1$1, l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return 0;
     return caml_call1(Stdlib[1], cst_List_iter2);
    }
   }
   function fold_left2(f, accu, l1, l2){
    var accu$0 = accu, l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var
        l2$1 = l2$0[2],
        a2 = l2$0[1],
        l1$1 = l1$0[2],
        a1 = l1$0[1],
        accu$1 = caml_call3(f, accu$0, a1, a2),
        accu$0 = accu$1,
        l1$0 = l1$1,
        l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return accu$0;
     return caml_call1(Stdlib[1], cst_List_fold_left2);
    }
   }
   function fold_right2(f, l1, l2, accu){
    if(l1){
     if(l2){
      var l2$0 = l2[2], a2 = l2[1], l1$0 = l1[2], a1 = l1[1];
      return caml_call3(f, a1, a2, fold_right2(f, l1$0, l2$0, accu));
     }
    }
    else if(! l2) return accu;
    return caml_call1(Stdlib[1], cst_List_fold_right2);
   }
   function for_all(p, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 1;
     var l = param$0[2], a = param$0[1], _I_ = caml_call1(p, a);
     if(! _I_) return _I_;
     var param$0 = l;
    }
   }
   function exists(p, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], a = param$0[1], _H_ = caml_call1(p, a);
     if(_H_) return _H_;
     var param$0 = l;
    }
   }
   function for_all2(p, l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var
        l2$1 = l2$0[2],
        a2 = l2$0[1],
        l1$1 = l1$0[2],
        a1 = l1$0[1],
        _G_ = caml_call2(p, a1, a2);
       if(! _G_) return _G_;
       var l1$0 = l1$1, l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return 1;
     return caml_call1(Stdlib[1], cst_List_for_all2);
    }
   }
   function exists2(p, l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var
        l2$1 = l2$0[2],
        a2 = l2$0[1],
        l1$1 = l1$0[2],
        a1 = l1$0[1],
        _F_ = caml_call2(p, a1, a2);
       if(_F_) return _F_;
       var l1$0 = l1$1, l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return 0;
     return caml_call1(Stdlib[1], cst_List_exists2);
    }
   }
   function mem(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var
      l = param$0[2],
      a = param$0[1],
      _E_ = 0 === caml_compare(a, x) ? 1 : 0;
     if(_E_) return _E_;
     var param$0 = l;
    }
   }
   function memq(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], a = param$0[1], _D_ = a === x ? 1 : 0;
     if(_D_) return _D_;
     var param$0 = l;
    }
   }
   function assoc(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     var l = param$0[2], match = param$0[1], b = match[2], a = match[1];
     if(0 === caml_compare(a, x)) return b;
     var param$0 = l;
    }
   }
   function assoc_opt(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], match = param$0[1], b = match[2], a = match[1];
     if(0 === caml_compare(a, x)) return [0, b];
     var param$0 = l;
    }
   }
   function assq(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     var l = param$0[2], match = param$0[1], b = match[2], a = match[1];
     if(a === x) return b;
     var param$0 = l;
    }
   }
   function assq_opt(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], match = param$0[1], b = match[2], a = match[1];
     if(a === x) return [0, b];
     var param$0 = l;
    }
   }
   function mem_assoc(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var
      l = param$0[2],
      a = param$0[1][1],
      _C_ = 0 === caml_compare(a, x) ? 1 : 0;
     if(_C_) return _C_;
     var param$0 = l;
    }
   }
   function mem_assq(x, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], a = param$0[1][1], _B_ = a === x ? 1 : 0;
     if(_B_) return _B_;
     var param$0 = l;
    }
   }
   function remove_assoc(x, param){
    if(! param) return 0;
    var l = param[2], pair = param[1], a = pair[1];
    return 0 === caml_compare(a, x) ? l : [0, pair, remove_assoc(x, l)];
   }
   function remove_assq(x, param){
    if(! param) return 0;
    var l = param[2], pair = param[1], a = pair[1];
    return a === x ? l : [0, pair, remove_assq(x, l)];
   }
   function find(p, param){
    var param$0 = param;
    for(;;){
     if(! param$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     var l = param$0[2], x = param$0[1];
     if(caml_call1(p, x)) return x;
     var param$0 = l;
    }
   }
   function find_opt(p, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], x = param$0[1];
     if(caml_call1(p, x)) return [0, x];
     var param$0 = l;
    }
   }
   function find_map(f, param){
    var param$0 = param;
    for(;;){
     if(! param$0) return 0;
     var l = param$0[2], x = param$0[1], result = caml_call1(f, x);
     if(result) return result;
     var param$0 = l;
    }
   }
   function find_all(p){
    var accu = 0;
    return function(param$0){
     var accu$0 = accu, param = param$0;
     for(;;){
      if(! param) return rev(accu$0);
      var l = param[2], x = param[1];
      if(caml_call1(p, x)){
       var accu$1 = [0, x, accu$0], accu$0 = accu$1, param = l;
       continue;
      }
      var param = l;
     }};
   }
   function filteri(p, l){
    var i = 0, acc = 0, param = l;
    for(;;){
     if(! param) return rev(acc);
     var
      l$0 = param[2],
      x = param[1],
      acc$0 = caml_call2(p, i, x) ? [0, x, acc] : acc,
      i$0 = i + 1 | 0,
      i = i$0,
      acc = acc$0,
      param = l$0;
    }
   }
   function filter_map(f){
    var accu = 0;
    return function(param$0){
     var accu$0 = accu, param = param$0;
     for(;;){
      if(! param) return rev(accu$0);
      var l = param[2], x = param[1], match = caml_call1(f, x);
      if(match){
       var v = match[1], accu$1 = [0, v, accu$0], accu$0 = accu$1, param = l;
       continue;
      }
      var param = l;
     }};
   }
   function concat_map(f, l){
    var acc = 0, param = l;
    for(;;){
     if(! param) return rev(acc);
     var
      l$0 = param[2],
      x = param[1],
      xs = caml_call1(f, x),
      acc$0 = rev_append(xs, acc),
      acc = acc$0,
      param = l$0;
    }
   }
   function fold_left_map(f, accu, l){
    var accu$0 = accu, l_accu = 0, param = l;
    for(;;){
     if(! param) return [0, accu$0, rev(l_accu)];
     var
      l$0 = param[2],
      x = param[1],
      match = caml_call2(f, accu$0, x),
      x$0 = match[2],
      accu$1 = match[1],
      l_accu$0 = [0, x$0, l_accu],
      accu$0 = accu$1,
      l_accu = l_accu$0,
      param = l$0;
    }
   }
   function partition(p, l){
    var yes = 0, no = 0, param = l;
    for(;;){
     if(! param){var _A_ = rev(no); return [0, rev(yes), _A_];}
     var l$0 = param[2], x = param[1];
     if(caml_call1(p, x)){
      var yes$0 = [0, x, yes], yes = yes$0, param = l$0;
      continue;
     }
     var no$0 = [0, x, no], no = no$0, param = l$0;
    }
   }
   function partition_map(p, l){
    var left = 0, right = 0, param = l;
    for(;;){
     if(! param){var _z_ = rev(right); return [0, rev(left), _z_];}
     var l$0 = param[2], x = param[1], match = caml_call1(p, x);
     if(0 === match[0]){
      var v = match[1], left$0 = [0, v, left], left = left$0, param = l$0;
      continue;
     }
     var
      v$0 = match[1],
      right$0 = [0, v$0, right],
      right = right$0,
      param = l$0;
    }
   }
   function split(param){
    if(! param) return _b_;
    var
     l = param[2],
     match = param[1],
     y = match[2],
     x = match[1],
     match$0 = split(l),
     ry = match$0[2],
     rx = match$0[1];
    return [0, [0, x, rx], [0, y, ry]];
   }
   function combine(l1, l2){
    if(l1){
     if(l2){
      var l2$0 = l2[2], a2 = l2[1], l1$0 = l1[2], a1 = l1[1];
      return [0, [0, a1, a2], combine(l1$0, l2$0)];
     }
    }
    else if(! l2) return 0;
    return caml_call1(Stdlib[1], cst_List_combine);
   }
   function merge(cmp, l1, l2){
    if(! l1) return l2;
    if(! l2) return l1;
    var t2 = l2[2], h2 = l2[1], t1 = l1[2], h1 = l1[1];
    return 0 < caml_call2(cmp, h1, h2)
            ? [0, h2, merge(cmp, l1, t2)]
            : [0, h1, merge(cmp, t1, l2)];
   }
   function stable_sort(cmp, l){
    function sort(n, l){
     if(2 === n){
      if(l){
       var match = l[2];
       if(match){
        var
         tl = match[2],
         x2 = match[1],
         x1 = l[1],
         s =
           0 < caml_call2(cmp, x1, x2)
            ? [0, x2, [0, x1, 0]]
            : [0, x1, [0, x2, 0]];
        return [0, s, tl];
       }
      }
     }
     else if(3 === n && l){
      var _y_ = l[2];
      if(_y_){
       var match$2 = _y_[2];
       if(match$2){
        var
         tl$1 = match$2[2],
         x3 = match$2[1],
         x2$0 = _y_[1],
         x1$0 = l[1],
         s$0 =
           0 < caml_call2(cmp, x1$0, x2$0)
            ? 0
              < caml_call2(cmp, x1$0, x3)
              ? 0
                < caml_call2(cmp, x2$0, x3)
                ? [0, x3, [0, x2$0, [0, x1$0, 0]]]
                : [0, x2$0, [0, x3, [0, x1$0, 0]]]
              : [0, x2$0, [0, x1$0, [0, x3, 0]]]
            : 0
              < caml_call2(cmp, x2$0, x3)
              ? 0
                < caml_call2(cmp, x1$0, x3)
                ? [0, x3, [0, x1$0, [0, x2$0, 0]]]
                : [0, x1$0, [0, x3, [0, x2$0, 0]]]
              : [0, x1$0, [0, x2$0, [0, x3, 0]]];
        return [0, s$0, tl$1];
       }
      }
     }
     var
      n1 = n >> 1,
      n2 = n - n1 | 0,
      match$0 = rev_sort(n1, l),
      l2$0 = match$0[2],
      s1 = match$0[1],
      match$1 = rev_sort(n2, l2$0),
      tl$0 = match$1[2],
      s2 = match$1[1],
      l1 = s1,
      l2 = s2,
      accu = 0;
     for(;;){
      if(l1){
       if(l2){
        var t2 = l2[2], h2 = l2[1], t1 = l1[2], h1 = l1[1];
        if(0 < caml_call2(cmp, h1, h2)){
         var accu$0 = [0, h1, accu], l1 = t1, accu = accu$0;
         continue;
        }
        var accu$1 = [0, h2, accu], l2 = t2, accu = accu$1;
        continue;
       }
       var _x_ = rev_append(l1, accu);
      }
      else
       var _x_ = rev_append(l2, accu);
      return [0, _x_, tl$0];
     }
    }
    function rev_sort(n, l){
     if(2 === n){
      if(l){
       var match = l[2];
       if(match){
        var
         tl = match[2],
         x2 = match[1],
         x1 = l[1],
         s =
           0 < caml_call2(cmp, x1, x2)
            ? [0, x1, [0, x2, 0]]
            : [0, x2, [0, x1, 0]];
        return [0, s, tl];
       }
      }
     }
     else if(3 === n && l){
      var _w_ = l[2];
      if(_w_){
       var match$2 = _w_[2];
       if(match$2){
        var
         tl$1 = match$2[2],
         x3 = match$2[1],
         x2$0 = _w_[1],
         x1$0 = l[1],
         s$0 =
           0 < caml_call2(cmp, x1$0, x2$0)
            ? 0
              < caml_call2(cmp, x2$0, x3)
              ? [0, x1$0, [0, x2$0, [0, x3, 0]]]
              : 0
                < caml_call2(cmp, x1$0, x3)
                ? [0, x1$0, [0, x3, [0, x2$0, 0]]]
                : [0, x3, [0, x1$0, [0, x2$0, 0]]]
            : 0
              < caml_call2(cmp, x1$0, x3)
              ? [0, x2$0, [0, x1$0, [0, x3, 0]]]
              : 0
                < caml_call2(cmp, x2$0, x3)
                ? [0, x2$0, [0, x3, [0, x1$0, 0]]]
                : [0, x3, [0, x2$0, [0, x1$0, 0]]];
        return [0, s$0, tl$1];
       }
      }
     }
     var
      n1 = n >> 1,
      n2 = n - n1 | 0,
      match$0 = sort(n1, l),
      l2$0 = match$0[2],
      s1 = match$0[1],
      match$1 = sort(n2, l2$0),
      tl$0 = match$1[2],
      s2 = match$1[1],
      l1 = s1,
      l2 = s2,
      accu = 0;
     for(;;){
      if(l1){
       if(l2){
        var t2 = l2[2], h2 = l2[1], t1 = l1[2], h1 = l1[1];
        if(0 < caml_call2(cmp, h1, h2)){
         var accu$0 = [0, h2, accu], l2 = t2, accu = accu$0;
         continue;
        }
        var accu$1 = [0, h1, accu], l1 = t1, accu = accu$1;
        continue;
       }
       var _v_ = rev_append(l1, accu);
      }
      else
       var _v_ = rev_append(l2, accu);
      return [0, _v_, tl$0];
     }
    }
    var len = length(l);
    return 2 <= len ? sort(len, l)[1] : l;
   }
   function sort_uniq(cmp, l){
    function sort(n, l){
     if(2 === n){
      if(l){
       var match = l[2];
       if(match){
        var
         tl = match[2],
         x2 = match[1],
         x1 = l[1],
         c$0 = caml_call2(cmp, x1, x2),
         s =
           0 === c$0
            ? [0, x1, 0]
            : 0 <= c$0 ? [0, x2, [0, x1, 0]] : [0, x1, [0, x2, 0]];
        return [0, s, tl];
       }
      }
     }
     else if(3 === n && l){
      var _p_ = l[2];
      if(_p_){
       var match$2 = _p_[2];
       if(match$2){
        var
         tl$1 = match$2[2],
         x3 = match$2[1],
         x2$0 = _p_[1],
         x1$0 = l[1],
         c$1 = caml_call2(cmp, x1$0, x2$0);
        if(0 === c$1)
         var
          c$2 = caml_call2(cmp, x2$0, x3),
          _q_ =
            0 === c$2
             ? [0, x2$0, 0]
             : 0 <= c$2 ? [0, x3, [0, x2$0, 0]] : [0, x2$0, [0, x3, 0]],
          s$0 = _q_;
        else if(0 <= c$1){
         var c$3 = caml_call2(cmp, x1$0, x3);
         if(0 === c$3)
          var _r_ = [0, x2$0, [0, x1$0, 0]];
         else if(0 <= c$3)
          var
           c$4 = caml_call2(cmp, x2$0, x3),
           _s_ =
             0 === c$4
              ? [0, x2$0, [0, x1$0, 0]]
              : 0
                <= c$4
                ? [0, x3, [0, x2$0, [0, x1$0, 0]]]
                : [0, x2$0, [0, x3, [0, x1$0, 0]]],
           _r_ = _s_;
         else
          var _r_ = [0, x2$0, [0, x1$0, [0, x3, 0]]];
         var s$0 = _r_;
        }
        else{
         var c$5 = caml_call2(cmp, x2$0, x3);
         if(0 === c$5)
          var _t_ = [0, x1$0, [0, x2$0, 0]];
         else if(0 <= c$5)
          var
           c$6 = caml_call2(cmp, x1$0, x3),
           _u_ =
             0 === c$6
              ? [0, x1$0, [0, x2$0, 0]]
              : 0
                <= c$6
                ? [0, x3, [0, x1$0, [0, x2$0, 0]]]
                : [0, x1$0, [0, x3, [0, x2$0, 0]]],
           _t_ = _u_;
         else
          var _t_ = [0, x1$0, [0, x2$0, [0, x3, 0]]];
         var s$0 = _t_;
        }
        return [0, s$0, tl$1];
       }
      }
     }
     var
      n1 = n >> 1,
      n2 = n - n1 | 0,
      match$0 = rev_sort(n1, l),
      l2$0 = match$0[2],
      s1 = match$0[1],
      match$1 = rev_sort(n2, l2$0),
      tl$0 = match$1[2],
      s2 = match$1[1],
      l1 = s1,
      l2 = s2,
      accu = 0;
     for(;;){
      if(l1){
       if(l2){
        var
         t2 = l2[2],
         h2 = l2[1],
         t1 = l1[2],
         h1 = l1[1],
         c = caml_call2(cmp, h1, h2);
        if(0 === c){
         var accu$0 = [0, h1, accu], l1 = t1, l2 = t2, accu = accu$0;
         continue;
        }
        if(0 < c){
         var accu$1 = [0, h1, accu], l1 = t1, accu = accu$1;
         continue;
        }
        var accu$2 = [0, h2, accu], l2 = t2, accu = accu$2;
        continue;
       }
       var _o_ = rev_append(l1, accu);
      }
      else
       var _o_ = rev_append(l2, accu);
      return [0, _o_, tl$0];
     }
    }
    function rev_sort(n, l){
     if(2 === n){
      if(l){
       var match = l[2];
       if(match){
        var
         tl = match[2],
         x2 = match[1],
         x1 = l[1],
         c$0 = caml_call2(cmp, x1, x2),
         s =
           0 === c$0
            ? [0, x1, 0]
            : 0 < c$0 ? [0, x1, [0, x2, 0]] : [0, x2, [0, x1, 0]];
        return [0, s, tl];
       }
      }
     }
     else if(3 === n && l){
      var _i_ = l[2];
      if(_i_){
       var match$2 = _i_[2];
       if(match$2){
        var
         tl$1 = match$2[2],
         x3 = match$2[1],
         x2$0 = _i_[1],
         x1$0 = l[1],
         c$1 = caml_call2(cmp, x1$0, x2$0);
        if(0 === c$1)
         var
          c$2 = caml_call2(cmp, x2$0, x3),
          _j_ =
            0 === c$2
             ? [0, x2$0, 0]
             : 0 < c$2 ? [0, x2$0, [0, x3, 0]] : [0, x3, [0, x2$0, 0]],
          s$0 = _j_;
        else if(0 < c$1){
         var c$3 = caml_call2(cmp, x2$0, x3);
         if(0 === c$3)
          var _k_ = [0, x1$0, [0, x2$0, 0]];
         else if(0 < c$3)
          var _k_ = [0, x1$0, [0, x2$0, [0, x3, 0]]];
         else
          var
           c$4 = caml_call2(cmp, x1$0, x3),
           _l_ =
             0 === c$4
              ? [0, x1$0, [0, x2$0, 0]]
              : 0
                < c$4
                ? [0, x1$0, [0, x3, [0, x2$0, 0]]]
                : [0, x3, [0, x1$0, [0, x2$0, 0]]],
           _k_ = _l_;
         var s$0 = _k_;
        }
        else{
         var c$5 = caml_call2(cmp, x1$0, x3);
         if(0 === c$5)
          var _m_ = [0, x2$0, [0, x1$0, 0]];
         else if(0 < c$5)
          var _m_ = [0, x2$0, [0, x1$0, [0, x3, 0]]];
         else
          var
           c$6 = caml_call2(cmp, x2$0, x3),
           _n_ =
             0 === c$6
              ? [0, x2$0, [0, x1$0, 0]]
              : 0
                < c$6
                ? [0, x2$0, [0, x3, [0, x1$0, 0]]]
                : [0, x3, [0, x2$0, [0, x1$0, 0]]],
           _m_ = _n_;
         var s$0 = _m_;
        }
        return [0, s$0, tl$1];
       }
      }
     }
     var
      n1 = n >> 1,
      n2 = n - n1 | 0,
      match$0 = sort(n1, l),
      l2$0 = match$0[2],
      s1 = match$0[1],
      match$1 = sort(n2, l2$0),
      tl$0 = match$1[2],
      s2 = match$1[1],
      l1 = s1,
      l2 = s2,
      accu = 0;
     for(;;){
      if(l1){
       if(l2){
        var
         t2 = l2[2],
         h2 = l2[1],
         t1 = l1[2],
         h1 = l1[1],
         c = caml_call2(cmp, h1, h2);
        if(0 === c){
         var accu$0 = [0, h1, accu], l1 = t1, l2 = t2, accu = accu$0;
         continue;
        }
        if(0 <= c){
         var accu$1 = [0, h2, accu], l2 = t2, accu = accu$1;
         continue;
        }
        var accu$2 = [0, h1, accu], l1 = t1, accu = accu$2;
        continue;
       }
       var _h_ = rev_append(l1, accu);
      }
      else
       var _h_ = rev_append(l2, accu);
      return [0, _h_, tl$0];
     }
    }
    var len = length(l);
    return 2 <= len ? sort(len, l)[1] : l;
   }
   function compare_lengths(l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(! l1$0) return l2$0 ? -1 : 0;
     if(! l2$0) return 1;
     var l2$1 = l2$0[2], l1$1 = l1$0[2], l1$0 = l1$1, l2$0 = l2$1;
    }
   }
   function compare_length_with(l, n){
    var l$0 = l, n$0 = n;
    for(;;){
     if(! l$0) return 0 === n$0 ? 0 : 0 < n$0 ? -1 : 1;
     var l$1 = l$0[2];
     if(0 >= n$0) return 1;
     var n$1 = n$0 - 1 | 0, l$0 = l$1, n$0 = n$1;
    }
   }
   function equal(eq, l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(l1$0){
      if(l2$0){
       var
        l2$1 = l2$0[2],
        a2 = l2$0[1],
        l1$1 = l1$0[2],
        a1 = l1$0[1],
        _g_ = caml_call2(eq, a1, a2);
       if(! _g_) return _g_;
       var l1$0 = l1$1, l2$0 = l2$1;
       continue;
      }
     }
     else if(! l2$0) return 1;
     return 0;
    }
   }
   function compare(cmp, l1, l2){
    var l1$0 = l1, l2$0 = l2;
    for(;;){
     if(! l1$0) return l2$0 ? -1 : 0;
     var l1$1 = l1$0[2], a1 = l1$0[1];
     if(! l2$0) return 1;
     var l2$1 = l2$0[2], a2 = l2$0[1], c = caml_call2(cmp, a1, a2);
     if(0 !== c) return c;
     var l1$0 = l1$1, l2$0 = l2$1;
    }
   }
   function to_seq(l){
    function aux(l, param){
     if(! l) return 0;
     var tail = l[2], x = l[1];
     return [0, x, function(_f_){return aux(tail, _f_);}];
    }
    return function(_e_){return aux(l, _e_);};
   }
   function of_seq(seq){
    function direct(depth, seq){
     if(0 === depth){
      var _c_ = 0, _d_ = function(acc, x){return [0, x, acc];};
      return rev(caml_call3(Stdlib_Seq[5], _d_, _c_, seq));
     }
     var match = caml_call1(seq, 0);
     if(! match) return 0;
     var next = match[2], x = match[1];
     return [0, x, direct(depth - 1 | 0, next)];
    }
    return direct(500, seq);
   }
   var
    Stdlib_List =
      [0,
       length,
       compare_lengths,
       compare_length_with,
       cons,
       hd,
       tl,
       nth,
       nth_opt,
       rev,
       init,
       append,
       rev_append,
       flatten,
       flatten,
       equal,
       compare,
       iter,
       iteri,
       map,
       mapi,
       rev_map,
       filter_map,
       concat_map,
       fold_left_map,
       fold_left,
       fold_right,
       iter2,
       map2,
       rev_map2,
       fold_left2,
       fold_right2,
       for_all,
       exists,
       for_all2,
       exists2,
       mem,
       memq,
       find,
       find_opt,
       find_map,
       find_all,
       find_all,
       filteri,
       partition,
       partition_map,
       assoc,
       assoc_opt,
       assq,
       assq_opt,
       mem_assoc,
       mem_assq,
       remove_assoc,
       remove_assq,
       split,
       combine,
       stable_sort,
       stable_sort,
       stable_sort,
       sort_uniq,
       merge,
       to_seq,
       of_seq];
   runtime.caml_register_global(18, Stdlib_List, "Stdlib__List");
   return;
  }
  (globalThis));

//# 3724 "../.js/default/stdlib/stdlib.cma.js"
(function(globalThis){
   "use strict";
   var runtime = globalThis.jsoo_runtime, zero = 0, one = 1, minus_one = -1;
   function abs(x){return 0 <= x ? x : - x | 0;}
   var max_int = 2147483647, min_int = -2147483648;
   function lognot(x){return x ^ -1;}
   function equal(_b_, _a_){return _b_ === _a_ ? 1 : 0;}
   var compare = runtime.caml_int_compare;
   function min(x, y){return x <= y ? x : y;}
   function max(x, y){return y <= x ? x : y;}
   function to_string(x){return "" + x;}
   var
    Stdlib_Int =
      [0,
       zero,
       one,
       minus_one,
       abs,
       max_int,
       min_int,
       lognot,
       equal,
       compare,
       min,
       max,
       to_string];
   runtime.caml_register_global(1, Stdlib_Int, "Stdlib__Int");
   return;
  }
  (globalThis));

//# 3757 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst_bytes_ml = "bytes.ml",
    cst_index_out_of_bounds$3 = "index out of bounds",
    caml_blit_bytes = runtime.caml_blit_bytes,
    caml_bswap16 = runtime.caml_bswap16,
    caml_bytes_get = runtime.caml_bytes_get,
    caml_bytes_get16 = runtime.caml_bytes_get16,
    caml_bytes_get32 = runtime.caml_bytes_get32,
    caml_bytes_get64 = runtime.caml_bytes_get64,
    caml_bytes_of_string = runtime.caml_bytes_of_string,
    caml_bytes_set = runtime.caml_bytes_set,
    caml_bytes_set16 = runtime.caml_bytes_set16,
    caml_bytes_set32 = runtime.caml_bytes_set32,
    caml_bytes_set64 = runtime.caml_bytes_set64,
    caml_bytes_unsafe_get = runtime.caml_bytes_unsafe_get,
    caml_bytes_unsafe_set = runtime.caml_bytes_unsafe_set,
    caml_create_bytes = runtime.caml_create_bytes,
    caml_fill_bytes = runtime.caml_fill_bytes,
    caml_int32_bswap = runtime.caml_int32_bswap,
    caml_int64_bswap = runtime.caml_int64_bswap,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_ml_bytes_length = runtime.caml_ml_bytes_length,
    caml_string_of_bytes = runtime.caml_string_of_bytes,
    caml_wrap_exception = runtime.caml_wrap_exception;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    Stdlib = global_data.Stdlib,
    Stdlib_Uchar = global_data.Stdlib__Uchar,
    Assert_failure = global_data.Assert_failure,
    Stdlib_Sys = global_data.Stdlib__Sys,
    Stdlib_Int = global_data.Stdlib__Int,
    Stdlib_Seq = global_data.Stdlib__Seq,
    Stdlib_Char = global_data.Stdlib__Char,
    cst_index_out_of_bounds$2 = cst_index_out_of_bounds$3,
    _f_ = [0, cst_bytes_ml, 808, 20],
    _e_ = [0, cst_bytes_ml, 819, 9],
    cst_index_out_of_bounds$1 = cst_index_out_of_bounds$3,
    cst_index_out_of_bounds$0 = cst_index_out_of_bounds$3,
    _d_ = [0, cst_bytes_ml, 754, 20],
    _c_ = [0, cst_bytes_ml, 765, 9],
    cst_index_out_of_bounds = cst_index_out_of_bounds$3,
    _b_ = [0, cst_bytes_ml, 642, 20],
    _a_ = [0, cst_bytes_ml, 667, 9],
    cst_Bytes_of_seq_cannot_grow_b = "Bytes.of_seq: cannot grow bytes",
    cst_String_rcontains_from_Byte =
      "String.rcontains_from / Bytes.rcontains_from",
    cst_String_contains_from_Bytes =
      "String.contains_from / Bytes.contains_from",
    cst_String_rindex_from_opt_Byt =
      "String.rindex_from_opt / Bytes.rindex_from_opt",
    cst_String_rindex_from_Bytes_r = "String.rindex_from / Bytes.rindex_from",
    cst_String_index_from_opt_Byte =
      "String.index_from_opt / Bytes.index_from_opt",
    cst_String_index_from_Bytes_in = "String.index_from / Bytes.index_from",
    cst_Bytes_concat = "Bytes.concat",
    cst_String_blit_Bytes_blit_str = "String.blit / Bytes.blit_string",
    cst_Bytes_blit = "Bytes.blit",
    cst_String_fill_Bytes_fill = "String.fill / Bytes.fill",
    cst_Bytes_extend = "Bytes.extend",
    cst_String_sub_Bytes_sub = "String.sub / Bytes.sub";
   function make(n, c){
    var s = caml_create_bytes(n);
    caml_fill_bytes(s, 0, n, c);
    return s;
   }
   function init(n, f){
    var s = caml_create_bytes(n), _aq_ = n - 1 | 0, _ap_ = 0;
    if(_aq_ >= 0){
     var i = _ap_;
     for(;;){
      caml_bytes_unsafe_set(s, i, caml_call1(f, i));
      var _ar_ = i + 1 | 0;
      if(_aq_ !== i){var i = _ar_; continue;}
      break;
     }
    }
    return s;
   }
   var empty = caml_create_bytes(0);
   function copy(s){
    var len = caml_ml_bytes_length(s), r = caml_create_bytes(len);
    caml_blit_bytes(s, 0, r, 0, len);
    return r;
   }
   function to_string(b){return caml_string_of_bytes(copy(b));}
   function of_string(s){return copy(caml_bytes_of_string(s));}
   function sub(s, ofs, len){
    if(0 <= ofs && 0 <= len && (caml_ml_bytes_length(s) - len | 0) >= ofs){
     var r = caml_create_bytes(len);
     caml_blit_bytes(s, ofs, r, 0, len);
     return r;
    }
    return caml_call1(Stdlib[1], cst_String_sub_Bytes_sub);
   }
   function sub_string(b, ofs, len){
    return caml_string_of_bytes(sub(b, ofs, len));
   }
   function symbol(a, b){
    var
     c = a + b | 0,
     _ao_ = b < 0 ? 1 : 0,
     match = c < 0 ? 1 : 0,
     switch$0 = 0;
    if(a < 0){
     if(_ao_ && ! match) switch$0 = 1;
    }
    else if(! _ao_ && match) switch$0 = 1;
    return switch$0 ? caml_call1(Stdlib[1], cst_Bytes_extend) : c;
   }
   function extend(s, left, right){
    var
     len = symbol(symbol(caml_ml_bytes_length(s), left), right),
     r = caml_create_bytes(len);
    if(0 <= left)
     var dstoff = left, srcoff = 0;
    else
     var dstoff = 0, srcoff = - left | 0;
    var
     cpylen =
       caml_call2
        (Stdlib_Int[10],
         caml_ml_bytes_length(s) - srcoff | 0,
         len - dstoff | 0);
    if(0 < cpylen) caml_blit_bytes(s, srcoff, r, dstoff, cpylen);
    return r;
   }
   function fill(s, ofs, len, c){
    if(0 <= ofs && 0 <= len && (caml_ml_bytes_length(s) - len | 0) >= ofs)
     return caml_fill_bytes(s, ofs, len, c);
    return caml_call1(Stdlib[1], cst_String_fill_Bytes_fill);
   }
   function blit(s1, ofs1, s2, ofs2, len){
    if
     (0 <= len
      &&
       0 <= ofs1
       &&
        (caml_ml_bytes_length(s1) - len | 0) >= ofs1
        && 0 <= ofs2 && (caml_ml_bytes_length(s2) - len | 0) >= ofs2)
     return caml_blit_bytes(s1, ofs1, s2, ofs2, len);
    return caml_call1(Stdlib[1], cst_Bytes_blit);
   }
   function blit_string(s1, ofs1, s2, ofs2, len){
    if
     (0 <= len
      &&
       0 <= ofs1
       &&
        (runtime.caml_ml_string_length(s1) - len | 0) >= ofs1
        && 0 <= ofs2 && (caml_ml_bytes_length(s2) - len | 0) >= ofs2)
     return runtime.caml_blit_string(s1, ofs1, s2, ofs2, len);
    return caml_call1(Stdlib[1], cst_String_blit_Bytes_blit_str);
   }
   function iter(f, a){
    var _am_ = caml_ml_bytes_length(a) - 1 | 0, _al_ = 0;
    if(_am_ >= 0){
     var i = _al_;
     for(;;){
      caml_call1(f, caml_bytes_unsafe_get(a, i));
      var _an_ = i + 1 | 0;
      if(_am_ !== i){var i = _an_; continue;}
      break;
     }
    }
    return 0;
   }
   function iteri(f, a){
    var _aj_ = caml_ml_bytes_length(a) - 1 | 0, _ai_ = 0;
    if(_aj_ >= 0){
     var i = _ai_;
     for(;;){
      caml_call2(f, i, caml_bytes_unsafe_get(a, i));
      var _ak_ = i + 1 | 0;
      if(_aj_ !== i){var i = _ak_; continue;}
      break;
     }
    }
    return 0;
   }
   function concat(sep, l){
    if(! l) return empty;
    var seplen = caml_ml_bytes_length(sep), acc = 0, param = l, pos$1 = 0;
    for(;;){
     if(param){
      var hd = param[1];
      if(param[2]){
       var
        tl = param[2],
        x = (caml_ml_bytes_length(hd) + seplen | 0) + acc | 0,
        acc$0 = acc <= x ? x : caml_call1(Stdlib[1], cst_Bytes_concat),
        acc = acc$0,
        param = tl;
       continue;
      }
      var _ah_ = caml_ml_bytes_length(hd) + acc | 0;
     }
     else
      var _ah_ = acc;
     var dst = caml_create_bytes(_ah_), pos = pos$1, param$0 = l;
     for(;;){
      if(! param$0) return dst;
      var hd$0 = param$0[1];
      if(param$0[2]){
       var tl$0 = param$0[2];
       caml_blit_bytes(hd$0, 0, dst, pos, caml_ml_bytes_length(hd$0));
       caml_blit_bytes
        (sep, 0, dst, pos + caml_ml_bytes_length(hd$0) | 0, seplen);
       var
        pos$0 = (pos + caml_ml_bytes_length(hd$0) | 0) + seplen | 0,
        pos = pos$0,
        param$0 = tl$0;
       continue;
      }
      caml_blit_bytes(hd$0, 0, dst, pos, caml_ml_bytes_length(hd$0));
      return dst;
     }
    }
   }
   function cat(s1, s2){
    var
     l1 = caml_ml_bytes_length(s1),
     l2 = caml_ml_bytes_length(s2),
     r = caml_create_bytes(l1 + l2 | 0);
    caml_blit_bytes(s1, 0, r, 0, l1);
    caml_blit_bytes(s2, 0, r, l1, l2);
    return r;
   }
   function is_space(param){
    var _ag_ = param - 9 | 0, switch$0 = 0;
    if(4 < _ag_ >>> 0){
     if(23 === _ag_) switch$0 = 1;
    }
    else if(2 !== _ag_) switch$0 = 1;
    return switch$0 ? 1 : 0;
   }
   function trim(s){
    var len = caml_ml_bytes_length(s), i = [0, 0];
    for(;;){
     if(i[1] < len && is_space(caml_bytes_unsafe_get(s, i[1]))){i[1]++; continue;}
     var j = [0, len - 1 | 0];
     for(;;){
      if(i[1] <= j[1] && is_space(caml_bytes_unsafe_get(s, j[1]))){j[1] += -1; continue;}
      return i[1] <= j[1] ? sub(s, i[1], (j[1] - i[1] | 0) + 1 | 0) : empty;
     }
    }
   }
   function escaped(s){
    var n = [0, 0], _$_ = caml_ml_bytes_length(s) - 1 | 0, ___ = 0;
    if(_$_ >= 0){
     var i$0 = ___;
     for(;;){
      var match = caml_bytes_unsafe_get(s, i$0), switch$0 = 0;
      if(32 <= match){
       var _ad_ = match - 34 | 0, switch$1 = 0;
       if(58 < _ad_ >>> 0){
        if(93 > _ad_) switch$1 = 1;
       }
       else if(56 < _ad_ - 1 >>> 0) switch$0 = 1; else switch$1 = 1;
       if(switch$1){var _ae_ = 1; switch$0 = 2;}
      }
      else
       if(11 <= match){
        if(13 === match) switch$0 = 1;
       }
       else if(8 <= match) switch$0 = 1;
      switch(switch$0){
        case 0:
         var _ae_ = 4; break;
        case 1:
         var _ae_ = 2; break;
      }
      n[1] = n[1] + _ae_ | 0;
      var _af_ = i$0 + 1 | 0;
      if(_$_ !== i$0){var i$0 = _af_; continue;}
      break;
     }
    }
    if(n[1] === caml_ml_bytes_length(s)) return copy(s);
    var s$0 = caml_create_bytes(n[1]);
    n[1] = 0;
    var _ab_ = caml_ml_bytes_length(s) - 1 | 0, _aa_ = 0;
    if(_ab_ >= 0){
     var i = _aa_;
     for(;;){
      var c = caml_bytes_unsafe_get(s, i), switch$2 = 0;
      if(35 <= c)
       if(92 === c)
        switch$2 = 2;
       else if(127 <= c) switch$2 = 1; else switch$2 = 3;
      else if(32 <= c)
       if(34 <= c) switch$2 = 2; else switch$2 = 3;
      else if(14 <= c)
       switch$2 = 1;
      else
       switch(c){
         case 8:
          caml_bytes_unsafe_set(s$0, n[1], 92);
          n[1]++;
          caml_bytes_unsafe_set(s$0, n[1], 98);
          break;
         case 9:
          caml_bytes_unsafe_set(s$0, n[1], 92);
          n[1]++;
          caml_bytes_unsafe_set(s$0, n[1], 116);
          break;
         case 10:
          caml_bytes_unsafe_set(s$0, n[1], 92);
          n[1]++;
          caml_bytes_unsafe_set(s$0, n[1], 110);
          break;
         case 13:
          caml_bytes_unsafe_set(s$0, n[1], 92);
          n[1]++;
          caml_bytes_unsafe_set(s$0, n[1], 114);
          break;
         default: switch$2 = 1;
       }
      switch(switch$2){
        case 1:
         caml_bytes_unsafe_set(s$0, n[1], 92);
         n[1]++;
         caml_bytes_unsafe_set(s$0, n[1], 48 + (c / 100 | 0) | 0);
         n[1]++;
         caml_bytes_unsafe_set(s$0, n[1], 48 + ((c / 10 | 0) % 10 | 0) | 0);
         n[1]++;
         caml_bytes_unsafe_set(s$0, n[1], 48 + (c % 10 | 0) | 0);
         break;
        case 2:
         caml_bytes_unsafe_set(s$0, n[1], 92);
         n[1]++;
         caml_bytes_unsafe_set(s$0, n[1], c);
         break;
        case 3:
         caml_bytes_unsafe_set(s$0, n[1], c); break;
      }
      n[1]++;
      var _ac_ = i + 1 | 0;
      if(_ab_ !== i){var i = _ac_; continue;}
      break;
     }
    }
    return s$0;
   }
   function map(f, s){
    var l = caml_ml_bytes_length(s);
    if(0 === l) return s;
    var r = caml_create_bytes(l), _Y_ = l - 1 | 0, _X_ = 0;
    if(_Y_ >= 0){
     var i = _X_;
     for(;;){
      caml_bytes_unsafe_set(r, i, caml_call1(f, caml_bytes_unsafe_get(s, i)));
      var _Z_ = i + 1 | 0;
      if(_Y_ !== i){var i = _Z_; continue;}
      break;
     }
    }
    return r;
   }
   function mapi(f, s){
    var l = caml_ml_bytes_length(s);
    if(0 === l) return s;
    var r = caml_create_bytes(l), _V_ = l - 1 | 0, _U_ = 0;
    if(_V_ >= 0){
     var i = _U_;
     for(;;){
      caml_bytes_unsafe_set
       (r, i, caml_call2(f, i, caml_bytes_unsafe_get(s, i)));
      var _W_ = i + 1 | 0;
      if(_V_ !== i){var i = _W_; continue;}
      break;
     }
    }
    return r;
   }
   function fold_left(f, x, a){
    var r = [0, x], _S_ = caml_ml_bytes_length(a) - 1 | 0, _R_ = 0;
    if(_S_ >= 0){
     var i = _R_;
     for(;;){
      r[1] = caml_call2(f, r[1], caml_bytes_unsafe_get(a, i));
      var _T_ = i + 1 | 0;
      if(_S_ !== i){var i = _T_; continue;}
      break;
     }
    }
    return r[1];
   }
   function fold_right(f, a, x){
    var r = [0, x], _P_ = caml_ml_bytes_length(a) - 1 | 0;
    if(_P_ >= 0){
     var i = _P_;
     for(;;){
      r[1] = caml_call2(f, caml_bytes_unsafe_get(a, i), r[1]);
      var _Q_ = i - 1 | 0;
      if(0 !== i){var i = _Q_; continue;}
      break;
     }
    }
    return r[1];
   }
   function exists(p, s){
    var n = caml_ml_bytes_length(s), i = 0;
    for(;;){
     if(i === n) return 0;
     if(caml_call1(p, caml_bytes_unsafe_get(s, i))) return 1;
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function for_all(p, s){
    var n = caml_ml_bytes_length(s), i = 0;
    for(;;){
     if(i === n) return 1;
     if(! caml_call1(p, caml_bytes_unsafe_get(s, i))) return 0;
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function uppercase_ascii(s){return map(Stdlib_Char[6], s);}
   function lowercase_ascii(s){return map(Stdlib_Char[5], s);}
   function apply1(f, s){
    if(0 === caml_ml_bytes_length(s)) return s;
    var r = copy(s);
    caml_bytes_unsafe_set(r, 0, caml_call1(f, caml_bytes_unsafe_get(s, 0)));
    return r;
   }
   function capitalize_ascii(s){return apply1(Stdlib_Char[6], s);}
   function uncapitalize_ascii(s){return apply1(Stdlib_Char[5], s);}
   function starts_with(prefix, s){
    var
     len_s = caml_ml_bytes_length(s),
     len_pre = caml_ml_bytes_length(prefix),
     _O_ = len_pre <= len_s ? 1 : 0;
    if(! _O_) return _O_;
    var i = 0;
    for(;;){
     if(i === len_pre) return 1;
     if(caml_bytes_unsafe_get(s, i) !== caml_bytes_unsafe_get(prefix, i))
      return 0;
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function ends_with(suffix, s){
    var
     len_s = caml_ml_bytes_length(s),
     len_suf = caml_ml_bytes_length(suffix),
     diff = len_s - len_suf | 0,
     _N_ = 0 <= diff ? 1 : 0;
    if(! _N_) return _N_;
    var i = 0;
    for(;;){
     if(i === len_suf) return 1;
     if
      (caml_bytes_unsafe_get(s, diff + i | 0)
       !== caml_bytes_unsafe_get(suffix, i))
      return 0;
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function index_rec(s, lim, i, c){
    var i$0 = i;
    for(;;){
     if(lim <= i$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     if(caml_bytes_unsafe_get(s, i$0) === c) return i$0;
     var i$1 = i$0 + 1 | 0, i$0 = i$1;
    }
   }
   function index(s, c){return index_rec(s, caml_ml_bytes_length(s), 0, c);}
   function index_rec_opt(s, lim, i, c){
    var i$0 = i;
    for(;;){
     if(lim <= i$0) return 0;
     if(caml_bytes_unsafe_get(s, i$0) === c) return [0, i$0];
     var i$1 = i$0 + 1 | 0, i$0 = i$1;
    }
   }
   function index_opt(s, c){
    return index_rec_opt(s, caml_ml_bytes_length(s), 0, c);
   }
   function index_from(s, i, c){
    var l = caml_ml_bytes_length(s);
    if(0 <= i && l >= i) return index_rec(s, l, i, c);
    return caml_call1(Stdlib[1], cst_String_index_from_Bytes_in);
   }
   function index_from_opt(s, i, c){
    var l = caml_ml_bytes_length(s);
    if(0 <= i && l >= i) return index_rec_opt(s, l, i, c);
    return caml_call1(Stdlib[1], cst_String_index_from_opt_Byte);
   }
   function rindex_rec(s, i, c){
    var i$0 = i;
    for(;;){
     if(0 > i$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     if(caml_bytes_unsafe_get(s, i$0) === c) return i$0;
     var i$1 = i$0 - 1 | 0, i$0 = i$1;
    }
   }
   function rindex(s, c){
    return rindex_rec(s, caml_ml_bytes_length(s) - 1 | 0, c);
   }
   function rindex_from(s, i, c){
    if(-1 <= i && caml_ml_bytes_length(s) > i) return rindex_rec(s, i, c);
    return caml_call1(Stdlib[1], cst_String_rindex_from_Bytes_r);
   }
   function rindex_rec_opt(s, i, c){
    var i$0 = i;
    for(;;){
     if(0 > i$0) return 0;
     if(caml_bytes_unsafe_get(s, i$0) === c) return [0, i$0];
     var i$1 = i$0 - 1 | 0, i$0 = i$1;
    }
   }
   function rindex_opt(s, c){
    return rindex_rec_opt(s, caml_ml_bytes_length(s) - 1 | 0, c);
   }
   function rindex_from_opt(s, i, c){
    if(-1 <= i && caml_ml_bytes_length(s) > i) return rindex_rec_opt(s, i, c);
    return caml_call1(Stdlib[1], cst_String_rindex_from_opt_Byt);
   }
   function contains_from(s, i, c){
    var l = caml_ml_bytes_length(s);
    if(0 <= i && l >= i)
     try{index_rec(s, l, i, c); var _L_ = 1; return _L_;}
     catch(_M_){
      var _K_ = caml_wrap_exception(_M_);
      if(_K_ === Stdlib[8]) return 0;
      throw caml_maybe_attach_backtrace(_K_, 0);
     }
    return caml_call1(Stdlib[1], cst_String_contains_from_Bytes);
   }
   function contains(s, c){return contains_from(s, 0, c);}
   function rcontains_from(s, i, c){
    if(0 <= i && caml_ml_bytes_length(s) > i)
     try{rindex_rec(s, i, c); var _I_ = 1; return _I_;}
     catch(_J_){
      var _H_ = caml_wrap_exception(_J_);
      if(_H_ === Stdlib[8]) return 0;
      throw caml_maybe_attach_backtrace(_H_, 0);
     }
    return caml_call1(Stdlib[1], cst_String_rcontains_from_Byte);
   }
   var compare = runtime.caml_bytes_compare;
   function split_on_char(sep, s){
    var
     r = [0, 0],
     j = [0, caml_ml_bytes_length(s)],
     _D_ = caml_ml_bytes_length(s) - 1 | 0;
    if(_D_ >= 0){
     var i = _D_;
     for(;;){
      if(caml_bytes_unsafe_get(s, i) === sep){
       var _F_ = r[1];
       r[1] = [0, sub(s, i + 1 | 0, (j[1] - i | 0) - 1 | 0), _F_];
       j[1] = i;
      }
      var _G_ = i - 1 | 0;
      if(0 !== i){var i = _G_; continue;}
      break;
     }
    }
    var _E_ = r[1];
    return [0, sub(s, 0, j[1]), _E_];
   }
   function uppercase(s){return map(Stdlib_Char[4], s);}
   function lowercase(s){return map(Stdlib_Char[3], s);}
   function capitalize(s){return apply1(Stdlib_Char[4], s);}
   function uncapitalize(s){return apply1(Stdlib_Char[3], s);}
   function to_seq(s){
    function aux(i, param){
     if(i === caml_ml_bytes_length(s)) return 0;
     var x = caml_bytes_get(s, i), _B_ = i + 1 | 0;
     return [0, x, function(_C_){return aux(_B_, _C_);}];
    }
    var _z_ = 0;
    return function(_A_){return aux(_z_, _A_);};
   }
   function to_seqi(s){
    function aux(i, param){
     if(i === caml_ml_bytes_length(s)) return 0;
     var x = caml_bytes_get(s, i), _x_ = i + 1 | 0;
     return [0, [0, i, x], function(_y_){return aux(_x_, _y_);}];
    }
    var _v_ = 0;
    return function(_w_){return aux(_v_, _w_);};
   }
   function of_seq(i){
    var n = [0, 0], buf = [0, make(256, 0)];
    function _u_(c){
     if(n[1] === caml_ml_bytes_length(buf[1])){
      var
       new_len =
         caml_call2
          (Stdlib_Int[10],
           2 * caml_ml_bytes_length(buf[1]) | 0,
           Stdlib_Sys[12]);
      if(caml_ml_bytes_length(buf[1]) === new_len)
       caml_call1(Stdlib[2], cst_Bytes_of_seq_cannot_grow_b);
      var new_buf = make(new_len, 0);
      blit(buf[1], 0, new_buf, 0, n[1]);
      buf[1] = new_buf;
     }
     caml_bytes_set(buf[1], n[1], c);
     n[1]++;
     return 0;
    }
    caml_call2(Stdlib_Seq[4], _u_, i);
    return sub(buf[1], 0, n[1]);
   }
   function unsafe_get_uint16_le(b, i){
    return Stdlib_Sys[11]
            ? caml_bswap16(caml_bytes_get16(b, i))
            : caml_bytes_get16(b, i);
   }
   function unsafe_get_uint16_be(b, i){
    return Stdlib_Sys[11]
            ? caml_bytes_get16(b, i)
            : caml_bswap16(caml_bytes_get16(b, i));
   }
   function get_int8(b, i){
    var _s_ = Stdlib_Sys[10] - 8 | 0, _t_ = Stdlib_Sys[10] - 8 | 0;
    return caml_bytes_get(b, i) << _t_ >> _s_;
   }
   function get_uint16_le(b, i){
    return Stdlib_Sys[11]
            ? caml_bswap16(caml_bytes_get16(b, i))
            : caml_bytes_get16(b, i);
   }
   function get_uint16_be(b, i){
    return Stdlib_Sys[11]
            ? caml_bytes_get16(b, i)
            : caml_bswap16(caml_bytes_get16(b, i));
   }
   function get_int16_ne(b, i){
    var _q_ = Stdlib_Sys[10] - 16 | 0, _r_ = Stdlib_Sys[10] - 16 | 0;
    return caml_bytes_get16(b, i) << _r_ >> _q_;
   }
   function get_int16_le(b, i){
    var _o_ = Stdlib_Sys[10] - 16 | 0, _p_ = Stdlib_Sys[10] - 16 | 0;
    return get_uint16_le(b, i) << _p_ >> _o_;
   }
   function get_int16_be(b, i){
    var _m_ = Stdlib_Sys[10] - 16 | 0, _n_ = Stdlib_Sys[10] - 16 | 0;
    return get_uint16_be(b, i) << _n_ >> _m_;
   }
   function get_int32_le(b, i){
    return Stdlib_Sys[11]
            ? caml_int32_bswap(caml_bytes_get32(b, i))
            : caml_bytes_get32(b, i);
   }
   function get_int32_be(b, i){
    return Stdlib_Sys[11]
            ? caml_bytes_get32(b, i)
            : caml_int32_bswap(caml_bytes_get32(b, i));
   }
   function get_int64_le(b, i){
    return Stdlib_Sys[11]
            ? caml_int64_bswap(caml_bytes_get64(b, i))
            : caml_bytes_get64(b, i);
   }
   function get_int64_be(b, i){
    return Stdlib_Sys[11]
            ? caml_bytes_get64(b, i)
            : caml_int64_bswap(caml_bytes_get64(b, i));
   }
   function unsafe_set_uint16_le(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set16(b, i, caml_bswap16(x))
            : caml_bytes_set16(b, i, x);
   }
   function unsafe_set_uint16_be(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set16(b, i, x)
            : caml_bytes_set16(b, i, caml_bswap16(x));
   }
   function set_int16_le(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set16(b, i, caml_bswap16(x))
            : caml_bytes_set16(b, i, x);
   }
   function set_int16_be(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set16(b, i, x)
            : caml_bytes_set16(b, i, caml_bswap16(x));
   }
   function set_int32_le(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set32(b, i, caml_int32_bswap(x))
            : caml_bytes_set32(b, i, x);
   }
   function set_int32_be(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set32(b, i, x)
            : caml_bytes_set32(b, i, caml_int32_bswap(x));
   }
   function set_int64_le(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set64(b, i, caml_int64_bswap(x))
            : caml_bytes_set64(b, i, x);
   }
   function set_int64_be(b, i, x){
    return Stdlib_Sys[11]
            ? caml_bytes_set64(b, i, x)
            : caml_bytes_set64(b, i, caml_int64_bswap(x));
   }
   var
    set_uint8 = caml_bytes_set,
    set_uint16_ne = caml_bytes_set16,
    dec_invalid = Stdlib_Uchar[22];
   function dec_ret(n, u){
    var _l_ = caml_call1(Stdlib_Uchar[9], u);
    return caml_call2(Stdlib_Uchar[21], n, _l_);
   }
   function not_in_x80_to_xBF(b){return 2 !== (b >>> 6 | 0) ? 1 : 0;}
   function not_in_xA0_to_xBF(b){return 5 !== (b >>> 5 | 0) ? 1 : 0;}
   function not_in_x80_to_x9F(b){return 4 !== (b >>> 5 | 0) ? 1 : 0;}
   function not_in_x90_to_xBF(b){
    var _j_ = b < 144 ? 1 : 0, _k_ = _j_ || (191 < b ? 1 : 0);
    return _k_;
   }
   function not_in_x80_to_x8F(b){return 8 !== (b >>> 4 | 0) ? 1 : 0;}
   function utf_8_uchar_3(b0, b1, b2){
    return (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63;
   }
   function utf_8_uchar_4(b0, b1, b2, b3){
    return (b0 & 7) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63;
   }
   function get_utf_8_uchar(b, i){
    var b0 = caml_bytes_get(b, i), max = caml_ml_bytes_length(b) - 1 | 0;
    if(224 <= b0){
     var switch$0 = 0;
     if(237 <= b0){
      if(245 > b0)
       switch(b0 - 237 | 0){
         case 0:
          var i$0 = i + 1 | 0;
          if(max < i$0) return caml_call1(dec_invalid, 1);
          var b1 = caml_bytes_unsafe_get(b, i$0);
          if(not_in_x80_to_x9F(b1)) return caml_call1(dec_invalid, 1);
          var i$1 = i$0 + 1 | 0;
          if(max < i$1) return caml_call1(dec_invalid, 2);
          var b2 = caml_bytes_unsafe_get(b, i$1);
          return not_in_x80_to_xBF(b2)
                  ? caml_call1(dec_invalid, 2)
                  : dec_ret(3, utf_8_uchar_3(b0, b1, b2));
         case 3:
          var i$4 = i + 1 | 0;
          if(max < i$4) return caml_call1(dec_invalid, 1);
          var b1$1 = caml_bytes_unsafe_get(b, i$4);
          if(not_in_x90_to_xBF(b1$1)) return caml_call1(dec_invalid, 1);
          var i$5 = i$4 + 1 | 0;
          if(max < i$5) return caml_call1(dec_invalid, 2);
          var b2$1 = caml_bytes_unsafe_get(b, i$5);
          if(not_in_x80_to_xBF(b2$1)) return caml_call1(dec_invalid, 2);
          var i$6 = i$5 + 1 | 0;
          if(max < i$6) return caml_call1(dec_invalid, 3);
          var b3 = caml_bytes_unsafe_get(b, i$6);
          return not_in_x80_to_xBF(b3)
                  ? caml_call1(dec_invalid, 3)
                  : dec_ret(4, utf_8_uchar_4(b0, b1$1, b2$1, b3));
         case 7:
          var i$10 = i + 1 | 0;
          if(max < i$10) return caml_call1(dec_invalid, 1);
          var b1$3 = caml_bytes_unsafe_get(b, i$10);
          if(not_in_x80_to_x8F(b1$3)) return caml_call1(dec_invalid, 1);
          var i$11 = i$10 + 1 | 0;
          if(max < i$11) return caml_call1(dec_invalid, 2);
          var b2$3 = caml_bytes_unsafe_get(b, i$11);
          if(not_in_x80_to_xBF(b2$3)) return caml_call1(dec_invalid, 2);
          var i$12 = i$11 + 1 | 0;
          if(max < i$12) return caml_call1(dec_invalid, 3);
          var b3$1 = caml_bytes_unsafe_get(b, i$12);
          return not_in_x80_to_xBF(b3$1)
                  ? caml_call1(dec_invalid, 3)
                  : dec_ret(4, utf_8_uchar_4(b0, b1$3, b2$3, b3$1));
         case 1:
         case 2:
          switch$0 = 1; break;
         default:
          var i$7 = i + 1 | 0;
          if(max < i$7) return caml_call1(dec_invalid, 1);
          var b1$2 = caml_bytes_unsafe_get(b, i$7);
          if(not_in_x80_to_xBF(b1$2)) return caml_call1(dec_invalid, 1);
          var i$8 = i$7 + 1 | 0;
          if(max < i$8) return caml_call1(dec_invalid, 2);
          var b2$2 = caml_bytes_unsafe_get(b, i$8);
          if(not_in_x80_to_xBF(b2$2)) return caml_call1(dec_invalid, 2);
          var i$9 = i$8 + 1 | 0;
          if(max < i$9) return caml_call1(dec_invalid, 3);
          var b3$0 = caml_bytes_unsafe_get(b, i$9);
          return not_in_x80_to_xBF(b3$0)
                  ? caml_call1(dec_invalid, 3)
                  : dec_ret(4, utf_8_uchar_4(b0, b1$2, b2$2, b3$0));
       }
     }
     else{
      if(225 > b0){
       var i$13 = i + 1 | 0;
       if(max < i$13) return caml_call1(dec_invalid, 1);
       var b1$4 = caml_bytes_unsafe_get(b, i$13);
       if(not_in_xA0_to_xBF(b1$4)) return caml_call1(dec_invalid, 1);
       var i$14 = i$13 + 1 | 0;
       if(max < i$14) return caml_call1(dec_invalid, 2);
       var b2$4 = caml_bytes_unsafe_get(b, i$14);
       return not_in_x80_to_xBF(b2$4)
               ? caml_call1(dec_invalid, 2)
               : dec_ret(3, utf_8_uchar_3(b0, b1$4, b2$4));
      }
      switch$0 = 1;
     }
     if(switch$0){
      var i$2 = i + 1 | 0;
      if(max < i$2) return caml_call1(dec_invalid, 1);
      var b1$0 = caml_bytes_unsafe_get(b, i$2);
      if(not_in_x80_to_xBF(b1$0)) return caml_call1(dec_invalid, 1);
      var i$3 = i$2 + 1 | 0;
      if(max < i$3) return caml_call1(dec_invalid, 2);
      var b2$0 = caml_bytes_unsafe_get(b, i$3);
      return not_in_x80_to_xBF(b2$0)
              ? caml_call1(dec_invalid, 2)
              : dec_ret(3, utf_8_uchar_3(b0, b1$0, b2$0));
     }
    }
    else{
     if(128 > b0) return dec_ret(1, b0);
     if(194 <= b0){
      var i$15 = i + 1 | 0;
      if(max < i$15) return caml_call1(dec_invalid, 1);
      var b1$5 = caml_bytes_unsafe_get(b, i$15);
      return not_in_x80_to_xBF(b1$5)
              ? caml_call1(dec_invalid, 1)
              : dec_ret(2, (b0 & 31) << 6 | b1$5 & 63);
     }
    }
    return caml_call1(dec_invalid, 1);
   }
   function set_utf_8_uchar(b, i, u){
    function set(_i_, _h_, _g_){
     caml_bytes_unsafe_set(_i_, _h_, _g_);
     return 0;
    }
    var
     max = caml_ml_bytes_length(b) - 1 | 0,
     u$0 = caml_call1(Stdlib_Uchar[10], u);
    if(0 > u$0)
     throw caml_maybe_attach_backtrace([0, Assert_failure, _b_], 1);
    if(127 >= u$0){caml_bytes_set(b, i, u$0); return 1;}
    if(2047 >= u$0){
     var last$1 = i + 1 | 0;
     return max < last$1
             ? 0
             : (caml_bytes_set
                (b, i, 192 | u$0 >>> 6 | 0),
               set(b, last$1, 128 | u$0 & 63),
               2);
    }
    if(65535 >= u$0){
     var last$0 = i + 2 | 0;
     return max < last$0
             ? 0
             : (caml_bytes_set
                (b, i, 224 | u$0 >>> 12 | 0),
               set(b, i + 1 | 0, 128 | (u$0 >>> 6 | 0) & 63),
               set(b, last$0, 128 | u$0 & 63),
               3);
    }
    if(1114111 < u$0)
     throw caml_maybe_attach_backtrace([0, Assert_failure, _a_], 1);
    var last = i + 3 | 0;
    return max < last
            ? 0
            : (caml_bytes_set
               (b, i, 240 | u$0 >>> 18 | 0),
              set(b, i + 1 | 0, 128 | (u$0 >>> 12 | 0) & 63),
              set(b, i + 2 | 0, 128 | (u$0 >>> 6 | 0) & 63),
              set(b, last, 128 | u$0 & 63),
              4);
   }
   function is_valid_utf_8(b){
    var max = caml_ml_bytes_length(b) - 1 | 0, i = 0;
    for(;;){
     if(max < i) return 1;
     var match = caml_bytes_unsafe_get(b, i);
     if(224 <= match){
      var switch$0 = 0;
      if(237 <= match){
       if(245 > match)
        switch(match - 237 | 0){
          case 0:
           var last = i + 2 | 0;
           if
            (max >= last
             &&
              !
              not_in_x80_to_x9F(caml_bytes_unsafe_get(b, i + 1 | 0))
              && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last))){var i$0 = last + 1 | 0, i = i$0; continue;}
           return 0;
          case 3:
           var last$1 = i + 3 | 0;
           if
            (max >= last$1
             &&
              !
              not_in_x90_to_xBF(caml_bytes_unsafe_get(b, i + 1 | 0))
              &&
               !
               not_in_x80_to_xBF(caml_bytes_unsafe_get(b, i + 2 | 0))
               && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$1))){var i$2 = last$1 + 1 | 0, i = i$2; continue;}
           return 0;
          case 7:
           var last$3 = i + 3 | 0;
           if
            (max >= last$3
             &&
              !
              not_in_x80_to_x8F(caml_bytes_unsafe_get(b, i + 1 | 0))
              &&
               !
               not_in_x80_to_xBF(caml_bytes_unsafe_get(b, i + 2 | 0))
               && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$3))){var i$4 = last$3 + 1 | 0, i = i$4; continue;}
           return 0;
          case 1:
          case 2:
           switch$0 = 1; break;
          default:
           var last$2 = i + 3 | 0;
           if
            (max >= last$2
             &&
              !
              not_in_x80_to_xBF(caml_bytes_unsafe_get(b, i + 1 | 0))
              &&
               !
               not_in_x80_to_xBF(caml_bytes_unsafe_get(b, i + 2 | 0))
               && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$2))){var i$3 = last$2 + 1 | 0, i = i$3; continue;}
           return 0;
        }
      }
      else{
       if(225 > match){
        var last$4 = i + 2 | 0;
        if
         (max >= last$4
          &&
           !
           not_in_xA0_to_xBF(caml_bytes_unsafe_get(b, i + 1 | 0))
           && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$4))){var i$5 = last$4 + 1 | 0, i = i$5; continue;}
        return 0;
       }
       switch$0 = 1;
      }
      if(switch$0){
       var last$0 = i + 2 | 0;
       if
        (max >= last$0
         &&
          !
          not_in_x80_to_xBF(caml_bytes_unsafe_get(b, i + 1 | 0))
          && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$0))){var i$1 = last$0 + 1 | 0, i = i$1; continue;}
       return 0;
      }
     }
     else{
      if(128 > match){var i$7 = i + 1 | 0, i = i$7; continue;}
      if(194 <= match){
       var last$5 = i + 1 | 0;
       if
        (max >= last$5
         && ! not_in_x80_to_xBF(caml_bytes_unsafe_get(b, last$5))){var i$6 = last$5 + 1 | 0, i = i$6; continue;}
       return 0;
      }
     }
     return 0;
    }
   }
   function get_utf_16be_uchar(b, i){
    var max = caml_ml_bytes_length(b) - 1 | 0;
    if(0 <= i && max >= i){
     if(i === max) return caml_call1(dec_invalid, 1);
     var hi = unsafe_get_uint16_be(b, i);
     if(55296 <= hi && 57343 >= hi){
      if(56319 < hi) return caml_call1(dec_invalid, 2);
      var last = i + 3 | 0;
      if(max < last) return caml_call1(dec_invalid, (max - i | 0) + 1 | 0);
      var lo = unsafe_get_uint16_be(b, i + 2 | 0);
      if(56320 <= lo && 57343 >= lo){
       var u = ((hi & 1023) << 10 | lo & 1023) + 65536 | 0;
       return dec_ret(4, u);
      }
      return caml_call1(dec_invalid, 2);
     }
     return dec_ret(2, hi);
    }
    return caml_call1(Stdlib[1], cst_index_out_of_bounds);
   }
   function set_utf_16be_uchar(b, i, u){
    var max = caml_ml_bytes_length(b) - 1 | 0;
    if(0 <= i && max >= i){
     var u$0 = caml_call1(Stdlib_Uchar[10], u);
     if(0 > u$0)
      throw caml_maybe_attach_backtrace([0, Assert_failure, _d_], 1);
     if(65535 >= u$0){
      var last$0 = i + 1 | 0;
      return max < last$0 ? 0 : (unsafe_set_uint16_be(b, i, u$0), 2);
     }
     if(1114111 < u$0)
      throw caml_maybe_attach_backtrace([0, Assert_failure, _c_], 1);
     var last = i + 3 | 0;
     if(max < last) return 0;
     var
      u$1 = u$0 - 65536 | 0,
      hi = 55296 | u$1 >>> 10 | 0,
      lo = 56320 | u$1 & 1023;
     unsafe_set_uint16_be(b, i, hi);
     unsafe_set_uint16_be(b, i + 2 | 0, lo);
     return 4;
    }
    return caml_call1(Stdlib[1], cst_index_out_of_bounds$0);
   }
   function is_valid_utf_16be(b){
    var max = caml_ml_bytes_length(b) - 1 | 0, i = 0;
    for(;;){
     if(max < i) return 1;
     if(i === max) return 0;
     var u = unsafe_get_uint16_be(b, i);
     if(55296 <= u && 57343 >= u){
      if(56319 < u) return 0;
      var last = i + 3 | 0;
      if(max < last) return 0;
      var u$0 = unsafe_get_uint16_be(b, i + 2 | 0);
      if(56320 <= u$0 && 57343 >= u$0){
       var i$1 = i + 4 | 0, i = i$1;
       continue;
      }
      return 0;
     }
     var i$0 = i + 2 | 0, i = i$0;
    }
   }
   function get_utf_16le_uchar(b, i){
    var max = caml_ml_bytes_length(b) - 1 | 0;
    if(0 <= i && max >= i){
     if(i === max) return caml_call1(dec_invalid, 1);
     var hi = unsafe_get_uint16_le(b, i);
     if(55296 <= hi && 57343 >= hi){
      if(56319 < hi) return caml_call1(dec_invalid, 2);
      var last = i + 3 | 0;
      if(max < last) return caml_call1(dec_invalid, (max - i | 0) + 1 | 0);
      var lo = unsafe_get_uint16_le(b, i + 2 | 0);
      if(56320 <= lo && 57343 >= lo){
       var u = ((hi & 1023) << 10 | lo & 1023) + 65536 | 0;
       return dec_ret(4, u);
      }
      return caml_call1(dec_invalid, 2);
     }
     return dec_ret(2, hi);
    }
    return caml_call1(Stdlib[1], cst_index_out_of_bounds$1);
   }
   function set_utf_16le_uchar(b, i, u){
    var max = caml_ml_bytes_length(b) - 1 | 0;
    if(0 <= i && max >= i){
     var u$0 = caml_call1(Stdlib_Uchar[10], u);
     if(0 > u$0)
      throw caml_maybe_attach_backtrace([0, Assert_failure, _f_], 1);
     if(65535 >= u$0){
      var last$0 = i + 1 | 0;
      return max < last$0 ? 0 : (unsafe_set_uint16_le(b, i, u$0), 2);
     }
     if(1114111 < u$0)
      throw caml_maybe_attach_backtrace([0, Assert_failure, _e_], 1);
     var last = i + 3 | 0;
     if(max < last) return 0;
     var
      u$1 = u$0 - 65536 | 0,
      hi = 55296 | u$1 >>> 10 | 0,
      lo = 56320 | u$1 & 1023;
     unsafe_set_uint16_le(b, i, hi);
     unsafe_set_uint16_le(b, i + 2 | 0, lo);
     return 4;
    }
    return caml_call1(Stdlib[1], cst_index_out_of_bounds$2);
   }
   function is_valid_utf_16le(b){
    var max = caml_ml_bytes_length(b) - 1 | 0, i = 0;
    for(;;){
     if(max < i) return 1;
     if(i === max) return 0;
     var u = unsafe_get_uint16_le(b, i);
     if(55296 <= u && 57343 >= u){
      if(56319 < u) return 0;
      var last = i + 3 | 0;
      if(max < last) return 0;
      var u$0 = unsafe_get_uint16_le(b, i + 2 | 0);
      if(56320 <= u$0 && 57343 >= u$0){
       var i$1 = i + 4 | 0, i = i$1;
       continue;
      }
      return 0;
     }
     var i$0 = i + 2 | 0, i = i$0;
    }
   }
   var
    Stdlib_Bytes =
      [0,
       make,
       init,
       empty,
       copy,
       of_string,
       to_string,
       sub,
       sub_string,
       extend,
       fill,
       blit,
       blit_string,
       concat,
       cat,
       iter,
       iteri,
       map,
       mapi,
       fold_left,
       fold_right,
       for_all,
       exists,
       trim,
       escaped,
       index,
       index_opt,
       rindex,
       rindex_opt,
       index_from,
       index_from_opt,
       rindex_from,
       rindex_from_opt,
       contains,
       contains_from,
       rcontains_from,
       uppercase,
       lowercase,
       capitalize,
       uncapitalize,
       uppercase_ascii,
       lowercase_ascii,
       capitalize_ascii,
       uncapitalize_ascii,
       compare,
       runtime.caml_bytes_equal,
       starts_with,
       ends_with,
       caml_string_of_bytes,
       caml_bytes_of_string,
       split_on_char,
       to_seq,
       to_seqi,
       of_seq,
       get_utf_8_uchar,
       set_utf_8_uchar,
       is_valid_utf_8,
       get_utf_16be_uchar,
       set_utf_16be_uchar,
       is_valid_utf_16be,
       get_utf_16le_uchar,
       set_utf_16le_uchar,
       is_valid_utf_16le,
       caml_bytes_get,
       get_int8,
       caml_bytes_get16,
       get_uint16_be,
       get_uint16_le,
       get_int16_ne,
       get_int16_be,
       get_int16_le,
       caml_bytes_get32,
       get_int32_be,
       get_int32_le,
       caml_bytes_get64,
       get_int64_be,
       get_int64_le,
       set_uint8,
       caml_bytes_set,
       set_uint16_ne,
       set_int16_be,
       set_int16_le,
       caml_bytes_set16,
       set_int16_be,
       set_int16_le,
       caml_bytes_set32,
       set_int32_be,
       set_int32_le,
       caml_bytes_set64,
       set_int64_be,
       set_int64_le];
   runtime.caml_register_global(30, Stdlib_Bytes, "Stdlib__Bytes");
   return;
  }
  (globalThis));

//# 4971 "../.js/default/stdlib/stdlib.cma.js"
(function
  (globalThis){
   "use strict";
   var
    runtime = globalThis.jsoo_runtime,
    cst$0 = "",
    caml_blit_string = runtime.caml_blit_string,
    caml_maybe_attach_backtrace = runtime.caml_maybe_attach_backtrace,
    caml_ml_string_length = runtime.caml_ml_string_length,
    caml_string_equal = runtime.caml_string_equal,
    caml_string_unsafe_get = runtime.caml_string_unsafe_get,
    caml_wrap_exception = runtime.caml_wrap_exception;
   function caml_call1(f, a0){
    return (f.l >= 0 ? f.l : f.l = f.length) == 1
            ? f(a0)
            : runtime.caml_call_gen(f, [a0]);
   }
   function caml_call2(f, a0, a1){
    return (f.l >= 0 ? f.l : f.l = f.length) == 2
            ? f(a0, a1)
            : runtime.caml_call_gen(f, [a0, a1]);
   }
   function caml_call3(f, a0, a1, a2){
    return (f.l >= 0 ? f.l : f.l = f.length) == 3
            ? f(a0, a1, a2)
            : runtime.caml_call_gen(f, [a0, a1, a2]);
   }
   var
    global_data = runtime.caml_get_global_data(),
    cst = cst$0,
    empty = cst$0,
    Stdlib = global_data.Stdlib,
    Stdlib_Bytes = global_data.Stdlib__Bytes,
    bts = Stdlib_Bytes[48],
    bos = Stdlib_Bytes[49],
    cst_String_rcontains_from_Byte =
      "String.rcontains_from / Bytes.rcontains_from",
    cst_String_contains_from_Bytes =
      "String.contains_from / Bytes.contains_from",
    cst_String_rindex_from_opt_Byt =
      "String.rindex_from_opt / Bytes.rindex_from_opt",
    cst_String_rindex_from_Bytes_r = "String.rindex_from / Bytes.rindex_from",
    cst_String_index_from_opt_Byte =
      "String.index_from_opt / Bytes.index_from_opt",
    cst_String_index_from_Bytes_in = "String.index_from / Bytes.index_from",
    cst_String_concat = "String.concat";
   function make(n, c){
    return caml_call1(bts, caml_call2(Stdlib_Bytes[1], n, c));
   }
   function init(n, f){
    return caml_call1(bts, caml_call2(Stdlib_Bytes[2], n, f));
   }
   function copy(s){
    var _ac_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call1(Stdlib_Bytes[4], _ac_));
   }
   var of_bytes = Stdlib_Bytes[6], to_bytes = Stdlib_Bytes[5];
   function sub(s, ofs, len){
    var _ab_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call3(Stdlib_Bytes[7], _ab_, ofs, len));
   }
   var fill = Stdlib_Bytes[10], blit = Stdlib_Bytes[12];
   function concat(sep, l){
    if(! l) return cst;
    var seplen = caml_ml_string_length(sep), acc = 0, param = l, pos$1 = 0;
    for(;;){
     if(param){
      var hd = param[1];
      if(param[2]){
       var
        tl = param[2],
        x = (caml_ml_string_length(hd) + seplen | 0) + acc | 0,
        acc$0 = acc <= x ? x : caml_call1(Stdlib[1], cst_String_concat),
        acc = acc$0,
        param = tl;
       continue;
      }
      var _aa_ = caml_ml_string_length(hd) + acc | 0;
     }
     else
      var _aa_ = acc;
     var dst = runtime.caml_create_bytes(_aa_), pos = pos$1, param$0 = l;
     for(;;){
      if(param$0){
       var hd$0 = param$0[1];
       if(param$0[2]){
        var tl$0 = param$0[2];
        caml_blit_string(hd$0, 0, dst, pos, caml_ml_string_length(hd$0));
        caml_blit_string
         (sep, 0, dst, pos + caml_ml_string_length(hd$0) | 0, seplen);
        var
         pos$0 = (pos + caml_ml_string_length(hd$0) | 0) + seplen | 0,
         pos = pos$0,
         param$0 = tl$0;
        continue;
       }
       caml_blit_string(hd$0, 0, dst, pos, caml_ml_string_length(hd$0));
      }
      return caml_call1(bts, dst);
     }
    }
   }
   var cat = Stdlib[28];
   function iter(f, s){
    var ___ = caml_ml_string_length(s) - 1 | 0, _Z_ = 0;
    if(___ >= 0){
     var i = _Z_;
     for(;;){
      caml_call1(f, caml_string_unsafe_get(s, i));
      var _$_ = i + 1 | 0;
      if(___ !== i){var i = _$_; continue;}
      break;
     }
    }
    return 0;
   }
   function iteri(f, s){
    var _X_ = caml_ml_string_length(s) - 1 | 0, _W_ = 0;
    if(_X_ >= 0){
     var i = _W_;
     for(;;){
      caml_call2(f, i, caml_string_unsafe_get(s, i));
      var _Y_ = i + 1 | 0;
      if(_X_ !== i){var i = _Y_; continue;}
      break;
     }
    }
    return 0;
   }
   function map(f, s){
    var _V_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call2(Stdlib_Bytes[17], f, _V_));
   }
   function mapi(f, s){
    var _U_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call2(Stdlib_Bytes[18], f, _U_));
   }
   function fold_right(f, x, a){
    var _T_ = caml_call1(bos, x);
    return caml_call3(Stdlib_Bytes[20], f, _T_, a);
   }
   function fold_left(f, a, x){
    var _S_ = caml_call1(bos, x);
    return caml_call3(Stdlib_Bytes[19], f, a, _S_);
   }
   function exists(f, s){
    var _R_ = caml_call1(bos, s);
    return caml_call2(Stdlib_Bytes[22], f, _R_);
   }
   function for_all(f, s){
    var _Q_ = caml_call1(bos, s);
    return caml_call2(Stdlib_Bytes[21], f, _Q_);
   }
   function is_space(param){
    var _P_ = param - 9 | 0, switch$0 = 0;
    if(4 < _P_ >>> 0){
     if(23 === _P_) switch$0 = 1;
    }
    else if(2 !== _P_) switch$0 = 1;
    return switch$0 ? 1 : 0;
   }
   function trim(s){
    if(caml_string_equal(s, cst$0)) return s;
    if
     (!
      is_space(caml_string_unsafe_get(s, 0))
      &&
       !
       is_space(caml_string_unsafe_get(s, caml_ml_string_length(s) - 1 | 0)))
     return s;
    var _O_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call1(Stdlib_Bytes[23], _O_));
   }
   function escaped(s){
    var n = caml_ml_string_length(s), i = 0;
    for(;;){
     if(n <= i) return s;
     var _M_ = caml_string_unsafe_get(s, i) - 32 | 0, switch$0 = 0;
     if(59 < _M_ >>> 0){
      if(33 < _M_ - 61 >>> 0) switch$0 = 1;
     }
     else if(2 === _M_) switch$0 = 1;
     if(switch$0){
      var _N_ = caml_call1(bos, s);
      return caml_call1(bts, caml_call1(Stdlib_Bytes[24], _N_));
     }
     var i$0 = i + 1 | 0, i = i$0;
    }
   }
   function index_rec(s, lim, i, c){
    var i$0 = i;
    for(;;){
     if(lim <= i$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     if(caml_string_unsafe_get(s, i$0) === c) return i$0;
     var i$1 = i$0 + 1 | 0, i$0 = i$1;
    }
   }
   function index(s, c){return index_rec(s, caml_ml_string_length(s), 0, c);}
   function index_rec_opt(s, lim, i, c){
    var i$0 = i;
    for(;;){
     if(lim <= i$0) return 0;
     if(caml_string_unsafe_get(s, i$0) === c) return [0, i$0];
     var i$1 = i$0 + 1 | 0, i$0 = i$1;
    }
   }
   function index_opt(s, c){
    return index_rec_opt(s, caml_ml_string_length(s), 0, c);
   }
   function index_from(s, i, c){
    var l = caml_ml_string_length(s);
    if(0 <= i && l >= i) return index_rec(s, l, i, c);
    return caml_call1(Stdlib[1], cst_String_index_from_Bytes_in);
   }
   function index_from_opt(s, i, c){
    var l = caml_ml_string_length(s);
    if(0 <= i && l >= i) return index_rec_opt(s, l, i, c);
    return caml_call1(Stdlib[1], cst_String_index_from_opt_Byte);
   }
   function rindex_rec(s, i, c){
    var i$0 = i;
    for(;;){
     if(0 > i$0) throw caml_maybe_attach_backtrace(Stdlib[8], 1);
     if(caml_string_unsafe_get(s, i$0) === c) return i$0;
     var i$1 = i$0 - 1 | 0, i$0 = i$1;
    }
   }
   function rindex(s, c){
    return rindex_rec(s, caml_ml_string_length(s) - 1 | 0, c);
   }
   function rindex_from(s, i, c){
    if(-1 <= i && caml_ml_string_length(s) > i) return rindex_rec(s, i, c);
    return caml_call1(Stdlib[1], cst_String_rindex_from_Bytes_r);
   }
   function rindex_rec_opt(s, i, c){
    var i$0 = i;
    for(;;){
     if(0 > i$0) return 0;
     if(caml_string_unsafe_get(s, i$0) === c) return [0, i$0];
     var i$1 = i$0 - 1 | 0, i$0 = i$1;
    }
   }
   function rindex_opt(s, c){
    return rindex_rec_opt(s, caml_ml_string_length(s) - 1 | 0, c);
   }
   function rindex_from_opt(s, i, c){
    if(-1 <= i && caml_ml_string_length(s) > i)
     return rindex_rec_opt(s, i, c);
    return caml_call1(Stdlib[1], cst_String_rindex_from_opt_Byt);
   }
   function contains_from(s, i, c){
    var l = caml_ml_string_length(s);
    if(0 <= i && l >= i)
     try{index_rec(s, l, i, c); var _K_ = 1; return _K_;}
     catch(_L_){
      var _J_ = caml_wrap_exception(_L_);
      if(_J_ === Stdlib[8]) return 0;
      throw caml_maybe_attach_backtrace(_J_, 0);
     }
    return caml_call1(Stdlib[1], cst_String_contains_from_Bytes);
   }
   function contains(s, c){return contains_from(s, 0, c);}
   function rcontains_from(s, i, c){
    if(0 <= i && caml_ml_string_length(s) > i)
     try{rindex_rec(s, i, c); var _H_ = 1; return _H_;}
     catch(_I_){
      var _G_ = caml_wrap_exception(_I_);
      if(_G_ === Stdlib[8]) return 0;
      throw caml_maybe_attach_backtrace(_G_, 0);
     }
    return caml_call1(Stdlib[1], cst_String_rcontains_from_Byte);
   }
   function uppercase_ascii(s){
    var _F_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call1(Stdlib_Bytes[40], _F_));
   }
   function lowercase_ascii(s){
    var _E_ = caml_call1(bos, s);
    return caml_call1(bts, caml_call1(Stdlib_Bytes[41], _E_));
   }
   function capitalize_ascii(s){
    var _D_ = 