/*! * Copyright (c) HANDSONCODE sp. z o. o. * * HANDSONTABLE is a software distributed by HANDSONCODE sp. z o. o., a Polish corporation based in * Gdynia, Poland, at Aleja Zwyciestwa 96-98, registered by the District Court in Gdansk under number * 538651, EU tax ID number: PL5862294002, share capital: PLN 62,800.00. * * This software is protected by applicable copyright laws, including international treaties, and dual- * licensed - depending on whether your use for commercial purposes, meaning intended for or * resulting in commercial advantage or monetary compensation, or not. * * If your use is strictly personal or solely for evaluation purposes, meaning for the purposes of testing * the suitability, performance, and usefulness of this software outside the production environment, * you agree to be bound by the terms included in the "handsontable-non-commercial-license.pdf" file. * * Your use of this software for commercial purposes is subject to the terms included in an applicable * license agreement. * * In any case, you must not make any such use of this software as to develop software which may be * considered competitive with this software. * * UNLESS EXPRESSLY AGREED OTHERWISE, HANDSONCODE PROVIDES THIS SOFTWARE ON AN "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, AND IN NO EVENT AND UNDER NO * LEGAL THEORY, SHALL HANDSONCODE BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING FROM * USE OR INABILITY TO USE THIS SOFTWARE. * * Version: 14.6.2 * Release date: 10/02/2025 (built at 07/02/2025 16:13:25) */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("Handsontable", [], factory); else if(typeof exports === 'object') exports["Handsontable"] = factory(); else root["Handsontable"] = factory(); })(typeof self !== 'undefined' ? self : this, () => { return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ([ /* 0 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AlwaysDense: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.AlwaysDense), /* harmony export */ AlwaysSparse: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.AlwaysSparse), /* harmony export */ ArraySize: () => (/* reexport safe */ _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize), /* harmony export */ CellError: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError), /* harmony export */ CellType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellType), /* harmony export */ CellValueDetailedType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueDetailedType), /* harmony export */ CellValueType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueType), /* harmony export */ ConfigValueTooBigError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooBigError), /* harmony export */ ConfigValueTooSmallError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooSmallError), /* harmony export */ DenseSparseChooseBasedOnThreshold: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.DenseSparseChooseBasedOnThreshold), /* harmony export */ DetailedCellError: () => (/* reexport safe */ _CellValue__WEBPACK_IMPORTED_MODULE_2__.DetailedCellError), /* harmony export */ EmptyValue: () => (/* reexport safe */ _interpreter__WEBPACK_IMPORTED_MODULE_9__.EmptyValue), /* harmony export */ ErrorType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType), /* harmony export */ EvaluationSuspendedError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.EvaluationSuspendedError), /* harmony export */ ExpectedOneOfValuesError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedOneOfValuesError), /* harmony export */ ExpectedValueOfTypeError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedValueOfTypeError), /* harmony export */ ExportedCellChange: () => (/* reexport safe */ _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedCellChange), /* harmony export */ ExportedNamedExpressionChange: () => (/* reexport safe */ _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedNamedExpressionChange), /* harmony export */ FunctionArgumentType: () => (/* reexport safe */ _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionArgumentType), /* harmony export */ FunctionPlugin: () => (/* reexport safe */ _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionPlugin), /* harmony export */ FunctionPluginValidationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.FunctionPluginValidationError), /* harmony export */ HyperFormula: () => (/* reexport safe */ _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula), /* harmony export */ InvalidAddressError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidAddressError), /* harmony export */ InvalidArgumentsError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidArgumentsError), /* harmony export */ LanguageAlreadyRegisteredError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageAlreadyRegisteredError), /* harmony export */ LanguageNotRegisteredError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageNotRegisteredError), /* harmony export */ MissingTranslationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.MissingTranslationError), /* harmony export */ NamedExpressionDoesNotExistError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionDoesNotExistError), /* harmony export */ NamedExpressionNameIsAlreadyTakenError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsAlreadyTakenError), /* harmony export */ NamedExpressionNameIsInvalidError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsInvalidError), /* harmony export */ NoOperationToRedoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToRedoError), /* harmony export */ NoOperationToUndoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToUndoError), /* harmony export */ NoRelativeAddressesAllowedError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoRelativeAddressesAllowedError), /* harmony export */ NoSheetWithIdError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithIdError), /* harmony export */ NoSheetWithNameError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithNameError), /* harmony export */ NotAFormulaError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NotAFormulaError), /* harmony export */ NothingToPasteError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NothingToPasteError), /* harmony export */ ProtectedFunctionTranslationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ProtectedFunctionTranslationError), /* harmony export */ SheetNameAlreadyTakenError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SheetNameAlreadyTakenError), /* harmony export */ SheetSizeLimitExceededError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SheetSizeLimitExceededError), /* harmony export */ SimpleRangeValue: () => (/* reexport safe */ _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__.SimpleRangeValue), /* harmony export */ SourceLocationHasArrayError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SourceLocationHasArrayError), /* harmony export */ TargetLocationHasArrayError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.TargetLocationHasArrayError), /* harmony export */ UnableToParseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.UnableToParseError), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _CellValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(100); /* harmony import */ var _Config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(101); /* harmony import */ var _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(105); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(77); /* harmony import */ var _Exporter__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(128); /* harmony import */ var _HyperFormula__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(110); /* harmony import */ var _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(146); /* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(96); /* harmony import */ var _interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(147); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Aggregate class for default export */ class HyperFormulaNS extends _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula {} HyperFormulaNS.HyperFormula = _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula; HyperFormulaNS.ErrorType = _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType; HyperFormulaNS.CellError = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError; HyperFormulaNS.CellType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellType; HyperFormulaNS.CellValueType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueType; HyperFormulaNS.CellValueDetailedType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueDetailedType; HyperFormulaNS.DetailedCellError = _CellValue__WEBPACK_IMPORTED_MODULE_2__.DetailedCellError; HyperFormulaNS.ExportedCellChange = _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedCellChange; HyperFormulaNS.ExportedNamedExpressionChange = _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedNamedExpressionChange; HyperFormulaNS.ConfigValueTooBigError = _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooBigError; HyperFormulaNS.ConfigValueTooSmallError = _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooSmallError; HyperFormulaNS.EvaluationSuspendedError = _errors__WEBPACK_IMPORTED_MODULE_5__.EvaluationSuspendedError; HyperFormulaNS.ExpectedOneOfValuesError = _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedOneOfValuesError; HyperFormulaNS.ExpectedValueOfTypeError = _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedValueOfTypeError; HyperFormulaNS.ArraySize = _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize; HyperFormulaNS.SimpleRangeValue = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__.SimpleRangeValue; HyperFormulaNS.EmptyValue = _interpreter__WEBPACK_IMPORTED_MODULE_9__.EmptyValue; HyperFormulaNS.FunctionPlugin = _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionPlugin; HyperFormulaNS.FunctionArgumentType = _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionArgumentType; HyperFormulaNS.FunctionPluginValidationError = _errors__WEBPACK_IMPORTED_MODULE_5__.FunctionPluginValidationError; HyperFormulaNS.InvalidAddressError = _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidAddressError; HyperFormulaNS.InvalidArgumentsError = _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidArgumentsError; HyperFormulaNS.LanguageNotRegisteredError = _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageNotRegisteredError; HyperFormulaNS.LanguageAlreadyRegisteredError = _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageAlreadyRegisteredError; HyperFormulaNS.MissingTranslationError = _errors__WEBPACK_IMPORTED_MODULE_5__.MissingTranslationError; HyperFormulaNS.NamedExpressionDoesNotExistError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionDoesNotExistError; HyperFormulaNS.NamedExpressionNameIsAlreadyTakenError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsAlreadyTakenError; HyperFormulaNS.NamedExpressionNameIsInvalidError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsInvalidError; HyperFormulaNS.NoOperationToRedoError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToRedoError; HyperFormulaNS.NoOperationToUndoError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToUndoError; HyperFormulaNS.NoRelativeAddressesAllowedError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoRelativeAddressesAllowedError; HyperFormulaNS.NoSheetWithIdError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithIdError; HyperFormulaNS.NoSheetWithNameError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithNameError; HyperFormulaNS.NotAFormulaError = _errors__WEBPACK_IMPORTED_MODULE_5__.NotAFormulaError; HyperFormulaNS.NothingToPasteError = _errors__WEBPACK_IMPORTED_MODULE_5__.NothingToPasteError; HyperFormulaNS.ProtectedFunctionTranslationError = _errors__WEBPACK_IMPORTED_MODULE_5__.ProtectedFunctionTranslationError; HyperFormulaNS.SheetNameAlreadyTakenError = _errors__WEBPACK_IMPORTED_MODULE_5__.SheetNameAlreadyTakenError; HyperFormulaNS.SheetSizeLimitExceededError = _errors__WEBPACK_IMPORTED_MODULE_5__.SheetSizeLimitExceededError; HyperFormulaNS.SourceLocationHasArrayError = _errors__WEBPACK_IMPORTED_MODULE_5__.SourceLocationHasArrayError; HyperFormulaNS.TargetLocationHasArrayError = _errors__WEBPACK_IMPORTED_MODULE_5__.TargetLocationHasArrayError; HyperFormulaNS.UnableToParseError = _errors__WEBPACK_IMPORTED_MODULE_5__.UnableToParseError; const defaultLanguage = _Config__WEBPACK_IMPORTED_MODULE_3__.Config.defaultConfig.language; _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.registerLanguage(defaultLanguage, _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"]); _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.languages[_i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"].langCode] = _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"]; for (const pluginName of Object.getOwnPropertyNames(_interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__)) { if (!pluginName.startsWith('_')) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.registerFunctionPlugin(_interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__[pluginName]); } } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (HyperFormulaNS); /*** EXPORTS FROM exports-to-window-loader ***/ window['HyperFormula'] = (__webpack_require__(0)["default"]); /***/ }), /* 1 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArraySize: () => (/* binding */ ArraySize), /* harmony export */ ArraySizePredictor: () => (/* binding */ ArraySizePredictor) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(95); /* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(96); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ArraySize { constructor(width, height, isRef = false) { this.width = width; this.height = height; this.isRef = isRef; } static error() { return new ArraySize(1, 1, true); } static scalar() { return new ArraySize(1, 1, false); } isScalar() { return this.width === 1 && this.height === 1 || this.isRef; } } function arraySizeForBinaryOp(leftArraySize, rightArraySize) { return new ArraySize(Math.max(leftArraySize.width, rightArraySize.width), Math.max(leftArraySize.height, rightArraySize.height)); } function arraySizeForUnaryOp(arraySize) { return new ArraySize(arraySize.width, arraySize.height); } class ArraySizePredictor { constructor(config, functionRegistry) { this.config = config; this.functionRegistry = functionRegistry; } checkArraySize(ast, formulaAddress) { return this.checkArraySizeForAst(ast, { formulaAddress, arraysFlag: this.config.useArrayArithmetic }); } checkArraySizeForAst(ast, state) { switch (ast.type) { case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.FUNCTION_CALL: { return this.checkArraySizeForFunction(ast, state); } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE: { const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromAstOrUndef(ast, state.formulaAddress); if (range === undefined) { return ArraySize.error(); } else { return new ArraySize(range.width(), range.height(), true); } } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ARRAY: { const heights = []; const widths = []; for (const row of ast.args) { const sizes = row.map(ast => this.checkArraySizeForAst(ast, state)); const h = Math.min(...sizes.map(size => size.height)); const w = sizes.reduce((total, size) => total + size.width, 0); heights.push(h); widths.push(w); } const height = heights.reduce((total, h) => total + h, 0); const width = Math.min(...widths); return new ArraySize(width, height); } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.STRING: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER: return ArraySize.scalar(); case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE: return new ArraySize(1, 1, true); case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.DIV_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CONCATENATE_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EQUALS_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.GREATER_THAN_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.LESS_THAN_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.LESS_THAN_OR_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NOT_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.POWER_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.TIMES_OP: { const left = this.checkArraySizeForAst(ast.left, state); const right = this.checkArraySizeForAst(ast.right, state); if (!state.arraysFlag && (left.height > 1 || left.width > 1 || right.height > 1 || right.width > 1)) { return ArraySize.error(); } return arraySizeForBinaryOp(left, right); } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_UNARY_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_UNARY_OP: case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PERCENT_OP: { const val = this.checkArraySizeForAst(ast.value, state); if (!state.arraysFlag && (val.height > 1 || val.width > 1)) { return ArraySize.error(); } return arraySizeForUnaryOp(val); } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS: { return this.checkArraySizeForAst(ast.expression, state); } case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY: return ArraySize.error(); default: return ArraySize.error(); } } checkArraySizeForFunction(ast, state) { const pluginArraySizeFunction = this.functionRegistry.getArraySizeFunction(ast.procedureName); if (pluginArraySizeFunction !== undefined) { return pluginArraySizeFunction(ast, state); } const metadata = this.functionRegistry.getMetadata(ast.procedureName); if (metadata === undefined || metadata.expandRanges || !state.arraysFlag || metadata.vectorizationForbidden || metadata.parameters === undefined) { return new ArraySize(1, 1); } const subChecks = ast.args.map(arg => { var _a; return this.checkArraySizeForAst(arg, new _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_1__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); const argumentDefinitions = [...metadata.parameters]; if (metadata.repeatLastArgs !== undefined && argumentDefinitions.length < subChecks.length && (subChecks.length - argumentDefinitions.length) % metadata.repeatLastArgs !== 0) { return ArraySize.error(); } while (argumentDefinitions.length < subChecks.length) { if (metadata.repeatLastArgs === undefined) { return ArraySize.error(); } argumentDefinitions.push(...argumentDefinitions.slice(argumentDefinitions.length - metadata.repeatLastArgs)); } let maxWidth = 1; let maxHeight = 1; for (let i = 0; i < subChecks.length; i++) { if (argumentDefinitions[i].argumentType !== _interpreter__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE && argumentDefinitions[i].argumentType !== _interpreter__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.ANY) { maxHeight = Math.max(maxHeight, subChecks[i].height); maxWidth = Math.max(maxWidth, subChecks[i].width); } } return new ArraySize(maxWidth, maxHeight); } } /***/ }), /* 2 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AbsoluteCellRange: () => (/* binding */ AbsoluteCellRange), /* harmony export */ AbsoluteColumnRange: () => (/* binding */ AbsoluteColumnRange), /* harmony export */ AbsoluteRowRange: () => (/* binding */ AbsoluteRowRange), /* harmony export */ WRONG_RANGE_SIZE: () => (/* binding */ WRONG_RANGE_SIZE), /* harmony export */ isSimpleCellRange: () => (/* binding */ isSimpleCellRange), /* harmony export */ simpleCellRange: () => (/* binding */ simpleCellRange) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); /* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(71); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const WRONG_RANGE_SIZE = 'AbsoluteCellRange: Wrong range size'; function isSimpleCellRange(obj) { if (obj && (typeof obj === 'object' || typeof obj === 'function')) { return 'start' in obj && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellAddress)(obj.start) && 'end' in obj && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellAddress)(obj.end); } else { return false; } } const simpleCellRange = (start, end) => ({ start, end }); class AbsoluteCellRange { constructor(start, end) { if (start.sheet !== end.sheet) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet); } this.start = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(start.sheet, start.col, start.row); this.end = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(end.sheet, end.col, end.row); } get sheet() { return this.start.sheet; } static fromSimpleCellAddresses(start, end) { if (start.sheet !== end.sheet) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet); } const width = end.col - start.col; const height = end.row - start.row; if (Number.isFinite(height) && Number.isFinite(width)) { return new AbsoluteCellRange(start, end); } if (Number.isFinite(height)) { return new AbsoluteRowRange(start.sheet, start.row, end.row); } return new AbsoluteColumnRange(start.sheet, start.col, end.col); } static fromAst(ast, baseAddress) { if (ast.type === _parser__WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE) { return AbsoluteCellRange.fromCellRange(ast, baseAddress); } else if (ast.type === _parser__WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE) { return AbsoluteColumnRange.fromColumnRange(ast, baseAddress); } else { return AbsoluteRowRange.fromRowRangeAst(ast, baseAddress); } } static fromAstOrUndef(ast, baseAddress) { try { return AbsoluteCellRange.fromAst(ast, baseAddress); } catch (_e) { return undefined; } } static fromCellRange(x, baseAddress) { return new AbsoluteCellRange(x.start.toSimpleCellAddress(baseAddress), x.end.toSimpleCellAddress(baseAddress)); } static spanFrom(topLeftCorner, width, height) { const ret = AbsoluteCellRange.spanFromOrUndef(topLeftCorner, width, height); if (ret === undefined) { throw new Error(WRONG_RANGE_SIZE); } return ret; } static spanFromOrUndef(topLeftCorner, width, height) { if (!Number.isFinite(width) && Number.isFinite(height)) { if (topLeftCorner.col !== 0) { return undefined; } return new AbsoluteRowRange(topLeftCorner.sheet, topLeftCorner.row, topLeftCorner.row + height - 1); } else if (!Number.isFinite(height) && Number.isFinite(width)) { if (topLeftCorner.row !== 0) { return undefined; } return new AbsoluteColumnRange(topLeftCorner.sheet, topLeftCorner.col, topLeftCorner.col + width - 1); } else if (Number.isFinite(height) && Number.isFinite(width)) { return new AbsoluteCellRange(topLeftCorner, (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(topLeftCorner.sheet, topLeftCorner.col + width - 1, topLeftCorner.row + height - 1)); } return undefined; } static fromCoordinates(sheet, x1, y1, x2, y2) { return new AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x1, y1), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x2, y2)); } isFinite() { return Number.isFinite(this.size()); } doesOverlap(other) { if (this.start.sheet != other.start.sheet) { return false; } if (this.end.row < other.start.row || this.start.row > other.end.row) { return false; } if (this.end.col < other.start.col || this.start.col > other.end.col) { return false; } return true; } addressInRange(address) { if (this.sheet !== address.sheet) { return false; } return this.start.row <= address.row && this.end.row >= address.row && this.start.col <= address.col && this.end.col >= address.col; } columnInRange(address) { if (this.sheet !== address.sheet) { return false; } return this.start.col <= address.col && this.end.col >= address.col; } rowInRange(address) { if (this.sheet !== address.sheet) { return false; } return this.start.row <= address.row && this.end.row >= address.row; } containsRange(range) { return this.addressInRange(range.start) && this.addressInRange(range.end); } intersectionWith(other) { if (this.sheet !== other.start.sheet) { return undefined; } const startRow = Math.max(this.start.row, other.start.row); const endRow = Math.min(this.end.row, other.end.row); const startCol = Math.max(this.start.col, other.start.col); const endCol = Math.min(this.end.col, other.end.col); if (startRow > endRow || startCol > endCol) { return undefined; } return new AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, startCol, startRow), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, endCol, endRow)); } includesRow(row) { return this.start.row < row && this.end.row >= row; } includesColumn(column) { return this.start.col < column && this.end.col >= column; } shiftByRows(numberOfRows) { this.start.row += numberOfRows; this.end.row += numberOfRows; } expandByRows(numberOfRows) { this.end.row += numberOfRows; } shiftByColumns(numberOfColumns) { this.start.col += numberOfColumns; this.end.col += numberOfColumns; } shifted(byCols, byRows) { return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col + byCols, this.start.row + byRows), this.width(), this.height()); } expandByColumns(numberOfColumns) { this.end.col += numberOfColumns; } moveToSheet(toSheet) { this.start.sheet = toSheet; this.end.sheet = toSheet; } removeSpan(span) { if (span instanceof _Span__WEBPACK_IMPORTED_MODULE_3__.RowsSpan) { this.removeRows(span.start, span.end); } else { this.removeColumns(span.start, span.end); } } shouldBeRemoved() { return this.width() <= 0 || this.height() <= 0; } rangeWithSameWidth(startRow, numberOfRows) { return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col, startRow), this.width(), numberOfRows); } rangeWithSameHeight(startColumn, numberOfColumns) { return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, startColumn, this.start.row), numberOfColumns, this.height()); } toString() { return `${this.start.sheet},${this.start.col},${this.start.row},${this.end.col},${this.end.row}`; } width() { return this.end.col - this.start.col + 1; } height() { return this.end.row - this.start.row + 1; } size() { return this.height() * this.width(); } arrayOfAddressesInRange() { const result = []; for (let y = 0; y < this.height(); ++y) { result[y] = []; for (let x = 0; x < this.width(); ++x) { const value = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col + x, this.start.row + y); result[y].push(value); } } return result; } withStart(newStart) { return new AbsoluteCellRange(newStart, this.end); } sameDimensionsAs(other) { return this.width() === other.width() && this.height() === other.height(); } sameAs(other) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.equalSimpleCellAddress)(this.start, other.start) && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.equalSimpleCellAddress)(this.end, other.end); } addressesArrayMap(dependencyGraph, op) { const ret = []; let currentRow = this.start.row; while (currentRow <= this.effectiveEndRow(dependencyGraph)) { let currentColumn = this.start.col; const tmp = []; while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) { tmp.push(op((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow))); currentColumn++; } ret.push(tmp); currentRow++; } return ret; } addresses(dependencyGraph) { const ret = []; let currentRow = this.start.row; const limitRow = this.effectiveEndRow(dependencyGraph); const limitColumn = this.effectiveEndColumn(dependencyGraph); while (currentRow <= limitRow) { let currentColumn = this.start.col; while (currentColumn <= limitColumn) { ret.push((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow)); currentColumn++; } currentRow++; } return ret; } *addressesWithDirection(right, bottom, dependencyGraph) { if (right > 0) { if (bottom > 0) { let currentRow = this.effectiveEndRow(dependencyGraph); while (currentRow >= this.start.row) { let currentColumn = this.effectiveEndColumn(dependencyGraph); while (currentColumn >= this.start.col) { yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow); currentColumn -= 1; } currentRow -= 1; } } else { let currentRow = this.start.row; while (currentRow <= this.effectiveEndRow(dependencyGraph)) { let currentColumn = this.effectiveEndColumn(dependencyGraph); while (currentColumn >= this.start.col) { yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow); currentColumn -= 1; } currentRow += 1; } } } else { if (bottom > 0) { let currentRow = this.effectiveEndRow(dependencyGraph); while (currentRow >= this.start.row) { let currentColumn = this.start.col; while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) { yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow); currentColumn += 1; } currentRow -= 1; } } else { let currentRow = this.start.row; while (currentRow <= this.effectiveEndRow(dependencyGraph)) { let currentColumn = this.start.col; while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) { yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow); currentColumn += 1; } currentRow += 1; } } } } getAddress(col, row) { if (col < 0 || row < 0 || row > this.height() - 1 || col > this.width() - 1) { throw Error('Index out of bound'); } return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, this.start.col + col, this.start.row + row); } exceedsSheetSizeLimits(maxColumns, maxRows) { return this.end.col >= maxColumns || this.end.row >= maxRows; } effectiveEndColumn(_dependencyGraph) { return this.end.col; } effectiveEndRow(_dependencyGraph) { return this.end.row; } effectiveWidth(_dependencyGraph) { return this.width(); } effectiveHeight(_dependencyGraph) { return this.height(); } removeRows(rowStart, rowEnd) { if (rowStart > this.end.row) { return; } if (rowEnd < this.start.row) { const numberOfRows = rowEnd - rowStart + 1; return this.shiftByRows(-numberOfRows); } if (rowStart <= this.start.row) { this.start.row = rowStart; } this.end.row -= Math.min(rowEnd, this.end.row) - rowStart + 1; } removeColumns(columnStart, columnEnd) { if (columnStart > this.end.col) { return; } if (columnEnd < this.start.col) { const numberOfColumns = columnEnd - columnStart + 1; return this.shiftByColumns(-numberOfColumns); } if (columnStart <= this.start.col) { this.start.col = columnStart; } this.end.col -= Math.min(columnEnd, this.end.col) - columnStart + 1; } } class AbsoluteColumnRange extends AbsoluteCellRange { constructor(sheet, columnStart, columnEnd) { super((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, columnStart, 0), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, columnEnd, Number.POSITIVE_INFINITY)); } static fromColumnRange(x, baseAddress) { const start = x.start.toSimpleColumnAddress(baseAddress); const end = x.end.toSimpleColumnAddress(baseAddress); if (start.sheet !== end.sheet) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet); } return new AbsoluteColumnRange(start.sheet, start.col, end.col); } shouldBeRemoved() { return this.width() <= 0; } shiftByRows(_numberOfRows) { return; } expandByRows(_numberOfRows) { return; } shifted(byCols, _byRows) { return new AbsoluteColumnRange(this.sheet, this.start.col + byCols, this.end.col + byCols); } rangeWithSameHeight(startColumn, numberOfColumns) { return new AbsoluteColumnRange(this.sheet, startColumn, startColumn + numberOfColumns - 1); } exceedsSheetSizeLimits(maxColumns, _maxRows) { return this.end.col >= maxColumns; } effectiveEndRow(dependencyGraph) { return this.effectiveHeight(dependencyGraph) - 1; } effectiveHeight(dependencyGraph) { return dependencyGraph.getSheetHeight(this.sheet); } removeRows(_rowStart, _rowEnd) { return; } } class AbsoluteRowRange extends AbsoluteCellRange { constructor(sheet, rowStart, rowEnd) { super((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, 0, rowStart), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, Number.POSITIVE_INFINITY, rowEnd)); } static fromRowRangeAst(x, baseAddress) { const start = x.start.toSimpleRowAddress(baseAddress); const end = x.end.toSimpleRowAddress(baseAddress); if (start.sheet !== end.sheet) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet); } return new AbsoluteRowRange(start.sheet, start.row, end.row); } shouldBeRemoved() { return this.height() <= 0; } shiftByColumns(_numberOfColumns) { return; } expandByColumns(_numberOfColumns) { return; } shifted(byCols, byRows) { return new AbsoluteRowRange(this.sheet, this.start.row + byRows, this.end.row + byRows); } rangeWithSameWidth(startRow, numberOfRows) { return new AbsoluteRowRange(this.sheet, startRow, startRow + numberOfRows - 1); } exceedsSheetSizeLimits(_maxColumns, maxRows) { return this.end.row >= maxRows; } effectiveEndColumn(dependencyGraph) { return this.effectiveWidth(dependencyGraph) - 1; } effectiveWidth(dependencyGraph) { return dependencyGraph.getSheetWidth(this.sheet); } removeColumns(_columnStart, _columnEnd) { return; } } /***/ }), /* 3 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CellError: () => (/* binding */ CellError), /* harmony export */ CellType: () => (/* binding */ CellType), /* harmony export */ CellValueDetailedType: () => (/* binding */ CellValueDetailedType), /* harmony export */ CellValueJustNumber: () => (/* binding */ CellValueJustNumber), /* harmony export */ CellValueNoNumber: () => (/* binding */ CellValueNoNumber), /* harmony export */ CellValueType: () => (/* binding */ CellValueType), /* harmony export */ CellValueTypeOrd: () => (/* binding */ CellValueTypeOrd), /* harmony export */ ErrorType: () => (/* binding */ ErrorType), /* harmony export */ absoluteSheetReference: () => (/* binding */ absoluteSheetReference), /* harmony export */ addressKey: () => (/* binding */ addressKey), /* harmony export */ equalSimpleCellAddress: () => (/* binding */ equalSimpleCellAddress), /* harmony export */ getCellType: () => (/* binding */ getCellType), /* harmony export */ getCellValueDetailedType: () => (/* binding */ getCellValueDetailedType), /* harmony export */ getCellValueFormat: () => (/* binding */ getCellValueFormat), /* harmony export */ getCellValueType: () => (/* binding */ getCellValueType), /* harmony export */ invalidSimpleCellAddress: () => (/* binding */ invalidSimpleCellAddress), /* harmony export */ invalidSimpleColumnAddress: () => (/* binding */ invalidSimpleColumnAddress), /* harmony export */ invalidSimpleRowAddress: () => (/* binding */ invalidSimpleRowAddress), /* harmony export */ isSimpleCellAddress: () => (/* binding */ isSimpleCellAddress), /* harmony export */ movedSimpleCellAddress: () => (/* binding */ movedSimpleCellAddress), /* harmony export */ simpleCellAddress: () => (/* binding */ simpleCellAddress), /* harmony export */ simpleColumnAddress: () => (/* binding */ simpleColumnAddress), /* harmony export */ simpleRowAddress: () => (/* binding */ simpleRowAddress) /* harmony export */ }); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Possible errors returned by our interpreter. */ var ErrorType; (function (ErrorType) { /** Division by zero. */ ErrorType["DIV_BY_ZERO"] = "DIV_BY_ZERO"; /** Unknown function name. */ ErrorType["NAME"] = "NAME"; ErrorType["VALUE"] = "VALUE"; ErrorType["NUM"] = "NUM"; ErrorType["NA"] = "NA"; /** Cyclic dependency. */ ErrorType["CYCLE"] = "CYCLE"; /** Wrong address reference. */ ErrorType["REF"] = "REF"; /** Array spill error. */ ErrorType["SPILL"] = "SPILL"; /** Invalid/missing licence error. */ ErrorType["LIC"] = "LIC"; /** Generic error */ ErrorType["ERROR"] = "ERROR"; })(ErrorType || (ErrorType = {})); var CellType; (function (CellType) { CellType["FORMULA"] = "FORMULA"; CellType["VALUE"] = "VALUE"; CellType["ARRAY"] = "ARRAY"; CellType["EMPTY"] = "EMPTY"; CellType["ARRAYFORMULA"] = "ARRAYFORMULA"; })(CellType || (CellType = {})); const getCellType = (vertex, address) => { if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ArrayVertex) { if (vertex.isLeftCorner(address)) { return CellType.ARRAYFORMULA; } else { return CellType.ARRAY; } } if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.FormulaCellVertex || vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ParsingErrorVertex) { return CellType.FORMULA; } if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ValueCellVertex) { return CellType.VALUE; } return CellType.EMPTY; }; var CellValueNoNumber; (function (CellValueNoNumber) { CellValueNoNumber["EMPTY"] = "EMPTY"; CellValueNoNumber["NUMBER"] = "NUMBER"; CellValueNoNumber["STRING"] = "STRING"; CellValueNoNumber["BOOLEAN"] = "BOOLEAN"; CellValueNoNumber["ERROR"] = "ERROR"; })(CellValueNoNumber || (CellValueNoNumber = {})); var CellValueJustNumber; (function (CellValueJustNumber) { CellValueJustNumber["NUMBER"] = "NUMBER"; })(CellValueJustNumber || (CellValueJustNumber = {})); const CellValueType = Object.assign(Object.assign({}, CellValueNoNumber), CellValueJustNumber); const CellValueDetailedType = Object.assign(Object.assign({}, CellValueNoNumber), _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType); const CellValueTypeOrd = arg => { switch (arg) { case CellValueType.EMPTY: return 0; case CellValueType.NUMBER: return 1; case CellValueType.STRING: return 2; case CellValueType.BOOLEAN: return 3; case CellValueType.ERROR: return 4; } throw new Error('Cell value not computed'); }; const getCellValueType = cellValue => { if (cellValue === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.EmptyValue) { return CellValueType.EMPTY; } if (cellValue instanceof CellError || cellValue instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_3__.SimpleRangeValue) { return CellValueType.ERROR; } if (typeof cellValue === 'string') { return CellValueType.STRING; } else if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) { return CellValueType.NUMBER; } else if (typeof cellValue === 'boolean') { return CellValueType.BOOLEAN; } throw new Error('Cell value not computed'); }; const getCellValueDetailedType = cellValue => { if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) { return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getTypeOfExtendedNumber)(cellValue); } else { return getCellValueType(cellValue); } }; const getCellValueFormat = cellValue => { if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) { return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getFormatOfExtendedNumber)(cellValue); } else { return undefined; } }; class CellError { constructor(type, message, root) { this.type = type; this.message = message; this.root = root; } /** * Returns a CellError with a given message. * @param {string} detailedMessage - message to be displayed */ static parsingError(detailedMessage) { return new CellError(ErrorType.ERROR, `${_error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ParseError}${detailedMessage ? ' ' + detailedMessage : ''}`); } attachRootVertex(vertex) { if (this.root === undefined) { return new CellError(this.type, this.message, vertex); } else { return this; } } } const simpleRowAddress = (sheet, row) => ({ sheet, row }); const invalidSimpleRowAddress = address => address.row < 0; const simpleColumnAddress = (sheet, col) => ({ sheet, col }); const invalidSimpleColumnAddress = address => address.col < 0; const simpleCellAddress = (sheet, col, row) => ({ sheet, col, row }); const invalidSimpleCellAddress = address => address.col < 0 || address.row < 0; const movedSimpleCellAddress = (address, toSheet, toRight, toBottom) => { return simpleCellAddress(toSheet, address.col + toRight, address.row + toBottom); }; const addressKey = address => `${address.sheet},${address.row},${address.col}`; /** * Checks if the object is a simple cell address. */ function isSimpleCellAddress(obj) { var _a, _b, _c; return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof ((_a = obj) === null || _a === void 0 ? void 0 : _a.sheet) === 'number' && typeof ((_b = obj) === null || _b === void 0 ? void 0 : _b.col) === 'number' && typeof ((_c = obj) === null || _c === void 0 ? void 0 : _c.row) === 'number'; } const absoluteSheetReference = (address, baseAddress) => { var _a; return (_a = address.sheet) !== null && _a !== void 0 ? _a : baseAddress.sheet; }; const equalSimpleCellAddress = (left, right) => { return left.sheet === right.sheet && left.col === right.col && left.row === right.row; }; /***/ }), /* 4 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddressMapping: () => (/* reexport safe */ _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_1__.AddressMapping), /* harmony export */ ArrayMapping: () => (/* reexport safe */ _ArrayMapping__WEBPACK_IMPORTED_MODULE_6__.ArrayMapping), /* harmony export */ ArrayVertex: () => (/* reexport safe */ _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_7__.ArrayVertex), /* harmony export */ DenseStrategy: () => (/* reexport safe */ _AddressMapping_DenseStrategy__WEBPACK_IMPORTED_MODULE_13__.DenseStrategy), /* harmony export */ DependencyGraph: () => (/* reexport safe */ _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.DependencyGraph), /* harmony export */ EmptyCellVertex: () => (/* reexport safe */ _EmptyCellVertex__WEBPACK_IMPORTED_MODULE_8__.EmptyCellVertex), /* harmony export */ FormulaCellVertex: () => (/* reexport safe */ _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_7__.FormulaCellVertex), /* harmony export */ Graph: () => (/* reexport safe */ _Graph__WEBPACK_IMPORTED_MODULE_2__.Graph), /* harmony export */ ParsingErrorVertex: () => (/* reexport safe */ _ParsingErrorVertex__WEBPACK_IMPORTED_MODULE_10__.ParsingErrorVertex), /* harmony export */ RangeMapping: () => (/* reexport safe */ _RangeMapping__WEBPACK_IMPORTED_MODULE_4__.RangeMapping), /* harmony export */ RangeVertex: () => (/* reexport safe */ _RangeVertex__WEBPACK_IMPORTED_MODULE_11__.RangeVertex), /* harmony export */ SheetMapping: () => (/* reexport safe */ _SheetMapping__WEBPACK_IMPORTED_MODULE_5__.SheetMapping), /* harmony export */ SparseStrategy: () => (/* reexport safe */ _AddressMapping_SparseStrategy__WEBPACK_IMPORTED_MODULE_12__.SparseStrategy), /* harmony export */ TopSort: () => (/* reexport safe */ _TopSort__WEBPACK_IMPORTED_MODULE_3__.TopSort), /* harmony export */ ValueCellVertex: () => (/* reexport safe */ _ValueCellVertex__WEBPACK_IMPORTED_MODULE_9__.ValueCellVertex) /* harmony export */ }); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); /* harmony import */ var _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76); /* harmony import */ var _Graph__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(83); /* harmony import */ var _TopSort__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(84); /* harmony import */ var _RangeMapping__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(86); /* harmony import */ var _SheetMapping__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(87); /* harmony import */ var _ArrayMapping__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(78); /* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(80); /* harmony import */ var _EmptyCellVertex__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(90); /* harmony import */ var _ValueCellVertex__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(91); /* harmony import */ var _ParsingErrorVertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(92); /* harmony import */ var _RangeVertex__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(82); /* harmony import */ var _AddressMapping_SparseStrategy__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(93); /* harmony import */ var _AddressMapping_DenseStrategy__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(94); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /***/ }), /* 5 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DependencyGraph: () => (/* binding */ DependencyGraph) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); /* harmony import */ var _ContentChanges__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(68); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(61); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7); /* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(71); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(72); /* harmony import */ var ___WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(4); /* harmony import */ var _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(76); /* harmony import */ var _ArrayMapping__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(78); /* harmony import */ var _collectAddressesDependentToRange__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(79); /* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(80); /* harmony import */ var _Graph__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(83); /* harmony import */ var _RangeMapping__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(86); /* harmony import */ var _SheetMapping__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(87); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class DependencyGraph { constructor(addressMapping, rangeMapping, sheetMapping, arrayMapping, stats, lazilyTransformingAstService, functionRegistry, namedExpressions) { this.addressMapping = addressMapping; this.rangeMapping = rangeMapping; this.sheetMapping = sheetMapping; this.arrayMapping = arrayMapping; this.stats = stats; this.lazilyTransformingAstService = lazilyTransformingAstService; this.functionRegistry = functionRegistry; this.namedExpressions = namedExpressions; this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty(); this.dependencyQueryAddresses = vertex => { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { return this.rangeDependencyQuery(vertex).map(([address, _]) => address); } else { const dependenciesResult = this.formulaDependencyQuery(vertex); if (dependenciesResult !== undefined) { const [address, dependencies] = dependenciesResult; return dependencies.map(dependency => { if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) { return this.namedExpressions.namedExpressionOrPlaceholder(dependency.name, address.sheet).address; } else if ((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.isSimpleCellAddress)(dependency)) { return dependency; } else { return (0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(dependency.start, dependency.end); } }); } else { return []; } } }; this.dependencyQueryVertices = vertex => { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { return this.rangeDependencyQuery(vertex); } else { const dependenciesResult = this.formulaDependencyQuery(vertex); if (dependenciesResult !== undefined) { const [address, dependencies] = dependenciesResult; return dependencies.map(dependency => { if (dependency instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) { return [dependency.start, this.rangeMapping.fetchRange(dependency.start, dependency.end)]; } else if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) { const namedExpression = this.namedExpressions.namedExpressionOrPlaceholder(dependency.name, address.sheet); return [namedExpression.address, this.addressMapping.fetchCell(namedExpression.address)]; } else { return [dependency, this.addressMapping.fetchCell(dependency)]; } }); } else { return []; } } }; this.rangeDependencyQuery = vertex => { const allDeps = []; const { smallerRangeVertex, restRange } = this.rangeMapping.findSmallerRange(vertex.range); //checking whether this range was splitted by bruteForce or not let range; if (smallerRangeVertex !== undefined && this.graph.adjacentNodes(smallerRangeVertex).has(vertex)) { range = restRange; allDeps.push([new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(smallerRangeVertex.start, smallerRangeVertex.end), smallerRangeVertex]); } else { //did we ever need to use full range range = vertex.range; } for (const address of range.addresses(this)) { const cell = this.addressMapping.getCell(address); if (cell !== undefined) { allDeps.push([address, cell]); } } return allDeps; }; this.formulaDependencyQuery = vertex => { let formula; let address; if (vertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex) { address = vertex.getAddress(this.lazilyTransformingAstService); formula = vertex.getFormula(this.lazilyTransformingAstService); } else { return undefined; } const deps = (0,_parser__WEBPACK_IMPORTED_MODULE_7__.collectDependencies)(formula, this.functionRegistry); return [address, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(deps, address)]; }; this.graph = new _Graph__WEBPACK_IMPORTED_MODULE_15__.Graph(this.dependencyQueryVertices); } /** * Invariants: * - empty cell has associated EmptyCellVertex if and only if it is a dependency (possibly indirect, through range) to some formula */ static buildEmpty(lazilyTransformingAstService, config, functionRegistry, namedExpressions, stats) { return new DependencyGraph(new _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_11__.AddressMapping(config.chooseAddressMappingPolicy), new _RangeMapping__WEBPACK_IMPORTED_MODULE_16__.RangeMapping(), new _SheetMapping__WEBPACK_IMPORTED_MODULE_17__.SheetMapping(config.translationPackage), new _ArrayMapping__WEBPACK_IMPORTED_MODULE_12__.ArrayMapping(), stats, lazilyTransformingAstService, functionRegistry, namedExpressions); } setFormulaToCell(address, ast, dependencies, size, hasVolatileFunction, hasStructuralChangeFunction) { const newVertex = _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex.fromAst(ast, address, size, this.lazilyTransformingAstService.version()); this.exchangeOrAddFormulaVertex(newVertex); this.processCellDependencies(dependencies, newVertex); this.graph.markNodeAsDirty(newVertex); if (hasVolatileFunction) { this.markAsVolatile(newVertex); } if (hasStructuralChangeFunction) { this.markAsDependentOnStructureChange(newVertex); } this.correctInfiniteRangesDependency(address); return this.getAndClearContentChanges(); } setParsingErrorToCell(address, errorVertex) { const vertex = this.shrinkPossibleArrayAndGetCell(address); this.exchangeOrAddGraphNode(vertex, errorVertex); this.addressMapping.setCell(address, errorVertex); this.graph.markNodeAsDirty(errorVertex); this.correctInfiniteRangesDependency(address); return this.getAndClearContentChanges(); } setValueToCell(address, value) { const vertex = this.shrinkPossibleArrayAndGetCell(address); if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { this.arrayMapping.removeArray(vertex.getRange()); } if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ValueCellVertex) { const oldValues = vertex.getValues(); if (oldValues.rawValue !== value.rawValue) { vertex.setValues(value); this.graph.markNodeAsDirty(vertex); } } else { const newVertex = new ___WEBPACK_IMPORTED_MODULE_10__.ValueCellVertex(value.parsedValue, value.rawValue); this.exchangeOrAddGraphNode(vertex, newVertex); this.addressMapping.setCell(address, newVertex); this.graph.markNodeAsDirty(newVertex); } this.correctInfiniteRangesDependency(address); return this.getAndClearContentChanges(); } setCellEmpty(address) { const vertex = this.shrinkPossibleArrayAndGetCell(address); if (vertex === undefined) { return _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty(); } if (this.graph.adjacentNodes(vertex).size > 0) { const emptyVertex = new ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex(); this.exchangeGraphNode(vertex, emptyVertex); if (this.graph.adjacentNodesCount(emptyVertex) === 0) { this.removeVertex(emptyVertex); this.addressMapping.removeCell(address); } else { this.graph.markNodeAsDirty(emptyVertex); this.addressMapping.setCell(address, emptyVertex); } } else { this.removeVertex(vertex); this.addressMapping.removeCell(address); } return this.getAndClearContentChanges(); } clearDirtyVertices() { this.graph.clearDirtyNodes(); } verticesToRecompute() { return this.graph.getDirtyAndVolatileNodes(); } processCellDependencies(cellDependencies, endVertex) { const endVertexId = this.graph.getNodeId(endVertex); cellDependencies.forEach(dep => { if (dep instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) { const range = dep; let rangeVertex = this.getRange(range.start, range.end); if (rangeVertex === undefined) { rangeVertex = new ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex(range); this.rangeMapping.setRange(rangeVertex); } this.graph.addNodeAndReturnId(rangeVertex); const rangeVertexId = this.graph.getNodeId(rangeVertex); if (!range.isFinite()) { this.graph.markNodeAsInfiniteRange(rangeVertexId); } const { smallerRangeVertex, restRange } = this.rangeMapping.findSmallerRange(range); if (smallerRangeVertex !== undefined) { this.graph.addEdge(smallerRangeVertex, rangeVertexId); if (rangeVertex.bruteForce) { rangeVertex.bruteForce = false; for (const cellFromRange of range.addresses(this)) { //if we ever switch heuristic to processing by sorted sizes, this would be unnecessary this.graph.removeEdge(this.fetchCell(cellFromRange), rangeVertexId); } } } else { rangeVertex.bruteForce = true; } const array = this.arrayMapping.getArray(restRange); if (array !== undefined) { this.graph.addEdge(array, rangeVertexId); } else { for (const cellFromRange of restRange.addresses(this)) { const { vertex, id } = this.fetchCellOrCreateEmpty(cellFromRange); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, rangeVertexId); } } this.graph.addEdge(rangeVertexId, endVertexId); if (range.isFinite()) { this.correctInfiniteRangesDependenciesByRangeVertex(rangeVertex); } } else if (dep instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) { const sheetOfVertex = endVertex.getAddress(this.lazilyTransformingAstService).sheet; const { vertex, id } = this.fetchNamedExpressionVertex(dep.name, sheetOfVertex); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, endVertexId); } else { const { vertex, id } = this.fetchCellOrCreateEmpty(dep); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, endVertexId); } }); } fetchNamedExpressionVertex(expressionName, sheetId) { const namedExpression = this.namedExpressions.namedExpressionOrPlaceholder(expressionName, sheetId); return this.fetchCellOrCreateEmpty(namedExpression.address); } exchangeNode(addressFrom, addressTo) { const vertexFrom = this.fetchCellOrCreateEmpty(addressFrom).vertex; const vertexTo = this.fetchCellOrCreateEmpty(addressTo).vertex; this.addressMapping.removeCell(addressFrom); this.exchangeGraphNode(vertexFrom, vertexTo); } fetchCellOrCreateEmpty(address) { const existingVertex = this.addressMapping.getCell(address); if (existingVertex !== undefined) { return { vertex: existingVertex, id: undefined }; } const newVertex = new ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex(); const newVertexId = this.graph.addNodeAndReturnId(newVertex); this.addressMapping.setCell(address, newVertex); return { vertex: newVertex, id: newVertexId }; } removeRows(removedRows) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { this.graph.markNodeAsDirty(adjacentNode); } if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { if (vertex.isLeftCorner(address)) { this.shrinkArrayToCorner(vertex); this.arrayMapping.removeArray(vertex.getRange()); } else { continue; } } this.removeVertex(vertex); } }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.removeRows(removedRows); }); const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => { const affectedRanges = this.truncateRanges(removedRows, address => address.row); return this.getArrayVerticesRelatedToRanges(affectedRanges); }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => { this.fixArraysAfterRemovingRows(removedRows.sheet, removedRows.rowStart, removedRows.numberOfRows); }); this.addStructuralNodesToChangeSet(); return { affectedArrays, contentChanges: this.getAndClearContentChanges() }; } removeSheet(removedSheetId) { this.clearSheet(removedSheetId); for (const [adr, vertex] of this.addressMapping.sheetEntries(removedSheetId)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { this.graph.markNodeAsDirty(adjacentNode); } this.removeVertex(vertex); this.addressMapping.removeCell(adr); } this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => { const rangesToRemove = this.rangeMapping.removeRangesInSheet(removedSheetId); for (const range of rangesToRemove) { this.removeVertex(range); } this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.removeSheet(removedSheetId); }); }); } clearSheet(sheetId) { const arrays = new Set(); for (const [address, vertex] of this.addressMapping.sheetEntries(sheetId)) { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { arrays.add(vertex); } else { this.setCellEmpty(address); } } for (const array of arrays.values()) { this.setArrayEmpty(array); } this.addStructuralNodesToChangeSet(); } removeColumns(removedColumns) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_GRAPH, () => { for (const [address, vertex] of this.addressMapping.entriesFromColumnsSpan(removedColumns)) { for (const adjacentNode of this.graph.adjacentNodes(vertex)) { this.graph.markNodeAsDirty(adjacentNode); } if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { if (vertex.isLeftCorner(address)) { this.shrinkArrayToCorner(vertex); this.arrayMapping.removeArray(vertex.getRange()); } else { continue; } } this.removeVertex(vertex); } }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.removeColumns(removedColumns); }); const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => { const affectedRanges = this.truncateRanges(removedColumns, address => address.col); return this.getArrayVerticesRelatedToRanges(affectedRanges); }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => { return this.fixArraysAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns); }); this.addStructuralNodesToChangeSet(); return { affectedArrays, contentChanges: this.getAndClearContentChanges() }; } addRows(addedRows) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows); }); const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows); this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows); return this.getArrayVerticesRelatedToRanges(result.verticesWithChangedSize); }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => { this.fixArraysAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows); }); for (const vertex of this.addressMapping.verticesFromRowsSpan(addedRows)) { this.graph.markNodeAsDirty(vertex); } this.addStructuralNodesToChangeSet(); return { affectedArrays }; } addColumns(addedColumns) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => { this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns); }); const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => { const result = this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns); this.fixRangesWhenAddingColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns); return this.getArrayVerticesRelatedToRanges(result.verticesWithChangedSize); }); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => { return this.fixArraysAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns); }); for (const vertex of this.addressMapping.verticesFromColumnsSpan(addedColumns)) { this.graph.markNodeAsDirty(vertex); } this.addStructuralNodesToChangeSet(); return { affectedArrays, contentChanges: this.getAndClearContentChanges() }; } isThereSpaceForArray(arrayVertex) { const range = arrayVertex.getRangeOrUndef(); if (range === undefined) { return false; } for (const address of range.addresses(this)) { const vertexUnderAddress = this.addressMapping.getCell(address); if (vertexUnderAddress !== undefined && !(vertexUnderAddress instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) && vertexUnderAddress !== arrayVertex) { return false; } } return true; } moveCells(sourceRange, toRight, toBottom, toSheet) { for (const sourceAddress of sourceRange.addressesWithDirection(toRight, toBottom, this)) { const targetAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(toSheet, sourceAddress.col + toRight, sourceAddress.row + toBottom); let sourceVertex = this.addressMapping.getCell(sourceAddress); const targetVertex = this.addressMapping.getCell(targetAddress); this.addressMapping.removeCell(sourceAddress); if (sourceVertex !== undefined) { this.graph.markNodeAsDirty(sourceVertex); this.addressMapping.setCell(targetAddress, sourceVertex); let emptyVertex = undefined; for (const adjacentNode of this.graph.adjacentNodes(sourceVertex)) { if (adjacentNode instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex && !sourceRange.containsRange(adjacentNode.range)) { emptyVertex = emptyVertex !== null && emptyVertex !== void 0 ? emptyVertex : this.fetchCellOrCreateEmpty(sourceAddress).vertex; this.graph.addEdge(emptyVertex, adjacentNode); this.graph.removeEdge(sourceVertex, adjacentNode); } } if (emptyVertex) { this.graph.markNodeAsDirty(emptyVertex); this.addressMapping.setCell(sourceAddress, emptyVertex); } } if (targetVertex !== undefined) { if (sourceVertex === undefined) { this.addressMapping.removeCell(targetAddress); } for (const adjacentNode of this.graph.adjacentNodes(targetVertex)) { sourceVertex = sourceVertex !== null && sourceVertex !== void 0 ? sourceVertex : this.fetchCellOrCreateEmpty(targetAddress).vertex; this.graph.addEdge(sourceVertex, adjacentNode); this.graph.markNodeAsDirty(sourceVertex); } this.removeVertex(targetVertex); } } for (const rangeVertex of this.rangeMapping.rangeVerticesContainedInRange(sourceRange)) { for (const adjacentNode of this.graph.adjacentNodes(rangeVertex)) { if (adjacentNode instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex && !sourceRange.containsRange(adjacentNode.range)) { this.graph.removeEdge(rangeVertex, adjacentNode); for (const address of rangeVertex.range.addresses(this)) { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, adjacentNode); this.addressMapping.setCell(address, vertex); this.graph.markNodeAsDirty(vertex); } } } } this.rangeMapping.moveRangesInsideSourceRange(sourceRange, toRight, toBottom, toSheet); } setArrayEmpty(arrayVertex) { const arrayRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(arrayVertex.getAddress(this.lazilyTransformingAstService), arrayVertex.width, arrayVertex.height); const adjacentNodes = this.graph.adjacentNodes(arrayVertex); for (const address of arrayRange.addresses(this)) { this.addressMapping.removeCell(address); } for (const adjacentNode of adjacentNodes.values()) { const nodeDependencies = (0,_collectAddressesDependentToRange__WEBPACK_IMPORTED_MODULE_13__.collectAddressesDependentToRange)(this.functionRegistry, adjacentNode, arrayVertex.getRange(), this.lazilyTransformingAstService, this); for (const address of nodeDependencies) { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, adjacentNode); } if (nodeDependencies.length > 0) { this.graph.markNodeAsDirty(adjacentNode); } } this.removeVertex(arrayVertex); this.arrayMapping.removeArray(arrayVertex.getRange()); } addVertex(address, vertex) { this.graph.addNodeAndReturnId(vertex); this.addressMapping.setCell(address, vertex); } addArrayVertex(address, vertex) { this.graph.addNodeAndReturnId(vertex); this.setAddressMappingForArrayVertex(vertex, address); } *arrayFormulaNodes() { for (const vertex of this.graph.getNodes()) { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { yield vertex; } } } *entriesFromRowsSpan(rowsSpan) { yield* this.addressMapping.entriesFromRowsSpan(rowsSpan); } *entriesFromColumnsSpan(columnsSpan) { yield* this.addressMapping.entriesFromColumnsSpan(columnsSpan); } fetchCell(address) { return this.addressMapping.fetchCell(address); } getCell(address) { return this.addressMapping.getCell(address); } getCellValue(address) { return this.addressMapping.getCellValue(address); } getRawValue(address) { return this.addressMapping.getRawValue(address); } getScalarValue(address) { const value = this.addressMapping.getCellValue(address); if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.ScalarExpected); } return value; } existsEdge(fromNode, toNode) { return this.graph.existsEdge(fromNode, toNode); } getSheetId(sheetName) { return this.sheetMapping.fetch(sheetName); } getSheetHeight(sheet) { return this.addressMapping.getHeight(sheet); } getSheetWidth(sheet) { return this.addressMapping.getWidth(sheet); } getArray(range) { return this.arrayMapping.getArray(range); } getRange(start, end) { return this.rangeMapping.getRange(start, end); } topSortWithScc() { return this.graph.topSortWithScc(); } markAsVolatile(vertex) { this.graph.markNodeAsVolatile(vertex); } markAsDependentOnStructureChange(vertex) { this.graph.markNodeAsChangingWithStructure(vertex); } forceApplyPostponedTransformations() { for (const vertex of this.graph.getNodes()) { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.FormulaCellVertex) { vertex.ensureRecentData(this.lazilyTransformingAstService); } } } *rawValuesFromRange(range) { for (const address of range.addresses(this)) { const value = this.getScalarValue(address); if (value !== _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue) { yield [(0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(value), address]; } } } computeListOfValuesInRange(range) { const values = []; for (const cellFromRange of range.addresses(this)) { const value = this.getScalarValue(cellFromRange); values.push(value); } return values; } shrinkArrayToCorner(array) { this.cleanAddressMappingUnderArray(array); for (const adjacentVertex of this.adjacentArrayVertices(array)) { let relevantDependencies; if (adjacentVertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex) { relevantDependencies = this.formulaDirectDependenciesToArray(adjacentVertex, array); } else { relevantDependencies = this.rangeDirectDependenciesToArray(adjacentVertex, array); } let dependentToCorner = false; for (const [address, vertex] of relevantDependencies) { if (array.isLeftCorner(address)) { dependentToCorner = true; } this.graph.addEdge(vertex, adjacentVertex); this.graph.markNodeAsDirty(vertex); } if (!dependentToCorner) { this.graph.removeEdge(array, adjacentVertex); } } this.graph.markNodeAsDirty(array); } isArrayInternalCell(address) { const vertex = this.getCell(address); return vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex && !vertex.isLeftCorner(address); } getAndClearContentChanges() { const changes = this.changes; this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty(); return changes; } getAdjacentNodesAddresses(inputVertex) { const deps = this.graph.adjacentNodes(inputVertex); const ret = []; deps.forEach(vertex => { const castVertex = vertex; if (castVertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { ret.push((0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(castVertex.start, castVertex.end)); } else { ret.push(castVertex.getAddress(this.lazilyTransformingAstService)); } }); return ret; } exchangeGraphNode(oldNode, newNode) { this.graph.addNodeAndReturnId(newNode); const adjNodesStored = this.graph.adjacentNodes(oldNode); this.removeVertex(oldNode); adjNodesStored.forEach(adjacentNode => { if (this.graph.hasNode(adjacentNode)) { this.graph.addEdge(newNode, adjacentNode); } }); } setArray(range, vertex) { this.arrayMapping.setArray(range, vertex); } correctInfiniteRangesDependency(address) { const relevantInfiniteRanges = this.graph.getInfiniteRanges().filter(({ node }) => node.range.addressInRange(address)); if (relevantInfiniteRanges.length <= 0) { return; } const { vertex, id: maybeVertexId } = this.fetchCellOrCreateEmpty(address); const vertexId = maybeVertexId !== null && maybeVertexId !== void 0 ? maybeVertexId : this.graph.getNodeId(vertex); relevantInfiniteRanges.forEach(({ id }) => { this.graph.addEdge(vertexId, id); }); } exchangeOrAddGraphNode(oldNode, newNode) { if (oldNode) { this.exchangeGraphNode(oldNode, newNode); } else { this.graph.addNodeAndReturnId(newNode); } } getArrayVerticesRelatedToRanges(ranges) { const arrayVertices = new Set(); ranges.forEach(range => { if (!this.graph.hasNode(range)) { return; } this.graph.adjacentNodes(range).forEach(adjacentVertex => { if (adjacentVertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { arrayVertices.add(adjacentVertex); } }); }); return arrayVertices; } correctInfiniteRangesDependenciesByRangeVertex(vertex) { this.graph.getInfiniteRanges().forEach(({ id: infiniteRangeVertexId, node: infiniteRangeVertex }) => { const intersection = vertex.range.intersectionWith(infiniteRangeVertex.range); if (intersection === undefined) { return; } intersection.addresses(this).forEach(address => { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, infiniteRangeVertexId); }); }); } cleanAddressMappingUnderArray(vertex) { const arrayRange = vertex.getRange(); for (const address of arrayRange.addresses(this)) { const oldValue = vertex.getArrayCellValue(address); if (this.getCell(address) === vertex) { if (vertex.isLeftCorner(address)) { this.changes.addChange(new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF), address, oldValue); } else { this.addressMapping.removeCell(address); this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, address, oldValue); } } else { this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, address, oldValue); } } } *formulaDirectDependenciesToArray(vertex, array) { var _a; const [, formulaDependencies] = (_a = this.formulaDependencyQuery(vertex)) !== null && _a !== void 0 ? _a : []; if (formulaDependencies === undefined) { return; } for (const dependency of formulaDependencies) { if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency || dependency instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) { continue; } if (array.getRange().addressInRange(dependency)) { const vertex = this.fetchCellOrCreateEmpty(dependency).vertex; yield [dependency, vertex]; } } } *rangeDirectDependenciesToArray(vertex, array) { const { restRange: range } = this.rangeMapping.findSmallerRange(vertex.range); for (const address of range.addresses(this)) { if (array.getRange().addressInRange(address)) { const cell = this.fetchCellOrCreateEmpty(address).vertex; yield [address, cell]; } } } *adjacentArrayVertices(vertex) { const adjacentNodes = this.graph.adjacentNodes(vertex); for (const item of adjacentNodes) { if (item instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex || item instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { yield item; } } } addStructuralNodesToChangeSet() { this.graph.markChangingWithStructureNodesAsDirty(); } fixRangesWhenAddingRows(sheet, row, numberOfRows) { const originalValues = Array.from(this.rangeMapping.rangesInSheet(sheet)); for (const rangeVertex of originalValues) { if (rangeVertex.range.includesRow(row + numberOfRows)) { if (rangeVertex.bruteForce) { const addedSubrangeInThatRange = rangeVertex.range.rangeWithSameWidth(row, numberOfRows); for (const address of addedSubrangeInThatRange.addresses(this)) { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, rangeVertex); } } else { let currentRangeVertex = rangeVertex; let find = this.rangeMapping.findSmallerRange(currentRangeVertex.range); if (find.smallerRangeVertex !== undefined) { continue; } while (find.smallerRangeVertex === undefined) { const newRangeVertex = new ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex(_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(currentRangeVertex.range.start, currentRangeVertex.range.width(), currentRangeVertex.range.height() - 1)); this.rangeMapping.setRange(newRangeVertex); this.graph.addNodeAndReturnId(newRangeVertex); const restRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(currentRangeVertex.range.start.sheet, currentRangeVertex.range.start.col, currentRangeVertex.range.end.row), currentRangeVertex.range.end); this.addAllFromRange(restRange, currentRangeVertex); this.graph.addEdge(newRangeVertex, currentRangeVertex); currentRangeVertex = newRangeVertex; find = this.rangeMapping.findSmallerRange(currentRangeVertex.range); } this.graph.addEdge(find.smallerRangeVertex, currentRangeVertex); this.addAllFromRange(find.restRange, currentRangeVertex); this.graph.removeEdge(find.smallerRangeVertex, rangeVertex); } } } } addAllFromRange(range, rangeVertex) { for (const address of range.addresses(this)) { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, rangeVertex); } } fixRangesWhenAddingColumns(sheet, column, numberOfColumns) { for (const rangeVertex of this.rangeMapping.rangesInSheet(sheet)) { if (rangeVertex.range.includesColumn(column + numberOfColumns)) { let subrange; if (rangeVertex.bruteForce) { subrange = rangeVertex.range.rangeWithSameHeight(column, numberOfColumns); } else { subrange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, column, rangeVertex.range.end.row), numberOfColumns, 1); } for (const address of subrange.addresses(this)) { const { vertex, id } = this.fetchCellOrCreateEmpty(address); this.graph.addEdge(id !== null && id !== void 0 ? id : vertex, rangeVertex); } } } } exchangeOrAddFormulaVertex(vertex) { const address = vertex.getAddress(this.lazilyTransformingAstService); const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(address, vertex.width, vertex.height); const oldNode = this.shrinkPossibleArrayAndGetCell(address); if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { this.setArray(range, vertex); } this.exchangeOrAddGraphNode(oldNode, vertex); this.addressMapping.setCell(address, vertex); if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { if (!this.isThereSpaceForArray(vertex)) { return; } for (const cellAddress of range.addresses(this)) { if (vertex.isLeftCorner(cellAddress)) { continue; } const old = this.getCell(cellAddress); this.exchangeOrAddGraphNode(old, vertex); } } for (const cellAddress of range.addresses(this)) { this.addressMapping.setCell(cellAddress, vertex); } } setAddressMappingForArrayVertex(vertex, formulaAddress) { this.addressMapping.setCell(formulaAddress, vertex); if (!(vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex)) { return; } const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFromOrUndef(formulaAddress, vertex.width, vertex.height); if (range === undefined) { return; } this.setArray(range, vertex); if (!this.isThereSpaceForArray(vertex)) { return; } for (const address of range.addresses(this)) { this.addressMapping.setCell(address, vertex); } } truncateRanges(span, coordinate) { const { verticesToRemove, verticesToMerge, verticesWithChangedSize } = this.rangeMapping.truncateRanges(span, coordinate); for (const [existingVertex, mergedVertex] of verticesToMerge) { this.mergeRangeVertices(existingVertex, mergedVertex); } for (const rangeVertex of verticesToRemove) { this.removeVertexAndCleanupDependencies(rangeVertex); } return verticesWithChangedSize; } fixArraysAfterAddingRow(sheet, rowStart, numberOfRows) { this.arrayMapping.moveArrayVerticesAfterRowByRows(sheet, rowStart, numberOfRows); if (rowStart <= 0) { return; } for (const [, array] of this.arrayMapping.arraysInRows(_Span__WEBPACK_IMPORTED_MODULE_8__.RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) { const arrayRange = array.getRange(); for (let col = arrayRange.start.col; col <= arrayRange.end.col; ++col) { for (let row = rowStart; row <= arrayRange.end.row; ++row) { const destination = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row); const source = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row + numberOfRows); const value = array.getArrayCellValue(destination); this.addressMapping.moveCell(source, destination); this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, source, value); } } } } fixArraysAfterRemovingRows(sheet, rowStart, numberOfRows) { this.arrayMapping.moveArrayVerticesAfterRowByRows(sheet, rowStart, -numberOfRows); if (rowStart <= 0) { return; } for (const [, array] of this.arrayMapping.arraysInRows(_Span__WEBPACK_IMPORTED_MODULE_8__.RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) { if (this.isThereSpaceForArray(array)) { for (const address of array.getRange().addresses(this)) { this.addressMapping.setCell(address, array); } } else { this.setNoSpaceIfArray(array); } } } fixArraysAfterAddingColumn(sheet, columnStart, numberOfColumns) { this.arrayMapping.moveArrayVerticesAfterColumnByColumns(sheet, columnStart, numberOfColumns); if (columnStart <= 0) { return; } for (const [, array] of this.arrayMapping.arraysInCols(_Span__WEBPACK_IMPORTED_MODULE_8__.ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { const arrayRange = array.getRange(); for (let row = arrayRange.start.row; row <= arrayRange.end.row; ++row) { for (let col = columnStart; col <= arrayRange.end.col; ++col) { const destination = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row); const source = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col + numberOfColumns, row); const value = array.getArrayCellValue(destination); this.addressMapping.moveCell(source, destination); this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, source, value); } } } } fixArraysAfterRemovingColumns(sheet, columnStart, numberOfColumns) { this.arrayMapping.moveArrayVerticesAfterColumnByColumns(sheet, columnStart, -numberOfColumns); if (columnStart <= 0) { return; } for (const [, array] of this.arrayMapping.arraysInCols(_Span__WEBPACK_IMPORTED_MODULE_8__.ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) { if (this.isThereSpaceForArray(array)) { for (const address of array.getRange().addresses(this)) { this.addressMapping.setCell(address, array); } } else { this.setNoSpaceIfArray(array); } } } shrinkPossibleArrayAndGetCell(address) { const vertex = this.getCell(address); if (!(vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex)) { return vertex; } this.setNoSpaceIfArray(vertex); return this.getCell(address); } setNoSpaceIfArray(vertex) { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) { this.shrinkArrayToCorner(vertex); vertex.setNoSpace(); } } removeVertex(vertex) { this.removeVertexAndCleanupDependencies(vertex); if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { this.rangeMapping.removeRange(vertex); } } mergeRangeVertices(existingVertex, newVertex) { const adjNodesStored = this.graph.adjacentNodes(newVertex); this.removeVertexAndCleanupDependencies(newVertex); this.graph.removeEdgeIfExists(existingVertex, newVertex); adjNodesStored.forEach(adjacentNode => { if (this.graph.hasNode(adjacentNode)) { this.graph.addEdge(existingVertex, adjacentNode); } }); } removeVertexAndCleanupDependencies(inputVertex) { const dependencies = new Set(this.graph.removeNode(inputVertex)); while (dependencies.size > 0) { const dependency = dependencies.values().next().value; dependencies.delete(dependency); const [address, vertex] = dependency; if (this.graph.hasNode(vertex) && this.graph.adjacentNodesCount(vertex) === 0) { if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex || vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) { this.graph.removeNode(vertex).forEach(candidate => dependencies.add(candidate)); } if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) { this.rangeMapping.removeRange(vertex); } else if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) { this.addressMapping.removeCell(address); } } } } } /***/ }), /* 6 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ absolutizeDependencies: () => (/* binding */ absolutizeDependencies), /* harmony export */ filterDependenciesOutOfScope: () => (/* binding */ filterDependenciesOutOfScope) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Converts dependencies from maybe relative addressing to absolute addressing. * * @param deps - list of addresses in R0C0 format * @param baseAddress - base address with regard to which make a convertion */ const absolutizeDependencies = (deps, baseAddress) => { return deps.map(dep => dep.absolutize(baseAddress)); }; const filterDependenciesOutOfScope = deps => { return deps.filter(dep => { if (dep instanceof _parser__WEBPACK_IMPORTED_MODULE_2__.NamedExpressionDependency) { return true; } if (dep instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) { return !((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep.start) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep.end)); } else { return !(0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep); } }); }; /***/ }), /* 7 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddressDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.AddressDependency), /* harmony export */ AstNodeType: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.AstNodeType), /* harmony export */ CellAddress: () => (/* reexport safe */ _CellAddress__WEBPACK_IMPORTED_MODULE_1__.CellAddress), /* harmony export */ CellRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.CellRangeDependency), /* harmony export */ ColumnRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.ColumnRangeDependency), /* harmony export */ FormulaLexer: () => (/* reexport safe */ _FormulaParser__WEBPACK_IMPORTED_MODULE_5__.FormulaLexer), /* harmony export */ NamedExpressionDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.NamedExpressionDependency), /* harmony export */ ParserWithCaching: () => (/* reexport safe */ _ParserWithCaching__WEBPACK_IMPORTED_MODULE_2__.ParserWithCaching), /* harmony export */ ParsingErrorType: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.ParsingErrorType), /* harmony export */ RowRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.RowRangeDependency), /* harmony export */ Unparser: () => (/* reexport safe */ _Unparser__WEBPACK_IMPORTED_MODULE_7__.Unparser), /* harmony export */ buildCellErrorAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildCellErrorAst), /* harmony export */ buildCellRangeAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildCellRangeAst), /* harmony export */ buildLexerConfig: () => (/* reexport safe */ _LexerConfig__WEBPACK_IMPORTED_MODULE_4__.buildLexerConfig), /* harmony export */ buildParsingErrorAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildParsingErrorAst), /* harmony export */ buildProcedureAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildProcedureAst), /* harmony export */ cellAddressFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.cellAddressFromString), /* harmony export */ collectDependencies: () => (/* reexport safe */ _collectDependencies__WEBPACK_IMPORTED_MODULE_3__.collectDependencies), /* harmony export */ simpleCellAddressFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddressFromString), /* harmony export */ simpleCellAddressToString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddressToString), /* harmony export */ simpleCellRangeFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellRangeFromString), /* harmony export */ simpleCellRangeToString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellRangeToString) /* harmony export */ }); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); /* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9); /* harmony import */ var _ParserWithCaching__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13); /* harmony import */ var _collectDependencies__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); /* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62); /* harmony import */ var _FormulaParser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(60); /* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(57); /* harmony import */ var _Unparser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(65); /* harmony import */ var _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(67); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /***/ }), /* 8 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ cellAddressFromString: () => (/* binding */ cellAddressFromString), /* harmony export */ columnAddressFromString: () => (/* binding */ columnAddressFromString), /* harmony export */ columnIndexToLabel: () => (/* binding */ columnIndexToLabel), /* harmony export */ rowAddressFromString: () => (/* binding */ rowAddressFromString), /* harmony export */ sheetIndexToString: () => (/* binding */ sheetIndexToString), /* harmony export */ simpleCellAddressFromString: () => (/* binding */ simpleCellAddressFromString), /* harmony export */ simpleCellAddressToString: () => (/* binding */ simpleCellAddressToString), /* harmony export */ simpleCellRangeFromString: () => (/* binding */ simpleCellRangeFromString), /* harmony export */ simpleCellRangeToString: () => (/* binding */ simpleCellRangeToString) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); /* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10); /* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12); /* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(11); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const addressRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([A-Za-z]+)(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([0-9]+)$`); const columnRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([A-Za-z]+)$`); const rowRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([0-9]+)$`); const simpleSheetNameRegex = new RegExp(`^${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.UNQUOTED_SHEET_NAME_PATTERN}$`); /** * Computes R0C0 representation of cell address based on it's string representation and base address. * * @param sheetMapping - mapping function needed to change name of a sheet to index * @param stringAddress - string representation of cell address, e.g., 'C64' * @param baseAddress - base address for R0C0 conversion * @returns object representation of address */ const cellAddressFromString = (sheetMapping, stringAddress, baseAddress) => { const result = addressRegex.exec(stringAddress); const col = columnLabelToIndex(result[6]); let sheet = extractSheetNumber(result, sheetMapping); if (sheet === undefined) { return undefined; } if (sheet === null) { sheet = undefined; } const row = Number(result[8]) - 1; if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR && result[7] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) { return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absolute(col, row, sheet); } else if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) { return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absoluteCol(col, row - baseAddress.row, sheet); } else if (result[7] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) { return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absoluteRow(col - baseAddress.col, row, sheet); } else { return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.relative(col - baseAddress.col, row - baseAddress.row, sheet); } }; const columnAddressFromString = (sheetMapping, stringAddress, baseAddress) => { const result = columnRegex.exec(stringAddress); let sheet = extractSheetNumber(result, sheetMapping); if (sheet === undefined) { return undefined; } if (sheet === null) { sheet = undefined; } const col = columnLabelToIndex(result[6]); if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) { return _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__.ColumnAddress.absolute(col, sheet); } else { return _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__.ColumnAddress.relative(col - baseAddress.col, sheet); } }; const rowAddressFromString = (sheetMapping, stringAddress, baseAddress) => { const result = rowRegex.exec(stringAddress); let sheet = extractSheetNumber(result, sheetMapping); if (sheet === undefined) { return undefined; } if (sheet === null) { sheet = undefined; } const row = Number(result[6]) - 1; if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) { return _RowAddress__WEBPACK_IMPORTED_MODULE_5__.RowAddress.absolute(row, sheet); } else { return _RowAddress__WEBPACK_IMPORTED_MODULE_5__.RowAddress.relative(row - baseAddress.row, sheet); } }; /** * Computes simple (absolute) address of a cell address based on its string representation. * - If sheet name is present in the string representation but is not present in sheet mapping, returns `undefined`. * - If sheet name is not present in the string representation, returns {@param contextSheetId} as sheet number. * * @param sheetMapping - mapping function needed to change name of a sheet to index * @param stringAddress - string representation of cell address, e.g., 'C64' * @param contextSheetId - sheet in context of which we should parse the address * @returns absolute representation of address, e.g., { sheet: 0, col: 1, row: 1 } */ const simpleCellAddressFromString = (sheetMapping, stringAddress, contextSheetId) => { const regExpExecArray = addressRegex.exec(stringAddress); if (!regExpExecArray) { return undefined; } const col = columnLabelToIndex(regExpExecArray[6]); let sheet = extractSheetNumber(regExpExecArray, sheetMapping); if (sheet === undefined) { return undefined; } if (sheet === null) { sheet = contextSheetId; } const row = Number(regExpExecArray[8]) - 1; return (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, col, row); }; const simpleCellRangeFromString = (sheetMapping, stringAddress, contextSheetId) => { const split = stringAddress.split(_parser_consts__WEBPACK_IMPORTED_MODULE_4__.RANGE_OPERATOR); if (split.length !== 2) { return undefined; } const [startString, endString] = split; const start = simpleCellAddressFromString(sheetMapping, startString, contextSheetId); if (start === undefined) { return undefined; } const end = simpleCellAddressFromString(sheetMapping, endString, start.sheet); if (end === undefined) { return undefined; } if (start.sheet !== end.sheet) { return undefined; } return (0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(start, end); }; /** * Returns string representation of absolute address * If sheet index is not present in sheet mapping, returns undefined * * @param sheetIndexMapping - mapping function needed to change sheet index to sheet name * @param address - object representation of absolute address * @param sheetIndex - if is not equal with address sheet index, string representation will contain sheet name */ const simpleCellAddressToString = (sheetIndexMapping, address, sheetIndex) => { const column = columnIndexToLabel(address.col); const sheetName = sheetIndexToString(address.sheet, sheetIndexMapping); if (sheetName === undefined) { return undefined; } if (sheetIndex !== address.sheet) { return `${sheetName}!${column}${address.row + 1}`; } else { return `${column}${address.row + 1}`; } }; const simpleCellRangeToString = (sheetIndexMapping, address, sheetIndex) => { const startString = simpleCellAddressToString(sheetIndexMapping, address.start, sheetIndex); const endString = simpleCellAddressToString(sheetIndexMapping, address.end, address.start.sheet); if (startString === undefined || endString === undefined) { return undefined; } else { return `${startString}${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.RANGE_OPERATOR}${endString}`; } }; /** * Convert column label to index * * @param columnStringRepresentation - column label (e.g., 'AAB') * @returns column index */ function columnLabelToIndex(columnStringRepresentation) { if (columnStringRepresentation.length === 1) { return columnStringRepresentation.toUpperCase().charCodeAt(0) - 65; } else { return columnStringRepresentation.split('').reduce((currentColumn, nextLetter) => { return currentColumn * 26 + (nextLetter.toUpperCase().charCodeAt(0) - 64); }, 0) - 1; } } /** * Converts column index to label * * @param column - address to convert * @returns string representation, e.g., 'AAB' */ function columnIndexToLabel(column) { let result = ''; while (column >= 0) { result = String.fromCharCode(column % 26 + 97) + result; column = Math.floor(column / 26) - 1; } return result.toUpperCase(); } function sheetIndexToString(sheetId, sheetMappingFn) { let sheetName = sheetMappingFn(sheetId); if (sheetName === undefined) { return undefined; } if (simpleSheetNameRegex.test(sheetName)) { return sheetName; } else { sheetName = sheetName.replace(/'/g, "''"); return `'${sheetName}'`; } } function extractSheetNumber(regexResult, sheetMapping) { var _a; let maybeSheetName = (_a = regexResult[3]) !== null && _a !== void 0 ? _a : regexResult[2]; if (maybeSheetName) { maybeSheetName = maybeSheetName.replace(/''/g, "'"); return sheetMapping(maybeSheetName); } else { return null; } } /***/ }), /* 9 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CellAddress: () => (/* binding */ CellAddress), /* harmony export */ CellReferenceType: () => (/* binding */ CellReferenceType) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); /* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10); /* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** Possible kinds of cell references */ var CellReferenceType; (function (CellReferenceType) { /** Cell reference with both row and column relative. */ CellReferenceType["CELL_REFERENCE_RELATIVE"] = "CELL_REFERENCE"; /** Cell reference with both row and column absolute. */ CellReferenceType["CELL_REFERENCE_ABSOLUTE"] = "CELL_REFERENCE_ABSOLUTE"; /** Cell reference with absolute column and relative row. */ CellReferenceType["CELL_REFERENCE_ABSOLUTE_COL"] = "CELL_REFERENCE_ABSOLUTE_COL"; /** Cell reference with relative column and absolute row. */ CellReferenceType["CELL_REFERENCE_ABSOLUTE_ROW"] = "CELL_REFERENCE_ABSOLUTE_ROW"; })(CellReferenceType || (CellReferenceType = {})); class CellAddress { constructor(col, row, type, sheet) { this.col = col; this.row = row; this.type = type; this.sheet = sheet; } static fromColAndRow(col, row, sheet) { const factoryMethod = col.isColumnAbsolute() && row.isRowAbsolute() ? CellAddress.absolute.bind(this) : col.isColumnAbsolute() ? CellAddress.absoluteCol.bind(this) : row.isRowAbsolute() ? CellAddress.absoluteRow.bind(this) : CellAddress.relative.bind(this); return factoryMethod(col.col, row.row, sheet); } static relative(col, row, sheet) { return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_RELATIVE, sheet); } static absolute(col, row, sheet) { return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE, sheet); } static absoluteCol(col, row, sheet) { return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL, sheet); } static absoluteRow(col, row, sheet) { return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW, sheet); } /** * Converts R0C0 representation of cell address to simple object representation. * * @param baseAddress - base address for R0C0 shifts */ toSimpleCellAddress(baseAddress) { const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress); if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, this.col, this.row); } else if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, baseAddress.col + this.col, this.row); } else if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, this.col, baseAddress.row + this.row); } else { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, baseAddress.col + this.col, baseAddress.row + this.row); } } toColumnAddress() { const refType = this.isColumnRelative() ? _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.RELATIVE : _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.ABSOLUTE; return new _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ColumnAddress(refType, this.col, this.sheet); } toRowAddress() { const refType = this.isRowRelative() ? _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.RELATIVE : _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.ABSOLUTE; return new _RowAddress__WEBPACK_IMPORTED_MODULE_3__.RowAddress(refType, this.row, this.sheet); } toSimpleColumnAddress(baseAddress) { const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress); let column = this.col; if (this.isColumnRelative()) { column += baseAddress.col; } return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleColumnAddress)(sheet, column); } toSimpleRowAddress(baseAddress) { const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress); let row = this.row; if (this.isRowRelative()) { row += baseAddress.row; } return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleRowAddress)(sheet, row); } isRowAbsolute() { return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW; } isColumnAbsolute() { return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL; } isColumnRelative() { return this.type === CellReferenceType.CELL_REFERENCE_RELATIVE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW; } isRowRelative() { return this.type === CellReferenceType.CELL_REFERENCE_RELATIVE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL; } isAbsolute() { return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE && this.sheet !== undefined; } shiftedByRows(numberOfRows) { return new CellAddress(this.col, this.row + numberOfRows, this.type, this.sheet); } shiftedByColumns(numberOfColumns) { return new CellAddress(this.col + numberOfColumns, this.row, this.type, this.sheet); } moved(toSheet, toRight, toBottom) { const newSheet = this.sheet === undefined ? undefined : toSheet; return new CellAddress(this.col + toRight, this.row + toBottom, this.type, newSheet); } withSheet(sheet) { return new CellAddress(this.col, this.row, this.type, sheet); } isInvalid(baseAddress) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleCellAddress)(this.toSimpleCellAddress(baseAddress)); } shiftRelativeDimensions(toRight, toBottom) { const col = this.isColumnAbsolute() ? this.col : this.col + toRight; const row = this.isRowAbsolute() ? this.row : this.row + toBottom; return new CellAddress(col, row, this.type, this.sheet); } shiftAbsoluteDimensions(toRight, toBottom) { const col = this.isColumnRelative() ? this.col : this.col + toRight; const row = this.isRowRelative() ? this.row : this.row + toBottom; return new CellAddress(col, row, this.type, this.sheet); } hash(withSheet) { const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : ''; switch (this.type) { case CellReferenceType.CELL_REFERENCE_RELATIVE: { return `${sheetPart}#${this.row}R${this.col}`; } case CellReferenceType.CELL_REFERENCE_ABSOLUTE: { return `${sheetPart}#${this.row}A${this.col}`; } case CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL: { return `${sheetPart}#${this.row}AC${this.col}`; } case CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW: { return `${sheetPart}#${this.row}AR${this.col}`; } } } unparse(baseAddress) { const simpleAddress = this.toSimpleCellAddress(baseAddress); if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleCellAddress)(simpleAddress)) { return undefined; } const column = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__.columnIndexToLabel)(simpleAddress.col); const rowDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW ? '$' : ''; const colDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL ? '$' : ''; return `${colDollar}${column}${rowDollar}${simpleAddress.row + 1}`; } exceedsSheetSizeLimits(maxColumns, maxRows) { return this.row >= maxRows || this.col >= maxColumns; } } /***/ }), /* 10 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ColumnAddress: () => (/* binding */ ColumnAddress), /* harmony export */ ReferenceType: () => (/* binding */ ReferenceType) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var ReferenceType; (function (ReferenceType) { ReferenceType["RELATIVE"] = "RELATIVE"; ReferenceType["ABSOLUTE"] = "ABSOLUTE"; })(ReferenceType || (ReferenceType = {})); class ColumnAddress { constructor(type, col, sheet) { this.type = type; this.col = col; this.sheet = sheet; } static absolute(column, sheet) { return new ColumnAddress(ReferenceType.ABSOLUTE, column, sheet); } static relative(column, sheet) { return new ColumnAddress(ReferenceType.RELATIVE, column, sheet); } static compareByAbsoluteAddress(baseAddress) { return (colA, colB) => colA.toSimpleColumnAddress(baseAddress).col - colB.toSimpleColumnAddress(baseAddress).col; } isColumnAbsolute() { return this.type === ReferenceType.ABSOLUTE; } isColumnRelative() { return this.type === ReferenceType.RELATIVE; } isAbsolute() { return this.type === ReferenceType.ABSOLUTE && this.sheet !== undefined; } moved(toSheet, toRight, _toBottom) { const newSheet = this.sheet === undefined ? undefined : toSheet; return new ColumnAddress(this.type, this.col + toRight, newSheet); } shiftedByColumns(numberOfColumns) { return new ColumnAddress(this.type, this.col + numberOfColumns, this.sheet); } toSimpleColumnAddress(baseAddress) { const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress); let column = this.col; if (this.isColumnRelative()) { column = baseAddress.col + this.col; } return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleColumnAddress)(sheet, column); } shiftRelativeDimensions(toRight, _toBottom) { const col = this.isColumnRelative() ? this.col + toRight : this.col; return new ColumnAddress(this.type, col, this.sheet); } shiftAbsoluteDimensions(toRight, _toBottom) { const col = this.isColumnAbsolute() ? this.col + toRight : this.col; return new ColumnAddress(this.type, col, this.sheet); } withSheet(sheet) { return new ColumnAddress(this.type, this.col, sheet); } isInvalid(baseAddress) { return this.toSimpleColumnAddress(baseAddress).col < 0; } hash(withSheet) { const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : ''; switch (this.type) { case ReferenceType.RELATIVE: { return `${sheetPart}#COLR${this.col}`; } case ReferenceType.ABSOLUTE: { return `${sheetPart}#COLA${this.col}`; } } } unparse(baseAddress) { const simpleAddress = this.toSimpleColumnAddress(baseAddress); if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleColumnAddress)(simpleAddress)) { return undefined; } const column = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__.columnIndexToLabel)(simpleAddress.col); const dollar = this.type === ReferenceType.ABSOLUTE ? '$' : ''; return `${dollar}${column}`; } exceedsSheetSizeLimits(maxColumns) { return this.col >= maxColumns; } } /***/ }), /* 11 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RowAddress: () => (/* binding */ RowAddress) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RowAddress { constructor(type, row, sheet) { this.type = type; this.row = row; this.sheet = sheet; } static absolute(row, sheet) { return new RowAddress(_ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE, row, sheet); } static relative(row, sheet) { return new RowAddress(_ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE, row, sheet); } static compareByAbsoluteAddress(baseAddress) { return (rowA, rowB) => rowA.toSimpleRowAddress(baseAddress).row - rowB.toSimpleRowAddress(baseAddress).row; } isRowAbsolute() { return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE; } isRowRelative() { return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE; } isAbsolute() { return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE && this.sheet !== undefined; } moved(toSheet, toRight, toBottom) { const newSheet = this.sheet === undefined ? undefined : toSheet; return new RowAddress(this.type, this.row + toBottom, newSheet); } shiftedByRows(numberOfColumns) { return new RowAddress(this.type, this.row + numberOfColumns, this.sheet); } toSimpleRowAddress(baseAddress) { const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress); let row = this.row; if (this.isRowRelative()) { row = baseAddress.row + this.row; } return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleRowAddress)(sheet, row); } shiftRelativeDimensions(toRight, toBottom) { const row = this.isRowRelative() ? this.row + toBottom : this.row; return new RowAddress(this.type, row, this.sheet); } shiftAbsoluteDimensions(toRight, toBottom) { const row = this.isRowAbsolute() ? this.row + toBottom : this.row; return new RowAddress(this.type, row, this.sheet); } withSheet(sheet) { return new RowAddress(this.type, this.row, sheet); } isInvalid(baseAddress) { return this.toSimpleRowAddress(baseAddress).row < 0; } hash(withSheet) { const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : ''; switch (this.type) { case _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE: { return `${sheetPart}#ROWR${this.row}`; } case _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE: { return `${sheetPart}#ROWA${this.row}`; } } } unparse(baseAddress) { const simpleAddress = this.toSimpleRowAddress(baseAddress); if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleRowAddress)(simpleAddress)) { return undefined; } const dollar = this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE ? '$' : ''; return `${dollar}${simpleAddress.row + 1}`; } exceedsSheetSizeLimits(maxRows) { return this.row >= maxRows; } } /***/ }), /* 12 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ABSOLUTE_OPERATOR: () => (/* binding */ ABSOLUTE_OPERATOR), /* harmony export */ ALL_DIGITS_ARRAY: () => (/* binding */ ALL_DIGITS_ARRAY), /* harmony export */ ALL_UNICODE_LETTERS_ARRAY: () => (/* binding */ ALL_UNICODE_LETTERS_ARRAY), /* harmony export */ ALL_WHITESPACE_PATTERN: () => (/* binding */ ALL_WHITESPACE_PATTERN), /* harmony export */ CELL_REFERENCE_PATTERN: () => (/* binding */ CELL_REFERENCE_PATTERN), /* harmony export */ CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN: () => (/* binding */ CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN), /* harmony export */ COLUMN_REFERENCE_PATTERN: () => (/* binding */ COLUMN_REFERENCE_PATTERN), /* harmony export */ NAMED_EXPRESSION_PATTERN: () => (/* binding */ NAMED_EXPRESSION_PATTERN), /* harmony export */ NON_RESERVED_CHARACTER_PATTERN: () => (/* binding */ NON_RESERVED_CHARACTER_PATTERN), /* harmony export */ ODFF_WHITESPACE_PATTERN: () => (/* binding */ ODFF_WHITESPACE_PATTERN), /* harmony export */ QUOTED_SHEET_NAME_PATTERN: () => (/* binding */ QUOTED_SHEET_NAME_PATTERN), /* harmony export */ R1C1_CELL_REFERENCE_PATTERN: () => (/* binding */ R1C1_CELL_REFERENCE_PATTERN), /* harmony export */ RANGE_OPERATOR: () => (/* binding */ RANGE_OPERATOR), /* harmony export */ ROW_REFERENCE_PATTERN: () => (/* binding */ ROW_REFERENCE_PATTERN), /* harmony export */ SHEET_NAME_PATTERN: () => (/* binding */ SHEET_NAME_PATTERN), /* harmony export */ UNICODE_LETTER_PATTERN: () => (/* binding */ UNICODE_LETTER_PATTERN), /* harmony export */ UNQUOTED_SHEET_NAME_PATTERN: () => (/* binding */ UNQUOTED_SHEET_NAME_PATTERN) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const RANGE_OPERATOR = ':'; const ABSOLUTE_OPERATOR = '$'; const ALL_WHITESPACE_PATTERN = '\\s+'; const ODFF_WHITESPACE_PATTERN = '[ \\t\\n\\r]+'; const UNICODE_LETTER_PATTERN = 'A-Za-z\u00C0-\u02AF'; const NON_RESERVED_CHARACTER_PATTERN = `${UNICODE_LETTER_PATTERN}0-9_.`; const UNQUOTED_SHEET_NAME_PATTERN = `[${UNICODE_LETTER_PATTERN}0-9_]+`; const QUOTED_SHEET_NAME_PATTERN = "'(((?!').|'')*)'"; const SHEET_NAME_PATTERN = `(${UNQUOTED_SHEET_NAME_PATTERN}|${QUOTED_SHEET_NAME_PATTERN})!`; const CELL_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+\\${ABSOLUTE_OPERATOR}?[0-9]+`; const COLUMN_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+`; const ROW_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[0-9]+`; const R1C1_CELL_REFERENCE_PATTERN = '[rR][0-9]*[cC][0-9]*'; const CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN = `(${CELL_REFERENCE_PATTERN})[^${NON_RESERVED_CHARACTER_PATTERN}]`; const NAMED_EXPRESSION_PATTERN = `[${UNICODE_LETTER_PATTERN}_][${NON_RESERVED_CHARACTER_PATTERN}]*`; const ALL_DIGITS_ARRAY = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const ALL_UNICODE_LETTERS_ARRAY = [...Array.from(Array(26)).map((_, i) => i + 'A'.charCodeAt(0)), ...Array.from(Array(26)).map((_, i) => i + 'a'.charCodeAt(0)), ...Array.from(Array(0x02AF - 0x00C0 + 1)).map((_, i) => i + 0x00C0)].map(code => String.fromCharCode(code)); /***/ }), /* 13 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ParserWithCaching: () => (/* binding */ ParserWithCaching) /* harmony export */ }); /* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var ___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); /* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57); /* harmony import */ var _binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); /* harmony import */ var _Cache__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(59); /* harmony import */ var _FormulaParser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(60); /* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(62); /* harmony import */ var _Unparser__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(65); /* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(10); /* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(11); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Parses formula using caching if feasible. */ class ParserWithCaching { constructor(config, functionRegistry, sheetMapping) { this.config = config; this.functionRegistry = functionRegistry; this.sheetMapping = sheetMapping; this.statsCacheUsed = 0; this.lexerConfig = (0,_LexerConfig__WEBPACK_IMPORTED_MODULE_8__.buildLexerConfig)(config); this.lexer = new _FormulaParser__WEBPACK_IMPORTED_MODULE_7__.FormulaLexer(this.lexerConfig); this.formulaParser = new _FormulaParser__WEBPACK_IMPORTED_MODULE_7__.FormulaParser(this.lexerConfig, this.sheetMapping); this.cache = new _Cache__WEBPACK_IMPORTED_MODULE_6__.Cache(this.functionRegistry); } /** * Parses a formula. * * @param text - formula to parse * @param formulaAddress - address with regard to which formula should be parsed. Impacts computed addresses in R0C0 format. */ parse(text, formulaAddress) { this.formulaAddress = formulaAddress; const lexerResult = this.tokenizeFormula(text); if (lexerResult.errors.length > 0) { const errors = lexerResult.errors.map(e => ({ type: _Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.LexingError, message: e.message })); return { ast: (0,___WEBPACK_IMPORTED_MODULE_2__.buildParsingErrorAst)(), errors, hasVolatileFunction: false, hasStructuralChangeFunction: false, dependencies: [] }; } const hash = this.computeHashFromTokens(lexerResult.tokens, formulaAddress); let cacheResult = this.cache.get(hash); if (cacheResult !== undefined) { ++this.statsCacheUsed; } else { const processedTokens = this.bindWhitespacesToTokens(lexerResult.tokens); const parsingResult = this.formulaParser.parseFromTokens(processedTokens, formulaAddress); if (parsingResult.errors.length > 0) { return Object.assign(Object.assign({}, parsingResult), { hasVolatileFunction: false, hasStructuralChangeFunction: false, dependencies: [] }); } else { cacheResult = this.cache.set(hash, parsingResult.ast); } } const { ast, hasVolatileFunction, hasStructuralChangeFunction } = cacheResult; const astWithNoReversedRanges = this.convertReversedRangesToRegularRanges(ast); const dependencies = (0,___WEBPACK_IMPORTED_MODULE_2__.collectDependencies)(astWithNoReversedRanges, this.functionRegistry); return { ast: astWithNoReversedRanges, errors: [], hasVolatileFunction, hasStructuralChangeFunction, dependencies }; } convertReversedRangesToRegularRanges(ast) { switch (ast.type) { case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EMPTY: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NUMBER: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.STRING: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR_WITH_RAW_INPUT: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_REFERENCE: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NAMED_EXPRESSION: return ast; case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE: { const { start, end } = ast; const orderedEnds = this.orderCellRangeEnds(start, end); return Object.assign(Object.assign({}, ast), { start: orderedEnds.start, end: orderedEnds.end }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE: { const { start, end } = ast; const orderedEnds = this.orderColumnRangeEnds(start, end); return Object.assign(Object.assign({}, ast), { start: orderedEnds.start, end: orderedEnds.end }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ROW_RANGE: { const { start, end } = ast; const orderedEnds = this.orderRowRangeEnds(start, end); return Object.assign(Object.assign({}, ast), { start: orderedEnds.start, end: orderedEnds.end }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PERCENT_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_UNARY_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_UNARY_OP: { const valueFixed = this.convertReversedRangesToRegularRanges(ast.value); return Object.assign(Object.assign({}, ast), { value: valueFixed }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CONCATENATE_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EQUALS_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NOT_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.LESS_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.GREATER_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.LESS_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.TIMES_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.DIV_OP: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.POWER_OP: { const leftFixed = this.convertReversedRangesToRegularRanges(ast.left); const rightFixed = this.convertReversedRangesToRegularRanges(ast.right); return Object.assign(Object.assign({}, ast), { left: leftFixed, right: rightFixed }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PARENTHESIS: { const exprFixed = this.convertReversedRangesToRegularRanges(ast.expression); return Object.assign(Object.assign({}, ast), { expression: exprFixed }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.FUNCTION_CALL: { const argsFixed = ast.args.map(arg => this.convertReversedRangesToRegularRanges(arg)); return Object.assign(Object.assign({}, ast), { args: argsFixed }); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ARRAY: { const argsFixed = ast.args.map(argsRow => argsRow.map(arg => this.convertReversedRangesToRegularRanges(arg))); return Object.assign(Object.assign({}, ast), { args: argsFixed }); } } } orderCellRangeEnds(endA, endB) { const ends = [endA, endB]; const [startCol, endCol] = ends.map(e => e.toColumnAddress()).sort(_ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)); const [startRow, endRow] = ends.map(e => e.toRowAddress()).sort(_RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress.compareByAbsoluteAddress(this.formulaAddress)); const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this)); return { start: ___WEBPACK_IMPORTED_MODULE_2__.CellAddress.fromColAndRow(startCol, startRow, startSheet), end: ___WEBPACK_IMPORTED_MODULE_2__.CellAddress.fromColAndRow(endCol, endRow, endSheet) }; } orderColumnRangeEnds(endA, endB) { const ends = [endA, endB]; const [startCol, endCol] = ends.sort(_ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress.compareByAbsoluteAddress(this.formulaAddress)); const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this)); return { start: new _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress(startCol.type, startCol.col, startSheet), end: new _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress(endCol.type, endCol.col, endSheet) }; } orderRowRangeEnds(endA, endB) { const ends = [endA, endB]; const [startRow, endRow] = ends.sort(_RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress.compareByAbsoluteAddress(this.formulaAddress)); const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this)); return { start: new _RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress(startRow.type, startRow.row, startSheet), end: new _RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress(endRow.type, endRow.row, endSheet) }; } static compareSheetIds(sheetA, sheetB) { sheetA = sheetA != null ? sheetA : Infinity; sheetB = sheetB != null ? sheetB : Infinity; return sheetA - sheetB; } fetchCachedResultForAst(ast) { const hash = this.computeHashFromAst(ast); return this.fetchCachedResult(hash); } fetchCachedResult(hash) { const cacheResult = this.cache.get(hash); if (cacheResult === undefined) { throw new Error('There is no AST with such key in the cache'); } else { const { ast, hasVolatileFunction, hasStructuralChangeFunction, relativeDependencies } = cacheResult; return { ast, errors: [], hasVolatileFunction, hasStructuralChangeFunction, dependencies: relativeDependencies }; } } computeHashFromTokens(tokens, baseAddress) { var _a; let hash = ''; let idx = 0; while (idx < tokens.length) { const token = tokens[idx]; if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.CellReference)) { const cellAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, token.image, baseAddress); if (cellAddress === undefined) { hash = hash.concat(token.image); } else { hash = hash.concat(cellAddress.hash(true)); } } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.ProcedureName)) { const procedureName = token.image.toUpperCase().slice(0, -1); const canonicalProcedureName = (_a = this.lexerConfig.functionMapping[procedureName]) !== null && _a !== void 0 ? _a : procedureName; hash = hash.concat(canonicalProcedureName, '('); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.ColumnRange)) { const [start, end] = token.image.split(':'); const startAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, start, baseAddress); const endAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, end, baseAddress); if (startAddress === undefined || endAddress === undefined) { hash = hash.concat('!REF'); } else { hash = hash.concat(startAddress.hash(true), ':', endAddress.hash(true)); } } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.RowRange)) { const [start, end] = token.image.split(':'); const startAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, start, baseAddress); const endAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, end, baseAddress); if (startAddress === undefined || endAddress === undefined) { hash = hash.concat('!REF'); } else { hash = hash.concat(startAddress.hash(true), ':', endAddress.hash(true)); } } else { hash = hash.concat(token.image); } idx++; } return hash; } rememberNewAst(ast) { const hash = this.computeHashFromAst(ast); return this.cache.maybeSetAndThenGet(hash, ast); } computeHashFromAst(ast) { return '=' + this.computeHashOfAstNode(ast); } computeHashOfAstNode(ast) { switch (ast.type) { case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EMPTY: { return ast.leadingWhitespace || ''; } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NUMBER: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)((0,_Unparser__WEBPACK_IMPORTED_MODULE_9__.formatNumber)(ast.value, this.config.decimalSeparator), ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.STRING: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('"' + ast.value + '"', ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NAMED_EXPRESSION: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.expressionName, ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.FUNCTION_CALL: { const args = ast.args.map(arg => this.computeHashOfAstNode(arg)).join(this.config.functionArgSeparator); const rightPart = ast.procedureName + '(' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(')', ast.internalWhitespace); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(rightPart, ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_REFERENCE: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.reference.hash(true), ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ROW_RANGE: case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE: { const start = ast.start.hash(ast.sheetReferenceType !== _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE); const end = ast.end.hash(ast.sheetReferenceType === _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.BOTH_ABSOLUTE); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(start + ':' + end, ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_UNARY_OP: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('-' + this.computeHashOfAstNode(ast.value), ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_UNARY_OP: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('+' + this.computeHashOfAstNode(ast.value), ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PERCENT_OP: { return this.computeHashOfAstNode(ast.value) + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('%', ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR: { const image = this.config.translationPackage.getErrorTranslation(ast.error ? ast.error.type : _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.ERROR); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(image, ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR_WITH_RAW_INPUT: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.rawInput, ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ARRAY: { const args = ast.args.map(row => row.map(val => this.computeHashOfAstNode(val)).join(',')).join(';'); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('{' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('}', ast.internalWhitespace), ast.leadingWhitespace); } case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PARENTHESIS: { const expression = this.computeHashOfAstNode(ast.expression); const rightPart = '(' + expression + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(')', ast.internalWhitespace); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(rightPart, ast.leadingWhitespace); } default: { return this.computeHashOfAstNode(ast.left) + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(_binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_5__.binaryOpTokenMap[ast.type], ast.leadingWhitespace) + this.computeHashOfAstNode(ast.right); } } } bindWhitespacesToTokens(tokens) { const processedTokens = []; const first = tokens[0]; if (!(0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(first, this.lexerConfig.WhiteSpace)) { processedTokens.push(first); } for (let i = 1; i < tokens.length; ++i) { const current = tokens[i]; if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace)) { continue; } const previous = tokens[i - 1]; if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, this.lexerConfig.WhiteSpace)) { current.leadingWhitespace = previous; } processedTokens.push(current); } return processedTokens; } tokenizeFormula(text) { return this.lexer.tokenizeFormula(text); } } /***/ }), /* 14 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Alternation: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Alternation), /* harmony export */ CstParser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.CstParser), /* harmony export */ EMPTY_ALT: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.EMPTY_ALT), /* harmony export */ EOF: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.EOF), /* harmony export */ EarlyExitException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.EarlyExitException), /* harmony export */ EmbeddedActionsParser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.EmbeddedActionsParser), /* harmony export */ Flat: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Flat), /* harmony export */ GAstVisitor: () => (/* reexport safe */ _parse_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_8__.GAstVisitor), /* harmony export */ Lexer: () => (/* reexport safe */ _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.Lexer), /* harmony export */ LexerDefinitionErrorType: () => (/* reexport safe */ _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.LexerDefinitionErrorType), /* harmony export */ MismatchedTokenException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.MismatchedTokenException), /* harmony export */ NoViableAltException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.NoViableAltException), /* harmony export */ NonTerminal: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.NonTerminal), /* harmony export */ NotAllInputParsedException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.NotAllInputParsedException), /* harmony export */ Option: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Option), /* harmony export */ Parser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.Parser), /* harmony export */ ParserDefinitionErrorType: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType), /* harmony export */ Repetition: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Repetition), /* harmony export */ RepetitionMandatory: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionMandatory), /* harmony export */ RepetitionMandatoryWithSeparator: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionMandatoryWithSeparator), /* harmony export */ RepetitionWithSeparator: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionWithSeparator), /* harmony export */ Rule: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Rule), /* harmony export */ Terminal: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Terminal), /* harmony export */ VERSION: () => (/* reexport safe */ _version__WEBPACK_IMPORTED_MODULE_0__.VERSION), /* harmony export */ assignOccurrenceIndices: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.assignOccurrenceIndices), /* harmony export */ clearCache: () => (/* binding */ clearCache), /* harmony export */ createSyntaxDiagramsCode: () => (/* reexport safe */ _diagrams_render_public__WEBPACK_IMPORTED_MODULE_10__.createSyntaxDiagramsCode), /* harmony export */ createToken: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.createToken), /* harmony export */ createTokenInstance: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.createTokenInstance), /* harmony export */ defaultGrammarResolverErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarResolverErrorProvider), /* harmony export */ defaultGrammarValidatorErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarValidatorErrorProvider), /* harmony export */ defaultLexerErrorProvider: () => (/* reexport safe */ _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_6__.defaultLexerErrorProvider), /* harmony export */ defaultParserErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultParserErrorProvider), /* harmony export */ generateParserFactory: () => (/* reexport safe */ _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__.generateParserFactory), /* harmony export */ generateParserModule: () => (/* reexport safe */ _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__.generateParserModule), /* harmony export */ isRecognitionException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.isRecognitionException), /* harmony export */ resolveGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.resolveGrammar), /* harmony export */ serializeGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.serializeGrammar), /* harmony export */ serializeProduction: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.serializeProduction), /* harmony export */ tokenLabel: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenLabel), /* harmony export */ tokenMatcher: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenMatcher), /* harmony export */ tokenName: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenName), /* harmony export */ validateGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.validateGrammar) /* harmony export */ }); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); /* harmony import */ var _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); /* harmony import */ var _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(21); /* harmony import */ var _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(35); /* harmony import */ var _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(42); /* harmony import */ var _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(28); /* harmony import */ var _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(20); /* harmony import */ var _parse_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(31); /* harmony import */ var _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(39); /* harmony import */ var _diagrams_render_public__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(54); /* harmony import */ var _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(55); // semantic version // Tokens utilities // Other Utilities // grammar reflection API // GAST Utilities /* istanbul ignore next */ function clearCache() { console.warn("The clearCache function was 'soft' removed from the Chevrotain API." + "\n\t It performs no action other than printing this message." + "\n\t Please avoid using it as it will be completely removed in the future"); } //# sourceMappingURL=api.js.map /***/ }), /* 15 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ VERSION: () => (/* binding */ VERSION) /* harmony export */ }); // needs a separate module as this is required inside chevrotain productive code // and also in the entry point for webpack(api.ts). // A separate file avoids cyclic dependencies and webpack errors. var VERSION = "6.5.0"; //# sourceMappingURL=version.js.map /***/ }), /* 16 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CstParser: () => (/* binding */ CstParser), /* harmony export */ DEFAULT_PARSER_CONFIG: () => (/* binding */ DEFAULT_PARSER_CONFIG), /* harmony export */ DEFAULT_RULE_CONFIG: () => (/* binding */ DEFAULT_RULE_CONFIG), /* harmony export */ EMPTY_ALT: () => (/* binding */ EMPTY_ALT), /* harmony export */ END_OF_FILE: () => (/* binding */ END_OF_FILE), /* harmony export */ EmbeddedActionsParser: () => (/* binding */ EmbeddedActionsParser), /* harmony export */ Parser: () => (/* binding */ Parser), /* harmony export */ ParserDefinitionErrorType: () => (/* binding */ ParserDefinitionErrorType) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _grammar_follow__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(21); /* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(33); /* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(35); /* harmony import */ var _grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(39); /* harmony import */ var _traits_recoverable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41); /* harmony import */ var _traits_looksahead__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(43); /* harmony import */ var _traits_tree_builder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(44); /* harmony import */ var _traits_lexer_adapter__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47); /* harmony import */ var _traits_recognizer_api__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(48); /* harmony import */ var _traits_recognizer_engine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(49); /* harmony import */ var _traits_error_handler__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(50); /* harmony import */ var _traits_context_assist__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(51); /* harmony import */ var _traits_gast_recorder__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(52); /* harmony import */ var _traits_perf_tracer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(53); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var END_OF_FILE = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__.createTokenInstance)(_scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); Object.freeze(END_OF_FILE); var DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 4, ignoredIssues: {}, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: _errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false }); var DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: function () { return undefined; }, resyncEnabled: true }); var ParserDefinitionErrorType; (function (ParserDefinitionErrorType) { ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME"; ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME"; ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE"; ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS"; ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF"; ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION"; ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT"; ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS"; ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE"; ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME"; ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_NESTED_RULE_NAME"] = 10] = "INVALID_NESTED_RULE_NAME"; ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_NESTED_NAME"] = 11] = "DUPLICATE_NESTED_NAME"; ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 12] = "NO_NON_EMPTY_LOOKAHEAD"; ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 13] = "AMBIGUOUS_PREFIX_ALTS"; ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 14] = "TOO_MANY_ALTS"; })(ParserDefinitionErrorType || (ParserDefinitionErrorType = {})); function EMPTY_ALT(value) { if (value === void 0) { value = undefined; } return function () { return value; }; } var Parser = /** @class */ (function () { function Parser(tokenVocabulary, config) { if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } this.ignoredIssues = DEFAULT_PARSER_CONFIG.ignoredIssues; this.definitionErrors = []; this.selfAnalysisDone = false; var that = this; that.initErrorHandler(config); that.initLexerAdapter(); that.initLooksAhead(config); that.initRecognizerEngine(tokenVocabulary, config); that.initRecoverable(config); that.initTreeBuilder(config); that.initContentAssist(); that.initGastRecorder(config); that.initPerformanceTracer(config); /* istanbul ignore if - complete over-kill to test this, we should only add a test when we actually hard deprecate it and throw an error... */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "ignoredIssues") && config.ignoredIssues !== DEFAULT_PARSER_CONFIG.ignoredIssues) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.PRINT_WARNING)("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\t" + "Please use the flag on the relevant DSL method instead."); } this.ignoredIssues = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "ignoredIssues") ? config.ignoredIssues : DEFAULT_PARSER_CONFIG.ignoredIssues; this.skipValidations = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "skipValidations") ? config.skipValidations : DEFAULT_PARSER_CONFIG.skipValidations; } /** * @deprecated use the **instance** method with the same name instead */ Parser.performSelfAnalysis = function (parserInstance) { ; parserInstance.performSelfAnalysis(); }; Parser.prototype.performSelfAnalysis = function () { var _this = this; this.TRACE_INIT("performSelfAnalysis", function () { var defErrorsMsgs; _this.selfAnalysisDone = true; var className = _this.className; _this.TRACE_INIT("toFastProps", function () { // Without this voodoo magic the parser would be x3-x4 slower // It seems it is better to invoke `toFastProperties` **before** // Any manipulations of the `this` object done during the recording phase. (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.toFastProperties)(_this); }); _this.TRACE_INIT("Grammar Recording", function () { try { _this.enableRecording(); // Building the GAST (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(_this.definedRulesNames, function (currRuleName) { var wrappedRule = _this[currRuleName]; var originalGrammarAction = wrappedRule["originalGrammarAction"]; var recordedRuleGast = undefined; _this.TRACE_INIT(currRuleName + " Rule", function () { recordedRuleGast = _this.topLevelRuleRecord(currRuleName, originalGrammarAction); }); _this.gastProductionsCache[currRuleName] = recordedRuleGast; }); } finally { _this.disableRecording(); } }); var resolverErrors = []; _this.TRACE_INIT("Grammar Resolving", function () { resolverErrors = (0,_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__.resolveGrammar)({ rules: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache) }); _this.definitionErrors.push.apply(_this.definitionErrors, resolverErrors); // mutability for the win? }); _this.TRACE_INIT("Grammar Validations", function () { // only perform additional grammar validations IFF no resolving errors have occurred. // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(resolverErrors) && _this.skipValidations === false) { var validationErrors = (0,_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__.validateGrammar)({ rules: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache), maxLookahead: _this.maxLookahead, tokenTypes: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.tokensMap), ignoredIssues: _this.ignoredIssues, errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarValidatorErrorProvider, grammarName: className }); _this.definitionErrors.push.apply(_this.definitionErrors, validationErrors); // mutability for the win? } }); // this analysis may fail if the grammar is not perfectly valid if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(_this.definitionErrors)) { // The results of these computations are not needed unless error recovery is enabled. if (_this.recoveryEnabled) { _this.TRACE_INIT("computeAllProdsFollows", function () { var allFollows = (0,_grammar_follow__WEBPACK_IMPORTED_MODULE_1__.computeAllProdsFollows)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache)); _this.resyncFollows = allFollows; }); } _this.TRACE_INIT("ComputeLookaheadFunctions", function () { _this.preComputeLookaheadFunctions((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache)); }); } _this.TRACE_INIT("expandAllNestedRuleNames", function () { // TODO: is this needed for EmbeddedActionsParser? var cstAnalysisResult = (0,_cst_cst__WEBPACK_IMPORTED_MODULE_3__.expandAllNestedRuleNames)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache), _this.fullRuleNameToShort); _this.allRuleNames = cstAnalysisResult.allRuleNames; }); if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(_this.definitionErrors)) { defErrorsMsgs = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(_this.definitionErrors, function (defError) { return defError.message; }); throw new Error("Parser Definition Errors detected:\n " + defErrorsMsgs.join("\n-------------------------------\n")); } }); }; // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected. // (normally during the parser's constructor). // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors, // for example: duplicate rule names, referencing an unresolved subrule, ect... // This flag should not be enabled during normal usage, it is used in special situations, for example when // needing to display the parser definition errors in some GUI(online playground). Parser.DEFER_DEFINITION_ERRORS_HANDLING = false; return Parser; }()); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.applyMixins)(Parser, [ _traits_recoverable__WEBPACK_IMPORTED_MODULE_6__.Recoverable, _traits_looksahead__WEBPACK_IMPORTED_MODULE_7__.LooksAhead, _traits_tree_builder__WEBPACK_IMPORTED_MODULE_8__.TreeBuilder, _traits_lexer_adapter__WEBPACK_IMPORTED_MODULE_9__.LexerAdapter, _traits_recognizer_engine__WEBPACK_IMPORTED_MODULE_11__.RecognizerEngine, _traits_recognizer_api__WEBPACK_IMPORTED_MODULE_10__.RecognizerApi, _traits_error_handler__WEBPACK_IMPORTED_MODULE_12__.ErrorHandler, _traits_context_assist__WEBPACK_IMPORTED_MODULE_13__.ContentAssist, _traits_gast_recorder__WEBPACK_IMPORTED_MODULE_14__.GastRecorder, _traits_perf_tracer__WEBPACK_IMPORTED_MODULE_15__.PerformanceTracer ]); var CstParser = /** @class */ (function (_super) { __extends(CstParser, _super); function CstParser(tokenVocabulary, config) { if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } var _this = this; var configClone = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(config); configClone.outputCst = true; _this = _super.call(this, tokenVocabulary, configClone) || this; return _this; } return CstParser; }(Parser)); var EmbeddedActionsParser = /** @class */ (function (_super) { __extends(EmbeddedActionsParser, _super); function EmbeddedActionsParser(tokenVocabulary, config) { if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } var _this = this; var configClone = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(config); configClone.outputCst = false; _this = _super.call(this, tokenVocabulary, configClone) || this; return _this; } return EmbeddedActionsParser; }(Parser)); //# sourceMappingURL=parser.js.map /***/ }), /* 17 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ IDENTITY: () => (/* binding */ IDENTITY), /* harmony export */ NOOP: () => (/* binding */ NOOP), /* harmony export */ PRINT_ERROR: () => (/* binding */ PRINT_ERROR), /* harmony export */ PRINT_WARNING: () => (/* binding */ PRINT_WARNING), /* harmony export */ applyMixins: () => (/* binding */ applyMixins), /* harmony export */ assign: () => (/* binding */ assign), /* harmony export */ assignNoOverwrite: () => (/* binding */ assignNoOverwrite), /* harmony export */ cloneArr: () => (/* binding */ cloneArr), /* harmony export */ cloneObj: () => (/* binding */ cloneObj), /* harmony export */ compact: () => (/* binding */ compact), /* harmony export */ contains: () => (/* binding */ contains), /* harmony export */ defaults: () => (/* binding */ defaults), /* harmony export */ difference: () => (/* binding */ difference), /* harmony export */ drop: () => (/* binding */ drop), /* harmony export */ dropRight: () => (/* binding */ dropRight), /* harmony export */ every: () => (/* binding */ every), /* harmony export */ filter: () => (/* binding */ filter), /* harmony export */ find: () => (/* binding */ find), /* harmony export */ findAll: () => (/* binding */ findAll), /* harmony export */ first: () => (/* binding */ first), /* harmony export */ flatten: () => (/* binding */ flatten), /* harmony export */ forEach: () => (/* binding */ forEach), /* harmony export */ groupBy: () => (/* binding */ groupBy), /* harmony export */ has: () => (/* binding */ has), /* harmony export */ indexOf: () => (/* binding */ indexOf), /* harmony export */ isArray: () => (/* binding */ isArray), /* harmony export */ isES2015MapSupported: () => (/* binding */ isES2015MapSupported), /* harmony export */ isEmpty: () => (/* binding */ isEmpty), /* harmony export */ isFunction: () => (/* binding */ isFunction), /* harmony export */ isObject: () => (/* binding */ isObject), /* harmony export */ isRegExp: () => (/* binding */ isRegExp), /* harmony export */ isString: () => (/* binding */ isString), /* harmony export */ isUndefined: () => (/* binding */ isUndefined), /* harmony export */ keys: () => (/* binding */ keys), /* harmony export */ last: () => (/* binding */ last), /* harmony export */ map: () => (/* binding */ map), /* harmony export */ mapValues: () => (/* binding */ mapValues), /* harmony export */ merge: () => (/* binding */ merge), /* harmony export */ packArray: () => (/* binding */ packArray), /* harmony export */ partial: () => (/* binding */ partial), /* harmony export */ peek: () => (/* binding */ peek), /* harmony export */ pick: () => (/* binding */ pick), /* harmony export */ reduce: () => (/* binding */ reduce), /* harmony export */ reject: () => (/* binding */ reject), /* harmony export */ some: () => (/* binding */ some), /* harmony export */ sortBy: () => (/* binding */ sortBy), /* harmony export */ timer: () => (/* binding */ timer), /* harmony export */ toFastProperties: () => (/* binding */ toFastProperties), /* harmony export */ uniq: () => (/* binding */ uniq), /* harmony export */ values: () => (/* binding */ values), /* harmony export */ zipObject: () => (/* binding */ zipObject) /* harmony export */ }); /* Utils using lodash style API. (not necessarily 100% compliant) for functional and other utils. These utils should replace usage of lodash in the production code base. not because they are any better... but for the purpose of being a dependency free library. The hotspots in the code are already written in imperative style for performance reasons. so writing several dozen utils which may be slower than the original lodash, does not matter as much considering they will not be invoked in hotspots... */ function isEmpty(arr) { return arr && arr.length === 0; } function keys(obj) { if (obj === undefined || obj === null) { return []; } return Object.keys(obj); } function values(obj) { var vals = []; var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { vals.push(obj[keys[i]]); } return vals; } function mapValues(obj, callback) { var result = []; var objKeys = keys(obj); for (var idx = 0; idx < objKeys.length; idx++) { var currKey = objKeys[idx]; result.push(callback.call(null, obj[currKey], currKey)); } return result; } function map(arr, callback) { var result = []; for (var idx = 0; idx < arr.length; idx++) { result.push(callback.call(null, arr[idx], idx)); } return result; } function flatten(arr) { var result = []; for (var idx = 0; idx < arr.length; idx++) { var currItem = arr[idx]; if (Array.isArray(currItem)) { result = result.concat(flatten(currItem)); } else { result.push(currItem); } } return result; } function first(arr) { return isEmpty(arr) ? undefined : arr[0]; } function last(arr) { var len = arr && arr.length; return len ? arr[len - 1] : undefined; } function forEach(collection, iteratorCallback) { /* istanbul ignore else */ if (Array.isArray(collection)) { for (var i = 0; i < collection.length; i++) { iteratorCallback.call(null, collection[i], i); } } else if (isObject(collection)) { var colKeys = keys(collection); for (var i = 0; i < colKeys.length; i++) { var key = colKeys[i]; var value = collection[key]; iteratorCallback.call(null, value, key); } } else { throw Error("non exhaustive match"); } } function isString(item) { return typeof item === "string"; } function isUndefined(item) { return item === undefined; } function isFunction(item) { return item instanceof Function; } function drop(arr, howMuch) { if (howMuch === void 0) { howMuch = 1; } return arr.slice(howMuch, arr.length); } function dropRight(arr, howMuch) { if (howMuch === void 0) { howMuch = 1; } return arr.slice(0, arr.length - howMuch); } function filter(arr, predicate) { var result = []; if (Array.isArray(arr)) { for (var i = 0; i < arr.length; i++) { var item = arr[i]; if (predicate.call(null, item)) { result.push(item); } } } return result; } function reject(arr, predicate) { return filter(arr, function (item) { return !predicate(item); }); } function pick(obj, predicate) { var keys = Object.keys(obj); var result = {}; for (var i = 0; i < keys.length; i++) { var currKey = keys[i]; var currItem = obj[currKey]; if (predicate(currItem)) { result[currKey] = currItem; } } return result; } function has(obj, prop) { if (isObject(obj)) { return obj.hasOwnProperty(prop); } return false; } function contains(arr, item) { return find(arr, function (currItem) { return currItem === item; }) !== undefined ? true : false; } /** * shallow clone */ function cloneArr(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { newArr.push(arr[i]); } return newArr; } /** * shallow clone */ function cloneObj(obj) { var clonedObj = {}; for (var key in obj) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(obj, key)) { clonedObj[key] = obj[key]; } } return clonedObj; } function find(arr, predicate) { for (var i = 0; i < arr.length; i++) { var item = arr[i]; if (predicate.call(null, item)) { return item; } } return undefined; } function findAll(arr, predicate) { var found = []; for (var i = 0; i < arr.length; i++) { var item = arr[i]; if (predicate.call(null, item)) { found.push(item); } } return found; } function reduce(arrOrObj, iterator, initial) { var isArr = Array.isArray(arrOrObj); var vals = isArr ? arrOrObj : values(arrOrObj); var objKeys = isArr ? [] : keys(arrOrObj); var accumulator = initial; for (var i = 0; i < vals.length; i++) { accumulator = iterator.call(null, accumulator, vals[i], isArr ? i : objKeys[i]); } return accumulator; } function compact(arr) { return reject(arr, function (item) { return item === null || item === undefined; }); } function uniq(arr, identity) { if (identity === void 0) { identity = function (item) { return item; }; } var identities = []; return reduce(arr, function (result, currItem) { var currIdentity = identity(currItem); if (contains(identities, currIdentity)) { return result; } else { identities.push(currIdentity); return result.concat(currItem); } }, []); } function partial(func) { var restArgs = []; for (var _i = 1; _i < arguments.length; _i++) { restArgs[_i - 1] = arguments[_i]; } var firstArg = [null]; var allArgs = firstArg.concat(restArgs); return Function.bind.apply(func, allArgs); } function isArray(obj) { return Array.isArray(obj); } function isRegExp(obj) { return obj instanceof RegExp; } function isObject(obj) { return obj instanceof Object; } function every(arr, predicate) { for (var i = 0; i < arr.length; i++) { if (!predicate(arr[i], i)) { return false; } } return true; } function difference(arr, values) { return reject(arr, function (item) { return contains(values, item); }); } function some(arr, predicate) { for (var i = 0; i < arr.length; i++) { if (predicate(arr[i])) { return true; } } return false; } function indexOf(arr, value) { for (var i = 0; i < arr.length; i++) { if (arr[i] === value) { return i; } } return -1; } function sortBy(arr, orderFunc) { var result = cloneArr(arr); result.sort(function (a, b) { return orderFunc(a) - orderFunc(b); }); return result; } function zipObject(keys, values) { if (keys.length !== values.length) { throw Error("can't zipObject with different number of keys and values!"); } var result = {}; for (var i = 0; i < keys.length; i++) { result[keys[i]] = values[i]; } return result; } /** * mutates! (and returns) target */ function assign(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var curSource = sources[i]; var currSourceKeys = keys(curSource); for (var j = 0; j < currSourceKeys.length; j++) { var currKey = currSourceKeys[j]; target[currKey] = curSource[currKey]; } } return target; } /** * mutates! (and returns) target */ function assignNoOverwrite(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var curSource = sources[i]; if (isUndefined(curSource)) { continue; } var currSourceKeys = keys(curSource); for (var j = 0; j < currSourceKeys.length; j++) { var currKey = currSourceKeys[j]; if (!has(target, currKey)) { target[currKey] = curSource[currKey]; } } } return target; } function defaults() { var sources = []; for (var _i = 0; _i < arguments.length; _i++) { sources[_i] = arguments[_i]; } return assignNoOverwrite.apply(null, [{}].concat(sources)); } function groupBy(arr, groupKeyFunc) { var result = {}; forEach(arr, function (item) { var currGroupKey = groupKeyFunc(item); var currGroupArr = result[currGroupKey]; if (currGroupArr) { currGroupArr.push(item); } else { result[currGroupKey] = [item]; } }); return result; } /** * Merge obj2 into obj1. * Will overwrite existing properties with the same name */ function merge(obj1, obj2) { var result = cloneObj(obj1); var keys2 = keys(obj2); for (var i = 0; i < keys2.length; i++) { var key = keys2[i]; var value = obj2[key]; result[key] = value; } return result; } function NOOP() { } function IDENTITY(item) { return item; } /** * Will return a new packed array with same values. */ function packArray(holeyArr) { var result = []; for (var i = 0; i < holeyArr.length; i++) { var orgValue = holeyArr[i]; result.push(orgValue !== undefined ? orgValue : undefined); } return result; } function PRINT_ERROR(msg) { /* istanbul ignore else - can't override global.console in node.js */ if (console && console.error) { console.error("Error: " + msg); } } function PRINT_WARNING(msg) { /* istanbul ignore else - can't override global.console in node.js*/ if (console && console.warn) { // TODO: modify docs accordingly console.warn("Warning: " + msg); } } function isES2015MapSupported() { return typeof Map === "function"; } function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach(function (baseCtor) { var baseProto = baseCtor.prototype; Object.getOwnPropertyNames(baseProto).forEach(function (propName) { if (propName === "constructor") { return; } var basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName); // Handle Accessors if (basePropDescriptor && (basePropDescriptor.get || basePropDescriptor.set)) { Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor); } else { derivedCtor.prototype[propName] = baseCtor.prototype[propName]; } }); }); } // base on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216 function toFastProperties(toBecomeFast) { function FakeConstructor() { } // If our object is used as a constructor it would receive FakeConstructor.prototype = toBecomeFast; var fakeInstance = new FakeConstructor(); function fakeAccess() { return typeof fakeInstance.bar; } // help V8 understand this is a "real" prototype by actually using // the fake instance. fakeAccess(); fakeAccess(); return toBecomeFast; // Eval prevents optimization of this method (even though this is dead code) /* istanbul ignore next */ // tslint:disable-next-line eval(toBecomeFast); } function peek(arr) { return arr[arr.length - 1]; } /* istanbul ignore next - for performance tracing*/ function timer(func) { var start = new Date().getTime(); var val = func(); var end = new Date().getTime(); var total = end - start; return { time: total, value: val }; } //# sourceMappingURL=utils.js.map /***/ }), /* 18 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ResyncFollowsWalker: () => (/* binding */ ResyncFollowsWalker), /* harmony export */ buildBetweenProdsFollowPrefix: () => (/* binding */ buildBetweenProdsFollowPrefix), /* harmony export */ buildInProdFollowPrefix: () => (/* binding */ buildInProdFollowPrefix), /* harmony export */ computeAllProdsFollows: () => (/* binding */ computeAllProdsFollows) /* harmony export */ }); /* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); /* harmony import */ var _first__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(29); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(32); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // This ResyncFollowsWalker computes all of the follows required for RESYNC // (skipping reference production). var ResyncFollowsWalker = /** @class */ (function (_super) { __extends(ResyncFollowsWalker, _super); function ResyncFollowsWalker(topProd) { var _this = _super.call(this) || this; _this.topProd = topProd; _this.follows = {}; return _this; } ResyncFollowsWalker.prototype.startWalking = function () { this.walk(this.topProd); return this.follows; }; ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { // do nothing! just like in the public sector after 13:00 }; ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + this.topProd.name; var fullRest = currRest.concat(prevRest); var restProd = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: fullRest }); var t_in_topProd_follows = (0,_first__WEBPACK_IMPORTED_MODULE_1__.first)(restProd); this.follows[followName] = t_in_topProd_follows; }; return ResyncFollowsWalker; }(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker)); function computeAllProdsFollows(topProductions) { var reSyncFollows = {}; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(topProductions, function (topProd) { var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking(); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.assign)(reSyncFollows, currRefsFollow); }); return reSyncFollows; } function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { return inner.name + occurenceInParent + _constants__WEBPACK_IMPORTED_MODULE_3__.IN; } function buildInProdFollowPrefix(terminal) { var terminalName = terminal.terminalType.name; return terminalName + terminal.idx + _constants__WEBPACK_IMPORTED_MODULE_3__.IN; } //# sourceMappingURL=follow.js.map /***/ }), /* 19 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RestWalker: () => (/* binding */ RestWalker) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); /** * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar. */ var RestWalker = /** @class */ (function () { function RestWalker() { } RestWalker.prototype.walk = function (prod, prevRest) { var _this = this; if (prevRest === void 0) { prevRest = []; } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(prod.definition, function (subProd, index) { var currRest = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.drop)(prod.definition, index + 1); /* istanbul ignore else */ if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) { _this.walkProdRef(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) { _this.walkTerminal(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat) { _this.walkFlat(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) { _this.walkOption(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) { _this.walkAtLeastOne(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) { _this.walkAtLeastOneSep(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) { _this.walkManySep(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) { _this.walkMany(subProd, currRest, prevRest); } else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) { _this.walkOr(subProd, currRest, prevRest); } else { throw Error("non exhaustive match"); } }); }; RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { }; RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { }; RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) { // ABCDEF => after the D the rest is EF var fullOrRest = currRest.concat(prevRest); this.walk(flatProd, fullOrRest); }; RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { // ABC(DE)?F => after the (DE)? the rest is F var fullOrRest = currRest.concat(prevRest); this.walk(optionProd, fullOrRest); }; RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { // ABC(DE)+F => after the (DE)+ the rest is (DE)?F var fullAtLeastOneRest = [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({ definition: atLeastOneProd.definition }) ].concat(currRest, prevRest); this.walk(atLeastOneProd, fullAtLeastOneRest); }; RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest); this.walk(atLeastOneSepProd, fullAtLeastOneSepRest); }; RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { // ABC(DE)*F => after the (DE)* the rest is (DE)?F var fullManyRest = [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({ definition: manyProd.definition }) ].concat(currRest, prevRest); this.walk(manyProd, fullManyRest); }; RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest); this.walk(manySepProd, fullManySepRest); }; RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) { var _this = this; // ABC(D|E|F)G => when finding the (D|E|F) the rest is G var fullOrRest = currRest.concat(prevRest); // walk all different alternatives (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(orProd.definition, function (alt) { // wrapping each alternative in a single definition wrapper // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1 var prodWrapper = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat({ definition: [alt] }); _this.walk(prodWrapper, fullOrRest); }); }; return RestWalker; }()); function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { var repSepRest = [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({ definition: [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal({ terminalType: repSepProd.separator }) ].concat(repSepProd.definition) }) ]; var fullRepSepRest = repSepRest.concat(currRest, prevRest); return fullRepSepRest; } //# sourceMappingURL=rest.js.map /***/ }), /* 20 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AbstractProduction: () => (/* binding */ AbstractProduction), /* harmony export */ Alternation: () => (/* binding */ Alternation), /* harmony export */ Flat: () => (/* binding */ Flat), /* harmony export */ NonTerminal: () => (/* binding */ NonTerminal), /* harmony export */ Option: () => (/* binding */ Option), /* harmony export */ Repetition: () => (/* binding */ Repetition), /* harmony export */ RepetitionMandatory: () => (/* binding */ RepetitionMandatory), /* harmony export */ RepetitionMandatoryWithSeparator: () => (/* binding */ RepetitionMandatoryWithSeparator), /* harmony export */ RepetitionWithSeparator: () => (/* binding */ RepetitionWithSeparator), /* harmony export */ Rule: () => (/* binding */ Rule), /* harmony export */ Terminal: () => (/* binding */ Terminal), /* harmony export */ serializeGrammar: () => (/* binding */ serializeGrammar), /* harmony export */ serializeProduction: () => (/* binding */ serializeProduction) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AbstractProduction = /** @class */ (function () { function AbstractProduction(definition) { this.definition = definition; } AbstractProduction.prototype.accept = function (visitor) { visitor.visit(this); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(this.definition, function (prod) { prod.accept(visitor); }); }; return AbstractProduction; }()); var NonTerminal = /** @class */ (function (_super) { __extends(NonTerminal, _super); function NonTerminal(options) { var _this = _super.call(this, []) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } Object.defineProperty(NonTerminal.prototype, "definition", { get: function () { if (this.referencedRule !== undefined) { return this.referencedRule.definition; } return []; }, set: function (definition) { // immutable }, enumerable: true, configurable: true }); NonTerminal.prototype.accept = function (visitor) { visitor.visit(this); // don't visit children of a reference, we will get cyclic infinite loops if we do so }; return NonTerminal; }(AbstractProduction)); var Rule = /** @class */ (function (_super) { __extends(Rule, _super); function Rule(options) { var _this = _super.call(this, options.definition) || this; _this.orgText = ""; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return Rule; }(AbstractProduction)); // TODO: is this only used in an Alternation? // Perhaps `Flat` should be renamed to `Alternative`? var Flat = /** @class */ (function (_super) { __extends(Flat, _super); // A named Flat production is used to indicate a Nested Rule in an alternation function Flat(options) { var _this = _super.call(this, options.definition) || this; _this.ignoreAmbiguities = false; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return Flat; }(AbstractProduction)); var Option = /** @class */ (function (_super) { __extends(Option, _super); function Option(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return Option; }(AbstractProduction)); var RepetitionMandatory = /** @class */ (function (_super) { __extends(RepetitionMandatory, _super); function RepetitionMandatory(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return RepetitionMandatory; }(AbstractProduction)); var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) { __extends(RepetitionMandatoryWithSeparator, _super); function RepetitionMandatoryWithSeparator(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return RepetitionMandatoryWithSeparator; }(AbstractProduction)); var Repetition = /** @class */ (function (_super) { __extends(Repetition, _super); function Repetition(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return Repetition; }(AbstractProduction)); var RepetitionWithSeparator = /** @class */ (function (_super) { __extends(RepetitionWithSeparator, _super); function RepetitionWithSeparator(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return RepetitionWithSeparator; }(AbstractProduction)); var Alternation = /** @class */ (function (_super) { __extends(Alternation, _super); function Alternation(options) { var _this = _super.call(this, options.definition) || this; _this.idx = 1; _this.ignoreAmbiguities = false; _this.hasPredicates = false; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); return _this; } return Alternation; }(AbstractProduction)); var Terminal = /** @class */ (function () { function Terminal(options) { this.idx = 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; })); } Terminal.prototype.accept = function (visitor) { visitor.visit(this); }; return Terminal; }()); function serializeGrammar(topRules) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topRules, serializeProduction); } function serializeProduction(node) { function convertDefinition(definition) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(definition, serializeProduction); } /* istanbul ignore else */ if (node instanceof NonTerminal) { return { type: "NonTerminal", name: node.nonTerminalName, idx: node.idx }; } else if (node instanceof Flat) { return { type: "Flat", definition: convertDefinition(node.definition) }; } else if (node instanceof Option) { return { type: "Option", idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionMandatory) { return { type: "RepetitionMandatory", name: node.name, idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionMandatoryWithSeparator) { return { type: "RepetitionMandatoryWithSeparator", name: node.name, idx: node.idx, separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), definition: convertDefinition(node.definition) }; } else if (node instanceof RepetitionWithSeparator) { return { type: "RepetitionWithSeparator", name: node.name, idx: node.idx, separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), definition: convertDefinition(node.definition) }; } else if (node instanceof Repetition) { return { type: "Repetition", name: node.name, idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof Alternation) { return { type: "Alternation", name: node.name, idx: node.idx, definition: convertDefinition(node.definition) }; } else if (node instanceof Terminal) { var serializedTerminal = { type: "Terminal", name: node.terminalType.name, label: (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_1__.tokenLabel)(node.terminalType), idx: node.idx }; var pattern = node.terminalType.PATTERN; if (node.terminalType.PATTERN) { serializedTerminal.pattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern) ? pattern.source : pattern; } return serializedTerminal; } else if (node instanceof Rule) { return { type: "Rule", name: node.name, orgText: node.orgText, definition: convertDefinition(node.definition) }; } else { throw Error("non exhaustive match"); } } //# sourceMappingURL=gast_public.js.map /***/ }), /* 21 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EOF: () => (/* binding */ EOF), /* harmony export */ createToken: () => (/* binding */ createToken), /* harmony export */ createTokenInstance: () => (/* binding */ createTokenInstance), /* harmony export */ hasTokenLabel: () => (/* binding */ hasTokenLabel), /* harmony export */ tokenLabel: () => (/* binding */ tokenLabel), /* harmony export */ tokenMatcher: () => (/* binding */ tokenMatcher), /* harmony export */ tokenName: () => (/* binding */ tokenName) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _lexer_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22); /* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27); function tokenLabel(tokType) { if (hasTokenLabel(tokType)) { return tokType.LABEL; } else { return tokType.name; } } function tokenName(tokType) { return tokType.name; } function hasTokenLabel(obj) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(obj.LABEL) && obj.LABEL !== ""; } var PARENT = "parent"; var CATEGORIES = "categories"; var LABEL = "label"; var GROUP = "group"; var PUSH_MODE = "push_mode"; var POP_MODE = "pop_mode"; var LONGER_ALT = "longer_alt"; var LINE_BREAKS = "line_breaks"; var START_CHARS_HINT = "start_chars_hint"; function createToken(config) { return createTokenInternal(config); } function createTokenInternal(config) { var pattern = config.pattern; var tokenType = {}; tokenType.name = config.name; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(pattern)) { tokenType.PATTERN = pattern; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, PARENT)) { throw "The parent property is no longer supported.\n" + "See: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details."; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, CATEGORIES)) { // casting to ANY as this will be fixed inside `augmentTokenTypes`` tokenType.CATEGORIES = config[CATEGORIES]; } (0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)([tokenType]); if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LABEL)) { tokenType.LABEL = config[LABEL]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, GROUP)) { tokenType.GROUP = config[GROUP]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, POP_MODE)) { tokenType.POP_MODE = config[POP_MODE]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, PUSH_MODE)) { tokenType.PUSH_MODE = config[PUSH_MODE]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LONGER_ALT)) { tokenType.LONGER_ALT = config[LONGER_ALT]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LINE_BREAKS)) { tokenType.LINE_BREAKS = config[LINE_BREAKS]; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, START_CHARS_HINT)) { tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; } return tokenType; } var EOF = createToken({ name: "EOF", pattern: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA }); (0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)([EOF]); function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) { return { image: image, startOffset: startOffset, endOffset: endOffset, startLine: startLine, endLine: endLine, startColumn: startColumn, endColumn: endColumn, tokenTypeIdx: tokType.tokenTypeIdx, tokenType: tokType }; } function tokenMatcher(token, tokType) { return (0,_tokens__WEBPACK_IMPORTED_MODULE_2__.tokenStructuredMatcher)(token, tokType); } //# sourceMappingURL=tokens_public.js.map /***/ }), /* 22 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Lexer: () => (/* binding */ Lexer), /* harmony export */ LexerDefinitionErrorType: () => (/* binding */ LexerDefinitionErrorType) /* harmony export */ }); /* harmony import */ var _lexer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27); /* harmony import */ var _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(28); /* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26); var LexerDefinitionErrorType; (function (LexerDefinitionErrorType) { LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"] = 0] = "MISSING_PATTERN"; LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"] = 1] = "INVALID_PATTERN"; LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND"; LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND"; LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND"; LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND"; LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST"; LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"; LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"; LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"; LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"; LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND"; LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN"; LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS"; LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN"; LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR"; LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK"; })(LexerDefinitionErrorType || (LexerDefinitionErrorType = {})); var DEFAULT_LEXER_CONFIG = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: ["\n", "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false }; Object.freeze(DEFAULT_LEXER_CONFIG); var Lexer = /** @class */ (function () { function Lexer(lexerDefinition, config) { var _this = this; if (config === void 0) { config = DEFAULT_LEXER_CONFIG; } this.lexerDefinition = lexerDefinition; this.lexerDefinitionErrors = []; this.lexerDefinitionWarning = []; this.patternIdxToConfig = {}; this.charCodeToPatternIdxToConfig = {}; this.modes = []; this.emptyGroups = {}; this.config = undefined; this.trackStartLines = true; this.trackEndLines = true; this.hasCustom = false; this.canModeBeOptimized = {}; if (typeof config === "boolean") { throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" + "a boolean 2nd argument is no longer supported"); } // todo: defaults func? this.config = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.merge)(DEFAULT_LEXER_CONFIG, config); var traceInitVal = this.config.traceInitPerf; if (traceInitVal === true) { this.traceInitMaxIdent = Infinity; this.traceInitPerf = true; } else if (typeof traceInitVal === "number") { this.traceInitMaxIdent = traceInitVal; this.traceInitPerf = true; } this.traceInitIndent = -1; this.TRACE_INIT("Lexer Constructor", function () { var actualDefinition; var hasOnlySingleMode = true; _this.TRACE_INIT("Lexer Config handling", function () { if (_this.config.lineTerminatorsPattern === DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) { // optimized built-in implementation for the defaults definition of lineTerminators _this.config.lineTerminatorsPattern = _lexer__WEBPACK_IMPORTED_MODULE_0__.LineTerminatorOptimizedTester; } else { if (_this.config.lineTerminatorCharacters === DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { throw Error("Error: Missing property on the Lexer config.\n" + "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS"); } } if (config.safeMode && config.ensureOptimizations) { throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); } _this.trackStartLines = /full|onlyStart/i.test(_this.config.positionTracking); _this.trackEndLines = /full/i.test(_this.config.positionTracking); // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isArray)(lexerDefinition)) { actualDefinition = { modes: {} }; actualDefinition.modes[_lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE] = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(lexerDefinition); actualDefinition[_lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE] = _lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE; } else { // no conversion needed, input should already be a IMultiModeLexerDefinition hasOnlySingleMode = false; actualDefinition = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneObj)((lexerDefinition)); } }); if (_this.config.skipValidations === false) { _this.TRACE_INIT("performRuntimeChecks", function () { _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.performRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); }); _this.TRACE_INIT("performWarningRuntimeChecks", function () { _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.performWarningRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); }); } // for extra robustness to avoid throwing an none informative error message actualDefinition.modes = actualDefinition.modes ? actualDefinition.modes : {}; // an error of undefined TokenTypes will be detected in "performRuntimeChecks" above. // this transformation is to increase robustness in the case of partially invalid lexer definition. (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(actualDefinition.modes, function (currModeValue, currModeName) { actualDefinition.modes[currModeName] = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reject)(currModeValue, function (currTokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(currTokType); }); }); var allModeNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.keys)(actualDefinition.modes); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(actualDefinition.modes, function (currModDef, currModName) { _this.TRACE_INIT("Mode: <" + currModName + "> processing", function () { _this.modes.push(currModName); if (_this.config.skipValidations === false) { _this.TRACE_INIT("validatePatterns", function () { _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.validatePatterns)(currModDef, allModeNames)); }); } // If definition errors were encountered, the analysis phase may fail unexpectedly/ // Considering a lexer with definition errors may never be used, there is no point // to performing the analysis anyhow... if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(_this.lexerDefinitionErrors)) { (0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)(currModDef); var currAnalyzeResult_1; _this.TRACE_INIT("analyzeTokenTypes", function () { currAnalyzeResult_1 = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.analyzeTokenTypes)(currModDef, { lineTerminatorCharacters: _this.config .lineTerminatorCharacters, positionTracking: config.positionTracking, ensureOptimizations: config.ensureOptimizations, safeMode: config.safeMode, tracer: _this.TRACE_INIT.bind(_this) }); }); _this.patternIdxToConfig[currModName] = currAnalyzeResult_1.patternIdxToConfig; _this.charCodeToPatternIdxToConfig[currModName] = currAnalyzeResult_1.charCodeToPatternIdxToConfig; _this.emptyGroups = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.merge)(_this.emptyGroups, currAnalyzeResult_1.emptyGroups); _this.hasCustom = currAnalyzeResult_1.hasCustom || _this.hasCustom; _this.canModeBeOptimized[currModName] = currAnalyzeResult_1.canBeOptimized; } }); }); _this.defaultMode = actualDefinition.defaultMode; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(_this.lexerDefinitionErrors) && !_this.config.deferDefinitionErrorsHandling) { var allErrMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(_this.lexerDefinitionErrors, function (error) { return error.message; }); var allErrMessagesString = allErrMessages.join("-----------------------\n"); throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString); } // Only print warning if there are no errors, This will avoid pl (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(_this.lexerDefinitionWarning, function (warningDescriptor) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_WARNING)(warningDescriptor.message); }); _this.TRACE_INIT("Choosing sub-methods implementations", function () { // Choose the relevant internal implementations for this specific parser. // These implementations should be in-lined by the JavaScript engine // to provide optimal performance in each scenario. if (_lexer__WEBPACK_IMPORTED_MODULE_0__.SUPPORT_STICKY) { _this.chopInput = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.IDENTITY; _this.match = _this.matchWithTest; } else { _this.updateLastIndex = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; _this.match = _this.matchWithExec; } if (hasOnlySingleMode) { _this.handleModes = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; } if (_this.trackStartLines === false) { _this.computeNewColumn = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.IDENTITY; } if (_this.trackEndLines === false) { _this.updateTokenEndLineColumnLocation = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; } if (/full/i.test(_this.config.positionTracking)) { _this.createTokenInstance = _this.createFullToken; } else if (/onlyStart/i.test(_this.config.positionTracking)) { _this.createTokenInstance = _this.createStartOnlyToken; } else if (/onlyOffset/i.test(_this.config.positionTracking)) { _this.createTokenInstance = _this.createOffsetOnlyToken; } else { throw Error("Invalid config option: \"" + _this.config.positionTracking + "\""); } if (_this.hasCustom) { _this.addToken = _this.addTokenUsingPush; _this.handlePayload = _this.handlePayloadWithCustom; } else { _this.addToken = _this.addTokenUsingMemberAccess; _this.handlePayload = _this.handlePayloadNoCustom; } }); _this.TRACE_INIT("Failed Optimization Warnings", function () { var unOptimizedModes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reduce)(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) { if (canBeOptimized === false) { cannotBeOptimized.push(modeName); } return cannotBeOptimized; }, []); if (config.ensureOptimizations && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(unOptimizedModes)) { throw Error("Lexer Modes: < " + unOptimizedModes.join(", ") + " > cannot be optimized.\n" + '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' + "\t Or inspect the console log for details on how to resolve these issues."); } }); _this.TRACE_INIT("clearRegExpParserCache", function () { (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.clearRegExpParserCache)(); }); _this.TRACE_INIT("toFastProperties", function () { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.toFastProperties)(_this); }); }); } Lexer.prototype.tokenize = function (text, initialMode) { if (initialMode === void 0) { initialMode = this.defaultMode; } if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.lexerDefinitionErrors)) { var allErrMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.lexerDefinitionErrors, function (error) { return error.message; }); var allErrMessagesString = allErrMessages.join("-----------------------\n"); throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString); } var lexResult = this.tokenizeInternal(text, initialMode); return lexResult; }; // There is quite a bit of duplication between this and "tokenizeInternalLazy" // This is intentional due to performance considerations. Lexer.prototype.tokenizeInternal = function (text, initialMode) { var _this = this; var i, j, matchAltImage, longerAltIdx, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match; var orgText = text; var orgLength = orgText.length; var offset = 0; var matchedTokensIndex = 0; // initializing the tokensArray to the "guessed" size. // guessing too little will still reduce the number of array re-sizes on pushes. // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory // but would still have a faster runtime by avoiding (All but one) array resizing. var guessedNumberOfTokens = this.hasCustom ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements. : Math.floor(text.length / 10); var matchedTokens = new Array(guessedNumberOfTokens); var errors = []; var line = this.trackStartLines ? 1 : undefined; var column = this.trackStartLines ? 1 : undefined; var groups = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.cloneEmptyGroups)(this.emptyGroups); var trackLines = this.trackStartLines; var lineTerminatorPattern = this.config.lineTerminatorsPattern; var currModePatternsLength = 0; var patternIdxToConfig = []; var currCharCodeToPatternIdxToConfig = []; var modeStack = []; var emptyArray = []; Object.freeze(emptyArray); var getPossiblePatterns = undefined; function getPossiblePatternsSlow() { return patternIdxToConfig; } function getPossiblePatternsOptimized(charCode) { var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.charCodeToOptimizedIndex)(charCode); var possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx]; if (possiblePatterns === undefined) { return emptyArray; } else { return possiblePatterns; } } var pop_mode = function (popToken) { // TODO: perhaps avoid this error in the edge case there is no more input? if (modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition" // So no error should occur. popToken.tokenType.PUSH_MODE === undefined) { // if we try to pop the last mode there lexer will no longer have ANY mode. // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode. var msg_1 = _this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken); errors.push({ offset: popToken.startOffset, line: popToken.startLine !== undefined ? popToken.startLine : undefined, column: popToken.startColumn !== undefined ? popToken.startColumn : undefined, length: popToken.image.length, message: msg_1 }); } else { modeStack.pop(); var newMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.last)(modeStack); patternIdxToConfig = _this.patternIdxToConfig[newMode]; currCharCodeToPatternIdxToConfig = _this .charCodeToPatternIdxToConfig[newMode]; currModePatternsLength = patternIdxToConfig.length; var modeCanBeOptimized = _this.canModeBeOptimized[newMode] && _this.config.safeMode === false; if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized; } else { getPossiblePatterns = getPossiblePatternsSlow; } } }; function push_mode(newMode) { modeStack.push(newMode); currCharCodeToPatternIdxToConfig = this .charCodeToPatternIdxToConfig[newMode]; patternIdxToConfig = this.patternIdxToConfig[newMode]; currModePatternsLength = patternIdxToConfig.length; currModePatternsLength = patternIdxToConfig.length; var modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false; if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) { getPossiblePatterns = getPossiblePatternsOptimized; } else { getPossiblePatterns = getPossiblePatternsSlow; } } // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not // seem to matter performance wise. push_mode.call(this, initialMode); var currConfig; while (offset < orgLength) { matchedImage = null; var nextCharCode = orgText.charCodeAt(offset); var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode); var chosenPatternsLength = chosenPatternIdxToConfig.length; for (i = 0; i < chosenPatternsLength; i++) { currConfig = chosenPatternIdxToConfig[i]; var currPattern = currConfig.pattern; payload = null; // manually in-lined because > 600 chars won't be in-lined in V8 var singleCharCode = currConfig.short; if (singleCharCode !== false) { if (nextCharCode === singleCharCode) { // single character string matchedImage = currPattern; } } else if (currConfig.isCustom === true) { match = currPattern.exec(orgText, offset, matchedTokens, groups); if (match !== null) { matchedImage = match[0]; if (match.payload !== undefined) { payload = match.payload; } } else { matchedImage = null; } } else { this.updateLastIndex(currPattern, offset); matchedImage = this.match(currPattern, text, offset); } if (matchedImage !== null) { // even though this pattern matched we must try a another longer alternative. // this can be used to prioritize keywords over identifiers longerAltIdx = currConfig.longerAlt; if (longerAltIdx !== undefined) { // TODO: micro optimize, avoid extra prop access // by saving/linking longerAlt on the original config? var longerAltConfig = patternIdxToConfig[longerAltIdx]; var longerAltPattern = longerAltConfig.pattern; altPayload = null; // single Char can never be a longer alt so no need to test it. // manually in-lined because > 600 chars won't be in-lined in V8 if (longerAltConfig.isCustom === true) { match = longerAltPattern.exec(orgText, offset, matchedTokens, groups); if (match !== null) { matchAltImage = match[0]; if (match.payload !== undefined) { altPayload = match.payload; } } else { matchAltImage = null; } } else { this.updateLastIndex(longerAltPattern, offset); matchAltImage = this.match(longerAltPattern, text, offset); } if (matchAltImage && matchAltImage.length > matchedImage.length) { matchedImage = matchAltImage; payload = altPayload; currConfig = longerAltConfig; } } break; } } // successful match if (matchedImage !== null) { imageLength = matchedImage.length; group = currConfig.group; if (group !== undefined) { tokType = currConfig.tokenTypeIdx; // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside // createFullToken method newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength); this.handlePayload(newToken, payload); // TODO: optimize NOOP in case there are no special groups? if (group === false) { matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken); } else { groups[group].push(newToken); } } text = this.chopInput(text, imageLength); offset = offset + imageLength; // TODO: with newlines the column may be assigned twice column = this.computeNewColumn(column, imageLength); if (trackLines === true && currConfig.canLineTerminator === true) { var numOfLTsInMatch = 0; var foundTerminator = void 0; var lastLTEndOffset = void 0; lineTerminatorPattern.lastIndex = 0; do { foundTerminator = lineTerminatorPattern.test(matchedImage); if (foundTerminator === true) { lastLTEndOffset = lineTerminatorPattern.lastIndex - 1; numOfLTsInMatch++; } } while (foundTerminator === true); if (numOfLTsInMatch !== 0) { line = line + numOfLTsInMatch; column = imageLength - lastLTEndOffset; this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength); } } // will be NOOP if no modes present this.handleModes(currConfig, pop_mode, push_mode, newToken); } else { // error recovery, drop characters until we identify a valid token's start point var errorStartOffset = offset; var errorLine = line; var errorColumn = column; var foundResyncPoint = false; while (!foundResyncPoint && offset < orgLength) { // drop chars until we succeed in matching something droppedChar = orgText.charCodeAt(offset); // Identity Func (when sticky flag is enabled) text = this.chopInput(text, 1); offset++; for (j = 0; j < currModePatternsLength; j++) { var currConfig_1 = patternIdxToConfig[j]; var currPattern = currConfig_1.pattern; // manually in-lined because > 600 chars won't be in-lined in V8 var singleCharCode = currConfig_1.short; if (singleCharCode !== false) { if (orgText.charCodeAt(offset) === singleCharCode) { // single character string foundResyncPoint = true; } } else if (currConfig_1.isCustom === true) { foundResyncPoint = currPattern.exec(orgText, offset, matchedTokens, groups) !== null; } else { this.updateLastIndex(currPattern, offset); foundResyncPoint = currPattern.exec(text) !== null; } if (foundResyncPoint === true) { break; } } } errLength = offset - errorStartOffset; // at this point we either re-synced or reached the end of the input text msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn); errors.push({ offset: errorStartOffset, line: errorLine, column: errorColumn, length: errLength, message: msg }); } } // if we do have custom patterns which push directly into the // TODO: custom tokens should not push directly?? if (!this.hasCustom) { // if we guessed a too large size for the tokens array this will shrink it to the right size. matchedTokens.length = matchedTokensIndex; } return { tokens: matchedTokens, groups: groups, errors: errors }; }; Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) { if (config.pop === true) { // need to save the PUSH_MODE property as if the mode is popped // patternIdxToPopMode is updated to reflect the new mode after popping the stack var pushMode = config.push; pop_mode(newToken); if (pushMode !== undefined) { push_mode.call(this, pushMode); } } else if (config.push !== undefined) { push_mode.call(this, config.push); } }; Lexer.prototype.chopInput = function (text, length) { return text.substring(length); }; Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) { regExp.lastIndex = newLastIndex; }; // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) { var lastCharIsLT, fixForEndingInLT; if (group !== undefined) { // a none skipped multi line Token, need to update endLine/endColumn lastCharIsLT = lastLTIdx === imageLength - 1; fixForEndingInLT = lastCharIsLT ? -1 : 0; if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) { // if a token ends in a LT that last LT only affects the line numbering of following Tokens newToken.endLine = line + fixForEndingInLT; // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd) // inclusive to exclusive range. newToken.endColumn = column - 1 + -fixForEndingInLT; } // else single LT in the last character of a token, no need to modify the endLine/EndColumn } }; Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) { return oldColumn + imageLength; }; // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. /* istanbul ignore next - place holder */ Lexer.prototype.createTokenInstance = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return null; }; Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) { return { image: image, startOffset: startOffset, tokenTypeIdx: tokenTypeIdx, tokenType: tokenType }; }; Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) { return { image: image, startOffset: startOffset, startLine: startLine, startColumn: startColumn, tokenTypeIdx: tokenTypeIdx, tokenType: tokenType }; }; Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) { return { image: image, startOffset: startOffset, endOffset: startOffset + imageLength - 1, startLine: startLine, endLine: startLine, startColumn: startColumn, endColumn: startColumn + imageLength - 1, tokenTypeIdx: tokenTypeIdx, tokenType: tokenType }; }; // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime. /* istanbul ignore next - place holder */ Lexer.prototype.addToken = function (tokenVector, index, tokenToAdd) { return 666; }; Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) { tokenVector.push(tokenToAdd); return index; }; Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) { tokenVector[index] = tokenToAdd; index++; return index; }; // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime. /* istanbul ignore next - place holder */ Lexer.prototype.handlePayload = function (token, payload) { }; Lexer.prototype.handlePayloadNoCustom = function (token, payload) { }; Lexer.prototype.handlePayloadWithCustom = function (token, payload) { if (payload !== null) { token.payload = payload; } }; /* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */ Lexer.prototype.match = function (pattern, text, offset) { return null; }; Lexer.prototype.matchWithTest = function (pattern, text, offset) { var found = pattern.test(text); if (found === true) { return text.substring(offset, pattern.lastIndex); } return null; }; Lexer.prototype.matchWithExec = function (pattern, text) { var regExpArray = pattern.exec(text); return regExpArray !== null ? regExpArray[0] : regExpArray; }; // Duplicated from the parser's perf trace trait to allow future extraction // of the lexer to a separate package. Lexer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { // No need to optimize this using NOOP pattern because // It is not called in a hot spot... if (this.traceInitPerf === true) { this.traceInitIndent++; var indent = new Array(this.traceInitIndent + 1).join("\t"); if (this.traceInitIndent < this.traceInitMaxIdent) { console.log(indent + "--> <" + phaseDesc + ">"); } var _a = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.timer)(phaseImpl), time = _a.time, value = _a.value; /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ var traceMethod = time > 10 ? console.warn : console.log; if (this.traceInitIndent < this.traceInitMaxIdent) { traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms"); } this.traceInitIndent--; return value; } else { return phaseImpl(); } }; Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" + "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace."; Lexer.NA = /NOT_APPLICABLE/; return Lexer; }()); //# sourceMappingURL=lexer_public.js.map /***/ }), /* 23 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DEFAULT_MODE: () => (/* binding */ DEFAULT_MODE), /* harmony export */ LineTerminatorOptimizedTester: () => (/* binding */ LineTerminatorOptimizedTester), /* harmony export */ MODES: () => (/* binding */ MODES), /* harmony export */ SUPPORT_STICKY: () => (/* binding */ SUPPORT_STICKY), /* harmony export */ addStartOfInput: () => (/* binding */ addStartOfInput), /* harmony export */ addStickyFlag: () => (/* binding */ addStickyFlag), /* harmony export */ analyzeTokenTypes: () => (/* binding */ analyzeTokenTypes), /* harmony export */ buildLineBreakIssueMessage: () => (/* binding */ buildLineBreakIssueMessage), /* harmony export */ charCodeToOptimizedIndex: () => (/* binding */ charCodeToOptimizedIndex), /* harmony export */ cloneEmptyGroups: () => (/* binding */ cloneEmptyGroups), /* harmony export */ disableSticky: () => (/* binding */ disableSticky), /* harmony export */ enableSticky: () => (/* binding */ enableSticky), /* harmony export */ findDuplicatePatterns: () => (/* binding */ findDuplicatePatterns), /* harmony export */ findEmptyMatchRegExps: () => (/* binding */ findEmptyMatchRegExps), /* harmony export */ findEndOfInputAnchor: () => (/* binding */ findEndOfInputAnchor), /* harmony export */ findInvalidGroupType: () => (/* binding */ findInvalidGroupType), /* harmony export */ findInvalidPatterns: () => (/* binding */ findInvalidPatterns), /* harmony export */ findMissingPatterns: () => (/* binding */ findMissingPatterns), /* harmony export */ findModesThatDoNotExist: () => (/* binding */ findModesThatDoNotExist), /* harmony export */ findStartOfInputAnchor: () => (/* binding */ findStartOfInputAnchor), /* harmony export */ findUnreachablePatterns: () => (/* binding */ findUnreachablePatterns), /* harmony export */ findUnsupportedFlags: () => (/* binding */ findUnsupportedFlags), /* harmony export */ isCustomPattern: () => (/* binding */ isCustomPattern), /* harmony export */ isShortPattern: () => (/* binding */ isShortPattern), /* harmony export */ minOptimizationVal: () => (/* binding */ minOptimizationVal), /* harmony export */ performRuntimeChecks: () => (/* binding */ performRuntimeChecks), /* harmony export */ performWarningRuntimeChecks: () => (/* binding */ performWarningRuntimeChecks), /* harmony export */ validatePatterns: () => (/* binding */ validatePatterns) /* harmony export */ }); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _lexer_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); /* harmony import */ var _reg_exp__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25); /* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PATTERN = "PATTERN"; var DEFAULT_MODE = "defaultMode"; var MODES = "modes"; var SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean"; function disableSticky() { SUPPORT_STICKY = false; } function enableSticky() { SUPPORT_STICKY = true; } function analyzeTokenTypes(tokenTypes, options) { options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.defaults)(options, { useSticky: SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", "\n"], tracer: function (msg, action) { return action(); } }); var tracer = options.tracer; tracer("initCharCodeToOptimizedIndexMap", function () { initCharCodeToOptimizedIndexMap(); }); var onlyRelevantTypes; tracer("Reject Lexer.NA", function () { onlyRelevantTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reject)(tokenTypes, function (currType) { return currType[PATTERN] === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA; }); }); var hasCustom = false; var allTransformedPatterns; tracer("Transform Patterns", function () { hasCustom = false; allTransformedPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (currType) { var currPattern = currType[PATTERN]; /* istanbul ignore else */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currPattern)) { var regExpSource = currPattern.source; if (regExpSource.length === 1 && // only these regExp meta characters which can appear in a length one regExp regExpSource !== "^" && regExpSource !== "$" && regExpSource !== ".") { return regExpSource; } else if (regExpSource.length === 2 && regExpSource[0] === "\\" && // not a meta character !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)([ "d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W" ], regExpSource[1])) { // escaped meta Characters: /\+/ /\[/ // or redundant escaping: /\a/ // without the escaping "\" return regExpSource[1]; } else { return options.useSticky ? addStickyFlag(currPattern) : addStartOfInput(currPattern); } } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(currPattern)) { hasCustom = true; // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object return { exec: currPattern }; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(currPattern, "exec")) { hasCustom = true; // ICustomPattern return currPattern; } else if (typeof currPattern === "string") { if (currPattern.length === 1) { return currPattern; } else { var escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); var wrappedRegExp = new RegExp(escapedRegExpString); return options.useSticky ? addStickyFlag(wrappedRegExp) : addStartOfInput(wrappedRegExp); } } else { throw Error("non exhaustive match"); } }); }); var patternIdxToType; var patternIdxToGroup; var patternIdxToLongerAltIdx; var patternIdxToPushMode; var patternIdxToPopMode; tracer("misc mapping", function () { patternIdxToType = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; }); patternIdxToGroup = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) { var groupName = clazz.GROUP; /* istanbul ignore next */ if (groupName === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED) { return undefined; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(groupName)) { return groupName; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isUndefined)(groupName)) { return false; } else { throw Error("non exhaustive match"); } }); patternIdxToLongerAltIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) { var longerAltType = clazz.LONGER_ALT; if (longerAltType) { var longerAltIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.indexOf)(onlyRelevantTypes, longerAltType); return longerAltIdx; } }); patternIdxToPushMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; }); patternIdxToPopMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(clazz, "POP_MODE"); }); }); var patternIdxToCanLineTerminator; tracer("Line Terminator Handling", function () { var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); patternIdxToCanLineTerminator = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (tokType) { return false; }); if (options.positionTracking !== "onlyOffset") { patternIdxToCanLineTerminator = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (tokType) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) { return tokType.LINE_BREAKS; } else { if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) { return (0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN); } } }); } }); var patternIdxToIsCustom; var patternIdxToShort; var emptyGroups; var patternIdxToConfig; tracer("Misc Mapping #2", function () { patternIdxToIsCustom = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, isCustomPattern); patternIdxToShort = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(allTransformedPatterns, isShortPattern); emptyGroups = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(onlyRelevantTypes, function (acc, clazz) { var groupName = clazz.GROUP; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(groupName) && !(groupName === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED)) { acc[groupName] = []; } return acc; }, {}); patternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(allTransformedPatterns, function (x, idx) { return { pattern: allTransformedPatterns[idx], longerAlt: patternIdxToLongerAltIdx[idx], canLineTerminator: patternIdxToCanLineTerminator[idx], isCustom: patternIdxToIsCustom[idx], short: patternIdxToShort[idx], group: patternIdxToGroup[idx], push: patternIdxToPushMode[idx], pop: patternIdxToPopMode[idx], tokenTypeIdx: patternIdxToType[idx], tokenType: onlyRelevantTypes[idx] }; }); }); var canBeOptimized = true; var charCodeToPatternIdxToConfig = []; if (!options.safeMode) { tracer("First Char Optimization", function () { charCodeToPatternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(onlyRelevantTypes, function (result, currTokType, idx) { if (typeof currTokType.PATTERN === "string") { var charCode = currTokType.PATTERN.charCodeAt(0); var optimizedIdx = charCodeToOptimizedIndex(charCode); addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isArray)(currTokType.START_CHARS_HINT)) { var lastOptimizedIdx_1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(currTokType.START_CHARS_HINT, function (charOrInt) { var charCode = typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt; var currOptimizedIdx = charCodeToOptimizedIndex(charCode); // Avoid adding the config multiple times if (lastOptimizedIdx_1 !== currOptimizedIdx) { lastOptimizedIdx_1 = currOptimizedIdx; addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); } }); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currTokType.PATTERN)) { if (currTokType.PATTERN.unicode) { canBeOptimized = false; if (options.ensureOptimizations) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.PRINT_ERROR)("" + _reg_exp__WEBPACK_IMPORTED_MODULE_3__.failedOptimizationPrefixMsg + ("\tUnable to analyze < " + currTokType.PATTERN.toString() + " > pattern.\n") + "\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" + "\tThis will disable the lexer's first char optimizations.\n" + "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE"); } } else { var optimizedCodes = (0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.getOptimizedStartCodesIndices)(currTokType.PATTERN, options.ensureOptimizations); /* istanbul ignore if */ // start code will only be empty given an empty regExp or failure of regexp-to-ast library // the first should be a different validation and the second cannot be tested. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isEmpty)(optimizedCodes)) { // we cannot understand what codes may start possible matches // The optimization correctness requires knowing start codes for ALL patterns. // Not actually sure this is an error, no debug message canBeOptimized = false; } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(optimizedCodes, function (code) { addToMapOfArrays(result, code, patternIdxToConfig[idx]); }); } } else { if (options.ensureOptimizations) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.PRINT_ERROR)("" + _reg_exp__WEBPACK_IMPORTED_MODULE_3__.failedOptimizationPrefixMsg + ("\tTokenType: <" + currTokType.name + "> is using a custom token pattern without providing parameter.\n") + "\tThis will disable the lexer's first char optimizations.\n" + "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE"); } canBeOptimized = false; } return result; }, []); }); } tracer("ArrayPacking", function () { charCodeToPatternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.packArray)(charCodeToPatternIdxToConfig); }); return { emptyGroups: emptyGroups, patternIdxToConfig: patternIdxToConfig, charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig, hasCustom: hasCustom, canBeOptimized: canBeOptimized }; } function validatePatterns(tokenTypes, validModesNames) { var errors = []; var missingResult = findMissingPatterns(tokenTypes); errors = errors.concat(missingResult.errors); var invalidResult = findInvalidPatterns(missingResult.valid); var validTokenTypes = invalidResult.valid; errors = errors.concat(invalidResult.errors); errors = errors.concat(validateRegExpPattern(validTokenTypes)); errors = errors.concat(findInvalidGroupType(validTokenTypes)); errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames)); errors = errors.concat(findUnreachablePatterns(validTokenTypes)); return errors; } function validateRegExpPattern(tokenTypes) { var errors = []; var withRegExpPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currTokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currTokType[PATTERN]); }); errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns)); errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns)); errors = errors.concat(findUnsupportedFlags(withRegExpPatterns)); errors = errors.concat(findDuplicatePatterns(withRegExpPatterns)); errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns)); return errors; } function findMissingPatterns(tokenTypes) { var tokenTypesWithMissingPattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { return !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(currType, PATTERN); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypesWithMissingPattern, function (currType) { return { message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [currType] }; }); var valid = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.difference)(tokenTypes, tokenTypesWithMissingPattern); return { errors: errors, valid: valid }; } function findInvalidPatterns(tokenTypes) { var tokenTypesWithInvalidPattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { var pattern = currType[PATTERN]; return (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec") && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern)); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypesWithInvalidPattern, function (currType) { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' can only be a RegExp, a" + " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [currType] }; }); var valid = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.difference)(tokenTypes, tokenTypesWithInvalidPattern); return { errors: errors, valid: valid }; } var end_of_input = /[^\\][\$]/; function findEndOfInputAnchor(tokenTypes) { var EndAnchorFinder = /** @class */ (function (_super) { __extends(EndAnchorFinder, _super); function EndAnchorFinder() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.found = false; return _this; } EndAnchorFinder.prototype.visitEndAnchor = function (node) { this.found = true; }; return EndAnchorFinder; }(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor)); var invalidRegex = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { var pattern = currType[PATTERN]; try { var regexpAst = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.getRegExpAst)(pattern); var endAnchorVisitor = new EndAnchorFinder(); endAnchorVisitor.visit(regexpAst); return endAnchorVisitor.found; } catch (e) { // old behavior in case of runtime exceptions with regexp-to-ast. /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ return end_of_input.test(pattern.source); } }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidRegex, function (currType) { return { message: "Unexpected RegExp Anchor Error:\n" + "\tToken Type: ->" + currType.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n" + "\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" + "\tfor details.", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [currType] }; }); return errors; } function findEmptyMatchRegExps(tokenTypes) { var matchesEmptyString = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { var pattern = currType[PATTERN]; return pattern.test(""); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(matchesEmptyString, function (currType) { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [currType] }; }); return errors; } var start_of_input = /[^\\[][\^]|^\^/; function findStartOfInputAnchor(tokenTypes) { var StartAnchorFinder = /** @class */ (function (_super) { __extends(StartAnchorFinder, _super); function StartAnchorFinder() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.found = false; return _this; } StartAnchorFinder.prototype.visitStartAnchor = function (node) { this.found = true; }; return StartAnchorFinder; }(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor)); var invalidRegex = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { var pattern = currType[PATTERN]; try { var regexpAst = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.getRegExpAst)(pattern); var startAnchorVisitor = new StartAnchorFinder(); startAnchorVisitor.visit(regexpAst); return startAnchorVisitor.found; } catch (e) { // old behavior in case of runtime exceptions with regexp-to-ast. /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/ return start_of_input.test(pattern.source); } }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidRegex, function (currType) { return { message: "Unexpected RegExp Anchor Error:\n" + "\tToken Type: ->" + currType.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n" + "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" + "\tfor details.", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [currType] }; }); return errors; } function findUnsupportedFlags(tokenTypes) { var invalidFlags = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) { var pattern = currType[PATTERN]; return (pattern instanceof RegExp && (pattern.multiline || pattern.global)); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidFlags, function (currType) { return { message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [currType] }; }); return errors; } // This can only test for identical duplicate RegExps, not semantically equivalent ones. function findDuplicatePatterns(tokenTypes) { var found = []; var identicalPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypes, function (outerType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(tokenTypes, function (result, innerType) { if (outerType.PATTERN.source === innerType.PATTERN.source && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)(found, innerType) && innerType.PATTERN !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA) { // this avoids duplicates in the result, each Token Type may only appear in one "set" // in essence we are creating Equivalence classes on equality relation. found.push(innerType); result.push(innerType); return result; } return result; }, []); }); identicalPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.compact)(identicalPatterns); var duplicatePatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(identicalPatterns, function (currIdenticalSet) { return currIdenticalSet.length > 1; }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(duplicatePatterns, function (setOfIdentical) { var tokenTypeNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(setOfIdentical, function (currType) { return currType.name; }); var dupPatternSrc = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.first)(setOfIdentical).PATTERN; return { message: "The same RegExp pattern ->" + dupPatternSrc + "<-" + ("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"), type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: setOfIdentical }; }); return errors; } function findInvalidGroupType(tokenTypes) { var invalidTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (clazz) { if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(clazz, "GROUP")) { return false; } var group = clazz.GROUP; return group !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED && group !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(group); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidTypes, function (currType) { return { message: "Token Type: ->" + currType.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [currType] }; }); return errors; } function findModesThatDoNotExist(tokenTypes, validModes) { var invalidModes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (clazz) { return (clazz.PUSH_MODE !== undefined && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)(validModes, clazz.PUSH_MODE)); }); var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidModes, function (tokType) { var msg = "Token Type: ->" + tokType.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + tokType.PUSH_MODE + "<-" + "which does not exist"; return { message: msg, type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [tokType] }; }); return errors; } function findUnreachablePatterns(tokenTypes) { var errors = []; var canBeTested = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(tokenTypes, function (result, tokType, idx) { var pattern = tokType.PATTERN; if (pattern === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA) { return result; } // a more comprehensive validation for all forms of regExps would require // deeper regExp analysis capabilities if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern)) { result.push({ str: pattern, idx: idx, tokenType: tokType }); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern) && noMetaChar(pattern)) { result.push({ str: pattern.source, idx: idx, tokenType: tokType }); } return result; }, []); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(tokenTypes, function (tokType, testIdx) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(canBeTested, function (_a) { var str = _a.str, idx = _a.idx, tokenType = _a.tokenType; if (testIdx < idx && testTokenType(str, tokType.PATTERN)) { var msg = "Token: ->" + tokenType.name + "<- can never be matched.\n" + ("Because it appears AFTER the Token Type ->" + tokType.name + "<-") + "in the lexer's definition.\n" + "See https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE"; errors.push({ message: msg, type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [tokType, tokenType] }); } }); }); return errors; } function testTokenType(str, pattern) { /* istanbul ignore else */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern)) { var regExpArray = pattern.exec(str); return regExpArray !== null && regExpArray.index === 0; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern)) { // maintain the API of custom patterns return pattern(str, 0, [], {}); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec")) { // maintain the API of custom patterns return pattern.exec(str, 0, [], {}); } else if (typeof pattern === "string") { return pattern === str; } else { throw Error("non exhaustive match"); } } function noMetaChar(regExp) { //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp var metaChars = [ ".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{" ]; return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.find)(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) === undefined); } function addStartOfInput(pattern) { var flags = pattern.ignoreCase ? "i" : ""; // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) return new RegExp("^(?:" + pattern.source + ")", flags); } function addStickyFlag(pattern) { var flags = pattern.ignoreCase ? "iy" : "y"; // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input. // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/) return new RegExp("" + pattern.source, flags); } function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { var errors = []; // some run time checks to help the end users. if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, DEFAULT_MODE)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + DEFAULT_MODE + "> property in its definition\n", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }); } if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES)) { errors.push({ message: "A MultiMode Lexer cannot be initialized without a <" + MODES + "> property in its definition\n", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }); } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES) && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, DEFAULT_MODE) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition.modes, lexerDefinition.defaultMode)) { errors.push({ message: "A MultiMode Lexer cannot be initialized with a " + DEFAULT_MODE + ": <" + lexerDefinition.defaultMode + ">" + "which does not exist\n", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }); } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES)) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(lexerDefinition.modes, function (currModeValue, currModeName) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(currModeValue, function (currTokType, currIdx) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isUndefined)(currTokType)) { errors.push({ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + ("<" + currModeName + "> at index: <" + currIdx + ">\n"), type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }); } }); }); } return errors; } function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { var warnings = []; var hasAnyLineBreak = false; var allTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.compact)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.mapValues)(lexerDefinition.modes, function (tokTypes) { return tokTypes; }))); var concreteTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reject)(allTokenTypes, function (currType) { return currType[PATTERN] === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA; }); var terminatorCharCodes = getCharCodes(lineTerminatorCharacters); if (trackLines) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(concreteTokenTypes, function (tokType) { var currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes); if (currIssue !== false) { var message = buildLineBreakIssueMessage(tokType, currIssue); var warningDescriptor = { message: message, type: currIssue.issue, tokenType: tokType }; warnings.push(warningDescriptor); } else { // we don't want to attempt to scan if the user explicitly specified the line_breaks option. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) { if (tokType.LINE_BREAKS === true) { hasAnyLineBreak = true; } } else { if ((0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(terminatorCharCodes, tokType.PATTERN)) { hasAnyLineBreak = true; } } } }); } if (trackLines && !hasAnyLineBreak) { warnings.push({ message: "Warning: No LINE_BREAKS Found.\n" + "\tThis Lexer has been defined to track line and column information,\n" + "\tBut none of the Token Types can be identified as matching a line terminator.\n" + "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" + "\tfor details.", type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }); } return warnings; } function cloneEmptyGroups(emptyGroups) { var clonedResult = {}; var groupKeys = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.keys)(emptyGroups); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(groupKeys, function (currKey) { var currGroupValue = emptyGroups[currKey]; /* istanbul ignore else */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isArray)(currGroupValue)) { clonedResult[currKey] = []; } else { throw Error("non exhaustive match"); } }); return clonedResult; } // TODO: refactor to avoid duplication function isCustomPattern(tokenType) { var pattern = tokenType.PATTERN; /* istanbul ignore else */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern)) { return false; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern)) { // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object return true; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec")) { // ICustomPattern return true; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern)) { return false; } else { throw Error("non exhaustive match"); } } function isShortPattern(pattern) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern) && pattern.length === 1) { return pattern.charCodeAt(0); } else { return false; } } /** * Faster than using a RegExp for default newline detection during lexing. */ var LineTerminatorOptimizedTester = { // implements /\n|\r\n?/g.test test: function (text) { var len = text.length; for (var i = this.lastIndex; i < len; i++) { var c = text.charCodeAt(i); if (c === 10) { this.lastIndex = i + 1; return true; } else if (c === 13) { if (text.charCodeAt(i + 1) === 10) { this.lastIndex = i + 2; } else { this.lastIndex = i + 1; } return true; } } return false; }, lastIndex: 0 }; function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) { // if the user explicitly declared the line_breaks option we will respect their choice // and assume it is correct. return false; } else { /* istanbul ignore else */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(tokType.PATTERN)) { try { (0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN); } catch (e) { /* istanbul ignore next - to test this we would have to mock to throw an error */ return { issue: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: e.message }; } return false; } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(tokType.PATTERN)) { // string literal patterns can always be analyzed to detect line terminator usage return false; } else if (isCustomPattern(tokType)) { // custom token types return { issue: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; } else { throw Error("non exhaustive match"); } } } function buildLineBreakIssueMessage(tokType, details) { /* istanbul ignore else */ if (details.issue === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) { return ("Warning: unable to identify line terminator usage in pattern.\n" + ("\tThe problem is in the <" + tokType.name + "> Token Type\n") + ("\t Root cause: " + details.errMsg + ".\n") + "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"); } else if (details.issue === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { return ("Warning: A Custom Token Pattern should specify the option.\n" + ("\tThe problem is in the <" + tokType.name + "> Token Type\n") + "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"); } else { throw Error("non exhaustive match"); } } function getCharCodes(charsOrCodes) { var charCodes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(charsOrCodes, function (numOrString) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(numOrString) && numOrString.length > 0) { return numOrString.charCodeAt(0); } else { return numOrString; } }); return charCodes; } function addToMapOfArrays(map, key, value) { if (map[key] === undefined) { map[key] = [value]; } else { map[key].push(value); } } var minOptimizationVal = 256; /** * We ae mapping charCode above ASCI (256) into buckets each in the size of 256. * This is because ASCI are the most common start chars so each one of those will get its own * possible token configs vector. * * Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford" * to place these into buckets of possible token configs, What we gain from * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig' * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario). * Our 'charCodeToPatternIdxToConfig' max size will now be: * 256 + (2^16 / 2^8) - 1 === 511 * * note the hack for fast division integer part extraction * See: https://stackoverflow.com/a/4228528 */ function charCodeToOptimizedIndex(charCode) { return charCode < minOptimizationVal ? charCode : charCodeToOptimizedIdxMap[charCode]; } /** * This is a compromise between cold start / hot running performance * Creating this array takes ~3ms on a modern machine, * But if we perform the computation at runtime as needed the CSS Lexer benchmark * performance degrades by ~10% * * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used. */ var charCodeToOptimizedIdxMap = []; function initCharCodeToOptimizedIndexMap() { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isEmpty)(charCodeToOptimizedIdxMap)) { charCodeToOptimizedIdxMap = new Array(65536); for (var i = 0; i < 65536; i++) { /* tslint:disable */ charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i; /* tslint:enable */ } } } //# sourceMappingURL=lexer.js.map /***/ }), /* 24 */ /***/ (function(module, exports) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;;(function(root, factory) { // istanbul ignore next if (true) { // istanbul ignore next !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) } else {} })( typeof self !== "undefined" ? // istanbul ignore next self : this, function() { // references // https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983 // https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern function RegExpParser() {} RegExpParser.prototype.saveState = function() { return { idx: this.idx, input: this.input, groupIdx: this.groupIdx } } RegExpParser.prototype.restoreState = function(newState) { this.idx = newState.idx this.input = newState.input this.groupIdx = newState.groupIdx } RegExpParser.prototype.pattern = function(input) { // parser state this.idx = 0 this.input = input this.groupIdx = 0 this.consumeChar("/") var value = this.disjunction() this.consumeChar("/") var flags = { type: "Flags", global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false } while (this.isRegExpFlag()) { switch (this.popChar()) { case "g": addFlag(flags, "global") break case "i": addFlag(flags, "ignoreCase") break case "m": addFlag(flags, "multiLine") break case "u": addFlag(flags, "unicode") break case "y": addFlag(flags, "sticky") break } } if (this.idx !== this.input.length) { throw Error( "Redundant input: " + this.input.substring(this.idx) ) } return { type: "Pattern", flags: flags, value: value } } RegExpParser.prototype.disjunction = function() { var alts = [] alts.push(this.alternative()) while (this.peekChar() === "|") { this.consumeChar("|") alts.push(this.alternative()) } return { type: "Disjunction", value: alts } } RegExpParser.prototype.alternative = function() { var terms = [] while (this.isTerm()) { terms.push(this.term()) } return { type: "Alternative", value: terms } } RegExpParser.prototype.term = function() { if (this.isAssertion()) { return this.assertion() } else { return this.atom() } } RegExpParser.prototype.assertion = function() { switch (this.popChar()) { case "^": return { type: "StartAnchor" } case "$": return { type: "EndAnchor" } // '\b' or '\B' case "\\": switch (this.popChar()) { case "b": return { type: "WordBoundary" } case "B": return { type: "NonWordBoundary" } } // istanbul ignore next throw Error("Invalid Assertion Escape") // '(?=' or '(?!' case "(": this.consumeChar("?") var type switch (this.popChar()) { case "=": type = "Lookahead" break case "!": type = "NegativeLookahead" break } ASSERT_EXISTS(type) var disjunction = this.disjunction() this.consumeChar(")") return { type: type, value: disjunction } } // istanbul ignore next ASSERT_NEVER_REACH_HERE() } RegExpParser.prototype.quantifier = function(isBacktracking) { var range switch (this.popChar()) { case "*": range = { atLeast: 0, atMost: Infinity } break case "+": range = { atLeast: 1, atMost: Infinity } break case "?": range = { atLeast: 0, atMost: 1 } break case "{": var atLeast = this.integerIncludingZero() switch (this.popChar()) { case "}": range = { atLeast: atLeast, atMost: atLeast } break case ",": var atMost if (this.isDigit()) { atMost = this.integerIncludingZero() range = { atLeast: atLeast, atMost: atMost } } else { range = { atLeast: atLeast, atMost: Infinity } } this.consumeChar("}") break } // throwing exceptions from "ASSERT_EXISTS" during backtracking // causes severe performance degradations if (isBacktracking === true && range === undefined) { return undefined } ASSERT_EXISTS(range) break } // throwing exceptions from "ASSERT_EXISTS" during backtracking // causes severe performance degradations if (isBacktracking === true && range === undefined) { return undefined } ASSERT_EXISTS(range) if (this.peekChar(0) === "?") { this.consumeChar("?") range.greedy = false } else { range.greedy = true } range.type = "Quantifier" return range } RegExpParser.prototype.atom = function() { var atom switch (this.peekChar()) { case ".": atom = this.dotAll() break case "\\": atom = this.atomEscape() break case "[": atom = this.characterClass() break case "(": atom = this.group() break } if (atom === undefined && this.isPatternCharacter()) { atom = this.patternCharacter() } ASSERT_EXISTS(atom) if (this.isQuantifier()) { atom.quantifier = this.quantifier() } return atom } RegExpParser.prototype.dotAll = function() { this.consumeChar(".") return { type: "Set", complement: true, value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")] } } RegExpParser.prototype.atomEscape = function() { this.consumeChar("\\") switch (this.peekChar()) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": return this.decimalEscapeAtom() case "d": case "D": case "s": case "S": case "w": case "W": return this.characterClassEscape() case "f": case "n": case "r": case "t": case "v": return this.controlEscapeAtom() case "c": return this.controlLetterEscapeAtom() case "0": return this.nulCharacterAtom() case "x": return this.hexEscapeSequenceAtom() case "u": return this.regExpUnicodeEscapeSequenceAtom() default: return this.identityEscapeAtom() } } RegExpParser.prototype.decimalEscapeAtom = function() { var value = this.positiveInteger() return { type: "GroupBackReference", value: value } } RegExpParser.prototype.characterClassEscape = function() { var set var complement = false switch (this.popChar()) { case "d": set = digitsCharCodes break case "D": set = digitsCharCodes complement = true break case "s": set = whitespaceCodes break case "S": set = whitespaceCodes complement = true break case "w": set = wordCharCodes break case "W": set = wordCharCodes complement = true break } ASSERT_EXISTS(set) return { type: "Set", value: set, complement: complement } } RegExpParser.prototype.controlEscapeAtom = function() { var escapeCode switch (this.popChar()) { case "f": escapeCode = cc("\f") break case "n": escapeCode = cc("\n") break case "r": escapeCode = cc("\r") break case "t": escapeCode = cc("\t") break case "v": escapeCode = cc("\v") break } ASSERT_EXISTS(escapeCode) return { type: "Character", value: escapeCode } } RegExpParser.prototype.controlLetterEscapeAtom = function() { this.consumeChar("c") var letter = this.popChar() if (/[a-zA-Z]/.test(letter) === false) { throw Error("Invalid ") } var letterCode = letter.toUpperCase().charCodeAt(0) - 64 return { type: "Character", value: letterCode } } RegExpParser.prototype.nulCharacterAtom = function() { // TODO implement '[lookahead ∉ DecimalDigit]' // TODO: for the deprecated octal escape sequence this.consumeChar("0") return { type: "Character", value: cc("\0") } } RegExpParser.prototype.hexEscapeSequenceAtom = function() { this.consumeChar("x") return this.parseHexDigits(2) } RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() { this.consumeChar("u") return this.parseHexDigits(4) } RegExpParser.prototype.identityEscapeAtom = function() { // TODO: implement "SourceCharacter but not UnicodeIDContinue" // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments var escapedChar = this.popChar() return { type: "Character", value: cc(escapedChar) } } RegExpParser.prototype.classPatternCharacterAtom = function() { switch (this.peekChar()) { // istanbul ignore next case "\n": // istanbul ignore next case "\r": // istanbul ignore next case "\u2028": // istanbul ignore next case "\u2029": // istanbul ignore next case "\\": // istanbul ignore next case "]": throw Error("TBD") default: var nextChar = this.popChar() return { type: "Character", value: cc(nextChar) } } } RegExpParser.prototype.characterClass = function() { var set = [] var complement = false this.consumeChar("[") if (this.peekChar(0) === "^") { this.consumeChar("^") complement = true } while (this.isClassAtom()) { var from = this.classAtom() var isFromSingleChar = from.type === "Character" if (isFromSingleChar && this.isRangeDash()) { this.consumeChar("-") var to = this.classAtom() var isToSingleChar = to.type === "Character" // a range can only be used when both sides are single characters if (isToSingleChar) { if (to.value < from.value) { throw Error("Range out of order in character class") } set.push({ from: from.value, to: to.value }) } else { // literal dash insertToSet(from.value, set) set.push(cc("-")) insertToSet(to.value, set) } } else { insertToSet(from.value, set) } } this.consumeChar("]") return { type: "Set", complement: complement, value: set } } RegExpParser.prototype.classAtom = function() { switch (this.peekChar()) { // istanbul ignore next case "]": // istanbul ignore next case "\n": // istanbul ignore next case "\r": // istanbul ignore next case "\u2028": // istanbul ignore next case "\u2029": throw Error("TBD") case "\\": return this.classEscape() default: return this.classPatternCharacterAtom() } } RegExpParser.prototype.classEscape = function() { this.consumeChar("\\") switch (this.peekChar()) { // Matches a backspace. // (Not to be confused with \b word boundary outside characterClass) case "b": this.consumeChar("b") return { type: "Character", value: cc("\u0008") } case "d": case "D": case "s": case "S": case "w": case "W": return this.characterClassEscape() case "f": case "n": case "r": case "t": case "v": return this.controlEscapeAtom() case "c": return this.controlLetterEscapeAtom() case "0": return this.nulCharacterAtom() case "x": return this.hexEscapeSequenceAtom() case "u": return this.regExpUnicodeEscapeSequenceAtom() default: return this.identityEscapeAtom() } } RegExpParser.prototype.group = function() { var capturing = true this.consumeChar("(") switch (this.peekChar(0)) { case "?": this.consumeChar("?") this.consumeChar(":") capturing = false break default: this.groupIdx++ break } var value = this.disjunction() this.consumeChar(")") var groupAst = { type: "Group", capturing: capturing, value: value } if (capturing) { groupAst.idx = this.groupIdx } return groupAst } RegExpParser.prototype.positiveInteger = function() { var number = this.popChar() // istanbul ignore next - can't ever get here due to previous lookahead checks // still implementing this error checking in case this ever changes. if (decimalPatternNoZero.test(number) === false) { throw Error("Expecting a positive integer") } while (decimalPattern.test(this.peekChar(0))) { number += this.popChar() } return parseInt(number, 10) } RegExpParser.prototype.integerIncludingZero = function() { var number = this.popChar() if (decimalPattern.test(number) === false) { throw Error("Expecting an integer") } while (decimalPattern.test(this.peekChar(0))) { number += this.popChar() } return parseInt(number, 10) } RegExpParser.prototype.patternCharacter = function() { var nextChar = this.popChar() switch (nextChar) { // istanbul ignore next case "\n": // istanbul ignore next case "\r": // istanbul ignore next case "\u2028": // istanbul ignore next case "\u2029": // istanbul ignore next case "^": // istanbul ignore next case "$": // istanbul ignore next case "\\": // istanbul ignore next case ".": // istanbul ignore next case "*": // istanbul ignore next case "+": // istanbul ignore next case "?": // istanbul ignore next case "(": // istanbul ignore next case ")": // istanbul ignore next case "[": // istanbul ignore next case "|": // istanbul ignore next throw Error("TBD") default: return { type: "Character", value: cc(nextChar) } } } RegExpParser.prototype.isRegExpFlag = function() { switch (this.peekChar(0)) { case "g": case "i": case "m": case "u": case "y": return true default: return false } } RegExpParser.prototype.isRangeDash = function() { return this.peekChar() === "-" && this.isClassAtom(1) } RegExpParser.prototype.isDigit = function() { return decimalPattern.test(this.peekChar(0)) } RegExpParser.prototype.isClassAtom = function(howMuch) { if (howMuch === undefined) { howMuch = 0 } switch (this.peekChar(howMuch)) { case "]": case "\n": case "\r": case "\u2028": case "\u2029": return false default: return true } } RegExpParser.prototype.isTerm = function() { return this.isAtom() || this.isAssertion() } RegExpParser.prototype.isAtom = function() { if (this.isPatternCharacter()) { return true } switch (this.peekChar(0)) { case ".": case "\\": // atomEscape case "[": // characterClass // TODO: isAtom must be called before isAssertion - disambiguate case "(": // group return true default: return false } } RegExpParser.prototype.isAssertion = function() { switch (this.peekChar(0)) { case "^": case "$": return true // '\b' or '\B' case "\\": switch (this.peekChar(1)) { case "b": case "B": return true default: return false } // '(?=' or '(?!' case "(": return ( this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!") ) default: return false } } RegExpParser.prototype.isQuantifier = function() { var prevState = this.saveState() try { return this.quantifier(true) !== undefined } catch (e) { return false } finally { this.restoreState(prevState) } } RegExpParser.prototype.isPatternCharacter = function() { switch (this.peekChar()) { case "^": case "$": case "\\": case ".": case "*": case "+": case "?": case "(": case ")": case "[": case "|": case "/": case "\n": case "\r": case "\u2028": case "\u2029": return false default: return true } } RegExpParser.prototype.parseHexDigits = function(howMany) { var hexString = "" for (var i = 0; i < howMany; i++) { var hexChar = this.popChar() if (hexDigitPattern.test(hexChar) === false) { throw Error("Expecting a HexDecimal digits") } hexString += hexChar } var charCode = parseInt(hexString, 16) return { type: "Character", value: charCode } } RegExpParser.prototype.peekChar = function(howMuch) { if (howMuch === undefined) { howMuch = 0 } return this.input[this.idx + howMuch] } RegExpParser.prototype.popChar = function() { var nextChar = this.peekChar(0) this.consumeChar() return nextChar } RegExpParser.prototype.consumeChar = function(char) { if (char !== undefined && this.input[this.idx] !== char) { throw Error( "Expected: '" + char + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx ) } if (this.idx >= this.input.length) { throw Error("Unexpected end of input") } this.idx++ } // consts and utilities var hexDigitPattern = /[0-9a-fA-F]/ var decimalPattern = /[0-9]/ var decimalPatternNoZero = /[1-9]/ function cc(char) { return char.charCodeAt(0) } function insertToSet(item, set) { if (item.length !== undefined) { item.forEach(function(subItem) { set.push(subItem) }) } else { set.push(item) } } function addFlag(flagObj, flagKey) { if (flagObj[flagKey] === true) { throw "duplicate flag " + flagKey } flagObj[flagKey] = true } function ASSERT_EXISTS(obj) { // istanbul ignore next if (obj === undefined) { throw Error("Internal Error - Should never get here!") } } // istanbul ignore next function ASSERT_NEVER_REACH_HERE() { throw Error("Internal Error - Should never get here!") } var i var digitsCharCodes = [] for (i = cc("0"); i <= cc("9"); i++) { digitsCharCodes.push(i) } var wordCharCodes = [cc("_")].concat(digitsCharCodes) for (i = cc("a"); i <= cc("z"); i++) { wordCharCodes.push(i) } for (i = cc("A"); i <= cc("Z"); i++) { wordCharCodes.push(i) } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes var whitespaceCodes = [ cc(" "), cc("\f"), cc("\n"), cc("\r"), cc("\t"), cc("\v"), cc("\t"), cc("\u00a0"), cc("\u1680"), cc("\u2000"), cc("\u2001"), cc("\u2002"), cc("\u2003"), cc("\u2004"), cc("\u2005"), cc("\u2006"), cc("\u2007"), cc("\u2008"), cc("\u2009"), cc("\u200a"), cc("\u2028"), cc("\u2029"), cc("\u202f"), cc("\u205f"), cc("\u3000"), cc("\ufeff") ] function BaseRegExpVisitor() {} BaseRegExpVisitor.prototype.visitChildren = function(node) { for (var key in node) { var child = node[key] /* istanbul ignore else */ if (node.hasOwnProperty(key)) { if (child.type !== undefined) { this.visit(child) } else if (Array.isArray(child)) { child.forEach(function(subChild) { this.visit(subChild) }, this) } } } } BaseRegExpVisitor.prototype.visit = function(node) { switch (node.type) { case "Pattern": this.visitPattern(node) break case "Flags": this.visitFlags(node) break case "Disjunction": this.visitDisjunction(node) break case "Alternative": this.visitAlternative(node) break case "StartAnchor": this.visitStartAnchor(node) break case "EndAnchor": this.visitEndAnchor(node) break case "WordBoundary": this.visitWordBoundary(node) break case "NonWordBoundary": this.visitNonWordBoundary(node) break case "Lookahead": this.visitLookahead(node) break case "NegativeLookahead": this.visitNegativeLookahead(node) break case "Character": this.visitCharacter(node) break case "Set": this.visitSet(node) break case "Group": this.visitGroup(node) break case "GroupBackReference": this.visitGroupBackReference(node) break case "Quantifier": this.visitQuantifier(node) break } this.visitChildren(node) } BaseRegExpVisitor.prototype.visitPattern = function(node) {} BaseRegExpVisitor.prototype.visitFlags = function(node) {} BaseRegExpVisitor.prototype.visitDisjunction = function(node) {} BaseRegExpVisitor.prototype.visitAlternative = function(node) {} // Assertion BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {} BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {} BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {} BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {} BaseRegExpVisitor.prototype.visitLookahead = function(node) {} BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {} // atoms BaseRegExpVisitor.prototype.visitCharacter = function(node) {} BaseRegExpVisitor.prototype.visitSet = function(node) {} BaseRegExpVisitor.prototype.visitGroup = function(node) {} BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {} BaseRegExpVisitor.prototype.visitQuantifier = function(node) {} return { RegExpParser: RegExpParser, BaseRegExpVisitor: BaseRegExpVisitor, VERSION: "0.4.0" } } ) /***/ }), /* 25 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ canMatchCharCode: () => (/* binding */ canMatchCharCode), /* harmony export */ failedOptimizationPrefixMsg: () => (/* binding */ failedOptimizationPrefixMsg), /* harmony export */ firstCharOptimizedIndices: () => (/* binding */ firstCharOptimizedIndices), /* harmony export */ getOptimizedStartCodesIndices: () => (/* binding */ getOptimizedStartCodesIndices) /* harmony export */ }); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(26); /* harmony import */ var _lexer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(23); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var complementErrorMessage = "Complement Sets are not supported for first char optimization"; var failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n'; function getOptimizedStartCodesIndices(regExp, ensureOptimizations) { if (ensureOptimizations === void 0) { ensureOptimizations = false; } try { var ast = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__.getRegExpAst)(regExp); var firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase); return firstChars; } catch (e) { /* istanbul ignore next */ // Testing this relies on the regexp-to-ast library having a bug... */ // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc if (e.message === complementErrorMessage) { if (ensureOptimizations) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_WARNING)("" + failedOptimizationPrefixMsg + ("\tUnable to optimize: < " + regExp.toString() + " >\n") + "\tComplement Sets cannot be automatically optimized.\n" + "\tThis will disable the lexer's first char optimizations.\n" + "\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details."); } } else { var msgSuffix = ""; if (ensureOptimizations) { msgSuffix = "\n\tThis will disable the lexer's first char optimizations.\n" + "\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details."; } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_ERROR)(failedOptimizationPrefixMsg + "\n" + ("\tFailed parsing: < " + regExp.toString() + " >\n") + ("\tUsing the regexp-to-ast library version: " + regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.VERSION + "\n") + "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + msgSuffix); } } return []; } function firstCharOptimizedIndices(ast, result, ignoreCase) { switch (ast.type) { case "Disjunction": for (var i = 0; i < ast.value.length; i++) { firstCharOptimizedIndices(ast.value[i], result, ignoreCase); } break; case "Alternative": var terms = ast.value; for (var i = 0; i < terms.length; i++) { var term = terms[i]; // skip terms that cannot effect the first char results switch (term.type) { case "EndAnchor": // A group back reference cannot affect potential starting char. // because if a back reference is the first production than automatically // the group being referenced has had to come BEFORE so its codes have already been added case "GroupBackReference": // assertions do not affect potential starting codes case "Lookahead": case "NegativeLookahead": case "StartAnchor": case "WordBoundary": case "NonWordBoundary": continue; } var atom = term; switch (atom.type) { case "Character": addOptimizedIdxToResult(atom.value, result, ignoreCase); break; case "Set": if (atom.complement === true) { throw Error(complementErrorMessage); } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(atom.value, function (code) { if (typeof code === "number") { addOptimizedIdxToResult(code, result, ignoreCase); } else { // range var range = code; // cannot optimize when ignoreCase is if (ignoreCase === true) { for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) { addOptimizedIdxToResult(rangeCode, result, ignoreCase); } } // Optimization (2 orders of magnitude less work for very large ranges) else { // handle unoptimized values for (var rangeCode = range.from; rangeCode <= range.to && rangeCode < _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal; rangeCode++) { addOptimizedIdxToResult(rangeCode, result, ignoreCase); } // Less common charCode where we optimize for faster init time, by using larger "buckets" if (range.to >= _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal) { var minUnOptVal = range.from >= _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal ? range.from : _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal; var maxUnOptVal = range.to; var minOptIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(minUnOptVal); var maxOptIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(maxUnOptVal); for (var currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) { result[currOptIdx] = currOptIdx; } } } } }); break; case "Group": firstCharOptimizedIndices(atom.value, result, ignoreCase); break; /* istanbul ignore next */ default: throw Error("Non Exhaustive Match"); } // reached a mandatory production, no more **start** codes can be found on this alternative var isOptionalQuantifier = atom.quantifier !== undefined && atom.quantifier.atLeast === 0; if ( // A group may be optional due to empty contents /(?:)/ // or if everything inside it is optional /((a)?)/ (atom.type === "Group" && isWholeOptional(atom) === false) || // If this term is not a group it may only be optional if it has an optional quantifier (atom.type !== "Group" && isOptionalQuantifier === false)) { break; } } break; /* istanbul ignore next */ default: throw Error("non exhaustive match!"); } // console.log(Object.keys(result).length) return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.values)(result); } function addOptimizedIdxToResult(code, result, ignoreCase) { var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(code); result[optimizedCharIdx] = optimizedCharIdx; if (ignoreCase === true) { handleIgnoreCase(code, result); } } function handleIgnoreCase(code, result) { var char = String.fromCharCode(code); var upperChar = char.toUpperCase(); /* istanbul ignore else */ if (upperChar !== char) { var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(upperChar.charCodeAt(0)); result[optimizedCharIdx] = optimizedCharIdx; } else { var lowerChar = char.toLowerCase(); if (lowerChar !== char) { var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(lowerChar.charCodeAt(0)); result[optimizedCharIdx] = optimizedCharIdx; } } } function findCode(setNode, targetCharCodes) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(setNode.value, function (codeOrRange) { if (typeof codeOrRange === "number") { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(targetCharCodes, codeOrRange); } else { // range var range_1 = codeOrRange; return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(targetCharCodes, function (targetCode) { return range_1.from <= targetCode && targetCode <= range_1.to; }) !== undefined); } }); } function isWholeOptional(ast) { if (ast.quantifier && ast.quantifier.atLeast === 0) { return true; } if (!ast.value) { return false; } return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isArray)(ast.value) ? (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.every)(ast.value, isWholeOptional) : isWholeOptional(ast.value); } var CharCodeFinder = /** @class */ (function (_super) { __extends(CharCodeFinder, _super); function CharCodeFinder(targetCharCodes) { var _this = _super.call(this) || this; _this.targetCharCodes = targetCharCodes; _this.found = false; return _this; } CharCodeFinder.prototype.visitChildren = function (node) { // No need to keep looking... if (this.found === true) { return; } // switch lookaheads as they do not actually consume any characters thus // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match. switch (node.type) { case "Lookahead": this.visitLookahead(node); return; case "NegativeLookahead": this.visitNegativeLookahead(node); return; } _super.prototype.visitChildren.call(this, node); }; CharCodeFinder.prototype.visitCharacter = function (node) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(this.targetCharCodes, node.value)) { this.found = true; } }; CharCodeFinder.prototype.visitSet = function (node) { if (node.complement) { if (findCode(node, this.targetCharCodes) === undefined) { this.found = true; } } else { if (findCode(node, this.targetCharCodes) !== undefined) { this.found = true; } } }; return CharCodeFinder; }(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor)); function canMatchCharCode(charCodes, pattern) { if (pattern instanceof RegExp) { var ast = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__.getRegExpAst)(pattern); var charCodeFinder = new CharCodeFinder(charCodes); charCodeFinder.visit(ast); return charCodeFinder.found; } else { return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(pattern, function (char) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(charCodes, char.charCodeAt(0)); }) !== undefined); } } //# sourceMappingURL=reg_exp.js.map /***/ }), /* 26 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ clearRegExpParserCache: () => (/* binding */ clearRegExpParserCache), /* harmony export */ getRegExpAst: () => (/* binding */ getRegExpAst) /* harmony export */ }); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24); /* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__); var regExpAstCache = {}; var regExpParser = new regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.RegExpParser(); function getRegExpAst(regExp) { var regExpStr = regExp.toString(); if (regExpAstCache.hasOwnProperty(regExpStr)) { return regExpAstCache[regExpStr]; } else { var regExpAst = regExpParser.pattern(regExpStr); regExpAstCache[regExpStr] = regExpAst; return regExpAst; } } function clearRegExpParserCache() { regExpAstCache = {}; } //# sourceMappingURL=reg_exp_parser.js.map /***/ }), /* 27 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ assignCategoriesMapProp: () => (/* binding */ assignCategoriesMapProp), /* harmony export */ assignCategoriesTokensProp: () => (/* binding */ assignCategoriesTokensProp), /* harmony export */ assignTokenDefaultProps: () => (/* binding */ assignTokenDefaultProps), /* harmony export */ augmentTokenTypes: () => (/* binding */ augmentTokenTypes), /* harmony export */ expandCategories: () => (/* binding */ expandCategories), /* harmony export */ hasCategoriesProperty: () => (/* binding */ hasCategoriesProperty), /* harmony export */ hasExtendingTokensTypesMapProperty: () => (/* binding */ hasExtendingTokensTypesMapProperty), /* harmony export */ hasExtendingTokensTypesProperty: () => (/* binding */ hasExtendingTokensTypesProperty), /* harmony export */ hasShortKeyProperty: () => (/* binding */ hasShortKeyProperty), /* harmony export */ isTokenType: () => (/* binding */ isTokenType), /* harmony export */ singleAssignCategoriesToksMap: () => (/* binding */ singleAssignCategoriesToksMap), /* harmony export */ tokenIdxToClass: () => (/* binding */ tokenIdxToClass), /* harmony export */ tokenShortNameIdx: () => (/* binding */ tokenShortNameIdx), /* harmony export */ tokenStructuredMatcher: () => (/* binding */ tokenStructuredMatcher), /* harmony export */ tokenStructuredMatcherNoCategories: () => (/* binding */ tokenStructuredMatcherNoCategories) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); function tokenStructuredMatcher(tokInstance, tokConstructor) { var instanceType = tokInstance.tokenTypeIdx; if (instanceType === tokConstructor.tokenTypeIdx) { return true; } else { return (tokConstructor.isParent === true && tokConstructor.categoryMatchesMap[instanceType] === true); } } // Optimized tokenMatcher in case our grammar does not use token categories // Being so tiny it is much more likely to be in-lined and this avoid the function call overhead function tokenStructuredMatcherNoCategories(token, tokType) { return token.tokenTypeIdx === tokType.tokenTypeIdx; } var tokenShortNameIdx = 1; var tokenIdxToClass = {}; function augmentTokenTypes(tokenTypes) { // collect the parent Token Types as well. var tokenTypesAndParents = expandCategories(tokenTypes); // add required tokenType and categoryMatches properties assignTokenDefaultProps(tokenTypesAndParents); // fill up the categoryMatches assignCategoriesMapProp(tokenTypesAndParents); assignCategoriesTokensProp(tokenTypesAndParents); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypesAndParents, function (tokType) { tokType.isParent = tokType.categoryMatches.length > 0; }); } function expandCategories(tokenTypes) { var result = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr)(tokenTypes); var categories = tokenTypes; var searching = true; while (searching) { categories = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(categories, function (currTokType) { return currTokType.CATEGORIES; }))); var newCategories = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.difference)(categories, result); result = result.concat(newCategories); if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(newCategories)) { searching = false; } else { categories = newCategories; } } return result; } function assignTokenDefaultProps(tokenTypes) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) { if (!hasShortKeyProperty(currTokType)) { tokenIdxToClass[tokenShortNameIdx] = currTokType; currTokType.tokenTypeIdx = tokenShortNameIdx++; } // CATEGORIES? : TokenType | TokenType[] if (hasCategoriesProperty(currTokType) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(currTokType.CATEGORIES) // && // !isUndefined(currTokType.CATEGORIES.PATTERN) ) { currTokType.CATEGORIES = [currTokType.CATEGORIES]; } if (!hasCategoriesProperty(currTokType)) { currTokType.CATEGORIES = []; } if (!hasExtendingTokensTypesProperty(currTokType)) { currTokType.categoryMatches = []; } if (!hasExtendingTokensTypesMapProperty(currTokType)) { currTokType.categoryMatchesMap = {}; } }); } function assignCategoriesTokensProp(tokenTypes) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) { // avoid duplications currTokType.categoryMatches = []; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatchesMap, function (val, key) { currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx); }); }); } function assignCategoriesMapProp(tokenTypes) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) { singleAssignCategoriesToksMap([], currTokType); }); } function singleAssignCategoriesToksMap(path, nextNode) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(path, function (pathNode) { nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(nextNode.CATEGORIES, function (nextCategory) { var newPath = path.concat(nextNode); // avoids infinite loops due to cyclic categories. if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(newPath, nextCategory)) { singleAssignCategoriesToksMap(newPath, nextCategory); } }); } function hasShortKeyProperty(tokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "tokenTypeIdx"); } function hasCategoriesProperty(tokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "CATEGORIES"); } function hasExtendingTokensTypesProperty(tokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "categoryMatches"); } function hasExtendingTokensTypesMapProperty(tokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "categoryMatchesMap"); } function isTokenType(tokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "tokenTypeIdx"); } //# sourceMappingURL=tokens.js.map /***/ }), /* 28 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ defaultLexerErrorProvider: () => (/* binding */ defaultLexerErrorProvider) /* harmony export */ }); var defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage: function (token) { return "Unable to pop Lexer Mode after encountering Token ->" + token.image + "<- The Mode Stack is empty"; }, buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) { return ("unexpected character: ->" + fullText.charAt(startOffset) + "<- at offset: " + startOffset + "," + (" skipped " + length + " characters.")); } }; //# sourceMappingURL=lexer_errors_public.js.map /***/ }), /* 29 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ first: () => (/* binding */ first), /* harmony export */ firstForBranching: () => (/* binding */ firstForBranching), /* harmony export */ firstForSequence: () => (/* binding */ firstForSequence), /* harmony export */ firstForTerminal: () => (/* binding */ firstForTerminal) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); /* harmony import */ var _gast_gast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30); function first(prod) { /* istanbul ignore else */ if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) { // this could in theory cause infinite loops if // (1) prod A refs prod B. // (2) prod B refs prod A // (3) AB can match the empty set // in other words a cycle where everything is optional so the first will keep // looking ahead for the next optional part and will never exit // currently there is no safeguard for this unique edge case because // (1) not sure a grammar in which this can happen is useful for anything (productive) return first(prod.referencedRule); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) { return firstForTerminal(prod); } else if ((0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isSequenceProd)(prod)) { return firstForSequence(prod); } else if ((0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isBranchingProd)(prod)) { return firstForBranching(prod); } else { throw Error("non exhaustive match"); } } function firstForSequence(prod) { var firstSet = []; var seq = prod.definition; var nextSubProdIdx = 0; var hasInnerProdsRemaining = seq.length > nextSubProdIdx; var currSubProd; // so we enter the loop at least once (if the definition is not empty var isLastInnerProdOptional = true; // scan a sequence until it's end or until we have found a NONE optional production in it while (hasInnerProdsRemaining && isLastInnerProdOptional) { currSubProd = seq[nextSubProdIdx]; isLastInnerProdOptional = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isOptionalProd)(currSubProd); firstSet = firstSet.concat(first(currSubProd)); nextSubProdIdx = nextSubProdIdx + 1; hasInnerProdsRemaining = seq.length > nextSubProdIdx; } return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)(firstSet); } function firstForBranching(prod) { var allAlternativesFirsts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prod.definition, function (innerProd) { return first(innerProd); }); return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(allAlternativesFirsts)); } function firstForTerminal(terminal) { return [terminal.terminalType]; } //# sourceMappingURL=first.js.map /***/ }), /* 30 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DslMethodsCollectorVisitor: () => (/* binding */ DslMethodsCollectorVisitor), /* harmony export */ collectMethods: () => (/* binding */ collectMethods), /* harmony export */ getProductionDslName: () => (/* binding */ getProductionDslName), /* harmony export */ isBranchingProd: () => (/* binding */ isBranchingProd), /* harmony export */ isOptionalProd: () => (/* binding */ isOptionalProd), /* harmony export */ isSequenceProd: () => (/* binding */ isSequenceProd) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); /* harmony import */ var _gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function isSequenceProd(prod) { return (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Rule); } function isOptionalProd(prod, alreadyVisited) { if (alreadyVisited === void 0) { alreadyVisited = []; } var isDirectlyOptional = prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition || prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator; if (isDirectlyOptional) { return true; } // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another // empty optional top rule // may be indirectly optional ((A?B?C?) | (D?E?F?)) if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) { // for OR its enough for just one of the alternatives to be optional return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.some)(prod.definition, function (subProd) { return isOptionalProd(subProd, alreadyVisited); }); } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(alreadyVisited, prod)) { // avoiding stack overflow due to infinite recursion return false; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.AbstractProduction) { if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) { alreadyVisited.push(prod); } return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(prod.definition, function (subProd) { return isOptionalProd(subProd, alreadyVisited); }); } else { return false; } } function isBranchingProd(prod) { return prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation; } function getProductionDslName(prod) { /* istanbul ignore else */ if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) { return "SUBRULE"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) { return "OPTION"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) { return "OR"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) { return "AT_LEAST_ONE"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) { return "AT_LEAST_ONE_SEP"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) { return "MANY_SEP"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) { return "MANY"; } else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) { return "CONSUME"; } else { throw Error("non exhaustive match"); } } var DslMethodsCollectorVisitor = /** @class */ (function (_super) { __extends(DslMethodsCollectorVisitor, _super); function DslMethodsCollectorVisitor() { var _this = _super !== null && _super.apply(this, arguments) || this; // A minus is never valid in an identifier name _this.separator = "-"; _this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; return _this; } DslMethodsCollectorVisitor.prototype.reset = function () { this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; }; DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) { var key = terminal.terminalType.name + this.separator + "Terminal"; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(this.dslMethods, key)) { this.dslMethods[key] = []; } this.dslMethods[key].push(terminal); }; DslMethodsCollectorVisitor.prototype.visitNonTerminal = function (subrule) { var key = subrule.nonTerminalName + this.separator + "Terminal"; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(this.dslMethods, key)) { this.dslMethods[key] = []; } this.dslMethods[key].push(subrule); }; DslMethodsCollectorVisitor.prototype.visitOption = function (option) { this.dslMethods.option.push(option); }; DslMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (manySep) { this.dslMethods.repetitionWithSeparator.push(manySep); }; DslMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (atLeastOne) { this.dslMethods.repetitionMandatory.push(atLeastOne); }; DslMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep); }; DslMethodsCollectorVisitor.prototype.visitRepetition = function (many) { this.dslMethods.repetition.push(many); }; DslMethodsCollectorVisitor.prototype.visitAlternation = function (or) { this.dslMethods.alternation.push(or); }; return DslMethodsCollectorVisitor; }(_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__.GAstVisitor)); var collectorVisitor = new DslMethodsCollectorVisitor(); function collectMethods(rule) { collectorVisitor.reset(); rule.accept(collectorVisitor); var dslMethods = collectorVisitor.dslMethods; // avoid uncleaned references collectorVisitor.reset(); return dslMethods; } //# sourceMappingURL=gast.js.map /***/ }), /* 31 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ GAstVisitor: () => (/* binding */ GAstVisitor) /* harmony export */ }); /* harmony import */ var _gast_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20); var GAstVisitor = /** @class */ (function () { function GAstVisitor() { } GAstVisitor.prototype.visit = function (node) { var nodeAny = node; switch (nodeAny.constructor) { case _gast_public__WEBPACK_IMPORTED_MODULE_0__.NonTerminal: return this.visitNonTerminal(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Flat: return this.visitFlat(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Option: return this.visitOption(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionMandatory: return this.visitRepetitionMandatory(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionMandatoryWithSeparator: return this.visitRepetitionMandatoryWithSeparator(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionWithSeparator: return this.visitRepetitionWithSeparator(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Repetition: return this.visitRepetition(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Alternation: return this.visitAlternation(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Terminal: return this.visitTerminal(nodeAny); case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Rule: return this.visitRule(nodeAny); /* istanbul ignore next */ default: throw Error("non exhaustive match"); } }; GAstVisitor.prototype.visitNonTerminal = function (node) { }; GAstVisitor.prototype.visitFlat = function (node) { }; GAstVisitor.prototype.visitOption = function (node) { }; GAstVisitor.prototype.visitRepetition = function (node) { }; GAstVisitor.prototype.visitRepetitionMandatory = function (node) { }; GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { }; GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { }; GAstVisitor.prototype.visitAlternation = function (node) { }; GAstVisitor.prototype.visitTerminal = function (node) { }; GAstVisitor.prototype.visitRule = function (node) { }; return GAstVisitor; }()); //# sourceMappingURL=gast_visitor_public.js.map /***/ }), /* 32 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ IN: () => (/* binding */ IN) /* harmony export */ }); // TODO: can this be removed? where is it used? var IN = "_~IN~_"; //# sourceMappingURL=constants.js.map /***/ }), /* 33 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ NamedDSLMethodsCollectorVisitor: () => (/* binding */ NamedDSLMethodsCollectorVisitor), /* harmony export */ addNoneTerminalToCst: () => (/* binding */ addNoneTerminalToCst), /* harmony export */ addTerminalToCst: () => (/* binding */ addTerminalToCst), /* harmony export */ expandAllNestedRuleNames: () => (/* binding */ expandAllNestedRuleNames), /* harmony export */ setNodeLocationFull: () => (/* binding */ setNodeLocationFull), /* harmony export */ setNodeLocationOnlyOffset: () => (/* binding */ setNodeLocationOnlyOffset) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34); /* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20); /* harmony import */ var _grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(31); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * This nodeLocation tracking is not efficient and should only be used * when error recovery is enabled or the Token Vector contains virtual Tokens * (e.g, Python Indent/Outdent) * As it executes the calculation for every single terminal/nonTerminal * and does not rely on the fact the token vector is **sorted** */ function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) { // First (valid) update for this cst node if (isNaN(currNodeLocation.startOffset) === true) { // assumption1: Token location information is either NaN or a valid number // assumption2: Token location information is fully valid if it exist // (both start/end offsets exist and are numbers). currNodeLocation.startOffset = newLocationInfo.startOffset; currNodeLocation.endOffset = newLocationInfo.endOffset; } // Once the startOffset has been updated with a valid number it should never receive // any farther updates as the Token vector is sorted. // We still have to check this this condition for every new possible location info // because with error recovery enabled we may encounter invalid tokens (NaN location props) else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { currNodeLocation.endOffset = newLocationInfo.endOffset; } } /** * This nodeLocation tracking is not efficient and should only be used * when error recovery is enabled or the Token Vector contains virtual Tokens * (e.g, Python Indent/Outdent) * As it executes the calculation for every single terminal/nonTerminal * and does not rely on the fact the token vector is **sorted** */ function setNodeLocationFull(currNodeLocation, newLocationInfo) { // First (valid) update for this cst node if (isNaN(currNodeLocation.startOffset) === true) { // assumption1: Token location information is either NaN or a valid number // assumption2: Token location information is fully valid if it exist // (all start/end props exist and are numbers). currNodeLocation.startOffset = newLocationInfo.startOffset; currNodeLocation.startColumn = newLocationInfo.startColumn; currNodeLocation.startLine = newLocationInfo.startLine; currNodeLocation.endOffset = newLocationInfo.endOffset; currNodeLocation.endColumn = newLocationInfo.endColumn; currNodeLocation.endLine = newLocationInfo.endLine; } // Once the start props has been updated with a valid number it should never receive // any farther updates as the Token vector is sorted. // We still have to check this this condition for every new possible location info // because with error recovery enabled we may encounter invalid tokens (NaN location props) else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) { currNodeLocation.endOffset = newLocationInfo.endOffset; currNodeLocation.endColumn = newLocationInfo.endColumn; currNodeLocation.endLine = newLocationInfo.endLine; } } function addTerminalToCst(node, token, tokenTypeName) { if (node.children[tokenTypeName] === undefined) { node.children[tokenTypeName] = [token]; } else { node.children[tokenTypeName].push(token); } } function addNoneTerminalToCst(node, ruleName, ruleResult) { if (node.children[ruleName] === undefined) { node.children[ruleName] = [ruleResult]; } else { node.children[ruleName].push(ruleResult); } } var NamedDSLMethodsCollectorVisitor = /** @class */ (function (_super) { __extends(NamedDSLMethodsCollectorVisitor, _super); function NamedDSLMethodsCollectorVisitor(ruleIdx) { var _this = _super.call(this) || this; _this.result = []; _this.ruleIdx = ruleIdx; return _this; } NamedDSLMethodsCollectorVisitor.prototype.collectNamedDSLMethod = function (node, newNodeConstructor, methodIdx) { // TODO: better hack to copy what we need here... if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(node.name)) { // copy without name so this will indeed be processed later. var nameLessNode /* istanbul ignore else */ = void 0; /* istanbul ignore else */ if (node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option || node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Repetition || node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatory || node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Alternation) { nameLessNode = new newNodeConstructor({ definition: node.definition, idx: node.idx }); } else if (node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatoryWithSeparator || node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionWithSeparator) { nameLessNode = new newNodeConstructor({ definition: node.definition, idx: node.idx, separator: node.separator }); } else { throw Error("non exhaustive match"); } var def = [nameLessNode]; var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.getKeyForAutomaticLookahead)(this.ruleIdx, methodIdx, node.idx); this.result.push({ def: def, key: key, name: node.name, orgProd: node }); } }; NamedDSLMethodsCollectorVisitor.prototype.visitOption = function (node) { this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX); }; NamedDSLMethodsCollectorVisitor.prototype.visitRepetition = function (node) { this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Repetition, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX); }; NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (node) { this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatory, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX); }; NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatoryWithSeparator, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX); }; NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (node) { this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionWithSeparator, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX); }; NamedDSLMethodsCollectorVisitor.prototype.visitAlternation = function (node) { var _this = this; this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Alternation, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX); var hasMoreThanOneAlternative = node.definition.length > 1; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(node.definition, function (currFlatAlt, altIdx) { if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(currFlatAlt.name)) { var def = currFlatAlt.definition; if (hasMoreThanOneAlternative) { def = [new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option({ definition: currFlatAlt.definition })]; } else { // mandatory def = currFlatAlt.definition; } var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.getKeyForAltIndex)(_this.ruleIdx, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, node.idx, altIdx); _this.result.push({ def: def, key: key, name: currFlatAlt.name, orgProd: currFlatAlt }); } }); }; return NamedDSLMethodsCollectorVisitor; }(_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_3__.GAstVisitor)); function expandAllNestedRuleNames(topRules, fullToShortName) { var result = { allRuleNames: [] }; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topRules, function (currTopRule) { var currTopRuleShortName = fullToShortName[currTopRule.name]; result.allRuleNames.push(currTopRule.name); var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor(currTopRuleShortName); currTopRule.accept(namedCollectorVisitor); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(namedCollectorVisitor.result, function (_a) { var def = _a.def, key = _a.key, name = _a.name; result.allRuleNames.push(currTopRule.name + name); }); }); return result; } //# sourceMappingURL=cst.js.map /***/ }), /* 34 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AT_LEAST_ONE_IDX: () => (/* binding */ AT_LEAST_ONE_IDX), /* harmony export */ AT_LEAST_ONE_SEP_IDX: () => (/* binding */ AT_LEAST_ONE_SEP_IDX), /* harmony export */ BITS_FOR_ALT_IDX: () => (/* binding */ BITS_FOR_ALT_IDX), /* harmony export */ BITS_FOR_METHOD_TYPE: () => (/* binding */ BITS_FOR_METHOD_TYPE), /* harmony export */ BITS_FOR_OCCURRENCE_IDX: () => (/* binding */ BITS_FOR_OCCURRENCE_IDX), /* harmony export */ BITS_FOR_RULE_IDX: () => (/* binding */ BITS_FOR_RULE_IDX), /* harmony export */ MANY_IDX: () => (/* binding */ MANY_IDX), /* harmony export */ MANY_SEP_IDX: () => (/* binding */ MANY_SEP_IDX), /* harmony export */ OPTION_IDX: () => (/* binding */ OPTION_IDX), /* harmony export */ OR_IDX: () => (/* binding */ OR_IDX), /* harmony export */ getKeyForAltIndex: () => (/* binding */ getKeyForAltIndex), /* harmony export */ getKeyForAutomaticLookahead: () => (/* binding */ getKeyForAutomaticLookahead) /* harmony export */ }); // Lookahead keys are 32Bit integers in the form // TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX // XXXX -> Occurrence Index bitmap. // YYYY -> DSL Method Type bitmap. // ZZZZZZZZZZZZZZZ -> Rule short Index bitmap. // TTTTTTTTT -> alternation alternative index bitmap var BITS_FOR_METHOD_TYPE = 4; var BITS_FOR_OCCURRENCE_IDX = 8; var BITS_FOR_RULE_IDX = 12; // TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation. var BITS_FOR_ALT_IDX = 8; // short string used as part of mapping keys. // being short improves the performance when composing KEYS for maps out of these // The 5 - 8 bits (16 possible values, are reserved for the DSL method indices) /* tslint:disable */ var OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX; var OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX; var MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX; var AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX; var MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX; var AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX; /* tslint:enable */ // this actually returns a number, but it is always used as a string (object prop key) function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) { /* tslint:disable */ return occurrence | dslMethodIdx | ruleIdx; /* tslint:enable */ } var BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX; function getKeyForAltIndex(ruleIdx, dslMethodIdx, occurrence, altIdx) { /* tslint:disable */ // alternative indices are zero based, thus must always add one (turn on one bit) to guarantee uniqueness. var altIdxBitMap = (altIdx + 1) << BITS_START_FOR_ALT_IDX; return (getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) | altIdxBitMap); /* tslint:enable */ } //# sourceMappingURL=keys.js.map /***/ }), /* 35 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ defaultGrammarResolverErrorProvider: () => (/* binding */ defaultGrammarResolverErrorProvider), /* harmony export */ defaultGrammarValidatorErrorProvider: () => (/* binding */ defaultGrammarValidatorErrorProvider), /* harmony export */ defaultParserErrorProvider: () => (/* binding */ defaultParserErrorProvider) /* harmony export */ }); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20); /* harmony import */ var _grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30); /* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(36); var defaultParserErrorProvider = { buildMismatchTokenMessage: function (_a) { var expected = _a.expected, actual = _a.actual, previous = _a.previous, ruleName = _a.ruleName; var hasLabel = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.hasTokenLabel)(expected); var expectedMsg = hasLabel ? "--> " + (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(expected) + " <--" : "token of type --> " + expected.name + " <--"; var msg = "Expecting " + expectedMsg + " but found --> '" + actual.image + "' <--"; return msg; }, buildNotAllInputParsedMessage: function (_a) { var firstRedundant = _a.firstRedundant, ruleName = _a.ruleName; return ("Redundant input, expecting EOF but found: " + firstRedundant.image); }, buildNoViableAltMessage: function (_a) { var expectedPathsPerAlt = _a.expectedPathsPerAlt, actual = _a.actual, previous = _a.previous, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName; var errPrefix = "Expecting: "; // TODO: issue: No Viable Alternative Error may have incomplete details. #502 var actualText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(actual).image; var errSuffix = "\nbut found: '" + actualText + "'"; if (customUserDescription) { return errPrefix + customUserDescription + errSuffix; } else { var allLookAheadPaths = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reduce)(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []); var nextValidTokenSequences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(allLookAheadPaths, function (currPath) { return "[" + (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(currPath, function (currTokenType) { return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTokenType); }).join(", ") + "]"; }); var nextValidSequenceItems = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(nextValidTokenSequences, function (itemMsg, idx) { return " " + (idx + 1) + ". " + itemMsg; }); var calculatedDescription = "one of these possible Token sequences:\n" + nextValidSequenceItems.join("\n"); return errPrefix + calculatedDescription + errSuffix; } }, buildEarlyExitMessage: function (_a) { var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName; var errPrefix = "Expecting: "; // TODO: issue: No Viable Alternative Error may have incomplete details. #502 var actualText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(actual).image; var errSuffix = "\nbut found: '" + actualText + "'"; if (customUserDescription) { return errPrefix + customUserDescription + errSuffix; } else { var nextValidTokenSequences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(expectedIterationPaths, function (currPath) { return "[" + (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(currPath, function (currTokenType) { return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTokenType); }).join(",") + "]"; }); var calculatedDescription = "expecting at least one iteration which starts with one of these possible Token sequences::\n " + ("<" + nextValidTokenSequences.join(" ,") + ">"); return errPrefix + calculatedDescription + errSuffix; } } }; Object.freeze(defaultParserErrorProvider); var defaultGrammarResolverErrorProvider = { buildRuleNotFoundError: function (topLevelRule, undefinedRule) { var msg = "Invalid grammar, reference to a rule which is not defined: ->" + undefinedRule.nonTerminalName + "<-\n" + "inside top level rule: ->" + topLevelRule.name + "<-"; return msg; } }; var defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError: function (topLevelRule, duplicateProds) { function getExtraProductionArgument(prod) { if (prod instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Terminal) { return prod.terminalType.name; } else if (prod instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.NonTerminal) { return prod.nonTerminalName; } else { return ""; } } var topLevelName = topLevelRule.name; var duplicateProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(duplicateProds); var index = duplicateProd.idx; var dslName = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__.getProductionDslName)(duplicateProd); var extraArgument = getExtraProductionArgument(duplicateProd); var hasExplicitIndex = index > 0; var msg = "->" + dslName + (hasExplicitIndex ? index : "") + "<- " + (extraArgument ? "with argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n "; // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings... msg = msg.replace(/[ \t]+/g, " "); msg = msg.replace(/\s\s+/g, "\n"); return msg; }, buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) { var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" + ("it must match the pattern: ->" + _grammar_checks__WEBPACK_IMPORTED_MODULE_4__.validNestedRuleName.toString() + "<-.\n") + "Note that this means a nested rule name must start with the '$'(dollar) sign."; return msg; }, buildDuplicateNestedRuleNameError: function (topLevelRule, nestedProd) { var duplicateName = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(nestedProd).name; var errMsg = "Duplicate nested rule name: ->" + duplicateName + "<- inside rule: ->" + topLevelRule.name + "<-\n" + "A nested name must be unique in the scope of a top level grammar rule."; return errMsg; }, buildNamespaceConflictError: function (rule) { var errMsg = "Namespace conflict found in grammar.\n" + ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + rule.name + ">.\n") + "To resolve this make sure each Terminal and Non-Terminal names are unique\n" + "This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" + "and Non-Terminal names start with a lower case letter."; return errMsg; }, buildAlternationPrefixAmbiguityError: function (options) { var pathMsg = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(options.prefixPath, function (currTok) { return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTok); }).join(", "); var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; var errMsg = "Ambiguous alternatives: <" + options.ambiguityIndices.join(" ,") + "> due to common lookahead prefix\n" + ("in inside <" + options.topLevelRule.name + "> Rule,\n") + ("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n") + "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n" + "For Further details."; return errMsg; }, buildAlternationAmbiguityError: function (options) { var pathMsg = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(options.prefixPath, function (currtok) { return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currtok); }).join(", "); var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; var currMessage = "Ambiguous Alternatives Detected: <" + options.ambiguityIndices.join(" ,") + "> in " + (" inside <" + options.topLevelRule.name + "> Rule,\n") + ("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n"); currMessage = currMessage + "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n" + "For Further details."; return currMessage; }, buildEmptyRepetitionError: function (options) { var dslName = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__.getProductionDslName)(options.repetition); if (options.repetition.idx !== 0) { dslName += options.repetition.idx; } var errMsg = "The repetition <" + dslName + "> within Rule <" + options.topLevelRule.name + "> can never consume any tokens.\n" + "This could lead to an infinite loop."; return errMsg; }, buildTokenNameError: function (options) { var tokTypeName = options.tokenType.name; var errMsg = "Invalid Grammar Token name: ->" + tokTypeName + "<- it must match the pattern: ->" + options.expectedPattern.toString() + "<-"; return errMsg; }, buildEmptyAlternationError: function (options) { var errMsg = "Ambiguous empty alternative: <" + (options.emptyChoiceIdx + 1) + ">" + (" in inside <" + options.topLevelRule.name + "> Rule.\n") + "Only the last alternative may be an empty alternative."; return errMsg; }, buildTooManyAlternativesError: function (options) { var errMsg = "An Alternation cannot have more than 256 alternatives:\n" + (" inside <" + options.topLevelRule.name + "> Rule.\n has " + (options.alternation.definition.length + 1) + " alternatives."); return errMsg; }, buildLeftRecursionError: function (options) { var ruleName = options.topLevelRule.name; var pathNames = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.map(options.leftRecursionPath, function (currRule) { return currRule.name; }); var leftRecursivePath = ruleName + " --> " + pathNames .concat([ruleName]) .join(" --> "); var errMsg = "Left Recursion found in grammar.\n" + ("rule: <" + ruleName + "> can be invoked from itself (directly or indirectly)\n") + ("without consuming any Tokens. The grammar path that causes this is: \n " + leftRecursivePath + "\n") + " To fix this refactor your grammar to remove the left recursion.\n" + "see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring."; return errMsg; }, buildInvalidRuleNameError: function (options) { var ruleName = options.topLevelRule.name; var expectedPatternString = options.expectedPattern.toString(); var errMsg = "Invalid grammar rule name: ->" + ruleName + "<- it must match the pattern: ->" + expectedPatternString + "<-"; return errMsg; }, buildDuplicateRuleNameError: function (options) { var ruleName; if (options.topLevelRule instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Rule) { ruleName = options.topLevelRule.name; } else { ruleName = options.topLevelRule; } var errMsg = "Duplicate definition, rule: ->" + ruleName + "<- is already defined in the grammar: ->" + options.grammarName + "<-"; return errMsg; } }; //# sourceMappingURL=errors_public.js.map /***/ }), /* 36 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ OccurrenceValidationCollector: () => (/* binding */ OccurrenceValidationCollector), /* harmony export */ RepetionCollector: () => (/* binding */ RepetionCollector), /* harmony export */ checkPrefixAlternativesAmbiguities: () => (/* binding */ checkPrefixAlternativesAmbiguities), /* harmony export */ getFirstNoneTerminal: () => (/* binding */ getFirstNoneTerminal), /* harmony export */ identifyProductionForDuplicates: () => (/* binding */ identifyProductionForDuplicates), /* harmony export */ validNestedRuleName: () => (/* binding */ validNestedRuleName), /* harmony export */ validTermsPattern: () => (/* binding */ validTermsPattern), /* harmony export */ validateAmbiguousAlternationAlternatives: () => (/* binding */ validateAmbiguousAlternationAlternatives), /* harmony export */ validateEmptyOrAlternative: () => (/* binding */ validateEmptyOrAlternative), /* harmony export */ validateGrammar: () => (/* binding */ validateGrammar), /* harmony export */ validateNestedRuleName: () => (/* binding */ validateNestedRuleName), /* harmony export */ validateNoLeftRecursion: () => (/* binding */ validateNoLeftRecursion), /* harmony export */ validateRuleDoesNotAlreadyExist: () => (/* binding */ validateRuleDoesNotAlreadyExist), /* harmony export */ validateRuleIsOverridden: () => (/* binding */ validateRuleIsOverridden), /* harmony export */ validateRuleName: () => (/* binding */ validateRuleName), /* harmony export */ validateSomeNonEmptyLookaheadPath: () => (/* binding */ validateSomeNonEmptyLookaheadPath), /* harmony export */ validateTokenName: () => (/* binding */ validateTokenName), /* harmony export */ validateTooManyAlts: () => (/* binding */ validateTooManyAlts) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _parser_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); /* harmony import */ var _gast_gast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30); /* harmony import */ var _lookahead__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37); /* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(33); /* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(38); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(20); /* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(31); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, ignoredIssues, errMsgProvider, grammarName) { var duplicateErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(topLevels, function (currTopLevel) { return validateDuplicateProductions(currTopLevel, errMsgProvider); }); var leftRecursionErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(topLevels, function (currTopRule) { return validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider); }); var emptyAltErrors = []; var ambiguousAltsErrors = []; var emptyRepetitionErrors = []; // left recursion could cause infinite loops in the following validations. // It is safest to first have the user fix the left recursion errors first and only then examine Further issues. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(leftRecursionErrors, _utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)) { emptyAltErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (currTopRule) { return validateEmptyOrAlternative(currTopRule, errMsgProvider); }); ambiguousAltsErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (currTopRule) { return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, ignoredIssues, errMsgProvider); }); emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider); } var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); var tokenNameErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(tokenTypes, function (currTokType) { return validateTokenName(currTokType, errMsgProvider); }); var nestedRulesNameErrors = validateNestedRulesNames(topLevels, errMsgProvider); var nestedRulesDuplicateErrors = validateDuplicateNestedRules(topLevels, errMsgProvider); var tooManyAltsErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) { return validateTooManyAlts(curRule, errMsgProvider); }); var ruleNameErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) { return validateRuleName(curRule, errMsgProvider); }); var duplicateRulesError = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) { return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider); }); return (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(duplicateErrors.concat(tokenNameErrors, nestedRulesNameErrors, nestedRulesDuplicateErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError))); } function validateNestedRulesNames(topLevels, errMsgProvider) { var result = []; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevels, function (curTopLevel) { var namedCollectorVisitor = new _cst_cst__WEBPACK_IMPORTED_MODULE_4__.NamedDSLMethodsCollectorVisitor(""); curTopLevel.accept(namedCollectorVisitor); var nestedProds = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(namedCollectorVisitor.result, function (currItem) { return currItem.orgProd; }); result.push((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(nestedProds, function (currNestedProd) { return validateNestedRuleName(curTopLevel, currNestedProd, errMsgProvider); })); }); return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(result); } function validateDuplicateProductions(topLevelRule, errMsgProvider) { var collectorVisitor = new OccurrenceValidationCollector(); topLevelRule.accept(collectorVisitor); var allRuleProductions = collectorVisitor.allProductions; var productionGroups = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.groupBy(allRuleProductions, identifyProductionForDuplicates); var duplicates = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick(productionGroups, function (currGroup) { return currGroup.length > 1; }); var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values(duplicates), function (currDuplicates) { var firstProd = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.first(currDuplicates); var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); var dslName = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(firstProd); var defError = { message: msg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: topLevelRule.name, dslName: dslName, occurrence: firstProd.idx }; var param = getExtraProductionArgument(firstProd); if (param) { defError.parameter = param; } return defError; }); return errors; } function identifyProductionForDuplicates(prod) { return (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod); } function getExtraProductionArgument(prod) { if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Terminal) { return prod.terminalType.name; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.NonTerminal) { return prod.nonTerminalName; } else { return ""; } } var OccurrenceValidationCollector = /** @class */ (function (_super) { __extends(OccurrenceValidationCollector, _super); function OccurrenceValidationCollector() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.allProductions = []; return _this; } OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) { this.allProductions.push(subrule); }; OccurrenceValidationCollector.prototype.visitOption = function (option) { this.allProductions.push(option); }; OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) { this.allProductions.push(manySep); }; OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { this.allProductions.push(atLeastOne); }; OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { this.allProductions.push(atLeastOneSep); }; OccurrenceValidationCollector.prototype.visitRepetition = function (many) { this.allProductions.push(many); }; OccurrenceValidationCollector.prototype.visitAlternation = function (or) { this.allProductions.push(or); }; OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) { this.allProductions.push(terminal); }; return OccurrenceValidationCollector; }(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor)); var validTermsPattern = /^[a-zA-Z_]\w*$/; var validNestedRuleName = new RegExp(validTermsPattern.source.replace("^", "^\\$")); // TODO: remove this limitation now that we use recorders function validateRuleName(rule, errMsgProvider) { var errors = []; var ruleName = rule.name; if (!ruleName.match(validTermsPattern)) { errors.push({ message: errMsgProvider.buildInvalidRuleNameError({ topLevelRule: rule, expectedPattern: validTermsPattern }), type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_RULE_NAME, ruleName: ruleName }); } return errors; } // TODO: did the nested rule name regExp now change? function validateNestedRuleName(topLevel, nestedProd, errMsgProvider) { var errors = []; var errMsg; if (!nestedProd.name.match(validNestedRuleName)) { errMsg = errMsgProvider.buildInvalidNestedRuleNameError(topLevel, nestedProd); errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME, ruleName: topLevel.name }); } return errors; } // TODO: remove this limitation now that we use recorders function validateTokenName(tokenType, errMsgProvider) { var errors = []; var tokTypeName = tokenType.name; if (!tokTypeName.match(validTermsPattern)) { errors.push({ message: errMsgProvider.buildTokenNameError({ tokenType: tokenType, expectedPattern: validTermsPattern }), type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_TOKEN_NAME }); } return errors; } function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { var errors = []; var occurrences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(allRules, function (result, curRule) { if (curRule.name === rule.name) { return result + 1; } return result; }, 0); if (occurrences > 1) { var errMsg = errMsgProvider.buildDuplicateRuleNameError({ topLevelRule: rule, grammarName: className }); errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: rule.name }); } return errors; } // TODO: is there anyway to get only the rule names of rules inherited from the super grammars? // This is not part of the IGrammarErrorProvider because the validation cannot be performed on // The grammar structure, only at runtime. function validateRuleIsOverridden(ruleName, definedRulesNames, className) { var errors = []; var errMsg; if (!_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains(definedRulesNames, ruleName)) { errMsg = "Invalid rule override, rule: ->" + ruleName + "<- cannot be overridden in the grammar: ->" + className + "<-" + "as it is not defined in any of the super grammars "; errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName: ruleName }); } return errors; } function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) { if (path === void 0) { path = []; } var errors = []; var nextNonTerminals = getFirstNoneTerminal(currRule.definition); if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(nextNonTerminals)) { return []; } else { var ruleName = topRule.name; var foundLeftRecursion = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains(nextNonTerminals, topRule); if (foundLeftRecursion) { errors.push({ message: errMsgProvider.buildLeftRecursionError({ topLevelRule: topRule, leftRecursionPath: path }), type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.LEFT_RECURSION, ruleName: ruleName }); } // we are only looking for cyclic paths leading back to the specific topRule // other cyclic paths are ignored, we still need this difference to avoid infinite loops... var validNextSteps = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.difference(nextNonTerminals, path.concat([topRule])); var errorsFromNextSteps = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(validNextSteps, function (currRefRule) { var newPath = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr(path); newPath.push(currRefRule); return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); }); return errors.concat(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(errorsFromNextSteps)); } } function getFirstNoneTerminal(definition) { var result = []; if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(definition)) { return result; } var firstProd = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.first(definition); /* istanbul ignore else */ if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.NonTerminal) { result.push(firstProd.referencedRule); } else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Flat || firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Option || firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionMandatory || firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionMandatoryWithSeparator || firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionWithSeparator || firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Repetition) { result = result.concat(getFirstNoneTerminal(firstProd.definition)); } else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Alternation) { // each sub definition in alternation is a FLAT result = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(firstProd.definition, function (currSubDef) { return getFirstNoneTerminal(currSubDef.definition); })); } else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Terminal) { // nothing to see, move along } else { throw Error("non exhaustive match"); } var isFirstOptional = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isOptionalProd)(firstProd); var hasMore = definition.length > 1; if (isFirstOptional && hasMore) { var rest = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.drop(definition); return result.concat(getFirstNoneTerminal(rest)); } else { return result; } } var OrCollector = /** @class */ (function (_super) { __extends(OrCollector, _super); function OrCollector() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.alternations = []; return _this; } OrCollector.prototype.visitAlternation = function (node) { this.alternations.push(node); }; return OrCollector; }(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor)); function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { var orCollector = new OrCollector(); topLevelRule.accept(orCollector); var ors = orCollector.alternations; var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (errors, currOr) { var exceptLast = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.dropRight(currOr.definition); var currErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(exceptLast, function (currAlternative, currAltIdx) { var possibleFirstInAlt = (0,_interpreter__WEBPACK_IMPORTED_MODULE_5__.nextPossibleTokensAfter)([currAlternative], [], null, 1); if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(possibleFirstInAlt)) { return { message: errMsgProvider.buildEmptyAlternationError({ topLevelRule: topLevelRule, alternation: currOr, emptyChoiceIdx: currAltIdx }), type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: topLevelRule.name, occurrence: currOr.idx, alternative: currAltIdx + 1 }; } else { return null; } }); return errors.concat(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact(currErrors)); }, []); return errors; } function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, ignoredIssues, errMsgProvider) { var orCollector = new OrCollector(); topLevelRule.accept(orCollector); var ors = orCollector.alternations; // TODO: this filtering should be deprecated once we remove the ignoredIssues // IParserConfig property var ignoredIssuesForCurrentRule = ignoredIssues[topLevelRule.name]; if (ignoredIssuesForCurrentRule) { ors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reject)(ors, function (currOr) { return ignoredIssuesForCurrentRule[(0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(currOr) + (currOr.idx === 0 ? "" : currOr.idx)]; }); } // New Handling of ignoring ambiguities // - https://github.com/SAP/chevrotain/issues/869 ors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reject)(ors, function (currOr) { return currOr.ignoreAmbiguities === true; }); var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (result, currOr) { var currOccurrence = currOr.idx; var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; var alternatives = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getLookaheadPathsForOr)(currOccurrence, topLevelRule, actualMaxLookahead, currOr); var altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); var altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider); return result.concat(altsAmbiguityErrors, altsPrefixAmbiguityErrors); }, []); return errors; } var RepetionCollector = /** @class */ (function (_super) { __extends(RepetionCollector, _super); function RepetionCollector() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.allProductions = []; return _this; } RepetionCollector.prototype.visitRepetitionWithSeparator = function (manySep) { this.allProductions.push(manySep); }; RepetionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) { this.allProductions.push(atLeastOne); }; RepetionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) { this.allProductions.push(atLeastOneSep); }; RepetionCollector.prototype.visitRepetition = function (many) { this.allProductions.push(many); }; return RepetionCollector; }(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor)); function validateTooManyAlts(topLevelRule, errMsgProvider) { var orCollector = new OrCollector(); topLevelRule.accept(orCollector); var ors = orCollector.alternations; var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (errors, currOr) { if (currOr.definition.length > 255) { errors.push({ message: errMsgProvider.buildTooManyAlternativesError({ topLevelRule: topLevelRule, alternation: currOr }), type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: topLevelRule.name, occurrence: currOr.idx }); } return errors; }, []); return errors; } function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { var errors = []; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevelRules, function (currTopRule) { var collectorVisitor = new RepetionCollector(); currTopRule.accept(collectorVisitor); var allRuleProductions = collectorVisitor.allProductions; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(allRuleProductions, function (currProd) { var prodType = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getProdType)(currProd); var actualMaxLookahead = currProd.maxLookahead || maxLookahead; var currOccurrence = currProd.idx; var paths = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getLookaheadPathsForOptionalProd)(currOccurrence, currTopRule, prodType, actualMaxLookahead); var pathsInsideProduction = paths[0]; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(pathsInsideProduction))) { var errMsg = errMsgProvider.buildEmptyRepetitionError({ topLevelRule: currTopRule, repetition: currProd }); errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: currTopRule.name }); } }); }); return errors; } function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { var foundAmbiguousPaths = []; var identicalAmbiguities = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(alternatives, function (result, currAlt, currAltIdx) { // ignore (skip) ambiguities with this alternative if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { return result; } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAlt, function (currPath) { var altsCurrPathAppearsIn = [currAltIdx]; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(alternatives, function (currOtherAlt, currOtherAltIdx) { if (currAltIdx !== currOtherAltIdx && (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.containsPath)(currOtherAlt, currPath) && // ignore (skip) ambiguities with this "other" alternative alternation.definition[currOtherAltIdx] .ignoreAmbiguities !== true) { altsCurrPathAppearsIn.push(currOtherAltIdx); } }); if (altsCurrPathAppearsIn.length > 1 && !(0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.containsPath)(foundAmbiguousPaths, currPath)) { foundAmbiguousPaths.push(currPath); result.push({ alts: altsCurrPathAppearsIn, path: currPath }); } }); return result; }, []); var currErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(identicalAmbiguities, function (currAmbDescriptor) { var ambgIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; }); var currMessage = errMsgProvider.buildAlternationAmbiguityError({ topLevelRule: rule, alternation: alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbDescriptor.path }); return { message: currMessage, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: rule.name, occurrence: alternation.idx, alternatives: [currAmbDescriptor.alts] }; }); return currErrors; } function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { var errors = []; // flatten var pathsAndIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(alternatives, function (result, currAlt, idx) { var currPathsAndIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currAlt, function (currPath) { return { idx: idx, path: currPath }; }); return result.concat(currPathsAndIdx); }, []); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(pathsAndIndices, function (currPathAndIdx) { var alternativeGast = alternation.definition[currPathAndIdx.idx]; // ignore (skip) ambiguities with this alternative if (alternativeGast.ignoreAmbiguities === true) { return; } var targetIdx = currPathAndIdx.idx; var targetPath = currPathAndIdx.path; var prefixAmbiguitiesPathsAndIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.findAll)(pathsAndIndices, function (searchPathAndIdx) { // prefix ambiguity can only be created from lower idx (higher priority) path return ( // ignore (skip) ambiguities with this "other" alternative alternation.definition[searchPathAndIdx.idx] .ignoreAmbiguities !== true && searchPathAndIdx.idx < targetIdx && // checking for strict prefix because identical lookaheads // will be be detected using a different validation. (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.isStrictPrefixOfPath)(searchPathAndIdx.path, targetPath)); }); var currPathPrefixErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) { var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1]; var occurrence = alternation.idx === 0 ? "" : alternation.idx; var message = errMsgProvider.buildAlternationPrefixAmbiguityError({ topLevelRule: rule, alternation: alternation, ambiguityIndices: ambgIndices, prefixPath: currAmbPathAndIdx.path }); return { message: message, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: rule.name, occurrence: occurrence, alternatives: ambgIndices }; }); errors = errors.concat(currPathPrefixErrors); }); return errors; } function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) { var errors = []; var tokenNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(tokenTypes, function (currToken) { return currToken.name; }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevels, function (currRule) { var currRuleName = currRule.name; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(tokenNames, currRuleName)) { var errMsg = errMsgProvider.buildNamespaceConflictError(currRule); errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: currRuleName }); } }); return errors; } function validateDuplicateNestedRules(topLevelRules, errMsgProvider) { var errors = []; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevelRules, function (currTopRule) { var namedCollectorVisitor = new _cst_cst__WEBPACK_IMPORTED_MODULE_4__.NamedDSLMethodsCollectorVisitor(""); currTopRule.accept(namedCollectorVisitor); var prodsByGroup = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.groupBy)(namedCollectorVisitor.result, function (item) { return item.name; }); var duplicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(prodsByGroup, function (currGroup) { return currGroup.length > 1; }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(duplicates), function (currDupGroup) { var currDupProds = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currDupGroup, function (dupGroup) { return dupGroup.orgProd; }); var errMsg = errMsgProvider.buildDuplicateNestedRuleNameError(currTopRule, currDupProds); errors.push({ message: errMsg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_NESTED_NAME, ruleName: currTopRule.name }); }); }); return errors; } //# sourceMappingURL=checks.js.map /***/ }), /* 37 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ PROD_TYPE: () => (/* binding */ PROD_TYPE), /* harmony export */ areTokenCategoriesNotUsed: () => (/* binding */ areTokenCategoriesNotUsed), /* harmony export */ buildAlternativesLookAheadFunc: () => (/* binding */ buildAlternativesLookAheadFunc), /* harmony export */ buildLookaheadFuncForOptionalProd: () => (/* binding */ buildLookaheadFuncForOptionalProd), /* harmony export */ buildLookaheadFuncForOr: () => (/* binding */ buildLookaheadFuncForOr), /* harmony export */ buildSingleAlternativeLookaheadFunction: () => (/* binding */ buildSingleAlternativeLookaheadFunction), /* harmony export */ containsPath: () => (/* binding */ containsPath), /* harmony export */ getLookaheadPathsForOptionalProd: () => (/* binding */ getLookaheadPathsForOptionalProd), /* harmony export */ getLookaheadPathsForOr: () => (/* binding */ getLookaheadPathsForOr), /* harmony export */ getProdType: () => (/* binding */ getProdType), /* harmony export */ isStrictPrefixOfPath: () => (/* binding */ isStrictPrefixOfPath), /* harmony export */ lookAheadSequenceFromAlternatives: () => (/* binding */ lookAheadSequenceFromAlternatives) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(38); /* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19); /* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); /* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(31); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PROD_TYPE; (function (PROD_TYPE) { PROD_TYPE[PROD_TYPE["OPTION"] = 0] = "OPTION"; PROD_TYPE[PROD_TYPE["REPETITION"] = 1] = "REPETITION"; PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY"; PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR"; PROD_TYPE[PROD_TYPE["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR"; PROD_TYPE[PROD_TYPE["ALTERNATION"] = 5] = "ALTERNATION"; })(PROD_TYPE || (PROD_TYPE = {})); function getProdType(prod) { /* istanbul ignore else */ if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Option) { return PROD_TYPE.OPTION; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Repetition) { return PROD_TYPE.REPETITION; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionMandatory) { return PROD_TYPE.REPETITION_MANDATORY; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionMandatoryWithSeparator) { return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionWithSeparator) { return PROD_TYPE.REPETITION_WITH_SEPARATOR; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Alternation) { return PROD_TYPE.ALTERNATION; } else { throw Error("non exhaustive match"); } } function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) { var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead); var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) ? _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcherNoCategories : _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcher; return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled); } /** * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare * the lookahead "inside" the production and the lookahead immediately "after" it in the same top level rule (context free). * * Example: given a production: * ABC(DE)?DF * * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two * alternatives. * * @returns A Lookahead function which will return true IFF the parser should parse the Optional production. */ function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) { var lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k); var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths) ? _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcherNoCategories : _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcher; return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled); } function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { var numOfAlts = alts.length; var areAllOneTokenLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(alts, function (currAlt) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(currAlt, function (currPath) { return currPath.length === 1; }); }); // This version takes into account the predicates as well. if (hasPredicates) { /** * @returns {number} - The chosen alternative index */ return function (orAlts) { // unfortunately the predicates must be extracted every single time // as they cannot be cached due to references to parameters(vars) which are no longer valid. // note that in the common case of no predicates, no cpu time will be wasted on this (see else block) var predicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(orAlts, function (currAlt) { return currAlt.GATE; }); for (var t = 0; t < numOfAlts; t++) { var currAlt = alts[t]; var currNumOfPaths = currAlt.length; var currPredicate = predicates[t]; if (currPredicate !== undefined && currPredicate.call(this) === false) { // if the predicate does not match there is no point in checking the paths continue; } nextPath: for (var j = 0; j < currNumOfPaths; j++) { var currPath = currAlt[j]; var currPathLength = currPath.length; for (var i = 0; i < currPathLength; i++) { var nextToken = this.LA(i + 1); if (tokenMatcher(nextToken, currPath[i]) === false) { // mismatch in current path // try the next pth continue nextPath; } } // found a full path that matches. // this will also work for an empty ALT as the loop will be skipped return t; } // none of the paths for the current alternative matched // try the next alternative } // none of the alternatives could be matched return undefined; }; } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) { // optimized (common) case of all the lookaheads paths requiring only // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used. var singleTokenAlts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(alts, function (currAlt) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(currAlt); }); var choiceToAlt_1 = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(singleTokenAlts, function (result, currAlt, idx) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAlt, function (currTokType) { if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(result, currTokType.tokenTypeIdx)) { result[currTokType.tokenTypeIdx] = idx; } (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatches, function (currExtendingType) { if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(result, currExtendingType)) { result[currExtendingType] = idx; } }); }); return result; }, []); /** * @returns {number} - The chosen alternative index */ return function () { var nextToken = this.LA(1); return choiceToAlt_1[nextToken.tokenTypeIdx]; }; } else { // optimized lookahead without needing to check the predicates at all. // this causes code duplication which is intentional to improve performance. /** * @returns {number} - The chosen alternative index */ return function () { for (var t = 0; t < numOfAlts; t++) { var currAlt = alts[t]; var currNumOfPaths = currAlt.length; nextPath: for (var j = 0; j < currNumOfPaths; j++) { var currPath = currAlt[j]; var currPathLength = currPath.length; for (var i = 0; i < currPathLength; i++) { var nextToken = this.LA(i + 1); if (tokenMatcher(nextToken, currPath[i]) === false) { // mismatch in current path // try the next pth continue nextPath; } } // found a full path that matches. // this will also work for an empty ALT as the loop will be skipped return t; } // none of the paths for the current alternative matched // try the next alternative } // none of the alternatives could be matched return undefined; }; } } function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) { var areAllOneTokenLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(alt, function (currPath) { return currPath.length === 1; }); var numOfPaths = alt.length; // optimized (common) case of all the lookaheads paths requiring only // a single token lookahead. if (areAllOneTokenLookahead && !dynamicTokensEnabled) { var singleTokensTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(alt); if (singleTokensTypes.length === 1 && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(singleTokensTypes[0].categoryMatches)) { var expectedTokenType = singleTokensTypes[0]; var expectedTokenUniqueKey_1 = expectedTokenType.tokenTypeIdx; return function () { return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey_1; }; } else { var choiceToAlt_2 = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(singleTokensTypes, function (result, currTokType, idx) { result[currTokType.tokenTypeIdx] = true; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatches, function (currExtendingType) { result[currExtendingType] = true; }); return result; }, []); return function () { var nextToken = this.LA(1); return choiceToAlt_2[nextToken.tokenTypeIdx] === true; }; } } else { return function () { nextPath: for (var j = 0; j < numOfPaths; j++) { var currPath = alt[j]; var currPathLength = currPath.length; for (var i = 0; i < currPathLength; i++) { var nextToken = this.LA(i + 1); if (tokenMatcher(nextToken, currPath[i]) === false) { // mismatch in current path // try the next pth continue nextPath; } } // found a full path that matches. return true; } // none of the paths matched return false; }; } } var RestDefinitionFinderWalker = /** @class */ (function (_super) { __extends(RestDefinitionFinderWalker, _super); function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) { var _this = _super.call(this) || this; _this.topProd = topProd; _this.targetOccurrence = targetOccurrence; _this.targetProdType = targetProdType; return _this; } RestDefinitionFinderWalker.prototype.startWalking = function () { this.walk(this.topProd); return this.restDef; }; RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) { if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdType) { this.restDef = currRest.concat(prevRest); return true; } // performance optimization, do not iterate over the entire Grammar ast after we have found the target return false; }; RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) { if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) { _super.prototype.walkOption.call(this, optionProd, currRest, prevRest); } }; RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) { _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest); } }; RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) { if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) { _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest); } }; RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) { _super.prototype.walkOption.call(this, manyProd, currRest, prevRest); } }; RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) { _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest); } }; return RestDefinitionFinderWalker; }(_rest__WEBPACK_IMPORTED_MODULE_2__.RestWalker)); /** * Returns the definition of a target production in a top level level rule. */ var InsideDefinitionFinderVisitor = /** @class */ (function (_super) { __extends(InsideDefinitionFinderVisitor, _super); function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) { var _this = _super.call(this) || this; _this.targetOccurrence = targetOccurrence; _this.targetProdType = targetProdType; _this.targetRef = targetRef; _this.result = []; return _this; } InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) { if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdName && (this.targetRef === undefined || node === this.targetRef)) { this.result = node.definition; } }; InsideDefinitionFinderVisitor.prototype.visitOption = function (node) { this.checkIsTarget(node, PROD_TYPE.OPTION); }; InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) { this.checkIsTarget(node, PROD_TYPE.REPETITION); }; InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY); }; InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR); }; InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) { this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR); }; InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) { this.checkIsTarget(node, PROD_TYPE.ALTERNATION); }; return InsideDefinitionFinderVisitor; }(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_5__.GAstVisitor)); function initializeArrayOfArrays(size) { var result = new Array(size); for (var i = 0; i < size; i++) { result[i] = []; } return result; } /** * A sort of hash function between a Path in the grammar and a string. * Note that this returns multiple "hashes" to support the scenario of token categories. * - A single path with categories may match multiple **actual** paths. */ function pathToHashKeys(path) { var keys = [""]; for (var i = 0; i < path.length; i++) { var tokType = path[i]; var longerKeys = []; for (var j = 0; j < keys.length; j++) { var currShorterKey = keys[j]; longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx); for (var t = 0; t < tokType.categoryMatches.length; t++) { var categoriesKeySuffix = "_" + tokType.categoryMatches[t]; longerKeys.push(currShorterKey + categoriesKeySuffix); } } keys = longerKeys; } return keys; } /** * Imperative style due to being called from a hot spot */ function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) { for (var currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) { // We only want to test vs the other alternatives if (currAltIdx === idx) { continue; } var otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx]; for (var searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) { var searchKey = searchPathKeys[searchIdx]; if (otherAltKnownPathsKeys[searchKey] === true) { return false; } } } // None of the SearchPathKeys were found in any of the other alternatives return true; } function lookAheadSequenceFromAlternatives(altsDefs, k) { var partialAlts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(altsDefs, function (currAlt) { return (0,_interpreter__WEBPACK_IMPORTED_MODULE_1__.possiblePathsFrom)([currAlt], 1); }); var finalResult = initializeArrayOfArrays(partialAlts.length); var altsHashes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(partialAlts, function (currAltPaths) { var dict = {}; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAltPaths, function (item) { var keys = pathToHashKeys(item.partialPath); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(keys, function (currKey) { dict[currKey] = true; }); }); return dict; }); var newData = partialAlts; // maxLookahead loop for (var pathLength = 1; pathLength <= k; pathLength++) { var currDataset = newData; newData = initializeArrayOfArrays(currDataset.length); var _loop_1 = function (altIdx) { var currAltPathsAndSuffixes = currDataset[altIdx]; // paths in current alternative loop for (var currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) { var currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath; var suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef; var prefixKeys = pathToHashKeys(currPathPrefix); var isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx); // End of the line for this path. if (isUnique || (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(suffixDef) || currPathPrefix.length === k) { var currAltResult = finalResult[altIdx]; // TODO: Can we implement a containsPath using Maps/Dictionaries? if (containsPath(currAltResult, currPathPrefix) === false) { currAltResult.push(currPathPrefix); // Update all new keys for the current path. for (var j = 0; j < prefixKeys.length; j++) { var currKey = prefixKeys[j]; altsHashes[altIdx][currKey] = true; } } } // Expand longer paths else { var newPartialPathsAndSuffixes = (0,_interpreter__WEBPACK_IMPORTED_MODULE_1__.possiblePathsFrom)(suffixDef, pathLength + 1, currPathPrefix); newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); // Update keys for new known paths (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(newPartialPathsAndSuffixes, function (item) { var prefixKeys = pathToHashKeys(item.partialPath); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(prefixKeys, function (key) { altsHashes[altIdx][key] = true; }); }); } } }; // alternatives loop for (var altIdx = 0; altIdx < currDataset.length; altIdx++) { _loop_1(altIdx); } } return finalResult; } function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) { var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd); ruleGrammar.accept(visitor); return lookAheadSequenceFromAlternatives(visitor.result, k); } function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) { var insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType); ruleGrammar.accept(insideDefVisitor); var insideDef = insideDefVisitor.result; var afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType); var afterDef = afterDefWalker.startWalking(); var insideFlat = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: insideDef }); var afterFlat = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: afterDef }); return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k); } function containsPath(alternative, searchPath) { compareOtherPath: for (var i = 0; i < alternative.length; i++) { var otherPath = alternative[i]; if (otherPath.length !== searchPath.length) { continue; } for (var j = 0; j < otherPath.length; j++) { var searchTok = searchPath[j]; var otherTok = otherPath[j]; var matchingTokens = searchTok === otherTok || otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== undefined; if (matchingTokens === false) { continue compareOtherPath; } } return true; } return false; } function isStrictPrefixOfPath(prefix, other) { return (prefix.length < other.length && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(prefix, function (tokType, idx) { var otherTokType = other[idx]; return (tokType === otherTokType || otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]); })); } function areTokenCategoriesNotUsed(lookAheadPaths) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(lookAheadPaths, function (singleAltPaths) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(singleAltPaths, function (singlePath) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(singlePath, function (token) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(token.categoryMatches); }); }); }); } //# sourceMappingURL=lookahead.js.map /***/ }), /* 38 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AbstractNextPossibleTokensWalker: () => (/* binding */ AbstractNextPossibleTokensWalker), /* harmony export */ AbstractNextTerminalAfterProductionWalker: () => (/* binding */ AbstractNextTerminalAfterProductionWalker), /* harmony export */ NextAfterTokenWalker: () => (/* binding */ NextAfterTokenWalker), /* harmony export */ NextTerminalAfterAtLeastOneSepWalker: () => (/* binding */ NextTerminalAfterAtLeastOneSepWalker), /* harmony export */ NextTerminalAfterAtLeastOneWalker: () => (/* binding */ NextTerminalAfterAtLeastOneWalker), /* harmony export */ NextTerminalAfterManySepWalker: () => (/* binding */ NextTerminalAfterManySepWalker), /* harmony export */ NextTerminalAfterManyWalker: () => (/* binding */ NextTerminalAfterManyWalker), /* harmony export */ nextPossibleTokensAfter: () => (/* binding */ nextPossibleTokensAfter), /* harmony export */ possiblePathsFrom: () => (/* binding */ possiblePathsFrom) /* harmony export */ }); /* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _first__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); /* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) { __extends(AbstractNextPossibleTokensWalker, _super); function AbstractNextPossibleTokensWalker(topProd, path) { var _this = _super.call(this) || this; _this.topProd = topProd; _this.path = path; _this.possibleTokTypes = []; _this.nextProductionName = ""; _this.nextProductionOccurrence = 0; _this.found = false; _this.isAtEndOfPath = false; return _this; } AbstractNextPossibleTokensWalker.prototype.startWalking = function () { this.found = false; if (this.path.ruleStack[0] !== this.topProd.name) { throw Error("The path does not start with the walker's top Rule!"); } // immutable for the win this.ruleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.path.ruleStack).reverse(); // intelij bug requires assertion this.occurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.path.occurrenceStack).reverse(); // intelij bug requires assertion // already verified that the first production is valid, we now seek the 2nd production this.ruleStack.pop(); this.occurrenceStack.pop(); this.updateExpectedNext(); this.walk(this.topProd); return this.possibleTokTypes; }; AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) { if (prevRest === void 0) { prevRest = []; } // stop scanning once we found the path if (!this.found) { _super.prototype.walk.call(this, prod, prevRest); } }; AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { // found the next production, need to keep walking in it if (refProd.referencedRule.name === this.nextProductionName && refProd.idx === this.nextProductionOccurrence) { var fullRest = currRest.concat(prevRest); this.updateExpectedNext(); this.walk(refProd.referencedRule, fullRest); } }; AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () { // need to consume the Terminal if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.ruleStack)) { // must reset nextProductionXXX to avoid walking down another Top Level production while what we are // really seeking is the last Terminal... this.nextProductionName = ""; this.nextProductionOccurrence = 0; this.isAtEndOfPath = true; } else { this.nextProductionName = this.ruleStack.pop(); this.nextProductionOccurrence = this.occurrenceStack.pop(); } }; return AbstractNextPossibleTokensWalker; }(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker)); var NextAfterTokenWalker = /** @class */ (function (_super) { __extends(NextAfterTokenWalker, _super); function NextAfterTokenWalker(topProd, path) { var _this = _super.call(this, topProd, path) || this; _this.path = path; _this.nextTerminalName = ""; _this.nextTerminalOccurrence = 0; _this.nextTerminalName = _this.path.lastTok.name; _this.nextTerminalOccurrence = _this.path.lastTokOccurrence; return _this; } NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { if (this.isAtEndOfPath && terminal.terminalType.name === this.nextTerminalName && terminal.idx === this.nextTerminalOccurrence && !this.found) { var fullRest = currRest.concat(prevRest); var restProd = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat({ definition: fullRest }); this.possibleTokTypes = (0,_first__WEBPACK_IMPORTED_MODULE_2__.first)(restProd); this.found = true; } }; return NextAfterTokenWalker; }(AbstractNextPossibleTokensWalker)); /** * This walker only "walks" a single "TOP" level in the Grammar Ast, this means * it never "follows" production refs */ var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) { __extends(AbstractNextTerminalAfterProductionWalker, _super); function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) { var _this = _super.call(this) || this; _this.topRule = topRule; _this.occurrence = occurrence; _this.result = { token: undefined, occurrence: undefined, isEndOfRule: undefined }; return _this; } AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () { this.walk(this.topRule); return this.result; }; return AbstractNextTerminalAfterProductionWalker; }(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker)); var NextTerminalAfterManyWalker = /** @class */ (function (_super) { __extends(NextTerminalAfterManyWalker, _super); function NextTerminalAfterManyWalker() { return _super !== null && _super.apply(this, arguments) || this; } NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) { if (manyProd.idx === this.occurrence) { var firstAfterMany = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterMany === undefined; if (firstAfterMany instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { this.result.token = firstAfterMany.terminalType; this.result.occurrence = firstAfterMany.idx; } } else { _super.prototype.walkMany.call(this, manyProd, currRest, prevRest); } }; return NextTerminalAfterManyWalker; }(AbstractNextTerminalAfterProductionWalker)); var NextTerminalAfterManySepWalker = /** @class */ (function (_super) { __extends(NextTerminalAfterManySepWalker, _super); function NextTerminalAfterManySepWalker() { return _super !== null && _super.apply(this, arguments) || this; } NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) { if (manySepProd.idx === this.occurrence) { var firstAfterManySep = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterManySep === undefined; if (firstAfterManySep instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { this.result.token = firstAfterManySep.terminalType; this.result.occurrence = firstAfterManySep.idx; } } else { _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest); } }; return NextTerminalAfterManySepWalker; }(AbstractNextTerminalAfterProductionWalker)); var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) { __extends(NextTerminalAfterAtLeastOneWalker, _super); function NextTerminalAfterAtLeastOneWalker() { return _super !== null && _super.apply(this, arguments) || this; } NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) { if (atLeastOneProd.idx === this.occurrence) { var firstAfterAtLeastOne = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterAtLeastOne === undefined; if (firstAfterAtLeastOne instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { this.result.token = firstAfterAtLeastOne.terminalType; this.result.occurrence = firstAfterAtLeastOne.idx; } } else { _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest); } }; return NextTerminalAfterAtLeastOneWalker; }(AbstractNextTerminalAfterProductionWalker)); // TODO: reduce code duplication in the AfterWalkers var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) { __extends(NextTerminalAfterAtLeastOneSepWalker, _super); function NextTerminalAfterAtLeastOneSepWalker() { return _super !== null && _super.apply(this, arguments) || this; } NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) { if (atleastOneSepProd.idx === this.occurrence) { var firstAfterfirstAfterAtLeastOneSep = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest)); this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined; if (firstAfterfirstAfterAtLeastOneSep instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType; this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx; } } else { _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest); } }; return NextTerminalAfterAtLeastOneSepWalker; }(AbstractNextTerminalAfterProductionWalker)); function possiblePathsFrom(targetDef, maxLength, currPath) { if (currPath === void 0) { currPath = []; } // avoid side effects currPath = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currPath); var result = []; var i = 0; // TODO: avoid inner funcs function remainingPathWith(nextDef) { return nextDef.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(targetDef, i + 1)); } // TODO: avoid inner funcs function getAlternativesForProd(definition) { var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath); return result.concat(alternatives); } /** * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the * following (rest) of the targetDef. * * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the * the optional production. */ while (currPath.length < maxLength && i < targetDef.length) { var prod = targetDef[i]; /* istanbul ignore else */ if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat) { return getAlternativesForProd(prod.definition); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.NonTerminal) { return getAlternativesForProd(prod.definition); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Option) { result = getAlternativesForProd(prod.definition); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatory) { var newDef = prod.definition.concat([ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: prod.definition }) ]); return getAlternativesForProd(newDef); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatoryWithSeparator) { var newDef = [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat({ definition: prod.definition }), new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator }) ].concat(prod.definition) }) ]; return getAlternativesForProd(newDef); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionWithSeparator) { var newDef = prod.definition.concat([ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: [ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator }) ].concat(prod.definition) }) ]); result = getAlternativesForProd(newDef); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition) { var newDef = prod.definition.concat([ new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: prod.definition }) ]); result = getAlternativesForProd(newDef); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Alternation) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(prod.definition, function (currAlt) { result = getAlternativesForProd(currAlt.definition); }); return result; } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { currPath.push(prod.terminalType); } else { throw Error("non exhaustive match"); } i++; } result.push({ partialPath: currPath, suffixDef: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(targetDef, i) }); return result; } function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) { var EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL"; // to avoid creating a new Array each time. var EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL]; var EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE"; var foundCompletePath = false; var tokenVectorLength = tokenVector.length; var minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1; var result = []; var possiblePaths = []; possiblePaths.push({ idx: -1, def: initialDef, ruleStack: [], occurrenceStack: [] }); while (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(possiblePaths)) { var currPath = possiblePaths.pop(); // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead) if (currPath === EXIT_ALTERNATIVE) { if (foundCompletePath && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.last)(possiblePaths).idx <= minimalAlternativesIndex) { // remove irrelevant alternative possiblePaths.pop(); } continue; } var currDef = currPath.def; var currIdx = currPath.idx; var currRuleStack = currPath.ruleStack; var currOccurrenceStack = currPath.occurrenceStack; // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(currDef)) { continue; } var prod = currDef[0]; /* istanbul ignore else */ if (prod === EXIT_NON_TERMINAL) { var nextPath = { idx: currIdx, def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef), ruleStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(currRuleStack), occurrenceStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(currOccurrenceStack) }; possiblePaths.push(nextPath); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) { /* istanbul ignore else */ if (currIdx < tokenVectorLength - 1) { var nextIdx = currIdx + 1; var actualToken = tokenVector[nextIdx]; if (tokMatcher(actualToken, prod.terminalType)) { var nextPath = { idx: nextIdx, def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } // end of the line } else if (currIdx === tokenVectorLength - 1) { // IGNORE ABOVE ELSE result.push({ nextTokenType: prod.terminalType, nextTokenOccurrence: prod.idx, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }); foundCompletePath = true; } else { throw Error("non exhaustive match"); } } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.NonTerminal) { var newRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currRuleStack); newRuleStack.push(prod.nonTerminalName); var newOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currOccurrenceStack); newOccurrenceStack.push(prod.idx); var nextPath = { idx: currIdx, def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)), ruleStack: newRuleStack, occurrenceStack: newOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Option) { // the order of alternatives is meaningful, FILO (Last path will be traversed first). var nextPathWithout = { idx: currIdx, def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); // required marker to avoid backtracking paths whose higher priority alternatives already matched possiblePaths.push(EXIT_ALTERNATIVE); var nextPathWith = { idx: currIdx, def: prod.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatory) { // TODO:(THE NEW operators here take a while...) (convert once?) var secondIteration = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: prod.definition, idx: prod.idx }); var nextDef = prod.definition.concat([secondIteration], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)); var nextPath = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatoryWithSeparator) { // TODO:(THE NEW operators here take a while...) (convert once?) var separatorGast = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator }); var secondIteration = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: [separatorGast].concat(prod.definition), idx: prod.idx }); var nextDef = prod.definition.concat([secondIteration], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)); var nextPath = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPath); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionWithSeparator) { // the order of alternatives is meaningful, FILO (Last path will be traversed first). var nextPathWithout = { idx: currIdx, def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); // required marker to avoid backtracking paths whose higher priority alternatives already matched possiblePaths.push(EXIT_ALTERNATIVE); var separatorGast = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator }); var nthRepetition = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: [separatorGast].concat(prod.definition), idx: prod.idx }); var nextDef = prod.definition.concat([nthRepetition], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)); var nextPathWith = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition) { // the order of alternatives is meaningful, FILO (Last path will be traversed first). var nextPathWithout = { idx: currIdx, def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWithout); // required marker to avoid backtracking paths whose higher priority alternatives already matched possiblePaths.push(EXIT_ALTERNATIVE); // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis? var nthRepetition = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({ definition: prod.definition, idx: prod.idx }); var nextDef = prod.definition.concat([nthRepetition], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)); var nextPathWith = { idx: currIdx, def: nextDef, ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(nextPathWith); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Alternation) { // the order of alternatives is meaningful, FILO (Last path will be traversed first). for (var i = prod.definition.length - 1; i >= 0; i--) { var currAlt = prod.definition[i]; var currAltPath = { idx: currIdx, def: currAlt.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }; possiblePaths.push(currAltPath); possiblePaths.push(EXIT_ALTERNATIVE); } } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat) { possiblePaths.push({ idx: currIdx, def: prod.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)), ruleStack: currRuleStack, occurrenceStack: currOccurrenceStack }); } else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Rule) { // last because we should only encounter at most a single one of these per invocation. possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack)); } else { throw Error("non exhaustive match"); } } return result; } function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) { var newRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currRuleStack); newRuleStack.push(topRule.name); var newCurrOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currOccurrenceStack); // top rule is always assumed to have been called with occurrence index 1 newCurrOccurrenceStack.push(1); return { idx: currIdx, def: topRule.definition, ruleStack: newRuleStack, occurrenceStack: newCurrOccurrenceStack }; } //# sourceMappingURL=interpreter.js.map /***/ }), /* 39 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ assignOccurrenceIndices: () => (/* binding */ assignOccurrenceIndices), /* harmony export */ resolveGrammar: () => (/* binding */ resolveGrammar), /* harmony export */ validateGrammar: () => (/* binding */ validateGrammar) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _resolver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40); /* harmony import */ var _checks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36); /* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); /* harmony import */ var _gast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30); function resolveGrammar(options) { options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.defaults)(options, { errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarResolverErrorProvider }); var topRulesTable = {}; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(options.rules, function (rule) { topRulesTable[rule.name] = rule; }); return (0,_resolver__WEBPACK_IMPORTED_MODULE_1__.resolveGrammar)(topRulesTable, options.errMsgProvider); } function validateGrammar(options) { options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.defaults)(options, { errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarValidatorErrorProvider, ignoredIssues: {} }); return (0,_checks__WEBPACK_IMPORTED_MODULE_2__.validateGrammar)(options.rules, options.maxLookahead, options.tokenTypes, options.ignoredIssues, options.errMsgProvider, options.grammarName); } function assignOccurrenceIndices(options) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(options.rules, function (currRule) { var methodsCollector = new _gast__WEBPACK_IMPORTED_MODULE_4__.DslMethodsCollectorVisitor(); currRule.accept(methodsCollector); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(methodsCollector.dslMethods, function (methods) { (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(methods, function (currMethod, arrIdx) { currMethod.idx = arrIdx + 1; }); }); }); } //# sourceMappingURL=gast_resolver_public.js.map /***/ }), /* 40 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ GastRefResolverVisitor: () => (/* binding */ GastRefResolverVisitor), /* harmony export */ resolveGrammar: () => (/* binding */ resolveGrammar) /* harmony export */ }); /* harmony import */ var _parser_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function resolveGrammar(topLevels, errMsgProvider) { var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider); refResolver.resolveRefs(); return refResolver.errors; } var GastRefResolverVisitor = /** @class */ (function (_super) { __extends(GastRefResolverVisitor, _super); function GastRefResolverVisitor(nameToTopRule, errMsgProvider) { var _this = _super.call(this) || this; _this.nameToTopRule = nameToTopRule; _this.errMsgProvider = errMsgProvider; _this.errors = []; return _this; } GastRefResolverVisitor.prototype.resolveRefs = function () { var _this = this; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.values)(this.nameToTopRule), function (prod) { _this.currTopLevel = prod; prod.accept(_this); }); }; GastRefResolverVisitor.prototype.visitNonTerminal = function (node) { var ref = this.nameToTopRule[node.nonTerminalName]; if (!ref) { var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node); this.errors.push({ message: msg, type: _parser_parser__WEBPACK_IMPORTED_MODULE_0__.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: node.nonTerminalName }); } else { node.referencedRule = ref; } }; return GastRefResolverVisitor; }(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__.GAstVisitor)); //# sourceMappingURL=resolver.js.map /***/ }), /* 41 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EOF_FOLLOW_KEY: () => (/* binding */ EOF_FOLLOW_KEY), /* harmony export */ IN_RULE_RECOVERY_EXCEPTION: () => (/* binding */ IN_RULE_RECOVERY_EXCEPTION), /* harmony export */ InRuleRecoveryException: () => (/* binding */ InRuleRecoveryException), /* harmony export */ Recoverable: () => (/* binding */ Recoverable), /* harmony export */ attemptInRepetitionRecovery: () => (/* binding */ attemptInRepetitionRecovery) /* harmony export */ }); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(32); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16); var EOF_FOLLOW_KEY = {}; var IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; function InRuleRecoveryException(message) { this.name = IN_RULE_RECOVERY_EXCEPTION; this.message = message; } InRuleRecoveryException.prototype = Error.prototype; /** * This trait is responsible for the error recovery and fault tolerant logic */ var Recoverable = /** @class */ (function () { function Recoverable() { } Recoverable.prototype.initRecoverable = function (config) { this.firstAfterRepMap = {}; this.resyncFollows = {}; this.recoveryEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "recoveryEnabled") ? config.recoveryEnabled : _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.recoveryEnabled; // performance optimization, NOOP will be inlined which // effectively means that this optional feature does not exist // when not used. if (this.recoveryEnabled) { this.attemptInRepetitionRecovery = attemptInRepetitionRecovery; } }; Recoverable.prototype.getTokenToInsert = function (tokType) { var tokToInsert = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.createTokenInstance)(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN); tokToInsert.isInsertedInRecovery = true; return tokToInsert; }; Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) { return true; }; Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) { var _this = this; // TODO: can the resyncTokenType be cached? var reSyncTokType = this.findReSyncTokenType(); var savedLexerState = this.exportLexerState(); var resyncedTokens = []; var passedResyncPoint = false; var nextTokenWithoutResync = this.LA(1); var currToken = this.LA(1); var generateErrorMessage = function () { var previousToken = _this.LA(0); // we are preemptively re-syncing before an error has been detected, therefor we must reproduce // the error that would have been thrown var msg = _this.errorMessageProvider.buildMismatchTokenMessage({ expected: expectedTokType, actual: nextTokenWithoutResync, previous: previousToken, ruleName: _this.getCurrRuleFullName() }); var error = new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.MismatchedTokenException(msg, nextTokenWithoutResync, _this.LA(0)); // the first token here will be the original cause of the error, this is not part of the resyncedTokens property. error.resyncedTokens = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(resyncedTokens); _this.SAVE_ERROR(error); }; while (!passedResyncPoint) { // re-synced to a point where we can safely exit the repetition/ if (this.tokenMatcher(currToken, expectedTokType)) { generateErrorMessage(); return; // must return here to avoid reverting the inputIdx } else if (lookAheadFunc.call(this)) { // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule generateErrorMessage(); // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule grammarRule.apply(this, grammarRuleArgs); return; // must return here to avoid reverting the inputIdx } else if (this.tokenMatcher(currToken, reSyncTokType)) { passedResyncPoint = true; } else { currToken = this.SKIP_TOKEN(); this.addToResyncTokens(currToken, resyncedTokens); } } // we were unable to find a CLOSER point to resync inside the Repetition, reset the state. // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by // "between rules" resync recovery later in the flow. this.importLexerState(savedLexerState); }; Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) { // Edge case of arriving from a MANY repetition which is stuck // Attempting recovery in this case could cause an infinite loop if (notStuck === false) { return false; } // arguments to try and perform resync into the next iteration of the many are missing if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) { return false; } // no need to recover, next token is what we expect... if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) { return false; } // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path // and prefer some backtracking path that includes recovered errors. if (this.isBackTracking()) { return false; } // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm // because if it works, it makes the least amount of changes to the input stream (greedy algorithm) //noinspection RedundantIfStatementJS if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) { return false; } return true; }; // Error Recovery functionality Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) { var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule); var follows = this.getNextPossibleTokenTypes(grammarPath); return follows; }; Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) { if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) { var tokToInsert = this.getTokenToInsert(expectedTokType); return tokToInsert; } if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) { var nextTok = this.SKIP_TOKEN(); this.consumeToken(); return nextTok; } throw new InRuleRecoveryException("sad sad panda"); }; Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) { return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || this.canRecoverWithSingleTokenDeletion(expectedToken)); }; Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) { var _this = this; if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) { return false; } // must know the possible following tokens to perform single token insertion if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(follows)) { return false; } var mismatchedTok = this.LA(1); var isMisMatchedTokInFollows = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(follows, function (possibleFollowsTokType) { return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType); }) !== undefined; return isMisMatchedTokInFollows; }; Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) { var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType); return isNextTokenWhatIsExpected; }; Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) { var followKey = this.getCurrFollowKey(); var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey); return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(currentRuleReSyncSet, tokenTypeIdx); }; Recoverable.prototype.findReSyncTokenType = function () { var allPossibleReSyncTokTypes = this.flattenFollowSet(); // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input var nextToken = this.LA(1); var k = 2; while (true) { var nextTokenType = nextToken.tokenType; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(allPossibleReSyncTokTypes, nextTokenType)) { return nextTokenType; } nextToken = this.LA(k); k++; } }; Recoverable.prototype.getCurrFollowKey = function () { // the length is at least one as we always add the ruleName to the stack before invoking the rule. if (this.RULE_STACK.length === 1) { return EOF_FOLLOW_KEY; } var currRuleShortName = this.getLastExplicitRuleShortName(); var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex(); var prevRuleShortName = this.getPreviousExplicitRuleShortName(); return { ruleName: this.shortRuleNameToFullName(currRuleShortName), idxInCallingRule: currRuleIdx, inRule: this.shortRuleNameToFullName(prevRuleShortName) }; }; Recoverable.prototype.buildFullFollowKeyStack = function () { var _this = this; var explicitRuleStack = this.RULE_STACK; var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.LAST_EXPLICIT_RULE_STACK)) { explicitRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_STACK[idx]; }); explicitOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_OCCURRENCE_STACK[idx]; }); } // TODO: only iterate over explicit rules here return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(explicitRuleStack, function (ruleName, idx) { if (idx === 0) { return EOF_FOLLOW_KEY; } return { ruleName: _this.shortRuleNameToFullName(ruleName), idxInCallingRule: explicitOccurrenceStack[idx], inRule: _this.shortRuleNameToFullName(explicitRuleStack[idx - 1]) }; }); }; Recoverable.prototype.flattenFollowSet = function () { var _this = this; var followStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.buildFullFollowKeyStack(), function (currKey) { return _this.getFollowSetFromFollowKey(currKey); }); return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.flatten)(followStack); }; Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) { if (followKey === EOF_FOLLOW_KEY) { return [_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF]; } var followName = followKey.ruleName + followKey.idxInCallingRule + _constants__WEBPACK_IMPORTED_MODULE_3__.IN + followKey.inRule; return this.resyncFollows[followName]; }; // It does not make any sense to include a virtual EOF token in the list of resynced tokens // as EOF does not really exist and thus does not contain any useful information (line/column numbers) Recoverable.prototype.addToResyncTokens = function (token, resyncTokens) { if (!this.tokenMatcher(token, _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF)) { resyncTokens.push(token); } return resyncTokens; }; Recoverable.prototype.reSyncTo = function (tokType) { var resyncedTokens = []; var nextTok = this.LA(1); while (this.tokenMatcher(nextTok, tokType) === false) { nextTok = this.SKIP_TOKEN(); this.addToResyncTokens(nextTok, resyncedTokens); } // the last token is not part of the error. return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(resyncedTokens); }; Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { // by default this is a NO-OP // The actual implementation is with the function(not method) below }; Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) { var pathRuleStack = this.getHumanReadableRuleStack(); var pathOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.RULE_OCCURRENCE_STACK); var grammarPath = { ruleStack: pathRuleStack, occurrenceStack: pathOccurrenceStack, lastTok: tokType, lastTokOccurrence: tokIdxInRule }; return grammarPath; }; Recoverable.prototype.getHumanReadableRuleStack = function () { var _this = this; if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.LAST_EXPLICIT_RULE_STACK)) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (currIdx) { return _this.shortRuleNameToFullName(_this.RULE_STACK[currIdx]); }); } else { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.RULE_STACK, function (currShortName) { return _this.shortRuleNameToFullName(currShortName); }); } }; return Recoverable; }()); function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) { var key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence); var firstAfterRepInfo = this.firstAfterRepMap[key]; if (firstAfterRepInfo === undefined) { var currRuleName = this.getCurrRuleFullName(); var ruleGrammar = this.getGAstProductions()[currRuleName]; var walker = new nextToksWalker(ruleGrammar, prodOccurrence); firstAfterRepInfo = walker.startWalking(); this.firstAfterRepMap[key] = firstAfterRepInfo; } var expectTokAfterLastMatch = firstAfterRepInfo.token; var nextTokIdx = firstAfterRepInfo.occurrence; var isEndOfRule = firstAfterRepInfo.isEndOfRule; // special edge case of a TOP most repetition after which the input should END. // this will force an attempt for inRule recovery in that scenario. if (this.RULE_STACK.length === 1 && isEndOfRule && expectTokAfterLastMatch === undefined) { expectTokAfterLastMatch = _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF; nextTokIdx = 1; } if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) { // TODO: performance optimization: instead of passing the original args here, we modify // the args param (or create a new one) and make sure the lookahead func is explicitly provided // to avoid searching the cache for it once more. this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch); } } //# sourceMappingURL=recoverable.js.map /***/ }), /* 42 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EarlyExitException: () => (/* binding */ EarlyExitException), /* harmony export */ MismatchedTokenException: () => (/* binding */ MismatchedTokenException), /* harmony export */ NoViableAltException: () => (/* binding */ NoViableAltException), /* harmony export */ NotAllInputParsedException: () => (/* binding */ NotAllInputParsedException), /* harmony export */ isRecognitionException: () => (/* binding */ isRecognitionException) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException"; var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException"; var EARLY_EXIT_EXCEPTION = "EarlyExitException"; var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException"; var RECOGNITION_EXCEPTION_NAMES = [ MISMATCHED_TOKEN_EXCEPTION, NO_VIABLE_ALT_EXCEPTION, EARLY_EXIT_EXCEPTION, NOT_ALL_INPUT_PARSED_EXCEPTION ]; Object.freeze(RECOGNITION_EXCEPTION_NAMES); // hacks to bypass no support for custom Errors in javascript/typescript function isRecognitionException(error) { // can't do instanceof on hacked custom js exceptions return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(RECOGNITION_EXCEPTION_NAMES, error.name); } function MismatchedTokenException(message, token, previousToken) { this.name = MISMATCHED_TOKEN_EXCEPTION; this.message = message; this.token = token; this.previousToken = previousToken; this.resyncedTokens = []; } // must use the "Error.prototype" instead of "new Error" // because the stack trace points to where "new Error" was invoked" MismatchedTokenException.prototype = Error.prototype; function NoViableAltException(message, token, previousToken) { this.name = NO_VIABLE_ALT_EXCEPTION; this.message = message; this.token = token; this.previousToken = previousToken; this.resyncedTokens = []; } NoViableAltException.prototype = Error.prototype; function NotAllInputParsedException(message, token) { this.name = NOT_ALL_INPUT_PARSED_EXCEPTION; this.message = message; this.token = token; this.resyncedTokens = []; } NotAllInputParsedException.prototype = Error.prototype; function EarlyExitException(message, token, previousToken) { this.name = EARLY_EXIT_EXCEPTION; this.message = message; this.token = token; this.previousToken = previousToken; this.resyncedTokens = []; } EarlyExitException.prototype = Error.prototype; //# sourceMappingURL=exceptions_public.js.map /***/ }), /* 43 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LooksAhead: () => (/* binding */ LooksAhead) /* harmony export */ }); /* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16); /* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34); /* harmony import */ var _grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30); /** * Trait responsible for the lookahead related utilities and optimizations. */ var LooksAhead = /** @class */ (function () { function LooksAhead() { } LooksAhead.prototype.initLooksAhead = function (config) { this.dynamicTokensEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "dynamicTokensEnabled") ? config.dynamicTokensEnabled : _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; this.maxLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "maxLookahead") ? config.maxLookahead : _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_PARSER_CONFIG.maxLookahead; /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ this.lookAheadFuncsCache = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isES2015MapSupported)() ? new Map() : []; // Performance optimization on newer engines that support ES6 Map // For larger Maps this is slightly faster than using a plain object (array in our case). /* istanbul ignore else - The else branch will be tested on older node.js versions and IE11 */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isES2015MapSupported)()) { this.getLaFuncFromCache = this.getLaFuncFromMap; this.setLaFuncCache = this.setLaFuncCacheUsingMap; } else { this.getLaFuncFromCache = this.getLaFuncFromObj; this.setLaFuncCache = this.setLaFuncUsingObj; } }; LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) { var _this = this; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(rules, function (currRule) { _this.TRACE_INIT(currRule.name + " Rule Lookahead", function () { var _a = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.collectMethods)(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(alternation, function (currProd) { var prodIdx = currProd.idx === 0 ? "" : currProd.idx; _this.TRACE_INIT("" + (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd) + prodIdx, function () { var laFunc = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildLookaheadFuncForOr)(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives); var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[currRule.name], _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.OR_IDX, currProd.idx); _this.setLaFuncCache(key, laFunc); }); }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetition, function (currProd) { _this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.MANY_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd)); }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(option, function (currProd) { _this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.OPTION_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.OPTION, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd)); }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionMandatory, function (currProd) { _this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.AT_LEAST_ONE_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd)); }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionMandatoryWithSeparator, function (currProd) { _this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.AT_LEAST_ONE_SEP_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd)); }); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionWithSeparator, function (currProd) { _this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.MANY_SEP_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd)); }); }); }); }; LooksAhead.prototype.computeLookaheadFunc = function (rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) { var _this = this; this.TRACE_INIT("" + dslMethodName + (prodOccurrence === 0 ? "" : prodOccurrence), function () { var laFunc = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildLookaheadFuncForOptionalProd)(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional); var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); _this.setLaFuncCache(key, laFunc); }); }; LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) { return (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildSingleAlternativeLookaheadFunction)(alt, tokenMatcher, dynamicTokensEnabled); }; LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { return (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildAlternativesLookAheadFunc)(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled); }; // this actually returns a number, but it is always used as a string (object prop key) LooksAhead.prototype.getKeyForAutomaticLookahead = function (dslMethodIdx, occurrence) { var currRuleShortName = this.getLastExplicitRuleShortName(); return (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(currRuleShortName, dslMethodIdx, occurrence); }; /* istanbul ignore next */ LooksAhead.prototype.getLaFuncFromCache = function (key) { return undefined; }; LooksAhead.prototype.getLaFuncFromMap = function (key) { return this.lookAheadFuncsCache.get(key); }; /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ LooksAhead.prototype.getLaFuncFromObj = function (key) { return this.lookAheadFuncsCache[key]; }; /* istanbul ignore next */ LooksAhead.prototype.setLaFuncCache = function (key, value) { }; LooksAhead.prototype.setLaFuncCacheUsingMap = function (key, value) { this.lookAheadFuncsCache.set(key, value); }; /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ LooksAhead.prototype.setLaFuncUsingObj = function (key, value) { this.lookAheadFuncsCache[key] = value; }; return LooksAhead; }()); //# sourceMappingURL=looksahead.js.map /***/ }), /* 44 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TreeBuilder: () => (/* binding */ TreeBuilder) /* harmony export */ }); /* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(33); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(45); /* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16); /** * This trait is responsible for the CST building logic. */ var TreeBuilder = /** @class */ (function () { function TreeBuilder() { } TreeBuilder.prototype.initTreeBuilder = function (config) { this.LAST_EXPLICIT_RULE_STACK = []; this.CST_STACK = []; this.outputCst = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "outputCst") ? config.outputCst : _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.outputCst; this.nodeLocationTracking = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "nodeLocationTracking") ? config.nodeLocationTracking : _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.nodeLocationTracking; if (!this.outputCst) { this.cstInvocationStateUpdate = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstFinallyStateUpdate = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostTerminal = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostNonTerminal = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.getLastExplicitRuleShortName = this.getLastExplicitRuleShortNameNoCst; this.getPreviousExplicitRuleShortName = this.getPreviousExplicitRuleShortNameNoCst; this.getLastExplicitRuleOccurrenceIndex = this.getLastExplicitRuleOccurrenceIndexNoCst; this.manyInternal = this.manyInternalNoCst; this.orInternal = this.orInternalNoCst; this.optionInternal = this.optionInternalNoCst; this.atLeastOneInternal = this.atLeastOneInternalNoCst; this.manySepFirstInternal = this.manySepFirstInternalNoCst; this.atLeastOneSepFirstInternal = this.atLeastOneSepFirstInternalNoCst; } else { if (/full/i.test(this.nodeLocationTracking)) { if (this.recoveryEnabled) { this.setNodeLocationFromToken = _cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationFull; this.setNodeLocationFromNode = _cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationFull; this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; } else { this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostRule = this.cstPostRuleFull; this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; } } else if (/onlyOffset/i.test(this.nodeLocationTracking)) { if (this.recoveryEnabled) { this.setNodeLocationFromToken = (_cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationOnlyOffset); this.setNodeLocationFromNode = (_cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationOnlyOffset); this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery; } else { this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostRule = this.cstPostRuleOnlyOffset; this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular; } } else if (/none/i.test(this.nodeLocationTracking)) { this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; this.setInitialNodeLocation = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP; } else { throw Error("Invalid config option: \"" + config.nodeLocationTracking + "\""); } } }; TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRecovery = function (cstNode) { cstNode.location = { startOffset: NaN, endOffset: NaN }; }; TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRegular = function (cstNode) { cstNode.location = { // without error recovery the starting Location of a new CstNode is guaranteed // To be the next Token's startOffset (for valid inputs). // For invalid inputs there won't be any CSTOutput so this potential // inaccuracy does not matter startOffset: this.LA(1).startOffset, endOffset: NaN }; }; TreeBuilder.prototype.setInitialNodeLocationFullRecovery = function (cstNode) { cstNode.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN }; }; /** * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work * @param cstNode */ TreeBuilder.prototype.setInitialNodeLocationFullRegular = function (cstNode) { var nextToken = this.LA(1); cstNode.location = { startOffset: nextToken.startOffset, startLine: nextToken.startLine, startColumn: nextToken.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN }; }; // CST TreeBuilder.prototype.cstNestedInvocationStateUpdate = function (nestedName, shortName) { var cstNode = { name: nestedName, fullName: this.shortRuleNameToFull[this.getLastExplicitRuleShortName()] + nestedName, children: {} }; this.setInitialNodeLocation(cstNode); this.CST_STACK.push(cstNode); }; TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) { this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length - 1); var cstNode = { name: fullRuleName, children: {} }; this.setInitialNodeLocation(cstNode); this.CST_STACK.push(cstNode); }; TreeBuilder.prototype.cstFinallyStateUpdate = function () { this.LAST_EXPLICIT_RULE_STACK.pop(); this.CST_STACK.pop(); }; TreeBuilder.prototype.cstNestedFinallyStateUpdate = function () { var lastCstNode = this.CST_STACK.pop(); // TODO: the naming is bad, this should go directly to the // (correct) cstLocation update method // e.g if we put other logic in postRule... this.cstPostRule(lastCstNode); }; TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) { var prevToken = this.LA(0); var loc = ruleCstNode.location; // If this condition is true it means we consumed at least one Token // In this CstNode or its nested children. if (loc.startOffset <= prevToken.startOffset === true) { loc.endOffset = prevToken.endOffset; loc.endLine = prevToken.endLine; loc.endColumn = prevToken.endColumn; } // "empty" CstNode edge case else { loc.startOffset = NaN; loc.startLine = NaN; loc.startColumn = NaN; } }; TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) { var prevToken = this.LA(0); var loc = ruleCstNode.location; // If this condition is true it means we consumed at least one Token // In this CstNode or its nested children. if (loc.startOffset <= prevToken.startOffset === true) { loc.endOffset = prevToken.endOffset; } // "empty" CstNode edge case else { loc.startOffset = NaN; } }; TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) { var rootCst = this.CST_STACK[this.CST_STACK.length - 1]; (0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addTerminalToCst)(rootCst, consumedToken, key); // This is only used when **both** error recovery and CST Output are enabled. this.setNodeLocationFromToken(rootCst.location, consumedToken); }; TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) { // Avoid side effects due to back tracking // TODO: This costs a 2-3% in performance, A flag on IParserConfig // could be used to get rid of this conditional, but not sure its worth the effort // and API complexity. if (this.isBackTracking() !== true) { var preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; (0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addNoneTerminalToCst)(preCstNode, ruleName, ruleCstResult); // This is only used when **both** error recovery and CST Output are enabled. this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location); } }; TreeBuilder.prototype.getBaseCstVisitorConstructor = function () { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(this.baseCstVisitorConstructor)) { var newBaseCstVisitorConstructor = (0,_cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__.createBaseSemanticVisitorConstructor)(this.className, this.allRuleNames); this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; return newBaseCstVisitorConstructor; } return this.baseCstVisitorConstructor; }; TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(this.baseCstVisitorWithDefaultsConstructor)) { var newConstructor = (0,_cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__.createBaseVisitorConstructorWithDefaults)(this.className, this.allRuleNames, this.getBaseCstVisitorConstructor()); this.baseCstVisitorWithDefaultsConstructor = newConstructor; return newConstructor; } return this.baseCstVisitorWithDefaultsConstructor; }; TreeBuilder.prototype.nestedRuleBeforeClause = function (methodOpts, laKey) { var nestedName; if (methodOpts.NAME !== undefined) { nestedName = methodOpts.NAME; this.nestedRuleInvocationStateUpdate(nestedName, laKey); return nestedName; } else { return undefined; } }; TreeBuilder.prototype.nestedAltBeforeClause = function (methodOpts, occurrence, methodKeyIdx, altIdx) { var ruleIdx = this.getLastExplicitRuleShortName(); var shortName = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAltIndex)(ruleIdx, methodKeyIdx, occurrence, altIdx); var nestedName; if (methodOpts.NAME !== undefined) { nestedName = methodOpts.NAME; this.nestedRuleInvocationStateUpdate(nestedName, shortName); return { shortName: shortName, nestedName: nestedName }; } else { return undefined; } }; TreeBuilder.prototype.nestedRuleFinallyClause = function (laKey, nestedName) { var cstStack = this.CST_STACK; var nestedRuleCst = cstStack[cstStack.length - 1]; this.nestedRuleFinallyStateUpdate(); // this return a different result than the previous invocation because "nestedRuleFinallyStateUpdate" pops the cst stack var parentCstNode = cstStack[cstStack.length - 1]; (0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addNoneTerminalToCst)(parentCstNode, nestedName, nestedRuleCst); this.setNodeLocationFromNode(parentCstNode.location, nestedRuleCst.location); }; TreeBuilder.prototype.getLastExplicitRuleShortName = function () { var lastExplictIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1]; return this.RULE_STACK[lastExplictIndex]; }; TreeBuilder.prototype.getLastExplicitRuleShortNameNoCst = function () { var ruleStack = this.RULE_STACK; return ruleStack[ruleStack.length - 1]; }; TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () { var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 2]; return this.RULE_STACK[lastExplicitIndex]; }; TreeBuilder.prototype.getPreviousExplicitRuleShortNameNoCst = function () { var ruleStack = this.RULE_STACK; return ruleStack[ruleStack.length - 2]; }; TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () { var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1]; return this.RULE_OCCURRENCE_STACK[lastExplicitIndex]; }; TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndexNoCst = function () { var occurrenceStack = this.RULE_OCCURRENCE_STACK; return occurrenceStack[occurrenceStack.length - 1]; }; TreeBuilder.prototype.nestedRuleInvocationStateUpdate = function (nestedRuleName, shortNameKey) { this.RULE_OCCURRENCE_STACK.push(1); this.RULE_STACK.push(shortNameKey); this.cstNestedInvocationStateUpdate(nestedRuleName, shortNameKey); }; TreeBuilder.prototype.nestedRuleFinallyStateUpdate = function () { this.RULE_STACK.pop(); this.RULE_OCCURRENCE_STACK.pop(); // NOOP when cst is disabled this.cstNestedFinallyStateUpdate(); }; return TreeBuilder; }()); //# sourceMappingURL=tree_builder.js.map /***/ }), /* 45 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CstVisitorDefinitionError: () => (/* binding */ CstVisitorDefinitionError), /* harmony export */ createBaseSemanticVisitorConstructor: () => (/* binding */ createBaseSemanticVisitorConstructor), /* harmony export */ createBaseVisitorConstructorWithDefaults: () => (/* binding */ createBaseVisitorConstructorWithDefaults), /* harmony export */ defaultVisit: () => (/* binding */ defaultVisit), /* harmony export */ validateMissingCstMethods: () => (/* binding */ validateMissingCstMethods), /* harmony export */ validateRedundantMethods: () => (/* binding */ validateRedundantMethods), /* harmony export */ validateVisitor: () => (/* binding */ validateVisitor) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46); /* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36); function defaultVisit(ctx, param) { var childrenNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.keys)(ctx); var childrenNamesLength = childrenNames.length; for (var i = 0; i < childrenNamesLength; i++) { var currChildName = childrenNames[i]; var currChildArray = ctx[currChildName]; var currChildArrayLength = currChildArray.length; for (var j = 0; j < currChildArrayLength; j++) { var currChild = currChildArray[j]; // distinction between Tokens Children and CstNode children if (currChild.tokenTypeIdx === undefined) { if (currChild.fullName !== undefined) { this[currChild.fullName](currChild.children, param); } else { this[currChild.name](currChild.children, param); } } } } // defaultVisit does not support generic out param return undefined; } function createBaseSemanticVisitorConstructor(grammarName, ruleNames) { var derivedConstructor = function () { }; // can be overwritten according to: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.defineNameProp)(derivedConstructor, grammarName + "BaseSemantics"); var semanticProto = { visit: function (cstNode, param) { // enables writing more concise visitor methods when CstNode has only a single child if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(cstNode)) { // A CST Node's children dictionary can never have empty arrays as values // If a key is defined there will be at least one element in the corresponding value array. cstNode = cstNode[0]; } // enables passing optional CstNodes concisely. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(cstNode)) { return undefined; } if (cstNode.fullName !== undefined) { return this[cstNode.fullName](cstNode.children, param); } else { return this[cstNode.name](cstNode.children, param); } }, validateVisitor: function () { var semanticDefinitionErrors = validateVisitor(this, ruleNames); if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(semanticDefinitionErrors)) { var errorMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; }); throw Error("Errors Detected in CST Visitor <" + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(this.constructor) + ">:\n\t" + ("" + errorMessages.join("\n\n").replace(/\n/g, "\n\t"))); } } }; derivedConstructor.prototype = semanticProto; derivedConstructor.prototype.constructor = derivedConstructor; derivedConstructor._RULE_NAMES = ruleNames; return derivedConstructor; } function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) { var derivedConstructor = function () { }; // can be overwritten according to: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/ // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.defineNameProp)(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); var withDefaultsProto = Object.create(baseConstructor.prototype); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(ruleNames, function (ruleName) { withDefaultsProto[ruleName] = defaultVisit; }); derivedConstructor.prototype = withDefaultsProto; derivedConstructor.prototype.constructor = derivedConstructor; return derivedConstructor; } var CstVisitorDefinitionError; (function (CstVisitorDefinitionError) { CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD"; CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD"; })(CstVisitorDefinitionError || (CstVisitorDefinitionError = {})); function validateVisitor(visitorInstance, ruleNames) { var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames); var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames); return missingErrors.concat(redundantErrors); } function validateMissingCstMethods(visitorInstance, ruleNames) { var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(ruleNames, function (currRuleName) { if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(visitorInstance[currRuleName])) { return { msg: "Missing visitor method: <" + currRuleName + "> on " + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(visitorInstance.constructor) + " CST Visitor.", type: CstVisitorDefinitionError.MISSING_METHOD, methodName: currRuleName }; } }); return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact)(errors); } var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"]; function validateRedundantMethods(visitorInstance, ruleNames) { var errors = []; for (var prop in visitorInstance) { if (_grammar_checks__WEBPACK_IMPORTED_MODULE_2__.validTermsPattern.test(prop) && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(visitorInstance[prop]) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(VALID_PROP_NAMES, prop) && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(ruleNames, prop)) { errors.push({ msg: "Redundant visitor method: <" + prop + "> on " + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(visitorInstance.constructor) + " CST Visitor\n" + "There is no Grammar Rule corresponding to this method's name.\n" + ("For utility methods on visitor classes use methods names that do not match /" + _grammar_checks__WEBPACK_IMPORTED_MODULE_2__.validTermsPattern.source + "/."), type: CstVisitorDefinitionError.REDUNDANT_METHOD, methodName: prop }); } } return errors; } //# sourceMappingURL=cst_visitor.js.map /***/ }), /* 46 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ classNameFromInstance: () => (/* binding */ classNameFromInstance), /* harmony export */ defineNameProp: () => (/* binding */ defineNameProp), /* harmony export */ functionName: () => (/* binding */ functionName) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); function classNameFromInstance(instance) { return functionName(instance.constructor); } var FUNC_NAME_REGEXP = /^\s*function\s*(\S*)\s*\(/; var NAME = "name"; /* istanbul ignore next too many hacks for IE/old versions of node.js here*/ function functionName(func) { // Engines that support Function.prototype.name OR the nth (n>1) time after // the name has been computed in the following else block. var existingNameProp = func.name; if (existingNameProp) { return existingNameProp; } // hack for IE and engines that do not support Object.defineProperty on function.name (Node.js 0.10 && 0.12) var computedName = func.toString().match(FUNC_NAME_REGEXP)[1]; return computedName; } /** * @returns {boolean} - has the property been successfully defined */ function defineNameProp(obj, nameValue) { var namePropDescriptor = Object.getOwnPropertyDescriptor(obj, NAME); /* istanbul ignore else -> will only run in old versions of node.js */ if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(namePropDescriptor) || namePropDescriptor.configurable) { Object.defineProperty(obj, NAME, { enumerable: false, configurable: true, writable: false, value: nameValue }); return true; } /* istanbul ignore next -> will only run in old versions of node.js */ return false; } //# sourceMappingURL=lang_extensions.js.map /***/ }), /* 47 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LexerAdapter: () => (/* binding */ LexerAdapter) /* harmony export */ }); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); /** * Trait responsible abstracting over the interaction with Lexer output (Token vector). * * This could be generalized to support other kinds of lexers, e.g. * - Just in Time Lexing / Lexer-Less parsing. * - Streaming Lexer. */ var LexerAdapter = /** @class */ (function () { function LexerAdapter() { } LexerAdapter.prototype.initLexerAdapter = function () { this.tokVector = []; this.tokVectorLength = 0; this.currIdx = -1; }; Object.defineProperty(LexerAdapter.prototype, "input", { get: function () { return this.tokVector; }, set: function (newInput) { if (this.selfAnalysisDone !== true) { throw Error("Missing invocation at the end of the Parser's constructor."); } this.reset(); this.tokVector = newInput; this.tokVectorLength = newInput.length; }, enumerable: true, configurable: true }); // skips a token and returns the next token LexerAdapter.prototype.SKIP_TOKEN = function () { if (this.currIdx <= this.tokVector.length - 2) { this.consumeToken(); return this.LA(1); } else { return _parser__WEBPACK_IMPORTED_MODULE_0__.END_OF_FILE; } }; // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers // or lexers dependent on parser context. LexerAdapter.prototype.LA = function (howMuch) { var soughtIdx = this.currIdx + howMuch; if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) { return _parser__WEBPACK_IMPORTED_MODULE_0__.END_OF_FILE; } else { return this.tokVector[soughtIdx]; } }; LexerAdapter.prototype.consumeToken = function () { this.currIdx++; }; LexerAdapter.prototype.exportLexerState = function () { return this.currIdx; }; LexerAdapter.prototype.importLexerState = function (newState) { this.currIdx = newState; }; LexerAdapter.prototype.resetLexerState = function () { this.currIdx = -1; }; LexerAdapter.prototype.moveToTerminatedState = function () { this.currIdx = this.tokVector.length - 1; }; LexerAdapter.prototype.getLexerPosition = function () { return this.exportLexerState(); }; return LexerAdapter; }()); //# sourceMappingURL=lexer_adapter.js.map /***/ }), /* 48 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RecognizerApi: () => (/* binding */ RecognizerApi) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16); /* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35); /* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(36); /* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(20); /** * This trait is responsible for implementing the public API * for defining Chevrotain parsers, i.e: * - CONSUME * - RULE * - OPTION * - ... */ var RecognizerApi = /** @class */ (function () { function RecognizerApi() { } RecognizerApi.prototype.ACTION = function (impl) { return impl.call(this); }; RecognizerApi.prototype.consume = function (idx, tokType, options) { return this.consumeInternal(tokType, idx, options); }; RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) { return this.subruleInternal(ruleToCall, idx, options); }; RecognizerApi.prototype.option = function (idx, actionORMethodDef) { return this.optionInternal(actionORMethodDef, idx); }; RecognizerApi.prototype.or = function (idx, altsOrOpts) { return this.orInternal(altsOrOpts, idx); }; RecognizerApi.prototype.many = function (idx, actionORMethodDef) { return this.manyInternal(idx, actionORMethodDef); }; RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) { return this.atLeastOneInternal(idx, actionORMethodDef); }; RecognizerApi.prototype.CONSUME = function (tokType, options) { return this.consumeInternal(tokType, 0, options); }; RecognizerApi.prototype.CONSUME1 = function (tokType, options) { return this.consumeInternal(tokType, 1, options); }; RecognizerApi.prototype.CONSUME2 = function (tokType, options) { return this.consumeInternal(tokType, 2, options); }; RecognizerApi.prototype.CONSUME3 = function (tokType, options) { return this.consumeInternal(tokType, 3, options); }; RecognizerApi.prototype.CONSUME4 = function (tokType, options) { return this.consumeInternal(tokType, 4, options); }; RecognizerApi.prototype.CONSUME5 = function (tokType, options) { return this.consumeInternal(tokType, 5, options); }; RecognizerApi.prototype.CONSUME6 = function (tokType, options) { return this.consumeInternal(tokType, 6, options); }; RecognizerApi.prototype.CONSUME7 = function (tokType, options) { return this.consumeInternal(tokType, 7, options); }; RecognizerApi.prototype.CONSUME8 = function (tokType, options) { return this.consumeInternal(tokType, 8, options); }; RecognizerApi.prototype.CONSUME9 = function (tokType, options) { return this.consumeInternal(tokType, 9, options); }; RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 0, options); }; RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 1, options); }; RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 2, options); }; RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 3, options); }; RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 4, options); }; RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 5, options); }; RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 6, options); }; RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 7, options); }; RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 8, options); }; RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) { return this.subruleInternal(ruleToCall, 9, options); }; RecognizerApi.prototype.OPTION = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 0); }; RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 1); }; RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 2); }; RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 3); }; RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 4); }; RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 5); }; RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 6); }; RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 7); }; RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 8); }; RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) { return this.optionInternal(actionORMethodDef, 9); }; RecognizerApi.prototype.OR = function (altsOrOpts) { return this.orInternal(altsOrOpts, 0); }; RecognizerApi.prototype.OR1 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 1); }; RecognizerApi.prototype.OR2 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 2); }; RecognizerApi.prototype.OR3 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 3); }; RecognizerApi.prototype.OR4 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 4); }; RecognizerApi.prototype.OR5 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 5); }; RecognizerApi.prototype.OR6 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 6); }; RecognizerApi.prototype.OR7 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 7); }; RecognizerApi.prototype.OR8 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 8); }; RecognizerApi.prototype.OR9 = function (altsOrOpts) { return this.orInternal(altsOrOpts, 9); }; RecognizerApi.prototype.MANY = function (actionORMethodDef) { this.manyInternal(0, actionORMethodDef); }; RecognizerApi.prototype.MANY1 = function (actionORMethodDef) { this.manyInternal(1, actionORMethodDef); }; RecognizerApi.prototype.MANY2 = function (actionORMethodDef) { this.manyInternal(2, actionORMethodDef); }; RecognizerApi.prototype.MANY3 = function (actionORMethodDef) { this.manyInternal(3, actionORMethodDef); }; RecognizerApi.prototype.MANY4 = function (actionORMethodDef) { this.manyInternal(4, actionORMethodDef); }; RecognizerApi.prototype.MANY5 = function (actionORMethodDef) { this.manyInternal(5, actionORMethodDef); }; RecognizerApi.prototype.MANY6 = function (actionORMethodDef) { this.manyInternal(6, actionORMethodDef); }; RecognizerApi.prototype.MANY7 = function (actionORMethodDef) { this.manyInternal(7, actionORMethodDef); }; RecognizerApi.prototype.MANY8 = function (actionORMethodDef) { this.manyInternal(8, actionORMethodDef); }; RecognizerApi.prototype.MANY9 = function (actionORMethodDef) { this.manyInternal(9, actionORMethodDef); }; RecognizerApi.prototype.MANY_SEP = function (options) { this.manySepFirstInternal(0, options); }; RecognizerApi.prototype.MANY_SEP1 = function (options) { this.manySepFirstInternal(1, options); }; RecognizerApi.prototype.MANY_SEP2 = function (options) { this.manySepFirstInternal(2, options); }; RecognizerApi.prototype.MANY_SEP3 = function (options) { this.manySepFirstInternal(3, options); }; RecognizerApi.prototype.MANY_SEP4 = function (options) { this.manySepFirstInternal(4, options); }; RecognizerApi.prototype.MANY_SEP5 = function (options) { this.manySepFirstInternal(5, options); }; RecognizerApi.prototype.MANY_SEP6 = function (options) { this.manySepFirstInternal(6, options); }; RecognizerApi.prototype.MANY_SEP7 = function (options) { this.manySepFirstInternal(7, options); }; RecognizerApi.prototype.MANY_SEP8 = function (options) { this.manySepFirstInternal(8, options); }; RecognizerApi.prototype.MANY_SEP9 = function (options) { this.manySepFirstInternal(9, options); }; RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) { this.atLeastOneInternal(0, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) { return this.atLeastOneInternal(1, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) { this.atLeastOneInternal(2, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) { this.atLeastOneInternal(3, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) { this.atLeastOneInternal(4, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) { this.atLeastOneInternal(5, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) { this.atLeastOneInternal(6, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) { this.atLeastOneInternal(7, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) { this.atLeastOneInternal(8, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) { this.atLeastOneInternal(9, actionORMethodDef); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) { this.atLeastOneSepFirstInternal(0, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) { this.atLeastOneSepFirstInternal(1, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) { this.atLeastOneSepFirstInternal(2, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) { this.atLeastOneSepFirstInternal(3, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) { this.atLeastOneSepFirstInternal(4, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) { this.atLeastOneSepFirstInternal(5, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) { this.atLeastOneSepFirstInternal(6, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) { this.atLeastOneSepFirstInternal(7, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) { this.atLeastOneSepFirstInternal(8, options); }; RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) { this.atLeastOneSepFirstInternal(9, options); }; RecognizerApi.prototype.RULE = function (name, implementation, config) { if (config === void 0) { config = _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_RULE_CONFIG; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(this.definedRulesNames, name)) { var errMsg = _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: name, grammarName: this.className }); var error = { message: errMsg, type: _parser__WEBPACK_IMPORTED_MODULE_2__.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: name }; this.definitionErrors.push(error); } this.definedRulesNames.push(name); var ruleImplementation = this.defineRule(name, implementation, config); this[name] = ruleImplementation; return ruleImplementation; }; RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) { if (config === void 0) { config = _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_RULE_CONFIG; } var ruleErrors = []; ruleErrors = ruleErrors.concat((0,_grammar_checks__WEBPACK_IMPORTED_MODULE_4__.validateRuleIsOverridden)(name, this.definedRulesNames, this.className)); this.definitionErrors.push.apply(this.definitionErrors, ruleErrors); // mutability for the win var ruleImplementation = this.defineRule(name, impl, config); this[name] = ruleImplementation; return ruleImplementation; }; RecognizerApi.prototype.BACKTRACK = function (grammarRule, args) { return function () { // save org state this.isBackTrackingStack.push(1); var orgState = this.saveRecogState(); try { grammarRule.apply(this, args); // if no exception was thrown we have succeed parsing the rule. return true; } catch (e) { if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_1__.isRecognitionException)(e)) { return false; } else { throw e; } } finally { this.reloadRecogState(orgState); this.isBackTrackingStack.pop(); } }; }; // GAST export APIs RecognizerApi.prototype.getGAstProductions = function () { return this.gastProductionsCache; }; RecognizerApi.prototype.getSerializedGastProductions = function () { return (0,_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_5__.serializeGrammar)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(this.gastProductionsCache)); }; return RecognizerApi; }()); //# sourceMappingURL=recognizer_api.js.map /***/ }), /* 49 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RecognizerEngine: () => (/* binding */ RecognizerEngine) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34); /* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42); /* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37); /* harmony import */ var _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16); /* harmony import */ var _recoverable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(21); /* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(27); /* harmony import */ var _lang_lang_extensions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(46); /** * This trait is responsible for the runtime parsing engine * Used by the official API (recognizer_api.ts) */ var RecognizerEngine = /** @class */ (function () { function RecognizerEngine() { } RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) { this.className = (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_9__.classNameFromInstance)(this); // TODO: would using an ES6 Map or plain object be faster (CST building scenario) this.shortRuleNameToFull = {}; this.fullRuleNameToShort = {}; this.ruleShortNameIdx = 256; this.tokenMatcher = _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcherNoCategories; this.definedRulesNames = []; this.tokensMap = {}; this.allRuleNames = []; this.isBackTrackingStack = []; this.RULE_STACK = []; this.RULE_OCCURRENCE_STACK = []; this.gastProductionsCache = {}; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "serializedGrammar")) { throw Error("The Parser's configuration can no longer contain a property.\n" + "\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" + "\tFor Further details."); } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(tokenVocabulary)) { // This only checks for Token vocabularies provided as arrays. // That is good enough because the main objective is to detect users of pre-V4.0 APIs // rather than all edge cases of empty Token vocabularies. if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(tokenVocabulary)) { throw Error("A Token Vocabulary cannot be empty.\n" + "\tNote that the first argument for the parser constructor\n" + "\tis no longer a Token vector (since v4.0)."); } if (typeof tokenVocabulary[0].startOffset === "number") { throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n" + "\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_4-0-0\n" + "\tFor Further details."); } } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(tokenVocabulary)) { this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(tokenVocabulary, function (acc, tokType) { acc[tokType.name] = tokType; return acc; }, {}); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokenVocabulary, "modes") && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary.modes)), _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.isTokenType)) { var allTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary.modes)); var uniqueTokens = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)(allTokenTypes); this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(uniqueTokens, function (acc, tokType) { acc[tokType.name] = tokType; return acc; }, {}); } else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isObject)(tokenVocabulary)) { this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(tokenVocabulary); } else { throw new Error(" argument must be An Array of Token constructors," + " A dictionary of Token constructors or an IMultiModeLexerDefinition"); } // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been // parsed with a clear error message ("expecting EOF but found ...") /* tslint:disable */ this.tokensMap["EOF"] = _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__.EOF; // TODO: This check may not be accurate for multi mode lexers var noTokenCategoriesUsed = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary), function (tokenConstructor) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(tokenConstructor.categoryMatches); }); this.tokenMatcher = noTokenCategoriesUsed ? _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcherNoCategories : _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcher; // Because ES2015+ syntax should be supported for creating Token classes // We cannot assume that the Token classes were created using the "extendToken" utilities // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization (0,_scan_tokens__WEBPACK_IMPORTED_MODULE_8__.augmentTokenTypes)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(this.tokensMap)); }; RecognizerEngine.prototype.defineRule = function (ruleName, impl, config) { if (this.selfAnalysisDone) { throw Error("Grammar rule <" + ruleName + "> may not be defined after the 'performSelfAnalysis' method has been called'\n" + "Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called."); } var resyncEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "resyncEnabled") ? config.resyncEnabled : _parser__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_RULE_CONFIG.resyncEnabled; var recoveryValueFunc = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "recoveryValueFunc") ? config.recoveryValueFunc : _parser__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_RULE_CONFIG.recoveryValueFunc; // performance optimization: Use small integers as keys for the longer human readable "full" rule names. // this greatly improves Map access time (as much as 8% for some performance benchmarks). /* tslint:disable */ var shortName = this.ruleShortNameIdx << (_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.BITS_FOR_METHOD_TYPE + _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.BITS_FOR_OCCURRENCE_IDX); /* tslint:enable */ this.ruleShortNameIdx++; this.shortRuleNameToFull[shortName] = ruleName; this.fullRuleNameToShort[ruleName] = shortName; function invokeRuleWithTry(args) { try { if (this.outputCst === true) { impl.apply(this, args); var cst = this.CST_STACK[this.CST_STACK.length - 1]; this.cstPostRule(cst); return cst; } else { return impl.apply(this, args); } } catch (e) { return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc); } finally { this.ruleFinallyStateUpdate(); } } var wrappedGrammarRule; wrappedGrammarRule = function (idxInCallingRule, args) { if (idxInCallingRule === void 0) { idxInCallingRule = 0; } this.ruleInvocationStateUpdate(shortName, ruleName, idxInCallingRule); return invokeRuleWithTry.call(this, args); }; var ruleNamePropName = "ruleName"; wrappedGrammarRule[ruleNamePropName] = ruleName; wrappedGrammarRule["originalGrammarAction"] = impl; return wrappedGrammarRule; }; RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) { var isFirstInvokedRule = this.RULE_STACK.length === 1; // note the reSync is always enabled for the first rule invocation, because we must always be able to // reSync with EOF and just output some INVALID ParseTree // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking // path is really the most valid one var reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled; if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_2__.isRecognitionException)(e)) { var recogError = e; if (reSyncEnabled) { var reSyncTokType = this.findReSyncTokenType(); if (this.isInCurrentRuleReSyncSet(reSyncTokType)) { recogError.resyncedTokens = this.reSyncTo(reSyncTokType); if (this.outputCst) { var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; partialCstResult.recoveredNode = true; return partialCstResult; } else { return recoveryValueFunc(); } } else { if (this.outputCst) { var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1]; partialCstResult.recoveredNode = true; recogError.partialCstResult = partialCstResult; } // to be handled Further up the call stack throw recogError; } } else if (isFirstInvokedRule) { // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case this.moveToTerminatedState(); // the parser should never throw one of its own errors outside its flow. // even if error recovery is disabled return recoveryValueFunc(); } else { // to be recovered Further up the call stack throw recogError; } } else { // some other Error type which we don't know how to handle (for example a built in JavaScript Error) throw e; } }; // Implementation of parsing DSL RecognizerEngine.prototype.optionInternal = function (actionORMethodDef, occurrence) { var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX, occurrence); var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, key); try { return this.optionInternalLogic(actionORMethodDef, occurrence, key); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(key, nestedName); } } }; RecognizerEngine.prototype.optionInternalNoCst = function (actionORMethodDef, occurrence) { var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX, occurrence); return this.optionInternalLogic(actionORMethodDef, occurrence, key); }; RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) { var _this = this; var lookAheadFunc = this.getLaFuncFromCache(key); var action; var predicate; if (actionORMethodDef.DEF !== undefined) { action = actionORMethodDef.DEF; predicate = actionORMethodDef.GATE; // predicate present if (predicate !== undefined) { var orgLookaheadFunction_1 = lookAheadFunc; lookAheadFunc = function () { return (predicate.call(_this) && orgLookaheadFunction_1.call(_this)); }; } } else { action = actionORMethodDef; } if (lookAheadFunc.call(this) === true) { return action.call(this); } return undefined; }; RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence); var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey); try { return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(laKey, nestedName); } } }; RecognizerEngine.prototype.atLeastOneInternalNoCst = function (prodOccurrence, actionORMethodDef) { var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence); this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key); }; RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) { var _this = this; var lookAheadFunc = this.getLaFuncFromCache(key); var action; var predicate; if (actionORMethodDef.DEF !== undefined) { action = actionORMethodDef.DEF; predicate = actionORMethodDef.GATE; // predicate present if (predicate !== undefined) { var orgLookaheadFunction_2 = lookAheadFunc; lookAheadFunc = function () { return (predicate.call(_this) && orgLookaheadFunction_2.call(_this)); }; } } else { action = actionORMethodDef; } if (lookAheadFunc.call(this) === true) { var notStuck = this.doSingleRepetition(action); while (lookAheadFunc.call(this) === true && notStuck === true) { notStuck = this.doSingleRepetition(action); } } else { throw this.raiseEarlyExitException(prodOccurrence, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__.PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG); } // note that while it may seem that this can cause an error because by using a recursive call to // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items. // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneWalker); }; RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence); var nestedName = this.nestedRuleBeforeClause(options, laKey); try { this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(laKey, nestedName); } } }; RecognizerEngine.prototype.atLeastOneSepFirstInternalNoCst = function (prodOccurrence, options) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence); this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey); }; RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) { var _this = this; var action = options.DEF; var separator = options.SEP; var firstIterationLookaheadFunc = this.getLaFuncFromCache(key); // 1st iteration if (firstIterationLookaheadFunc.call(this) === true) { ; action.call(this); // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery" // because it is only needed in error recovery scenarios. var separatorLookAheadFunc = function () { return _this.tokenMatcher(_this.LA(1), separator); }; // 2nd..nth iterations while (this.tokenMatcher(this.LA(1), separator) === true) { // note that this CONSUME will never enter recovery because // the separatorLookAheadFunc checks that the separator really does exist. this.CONSUME(separator); action.call(this); } // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ prodOccurrence, separator, separatorLookAheadFunc, action, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneSepWalker ], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneSepWalker); } else { throw this.raiseEarlyExitException(prodOccurrence, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG); } }; RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence); var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey); try { return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(laKey, nestedName); } } }; RecognizerEngine.prototype.manyInternalNoCst = function (prodOccurrence, actionORMethodDef) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence); return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey); }; RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) { var _this = this; var lookaheadFunction = this.getLaFuncFromCache(key); var action; var predicate; if (actionORMethodDef.DEF !== undefined) { action = actionORMethodDef.DEF; predicate = actionORMethodDef.GATE; // predicate present if (predicate !== undefined) { var orgLookaheadFunction_3 = lookaheadFunction; lookaheadFunction = function () { return (predicate.call(_this) && orgLookaheadFunction_3.call(_this)); }; } } else { action = actionORMethodDef; } var notStuck = true; while (lookaheadFunction.call(this) === true && notStuck === true) { notStuck = this.doSingleRepetition(action); } // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManyWalker, // The notStuck parameter is only relevant when "attemptInRepetitionRecovery" // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP] // An infinite loop cannot occur as: // - Either the lookahead is guaranteed to consume something (Single Token Separator) // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out). notStuck); }; RecognizerEngine.prototype.manySepFirstInternal = function (prodOccurrence, options) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence); var nestedName = this.nestedRuleBeforeClause(options, laKey); try { this.manySepFirstInternalLogic(prodOccurrence, options, laKey); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(laKey, nestedName); } } }; RecognizerEngine.prototype.manySepFirstInternalNoCst = function (prodOccurrence, options) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence); this.manySepFirstInternalLogic(prodOccurrence, options, laKey); }; RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) { var _this = this; var action = options.DEF; var separator = options.SEP; var firstIterationLaFunc = this.getLaFuncFromCache(key); // 1st iteration if (firstIterationLaFunc.call(this) === true) { action.call(this); var separatorLookAheadFunc = function () { return _this.tokenMatcher(_this.LA(1), separator); }; // 2nd..nth iterations while (this.tokenMatcher(this.LA(1), separator) === true) { // note that this CONSUME will never enter recovery because // the separatorLookAheadFunc checks that the separator really does exist. this.CONSUME(separator); // No need for checking infinite loop here due to consuming the separator. action.call(this); } // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ prodOccurrence, separator, separatorLookAheadFunc, action, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManySepWalker ], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManySepWalker); } }; RecognizerEngine.prototype.repetitionSepSecondInternal = function (prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) { while (separatorLookAheadFunc()) { // note that this CONSUME will never enter recovery because // the separatorLookAheadFunc checks that the separator really does exist. this.CONSUME(separator); action.call(this); } // we can only arrive to this function after an error // has occurred (hence the name 'second') so the following // IF will always be entered, its possible to remove it... // however it is kept to avoid confusion and be consistent. // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled /* istanbul ignore else */ this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [ prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker ], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker); }; RecognizerEngine.prototype.doSingleRepetition = function (action) { var beforeIteration = this.getLexerPosition(); action.call(this); var afterIteration = this.getLexerPosition(); // This boolean will indicate if this repetition progressed // or if we are "stuck" (potential infinite loop in the repetition). return afterIteration > beforeIteration; }; RecognizerEngine.prototype.orInternalNoCst = function (altsOrOpts, occurrence) { var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, occurrence); var laFunc = this.getLaFuncFromCache(laKey); var altIdxToTake = laFunc.call(this, alts); if (altIdxToTake !== undefined) { var chosenAlternative = alts[altIdxToTake]; return chosenAlternative.ALT.call(this); } this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); }; RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) { var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, occurrence); var nestedName = this.nestedRuleBeforeClause(altsOrOpts, laKey); try { var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF; var laFunc = this.getLaFuncFromCache(laKey); var altIdxToTake = laFunc.call(this, alts); if (altIdxToTake !== undefined) { var chosenAlternative = alts[altIdxToTake]; var nestedAltBeforeClauseResult = this.nestedAltBeforeClause(chosenAlternative, occurrence, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, altIdxToTake); try { return chosenAlternative.ALT.call(this); } finally { if (nestedAltBeforeClauseResult !== undefined) { this.nestedRuleFinallyClause(nestedAltBeforeClauseResult.shortName, nestedAltBeforeClauseResult.nestedName); } } } this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG); } finally { if (nestedName !== undefined) { this.nestedRuleFinallyClause(laKey, nestedName); } } }; RecognizerEngine.prototype.ruleFinallyStateUpdate = function () { this.RULE_STACK.pop(); this.RULE_OCCURRENCE_STACK.pop(); // NOOP when cst is disabled this.cstFinallyStateUpdate(); if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { var firstRedundantTok = this.LA(1); var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: firstRedundantTok, ruleName: this.getCurrRuleFullName() }); this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.NotAllInputParsedException(errMsg, firstRedundantTok)); } }; RecognizerEngine.prototype.subruleInternal = function (ruleToCall, idx, options) { var ruleResult; try { var args = options !== undefined ? options.ARGS : undefined; ruleResult = ruleToCall.call(this, idx, args); this.cstPostNonTerminal(ruleResult, options !== undefined && options.LABEL !== undefined ? options.LABEL : ruleToCall.ruleName); return ruleResult; } catch (e) { this.subruleInternalError(e, options, ruleToCall.ruleName); } }; RecognizerEngine.prototype.subruleInternalError = function (e, options, ruleName) { if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_2__.isRecognitionException)(e) && e.partialCstResult !== undefined) { this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined ? options.LABEL : ruleName); delete e.partialCstResult; } throw e; }; RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) { var consumedToken; try { var nextToken = this.LA(1); if (this.tokenMatcher(nextToken, tokType) === true) { this.consumeToken(); consumedToken = nextToken; } else { this.consumeInternalError(tokType, nextToken, options); } } catch (eFromConsumption) { consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption); } this.cstPostTerminal(options !== undefined && options.LABEL !== undefined ? options.LABEL : tokType.name, consumedToken); return consumedToken; }; RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) { var msg; var previousToken = this.LA(0); if (options !== undefined && options.ERR_MSG) { msg = options.ERR_MSG; } else { msg = this.errorMessageProvider.buildMismatchTokenMessage({ expected: tokType, actual: nextToken, previous: previousToken, ruleName: this.getCurrRuleFullName() }); } throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.MismatchedTokenException(msg, nextToken, previousToken)); }; RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) { // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it // but the original syntax could have been parsed successfully without any backtracking + recovery if (this.recoveryEnabled && // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions? eFromConsumption.name === "MismatchedTokenException" && !this.isBackTracking()) { var follows = this.getFollowsForInRuleRecovery(tokType, idx); try { return this.tryInRuleRecovery(tokType, follows); } catch (eFromInRuleRecovery) { if (eFromInRuleRecovery.name === _recoverable__WEBPACK_IMPORTED_MODULE_6__.IN_RULE_RECOVERY_EXCEPTION) { // failed in RuleRecovery. // throw the original error in order to trigger reSync error recovery throw eFromConsumption; } else { throw eFromInRuleRecovery; } } } else { throw eFromConsumption; } }; RecognizerEngine.prototype.saveRecogState = function () { // errors is a getter which will clone the errors array var savedErrors = this.errors; var savedRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr)(this.RULE_STACK); return { errors: savedErrors, lexerState: this.exportLexerState(), RULE_STACK: savedRuleStack, CST_STACK: this.CST_STACK, LAST_EXPLICIT_RULE_STACK: this.LAST_EXPLICIT_RULE_STACK }; }; RecognizerEngine.prototype.reloadRecogState = function (newState) { this.errors = newState.errors; this.importLexerState(newState.lexerState); this.RULE_STACK = newState.RULE_STACK; }; RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) { this.RULE_OCCURRENCE_STACK.push(idxInCallingRule); this.RULE_STACK.push(shortName); // NOOP when cst is disabled this.cstInvocationStateUpdate(fullName, shortName); }; RecognizerEngine.prototype.isBackTracking = function () { return this.isBackTrackingStack.length !== 0; }; RecognizerEngine.prototype.getCurrRuleFullName = function () { var shortName = this.getLastExplicitRuleShortName(); return this.shortRuleNameToFull[shortName]; }; RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) { return this.shortRuleNameToFull[shortName]; }; RecognizerEngine.prototype.isAtEndOfInput = function () { return this.tokenMatcher(this.LA(1), _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__.EOF); }; RecognizerEngine.prototype.reset = function () { this.resetLexerState(); this.isBackTrackingStack = []; this.errors = []; this.RULE_STACK = []; this.LAST_EXPLICIT_RULE_STACK = []; // TODO: extract a specific rest for TreeBuilder trait this.CST_STACK = []; this.RULE_OCCURRENCE_STACK = []; }; return RecognizerEngine; }()); //# sourceMappingURL=recognizer_engine.js.map /***/ }), /* 50 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ErrorHandler: () => (/* binding */ ErrorHandler) /* harmony export */ }); /* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(42); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(37); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); /** * Trait responsible for runtime parsing errors. */ var ErrorHandler = /** @class */ (function () { function ErrorHandler() { } ErrorHandler.prototype.initErrorHandler = function (config) { this._errors = []; this.errorMessageProvider = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.defaults)(config.errorMessageProvider, _parser__WEBPACK_IMPORTED_MODULE_3__.DEFAULT_PARSER_CONFIG.errorMessageProvider); }; ErrorHandler.prototype.SAVE_ERROR = function (error) { if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_0__.isRecognitionException)(error)) { error.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.RULE_OCCURRENCE_STACK) }; this._errors.push(error); return error; } else { throw Error("Trying to save an Error which is not a RecognitionException"); } }; Object.defineProperty(ErrorHandler.prototype, "errors", { // TODO: extract these methods to ErrorHandler Trait? get: function () { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this._errors); }, set: function (newErrors) { this._errors = newErrors; }, enumerable: true, configurable: true }); // TODO: consider caching the error message computed information ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) { var ruleName = this.getCurrRuleFullName(); var ruleGrammar = this.getGAstProductions()[ruleName]; var lookAheadPathsPerAlternative = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__.getLookaheadPathsForOptionalProd)(occurrence, ruleGrammar, prodType, this.maxLookahead); var insideProdPaths = lookAheadPathsPerAlternative[0]; var actualTokens = []; for (var i = 1; i <= this.maxLookahead; i++) { actualTokens.push(this.LA(i)); } var msg = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: insideProdPaths, actual: actualTokens, previous: this.LA(0), customUserDescription: userDefinedErrMsg, ruleName: ruleName }); throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_0__.EarlyExitException(msg, this.LA(1), this.LA(0))); }; // TODO: consider caching the error message computed information ErrorHandler.prototype.raiseNoAltException = function (occurrence, errMsgTypes) { var ruleName = this.getCurrRuleFullName(); var ruleGrammar = this.getGAstProductions()[ruleName]; // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ? var lookAheadPathsPerAlternative = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__.getLookaheadPathsForOr)(occurrence, ruleGrammar, this.maxLookahead); var actualTokens = []; for (var i = 1; i <= this.maxLookahead; i++) { actualTokens.push(this.LA(i)); } var previousToken = this.LA(0); var errMsg = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: lookAheadPathsPerAlternative, actual: actualTokens, previous: previousToken, customUserDescription: errMsgTypes, ruleName: this.getCurrRuleFullName() }); throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_0__.NoViableAltException(errMsg, this.LA(1), previousToken)); }; return ErrorHandler; }()); //# sourceMappingURL=error_handler.js.map /***/ }), /* 51 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ContentAssist: () => (/* binding */ ContentAssist) /* harmony export */ }); /* harmony import */ var _grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(38); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); var ContentAssist = /** @class */ (function () { function ContentAssist() { } ContentAssist.prototype.initContentAssist = function () { }; ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) { var startRuleGast = this.gastProductionsCache[startRuleName]; if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(startRuleGast)) { throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar."); } return (0,_grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__.nextPossibleTokensAfter)([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead); }; // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'... // TODO: should this be more explicitly part of the public API? ContentAssist.prototype.getNextPossibleTokenTypes = function (grammarPath) { var topRuleName = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(grammarPath.ruleStack); var gastProductions = this.getGAstProductions(); var topProduction = gastProductions[topRuleName]; var nextPossibleTokenTypes = new _grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__.NextAfterTokenWalker(topProduction, grammarPath).startWalking(); return nextPossibleTokenTypes; }; return ContentAssist; }()); //# sourceMappingURL=context_assist.js.map /***/ }), /* 52 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ GastRecorder: () => (/* binding */ GastRecorder) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); /* harmony import */ var _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22); /* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27); /* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16); /* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(34); var RECORDING_NULL_OBJECT = { description: "This Object indicates the Parser is during Recording Phase" }; Object.freeze(RECORDING_NULL_OBJECT); var HANDLE_SEPARATOR = true; var MAX_METHOD_IDX = Math.pow(2, _grammar_keys__WEBPACK_IMPORTED_MODULE_6__.BITS_FOR_OCCURRENCE_IDX) - 1; var RFT = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__.createToken)({ name: "RECORDING_PHASE_TOKEN", pattern: _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.Lexer.NA }); (0,_scan_tokens__WEBPACK_IMPORTED_MODULE_3__.augmentTokenTypes)([RFT]); var RECORDING_PHASE_TOKEN = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__.createTokenInstance)(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" + "" + "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details", // Using "-1" instead of NaN (as in EOF) because an actual number is less likely to // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase. -1, -1, -1, -1, -1, -1); Object.freeze(RECORDING_PHASE_TOKEN); var RECORDING_PHASE_CSTNODE = { name: "This CSTNode indicates the Parser is in Recording Phase\n\t" + "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details", children: {} }; /** * This trait handles the creation of the GAST structure for Chevrotain Grammars */ var GastRecorder = /** @class */ (function () { function GastRecorder() { } GastRecorder.prototype.initGastRecorder = function (config) { this.recordingProdStack = []; this.RECORDING_PHASE = false; }; GastRecorder.prototype.enableRecording = function () { var _this = this; this.RECORDING_PHASE = true; this.TRACE_INIT("Enable Recording", function () { var _loop_1 = function (i) { var idx = i > 0 ? i : ""; _this["CONSUME" + idx] = function (arg1, arg2) { return this.consumeInternalRecord(arg1, i, arg2); }; _this["SUBRULE" + idx] = function (arg1, arg2) { return this.subruleInternalRecord(arg1, i, arg2); }; _this["OPTION" + idx] = function (arg1) { return this.optionInternalRecord(arg1, i); }; _this["OR" + idx] = function (arg1) { return this.orInternalRecord(arg1, i); }; _this["MANY" + idx] = function (arg1) { this.manyInternalRecord(i, arg1); }; _this["MANY_SEP" + idx] = function (arg1) { this.manySepFirstInternalRecord(i, arg1); }; _this["AT_LEAST_ONE" + idx] = function (arg1) { this.atLeastOneInternalRecord(i, arg1); }; _this["AT_LEAST_ONE_SEP" + idx] = function (arg1) { this.atLeastOneSepFirstInternalRecord(i, arg1); }; }; /** * Warning Dark Voodoo Magic upcoming! * We are "replacing" the public parsing DSL methods API * With **new** alternative implementations on the Parser **instance** * * So far this is the only way I've found to avoid performance regressions during parsing time. * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal" * implementations directly instead. */ for (var i = 0; i < 10; i++) { _loop_1(i); } // DSL methods with the idx(suffix) as an argument _this["consume"] = function (idx, arg1, arg2) { return this.consumeInternalRecord(arg1, idx, arg2); }; _this["subrule"] = function (idx, arg1, arg2) { return this.subruleInternalRecord(arg1, idx, arg2); }; _this["option"] = function (idx, arg1) { return this.optionInternalRecord(arg1, idx); }; _this["or"] = function (idx, arg1) { return this.orInternalRecord(arg1, idx); }; _this["many"] = function (idx, arg1) { this.manyInternalRecord(idx, arg1); }; _this["atLeastOne"] = function (idx, arg1) { this.atLeastOneInternalRecord(idx, arg1); }; _this.ACTION = _this.ACTION_RECORD; _this.BACKTRACK = _this.BACKTRACK_RECORD; _this.LA = _this.LA_RECORD; }); }; GastRecorder.prototype.disableRecording = function () { var _this = this; this.RECORDING_PHASE = false; // By deleting these **instance** properties, any future invocation // will be deferred to the original methods on the **prototype** object // This seems to get rid of any incorrect optimizations that V8 may // do during the recording phase. this.TRACE_INIT("Deleting Recording methods", function () { for (var i = 0; i < 10; i++) { var idx = i > 0 ? i : ""; delete _this["CONSUME" + idx]; delete _this["SUBRULE" + idx]; delete _this["OPTION" + idx]; delete _this["OR" + idx]; delete _this["MANY" + idx]; delete _this["MANY_SEP" + idx]; delete _this["AT_LEAST_ONE" + idx]; delete _this["AT_LEAST_ONE_SEP" + idx]; } delete _this["consume"]; delete _this["subrule"]; delete _this["option"]; delete _this["or"]; delete _this["many"]; delete _this["atLeastOne"]; delete _this.ACTION; delete _this.BACKTRACK; delete _this.LA; }); }; // TODO: is there any way to use this method to check no // Parser methods are called inside an ACTION? // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes? GastRecorder.prototype.ACTION_RECORD = function (impl) { // NO-OP during recording return; }; // Executing backtracking logic will break our recording logic assumptions GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) { return function () { return true; }; }; // LA is part of the official API and may be used for custom lookahead logic // by end users who may forget to wrap it in ACTION or inside a GATE GastRecorder.prototype.LA_RECORD = function (howMuch) { // We cannot use the RECORD_PHASE_TOKEN here because someone may depend // On LA return EOF at the end of the input so an infinite loop may occur. return _parser__WEBPACK_IMPORTED_MODULE_5__.END_OF_FILE; }; GastRecorder.prototype.topLevelRuleRecord = function (name, def) { try { var newTopLevelRule = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Rule({ definition: [], name: name }); newTopLevelRule.name = name; this.recordingProdStack.push(newTopLevelRule); def.call(this); this.recordingProdStack.pop(); return newTopLevelRule; } catch (originalError) { if (originalError.KNOWN_RECORDER_ERROR !== true) { try { originalError.message = originalError.message + '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' + "https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording"; } catch (mutabilityError) { // We may not be able to modify the original error object throw originalError; } } throw originalError; } }; // Implementation of parsing DSL GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) { return recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option, actionORMethodDef, occurrence); }; GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) { recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory, actionORMethodDef, occurrence); }; GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) { recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); }; GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) { recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition, actionORMethodDef, occurrence); }; GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) { recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR); }; GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) { return recordOrProd.call(this, altsOrOpts, occurrence); }; GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) { assertMethodIdxIsValid(occurrence); if (!ruleToCall || (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(ruleToCall, "ruleName") === false) { var error = new Error(" argument is invalid" + (" expecting a Parser method reference but got: <" + JSON.stringify(ruleToCall) + ">") + ("\n inside top level rule: <" + this.recordingProdStack[0].name + ">")); error.KNOWN_RECORDER_ERROR = true; throw error; } var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack); var ruleName = ruleToCall["ruleName"]; var newNoneTerminal = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal({ idx: occurrence, nonTerminalName: ruleName, // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created referencedRule: undefined }); prevProd.definition.push(newNoneTerminal); return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT; }; GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) { assertMethodIdxIsValid(occurrence); if (!(0,_scan_tokens__WEBPACK_IMPORTED_MODULE_3__.hasShortKeyProperty)(tokType)) { var error = new Error(" argument is invalid" + (" expecting a TokenType reference but got: <" + JSON.stringify(tokType) + ">") + ("\n inside top level rule: <" + this.recordingProdStack[0].name + ">")); error.KNOWN_RECORDER_ERROR = true; throw error; } var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack); var newNoneTerminal = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal({ idx: occurrence, terminalType: tokType }); prevProd.definition.push(newNoneTerminal); return RECORDING_PHASE_TOKEN; }; return GastRecorder; }()); function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) { if (handleSep === void 0) { handleSep = false; } assertMethodIdxIsValid(occurrence); var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack); var grammarAction = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(mainProdArg) ? mainProdArg : mainProdArg.DEF; var newProd = new prodConstructor({ definition: [], idx: occurrence }); if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "NAME")) { newProd.name = mainProdArg.NAME; } if (handleSep) { newProd.separator = mainProdArg.SEP; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "MAX_LOOKAHEAD")) { newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; } this.recordingProdStack.push(newProd); grammarAction.call(this); prevProd.definition.push(newProd); this.recordingProdStack.pop(); return RECORDING_NULL_OBJECT; } function recordOrProd(mainProdArg, occurrence) { var _this = this; assertMethodIdxIsValid(occurrence); var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack); // Only an array of alternatives var hasOptions = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(mainProdArg) === false; var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; var newOrProd = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation({ definition: [], idx: occurrence, ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true }); if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "NAME")) { newOrProd.name = mainProdArg.NAME; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "MAX_LOOKAHEAD")) { newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; } var hasPredicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.some)(alts, function (currAlt) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(currAlt.GATE); }); newOrProd.hasPredicates = hasPredicates; prevProd.definition.push(newOrProd); (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(alts, function (currAlt) { var currAltFlat = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat({ definition: [] }); newOrProd.definition.push(currAltFlat); if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "NAME")) { currAltFlat.name = currAlt.NAME; } if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "IGNORE_AMBIGUITIES")) { currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; } // **implicit** ignoreAmbiguities due to usage of gate else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "GATE")) { currAltFlat.ignoreAmbiguities = true; } _this.recordingProdStack.push(currAltFlat); currAlt.ALT.call(_this); _this.recordingProdStack.pop(); }); return RECORDING_NULL_OBJECT; } function getIdxSuffix(idx) { return idx === 0 ? "" : "" + idx; } function assertMethodIdxIsValid(idx) { if (idx < 0 || idx > MAX_METHOD_IDX) { var error = new Error( // The stack trace will contain all the needed details "Invalid DSL Method idx value: <" + idx + ">\n\t" + ("Idx value must be a none negative value smaller than " + (MAX_METHOD_IDX + 1))); error.KNOWN_RECORDER_ERROR = true; throw error; } } //# sourceMappingURL=gast_recorder.js.map /***/ }), /* 53 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ PerformanceTracer: () => (/* binding */ PerformanceTracer) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); /** * Trait responsible for runtime parsing errors. */ var PerformanceTracer = /** @class */ (function () { function PerformanceTracer() { } PerformanceTracer.prototype.initPerformanceTracer = function (config) { if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "traceInitPerf")) { var userTraceInitPerf = config.traceInitPerf; var traceIsNumber = typeof userTraceInitPerf === "number"; this.traceInitMaxIdent = traceIsNumber ? userTraceInitPerf : Infinity; this.traceInitPerf = traceIsNumber ? userTraceInitPerf > 0 : userTraceInitPerf; } else { this.traceInitMaxIdent = 0; this.traceInitPerf = _parser__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_PARSER_CONFIG.traceInitPerf; } this.traceInitIndent = -1; }; PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) { // No need to optimize this using NOOP pattern because // It is not called in a hot spot... if (this.traceInitPerf === true) { this.traceInitIndent++; var indent = new Array(this.traceInitIndent + 1).join("\t"); if (this.traceInitIndent < this.traceInitMaxIdent) { console.log(indent + "--> <" + phaseDesc + ">"); } var _a = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.timer)(phaseImpl), time = _a.time, value = _a.value; /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */ var traceMethod = time > 10 ? console.warn : console.log; if (this.traceInitIndent < this.traceInitMaxIdent) { traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms"); } this.traceInitIndent--; return value; } else { return phaseImpl(); } }; return PerformanceTracer; }()); //# sourceMappingURL=perf_tracer.js.map /***/ }), /* 54 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ createSyntaxDiagramsCode: () => (/* binding */ createSyntaxDiagramsCode) /* harmony export */ }); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); function createSyntaxDiagramsCode(grammar, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@" + _version__WEBPACK_IMPORTED_MODULE_0__.VERSION + "/diagrams/" : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@" + _version__WEBPACK_IMPORTED_MODULE_0__.VERSION + "/diagrams/diagrams.css" : _d; var header = "\n\n\n\n\n\n"; var cssHtml = "\n\n"; var scripts = "\n\n\n\n\n"; var diagramsDiv = "\n
\n"; var serializedGrammar = "\n\n"; var initLogic = "\n\n"; return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic); } //# sourceMappingURL=render_public.js.map /***/ }), /* 55 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ generateParserFactory: () => (/* binding */ generateParserFactory), /* harmony export */ generateParserModule: () => (/* binding */ generateParserModule) /* harmony export */ }); /* harmony import */ var _generate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(56); function generateParserFactory(options) { var wrapperText = (0,_generate__WEBPACK_IMPORTED_MODULE_0__.genWrapperFunction)({ name: options.name, rules: options.rules }); var constructorWrapper = new Function("tokenVocabulary", "config", "chevrotain", wrapperText); return function (config) { return constructorWrapper(options.tokenVocabulary, config, // TODO: check how the require is transpiled/webpacked __webpack_require__(14)); }; } function generateParserModule(options) { return (0,_generate__WEBPACK_IMPORTED_MODULE_0__.genUmdModule)({ name: options.name, rules: options.rules }); } //# sourceMappingURL=generate_public.js.map /***/ }), /* 56 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ genAllRules: () => (/* binding */ genAllRules), /* harmony export */ genAlternation: () => (/* binding */ genAlternation), /* harmony export */ genClass: () => (/* binding */ genClass), /* harmony export */ genNonTerminal: () => (/* binding */ genNonTerminal), /* harmony export */ genRule: () => (/* binding */ genRule), /* harmony export */ genSingleAlt: () => (/* binding */ genSingleAlt), /* harmony export */ genTerminal: () => (/* binding */ genTerminal), /* harmony export */ genUmdModule: () => (/* binding */ genUmdModule), /* harmony export */ genWrapperFunction: () => (/* binding */ genWrapperFunction) /* harmony export */ }); /* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17); /* harmony import */ var _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); /** * Missing features * 1. Rule arguments * 2. Gates * 3. embedded actions */ var NL = "\n"; function genUmdModule(options) { return "\n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['chevrotain'], factory);\n } else if (typeof module === 'object' && module.exports) {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like environments that support module.exports,\n // like Node.\n module.exports = factory(require('chevrotain'));\n } else {\n // Browser globals (root is window)\n root.returnExports = factory(root.b);\n }\n}(typeof self !== 'undefined' ? self : this, function (chevrotain) {\n\n" + genClass(options) + "\n \nreturn {\n " + options.name + ": " + options.name + " \n}\n}));\n"; } function genWrapperFunction(options) { return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n"; } function genClass(options) { // TODO: how to pass the token vocabulary? Constructor? other? var result = "\nfunction " + options.name + "(tokenVocabulary, config) {\n // invoke super constructor\n // No support for embedded actions currently, so we can 'hardcode'\n // The use of CstParser.\n chevrotain.CstParser.call(this, tokenVocabulary, config)\n\n const $ = this\n\n " + genAllRules(options.rules) + "\n\n // very important to call this after all the rules have been defined.\n // otherwise the parser may not work correctly as it will lack information\n // derived during the self analysis phase.\n this.performSelfAnalysis(this)\n}\n\n// inheritance as implemented in javascript in the previous decade... :(\n" + options.name + ".prototype = Object.create(chevrotain.CstParser.prototype)\n" + options.name + ".prototype.constructor = " + options.name + " \n "; return result; } function genAllRules(rules) { var rulesText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(rules, function (currRule) { return genRule(currRule, 1); }); return rulesText.join("\n"); } function genRule(prod, n) { var result = indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL; result += genDefinition(prod.definition, n + 1); result += indent(n + 1, "})") + NL; return result; } function genTerminal(prod, n) { var name = prod.terminalType.name; // TODO: potential performance optimization, avoid tokenMap Dictionary access return indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL); } function genNonTerminal(prod, n) { return indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL); } function genAlternation(prod, n) { var result = indent(n, "$.OR" + prod.idx + "([") + NL; var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); }); result += alts.join("," + NL); result += NL + indent(n, "])" + NL); return result; } function genSingleAlt(prod, n) { var result = indent(n, "{") + NL; if (prod.name) { result += indent(n + 1, "NAME: \"" + prod.name + "\",") + NL; } result += indent(n + 1, "ALT: function() {") + NL; result += genDefinition(prod.definition, n + 1); result += indent(n + 1, "}") + NL; result += indent(n, "}"); return result; } function genProd(prod, n) { /* istanbul ignore else */ if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) { return genNonTerminal(prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) { return genDSLRule("OPTION", prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) { return genDSLRule("AT_LEAST_ONE", prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) { return genDSLRule("AT_LEAST_ONE_SEP", prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) { return genDSLRule("MANY_SEP", prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) { return genDSLRule("MANY", prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) { return genAlternation(prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) { return genTerminal(prod, n); } else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat) { return genDefinition(prod.definition, n); } else { throw Error("non exhaustive match"); } } function genDSLRule(dslName, prod, n) { var result = indent(n, "$." + (dslName + prod.idx) + "("); if (prod.name || prod.separator) { result += "{" + NL; if (prod.name) { result += indent(n + 1, "NAME: \"" + prod.name + "\"") + "," + NL; } if (prod.separator) { result += indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) + "," + NL; } result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL; result += indent(n, "}") + NL; } else { result += genDefFunction(prod.definition, n + 1); } result += indent(n, ")") + NL; return result; } function genDefFunction(definition, n) { var def = "function() {" + NL; def += genDefinition(definition, n); def += indent(n, "}") + NL; return def; } function genDefinition(def, n) { var result = ""; (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(def, function (prod) { result += genProd(prod, n + 1); }); return result; } function indent(howMuch, text) { var spaces = Array(howMuch * 4 + 1).join(" "); return spaces + text; } //# sourceMappingURL=generate.js.map /***/ }), /* 57 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AstNodeType: () => (/* binding */ AstNodeType), /* harmony export */ ParsingErrorType: () => (/* binding */ ParsingErrorType), /* harmony export */ RangeSheetReferenceType: () => (/* binding */ RangeSheetReferenceType), /* harmony export */ buildArrayAst: () => (/* binding */ buildArrayAst), /* harmony export */ buildCellErrorAst: () => (/* binding */ buildCellErrorAst), /* harmony export */ buildCellRangeAst: () => (/* binding */ buildCellRangeAst), /* harmony export */ buildCellReferenceAst: () => (/* binding */ buildCellReferenceAst), /* harmony export */ buildColumnRangeAst: () => (/* binding */ buildColumnRangeAst), /* harmony export */ buildConcatenateOpAst: () => (/* binding */ buildConcatenateOpAst), /* harmony export */ buildDivOpAst: () => (/* binding */ buildDivOpAst), /* harmony export */ buildEmptyArgAst: () => (/* binding */ buildEmptyArgAst), /* harmony export */ buildEqualsOpAst: () => (/* binding */ buildEqualsOpAst), /* harmony export */ buildErrorWithRawInputAst: () => (/* binding */ buildErrorWithRawInputAst), /* harmony export */ buildGreaterThanOpAst: () => (/* binding */ buildGreaterThanOpAst), /* harmony export */ buildGreaterThanOrEqualOpAst: () => (/* binding */ buildGreaterThanOrEqualOpAst), /* harmony export */ buildLessThanOpAst: () => (/* binding */ buildLessThanOpAst), /* harmony export */ buildLessThanOrEqualOpAst: () => (/* binding */ buildLessThanOrEqualOpAst), /* harmony export */ buildMinusOpAst: () => (/* binding */ buildMinusOpAst), /* harmony export */ buildMinusUnaryOpAst: () => (/* binding */ buildMinusUnaryOpAst), /* harmony export */ buildNamedExpressionAst: () => (/* binding */ buildNamedExpressionAst), /* harmony export */ buildNotEqualOpAst: () => (/* binding */ buildNotEqualOpAst), /* harmony export */ buildNumberAst: () => (/* binding */ buildNumberAst), /* harmony export */ buildParenthesisAst: () => (/* binding */ buildParenthesisAst), /* harmony export */ buildParsingErrorAst: () => (/* binding */ buildParsingErrorAst), /* harmony export */ buildPercentOpAst: () => (/* binding */ buildPercentOpAst), /* harmony export */ buildPlusOpAst: () => (/* binding */ buildPlusOpAst), /* harmony export */ buildPlusUnaryOpAst: () => (/* binding */ buildPlusUnaryOpAst), /* harmony export */ buildPowerOpAst: () => (/* binding */ buildPowerOpAst), /* harmony export */ buildProcedureAst: () => (/* binding */ buildProcedureAst), /* harmony export */ buildRowRangeAst: () => (/* binding */ buildRowRangeAst), /* harmony export */ buildStringAst: () => (/* binding */ buildStringAst), /* harmony export */ buildTimesOpAst: () => (/* binding */ buildTimesOpAst), /* harmony export */ imageWithWhitespace: () => (/* binding */ imageWithWhitespace), /* harmony export */ parsingError: () => (/* binding */ parsingError) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const parsingError = (type, message) => ({ type, message }); /** * Represents types of parsing errors. */ var ParsingErrorType; (function (ParsingErrorType) { ParsingErrorType["LexingError"] = "LexingError"; ParsingErrorType["ParserError"] = "ParsingError"; ParsingErrorType["StaticOffsetError"] = "StaticOffsetError"; ParsingErrorType["StaticOffsetOutOfRangeError"] = "StaticOffsetOutOfRangeError"; ParsingErrorType["RangeOffsetNotAllowed"] = "RangeOffsetNotAllowed"; ParsingErrorType["InvalidRangeSize"] = "InvalidRangeSize"; })(ParsingErrorType || (ParsingErrorType = {})); var AstNodeType; (function (AstNodeType) { AstNodeType["EMPTY"] = "EMPTY"; AstNodeType["NUMBER"] = "NUMBER"; AstNodeType["STRING"] = "STRING"; AstNodeType["MINUS_UNARY_OP"] = "MINUS_UNARY_OP"; AstNodeType["PLUS_UNARY_OP"] = "PLUS_UNARY_OP"; AstNodeType["PERCENT_OP"] = "PERCENT_OP"; AstNodeType["CONCATENATE_OP"] = "CONCATENATE_OP"; AstNodeType["EQUALS_OP"] = "EQUALS_OP"; AstNodeType["NOT_EQUAL_OP"] = "NOT_EQUAL_OP"; AstNodeType["GREATER_THAN_OP"] = "GREATER_THAN_OP"; AstNodeType["LESS_THAN_OP"] = "LESS_THAN_OP"; AstNodeType["GREATER_THAN_OR_EQUAL_OP"] = "GREATER_THAN_OR_EQUAL_OP"; AstNodeType["LESS_THAN_OR_EQUAL_OP"] = "LESS_THAN_OR_EQUAL_OP"; AstNodeType["PLUS_OP"] = "PLUS_OP"; AstNodeType["MINUS_OP"] = "MINUS_OP"; AstNodeType["TIMES_OP"] = "TIMES_OP"; AstNodeType["DIV_OP"] = "DIV_OP"; AstNodeType["POWER_OP"] = "POWER_OP"; AstNodeType["FUNCTION_CALL"] = "FUNCTION_CALL"; AstNodeType["NAMED_EXPRESSION"] = "NAMED_EXPRESSION"; AstNodeType["PARENTHESIS"] = "PARENTHESES"; AstNodeType["CELL_REFERENCE"] = "CELL_REFERENCE"; AstNodeType["CELL_RANGE"] = "CELL_RANGE"; AstNodeType["COLUMN_RANGE"] = "COLUMN_RANGE"; AstNodeType["ROW_RANGE"] = "ROW_RANGE"; AstNodeType["ERROR"] = "ERROR"; AstNodeType["ERROR_WITH_RAW_INPUT"] = "ERROR_WITH_RAW_INPUT"; AstNodeType["ARRAY"] = "ARRAY"; })(AstNodeType || (AstNodeType = {})); var RangeSheetReferenceType; (function (RangeSheetReferenceType) { RangeSheetReferenceType[RangeSheetReferenceType["RELATIVE"] = 0] = "RELATIVE"; RangeSheetReferenceType[RangeSheetReferenceType["START_ABSOLUTE"] = 1] = "START_ABSOLUTE"; RangeSheetReferenceType[RangeSheetReferenceType["BOTH_ABSOLUTE"] = 2] = "BOTH_ABSOLUTE"; })(RangeSheetReferenceType || (RangeSheetReferenceType = {})); const buildEmptyArgAst = leadingWhitespace => ({ type: AstNodeType.EMPTY, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildNumberAst = (value, leadingWhitespace) => ({ type: AstNodeType.NUMBER, value: value, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildStringAst = token => { var _a; return { type: AstNodeType.STRING, value: token.image.slice(1, -1), leadingWhitespace: (_a = token.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image }; }; const buildCellReferenceAst = (reference, leadingWhitespace) => ({ type: AstNodeType.CELL_REFERENCE, reference, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildCellRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => { assertRangeConsistency(start, end, sheetReferenceType); return { type: AstNodeType.CELL_RANGE, start, end, sheetReferenceType, leadingWhitespace }; }; const buildColumnRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => { assertRangeConsistency(start, end, sheetReferenceType); return { type: AstNodeType.COLUMN_RANGE, start, end, sheetReferenceType, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }; }; const buildRowRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => { assertRangeConsistency(start, end, sheetReferenceType); return { type: AstNodeType.ROW_RANGE, start, end, sheetReferenceType, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }; }; const buildConcatenateOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.CONCATENATE_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildEqualsOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.EQUALS_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildNotEqualOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.NOT_EQUAL_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildGreaterThanOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.GREATER_THAN_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildLessThanOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.LESS_THAN_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildGreaterThanOrEqualOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.GREATER_THAN_OR_EQUAL_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildLessThanOrEqualOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.LESS_THAN_OR_EQUAL_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildPlusOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.PLUS_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildMinusOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.MINUS_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildTimesOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.TIMES_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildDivOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.DIV_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildPowerOpAst = (left, right, leadingWhitespace) => ({ type: AstNodeType.POWER_OP, left, right, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildMinusUnaryOpAst = (value, leadingWhitespace) => ({ type: AstNodeType.MINUS_UNARY_OP, value, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildPlusUnaryOpAst = (value, leadingWhitespace) => ({ type: AstNodeType.PLUS_UNARY_OP, value, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildPercentOpAst = (value, leadingWhitespace) => ({ type: AstNodeType.PERCENT_OP, value, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildProcedureAst = (procedureName, args, leadingWhitespace, internalWhitespace, hyperlink) => ({ type: AstNodeType.FUNCTION_CALL, procedureName, args, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image, internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image, hyperlink }); const buildArrayAst = (args, leadingWhitespace, internalWhitespace) => ({ type: AstNodeType.ARRAY, args, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image, internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image }); const buildNamedExpressionAst = (expressionName, leadingWhitespace) => ({ type: AstNodeType.NAMED_EXPRESSION, expressionName, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildParenthesisAst = (expression, leadingWhitespace, internalWhitespace) => ({ type: AstNodeType.PARENTHESIS, expression, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image, internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image }); const buildCellErrorAst = (error, leadingWhitespace) => ({ type: AstNodeType.ERROR, error, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildErrorWithRawInputAst = (rawInput, error, leadingWhitespace) => ({ type: AstNodeType.ERROR_WITH_RAW_INPUT, error, rawInput, leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image }); const buildParsingErrorAst = () => ({ type: AstNodeType.ERROR, error: _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError.parsingError() }); function assertRangeConsistency(start, end, sheetReferenceType) { if (start.sheet !== undefined && end.sheet === undefined || start.sheet === undefined && end.sheet !== undefined) { throw new Error('Start address inconsistent with end address'); } if (start.sheet === undefined && sheetReferenceType !== RangeSheetReferenceType.RELATIVE || start.sheet !== undefined && sheetReferenceType === RangeSheetReferenceType.RELATIVE) { throw new Error('Sheet address inconsistent with sheet reference type'); } } function imageWithWhitespace(image, leadingWhitespace) { return (leadingWhitespace !== null && leadingWhitespace !== void 0 ? leadingWhitespace : '') + image; } /***/ }), /* 58 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ binaryOpTokenMap: () => (/* binding */ binaryOpTokenMap) /* harmony export */ }); /* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const binaryOpTokenMap = { [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP]: '+', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP]: '-', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP]: '*', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP]: '/', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP]: '&', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP]: '^', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP]: '=', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP]: '<>', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP]: '>', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP]: '>=', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP]: '<', [_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP]: '<=' }; /***/ }), /* 59 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Cache: () => (/* binding */ Cache), /* harmony export */ doesContainFunctions: () => (/* binding */ doesContainFunctions) /* harmony export */ }); /* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const buildCacheEntry = (ast, relativeDependencies, hasVolatileFunction, hasStructuralChangeFunction) => ({ ast, relativeDependencies, hasVolatileFunction, hasStructuralChangeFunction }); class Cache { constructor(functionRegistry) { this.functionRegistry = functionRegistry; this.cache = new Map(); } set(hash, ast) { const astRelativeDependencies = (0,___WEBPACK_IMPORTED_MODULE_0__.collectDependencies)(ast, this.functionRegistry); const cacheEntry = buildCacheEntry(ast, astRelativeDependencies, doesContainFunctions(ast, this.functionRegistry.isFunctionVolatile), doesContainFunctions(ast, this.functionRegistry.isFunctionDependentOnSheetStructureChange)); this.cache.set(hash, cacheEntry); return cacheEntry; } get(hash) { return this.cache.get(hash); } maybeSetAndThenGet(hash, ast) { const entryFromCache = this.cache.get(hash); if (entryFromCache !== undefined) { return entryFromCache.ast; } else { this.set(hash, ast); return ast; } } } const doesContainFunctions = (ast, functionCriterion) => { switch (ast.type) { case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EMPTY: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NUMBER: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.STRING: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR_WITH_RAW_INPUT: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_REFERENCE: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_RANGE: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.COLUMN_RANGE: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ROW_RANGE: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NAMED_EXPRESSION: return false; case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PERCENT_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_UNARY_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_UNARY_OP: { return doesContainFunctions(ast.value, functionCriterion); } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP: return doesContainFunctions(ast.left, functionCriterion) || doesContainFunctions(ast.right, functionCriterion); case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PARENTHESIS: return doesContainFunctions(ast.expression, functionCriterion); case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.FUNCTION_CALL: { if (functionCriterion(ast.procedureName)) { return true; } return ast.args.some(arg => doesContainFunctions(arg, functionCriterion)); } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ARRAY: { return ast.args.some(row => row.some(arg => doesContainFunctions(arg, functionCriterion))); } } }; /***/ }), /* 60 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FormulaLexer: () => (/* binding */ FormulaLexer), /* harmony export */ FormulaParser: () => (/* binding */ FormulaParser) /* harmony export */ }); /* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); /* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57); /* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9); /* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(62); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * LL(k) formula parser described using Chevrotain DSL * * It is equivalent to the grammar below: * * F -> '=' E
* B -> K < B | K >= B ... | K
* K -> E & K | E
* E -> M + E | M - E | M
* M -> W * M | W / M | W
* W -> C * W | C
* C -> N | R | O | A | P | num
* N -> '(' E ')'
* R -> A:OFFSET(..) | A:A
* O -> OFFSET(..) | OFFSET(..):A | OFFSET(..):OFFSET(..)
* A -> A1 | $A1 | A$1 | $A$1
* P -> SUM(..)
*/ class FormulaParser extends chevrotain__WEBPACK_IMPORTED_MODULE_0__.EmbeddedActionsParser { constructor(lexerConfig, sheetMapping) { super(lexerConfig.allTokens, { outputCst: false, maxLookahead: 7 }); this.booleanExpressionOrEmpty = this.RULE('booleanExpressionOrEmpty', () => { return this.OR([{ ALT: () => this.SUBRULE(this.booleanExpression) }, { ALT: (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.EMPTY_ALT)((0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildEmptyArgAst)()) }]); }); /** * Rule for procedure expressions: SUM(1,A1) */ this.procedureExpression = this.RULE('procedureExpression', () => { var _a; const procedureNameToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ProcedureName); const procedureName = procedureNameToken.image.toUpperCase().slice(0, -1); const canonicalProcedureName = (_a = this.lexerConfig.functionMapping[procedureName]) !== null && _a !== void 0 ? _a : procedureName; const args = []; let argument = this.SUBRULE(this.booleanExpressionOrEmpty); this.MANY(() => { var _a; const separator = this.CONSUME(this.lexerConfig.ArgSeparator); if (argument.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EMPTY) { argument.leadingWhitespace = (_a = separator.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image; } args.push(argument); argument = this.SUBRULE2(this.booleanExpressionOrEmpty); }); args.push(argument); if (args.length === 1 && args[0].type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EMPTY) { args.length = 0; } const rParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildProcedureAst)(canonicalProcedureName, args, procedureNameToken.leadingWhitespace, rParenToken.leadingWhitespace); }); this.namedExpressionExpression = this.RULE('namedExpressionExpression', () => { const name = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.NamedExpression); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNamedExpressionAst)(name.image, name.leadingWhitespace); }); /** * Rule for OFFSET() function expression */ this.offsetProcedureExpression = this.RULE('offsetProcedureExpression', () => { const args = []; this.CONSUME(this.lexerConfig.OffsetProcedureName); this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LParen); this.MANY_SEP({ SEP: this.lexerConfig.ArgSeparator, DEF: () => { args.push(this.SUBRULE(this.booleanExpression)); } }); this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen); return this.handleOffsetHeuristic(args); }); /** * Rule for column range, e.g., A:B, Sheet1!A:B, Sheet1!A:Sheet1!B */ this.columnRangeExpression = this.RULE('columnRangeExpression', () => { const range = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ColumnRange); const [startImage, endImage] = range.image.split(':'); const firstAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, startImage, this.formulaAddress)); const secondAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, endImage, this.formulaAddress)); if (firstAddress === undefined || secondAddress === undefined) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF)); } if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns)) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(range.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), range.leadingWhitespace); } if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression'); } const { firstEnd, secondEnd, sheetRefType } = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildColumnRangeAst)(firstEnd, secondEnd, sheetRefType, range.leadingWhitespace); }); /** * Rule for row range, e.g., 1:2, Sheet1!1:2, Sheet1!1:Sheet1!2 */ this.rowRangeExpression = this.RULE('rowRangeExpression', () => { const range = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RowRange); const [startImage, endImage] = range.image.split(':'); const firstAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, startImage, this.formulaAddress)); const secondAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, endImage, this.formulaAddress)); if (firstAddress === undefined || secondAddress === undefined) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF)); } if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows)) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(range.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), range.leadingWhitespace); } if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression'); } const { firstEnd, secondEnd, sheetRefType } = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildRowRangeAst)(firstEnd, secondEnd, sheetRefType, range.leadingWhitespace); }); /** * Rule for cell reference expression (e.g., A1, $A1, A$1, $A$1, $Sheet42!A$17) */ this.cellReference = this.RULE('cellReference', () => { const cell = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference); const address = this.ACTION(() => { return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, cell.image, this.formulaAddress); }); if (address === undefined) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(cell.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF), cell.leadingWhitespace); } else if (address.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(cell.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), cell.leadingWhitespace); } else { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellReferenceAst)(address, cell.leadingWhitespace); } }); /** * Rule for end range reference expression with additional checks considering range start */ this.endRangeReference = this.RULE('endRangeReference', start => { var _a; const end = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference); const startAddress = this.ACTION(() => { return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, start.image, this.formulaAddress); }); const endAddress = this.ACTION(() => { return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, end.image, this.formulaAddress); }); if (startAddress === undefined || endAddress === undefined) { return this.ACTION(() => { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(`${start.image}:${end.image}`, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF), start.leadingWhitespace); }); } else if (startAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows) || endAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) { return this.ACTION(() => { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(`${start.image}:${end.image}`, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), start.leadingWhitespace); }); } return this.buildCellRange(startAddress, endAddress, (_a = start.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image); }); /** * Rule for end of range expression * * End of range may be a cell reference or OFFSET() function call */ this.endOfRangeExpression = this.RULE('endOfRangeExpression', start => { return this.OR([{ ALT: () => { return this.SUBRULE(this.endRangeReference, { ARGS: [start] }); } }, { ALT: () => { var _a; const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression); const startAddress = this.ACTION(() => { return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, start.image, this.formulaAddress); }); if (startAddress === undefined) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF)); } if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) { return this.buildCellRange(startAddress, offsetProcedure.reference, (_a = start.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image); } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here'); } } }]); }); /** * Rule for cell ranges (e.g., A1:B$3, A1:OFFSET()) */ this.cellRangeExpression = this.RULE('cellRangeExpression', () => { const start = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference); this.CONSUME2(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator); return this.SUBRULE(this.endOfRangeExpression, { ARGS: [start] }); }); /** * Rule for end range reference expression starting with offset procedure with additional checks considering range start */ this.endRangeWithOffsetStartReference = this.RULE('endRangeWithOffsetStartReference', start => { const end = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference); const endAddress = this.ACTION(() => { return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, end.image, this.formulaAddress); }); if (endAddress === undefined) { return this.ACTION(() => { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF)); }); } return this.buildCellRange(start.reference, endAddress, start.leadingWhitespace); }); /** * Rule for end of range expression * * End of range may be a cell reference or OFFSET() function call */ this.endOfRangeWithOffsetStartExpression = this.RULE('endOfRangeWithOffsetStartExpression', start => { return this.OR([{ ALT: () => { return this.SUBRULE(this.endRangeWithOffsetStartReference, { ARGS: [start] }); } }, { ALT: () => { const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression); if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) { return this.buildCellRange(start.reference, offsetProcedure.reference, start.leadingWhitespace); } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here'); } } }]); }); /** * Rule for expressions that start with the OFFSET function. * * The OFFSET function can occur as a cell reference, or as a part of a cell range. * To preserve LL(k) properties, expressions that start with the OFFSET function need a separate rule. * * Depending on the presence of the {@link RangeSeparator}, a proper {@link Ast} node type is built. */ this.offsetExpression = this.RULE('offsetExpression', () => { const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression); let end; this.OPTION(() => { this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator); if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_RANGE) { end = this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here'); } else { end = this.SUBRULE(this.endOfRangeWithOffsetStartExpression, { ARGS: [offsetProcedure] }); } }); if (end !== undefined) { return end; } return offsetProcedure; }); this.insideArrayExpression = this.RULE('insideArrayExpression', () => { const ret = [[]]; ret[ret.length - 1].push(this.SUBRULE(this.booleanExpression)); this.MANY(() => { this.OR([{ ALT: () => { this.CONSUME(this.lexerConfig.ArrayColSeparator); ret[ret.length - 1].push(this.SUBRULE2(this.booleanExpression)); } }, { ALT: () => { this.CONSUME(this.lexerConfig.ArrayRowSeparator); ret.push([]); ret[ret.length - 1].push(this.SUBRULE3(this.booleanExpression)); } }]); }); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildArrayAst)(ret); }); /** * Rule for parenthesis expression */ this.parenthesisExpression = this.RULE('parenthesisExpression', () => { const lParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LParen); const expression = this.SUBRULE(this.booleanExpression); const rParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParenthesisAst)(expression, lParenToken.leadingWhitespace, rParenToken.leadingWhitespace); }); this.arrayExpression = this.RULE('arrayExpression', () => { return this.OR([{ ALT: () => { const ltoken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ArrayLParen); const ret = this.SUBRULE(this.insideArrayExpression); const rtoken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ArrayRParen); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildArrayAst)(ret.args, ltoken.leadingWhitespace, rtoken.leadingWhitespace); } }, { ALT: () => this.SUBRULE(this.parenthesisExpression) }]); }); this.numericStringToNumber = input => { const normalized = input.replace(this.lexerConfig.decimalSeparator, '.'); return Number(normalized); }; /** * Rule for positive atomic expressions */ this.positiveAtomicExpression = this.RULE('positiveAtomicExpression', () => { var _a; return this.OR((_a = this.atomicExpCache) !== null && _a !== void 0 ? _a : this.atomicExpCache = [{ ALT: () => this.SUBRULE(this.arrayExpression) }, { ALT: () => this.SUBRULE(this.cellRangeExpression) }, { ALT: () => this.SUBRULE(this.columnRangeExpression) }, { ALT: () => this.SUBRULE(this.rowRangeExpression) }, { ALT: () => this.SUBRULE(this.offsetExpression) }, { ALT: () => this.SUBRULE(this.cellReference) }, { ALT: () => this.SUBRULE(this.procedureExpression) }, { ALT: () => this.SUBRULE(this.namedExpressionExpression) }, { ALT: () => { const number = this.CONSUME(this.lexerConfig.NumberLiteral); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNumberAst)(this.numericStringToNumber(number.image), number.leadingWhitespace); } }, { ALT: () => { const str = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.StringLiteral); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildStringAst)(str); } }, { ALT: () => { const token = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ErrorLiteral); const errString = token.image.toUpperCase(); const errorType = this.lexerConfig.errorMapping[errString]; if (errorType) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(errorType), token.leadingWhitespace); } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Unknown error literal'); } } }]); }); this.rightUnaryOpAtomicExpression = this.RULE('rightUnaryOpAtomicExpression', () => { const positiveAtomicExpression = this.SUBRULE(this.positiveAtomicExpression); const percentage = this.OPTION(() => { return this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PercentOp); }); if (percentage) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPercentOpAst)(positiveAtomicExpression, percentage.leadingWhitespace); } return positiveAtomicExpression; }); /** * Rule for atomic expressions, which is positive atomic expression or negation of it */ this.atomicExpression = this.RULE('atomicExpression', () => { return this.OR([{ ALT: () => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.AdditionOp); const value = this.SUBRULE(this.atomicExpression); if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PlusOp)) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPlusUnaryOpAst)(value, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MinusOp)) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildMinusUnaryOpAst)(value, op.leadingWhitespace); } else { this.customParsingError = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.parsingError)(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Mismatched token type'); return this.customParsingError; } } }, { ALT: () => this.SUBRULE2(this.rightUnaryOpAtomicExpression) }]); }); /** * Rule for power expression */ this.powerExpression = this.RULE('powerExpression', () => { let lhs = this.SUBRULE(this.atomicExpression); this.MANY(() => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PowerOp); const rhs = this.SUBRULE2(this.atomicExpression); if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PowerOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPowerOpAst)(lhs, rhs, op.leadingWhitespace); } else { this.ACTION(() => { throw Error('Operator not supported'); }); } }); return lhs; }); /** * Rule for multiplication category operators (e.g., 1 * A1, 1 / A1) */ this.multiplicationExpression = this.RULE('multiplicationExpression', () => { let lhs = this.SUBRULE(this.powerExpression); this.MANY(() => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MultiplicationOp); const rhs = this.SUBRULE2(this.powerExpression); if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.TimesOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildTimesOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.DivOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildDivOpAst)(lhs, rhs, op.leadingWhitespace); } else { this.ACTION(() => { throw Error('Operator not supported'); }); } }); return lhs; }); /** * Rule for addition category operators (e.g., 1 + A1, 1 - A1) */ this.additionExpression = this.RULE('additionExpression', () => { let lhs = this.SUBRULE(this.multiplicationExpression); this.MANY(() => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.AdditionOp); const rhs = this.SUBRULE2(this.multiplicationExpression); if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PlusOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPlusOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MinusOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildMinusOpAst)(lhs, rhs, op.leadingWhitespace); } else { this.ACTION(() => { throw Error('Operator not supported'); }); } }); return lhs; }); /** * Rule for concatenation operator expression (e.g., "=" & A1) */ this.concatenateExpression = this.RULE('concatenateExpression', () => { let lhs = this.SUBRULE(this.additionExpression); this.MANY(() => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ConcatenateOp); const rhs = this.SUBRULE2(this.additionExpression); lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildConcatenateOpAst)(lhs, rhs, op.leadingWhitespace); }); return lhs; }); /** * Rule for boolean expression (e.g., 1 <= A1) */ this.booleanExpression = this.RULE('booleanExpression', () => { let lhs = this.SUBRULE(this.concatenateExpression); this.MANY(() => { const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.BooleanOp); const rhs = this.SUBRULE2(this.concatenateExpression); if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.EqualsOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildEqualsOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.NotEqualOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNotEqualOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.GreaterThanOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildGreaterThanOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LessThanOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildLessThanOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.GreaterThanOrEqualOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildGreaterThanOrEqualOpAst)(lhs, rhs, op.leadingWhitespace); } else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LessThanOrEqualOp)) { lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildLessThanOrEqualOpAst)(lhs, rhs, op.leadingWhitespace); } else { this.ACTION(() => { throw Error('Operator not supported'); }); } }); return lhs; }); /** * Entry rule */ this.formula = this.RULE('formula', () => { this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.EqualsOp); return this.SUBRULE(this.booleanExpression); }); this.lexerConfig = lexerConfig; this.sheetMapping = sheetMapping; this.formulaAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(0, 0, 0); this.performSelfAnalysis(); } /** * Parses tokenized formula and builds abstract syntax tree * * @param {ExtendedToken[]} tokens - tokenized formula * @param {SimpleCellAddress} formulaAddress - address of the cell in which formula is located */ parseFromTokens(tokens, formulaAddress) { this.input = tokens; let ast = this.formulaWithContext(formulaAddress); let errors = []; if (this.customParsingError) { errors.push(this.customParsingError); } errors = errors.concat(this.errors.map(e => ({ type: _Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, message: e.message }))); if (errors.length > 0) { ast = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParsingErrorAst)(); } return { ast, errors }; } reset() { super.reset(); this.customParsingError = undefined; } /** * Entry rule wrapper that sets formula address * * @param {SimpleCellAddress} address - address of the cell in which formula is located */ formulaWithContext(address) { this.formulaAddress = address; return this.formula(); } buildCellRange(firstAddress, secondAddress, leadingWhitespace) { if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression'); } const { firstEnd, secondEnd, sheetRefType } = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellRangeAst)(firstEnd, secondEnd, sheetRefType, leadingWhitespace); } static fixSheetIdsForRangeEnds(firstEnd, secondEnd) { const sheetRefType = FormulaParser.rangeSheetReferenceType(firstEnd.sheet, secondEnd.sheet); const secondEndFixed = firstEnd.sheet !== undefined && secondEnd.sheet === undefined ? secondEnd.withSheet(firstEnd.sheet) : secondEnd; return { firstEnd, secondEnd: secondEndFixed, sheetRefType }; } /** * Returns {@link CellReferenceAst} or {@link CellRangeAst} based on OFFSET function arguments * * @param {Ast[]} args - OFFSET function arguments */ handleOffsetHeuristic(args) { const cellArg = args[0]; if (cellArg.type !== _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'First argument to OFFSET is not a reference'); } const rowsArg = args[1]; let rowShift; if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value)) { rowShift = rowsArg.value; } else if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_UNARY_OP && rowsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value.value)) { rowShift = rowsArg.value.value; } else if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_UNARY_OP && rowsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value.value)) { rowShift = -rowsArg.value.value; } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Second argument to OFFSET is not a static number'); } const columnsArg = args[2]; let colShift; if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value)) { colShift = columnsArg.value; } else if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_UNARY_OP && columnsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value.value)) { colShift = columnsArg.value.value; } else if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_UNARY_OP && columnsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value.value)) { colShift = -columnsArg.value.value; } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Third argument to OFFSET is not a static number'); } const heightArg = args[3]; let height; if (heightArg === undefined) { height = 1; } else if (heightArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER) { height = heightArg.value; if (height < 1) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is too small number'); } else if (!Number.isInteger(height)) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is not integer'); } } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is not a static number'); } const widthArg = args[4]; let width; if (widthArg === undefined) { width = 1; } else if (widthArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER) { width = widthArg.value; if (width < 1) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is too small number'); } else if (!Number.isInteger(width)) { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is not integer'); } } else { return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is not a static number'); } const topLeftCorner = new _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellAddress(cellArg.reference.col + colShift, cellArg.reference.row + rowShift, cellArg.reference.type); let absoluteCol = topLeftCorner.col; let absoluteRow = topLeftCorner.row; if (cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_RELATIVE || cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL) { absoluteRow = absoluteRow + this.formulaAddress.row; } if (cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_RELATIVE || cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion absoluteCol = absoluteCol + this.formulaAddress.col; } if (absoluteCol < 0 || absoluteRow < 0) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.OutOfSheet)); } if (width === 1 && height === 1) { return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellReferenceAst)(topLeftCorner); } else { const bottomRightCorner = new _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellAddress(topLeftCorner.col + width - 1, topLeftCorner.row + height - 1, topLeftCorner.type); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellRangeAst)(topLeftCorner, bottomRightCorner, _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE); } } parsingError(type, message) { this.customParsingError = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.parsingError)(type, message); return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParsingErrorAst)(); } static rangeSheetReferenceType(start, end) { if (start === undefined) { return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE; } else if (end === undefined) { return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.START_ABSOLUTE; } else { return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.BOTH_ABSOLUTE; } } } class FormulaLexer { constructor(lexerConfig) { this.lexerConfig = lexerConfig; this.lexer = new chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer(lexerConfig.allTokens, { ensureOptimizations: true }); } /** * Returns Lexer tokens from formula string * * @param {string} text - string representation of a formula */ tokenizeFormula(text) { const lexingResult = this.lexer.tokenize(text); let tokens = lexingResult.tokens; tokens = this.trimTrailingWhitespaces(tokens); tokens = this.skipWhitespacesInsideRanges(tokens); tokens = this.skipWhitespacesBeforeArgSeparators(tokens); lexingResult.tokens = tokens; return lexingResult; } skipWhitespacesInsideRanges(tokens) { return FormulaLexer.filterTokensByNeighbors(tokens, (previous, current, next) => { return ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference) || (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator)) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace) && ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference) || (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator)); }); } skipWhitespacesBeforeArgSeparators(tokens) { return FormulaLexer.filterTokensByNeighbors(tokens, (previous, current, next) => { return !(0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, this.lexerConfig.ArgSeparator) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, this.lexerConfig.ArgSeparator); }); } static filterTokensByNeighbors(tokens, shouldBeSkipped) { if (tokens.length < 3) { return tokens; } let i = 0; const filteredTokens = [tokens[i++]]; while (i < tokens.length - 1) { if (!shouldBeSkipped(tokens[i - 1], tokens[i], tokens[i + 1])) { filteredTokens.push(tokens[i]); } ++i; } filteredTokens.push(tokens[i]); return filteredTokens; } trimTrailingWhitespaces(tokens) { if (tokens.length > 0 && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(tokens[tokens.length - 1], this.lexerConfig.WhiteSpace)) { tokens.pop(); } return tokens; } } /***/ }), /* 61 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ErrorMessage: () => (/* binding */ ErrorMessage) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * This is a class for detailed error messages across HyperFormula. */ class ErrorMessage {} ErrorMessage.DistinctSigns = 'Distinct signs.'; ErrorMessage.WrongArgNumber = 'Wrong number of arguments.'; ErrorMessage.EmptyArg = 'Empty function argument.'; ErrorMessage.EmptyArray = 'Empty array not allowed.'; ErrorMessage.ArrayDimensions = 'Array dimensions are not compatible.'; ErrorMessage.NoSpaceForArrayResult = 'No space for array result.'; ErrorMessage.ValueSmall = 'Value too small.'; ErrorMessage.ValueLarge = 'Value too large.'; ErrorMessage.BadCriterion = 'Incorrect criterion.'; ErrorMessage.RangeManySheets = 'Range spans more than one sheet.'; ErrorMessage.CellRangeExpected = 'Cell range expected.'; ErrorMessage.WrongDimension = 'Wrong range dimension.'; ErrorMessage.ScalarExpected = 'Cell range not allowed.'; ErrorMessage.NumberCoercion = 'Value cannot be coerced to number.'; ErrorMessage.NumberExpected = 'Number argument expected.'; ErrorMessage.IntegerExpected = 'Value needs to be an integer.'; ErrorMessage.BadMode = 'Mode not recognized.'; ErrorMessage.DateBounds = 'Date outside of bounds.'; ErrorMessage.OutOfSheet = 'Resulting reference is out of the sheet.'; ErrorMessage.WrongType = 'Wrong type of argument.'; ErrorMessage.NaN = 'NaN or infinite value encountered.'; ErrorMessage.EqualLength = 'Ranges need to be of equal length.'; ErrorMessage.Negative = 'Value cannot be negative.'; ErrorMessage.NotBinary = 'String does not represent a binary number.'; ErrorMessage.NotOctal = 'String does not represent an octal number.'; ErrorMessage.NotHex = 'String does not represent a hexadecimal number.'; ErrorMessage.EndStartPeriod = 'End period needs to be at least start period.'; ErrorMessage.CellRefExpected = 'Cell reference expected.'; ErrorMessage.EmptyRange = 'Empty range not allowed.'; ErrorMessage.BadRef = 'Address is not correct.'; ErrorMessage.NumberRange = 'Number-only range expected.'; ErrorMessage.ValueNotFound = 'Value not found.'; ErrorMessage.ValueBaseLarge = 'Value in base too large.'; ErrorMessage.ValueBaseSmall = 'Value in base too small.'; ErrorMessage.ValueBaseLong = 'Value in base too long.'; ErrorMessage.NegativeLength = 'Length cannot be negative.'; ErrorMessage.PatternNotFound = 'Pattern not found.'; ErrorMessage.OneValue = 'Needs at least one value.'; ErrorMessage.TwoValues = 'Range needs to contain at least two elements.'; ErrorMessage.ThreeValues = 'Range needs to contain at least three elements.'; ErrorMessage.IndexBounds = 'Index out of bounds.'; ErrorMessage.IndexLarge = 'Index too large.'; ErrorMessage.Formula = 'Expected formula.'; ErrorMessage.NegativeCount = 'Count cannot be negative.'; ErrorMessage.ParseError = 'Parsing error.'; ErrorMessage.SheetRef = 'Sheet does not exist.'; ErrorMessage.PeriodLong = 'Period number cannot exceed life length.'; ErrorMessage.InvalidDate = 'Invalid date.'; ErrorMessage.BitshiftLong = 'Result of bitshift is too long.'; ErrorMessage.EmptyString = 'Empty-string argument not allowed.'; ErrorMessage.LengthBounds = 'Length out of bounds.'; ErrorMessage.NegativeTime = 'Time cannot be negative.'; ErrorMessage.NoDefault = 'No default option.'; ErrorMessage.NoConditionMet = 'None of the conditions were met.'; ErrorMessage.Selector = 'Selector cannot exceed the number of arguments.'; ErrorMessage.StartEndDate = 'Start date needs to be earlier than end date.'; ErrorMessage.IncorrectDateTime = 'String does not represent correct DateTime.'; ErrorMessage.CharacterCodeBounds = 'Character code out of bounds.'; ErrorMessage.NonZero = 'Argument cannot be 0.'; ErrorMessage.LessThanOne = 'Argument cannot be less than 1.'; ErrorMessage.WeekendString = 'Incorrect weekend bitmask string.'; ErrorMessage.InvalidRoman = 'Invalid roman numeral.'; ErrorMessage.WrongOrder = 'Wrong order of values.'; ErrorMessage.ComplexNumberExpected = 'Complex number expected.'; ErrorMessage.ShouldBeIorJ = 'Should be \'i\' or \'j\'.'; ErrorMessage.SizeMismatch = 'Array dimensions mismatched.'; ErrorMessage.FunctionName = arg => `Function name ${arg} not recognized.`; ErrorMessage.NamedExpressionName = arg => `Named expression ${arg} not recognized.`; ErrorMessage.LicenseKey = arg => `License key is ${arg}.`; /***/ }), /* 62 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AdditionOp: () => (/* binding */ AdditionOp), /* harmony export */ ArrayLParen: () => (/* binding */ ArrayLParen), /* harmony export */ ArrayRParen: () => (/* binding */ ArrayRParen), /* harmony export */ BooleanOp: () => (/* binding */ BooleanOp), /* harmony export */ CellReference: () => (/* binding */ CellReference), /* harmony export */ ColumnRange: () => (/* binding */ ColumnRange), /* harmony export */ ConcatenateOp: () => (/* binding */ ConcatenateOp), /* harmony export */ DivOp: () => (/* binding */ DivOp), /* harmony export */ EqualsOp: () => (/* binding */ EqualsOp), /* harmony export */ ErrorLiteral: () => (/* binding */ ErrorLiteral), /* harmony export */ GreaterThanOp: () => (/* binding */ GreaterThanOp), /* harmony export */ GreaterThanOrEqualOp: () => (/* binding */ GreaterThanOrEqualOp), /* harmony export */ LParen: () => (/* binding */ LParen), /* harmony export */ LessThanOp: () => (/* binding */ LessThanOp), /* harmony export */ LessThanOrEqualOp: () => (/* binding */ LessThanOrEqualOp), /* harmony export */ MinusOp: () => (/* binding */ MinusOp), /* harmony export */ MultiplicationOp: () => (/* binding */ MultiplicationOp), /* harmony export */ NamedExpression: () => (/* binding */ NamedExpression), /* harmony export */ NotEqualOp: () => (/* binding */ NotEqualOp), /* harmony export */ PercentOp: () => (/* binding */ PercentOp), /* harmony export */ PlusOp: () => (/* binding */ PlusOp), /* harmony export */ PowerOp: () => (/* binding */ PowerOp), /* harmony export */ ProcedureName: () => (/* binding */ ProcedureName), /* harmony export */ RParen: () => (/* binding */ RParen), /* harmony export */ RangeSeparator: () => (/* binding */ RangeSeparator), /* harmony export */ RowRange: () => (/* binding */ RowRange), /* harmony export */ StringLiteral: () => (/* binding */ StringLiteral), /* harmony export */ TimesOp: () => (/* binding */ TimesOp), /* harmony export */ buildLexerConfig: () => (/* binding */ buildLexerConfig) /* harmony export */ }); /* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); /* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); /* harmony import */ var _CellReferenceMatcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63); /* harmony import */ var _NamedExpressionMatcher__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(64); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const AdditionOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'AdditionOp', pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA }); const PlusOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'PlusOp', pattern: /\+/, categories: AdditionOp }); const MinusOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'MinusOp', pattern: /-/, categories: AdditionOp }); const MultiplicationOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'MultiplicationOp', pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA }); const TimesOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'TimesOp', pattern: /\*/, categories: MultiplicationOp }); const DivOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'DivOp', pattern: /\//, categories: MultiplicationOp }); const PowerOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'PowerOp', pattern: /\^/ }); const PercentOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'PercentOp', pattern: /%/ }); const BooleanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'BooleanOp', pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA }); const EqualsOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'EqualsOp', pattern: /=/, categories: BooleanOp }); const NotEqualOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'NotEqualOp', pattern: /<>/, categories: BooleanOp }); const GreaterThanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'GreaterThanOp', pattern: />/, categories: BooleanOp }); const LessThanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'LessThanOp', pattern: /=/, categories: BooleanOp }); const LessThanOrEqualOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'LessThanOrEqualOp', pattern: /<=/, categories: BooleanOp }); const ConcatenateOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ConcatenateOp', pattern: /&/ }); const LParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'LParen', pattern: /\(/ }); const RParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'RParen', pattern: /\)/ }); const ArrayLParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ArrayLParen', pattern: /{/ }); const ArrayRParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ArrayRParen', pattern: /}/ }); const StringLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'StringLiteral', pattern: /"([^"\\]*(\\.[^"\\]*)*)"/ }); const ErrorLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ErrorLiteral', pattern: /#[A-Za-z0-9\/]+[?!]?/ }); const RangeSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'RangeSeparator', pattern: new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR) }); const ColumnRange = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ColumnRange', pattern: new RegExp(`${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.COLUMN_REFERENCE_PATTERN}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.COLUMN_REFERENCE_PATTERN}`) }); const RowRange = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'RowRange', pattern: new RegExp(`${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.ROW_REFERENCE_PATTERN}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.ROW_REFERENCE_PATTERN}`) }); const ProcedureName = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ProcedureName', pattern: new RegExp(`([${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.UNICODE_LETTER_PATTERN}][${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.NON_RESERVED_CHARACTER_PATTERN}]*)\\(`) }); const cellReferenceMatcher = new _CellReferenceMatcher__WEBPACK_IMPORTED_MODULE_2__.CellReferenceMatcher(); const CellReference = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'CellReference', pattern: cellReferenceMatcher.match.bind(cellReferenceMatcher), start_chars_hint: cellReferenceMatcher.POSSIBLE_START_CHARACTERS, line_breaks: false }); const namedExpressionMatcher = new _NamedExpressionMatcher__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionMatcher(); const NamedExpression = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'NamedExpression', pattern: namedExpressionMatcher.match.bind(namedExpressionMatcher), start_chars_hint: namedExpressionMatcher.POSSIBLE_START_CHARACTERS, line_breaks: false }); /** * Builds the configuration object for the lexer */ const buildLexerConfig = config => { const offsetProcedureNameLiteral = config.translationPackage.getFunctionTranslation('OFFSET'); const errorMapping = config.errorMapping; const functionMapping = config.translationPackage.buildFunctionMapping(); const whitespaceTokenRegexp = new RegExp(config.ignoreWhiteSpace === 'standard' ? _parser_consts__WEBPACK_IMPORTED_MODULE_1__.ODFF_WHITESPACE_PATTERN : _parser_consts__WEBPACK_IMPORTED_MODULE_1__.ALL_WHITESPACE_PATTERN); const WhiteSpace = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'WhiteSpace', pattern: whitespaceTokenRegexp }); const ArrayRowSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ArrayRowSep', pattern: config.arrayRowSeparator }); const ArrayColSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ArrayColSep', pattern: config.arrayColumnSeparator }); const NumberLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'NumberLiteral', pattern: new RegExp(`(([${config.decimalSeparator}]\\d+)|(\\d+([${config.decimalSeparator}]\\d*)?))(e[+-]?\\d+)?`) }); const OffsetProcedureName = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'OffsetProcedureName', pattern: new RegExp(offsetProcedureNameLiteral, 'i') }); let ArgSeparator; let inject; if (config.functionArgSeparator === config.arrayColumnSeparator) { ArgSeparator = ArrayColSeparator; inject = []; } else if (config.functionArgSeparator === config.arrayRowSeparator) { ArgSeparator = ArrayRowSeparator; inject = []; } else { ArgSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({ name: 'ArgSeparator', pattern: config.functionArgSeparator }); inject = [ArgSeparator]; } /* order is important, first pattern is used */ const allTokens = [WhiteSpace, PlusOp, MinusOp, TimesOp, DivOp, PowerOp, EqualsOp, NotEqualOp, PercentOp, GreaterThanOrEqualOp, LessThanOrEqualOp, GreaterThanOp, LessThanOp, LParen, RParen, ArrayLParen, ArrayRParen, OffsetProcedureName, ProcedureName, RangeSeparator, ...inject, ColumnRange, RowRange, NumberLiteral, StringLiteral, ErrorLiteral, ConcatenateOp, BooleanOp, AdditionOp, MultiplicationOp, CellReference, NamedExpression, ArrayRowSeparator, ArrayColSeparator]; return { ArgSeparator, NumberLiteral, OffsetProcedureName, ArrayRowSeparator, ArrayColSeparator, WhiteSpace, allTokens, errorMapping, functionMapping, decimalSeparator: config.decimalSeparator, maxColumns: config.maxColumns, maxRows: config.maxRows }; }; /***/ }), /* 63 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CellReferenceMatcher: () => (/* binding */ CellReferenceMatcher) /* harmony export */ }); /* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Helper class for recognizing CellReference token in text */ class CellReferenceMatcher { constructor() { this.POSSIBLE_START_CHARACTERS = [..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_UNICODE_LETTERS_ARRAY, ..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_DIGITS_ARRAY, _parser_consts__WEBPACK_IMPORTED_MODULE_0__.ABSOLUTE_OPERATOR, "'", '_']; this.cellReferenceRegexp = new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_0__.CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN, 'y'); } /** * Method used by the lexer to recognize CellReference token in text * * Note: using 'y' sticky flag for a named expression which is not supported on IE11... * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky */ match(text, startOffset) { this.cellReferenceRegexp.lastIndex = startOffset; const execResult = this.cellReferenceRegexp.exec(text + '@'); if (execResult == null || execResult[1] == null) { return null; } execResult[0] = execResult[1]; return execResult; } } /***/ }), /* 64 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ NamedExpressionMatcher: () => (/* binding */ NamedExpressionMatcher) /* harmony export */ }); /* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Helper class for recognizing NamedExpression token in text */ class NamedExpressionMatcher { constructor() { this.POSSIBLE_START_CHARACTERS = [..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_UNICODE_LETTERS_ARRAY, '_']; this.namedExpressionRegexp = new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_0__.NAMED_EXPRESSION_PATTERN, 'y'); this.r1c1CellRefRegexp = new RegExp(`^${_parser_consts__WEBPACK_IMPORTED_MODULE_0__.R1C1_CELL_REFERENCE_PATTERN}$`); } /** * Method used by the lexer to recognize NamedExpression token in text * * Note: using 'y' sticky flag for a named expression which is not supported on IE11... * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky */ match(text, startOffset) { this.namedExpressionRegexp.lastIndex = startOffset; const execResult = this.namedExpressionRegexp.exec(text); if (execResult == null || execResult[0] == null) { return null; } if (this.r1c1CellRefRegexp.test(execResult[0])) { return null; } return execResult; } } /***/ }), /* 65 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Unparser: () => (/* binding */ Unparser), /* harmony export */ formatNumber: () => (/* binding */ formatNumber) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); /* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); /* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(57); /* harmony import */ var _binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(58); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class Unparser { constructor(config, lexerConfig, sheetMappingFn, namedExpressions) { this.config = config; this.lexerConfig = lexerConfig; this.sheetMappingFn = sheetMappingFn; this.namedExpressions = namedExpressions; } unparse(ast, address) { return '=' + this.unparseAst(ast, address); } unparseAst(ast, address) { var _a, _b; switch (ast.type) { case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('', ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(formatNumber(ast.value, this.config.decimalSeparator), ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.STRING: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('"' + ast.value + '"', ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.FUNCTION_CALL: { const args = ast.args.map(arg => arg !== undefined ? this.unparseAst(arg, address) : '').join(this.config.functionArgSeparator); const procedureName = this.config.translationPackage.isFunctionTranslated(ast.procedureName) ? this.config.translationPackage.getFunctionTranslation(ast.procedureName) : ast.procedureName; const rightPart = procedureName + '(' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(')', ast.internalWhitespace); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(rightPart, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NAMED_EXPRESSION: { const originalNamedExpressionName = (_a = this.namedExpressions.nearestNamedExpression(ast.expressionName, address.sheet)) === null || _a === void 0 ? void 0 : _a.displayName; return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(originalNamedExpressionName || ast.expressionName, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE: { let image; if (ast.reference.sheet !== undefined) { image = this.unparseSheetName(ast.reference.sheet) + '!'; } else { image = ''; } image += (_b = ast.reference.unparse(address)) !== null && _b !== void 0 ? _b : this.config.translationPackage.getErrorTranslation(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(image, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE: case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE: case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(this.formatRange(ast, address), ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_UNARY_OP: { const unparsedExpr = this.unparseAst(ast.value, address); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('+', ast.leadingWhitespace) + unparsedExpr; } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_UNARY_OP: { const unparsedExpr = this.unparseAst(ast.value, address); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('-', ast.leadingWhitespace) + unparsedExpr; } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PERCENT_OP: { return this.unparseAst(ast.value, address) + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('%', ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ERROR: { const image = this.config.translationPackage.getErrorTranslation(ast.error ? ast.error.type : _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.ERROR); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(image, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ERROR_WITH_RAW_INPUT: { return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(ast.rawInput, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS: { const expression = this.unparseAst(ast.expression, address); const rightPart = '(' + expression + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(')', ast.internalWhitespace); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(rightPart, ast.leadingWhitespace); } case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ARRAY: { const ret = '{' + ast.args.map(row => row.map(val => this.unparseAst(val, address)).join(this.config.arrayColumnSeparator)).join(this.config.arrayRowSeparator) + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('}', ast.internalWhitespace); return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(ret, ast.leadingWhitespace); } default: { const left = this.unparseAst(ast.left, address); const right = this.unparseAst(ast.right, address); return left + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(_binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_4__.binaryOpTokenMap[ast.type], ast.leadingWhitespace) + right; } } } unparseSheetName(sheetId) { const sheetName = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_2__.sheetIndexToString)(sheetId, this.sheetMappingFn); if (sheetName === undefined) { throw new _index__WEBPACK_IMPORTED_MODULE_1__.NoSheetWithIdError(sheetId); } return sheetName; } formatRange(ast, baseAddress) { let startSheeet = ''; let endSheet = ''; if (ast.start.sheet !== undefined && ast.sheetReferenceType !== _Ast__WEBPACK_IMPORTED_MODULE_3__.RangeSheetReferenceType.RELATIVE) { startSheeet = this.unparseSheetName(ast.start.sheet) + '!'; } if (ast.end.sheet !== undefined && ast.sheetReferenceType === _Ast__WEBPACK_IMPORTED_MODULE_3__.RangeSheetReferenceType.BOTH_ABSOLUTE) { endSheet = this.unparseSheetName(ast.end.sheet) + '!'; } const unparsedStart = ast.start.unparse(baseAddress); const unparsedEnd = ast.end.unparse(baseAddress); if (unparsedStart === undefined || unparsedEnd === undefined) { return this.config.translationPackage.getErrorTranslation(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF); } return `${startSheeet}${unparsedStart}:${endSheet}${unparsedEnd}`; } } function formatNumber(number, decimalSeparator) { const numericString = number.toString(); return numericString.replace('.', decimalSeparator); } /***/ }), /* 66 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ collectDependencies: () => (/* binding */ collectDependencies) /* harmony export */ }); /* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const collectDependenciesFn = (ast, functionRegistry, dependenciesSet, needArgument) => { switch (ast.type) { case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EMPTY: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NUMBER: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.STRING: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR: return; case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NAMED_EXPRESSION: { if (needArgument) { dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.NamedExpressionDependency(ast.expressionName)); } return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_REFERENCE: { if (needArgument) { dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.AddressDependency(ast.reference)); } return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_RANGE: { if (needArgument && ast.start.sheet === ast.end.sheet) { dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.CellRangeDependency(ast.start, ast.end)); } return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.COLUMN_RANGE: { if (needArgument && ast.start.sheet === ast.end.sheet) { dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.ColumnRangeDependency(ast.start, ast.end)); } return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ROW_RANGE: { if (needArgument && ast.start.sheet === ast.end.sheet) { dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.RowRangeDependency(ast.start, ast.end)); } return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PERCENT_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_UNARY_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_UNARY_OP: { collectDependenciesFn(ast.value, functionRegistry, dependenciesSet, true); return; } case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP: case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP: collectDependenciesFn(ast.left, functionRegistry, dependenciesSet, true); collectDependenciesFn(ast.right, functionRegistry, dependenciesSet, true); return; case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PARENTHESIS: collectDependenciesFn(ast.expression, functionRegistry, dependenciesSet, needArgument); return; case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.FUNCTION_CALL: { const functionNeedArgument = !functionRegistry.doesFunctionNeedArgumentToBeComputed(ast.procedureName); ast.args.forEach(argAst => collectDependenciesFn(argAst, functionRegistry, dependenciesSet, functionNeedArgument)); return; } } }; const collectDependencies = (ast, functionRegistry) => { const result = new Array(); collectDependenciesFn(ast, functionRegistry, result, true); return result; }; /***/ }), /* 67 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddressDependency: () => (/* binding */ AddressDependency), /* harmony export */ CellRangeDependency: () => (/* binding */ CellRangeDependency), /* harmony export */ ColumnRangeDependency: () => (/* binding */ ColumnRangeDependency), /* harmony export */ NamedExpressionDependency: () => (/* binding */ NamedExpressionDependency), /* harmony export */ RowRangeDependency: () => (/* binding */ RowRangeDependency) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AddressDependency { constructor(dependency) { this.dependency = dependency; } absolutize(baseAddress) { return this.dependency.toSimpleCellAddress(baseAddress); } } class CellRangeDependency { constructor(start, end) { this.start = start; this.end = end; } absolutize(baseAddress) { return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(this.start.toSimpleCellAddress(baseAddress), this.end.toSimpleCellAddress(baseAddress)); } } class ColumnRangeDependency { constructor(start, end) { this.start = start; this.end = end; } absolutize(baseAddress) { const start = this.start.toSimpleColumnAddress(baseAddress); const end = this.end.toSimpleColumnAddress(baseAddress); return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteColumnRange(start.sheet, start.col, end.col); } } class RowRangeDependency { constructor(start, end) { this.start = start; this.end = end; } absolutize(baseAddress) { const start = this.start.toSimpleRowAddress(baseAddress); const end = this.end.toSimpleRowAddress(baseAddress); return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteRowRange(start.sheet, start.row, end.row); } } class NamedExpressionDependency { constructor(name) { this.name = name; } absolutize(_baseAddress) { return this; } } /***/ }), /* 68 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ContentChanges: () => (/* binding */ ContentChanges) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ContentChanges { constructor() { this.changes = new Map(); } static empty() { return new ContentChanges(); } addAll(other) { for (const change of other.changes.values()) { this.add(change.address, change); } return this; } addChange(newValue, address, oldValue) { this.addInterpreterValue(newValue, address, oldValue); } exportChanges(exporter) { let ret = []; this.changes.forEach(e => { const change = exporter.exportChange(e); if (Array.isArray(change)) { ret = ret.concat(change); } else { ret.push(change); } }); return ret; } getChanges() { return Array.from(this.changes.values()); } isEmpty() { return this.changes.size === 0; } add(address, change) { const value = change.value; if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_1__.SimpleRangeValue) { for (const cellAddress of value.effectiveAddressesFromData(address)) { this.changes.delete((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(cellAddress)); } } this.changes.set((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(address), change); } addInterpreterValue(value, address, oldValue) { this.add(address, { address, value, oldValue }); } } /***/ }), /* 69 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SimpleRangeValue: () => (/* binding */ SimpleRangeValue) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * A class that represents a range of data. */ class SimpleRangeValue { /** * In most cases, it's more convenient to create a `SimpleRangeValue` object * by calling one of the [static factory methods](#fromrange). */ constructor(_data, /** * A property that represents the address of the range. */ range, dependencyGraph, _hasOnlyNumbers) { this._data = _data; this.range = range; this.dependencyGraph = dependencyGraph; this._hasOnlyNumbers = _hasOnlyNumbers; this.size = _data === undefined ? new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(range.effectiveWidth(dependencyGraph), range.effectiveHeight(dependencyGraph)) : new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(_data[0].length, _data.length); } /** * Returns the range data as a 2D array. */ get data() { this.ensureThatComputed(); return this._data; } /** * A factory method. Returns a `SimpleRangeValue` object with the provided range address and the provided data. */ static fromRange(data, range, dependencyGraph) { return new SimpleRangeValue(data, range, dependencyGraph, true); } /** * A factory method. Returns a `SimpleRangeValue` object with the provided numeric data. */ static onlyNumbers(data) { return new SimpleRangeValue(data, undefined, undefined, true); } /** * A factory method. Returns a `SimpleRangeValue` object with the provided data. */ static onlyValues(data) { return new SimpleRangeValue(data, undefined, undefined, undefined); } /** * A factory method. Returns a `SimpleRangeValue` object with the provided range address. */ static onlyRange(range, dependencyGraph) { return new SimpleRangeValue(undefined, range, dependencyGraph, undefined); } /** * A factory method. Returns a `SimpleRangeValue` object that contains a single value. */ static fromScalar(scalar) { return new SimpleRangeValue([[scalar]], undefined, undefined, undefined); } /** * Returns `true` if and only if the `SimpleRangeValue` has no address set. */ isAdHoc() { return this.range === undefined; } /** * Returns the number of columns contained in the range. */ width() { return this.size.width; } /** * Returns the number of rows contained in the range. */ height() { return this.size.height; } /** * Returns the range data as a 1D array. */ valuesFromTopLeftCorner() { this.ensureThatComputed(); const ret = []; for (let i = 0; i < this._data.length; i++) { for (let j = 0; j < this._data[0].length; j++) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion ret.push(this._data[i][j]); } } return ret; } /** * Generates the addresses of the cells contained in the range assuming the provided address is the left corner of the range. */ *effectiveAddressesFromData(leftCorner) { for (let row = 0; row < this.data.length; ++row) { const rowData = this.data[row]; for (let col = 0; col < rowData.length; ++col) { yield (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row); } } } /** * Generates values and addresses of the cells contained in the range assuming the provided address is the left corner of the range. * * This method combines the functionalities of [`iterateValuesFromTopLeftCorner()`](#iteratevaluesfromtopleftcorner) and [`effectiveAddressesFromData()`](#effectiveaddressesfromdata). */ *entriesFromTopLeftCorner(leftCorner) { this.ensureThatComputed(); for (let row = 0; row < this.size.height; ++row) { for (let col = 0; col < this.size.width; ++col) { yield [this._data[row][col], (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row)]; } } } /** * Generates the values of the cells contained in the range assuming the provided address is the left corner of the range. */ *iterateValuesFromTopLeftCorner() { yield* this.valuesFromTopLeftCorner(); } /** * Returns the number of cells contained in the range. */ numberOfElements() { return this.size.width * this.size.height; } /** * Returns `true` if and only if the range contains only numeric values. */ hasOnlyNumbers() { if (this._hasOnlyNumbers === undefined) { this._hasOnlyNumbers = true; for (const row of this.data) { for (const v of row) { if (typeof v !== 'number') { this._hasOnlyNumbers = false; return false; } } } } return this._hasOnlyNumbers; } /** * Returns the range data as a 2D array of numbers. * * Internal use only. */ rawNumbers() { return this._data; } /** * Returns the range data as a 2D array. * * Internal use only. */ rawData() { var _a; this.ensureThatComputed(); return (_a = this._data) !== null && _a !== void 0 ? _a : []; } /** * Returns `true` if and only if the range has the same width and height as the `other` range object. */ sameDimensionsAs(other) { return this.width() === other.width() && this.height() === other.height(); } /** * Computes the range data if it is not computed yet. */ ensureThatComputed() { if (this._data !== undefined) { return; } this._hasOnlyNumbers = true; this._data = this.range.addressesArrayMap(this.dependencyGraph, cellFromRange => { const value = this.dependencyGraph.getCellValue(cellFromRange); if (value instanceof SimpleRangeValue) { this._hasOnlyNumbers = false; return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ScalarExpected); } else if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(value)) { return value; } else { this._hasOnlyNumbers = false; return value; } }); } } /***/ }), /* 70 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CurrencyNumber: () => (/* binding */ CurrencyNumber), /* harmony export */ DateNumber: () => (/* binding */ DateNumber), /* harmony export */ DateTimeNumber: () => (/* binding */ DateTimeNumber), /* harmony export */ EmptyValue: () => (/* binding */ EmptyValue), /* harmony export */ NumberType: () => (/* binding */ NumberType), /* harmony export */ PercentNumber: () => (/* binding */ PercentNumber), /* harmony export */ RichNumber: () => (/* binding */ RichNumber), /* harmony export */ TimeNumber: () => (/* binding */ TimeNumber), /* harmony export */ cloneNumber: () => (/* binding */ cloneNumber), /* harmony export */ getFormatOfExtendedNumber: () => (/* binding */ getFormatOfExtendedNumber), /* harmony export */ getRawValue: () => (/* binding */ getRawValue), /* harmony export */ getTypeFormatOfExtendedNumber: () => (/* binding */ getTypeFormatOfExtendedNumber), /* harmony export */ getTypeOfExtendedNumber: () => (/* binding */ getTypeOfExtendedNumber), /* harmony export */ isExtendedNumber: () => (/* binding */ isExtendedNumber) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * A symbol representing an empty cell value. */ const EmptyValue = Symbol('Empty value'); function getRawValue(num) { if (num instanceof RichNumber) { return num.val; } else { return num; } } class RichNumber { constructor(val, format) { this.val = val; this.format = format; } fromNumber(val) { // eslint-disable-next-line @typescript-eslint/no-unsafe-call return new this.constructor(val); } } function cloneNumber(val, newVal) { if (typeof val === 'number') { return newVal; } else { const ret = val.fromNumber(newVal); ret.format = val.format; return ret; } } class DateNumber extends RichNumber { getDetailedType() { return NumberType.NUMBER_DATE; } } class CurrencyNumber extends RichNumber { getDetailedType() { return NumberType.NUMBER_CURRENCY; } } class TimeNumber extends RichNumber { getDetailedType() { return NumberType.NUMBER_TIME; } } class DateTimeNumber extends RichNumber { getDetailedType() { return NumberType.NUMBER_DATETIME; } } class PercentNumber extends RichNumber { getDetailedType() { return NumberType.NUMBER_PERCENT; } } function isExtendedNumber(val) { return typeof val === 'number' || val instanceof RichNumber; } var NumberType; (function (NumberType) { NumberType["NUMBER_RAW"] = "NUMBER_RAW"; NumberType["NUMBER_DATE"] = "NUMBER_DATE"; NumberType["NUMBER_TIME"] = "NUMBER_TIME"; NumberType["NUMBER_DATETIME"] = "NUMBER_DATETIME"; NumberType["NUMBER_CURRENCY"] = "NUMBER_CURRENCY"; NumberType["NUMBER_PERCENT"] = "NUMBER_PERCENT"; })(NumberType || (NumberType = {})); function getTypeOfExtendedNumber(num) { if (num instanceof RichNumber) { return num.getDetailedType(); } else { return NumberType.NUMBER_RAW; } } function getFormatOfExtendedNumber(num) { if (num instanceof RichNumber) { return num.format; } else { return undefined; } } function getTypeFormatOfExtendedNumber(num) { if (num instanceof RichNumber) { return { type: num.getDetailedType(), format: num.format }; } else { return { type: NumberType.NUMBER_RAW }; } } /***/ }), /* 71 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ColumnsSpan: () => (/* binding */ ColumnsSpan), /* harmony export */ RowsSpan: () => (/* binding */ RowsSpan) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /* * A class representing a set of rows in specific sheet */ class RowsSpan { constructor(sheet, rowStart, rowEnd) { this.sheet = sheet; this.rowStart = rowStart; this.rowEnd = rowEnd; if (rowStart < 0) { throw Error('Starting row cant be less than 0'); } if (rowEnd < rowStart) { throw Error('Row span cant end before start'); } } get numberOfRows() { return this.rowEnd - this.rowStart + 1; } get start() { return this.rowStart; } get end() { return this.rowEnd; } static fromNumberOfRows(sheet, rowStart, numberOfRows) { return new RowsSpan(sheet, rowStart, rowStart + numberOfRows - 1); } static fromRowStartAndEnd(sheet, rowStart, rowEnd) { return new RowsSpan(sheet, rowStart, rowEnd); } *rows() { for (let col = this.rowStart; col <= this.rowEnd; ++col) { yield col; } } intersect(otherSpan) { if (this.sheet !== otherSpan.sheet) { throw Error('Can\'t intersect spans from different sheets'); } const start = Math.max(this.rowStart, otherSpan.rowStart); const end = Math.min(this.rowEnd, otherSpan.rowEnd); if (start > end) { return null; } return new RowsSpan(this.sheet, start, end); } firstRow() { return new RowsSpan(this.sheet, this.rowStart, this.rowStart); } } /* * A class representing a set of columns in specific sheet */ class ColumnsSpan { constructor(sheet, columnStart, columnEnd) { this.sheet = sheet; this.columnStart = columnStart; this.columnEnd = columnEnd; if (columnStart < 0) { throw Error('Starting column cant be less than 0'); } if (columnEnd < columnStart) { throw Error('Column span cant end before start'); } } get numberOfColumns() { return this.columnEnd - this.columnStart + 1; } get start() { return this.columnStart; } get end() { return this.columnEnd; } static fromNumberOfColumns(sheet, columnStart, numberOfColumns) { return new ColumnsSpan(sheet, columnStart, columnStart + numberOfColumns - 1); } static fromColumnStartAndEnd(sheet, columnStart, columnEnd) { return new ColumnsSpan(sheet, columnStart, columnEnd); } *columns() { for (let col = this.columnStart; col <= this.columnEnd; ++col) { yield col; } } intersect(otherSpan) { if (this.sheet !== otherSpan.sheet) { throw Error('Can\'t intersect spans from different sheets'); } const start = Math.max(this.columnStart, otherSpan.columnStart); const end = Math.min(this.columnEnd, otherSpan.columnEnd); if (start > end) { return null; } return new ColumnsSpan(this.sheet, start, end); } firstColumn() { return new ColumnsSpan(this.sheet, this.columnStart, this.columnStart); } } /***/ }), /* 72 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EmptyStatistics: () => (/* reexport safe */ _EmptyStatistics__WEBPACK_IMPORTED_MODULE_0__.EmptyStatistics), /* harmony export */ StatType: () => (/* reexport safe */ _StatType__WEBPACK_IMPORTED_MODULE_2__.StatType), /* harmony export */ Statistics: () => (/* reexport safe */ _Statistics__WEBPACK_IMPORTED_MODULE_1__.Statistics) /* harmony export */ }); /* harmony import */ var _EmptyStatistics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73); /* harmony import */ var _Statistics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(74); /* harmony import */ var _StatType__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(75); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /***/ }), /* 73 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EmptyStatistics: () => (/* binding */ EmptyStatistics) /* harmony export */ }); /* harmony import */ var _Statistics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(74); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** Do not store stats in the memory. Stats are not needed on daily basis */ class EmptyStatistics extends _Statistics__WEBPACK_IMPORTED_MODULE_0__.Statistics { /** @inheritDoc */ incrementCriterionFunctionFullCacheUsed() { // do nothing } /** @inheritDoc */ incrementCriterionFunctionPartialCacheUsed() { // do nothing } /** @inheritDoc */ start(_name) { // do nothing } /** @inheritDoc */ end(_name) { // do nothing } } /***/ }), /* 74 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Statistics: () => (/* binding */ Statistics) /* harmony export */ }); /* harmony import */ var _StatType__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(75); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Provides tracking performance statistics to the engine */ class Statistics { constructor() { this.stats = new Map([[_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, 0], [_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, 0]]); this.startTimes = new Map(); } incrementCriterionFunctionFullCacheUsed() { var _a; const newValue = ((_a = this.stats.get(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED)) !== null && _a !== void 0 ? _a : 0) + 1; this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, newValue); } incrementCriterionFunctionPartialCacheUsed() { var _a; const newValue = ((_a = this.stats.get(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED)) !== null && _a !== void 0 ? _a : 0) + 1; this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, newValue); } /** * Resets statistics */ reset() { this.stats.clear(); this.startTimes.clear(); this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, 0); this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, 0); } /** * Starts tracking particular statistic. * * @param name - statistic to start tracking */ start(name) { if (this.startTimes.get(name)) { throw Error(`Statistics ${name} already started`); } else { this.startTimes.set(name, Date.now()); } } /** * Stops tracking particular statistic. * Raise error if tracking statistic wasn't started. * * @param name - statistic to stop tracking */ end(name) { var _a; const now = Date.now(); const startTime = this.startTimes.get(name); if (startTime) { let values = (_a = this.stats.get(name)) !== null && _a !== void 0 ? _a : 0; values += now - startTime; this.stats.set(name, values); this.startTimes.delete(name); } else { throw Error(`Statistics ${name} not started`); } } /** * Measure given statistic as execution of given function. * * @param name - statistic to track * @param func - function to call * @returns result of the function call */ measure(name, func) { this.start(name); const result = func(); this.end(name); return result; } /** * Returns the snapshot of current results */ snapshot() { return new Map(this.stats); } } /***/ }), /* 75 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ StatType: () => (/* binding */ StatType) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var StatType; (function (StatType) { /* build engine */ StatType["BUILD_ENGINE_TOTAL"] = "BUILD_ENGINE_TOTAL"; StatType["PARSER"] = "PARSER"; StatType["GRAPH_BUILD"] = "GRAPH_BUILD"; StatType["COLLECT_DEPENDENCIES"] = "COLLECT_DEPENDENCIES"; StatType["PROCESS_DEPENDENCIES"] = "PROCESS_DEPENDENCIES"; StatType["TOP_SORT"] = "TOP_SORT"; StatType["BUILD_COLUMN_INDEX"] = "BUILD_COLUMN_INDEX"; StatType["EVALUATION"] = "EVALUATION"; StatType["VLOOKUP"] = "VLOOKUP"; /* crud adjustments */ StatType["TRANSFORM_ASTS"] = "TRANSFORM_ASTS"; StatType["TRANSFORM_ASTS_POSTPONED"] = "TRANSFORM_ASTS_POSTPONED"; StatType["ADJUSTING_ADDRESS_MAPPING"] = "ADJUSTING_ADDRESS_MAPPING"; StatType["ADJUSTING_ARRAY_MAPPING"] = "ADJUSTING_ARRAY_MAPPING"; StatType["ADJUSTING_RANGES"] = "ADJUSTING_RANGES"; StatType["ADJUSTING_GRAPH"] = "ADJUSTING_GRAPH"; /* criterion cache */ StatType["CRITERION_FUNCTION_FULL_CACHE_USED"] = "CRITERION_FUNCTION_FULL_CACHE_USED"; StatType["CRITERION_FUNCTION_PARTIAL_CACHE_USED"] = "CRITERION_FUNCTION_PARTIAL_CACHE_USED"; })(StatType || (StatType = {})); /***/ }), /* 76 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddressMapping: () => (/* binding */ AddressMapping) /* harmony export */ }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70); /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AddressMapping { constructor(policy) { this.policy = policy; this.mapping = new Map(); } /** @inheritDoc */ getCell(address) { const sheetMapping = this.mapping.get(address.sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(address.sheet); } return sheetMapping.getCell(address); } fetchCell(address) { const sheetMapping = this.mapping.get(address.sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(address.sheet); } const vertex = sheetMapping.getCell(address); if (!vertex) { throw Error('Vertex for address missing in AddressMapping'); } return vertex; } strategyFor(sheetId) { const strategy = this.mapping.get(sheetId); if (strategy === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId); } return strategy; } addSheet(sheetId, strategy) { if (this.mapping.has(sheetId)) { throw Error('Sheet already added'); } this.mapping.set(sheetId, strategy); } autoAddSheet(sheetId, sheetBoundaries) { const { height, width, fill } = sheetBoundaries; const strategyConstructor = this.policy.call(fill); this.addSheet(sheetId, new strategyConstructor(width, height)); } getCellValue(address) { const vertex = this.getCell(address); if (vertex === undefined) { return _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue; } else if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ArrayVertex) { return vertex.getArrayCellValue(address); } else { return vertex.getCellValue(); } } getRawValue(address) { const vertex = this.getCell(address); if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ValueCellVertex) { return vertex.getValues().rawValue; } else if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ArrayVertex) { return vertex.getArrayCellRawValue(address); } else { return null; } } /** @inheritDoc */ setCell(address, newVertex) { const sheetMapping = this.mapping.get(address.sheet); if (!sheetMapping) { throw Error('Sheet not initialized'); } sheetMapping.setCell(address, newVertex); } moveCell(source, destination) { const sheetMapping = this.mapping.get(source.sheet); if (!sheetMapping) { throw Error('Sheet not initialized.'); } if (source.sheet !== destination.sheet) { throw Error('Cannot move cells between sheets.'); } if (sheetMapping.has(destination)) { throw new Error('Cannot move cell. Destination already occupied.'); } const vertex = sheetMapping.getCell(source); if (vertex === undefined) { throw new Error('Cannot move cell. No cell with such address.'); } this.setCell(destination, vertex); this.removeCell(source); } removeCell(address) { const sheetMapping = this.mapping.get(address.sheet); if (!sheetMapping) { throw Error('Sheet not initialized'); } sheetMapping.removeCell(address); } /** @inheritDoc */ has(address) { const sheetMapping = this.mapping.get(address.sheet); if (sheetMapping === undefined) { return false; } return sheetMapping.has(address); } /** @inheritDoc */ getHeight(sheetId) { const sheetMapping = this.mapping.get(sheetId); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId); } return sheetMapping.getHeight(); } /** @inheritDoc */ getWidth(sheetId) { const sheetMapping = this.mapping.get(sheetId); if (!sheetMapping) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId); } return sheetMapping.getWidth(); } addRows(sheet, row, numberOfRows) { const sheetMapping = this.mapping.get(sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet); } sheetMapping.addRows(row, numberOfRows); } removeRows(removedRows) { const sheetMapping = this.mapping.get(removedRows.sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(removedRows.sheet); } sheetMapping.removeRows(removedRows); } removeSheet(sheetId) { this.mapping.delete(sheetId); } addColumns(sheet, column, numberOfColumns) { const sheetMapping = this.mapping.get(sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet); } sheetMapping.addColumns(column, numberOfColumns); } removeColumns(removedColumns) { const sheetMapping = this.mapping.get(removedColumns.sheet); if (sheetMapping === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(removedColumns.sheet); } sheetMapping.removeColumns(removedColumns); } *verticesFromRowsSpan(rowsSpan) { yield* this.mapping.get(rowsSpan.sheet).verticesFromRowsSpan(rowsSpan); // eslint-disable-line @typescript-eslint/no-non-null-assertion } *verticesFromColumnsSpan(columnsSpan) { yield* this.mapping.get(columnsSpan.sheet).verticesFromColumnsSpan(columnsSpan); // eslint-disable-line @typescript-eslint/no-non-null-assertion } *entriesFromRowsSpan(rowsSpan) { yield* this.mapping.get(rowsSpan.sheet).entriesFromRowsSpan(rowsSpan); } *entriesFromColumnsSpan(columnsSpan) { yield* this.mapping.get(columnsSpan.sheet).entriesFromColumnsSpan(columnsSpan); } *entries() { for (const [sheet, mapping] of this.mapping.entries()) { yield* mapping.getEntries(sheet); } } *sheetEntries(sheet) { const sheetMapping = this.mapping.get(sheet); if (sheetMapping !== undefined) { yield* sheetMapping.getEntries(sheet); } else { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet); } } } /***/ }), /* 77 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AliasAlreadyExisting: () => (/* binding */ AliasAlreadyExisting), /* harmony export */ ConfigValueEmpty: () => (/* binding */ ConfigValueEmpty), /* harmony export */ ConfigValueTooBigError: () => (/* binding */ ConfigValueTooBigError), /* harmony export */ ConfigValueTooSmallError: () => (/* binding */ ConfigValueTooSmallError), /* harmony export */ EvaluationSuspendedError: () => (/* binding */ EvaluationSuspendedError), /* harmony export */ ExpectedOneOfValuesError: () => (/* binding */ ExpectedOneOfValuesError), /* harmony export */ ExpectedValueOfTypeError: () => (/* binding */ ExpectedValueOfTypeError), /* harmony export */ FunctionPluginValidationError: () => (/* binding */ FunctionPluginValidationError), /* harmony export */ InvalidAddressError: () => (/* binding */ InvalidAddressError), /* harmony export */ InvalidArgumentsError: () => (/* binding */ InvalidArgumentsError), /* harmony export */ LanguageAlreadyRegisteredError: () => (/* binding */ LanguageAlreadyRegisteredError), /* harmony export */ LanguageNotRegisteredError: () => (/* binding */ LanguageNotRegisteredError), /* harmony export */ MissingTranslationError: () => (/* binding */ MissingTranslationError), /* harmony export */ NamedExpressionDoesNotExistError: () => (/* binding */ NamedExpressionDoesNotExistError), /* harmony export */ NamedExpressionNameIsAlreadyTakenError: () => (/* binding */ NamedExpressionNameIsAlreadyTakenError), /* harmony export */ NamedExpressionNameIsInvalidError: () => (/* binding */ NamedExpressionNameIsInvalidError), /* harmony export */ NoOperationToRedoError: () => (/* binding */ NoOperationToRedoError), /* harmony export */ NoOperationToUndoError: () => (/* binding */ NoOperationToUndoError), /* harmony export */ NoRelativeAddressesAllowedError: () => (/* binding */ NoRelativeAddressesAllowedError), /* harmony export */ NoSheetWithIdError: () => (/* binding */ NoSheetWithIdError), /* harmony export */ NoSheetWithNameError: () => (/* binding */ NoSheetWithNameError), /* harmony export */ NotAFormulaError: () => (/* binding */ NotAFormulaError), /* harmony export */ NothingToPasteError: () => (/* binding */ NothingToPasteError), /* harmony export */ ProtectedFunctionError: () => (/* binding */ ProtectedFunctionError), /* harmony export */ ProtectedFunctionTranslationError: () => (/* binding */ ProtectedFunctionTranslationError), /* harmony export */ SheetNameAlreadyTakenError: () => (/* binding */ SheetNameAlreadyTakenError), /* harmony export */ SheetSizeLimitExceededError: () => (/* binding */ SheetSizeLimitExceededError), /* harmony export */ SheetsNotEqual: () => (/* binding */ SheetsNotEqual), /* harmony export */ SourceLocationHasArrayError: () => (/* binding */ SourceLocationHasArrayError), /* harmony export */ TargetLocationHasArrayError: () => (/* binding */ TargetLocationHasArrayError), /* harmony export */ UnableToParseError: () => (/* binding */ UnableToParseError) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Error thrown when the sheet of a given ID does not exist. */ class NoSheetWithIdError extends Error { constructor(sheetId) { super(`There's no sheet with id = ${sheetId}`); } } /** * Error thrown when the sheet of a given name does not exist. */ class NoSheetWithNameError extends Error { constructor(sheetName) { super(`There's no sheet with name '${sheetName}'`); } } /** * Error thrown when the sheet of a given name already exists. */ class SheetNameAlreadyTakenError extends Error { constructor(sheetName) { super(`Sheet with name ${sheetName} already exists`); } } /** * Error thrown when loaded sheet size exceeds configured limits. */ class SheetSizeLimitExceededError extends Error { constructor() { super('Sheet size limit exceeded'); } } /** * Error thrown when the the provided string is not a valid formula, i.e does not start with "=" */ class NotAFormulaError extends Error { constructor() { super('This is not a formula'); } } /** * Error thrown when the given address is invalid. */ class InvalidAddressError extends Error { constructor(address) { super(`Address (row = ${address.row}, col = ${address.col}) is invalid`); } } /** * Error thrown when the given arguments are invalid */ class InvalidArgumentsError extends Error { constructor(expectedArguments) { super(`Invalid arguments, expected ${expectedArguments}`); } } /** * Error thrown when the given sheets are not equal. */ class SheetsNotEqual extends Error { constructor(sheet1, sheet2) { super(`Sheets ${sheet1} and ${sheet2} are not equal.`); } } /** * Error thrown when the given named expression already exists in the workbook and therefore it cannot be added. */ class NamedExpressionNameIsAlreadyTakenError extends Error { constructor(expressionName) { super(`Name of Named Expression '${expressionName}' is already present`); } } /** * Error thrown when the name given for the named expression is invalid. */ class NamedExpressionNameIsInvalidError extends Error { constructor(expressionName) { super(`Name of Named Expression '${expressionName}' is invalid`); } } /** * Error thrown when the given named expression does not exist. */ class NamedExpressionDoesNotExistError extends Error { constructor(expressionName) { super(`Named Expression '${expressionName}' does not exist`); } } /** * Error thrown when there are no operations to be undone by the [[undo]] method. */ class NoOperationToUndoError extends Error { constructor() { super('There is no operation to undo'); } } /** * Error thrown when there are no operations to redo by the [[redo]] method. */ class NoOperationToRedoError extends Error { constructor() { super('There is no operation to redo'); } } /** * Error thrown when there is nothing to paste by the [[paste]] method. */ class NothingToPasteError extends Error { constructor() { super('There is nothing to paste'); } } function replacer(key, val) { switch (typeof val) { case 'function': case 'symbol': return val.toString(); case 'bigint': return 'BigInt(' + val.toString() + ')'; default: { if (val instanceof RegExp) { return 'RegExp(' + val.toString() + ')'; } else { return val; } } } } /** * Error thrown when the given value cannot be parsed. * * Checks against the validity in: * * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[setCellsContents]] */ class UnableToParseError extends Error { constructor(value) { super(`Unable to parse value: ${JSON.stringify(value, replacer, 4)}`); } } /** * Error thrown when the expected value type differs from the given value type. * It also displays the expected type. * This error might be thrown while setting or updating the [[ConfigParams]]. * The following methods accept [[ConfigParams]] as a parameter: * * @see [[buildEmpty]] * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[updateConfig]] */ class ExpectedValueOfTypeError extends Error { constructor(expectedType, paramName) { super(`Expected value of type: ${expectedType} for config parameter: ${paramName}`); } } /** * Error thrown when supplied config parameter value is an empty string. * This error might be thrown while setting or updating the [[ConfigParams]]. * The following methods accept [[ConfigParams]] as a parameter: * * @see [[buildEmpty]] * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[updateConfig]] */ class ConfigValueEmpty extends Error { constructor(paramName) { super(`Config parameter ${paramName} cannot be empty.`); } } /** * Error thrown when supplied config parameter value is too small. * This error might be thrown while setting or updating the [[ConfigParams]]. * The following methods accept [[ConfigParams]] as a parameter: * * @see [[buildEmpty]] * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[updateConfig]] */ class ConfigValueTooSmallError extends Error { constructor(paramName, minimum) { super(`Config parameter ${paramName} should be at least ${minimum}`); } } /** * Error thrown when supplied config parameter value is too big. * This error might be thrown while setting or updating the [[ConfigParams]]. * The following methods accept [[ConfigParams]] as a parameter: * * @see [[buildEmpty]] * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[updateConfig]] */ class ConfigValueTooBigError extends Error { constructor(paramName, maximum) { super(`Config parameter ${paramName} should be at most ${maximum}`); } } /** * Error thrown when the value was expected to be set for a config parameter. * It also displays the expected value. * This error might be thrown while setting or updating the [[ConfigParams]]. * The following methods accept [[ConfigParams]] as a parameter: * * @see [[buildEmpty]] * @see [[buildFromArray]] * @see [[buildFromSheets]] * @see [[updateConfig]] */ class ExpectedOneOfValuesError extends Error { constructor(values, paramName) { super(`Expected one of ${values} for config parameter: ${paramName}`); } } /** * Error thrown when computations become suspended. * To perform any other action wait for the batch to complete or resume the evaluation. * Relates to: * * @see [[batch]] * @see [[suspendEvaluation]] * @see [[resumeEvaluation]] */ class EvaluationSuspendedError extends Error { constructor() { super('Computations are suspended'); } } /** * Error thrown when translation is missing in translation package. */ class MissingTranslationError extends Error { constructor(key) { super(`Translation for ${key} is missing in the translation package you're using.`); } } /** * Error thrown when trying to override protected translation. * * @see [[registerLanguage]] * @see [[registerFunction]] * @see [[registerFunctionPlugin]] */ class ProtectedFunctionTranslationError extends Error { constructor(key) { super(`Cannot register translation for function with id: ${key}`); } } /** * Error thrown when trying to retrieve not registered language * * @see [[getLanguage]] * @see [[unregisterLanguage]] */ class LanguageNotRegisteredError extends Error { constructor() { super('Language not registered.'); } } /** * Error thrown when trying to register already registered language * * @see [[registerLanguage]] */ class LanguageAlreadyRegisteredError extends Error { constructor() { super('Language already registered.'); } } /** * Error thrown when function plugin is invalid. * * @see [[registerFunction]] * @see [[registerFunctionPlugin]] * @see [[buildFromArray]] * @see [[buildFromSheets]] */ class FunctionPluginValidationError extends Error { static functionNotDeclaredInPlugin(functionId, pluginName) { return new FunctionPluginValidationError(`Function with id ${functionId} not declared in plugin ${pluginName}`); } static functionMethodNotFound(functionName, pluginName) { return new FunctionPluginValidationError(`Function method ${functionName} not found in plugin ${pluginName}`); } } /** * Error thrown when trying to register, override or remove function with reserved id. * * @see [[registerFunctionPlugin]] * @see [[registerFunction]] * @see [[unregisterFunction]] */ class ProtectedFunctionError extends Error { static cannotRegisterFunctionWithId(functionId) { return new ProtectedFunctionError(`Cannot register function with id ${functionId}`); } static cannotUnregisterFunctionWithId(functionId) { return new ProtectedFunctionError(`Cannot unregister function with id ${functionId}`); } static cannotUnregisterProtectedPlugin() { return new ProtectedFunctionError('Cannot unregister protected plugin'); } } /** * Error thrown when selected source location has an array. */ class SourceLocationHasArrayError extends Error { constructor() { super('Cannot perform this operation, source location has an array inside.'); } } /** * Error thrown when selected target location has an array. * * @see [[addRows]] * @see [[addColumns]] * @see [[moveCells]] * @see [[moveRows]] * @see [[moveColumns]] * @see [[paste]] */ class TargetLocationHasArrayError extends Error { constructor() { super('Cannot perform this operation, target location has an array inside.'); } } /** * Error thrown when named expression contains relative addresses. * * @see [[addNamedExpression]] * @see [[changeNamedExpression]] */ class NoRelativeAddressesAllowedError extends Error { constructor() { super('Relative addresses not allowed in named expressions.'); } } /** * Error thrown when alias to a function is already defined. * * @see [[registerFunctionPlugin]] * @see [[registerFunction]] */ class AliasAlreadyExisting extends Error { constructor(name, pluginName) { super(`Alias id ${name} in plugin ${pluginName} already defined as a function or alias.`); } } /***/ }), /* 78 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArrayMapping: () => (/* binding */ ArrayMapping) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ArrayMapping { constructor() { this.arrayMapping = new Map(); } getArray(range) { const array = this.getArrayByCorner(range.start); if (array === null || array === void 0 ? void 0 : array.getRange().sameAs(range)) { return array; } return; } getArrayByCorner(address) { return this.arrayMapping.get((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(address)); } setArray(range, vertex) { this.arrayMapping.set((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(range.start), vertex); } removeArray(range) { if (typeof range === 'string') { this.arrayMapping.delete(range); } else { this.arrayMapping.delete((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(range.start)); } } count() { return this.arrayMapping.size; } *arraysInRows(rowsSpan) { for (const [mtxKey, mtx] of this.arrayMapping.entries()) { if (mtx.spansThroughSheetRows(rowsSpan.sheet, rowsSpan.rowStart, rowsSpan.rowEnd)) { yield [mtxKey, mtx]; } } } *arraysInCols(col) { for (const [mtxKey, mtx] of this.arrayMapping.entries()) { if (mtx.spansThroughSheetColumn(col.sheet, col.columnStart, col.columnEnd)) { yield [mtxKey, mtx]; } } } isFormulaArrayInRow(sheet, row) { for (const mtx of this.arrayMapping.values()) { if (mtx.spansThroughSheetRows(sheet, row)) { return true; } } return false; } isFormulaArrayInAllRows(span) { let result = true; for (const row of span.rows()) { if (!this.isFormulaArrayInRow(span.sheet, row)) { result = false; } } return result; } isFormulaArrayInColumn(sheet, column) { for (const mtx of this.arrayMapping.values()) { if (mtx.spansThroughSheetColumn(sheet, column)) { return true; } } return false; } isFormulaArrayInAllColumns(span) { let result = true; for (const col of span.columns()) { if (!this.isFormulaArrayInColumn(span.sheet, col)) { result = false; } } return result; } isFormulaArrayInRange(range) { for (const mtx of this.arrayMapping.values()) { if (mtx.getRange().doesOverlap(range)) { return true; } } return false; } isFormulaArrayAtAddress(address) { for (const mtx of this.arrayMapping.values()) { if (mtx.getRange().addressInRange(address)) { return true; } } return false; } moveArrayVerticesAfterRowByRows(sheet, row, numberOfRows) { this.updateArrayVerticesInSheet(sheet, (key, vertex) => { const range = vertex.getRange(); return row <= range.start.row ? [range.shifted(0, numberOfRows), vertex] : undefined; }); } moveArrayVerticesAfterColumnByColumns(sheet, column, numberOfColumns) { this.updateArrayVerticesInSheet(sheet, (key, vertex) => { const range = vertex.getRange(); return column <= range.start.col ? [range.shifted(numberOfColumns, 0), vertex] : undefined; }); } updateArrayVerticesInSheet(sheet, fn) { const updated = Array(); for (const [key, vertex] of this.arrayMapping.entries()) { if (vertex.sheet !== sheet) { continue; } const result = fn(key, vertex); if (result !== undefined) { this.removeArray(key); updated.push(result); } } updated.forEach(([range, array]) => { this.setArray(range, array); }); } } /***/ }), /* 79 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ collectAddressesDependentToRange: () => (/* binding */ collectAddressesDependentToRange) /* harmony export */ }); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); /* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80); /* harmony import */ var _RangeVertex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const collectAddressesDependentToRange = (functionRegistry, vertex, range, lazilyTransformingAstService, dependencyGraph) => { if (vertex instanceof _RangeVertex__WEBPACK_IMPORTED_MODULE_2__.RangeVertex) { const intersection = vertex.range.intersectionWith(range); if (intersection !== undefined) { return Array.from(intersection.addresses(dependencyGraph)); } else { return []; } } let formula; let address; if (vertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__.FormulaVertex) { formula = vertex.getFormula(lazilyTransformingAstService); address = vertex.getAddress(lazilyTransformingAstService); } else { return []; } return (0,_parser__WEBPACK_IMPORTED_MODULE_0__.collectDependencies)(formula, functionRegistry).filter(d => d instanceof _parser__WEBPACK_IMPORTED_MODULE_0__.AddressDependency).map(d => d.dependency.toSimpleCellAddress(address)).filter(d => range.addressInRange(d)); }; /***/ }), /* 80 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArrayVertex: () => (/* binding */ ArrayVertex), /* harmony export */ FormulaCellVertex: () => (/* binding */ FormulaCellVertex), /* harmony export */ FormulaVertex: () => (/* binding */ FormulaVertex) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); /* harmony import */ var _ArrayValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(81); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(61); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70); /* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(71); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class FormulaVertex { constructor(formula, cellAddress, version) { this.formula = formula; this.cellAddress = cellAddress; this.version = version; } get width() { return 1; } get height() { return 1; } static fromAst(formula, address, size, version) { if (size.isScalar()) { return new FormulaCellVertex(formula, address, version); } else { return new ArrayVertex(formula, address, size, version); } } /** * Returns formula stored in this vertex */ getFormula(updatingService) { this.ensureRecentData(updatingService); return this.formula; } ensureRecentData(updatingService) { if (this.version != updatingService.version()) { const [newAst, newAddress, newVersion] = updatingService.applyTransformations(this.formula, this.cellAddress, this.version); this.formula = newAst; this.cellAddress = newAddress; this.version = newVersion; } } /** * Returns address of the cell associated with vertex */ getAddress(updatingService) { this.ensureRecentData(updatingService); return this.cellAddress; } } class ArrayVertex extends FormulaVertex { constructor(formula, cellAddress, size, version = 0) { super(formula, cellAddress, version); if (size.isRef) { this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.NoSpaceForArrayResult), _ArraySize__WEBPACK_IMPORTED_MODULE_1__.ArraySize.error()); } else { this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray(size); } } get width() { return this.array.width(); } get height() { return this.array.height(); } get sheet() { return this.cellAddress.sheet; } get leftCorner() { return this.cellAddress; } setCellValue(value) { if (value instanceof _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError) { this.setErrorValue(value); return value; } const array = _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ArrayValue.fromInterpreterValue(value); array.resize(this.array.size); this.array = array; return value; } getCellValue() { if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray) { throw Error('Array not computed yet.'); } return this.array.simpleRangeValue(); } valueOrUndef() { if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray) { return undefined; } return this.array.simpleRangeValue(); } getArrayCellValue(address) { const col = address.col - this.cellAddress.col; const row = address.row - this.cellAddress.row; try { return this.array.get(col, row); } catch (e) { return new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.REF); } } getArrayCellRawValue(address) { const val = this.getArrayCellValue(address); if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError || val === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue) { return undefined; } else { return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(val); } } setArrayCellValue(address, value) { const col = address.col - this.cellAddress.col; const row = address.row - this.cellAddress.row; if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ArrayValue) { this.array.set(col, row, value); } } setNoSpace() { this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.SPILL, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.NoSpaceForArrayResult), _ArraySize__WEBPACK_IMPORTED_MODULE_1__.ArraySize.error()); return this.getCellValue(); } getRange() { return _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(this.cellAddress, this.width, this.height); } getRangeOrUndef() { return _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFromOrUndef(this.cellAddress, this.width, this.height); } setAddress(address) { this.cellAddress = address; } setFormula(newFormula) { this.formula = newFormula; } spansThroughSheetRows(sheet, startRow, endRow = startRow) { return this.cellAddress.sheet === sheet && this.cellAddress.row <= endRow && startRow < this.cellAddress.row + this.height; } spansThroughSheetColumn(sheet, col, columnEnd = col) { return this.cellAddress.sheet === sheet && this.cellAddress.col <= columnEnd && col < this.cellAddress.col + this.width; } isComputed() { return !(this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray); } columnsFromArray() { return _Span__WEBPACK_IMPORTED_MODULE_6__.ColumnsSpan.fromNumberOfColumns(this.cellAddress.sheet, this.cellAddress.col, this.width); } rowsFromArray() { return _Span__WEBPACK_IMPORTED_MODULE_6__.RowsSpan.fromNumberOfRows(this.cellAddress.sheet, this.cellAddress.row, this.height); } /** * No-op as array vertices are transformed eagerly. */ ensureRecentData(_updatingService) {} isLeftCorner(address) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.equalSimpleCellAddress)(this.cellAddress, address); } setErrorValue(error) { this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(error, this.array.size); } } /** * Represents vertex which keeps formula */ class FormulaCellVertex extends FormulaVertex { constructor( /** Formula in AST format */ formula, /** Address which this vertex represents */ address, version) { super(formula, address, version); } valueOrUndef() { return this.cachedCellValue; } /** * Sets computed cell value stored in this vertex */ setCellValue(cellValue) { this.cachedCellValue = cellValue; return this.cachedCellValue; } /** * Returns cell value stored in vertex */ getCellValue() { if (this.cachedCellValue !== undefined) { return this.cachedCellValue; } else { throw Error('Value of the formula cell is not computed.'); } } isComputed() { return this.cachedCellValue !== undefined; } } /***/ }), /* 81 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArrayValue: () => (/* binding */ ArrayValue), /* harmony export */ ErroredArray: () => (/* binding */ ErroredArray), /* harmony export */ NotComputedArray: () => (/* binding */ NotComputedArray) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class NotComputedArray { constructor(size) { this.size = size; } width() { return this.size.width; } height() { return this.size.height; } // eslint-disable-next-line @typescript-eslint/no-unused-vars get(col, row) { throw Error('Array not computed yet.'); } simpleRangeValue() { throw Error('Array not computed yet.'); } } class ArrayValue { constructor(array) { this.size = new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(array.length > 0 ? array[0].length : 0, array.length); this.array = array; if (this.size.width <= 0 || this.size.height <= 0) { throw Error('Incorrect array size'); } } static fromInterpreterValue(value) { if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__.SimpleRangeValue) { return new ArrayValue(value.data); } else { return new ArrayValue([[value]]); } } simpleRangeValue() { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__.SimpleRangeValue.onlyValues(this.array); } addRows(aboveRow, numberOfRows) { this.array.splice(aboveRow, 0, ...this.nullArrays(numberOfRows, this.width())); this.size.height += numberOfRows; } addColumns(aboveColumn, numberOfColumns) { for (let i = 0; i < this.height(); i++) { this.array[i].splice(aboveColumn, 0, ...new Array(numberOfColumns).fill(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue)); } this.size.width += numberOfColumns; } removeRows(startRow, endRow) { if (this.outOfBound(0, startRow) || this.outOfBound(0, endRow)) { throw Error('Array index out of bound'); } const numberOfRows = endRow - startRow + 1; this.array.splice(startRow, numberOfRows); this.size.height -= numberOfRows; } removeColumns(leftmostColumn, rightmostColumn) { if (this.outOfBound(leftmostColumn, 0) || this.outOfBound(rightmostColumn, 0)) { throw Error('Array index out of bound'); } const numberOfColumns = rightmostColumn - leftmostColumn + 1; for (const row of this.array) { row.splice(leftmostColumn, numberOfColumns); } this.size.width -= numberOfColumns; } nullArrays(count, size) { const result = []; for (let i = 0; i < count; ++i) { result.push(new Array(size).fill(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue)); } return result; } get(col, row) { if (this.outOfBound(col, row)) { throw Error('Array index out of bound'); } return this.array[row][col]; } set(col, row, value) { if (this.outOfBound(col, row)) { throw Error('Array index out of bound'); } this.array[row][col] = value; } width() { return this.size.width; } height() { return this.size.height; } raw() { return this.array; } resize(newSize) { if (this.height() < newSize.height && isFinite(newSize.height)) { this.addRows(this.height(), newSize.height - this.height()); } if (this.height() > newSize.height) { throw Error('Resizing to smaller array'); } if (this.width() < newSize.width && isFinite(newSize.width)) { this.addColumns(this.width(), newSize.width - this.width()); } if (this.width() > newSize.width) { throw Error('Resizing to smaller array'); } } outOfBound(col, row) { return col < 0 || row < 0 || row > this.size.height - 1 || col > this.size.width - 1; } } class ErroredArray { constructor(error, size) { this.error = error; this.size = size; } // eslint-disable-next-line @typescript-eslint/no-unused-vars get(col, row) { return this.error; } width() { return this.size.width; } height() { return this.size.height; } simpleRangeValue() { return this.error; } } /***/ }), /* 82 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RangeVertex: () => (/* binding */ RangeVertex) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Represents vertex bound to range */ class RangeVertex { constructor(range) { this.range = range; this.functionCache = new Map(); this.criterionFunctionCache = new Map(); this.dependentCacheRanges = new Set(); this.bruteForce = false; } get start() { return this.range.start; } get end() { return this.range.end; } get sheet() { return this.range.start.sheet; } /** * Returns cached value stored for given function * * @param functionName - name of the function */ getFunctionValue(functionName) { return this.functionCache.get(functionName); } /** * Stores cached value for given function * * @param functionName - name of the function * @param value - cached value */ setFunctionValue(functionName, value) { this.functionCache.set(functionName, value); } /** * Returns cached value for given cache key and criterion text representation * * @param cacheKey - key to retrieve from the cache * @param criterionString - criterion text (ex. '<=5') */ getCriterionFunctionValue(cacheKey, criterionString) { var _a; return (_a = this.getCriterionFunctionValues(cacheKey).get(criterionString)) === null || _a === void 0 ? void 0 : _a[0]; } /** * Returns all cached values stored for given criterion function * * @param cacheKey - key to retrieve from the cache */ getCriterionFunctionValues(cacheKey) { var _a; return (_a = this.criterionFunctionCache.get(cacheKey)) !== null && _a !== void 0 ? _a : new Map(); } /** * Stores all values for given criterion function * * @param cacheKey - key to store in the cache * @param values - map with values */ setCriterionFunctionValues(cacheKey, values) { this.criterionFunctionCache.set(cacheKey, values); } addDependentCacheRange(dependentRange) { if (dependentRange !== this) { this.dependentCacheRanges.add(dependentRange); } } /** * Clears function cache */ clearCache() { this.functionCache.clear(); this.criterionFunctionCache.clear(); this.dependentCacheRanges.forEach(range => range.criterionFunctionCache.clear()); this.dependentCacheRanges.clear(); } /** * Returns start of the range (it's top-left corner) */ getStart() { return this.start; } /** * Returns end of the range (it's bottom-right corner) */ getEnd() { return this.end; } } /***/ }), /* 83 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Graph: () => (/* binding */ Graph) /* harmony export */ }); /* harmony import */ var _TopSort__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84); /* harmony import */ var _ProcessableValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Provides directed graph structure. * * Idea for performance improvement: * - use Set[] instead of NodeId[][] for edgesSparseArray */ class Graph { constructor(dependencyQuery) { this.dependencyQuery = dependencyQuery; /** * A sparse array. The value nodesSparseArray[n] exists if and only if node n is in the graph. * @private */ this.nodesSparseArray = []; /** * A sparse array. The value edgesSparseArray[n] exists if and only if node n is in the graph. * The edgesSparseArray[n] is also a sparse array. It may contain removed nodes. To make sure check nodesSparseArray. * @private */ this.edgesSparseArray = []; /** * A mapping from node to its id. The value nodesIds.get(node) exists if and only if node is in the graph. * @private */ this.nodesIds = new Map(); /** * A ProcessableValue object. * @private */ this.dirtyAndVolatileNodeIds = new _ProcessableValue__WEBPACK_IMPORTED_MODULE_1__.ProcessableValue({ dirty: [], volatile: [] }, r => this.processDirtyAndVolatileNodeIds(r)); /** * A set of node ids. The value infiniteRangeIds.get(nodeId) exists if and only if node is in the graph. * @private */ this.infiniteRangeIds = new Set(); /** * A dense array. It may contain duplicates and removed nodes. * @private */ this.changingWithStructureNodeIds = []; this.nextId = 0; } /** * Iterate over all nodes the in graph */ getNodes() { return this.nodesSparseArray.filter(node => node !== undefined); } /** * Checks whether a node is present in graph * * @param node - node to check */ hasNode(node) { return this.nodesIds.has(node); } /** * Checks whether exists edge between nodes. If one or both of nodes are not present in graph, returns false. * * @param fromNode - node from which edge is outcoming * @param toNode - node to which edge is incoming */ existsEdge(fromNode, toNode) { const fromId = this.getNodeId(fromNode); const toId = this.getNodeId(toNode); if (fromId === undefined || toId === undefined) { return false; } return this.edgesSparseArray[fromId].includes(toId); } /** * Returns nodes adjacent to given node. May contain removed nodes. * * @param node - node to which adjacent nodes we want to retrieve * * Idea for performance improvement: * - return an array instead of set */ adjacentNodes(node) { const id = this.getNodeId(node); if (id === undefined) { throw this.missingNodeError(node); } return new Set(this.edgesSparseArray[id].filter(id => id !== undefined).map(id => this.nodesSparseArray[id])); } /** * Returns number of nodes adjacent to given node. Contrary to adjacentNodes(), this method returns only nodes that are present in graph. * * @param node - node to which adjacent nodes we want to retrieve */ adjacentNodesCount(node) { const id = this.getNodeId(node); if (id === undefined) { throw this.missingNodeError(node); } return this.fixEdgesArrayForNode(id).length; } /** * Adds node to a graph * * @param node - a node to be added */ addNodeAndReturnId(node) { const idOfExistingNode = this.nodesIds.get(node); if (idOfExistingNode !== undefined) { return idOfExistingNode; } const newId = this.nextId; this.nextId++; this.nodesSparseArray[newId] = node; this.edgesSparseArray[newId] = []; this.nodesIds.set(node, newId); return newId; } /** * Adds edge between nodes. * * The nodes had to be added to the graph before, or the error will be raised * * @param fromNode - node from which edge is outcoming * @param toNode - node to which edge is incoming */ addEdge(fromNode, toNode) { const fromId = this.getNodeIdIfNotNumber(fromNode); const toId = this.getNodeIdIfNotNumber(toNode); if (fromId === undefined) { throw this.missingNodeError(fromNode); } if (toId === undefined) { throw this.missingNodeError(toNode); } if (this.edgesSparseArray[fromId].includes(toId)) { return; } this.edgesSparseArray[fromId].push(toId); } /** * Removes node from graph */ removeNode(node) { const id = this.getNodeId(node); if (id === undefined) { throw this.missingNodeError(node); } if (this.edgesSparseArray[id].length > 0) { this.edgesSparseArray[id].forEach(adjacentId => this.dirtyAndVolatileNodeIds.rawValue.dirty.push(adjacentId)); this.dirtyAndVolatileNodeIds.markAsModified(); } const dependencies = this.removeDependencies(node); delete this.nodesSparseArray[id]; delete this.edgesSparseArray[id]; this.infiniteRangeIds.delete(id); this.nodesIds.delete(node); return dependencies; } /** * Removes edge between nodes. */ removeEdge(fromNode, toNode) { const fromId = this.getNodeIdIfNotNumber(fromNode); const toId = this.getNodeIdIfNotNumber(toNode); if (fromId === undefined) { throw this.missingNodeError(fromNode); } if (toId === undefined) { throw this.missingNodeError(toNode); } const indexOfToId = this.edgesSparseArray[fromId].indexOf(toId); if (indexOfToId === -1) { throw new Error('Edge does not exist'); } delete this.edgesSparseArray[fromId][indexOfToId]; } /** * Removes edge between nodes if it exists. */ removeEdgeIfExists(fromNode, toNode) { const fromId = this.getNodeId(fromNode); const toId = this.getNodeId(toNode); if (fromId === undefined) { return; } if (toId === undefined) { return; } const indexOfToId = this.edgesSparseArray[fromId].indexOf(toId); if (indexOfToId === -1) { return; } delete this.edgesSparseArray[fromId][indexOfToId]; } /** * Sorts the whole graph topologically. Nodes that are on cycles are kept separate. */ topSortWithScc() { return this.getTopSortedWithSccSubgraphFrom(this.getNodes(), () => true, () => {}); } /** * Sorts the graph topologically. Nodes that are on cycles are kept separate. * * @param modifiedNodes - seed for computation. The algorithm assumes that only these nodes have changed since the last run. * @param operatingFunction - recomputes value of a node, and returns whether a change occurred * @param onCycle - action to be performed when node is on cycle */ getTopSortedWithSccSubgraphFrom(modifiedNodes, operatingFunction, onCycle) { const topSortAlgorithm = new _TopSort__WEBPACK_IMPORTED_MODULE_0__.TopSort(this.nodesSparseArray, this.edgesSparseArray); const modifiedNodesIds = modifiedNodes.map(node => this.getNodeId(node)).filter(id => id !== undefined); return topSortAlgorithm.getTopSortedWithSccSubgraphFrom(modifiedNodesIds, operatingFunction, onCycle); } /** * Marks node as volatile. */ markNodeAsVolatile(node) { const id = this.getNodeId(node); if (id === undefined) { return; } this.dirtyAndVolatileNodeIds.rawValue.volatile.push(id); this.dirtyAndVolatileNodeIds.markAsModified(); } /** * Marks node as dirty. */ markNodeAsDirty(node) { const id = this.getNodeId(node); if (id === undefined) { return; } this.dirtyAndVolatileNodeIds.rawValue.dirty.push(id); this.dirtyAndVolatileNodeIds.markAsModified(); } /** * Returns an array of nodes that are marked as dirty and/or volatile. */ getDirtyAndVolatileNodes() { return this.dirtyAndVolatileNodeIds.getProcessedValue(); } /** * Clears dirty nodes. */ clearDirtyNodes() { this.dirtyAndVolatileNodeIds.rawValue.dirty = []; this.dirtyAndVolatileNodeIds.markAsModified(); } /** * Marks node as changingWithStructure. */ markNodeAsChangingWithStructure(node) { const id = this.getNodeId(node); if (id === undefined) { return; } this.changingWithStructureNodeIds.push(id); } /** * Marks all nodes marked as changingWithStructure as dirty. */ markChangingWithStructureNodesAsDirty() { if (this.changingWithStructureNodeIds.length <= 0) { return; } this.dirtyAndVolatileNodeIds.rawValue.dirty = [...this.dirtyAndVolatileNodeIds.rawValue.dirty, ...this.changingWithStructureNodeIds]; this.dirtyAndVolatileNodeIds.markAsModified(); } /** * Marks node as infinite range. */ markNodeAsInfiniteRange(node) { const id = this.getNodeIdIfNotNumber(node); if (id === undefined) { return; } this.infiniteRangeIds.add(id); } /** * Returns an array of nodes marked as infinite ranges */ getInfiniteRanges() { return [...this.infiniteRangeIds].map(id => ({ node: this.nodesSparseArray[id], id })); } /** * Returns the internal id of a node. */ getNodeId(node) { return this.nodesIds.get(node); } /** * */ getNodeIdIfNotNumber(node) { return typeof node === 'number' ? node : this.nodesIds.get(node); } /** * Removes invalid neighbors of a given node from the edges array and returns adjacent nodes for the input node. */ fixEdgesArrayForNode(id) { const adjacentNodeIds = this.edgesSparseArray[id]; this.edgesSparseArray[id] = adjacentNodeIds.filter(adjacentId => adjacentId !== undefined && this.nodesSparseArray[adjacentId]); return this.edgesSparseArray[id]; } /** * Removes edges from the given node to its dependencies based on the dependencyQuery function. */ removeDependencies(node) { const dependencies = this.dependencyQuery(node); dependencies.forEach(([_, dependency]) => { this.removeEdgeIfExists(dependency, node); }); return dependencies; } /** * processFn for dirtyAndVolatileNodeIds ProcessableValue instance * @private */ processDirtyAndVolatileNodeIds({ dirty, volatile }) { return [...new Set([...dirty, ...volatile])].map(id => this.nodesSparseArray[id]).filter(node => node !== undefined); } /** * Returns error for missing node. */ missingNodeError(node) { return new Error(`Unknown node ${node}`); } } /***/ }), /* 84 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TopSort: () => (/* binding */ TopSort) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ // node status life cycle: undefined -> ON_STACK -> PROCESSED -> POPPED var NodeVisitStatus; (function (NodeVisitStatus) { NodeVisitStatus[NodeVisitStatus["ON_STACK"] = 0] = "ON_STACK"; NodeVisitStatus[NodeVisitStatus["PROCESSED"] = 1] = "PROCESSED"; NodeVisitStatus[NodeVisitStatus["POPPED"] = 2] = "POPPED"; })(NodeVisitStatus || (NodeVisitStatus = {})); /** * An algorithm class. Provides an iterative implementation of Tarjan's algorithm for finding strongly connected components */ class TopSort { constructor(nodesSparseArray = [], edgesSparseArray = []) { this.nodesSparseArray = nodesSparseArray; this.edgesSparseArray = edgesSparseArray; this.entranceTime = []; this.low = []; this.parent = []; this.inSCC = []; this.nodeStatus = []; this.order = []; this.sccNonSingletons = []; this.timeCounter = 0; } /** * An iterative implementation of Tarjan's algorithm for finding strongly connected components. * Returns vertices in order of topological sort, but vertices that are on cycles are kept separate. * * @param modifiedNodes - seed for computation. During engine init run, all of the vertices of grap. In recomputation run, changed vertices. * @param operatingFunction - recomputes value of a node, and returns whether a change occured * @param onCycle - action to be performed when node is on cycle */ getTopSortedWithSccSubgraphFrom(modifiedNodeIds, operatingFunction, onCycle) { const modifiedNodeIdsReversed = modifiedNodeIds.reverse(); modifiedNodeIdsReversed.forEach(id => this.runDFS(id)); return this.postprocess(modifiedNodeIdsReversed, onCycle, operatingFunction); } /** * Returns adjacent nodes of a given node. */ getAdjacentNodeIds(id) { return this.edgesSparseArray[id].filter(adjacentId => adjacentId !== undefined && this.nodesSparseArray[adjacentId]); } /** * Runs DFS starting from a given node. */ runDFS(v) { if (this.nodeStatus[v] !== undefined) { return; } this.nodeStatus[v] = NodeVisitStatus.ON_STACK; const DFSstack = [v]; const SCCstack = []; while (DFSstack.length > 0) { const u = DFSstack[DFSstack.length - 1]; switch (this.nodeStatus[u]) { case NodeVisitStatus.ON_STACK: { this.handleOnStack(u, SCCstack, DFSstack); break; } case NodeVisitStatus.PROCESSED: { // leaving this DFS subtree this.handleProcessed(u, SCCstack, DFSstack); break; } case NodeVisitStatus.POPPED: { // it's a 'shadow' copy, we already processed this vertex and can ignore it DFSstack.pop(); break; } } } } /** * Handles a node that is on stack. */ handleOnStack(u, SCCstack, DFSstack) { this.entranceTime[u] = this.timeCounter; this.low[u] = this.timeCounter; this.timeCounter++; SCCstack.push(u); this.getAdjacentNodeIds(u).forEach(t => { if (this.entranceTime[t] === undefined) { DFSstack.push(t); this.parent[t] = u; this.nodeStatus[t] = NodeVisitStatus.ON_STACK; } }); this.nodeStatus[u] = NodeVisitStatus.PROCESSED; } /** * Handles a node that is already processed. */ handleProcessed(u, SCCstack, DFSstack) { let uLow = this.entranceTime[u]; this.getAdjacentNodeIds(u).forEach(t => { if (this.inSCC[t]) { return; } uLow = this.parent[t] === u ? Math.min(uLow, this.low[t]) : Math.min(uLow, this.entranceTime[t]); }); this.low[u] = uLow; if (uLow === this.entranceTime[u]) { const currentSCC = []; do { currentSCC.push(SCCstack[SCCstack.length - 1]); SCCstack.pop(); } while (currentSCC[currentSCC.length - 1] !== u); currentSCC.forEach(t => { this.inSCC[t] = true; }); this.order.push(...currentSCC); if (currentSCC.length > 1) { currentSCC.forEach(t => { this.sccNonSingletons[t] = true; }); } } DFSstack.pop(); this.nodeStatus[u] = NodeVisitStatus.POPPED; } /** * Postprocesses the result of Tarjan's algorithm. */ postprocess(modifiedNodeIds, onCycle, operatingFunction) { const shouldBeUpdatedMapping = []; modifiedNodeIds.forEach(t => { shouldBeUpdatedMapping[t] = true; }); const sorted = []; const cycled = []; this.order.reverse(); this.order.forEach(t => { const adjacentNodes = this.getAdjacentNodeIds(t); // The following line is a potential performance bottleneck. // Array.includes() is O(n) operation, which makes the whole algorithm O(n^2). // Idea for improvement: use Set[] instead of number[][] for edgesSparseArray. if (this.sccNonSingletons[t] || adjacentNodes.includes(t)) { cycled.push(this.nodesSparseArray[t]); onCycle(this.nodesSparseArray[t]); adjacentNodes.forEach(s => shouldBeUpdatedMapping[s] = true); } else { sorted.push(this.nodesSparseArray[t]); if (shouldBeUpdatedMapping[t] && operatingFunction(this.nodesSparseArray[t])) { adjacentNodes.forEach(s => shouldBeUpdatedMapping[s] = true); } } }); return { sorted, cycled }; } } /***/ }), /* 85 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ProcessableValue: () => (/* binding */ ProcessableValue) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ProcessableValue { constructor(rawValue, processFn) { this.rawValue = rawValue; this.processFn = processFn; this.processedValue = null; } getProcessedValue() { if (this.processedValue === null) { this.processedValue = this.processFn(this.rawValue); } return this.processedValue; } markAsModified() { this.processedValue = null; } } /***/ }), /* 86 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RangeMapping: () => (/* binding */ RangeMapping) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Mapping from address ranges to range vertices */ class RangeMapping { constructor() { /** Map in which actual data is stored. */ this.rangeMapping = new Map(); } getMappingSize(sheet) { var _a, _b; return (_b = (_a = this.rangeMapping.get(sheet)) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0; } /** * Saves range vertex * * @param vertex - vertex to save */ setRange(vertex) { let sheetMap = this.rangeMapping.get(vertex.getStart().sheet); if (sheetMap === undefined) { sheetMap = new Map(); this.rangeMapping.set(vertex.getStart().sheet, sheetMap); } const key = keyFromAddresses(vertex.getStart(), vertex.getEnd()); sheetMap.set(key, vertex); } removeRange(vertex) { const sheet = vertex.getStart().sheet; const sheetMap = this.rangeMapping.get(sheet); if (sheetMap === undefined) { return; } const key = keyFromAddresses(vertex.getStart(), vertex.getEnd()); sheetMap.delete(key); if (sheetMap.size === 0) { this.rangeMapping.delete(sheet); } } /** * Returns associated vertex for given range * * @param start - top-left corner of the range * @param end - bottom-right corner of the range */ getRange(start, end) { const sheetMap = this.rangeMapping.get(start.sheet); const key = keyFromAddresses(start, end); return sheetMap === null || sheetMap === void 0 ? void 0 : sheetMap.get(key); } fetchRange(start, end) { const maybeRange = this.getRange(start, end); if (!maybeRange) { throw Error('Range does not exist'); } return maybeRange; } truncateRanges(span, coordinate) { const verticesToRemove = Array(); const updated = Array(); const verticesWithChangedSize = Array(); const sheet = span.sheet; for (const [key, vertex] of this.entriesFromSheet(span.sheet)) { const range = vertex.range; if (span.start <= coordinate(vertex.range.end)) { range.removeSpan(span); if (range.shouldBeRemoved()) { this.removeByKey(sheet, key); verticesToRemove.push(vertex); } else { updated.push([key, vertex]); } verticesWithChangedSize.push(vertex); } } const verticesToMerge = []; updated.sort((left, right) => compareBy(left[1], right[1], coordinate)); for (const [oldKey, vertex] of updated) { const newKey = keyFromRange(vertex.range); if (newKey === oldKey) { continue; } const existingVertex = this.getByKey(sheet, newKey); this.removeByKey(sheet, oldKey); if (existingVertex !== undefined && vertex != existingVertex) { verticesToMerge.push([existingVertex, vertex]); } else { this.setRange(vertex); } } return { verticesToRemove, verticesToMerge, verticesWithChangedSize }; } moveAllRangesInSheetAfterRowByRows(sheet, row, numberOfRows) { return this.updateVerticesFromSheet(sheet, (key, vertex) => { if (row <= vertex.start.row) { vertex.range.shiftByRows(numberOfRows); return { changedSize: false, vertex: vertex }; } else if (row > vertex.start.row && row <= vertex.end.row) { vertex.range.expandByRows(numberOfRows); return { changedSize: true, vertex: vertex }; } else { return undefined; } }); } moveAllRangesInSheetAfterColumnByColumns(sheet, column, numberOfColumns) { return this.updateVerticesFromSheet(sheet, (key, vertex) => { if (column <= vertex.start.col) { vertex.range.shiftByColumns(numberOfColumns); return { changedSize: false, vertex: vertex }; } else if (column > vertex.start.col && column <= vertex.end.col) { vertex.range.expandByColumns(numberOfColumns); return { changedSize: true, vertex: vertex }; } else { return undefined; } }); } moveRangesInsideSourceRange(sourceRange, toRight, toBottom, toSheet) { this.updateVerticesFromSheet(sourceRange.sheet, (key, vertex) => { if (sourceRange.containsRange(vertex.range)) { vertex.range.shiftByColumns(toRight); vertex.range.shiftByRows(toBottom); vertex.range.moveToSheet(toSheet); return { changedSize: false, vertex: vertex }; } else { return undefined; } }); } removeRangesInSheet(sheet) { if (this.rangeMapping.has(sheet)) { const ranges = this.rangeMapping.get(sheet).values(); this.rangeMapping.delete(sheet); return ranges; } return [][Symbol.iterator](); } *rangesInSheet(sheet) { const sheetMap = this.rangeMapping.get(sheet); if (!sheetMap) { return; } yield* sheetMap.values(); } *rangeVerticesContainedInRange(sourceRange) { for (const rangeVertex of this.rangesInSheet(sourceRange.sheet)) { if (sourceRange.containsRange(rangeVertex.range)) { yield rangeVertex; } } } /** * Finds smaller range does have own vertex. * * @param range */ findSmallerRange(range) { if (range.height() > 1 && Number.isFinite(range.height())) { const valuesRangeEndRowLess = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.end.sheet, range.end.col, range.end.row - 1); const rowLessVertex = this.getRange(range.start, valuesRangeEndRowLess); if (rowLessVertex !== undefined) { const restRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromSimpleCellAddresses((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.start.sheet, range.start.col, range.end.row), range.end); return { smallerRangeVertex: rowLessVertex, restRange }; } } return { restRange: range }; } *entriesFromSheet(sheet) { const sheetMap = this.rangeMapping.get(sheet); if (!sheetMap) { return; } yield* sheetMap.entries(); } removeByKey(sheet, key) { this.rangeMapping.get(sheet).delete(key); } getByKey(sheet, key) { var _a; return (_a = this.rangeMapping.get(sheet)) === null || _a === void 0 ? void 0 : _a.get(key); } updateVerticesFromSheet(sheet, fn) { const updated = Array(); for (const [key, vertex] of this.entriesFromSheet(sheet)) { const result = fn(key, vertex); if (result !== undefined) { this.removeByKey(sheet, key); updated.push(result); } } updated.forEach(entry => { this.setRange(entry.vertex); }); return { verticesWithChangedSize: updated.filter(entry => entry.changedSize).map(entry => entry.vertex) }; } } function keyFromAddresses(start, end) { return `${start.col},${start.row},${end.col},${end.row}`; } function keyFromRange(range) { return keyFromAddresses(range.start, range.end); } const compareBy = (left, right, coordinate) => { const leftStart = coordinate(left.range.start); const rightStart = coordinate(left.range.start); if (leftStart === rightStart) { const leftEnd = coordinate(left.range.end); const rightEnd = coordinate(right.range.end); return leftEnd - rightEnd; } else { return leftStart - rightStart; } }; /***/ }), /* 87 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SheetMapping: () => (/* binding */ SheetMapping) /* harmony export */ }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77); /* harmony import */ var _i18n__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(88); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function canonicalize(sheetDisplayName) { return sheetDisplayName.toLowerCase(); } class Sheet { constructor(id, displayName) { this.id = id; this.displayName = displayName; } get canonicalName() { return canonicalize(this.displayName); } } class SheetMapping { constructor(languages) { this.languages = languages; this.mappingFromCanonicalName = new Map(); this.mappingFromId = new Map(); this.lastSheetId = -1; this.fetch = sheetName => { const sheet = this.mappingFromCanonicalName.get(canonicalize(sheetName)); if (sheet === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithNameError(sheetName); } return sheet.id; }; this.get = sheetName => { var _a; return (_a = this.mappingFromCanonicalName.get(canonicalize(sheetName))) === null || _a === void 0 ? void 0 : _a.id; }; this.fetchDisplayName = sheetId => { return this.fetchSheetById(sheetId).displayName; }; this.sheetNamePrefix = languages.getUITranslation(_i18n__WEBPACK_IMPORTED_MODULE_1__.UIElement.NEW_SHEET_PREFIX); } addSheet(newSheetDisplayName = `${this.sheetNamePrefix}${this.lastSheetId + 2}`) { const newSheetCanonicalName = canonicalize(newSheetDisplayName); if (this.mappingFromCanonicalName.has(newSheetCanonicalName)) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.SheetNameAlreadyTakenError(newSheetDisplayName); } this.lastSheetId++; const sheet = new Sheet(this.lastSheetId, newSheetDisplayName); this.store(sheet); return sheet.id; } removeSheet(sheetId) { const sheet = this.fetchSheetById(sheetId); if (sheetId == this.lastSheetId) { --this.lastSheetId; } this.mappingFromCanonicalName.delete(sheet.canonicalName); this.mappingFromId.delete(sheet.id); } getDisplayName(sheetId) { var _a; return (_a = this.mappingFromId.get(sheetId)) === null || _a === void 0 ? void 0 : _a.displayName; } *displayNames() { for (const sheet of this.mappingFromCanonicalName.values()) { yield sheet.displayName; } } numberOfSheets() { return this.mappingFromCanonicalName.size; } hasSheetWithId(sheetId) { return this.mappingFromId.has(sheetId); } hasSheetWithName(sheetName) { return this.mappingFromCanonicalName.has(canonicalize(sheetName)); } renameSheet(sheetId, newDisplayName) { const sheet = this.fetchSheetById(sheetId); const currentDisplayName = sheet.displayName; if (currentDisplayName === newDisplayName) { return undefined; } const sheetWithThisCanonicalName = this.mappingFromCanonicalName.get(canonicalize(newDisplayName)); if (sheetWithThisCanonicalName !== undefined && sheetWithThisCanonicalName.id !== sheet.id) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.SheetNameAlreadyTakenError(newDisplayName); } const currentCanonicalName = sheet.canonicalName; this.mappingFromCanonicalName.delete(currentCanonicalName); sheet.displayName = newDisplayName; this.store(sheet); return currentDisplayName; } sheetNames() { return Array.from(this.mappingFromId.values()).map(s => s.displayName); } store(sheet) { this.mappingFromId.set(sheet.id, sheet); this.mappingFromCanonicalName.set(sheet.canonicalName, sheet); } fetchSheetById(sheetId) { const sheet = this.mappingFromId.get(sheetId); if (sheet === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId); } return sheet; } } /***/ }), /* 88 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TranslationPackage: () => (/* reexport safe */ _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__.TranslationPackage), /* harmony export */ UIElement: () => (/* binding */ UIElement), /* harmony export */ buildTranslationPackage: () => (/* reexport safe */ _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__.buildTranslationPackage) /* harmony export */ }); /* harmony import */ var _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(89); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var UIElement; (function (UIElement) { UIElement["NEW_SHEET_PREFIX"] = "NEW_SHEET_PREFIX"; })(UIElement || (UIElement = {})); /***/ }), /* 89 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TranslationPackage: () => (/* binding */ TranslationPackage), /* harmony export */ buildTranslationPackage: () => (/* binding */ buildTranslationPackage) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77); /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class TranslationPackage { constructor(functions, errors, ui) { this.functions = functions; this.errors = errors; this.ui = ui; this._protectedTranslations = { 'VERSION': 'VERSION' }; this.checkUI(); this.checkErrors(); this.checkFunctionTranslations(this.functions); Object.assign(this.functions, this._protectedTranslations); } extendFunctions(additionalFunctionTranslations) { this.checkFunctionTranslations(additionalFunctionTranslations); Object.assign(this.functions, additionalFunctionTranslations); } buildFunctionMapping() { return Object.keys(this.functions).reduce((ret, key) => { ret[this.functions[key]] = key; return ret; }, {}); } buildErrorMapping() { return Object.keys(this.errors).reduce((ret, key) => { ret[this.errors[key]] = key; return ret; }, {}); } isFunctionTranslated(key) { return this.functions[key] !== undefined; } getFunctionTranslations(functionIds) { const translations = []; for (const functionId of functionIds) { if (this.isFunctionTranslated(functionId)) { translations.push(this.functions[functionId]); } } return translations; } getFunctionTranslation(key) { const val = this.functions[key]; if (val === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`functions.${key}`); } else { return val; } } getMaybeFunctionTranslation(key) { return this.functions[key]; } getErrorTranslation(key) { if (key === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC) { return `#${_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC}!`; } const val = this.errors[key]; if (val === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`errors.${key}`); } else { return val; } } getUITranslation(key) { const val = this.ui[key]; if (val === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`ui.${key}`); } else { return val; } } checkUI() { for (const key of Object.values(_index__WEBPACK_IMPORTED_MODULE_2__.UIElement)) { if (!(key in this.ui)) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`ui.${key}`); } } } checkErrors() { for (const key of Object.values(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType)) { if (!(key in this.errors) && key !== _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`errors.${key}`); } } } checkFunctionTranslations(functions) { const functionNames = new Set(Object.getOwnPropertyNames(functions)); for (const protectedTranslation of Object.getOwnPropertyNames(this._protectedTranslations)) { if (functionNames.has(protectedTranslation)) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ProtectedFunctionTranslationError(protectedTranslation); } } } } function buildTranslationPackage(rawTranslationPackage) { return new TranslationPackage(Object.assign({}, rawTranslationPackage.functions), Object.assign({}, rawTranslationPackage.errors), Object.assign({}, rawTranslationPackage.ui)); } /***/ }), /* 90 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EmptyCellVertex: () => (/* binding */ EmptyCellVertex) /* harmony export */ }); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Represents singleton vertex bound to all empty cells */ class EmptyCellVertex { constructor() {} /** * Retrieves cell value bound to that singleton */ getCellValue() { return _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.EmptyValue; } } /***/ }), /* 91 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ValueCellVertex: () => (/* binding */ ValueCellVertex) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Represents vertex which keeps static cell value */ class ValueCellVertex { /** Static cell value. */ constructor(parsedValue, rawValue) { this.parsedValue = parsedValue; this.rawValue = rawValue; } getValues() { return { parsedValue: this.parsedValue, rawValue: this.rawValue }; } setValues(values) { this.parsedValue = values.parsedValue; this.rawValue = values.rawValue; } /** * Returns cell value stored in vertex */ getCellValue() { return this.parsedValue; } setCellValue(_cellValue) { throw Error('SetCellValue is deprecated for ValueCellVertex'); } } /***/ }), /* 92 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ParsingErrorVertex: () => (/* binding */ ParsingErrorVertex) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Represents a cell that contains a parsing error. */ class ParsingErrorVertex { /** * Constructor */ constructor(errors, rawInput) { this.errors = errors; this.rawInput = rawInput; } /** * Returns the value of the cell. */ getCellValue() { const firstNonemptyMessage = this.errors.map(error => error.message).find(msg => msg); return _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError.parsingError(firstNonemptyMessage); } /** * Returns the formula of the cell. */ getFormula() { return this.rawInput; } } /***/ }), /* 93 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SparseStrategy: () => (/* binding */ SparseStrategy) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Mapping from cell addresses to vertices * * Uses Map to store addresses, having minimal memory usage for sparse sheets but not necessarily constant set/lookup. */ class SparseStrategy { constructor(width, height) { this.width = width; this.height = height; /** * Map of Maps in which actual data is stored. * * Key of map in first level is column number. * Key of map in second level is row number. */ this.mapping = new Map(); } /** @inheritDoc */ getCell(address) { var _a; return (_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.get(address.row); } /** @inheritDoc */ setCell(address, newVertex) { this.width = Math.max(this.width, address.col + 1); this.height = Math.max(this.height, address.row + 1); let colMapping = this.mapping.get(address.col); if (!colMapping) { colMapping = new Map(); this.mapping.set(address.col, colMapping); } colMapping.set(address.row, newVertex); } /** @inheritDoc */ has(address) { var _a; return !!((_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.get(address.row)); } /** @inheritDoc */ getHeight() { return this.height; } /** @inheritDoc */ getWidth() { return this.width; } removeCell(address) { var _a; (_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.delete(address.row); } addRows(row, numberOfRows) { this.mapping.forEach(rowMapping => { const tmpMapping = new Map(); rowMapping.forEach((vertex, rowNumber) => { if (rowNumber >= row) { tmpMapping.set(rowNumber + numberOfRows, vertex); rowMapping.delete(rowNumber); } }); tmpMapping.forEach((vertex, rowNumber) => { rowMapping.set(rowNumber, vertex); }); }); this.height += numberOfRows; } addColumns(column, numberOfColumns) { const tmpMapping = new Map(); this.mapping.forEach((rowMapping, colNumber) => { if (colNumber >= column) { tmpMapping.set(colNumber + numberOfColumns, rowMapping); this.mapping.delete(colNumber); } }); tmpMapping.forEach((rowMapping, colNumber) => { this.mapping.set(colNumber, rowMapping); }); this.width += numberOfColumns; } removeRows(removedRows) { this.mapping.forEach(rowMapping => { const tmpMapping = new Map(); rowMapping.forEach((vertex, rowNumber) => { if (rowNumber >= removedRows.rowStart) { rowMapping.delete(rowNumber); if (rowNumber > removedRows.rowEnd) { tmpMapping.set(rowNumber - removedRows.numberOfRows, vertex); } } }); tmpMapping.forEach((vertex, rowNumber) => { rowMapping.set(rowNumber, vertex); }); }); const rightmostRowRemoved = Math.min(this.height - 1, removedRows.rowEnd); const numberOfRowsRemoved = Math.max(0, rightmostRowRemoved - removedRows.rowStart + 1); this.height = Math.max(0, this.height - numberOfRowsRemoved); } removeColumns(removedColumns) { const tmpMapping = new Map(); this.mapping.forEach((rowMapping, colNumber) => { if (colNumber >= removedColumns.columnStart) { this.mapping.delete(colNumber); if (colNumber > removedColumns.columnEnd) { tmpMapping.set(colNumber - removedColumns.numberOfColumns, rowMapping); } } }); tmpMapping.forEach((rowMapping, colNumber) => { this.mapping.set(colNumber, rowMapping); }); const rightmostColumnRemoved = Math.min(this.width - 1, removedColumns.columnEnd); const numberOfColumnsRemoved = Math.max(0, rightmostColumnRemoved - removedColumns.columnStart + 1); this.width = Math.max(0, this.width - numberOfColumnsRemoved); } *getEntries(sheet) { for (const [colNumber, col] of this.mapping) { for (const [rowNumber, value] of col) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, colNumber, rowNumber), value]; } } } *verticesFromColumn(column) { const colMapping = this.mapping.get(column); if (colMapping === undefined) { return; } for (const [_, vertex] of colMapping) { yield vertex; } } *verticesFromRow(row) { for (const colMapping of this.mapping.values()) { const rowVertex = colMapping.get(row); if (rowVertex !== undefined) { yield rowVertex; } } } *verticesFromColumnsSpan(columnsSpan) { for (const column of columnsSpan.columns()) { const colMapping = this.mapping.get(column); if (colMapping === undefined) { continue; } for (const [_, vertex] of colMapping) { yield vertex; } } } *verticesFromRowsSpan(rowsSpan) { for (const colMapping of this.mapping.values()) { for (const row of rowsSpan.rows()) { const rowVertex = colMapping.get(row); if (rowVertex !== undefined) { yield rowVertex; } } } } *entriesFromRowsSpan(rowsSpan) { for (const [col, colMapping] of this.mapping.entries()) { for (const row of rowsSpan.rows()) { const rowVertex = colMapping.get(row); if (rowVertex !== undefined) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(rowsSpan.sheet, col, row), rowVertex]; } } } } *entriesFromColumnsSpan(columnsSpan) { for (const col of columnsSpan.columns()) { const colMapping = this.mapping.get(col); if (colMapping !== undefined) { for (const [row, vertex] of colMapping.entries()) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(columnsSpan.sheet, col, row), vertex]; } } } } *vertices() { for (const [_, col] of this.mapping) { for (const [_, value] of col) { if (value !== undefined) { yield value; } } } } } /***/ }), /* 94 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DenseStrategy: () => (/* binding */ DenseStrategy) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Mapping from cell addresses to vertices * * Uses Array to store addresses, having minimal memory usage for dense sheets and constant set/lookup. */ class DenseStrategy { /** * @param width - width of the stored sheet * @param height - height of the stored sheet */ constructor(width, height) { this.width = width; this.height = height; this.mapping = new Array(height); for (let i = 0; i < height; i++) { this.mapping[i] = new Array(width); } } /** @inheritDoc */ getCell(address) { return this.getCellVertex(address.col, address.row); } /** @inheritDoc */ setCell(address, newVertex) { this.width = Math.max(this.width, address.col + 1); this.height = Math.max(this.height, address.row + 1); const rowMapping = this.mapping[address.row]; if (!rowMapping) { this.mapping[address.row] = new Array(this.width); } this.mapping[address.row][address.col] = newVertex; } /** @inheritDoc */ has(address) { const row = this.mapping[address.row]; if (!row) { return false; } return !!row[address.col]; } /** @inheritDoc */ getHeight() { return this.height; } /** @inheritDoc */ getWidth() { return this.width; } removeCell(address) { if (this.mapping[address.row] !== undefined) { delete this.mapping[address.row][address.col]; } } addRows(row, numberOfRows) { const newRows = []; for (let i = 0; i < numberOfRows; i++) { newRows.push(new Array(this.width)); } this.mapping.splice(row, 0, ...newRows); this.height += numberOfRows; } addColumns(column, numberOfColumns) { for (let i = 0; i < this.height; i++) { if (this.mapping[i] !== undefined) { this.mapping[i].splice(column, 0, ...new Array(numberOfColumns)); } } this.width += numberOfColumns; } removeRows(removedRows) { this.mapping.splice(removedRows.rowStart, removedRows.numberOfRows); const rightmostRowRemoved = Math.min(this.height - 1, removedRows.rowEnd); const numberOfRowsRemoved = Math.max(0, rightmostRowRemoved - removedRows.rowStart + 1); this.height = Math.max(0, this.height - numberOfRowsRemoved); } removeColumns(removedColumns) { for (let i = 0; i < this.height; i++) { if (this.mapping[i] !== undefined) { this.mapping[i].splice(removedColumns.columnStart, removedColumns.numberOfColumns); } } const rightmostColumnRemoved = Math.min(this.width - 1, removedColumns.columnEnd); const numberOfColumnsRemoved = Math.max(0, rightmostColumnRemoved - removedColumns.columnStart + 1); this.width = Math.max(0, this.width - numberOfColumnsRemoved); } *getEntries(sheet) { for (let y = 0; y < this.height; ++y) { for (let x = 0; x < this.width; ++x) { const vertex = this.getCellVertex(x, y); if (vertex) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x, y), vertex]; } } } } *verticesFromColumn(column) { for (let y = 0; y < this.height; ++y) { const vertex = this.getCellVertex(column, y); if (vertex) { yield vertex; } } } *verticesFromRow(row) { for (let x = 0; x < this.width; ++x) { const vertex = this.getCellVertex(x, row); if (vertex) { yield vertex; } } } *verticesFromColumnsSpan(columnsSpan) { for (let x = columnsSpan.columnStart; x <= columnsSpan.columnEnd; ++x) { for (let y = 0; y < this.height; ++y) { const vertex = this.getCellVertex(x, y); if (vertex) { yield vertex; } } } } *verticesFromRowsSpan(rowsSpan) { for (let x = 0; x < this.width; ++x) { for (let y = rowsSpan.rowStart; y <= rowsSpan.rowEnd; ++y) { const vertex = this.getCellVertex(x, y); if (vertex) { yield vertex; } } } } *entriesFromRowsSpan(rowsSpan) { for (let x = 0; x < this.width; ++x) { for (let y = rowsSpan.rowStart; y <= rowsSpan.rowEnd; ++y) { const vertex = this.getCellVertex(x, y); if (vertex) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(rowsSpan.sheet, x, y), vertex]; } } } } *entriesFromColumnsSpan(columnsSpan) { for (let x = columnsSpan.columnStart; x <= columnsSpan.columnEnd; ++x) { for (let y = 0; y < this.height; ++y) { const vertex = this.getCellVertex(x, y); if (vertex) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(columnsSpan.sheet, x, y), vertex]; } } } } *vertices() { for (let y = 0; y < this.height; ++y) { for (let x = 0; x < this.width; ++x) { const vertex = this.getCellVertex(x, y); if (vertex) { yield vertex; } } } } getCellVertex(x, y) { var _a; return (_a = this.mapping[y]) === null || _a === void 0 ? void 0 : _a[x]; } } /***/ }), /* 95 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ InterpreterState: () => (/* binding */ InterpreterState) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class InterpreterState { constructor(formulaAddress, arraysFlag, formulaVertex) { this.formulaAddress = formulaAddress; this.arraysFlag = arraysFlag; this.formulaVertex = formulaVertex; } } /***/ }), /* 96 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EmptyValue: () => (/* reexport safe */ _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue), /* harmony export */ FunctionArgumentType: () => (/* reexport safe */ _plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType), /* harmony export */ FunctionPlugin: () => (/* reexport safe */ _plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin) /* harmony export */ }); /* harmony import */ var _plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /***/ }), /* 97 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FunctionArgumentType: () => (/* binding */ FunctionArgumentType), /* harmony export */ FunctionPlugin: () => (/* binding */ FunctionPlugin) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(98); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var FunctionArgumentType; (function (FunctionArgumentType) { /** * String type. */ FunctionArgumentType["STRING"] = "STRING"; /** * Floating point type. */ FunctionArgumentType["NUMBER"] = "NUMBER"; /** * Boolean type. */ FunctionArgumentType["BOOLEAN"] = "BOOLEAN"; /** * Any non-range value. */ FunctionArgumentType["SCALAR"] = "SCALAR"; /** * Any non-range, no-error type. */ FunctionArgumentType["NOERROR"] = "NOERROR"; /** * Range type. */ FunctionArgumentType["RANGE"] = "RANGE"; /** * Integer type. */ FunctionArgumentType["INTEGER"] = "INTEGER"; /** * String representing complex number. */ FunctionArgumentType["COMPLEX"] = "COMPLEX"; /** * Range or scalar. */ FunctionArgumentType["ANY"] = "ANY"; })(FunctionArgumentType || (FunctionArgumentType = {})); /** * Abstract class representing interpreter function plugin. * Plugin may contain multiple functions. Each function should be of type {@link PluginFunctionType} and needs to be * included in {@link implementedFunctions} */ class FunctionPlugin { constructor(interpreter) { this.coerceScalarToNumberOrError = arg => this.arithmeticHelper.coerceScalarToNumberOrError(arg); /** * A method that should wrap the logic of every built-in function and custom function. It: * - Evaluates the function's arguments. * - Validates the number of arguments against the [`parameters` array](#function-options). * - Coerces the argument values to types set in the [`parameters` array](#argument-validation-options). * - Handles optional arguments and default values according to options set in the [`parameters` array](#argument-validation-options). * - Validates the function's arguments against the [argument validation options](#argument-validation-options). * - Duplicates the arguments according to the [`repeatLastArgs` option](#function-options). * - Handles the [array arithmetic mode](arrays.md#array-arithmetic-mode). * - Performs [function vectorization](arrays.md#passing-arrays-to-scalar-functions-vectorization). * - Performs [argument broadcasting](arrays.md#broadcasting). */ this.runFunction = (args, state, metadata, functionImplementation) => { const evaluatedArguments = this.evaluateArguments(args, state, metadata); // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const argumentValues = evaluatedArguments.map(([value, _]) => value); const argumentIgnorableFlags = evaluatedArguments.map(([_, ignorable]) => ignorable); const argumentMetadata = this.buildMetadataForEachArgumentValue(argumentValues.length, metadata); const isVectorizationOn = state.arraysFlag && !metadata.vectorizationForbidden; if (!this.isNumberOfArgumentValuesValid(argumentMetadata, argumentValues.length)) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } const [resultArrayHeight, resultArrayWidth] = isVectorizationOn ? this.calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) : [1, 1]; if (resultArrayHeight === 1 && resultArrayWidth === 1) { const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, 0, 0); return this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType); } const resultArray = [...Array(resultArrayHeight).keys()].map(row => [...Array(resultArrayWidth).keys()].map(col => { const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col); const result = this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType); if (result instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { throw new Error('Function returning array cannot be vectorized.'); } return result; })); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues(resultArray); }; this.runFunctionWithReferenceArgument = (args, state, metadata, noArgCallback, referenceCallback, nonReferenceCallback = () => new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRefExpected)) => { if (args.length === 0) { return this.returnNumberWrapper(noArgCallback(), metadata.returnNumberType); } else if (args.length > 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } let arg = args[0]; while (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS) { arg = arg.expression; } let cellReference; if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE) { cellReference = arg.reference.toSimpleCellAddress(state.formulaAddress); } else if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE) { try { cellReference = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromAst(arg, state.formulaAddress).start; } catch (e) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRefExpected); } } if (cellReference !== undefined) { return this.returnNumberWrapper(referenceCallback(cellReference), metadata.returnNumberType); } return this.runFunction(args, state, metadata, nonReferenceCallback); }; this.interpreter = interpreter; this.dependencyGraph = interpreter.dependencyGraph; this.columnSearch = interpreter.columnSearch; this.config = interpreter.config; this.serialization = interpreter.serialization; this.arraySizePredictor = interpreter.arraySizePredictor; this.dateTimeHelper = interpreter.dateTimeHelper; this.arithmeticHelper = interpreter.arithmeticHelper; } evaluateAst(ast, state) { return this.interpreter.evaluateAst(ast, state); } arraySizeForAst(ast, state) { return this.arraySizePredictor.checkArraySizeForAst(ast, state); } listOfScalarValues(asts, state) { const ret = []; for (const argAst of asts) { const value = this.evaluateAst(argAst, state); if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { for (const scalarValue of value.valuesFromTopLeftCorner()) { ret.push([scalarValue, true]); } } else { ret.push([value, false]); } } return ret; } coerceToType(arg, coercedType, state) { let ret; if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { switch (coercedType.argumentType) { case FunctionArgumentType.RANGE: case FunctionArgumentType.ANY: ret = arg; break; default: { const coerce = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceRangeToScalar)(arg, state); if (coerce === undefined) { return undefined; } arg = coerce; } } } if (!(arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue)) { switch (coercedType.argumentType) { case FunctionArgumentType.INTEGER: case FunctionArgumentType.NUMBER: // eslint-disable-next-line no-case-declarations const coerced = this.coerceScalarToNumberOrError(arg); if (!(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.isExtendedNumber)(coerced)) { ret = coerced; break; } // eslint-disable-next-line no-case-declarations const value = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(coerced); if (coercedType.maxValue !== undefined && value > coercedType.maxValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge); } if (coercedType.minValue !== undefined && value < coercedType.minValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueSmall); } if (coercedType.lessThan !== undefined && value >= coercedType.lessThan) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge); } if (coercedType.greaterThan !== undefined && value <= coercedType.greaterThan) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueSmall); } if (coercedType.argumentType === FunctionArgumentType.INTEGER && !Number.isInteger(value)) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IntegerExpected); } ret = coerced; break; case FunctionArgumentType.STRING: ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceScalarToString)(arg); break; case FunctionArgumentType.BOOLEAN: ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceScalarToBoolean)(arg); break; case FunctionArgumentType.SCALAR: case FunctionArgumentType.NOERROR: case FunctionArgumentType.ANY: ret = arg; break; case FunctionArgumentType.RANGE: if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg; } ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceToRange)(arg); break; case FunctionArgumentType.COMPLEX: return this.arithmeticHelper.coerceScalarToComplex((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(arg)); } } if (coercedType.passSubtype || ret === undefined) { return ret; } else { return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(ret); } } calculateSingleCellOfResultArray(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags, functionImplementation, returnNumberType) { const coercedArguments = this.coerceArgumentsToRequiredTypes(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags); if (coercedArguments instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return coercedArguments; } const functionCalculationResult = functionImplementation(...coercedArguments); return this.returnNumberWrapper(functionCalculationResult, returnNumberType); } coerceArgumentsToRequiredTypes(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags) { const coercedArguments = []; for (let i = 0; i < argumentsMetadata.length; i++) { const argumentMetadata = argumentsMetadata[i]; const argumentValue = vectorizedArguments[i] !== undefined ? vectorizedArguments[i] : argumentMetadata === null || argumentMetadata === void 0 ? void 0 : argumentMetadata.defaultValue; if (argumentValue === undefined) { coercedArguments.push(undefined); continue; } const coercedValue = this.coerceToType(argumentValue, argumentMetadata, state); if (coercedValue === undefined && !argumentIgnorableFlags[i]) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } if (coercedValue instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError && argumentMetadata.argumentType !== FunctionArgumentType.SCALAR) { return coercedValue; } coercedArguments.push(coercedValue); } return coercedArguments; } vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col) { return argumentValues.map((value, i) => isVectorizationOn && this.isRangePassedAsAScalarArgument(value, argumentMetadata[i]) ? this.vectorizeAndBroadcastRangeArgument(value, row, col) : value); } vectorizeAndBroadcastRangeArgument(argumentValue, rowNum, colNum) { var _a; const targetRowNum = argumentValue.height() === 1 ? 0 : rowNum; const targetColNum = argumentValue.width() === 1 ? 0 : colNum; return (_a = argumentValue.data[targetRowNum]) === null || _a === void 0 ? void 0 : _a[targetColNum]; } evaluateArguments(args, state, metadata) { return metadata.expandRanges ? this.listOfScalarValues(args, state) : args.map(ast => [this.evaluateAst(ast, state), false]); } buildMetadataForEachArgumentValue(numberOfArgumentValuesPassed, metadata) { const argumentsMetadata = metadata.parameters ? [...metadata.parameters] : []; const isRepeatLastArgsValid = metadata.repeatLastArgs !== undefined && Number.isInteger(metadata.repeatLastArgs) && metadata.repeatLastArgs > 0; if (isRepeatLastArgsValid) { while (numberOfArgumentValuesPassed > argumentsMetadata.length) { argumentsMetadata.push(...argumentsMetadata.slice(argumentsMetadata.length - metadata.repeatLastArgs)); } } return argumentsMetadata; } isNumberOfArgumentValuesValid(argumentsMetadata, numberOfArgumentValuesPassed) { if (numberOfArgumentValuesPassed > argumentsMetadata.length) { return false; } if (numberOfArgumentValuesPassed < argumentsMetadata.length) { const metadataForMissingArguments = argumentsMetadata.slice(numberOfArgumentValuesPassed); const areMissingArgumentsOptional = metadataForMissingArguments.every(argMetadata => (argMetadata === null || argMetadata === void 0 ? void 0 : argMetadata.optionalArg) || (argMetadata === null || argMetadata === void 0 ? void 0 : argMetadata.defaultValue) !== undefined); return areMissingArgumentsOptional; } return true; } calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) { const argumentsThatRequireVectorization = argumentValues.filter((value, i) => this.isRangePassedAsAScalarArgument(value, argumentMetadata[i])); const height = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.height())); const width = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.width())); return [height, width]; } isRangePassedAsAScalarArgument(argumentValue, argumentMetadata) { if (argumentValue == null || argumentMetadata == null) { return false; } return argumentValue instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue && ![FunctionArgumentType.RANGE, FunctionArgumentType.ANY].includes(argumentMetadata.argumentType); } metadata(name) { const params = this.constructor.implementedFunctions[name]; if (params !== undefined) { return params; } throw new Error(`No metadata for function ${name}.`); } returnNumberWrapper(val, type, format) { if (type !== undefined && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.isExtendedNumber)(val)) { return this.arithmeticHelper.ExtendedNumberFactory((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(val), { type, format }); } else { return val; } } } /***/ }), /* 98 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArithmeticHelper: () => (/* binding */ ArithmeticHelper), /* harmony export */ coerceBooleanToNumber: () => (/* binding */ coerceBooleanToNumber), /* harmony export */ coerceComplexToString: () => (/* binding */ coerceComplexToString), /* harmony export */ coerceEmptyToValue: () => (/* binding */ coerceEmptyToValue), /* harmony export */ coerceRangeToScalar: () => (/* binding */ coerceRangeToScalar), /* harmony export */ coerceScalarToBoolean: () => (/* binding */ coerceScalarToBoolean), /* harmony export */ coerceScalarToString: () => (/* binding */ coerceScalarToString), /* harmony export */ coerceToRange: () => (/* binding */ coerceToRange), /* harmony export */ coerceToRangeNumbersOrError: () => (/* binding */ coerceToRangeNumbersOrError), /* harmony export */ fixNegativeZero: () => (/* binding */ fixNegativeZero), /* harmony export */ forceNormalizeString: () => (/* binding */ forceNormalizeString), /* harmony export */ isNumberOverflow: () => (/* binding */ isNumberOverflow), /* harmony export */ normalizeString: () => (/* binding */ normalizeString), /* harmony export */ numberCmp: () => (/* binding */ numberCmp), /* harmony export */ zeroIfEmpty: () => (/* binding */ zeroIfEmpty) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _StringHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(99); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const COMPLEX_NUMBER_SYMBOL = 'i'; const complexParsingRegexp = /^\s*([+-]?)\s*(([\d\.,]+(e[+-]?\d+)?)\s*([ij]?)|([ij]))\s*(([+-])\s*([+-]?)\s*(([\d\.,]+(e[+-]?\d+)?)\s*([ij]?)|([ij])))?$/; class ArithmeticHelper { constructor(config, dateTimeHelper, numberLiteralsHelper) { this.config = config; this.dateTimeHelper = dateTimeHelper; this.numberLiteralsHelper = numberLiteralsHelper; this.lt = (left, right) => { return this.compare(left, right) < 0; }; this.leq = (left, right) => { return this.compare(left, right) <= 0; }; this.gt = (left, right) => { return this.compare(left, right) > 0; }; this.geq = (left, right) => { return this.compare(left, right) >= 0; }; this.eq = (left, right) => { return this.compare(left, right) === 0; }; this.neq = (left, right) => { return this.compare(left, right) !== 0; }; this.pow = (left, right) => { return Math.pow((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(left), (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(right)); }; this.addWithEpsilonRaw = (left, right) => { const ret = left + right; if (Math.abs(ret) < this.actualEps * Math.abs(left)) { return 0; } else { return ret; } }; this.addWithEpsilon = (left, right) => { const typeOfResult = inferExtendedNumberTypeAdditive(left, right); return this.ExtendedNumberFactory(this.addWithEpsilonRaw((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(left), (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(right)), typeOfResult); }; this.unaryMinus = arg => { return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.cloneNumber)(arg, -(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg)); }; this.unaryPlus = arg => arg; this.unaryPercent = arg => { return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.PercentNumber((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg) / 100); }; this.concat = (left, right) => { return left.concat(right); }; this.nonstrictadd = (left, right) => { if (left instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return left; } else if (right instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return right; } else if (typeof left === 'number') { if (typeof right === 'number') { return this.addWithEpsilonRaw(left, right); } else { return left; } } else if (typeof right === 'number') { return right; } else { return 0; } }; /** * Subtracts two numbers * * Implementation of subtracting which is used in interpreter. * * @param left - left operand of subtraction * @param right - right operand of subtraction * @param eps - precision of comparison */ this.subtract = (leftArg, rightArg) => { const typeOfResult = inferExtendedNumberTypeAdditive(leftArg, rightArg); const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(leftArg); const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(rightArg); let ret = left - right; if (Math.abs(ret) < this.actualEps * Math.abs(left)) { ret = 0; } return this.ExtendedNumberFactory(ret, typeOfResult); }; this.divide = (leftArg, rightArg) => { const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(leftArg); const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(rightArg); if (right === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } else { const typeOfResult = inferExtendedNumberTypeMultiplicative(leftArg, rightArg); return this.ExtendedNumberFactory(left / right, typeOfResult); } }; this.multiply = (left, right) => { const typeOfResult = inferExtendedNumberTypeMultiplicative(left, right); return this.ExtendedNumberFactory((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(left) * (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(right), typeOfResult); }; this.manyToExactComplex = args => { const ret = []; for (const arg of args) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg) || typeof arg === 'string') { const coerced = this.coerceScalarToComplex(arg); if (!(coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError)) { ret.push(coerced); } } } return ret; }; this.coerceNumbersExactRanges = args => this.manyToNumbers(args, this.manyToExactNumbers); this.coerceNumbersCoerceRangesDropNulls = args => this.manyToNumbers(args, this.manyToCoercedNumbersDropNulls); this.manyToExactNumbers = args => { const ret = []; for (const arg of args) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg)); } } return ret; }; this.manyToOnlyNumbersDropNulls = args => { const ret = []; for (const arg of args) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg)); } else if (arg !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NumberExpected); } } return ret; }; this.manyToCoercedNumbersDropNulls = args => { const ret = []; for (const arg of args) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { continue; } const coerced = this.coerceScalarToNumberOrError(arg); if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(coerced)) { ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(coerced)); } } return ret; }; this.collator = (0,_StringHelper__WEBPACK_IMPORTED_MODULE_2__.collatorFromConfig)(config); this.actualEps = config.smartRounding ? config.precisionEpsilon : 0; } eqMatcherFunction(pattern) { const regexp = this.buildRegex(pattern); return cellValue => typeof cellValue === 'string' && regexp.test(this.normalizeString(cellValue)); } neqMatcherFunction(pattern) { const regexp = this.buildRegex(pattern); return cellValue => { return !(typeof cellValue === 'string') || !regexp.test(this.normalizeString(cellValue)); }; } searchString(pattern, text) { var _a; const regexp = this.buildRegex(pattern, false); const result = regexp.exec(text); return (_a = result === null || result === void 0 ? void 0 : result.index) !== null && _a !== void 0 ? _a : -1; } requiresRegex(pattern) { if (!this.config.useRegularExpressions && !this.config.useWildcards) { return !this.config.matchWholeCell; } for (let i = 0; i < pattern.length; i++) { const c = pattern.charAt(i); if (isWildcard(c) || this.config.useRegularExpressions && needsEscape(c)) { return true; } } return false; } floatCmp(leftArg, rightArg) { const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(leftArg); const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(rightArg); const mod = 1 + this.actualEps; if (right >= 0 && left * mod >= right && left <= right * mod) { return 0; } else if (right <= 0 && left * mod <= right && left >= right * mod) { return 0; } else if (left > right) { return 1; } else { return -1; } } coerceScalarToNumberOrError(arg) { var _a; if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } return (_a = this.coerceToMaybeNumber(arg)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NumberCoercion); } coerceToMaybeNumber(arg) { var _a; return (_a = this.coerceNonDateScalarToMaybeNumber(arg)) !== null && _a !== void 0 ? _a : typeof arg === 'string' ? this.dateTimeHelper.dateStringToDateNumber(arg) : undefined; } coerceNonDateScalarToMaybeNumber(arg) { if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return 0; } else if (typeof arg === 'string') { if (arg === '') { return 0; } const maybePercentNumber = this.coerceStringToMaybePercentNumber(arg); if (maybePercentNumber !== undefined) { return maybePercentNumber; } const maybeCurrencyNumber = this.coerceStringToMaybeCurrencyNumber(arg); if (maybeCurrencyNumber !== undefined) { return maybeCurrencyNumber; } return this.numberLiteralsHelper.numericStringToMaybeNumber(arg.trim()); } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return arg; } else if (typeof arg === 'boolean') { return Number(arg); } else { return undefined; } } coerceStringToMaybePercentNumber(input) { const trimmedInput = input.trim(); if (trimmedInput.endsWith('%')) { const numOfPercents = trimmedInput.slice(0, trimmedInput.length - 1).trim(); const parsedNumOfPercents = this.numberLiteralsHelper.numericStringToMaybeNumber(numOfPercents); if (parsedNumOfPercents !== undefined) { return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.PercentNumber(parsedNumOfPercents / 100); } } return undefined; } coerceStringToMaybeCurrencyNumber(input) { const matchedCurrency = this.currencyMatcher(input.trim()); if (matchedCurrency !== undefined) { const [currencySymbol, currencyValue] = matchedCurrency; const parsedCurrencyValue = this.numberLiteralsHelper.numericStringToMaybeNumber(currencyValue); if (parsedCurrencyValue !== undefined) { return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.CurrencyNumber(parsedCurrencyValue, currencySymbol); } } return undefined; } currencyMatcher(token) { for (const currency of this.config.currencySymbol) { if (token.startsWith(currency)) { return [currency, token.slice(currency.length).trim()]; } if (token.endsWith(currency)) { return [currency, token.slice(0, token.length - currency.length).trim()]; } } return undefined; } coerceComplexExactRanges(args) { const vals = []; for (const arg of args) { if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { vals.push(arg); } else if (arg !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { const coerced = this.coerceScalarToComplex(arg); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } else { vals.push(coerced); } } } const expandedVals = []; for (const val of vals) { if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { const arr = this.manyToExactComplex(val.valuesFromTopLeftCorner()); if (arr instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arr; } else { expandedVals.push(...arr); } } else { expandedVals.push(val); } } return expandedVals; } coerceScalarToComplex(arg) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return [0, 0]; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return [(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg), 0]; } else if (typeof arg === 'string') { return this.coerceStringToComplex(arg); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ComplexNumberExpected); } } ExtendedNumberFactory(value, typeFormat) { const { type, format } = typeFormat; switch (type) { case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW: return value; case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_CURRENCY: { return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.CurrencyNumber(value, format !== null && format !== void 0 ? format : this.config.currencySymbol[0]); } case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATE: return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.DateNumber(value, format); case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME: return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.DateTimeNumber(value, format); case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_TIME: return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.TimeNumber(value, format); case _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_PERCENT: return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.PercentNumber(value, format); } } buildRegex(pattern, matchWholeCell = true) { pattern = this.normalizeString(pattern); let regexpStr; let useWildcards = this.config.useWildcards; let useRegularExpressions = this.config.useRegularExpressions; if (useRegularExpressions) { try { RegExp(pattern); } catch (e) { useRegularExpressions = false; useWildcards = false; } } if (useRegularExpressions) { regexpStr = escapeNoCharacters(pattern, this.config.caseSensitive); } else if (useWildcards) { regexpStr = escapeNonWildcards(pattern, this.config.caseSensitive); } else { regexpStr = escapeAllCharacters(pattern, this.config.caseSensitive); } if (this.config.matchWholeCell && matchWholeCell) { return RegExp('^(' + regexpStr + ')$'); } else { return RegExp(regexpStr); } } normalizeString(str) { if (!this.config.caseSensitive) { str = str.toLowerCase(); } if (!this.config.accentSensitive) { str = normalizeString(str, 'nfd').replace(/[\u0300-\u036f]/g, ''); } return str; } compare(left, right) { if (typeof left === 'string' || typeof right === 'string') { const leftTmp = typeof left === 'string' ? this.dateTimeHelper.dateStringToDateNumber(left) : left; const rightTmp = typeof right === 'string' ? this.dateTimeHelper.dateStringToDateNumber(right) : right; if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(leftTmp) && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(rightTmp)) { return this.floatCmp(leftTmp, rightTmp); } } if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { left = coerceEmptyToValue(right); } else if (right === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { right = coerceEmptyToValue(left); } if (typeof left === 'string' && typeof right === 'string') { return this.stringCmp(left, right); } else if (typeof left === 'boolean' && typeof right === 'boolean') { return numberCmp(coerceBooleanToNumber(left), coerceBooleanToNumber(right)); } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(left) && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(right)) { return this.floatCmp(left, right); } else if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue && right === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return 0; } else { return numberCmp((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.CellValueTypeOrd)((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.getCellValueType)(left)), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.CellValueTypeOrd)((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.getCellValueType)(right))); } } stringCmp(left, right) { return this.collator.compare(left, right); } manyToNumbers(args, rangeFn) { const vals = []; for (const arg of args) { if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { vals.push(arg); } else { const coerced = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(this.coerceScalarToNumberOrError(arg)); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } else { vals.push(coerced); } } } const expandedVals = []; for (const val of vals) { if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { const arr = rangeFn(val.valuesFromTopLeftCorner()); if (arr instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arr; } else { expandedVals.push(...arr); } } else { expandedVals.push(val); } } return expandedVals; } coerceStringToComplex(arg) { const match = complexParsingRegexp.exec(arg); if (match === null) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ComplexNumberExpected); } let val1; if (match[6] !== undefined) { val1 = match[1] === '-' ? [0, -1] : [0, 1]; } else { val1 = this.parseComplexToken(match[1] + match[3], match[5]); } if (val1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val1; } if (match[8] === undefined) { return val1; } let val2; if (match[14] !== undefined) { val2 = match[9] === '-' ? [0, -1] : [0, 1]; } else { val2 = this.parseComplexToken(match[9] + match[11], match[13]); } if (val2 instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val2; } if (match[5] !== '' || match[13] === '') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ComplexNumberExpected); } if (match[8] === '+') { return [val1[0] + val2[0], val1[1] + val2[1]]; } else { return [val1[0] - val2[0], val1[1] - val2[1]]; } } parseComplexToken(arg, mod) { const val = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(this.coerceNonDateScalarToMaybeNumber(arg)); if (val === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ComplexNumberExpected); } if (mod === '') { return [val, 0]; } else { return [0, val]; } } } function coerceComplexToString([re, im], symb) { if (!isFinite(re) || !isFinite(im)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NaN); } symb = symb !== null && symb !== void 0 ? symb : COMPLEX_NUMBER_SYMBOL; if (im === 0) { return `${re}`; } const imStr = `${im === -1 || im === 1 ? '' : Math.abs(im)}${symb}`; if (re === 0) { return `${im < 0 ? '-' : ''}${imStr}`; } return `${re}${im < 0 ? '-' : '+'}${imStr}`; } function coerceToRange(arg) { if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { return arg; } else { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue.fromScalar(arg); } } function coerceToRangeNumbersOrError(arg) { if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue && arg.hasOnlyNumbers() || arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue.fromScalar(arg); } else { return null; } } function coerceBooleanToNumber(arg) { return Number(arg); } function coerceEmptyToValue(arg) { if (typeof arg === 'string') { return ''; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return 0; } else if (typeof arg === 'boolean') { return false; } else { return _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue; } } /** * Coerce scalar value to boolean if possible, or error if value is an error * * @param arg */ function coerceScalarToBoolean(arg) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError || typeof arg === 'boolean') { return arg; } else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return false; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg) !== 0; } else { const argUppered = arg.toUpperCase(); if (argUppered === 'TRUE') { return true; } else if (argUppered === 'FALSE') { return false; } else if (argUppered === '') { return false; } else { return undefined; } } } function coerceScalarToString(arg) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError || typeof arg === 'string') { return arg; } else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return ''; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg).toString(); } else { return arg ? 'TRUE' : 'FALSE'; } } function zeroIfEmpty(arg) { return arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue ? 0 : arg; } function numberCmp(leftArg, rightArg) { const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(leftArg); const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(rightArg); if (left > right) { return 1; } else if (left < right) { return -1; } else { return 0; } } function isNumberOverflow(arg) { return isNaN(arg) || arg === Infinity || arg === -Infinity; } function fixNegativeZero(arg) { if (arg === 0) { return 0; } else { return arg; } } function isWildcard(c) { return ['*', '?'].includes(c); } const escapedCharacters = ['{', '}', '[', ']', '(', ')', '<', '>', '=', '.', '+', '-', ',', '\\', '$', '^', '!']; function needsEscape(c) { return escapedCharacters.includes(c); } function escapeNonWildcards(pattern, caseSensitive) { let str = ''; for (let i = 0; i < pattern.length; i++) { const c = pattern.charAt(i); if (c === '~') { if (i == pattern.length - 1) { str += '~'; continue; } const d = pattern.charAt(i + 1); if (isWildcard(d) || needsEscape(d)) { str += '\\' + d; i++; } else { str += d; i++; } } else if (isWildcard(c)) { str += '.' + c; } else if (needsEscape(c)) { str += '\\' + c; } else if (caseSensitive) { str += c; } else { str += c.toLowerCase(); } } return str; } function escapeAllCharacters(pattern, caseSensitive) { let str = ''; for (let i = 0; i < pattern.length; i++) { const c = pattern.charAt(i); if (isWildcard(c) || needsEscape(c)) { str += '\\' + c; } else if (caseSensitive) { str += c; } else { str += c.toLowerCase(); } } return str; } function escapeNoCharacters(pattern, caseSensitive) { let str = ''; for (let i = 0; i < pattern.length; i++) { const c = pattern.charAt(i); if (isWildcard(c) || needsEscape(c)) { str += c; } else if (caseSensitive) { str += c; } else { str += c.toLowerCase(); } } return str; } function inferExtendedNumberTypeAdditive(leftArg, rightArg) { const { type: leftType, format: leftFormat } = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getTypeFormatOfExtendedNumber)(leftArg); const { type: rightType, format: rightFormat } = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getTypeFormatOfExtendedNumber)(rightArg); if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW) { return { type: rightType, format: rightFormat }; } if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW) { return { type: leftType, format: leftFormat }; } if ((leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME || leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATE) && (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME || rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATE)) { return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW }; } if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_TIME) { if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATE) { return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME, format: `${rightFormat} ${leftFormat}` }; } if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME) { return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME, format: rightFormat }; } } if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_TIME) { if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATE) { return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME, format: `${leftFormat} ${rightFormat}` }; } if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME) { return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_DATETIME, format: leftFormat }; } } return { type: leftType, format: leftFormat }; } function inferExtendedNumberTypeMultiplicative(leftArg, rightArg) { let { type: leftType, format: leftFormat } = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getTypeFormatOfExtendedNumber)(leftArg); let { type: rightType, format: rightFormat } = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getTypeFormatOfExtendedNumber)(rightArg); if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_PERCENT) { leftType = _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW; leftFormat = undefined; } if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_PERCENT) { rightType = _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW; rightFormat = undefined; } if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW) { return { type: rightType, format: rightFormat }; } if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW) { return { type: leftType, format: leftFormat }; } return { type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.NumberType.NUMBER_RAW }; } function forceNormalizeString(str) { return normalizeString(str.toLowerCase(), 'nfd').replace(/[\u0300-\u036f]/g, ''); } function coerceRangeToScalar(arg, state) { var _a; if (arg.isAdHoc()) { return (_a = arg.data[0]) === null || _a === void 0 ? void 0 : _a[0]; } const range = arg.range; if (state.formulaAddress.sheet === range.sheet) { if (range.width() === 1) { const offset = state.formulaAddress.row - range.start.row; if (offset >= 0 && offset < range.height()) { return arg.data[offset][0]; } } else if (range.height() === 1) { const offset = state.formulaAddress.col - range.start.col; if (offset >= 0 && offset < range.width()) { return arg.data[0][offset]; } } } return undefined; } function normalizeString(str, form) { return str.normalize(form.toUpperCase()); } /***/ }), /* 99 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ collatorFromConfig: () => (/* binding */ collatorFromConfig) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function collatorFromConfig(config) { const sensitivity = config.caseSensitive ? config.accentSensitive ? 'variant' : 'case' : config.accentSensitive ? 'accent' : 'base'; const caseFirst = config.caseFirst; const ignorePunctuation = config.ignorePunctuation; return new Intl.Collator(config.localeLang, { sensitivity, caseFirst, ignorePunctuation }); } /***/ }), /* 100 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DetailedCellError: () => (/* binding */ DetailedCellError) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class DetailedCellError { constructor(error, value, address) { var _a; this.value = value; this.address = address; this.type = error.type; this.message = (_a = error.message) !== null && _a !== void 0 ? _a : ''; } toString() { return this.value; } valueOf() { return this.value; } } /***/ }), /* 101 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Config: () => (/* binding */ Config), /* harmony export */ getDefaultConfig: () => (/* binding */ getDefaultConfig) /* harmony export */ }); /* harmony import */ var _ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(102); /* harmony import */ var _DateTimeDefault__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(104); /* harmony import */ var _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(105); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(77); /* harmony import */ var _format_format__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(106); /* harmony import */ var _helpers_licenseKeyValidator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(108); /* harmony import */ var _HyperFormula__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(110); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const privatePool = new WeakMap(); class Config { constructor(options = {}, showDeprecatedWarns = true) { const { accentSensitive, binarySearchThreshold, caseSensitive, caseFirst, chooseAddressMappingPolicy, context, currencySymbol, dateFormats, decimalSeparator, evaluateNullToZero, functionArgSeparator, functionPlugins, ignorePunctuation, leapYear1900, localeLang, language, ignoreWhiteSpace, licenseKey, matchWholeCell, arrayColumnSeparator, arrayRowSeparator, maxRows, maxColumns, nullYear, nullDate, parseDateTime, precisionEpsilon, precisionRounding, stringifyDateTime, stringifyDuration, smartRounding, timeFormats, thousandSeparator, useArrayArithmetic, useStats, undoLimit, useColumnIndex, useRegularExpressions, useWildcards } = options; if (showDeprecatedWarns) { Config.warnDeprecatedOptions(options); } this.useArrayArithmetic = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(useArrayArithmetic, 'boolean', 'useArrayArithmetic'); this.accentSensitive = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(accentSensitive, 'boolean', 'accentSensitive'); this.caseSensitive = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(caseSensitive, 'boolean', 'caseSensitive'); this.caseFirst = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(caseFirst, ['upper', 'lower', 'false'], 'caseFirst'); this.ignorePunctuation = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(ignorePunctuation, 'boolean', 'ignorePunctuation'); this.chooseAddressMappingPolicy = chooseAddressMappingPolicy !== null && chooseAddressMappingPolicy !== void 0 ? chooseAddressMappingPolicy : Config.defaultConfig.chooseAddressMappingPolicy; this.dateFormats = [...(0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParamCheck)(dateFormats, Array.isArray, 'array', 'dateFormats')]; this.timeFormats = [...(0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParamCheck)(timeFormats, Array.isArray, 'array', 'timeFormats')]; this.functionArgSeparator = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(functionArgSeparator, 'string', 'functionArgSeparator'); this.decimalSeparator = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(decimalSeparator, ['.', ','], 'decimalSeparator'); this.language = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(language, 'string', 'language'); this.ignoreWhiteSpace = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(ignoreWhiteSpace, ['standard', 'any'], 'ignoreWhiteSpace'); this.licenseKey = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(licenseKey, 'string', 'licenseKey'); this.thousandSeparator = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(thousandSeparator, ['', ',', ' ', '.'], 'thousandSeparator'); this.arrayColumnSeparator = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(arrayColumnSeparator, [',', ';'], 'arrayColumnSeparator'); this.arrayRowSeparator = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(arrayRowSeparator, [';', '|'], 'arrayRowSeparator'); this.localeLang = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(localeLang, 'string', 'localeLang'); this.functionPlugins = [...(functionPlugins !== null && functionPlugins !== void 0 ? functionPlugins : Config.defaultConfig.functionPlugins)]; this.smartRounding = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(smartRounding, 'boolean', 'smartRounding'); this.evaluateNullToZero = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(evaluateNullToZero, 'boolean', 'evaluateNullToZero'); this.nullYear = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(nullYear, 'number', 'nullYear'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.nullYear, 'nullYear', 0); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtMost)(this.nullYear, 'nullYear', 100); this.precisionRounding = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(precisionRounding, 'number', 'precisionRounding'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.precisionRounding, 'precisionRounding', 0); this.precisionEpsilon = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(precisionEpsilon, 'number', 'precisionEpsilon'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.precisionEpsilon, 'precisionEpsilon', 0); this.useColumnIndex = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(useColumnIndex, 'boolean', 'useColumnIndex'); this.useStats = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(useStats, 'boolean', 'useStats'); this.binarySearchThreshold = binarySearchThreshold !== null && binarySearchThreshold !== void 0 ? binarySearchThreshold : Config.defaultConfig.binarySearchThreshold; this.parseDateTime = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(parseDateTime, 'function', 'parseDateTime'); this.stringifyDateTime = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(stringifyDateTime, 'function', 'stringifyDateTime'); this.stringifyDuration = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(stringifyDuration, 'function', 'stringifyDuration'); this.translationPackage = _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.getLanguage(this.language); this.errorMapping = this.translationPackage.buildErrorMapping(); this.nullDate = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParamCheck)(nullDate, _DateTimeHelper__WEBPACK_IMPORTED_MODULE_2__.instanceOfSimpleDate, 'IDate', 'nullDate'); this.leapYear1900 = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(leapYear1900, 'boolean', 'leapYear1900'); this.undoLimit = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(undoLimit, 'number', 'undoLimit'); this.useRegularExpressions = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(useRegularExpressions, 'boolean', 'useRegularExpressions'); this.useWildcards = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(useWildcards, 'boolean', 'useWildcards'); this.matchWholeCell = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(matchWholeCell, 'boolean', 'matchWholeCell'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.undoLimit, 'undoLimit', 0); this.maxRows = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(maxRows, 'number', 'maxRows'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.maxRows, 'maxRows', 1); this.maxColumns = (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParam)(maxColumns, 'number', 'maxColumns'); this.currencySymbol = this.setupCurrencySymbol(currencySymbol); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.validateNumberToBeAtLeast)(this.maxColumns, 'maxColumns', 1); this.context = context; privatePool.set(this, { licenseKeyValidityState: (0,_helpers_licenseKeyValidator__WEBPACK_IMPORTED_MODULE_6__.checkLicenseKeyValidity)(this.licenseKey) }); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configCheckIfParametersNotInConflict)({ value: this.decimalSeparator, name: 'decimalSeparator' }, { value: this.functionArgSeparator, name: 'functionArgSeparator' }, { value: this.thousandSeparator, name: 'thousandSeparator' }); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configCheckIfParametersNotInConflict)({ value: this.arrayRowSeparator, name: 'arrayRowSeparator' }, { value: this.arrayColumnSeparator, name: 'arrayColumnSeparator' }); } setupCurrencySymbol(currencySymbol) { const valueAfterCheck = [...(0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_0__.configValueFromParamCheck)(currencySymbol, Array.isArray, 'array', 'currencySymbol')]; valueAfterCheck.forEach(val => { if (typeof val !== 'string') { throw new _errors__WEBPACK_IMPORTED_MODULE_4__.ExpectedValueOfTypeError('string[]', 'currencySymbol'); } if (val === '') { throw new _errors__WEBPACK_IMPORTED_MODULE_4__.ConfigValueEmpty('currencySymbol'); } }); return valueAfterCheck; } /** * Proxied property to its private counterpart. This makes the property * as accessible as the other Config options but without ability to change the value. * * @internal */ get licenseKeyValidityState() { return privatePool.get(this).licenseKeyValidityState; } getConfig() { return getFullConfigFromPartial(this); } mergeConfig(init) { const mergedConfig = Object.assign({}, this.getConfig(), init); Config.warnDeprecatedOptions(init); return new Config(mergedConfig, false); } static warnDeprecatedOptions(options) { Config.warnDeprecatedIfUsed(options.binarySearchThreshold, 'binarySearchThreshold', '1.1'); } // eslint-disable-next-line @typescript-eslint/no-explicit-any static warnDeprecatedIfUsed(inputValue, paramName, fromVersion, replacementName) { if (inputValue !== undefined) { if (replacementName === undefined) { console.warn(`${paramName} option is deprecated since ${fromVersion}`); } else { console.warn(`${paramName} option is deprecated since ${fromVersion}, please use ${replacementName}`); } } } } Config.defaultConfig = { accentSensitive: false, binarySearchThreshold: 20, currencySymbol: ['$'], caseSensitive: false, caseFirst: 'lower', context: undefined, chooseAddressMappingPolicy: new _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_3__.AlwaysDense(), dateFormats: ['DD/MM/YYYY', 'DD/MM/YY'], decimalSeparator: '.', evaluateNullToZero: false, functionArgSeparator: ',', functionPlugins: [], ignorePunctuation: false, language: 'enGB', ignoreWhiteSpace: 'standard', licenseKey: '', leapYear1900: false, localeLang: 'en', matchWholeCell: true, arrayColumnSeparator: ',', arrayRowSeparator: ';', maxRows: 40000, maxColumns: 18278, nullYear: 30, nullDate: { year: 1899, month: 12, day: 30 }, parseDateTime: _DateTimeDefault__WEBPACK_IMPORTED_MODULE_1__.defaultParseToDateTime, precisionEpsilon: 1e-13, precisionRounding: 14, smartRounding: true, stringifyDateTime: _format_format__WEBPACK_IMPORTED_MODULE_5__.defaultStringifyDateTime, stringifyDuration: _format_format__WEBPACK_IMPORTED_MODULE_5__.defaultStringifyDuration, timeFormats: ['hh:mm', 'hh:mm:ss.sss'], thousandSeparator: '', undoLimit: 20, useRegularExpressions: false, useWildcards: true, useColumnIndex: false, useStats: false, useArrayArithmetic: false }; function getFullConfigFromPartial(partialConfig) { var _a; // eslint-disable-next-line @typescript-eslint/no-explicit-any const ret = {}; for (const key in Config.defaultConfig) { const val = (_a = partialConfig[key]) !== null && _a !== void 0 ? _a : Config.defaultConfig[key]; if (Array.isArray(val)) { ret[key] = [...val]; } else { ret[key] = val; } } return ret; } function getDefaultConfig() { return getFullConfigFromPartial({}); } /***/ }), /* 102 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ configCheckIfParametersNotInConflict: () => (/* binding */ configCheckIfParametersNotInConflict), /* harmony export */ configValueFromParam: () => (/* binding */ configValueFromParam), /* harmony export */ configValueFromParamCheck: () => (/* binding */ configValueFromParamCheck), /* harmony export */ validateArgToType: () => (/* binding */ validateArgToType), /* harmony export */ validateNumberToBeAtLeast: () => (/* binding */ validateNumberToBeAtLeast), /* harmony export */ validateNumberToBeAtMost: () => (/* binding */ validateNumberToBeAtMost) /* harmony export */ }); /* harmony import */ var _Config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(101); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function configValueFromParam(inputValue, expectedType, paramName) { if (typeof inputValue === 'undefined') { return _Config__WEBPACK_IMPORTED_MODULE_0__.Config.defaultConfig[paramName]; } else if (typeof expectedType === 'string') { if (typeof inputValue === expectedType) { return inputValue; } else { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ExpectedValueOfTypeError(expectedType, paramName); } } else { if (expectedType.includes(inputValue)) { return inputValue; } else { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ExpectedOneOfValuesError(expectedType.map(val => `'${val}'`).join(' '), paramName); } } } function validateNumberToBeAtLeast(value, paramName, minimum) { if (value < minimum) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ConfigValueTooSmallError(paramName, minimum); } } function validateNumberToBeAtMost(value, paramName, maximum) { if (value > maximum) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ConfigValueTooBigError(paramName, maximum); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function configValueFromParamCheck(inputValue, typeCheck, expectedType, paramName) { if (typeCheck(inputValue)) { return inputValue; } else if (typeof inputValue === 'undefined') { return _Config__WEBPACK_IMPORTED_MODULE_0__.Config.defaultConfig[paramName]; } else { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ExpectedValueOfTypeError(expectedType, paramName); } } function configCheckIfParametersNotInConflict(...params) { const valuesMap = new Map(); params.forEach(param => { const names = valuesMap.get(param.value) || []; names.push(param.name); valuesMap.set(param.value, names); }); const duplicates = []; for (const entry of valuesMap.values()) { if (entry.length > 1) { duplicates.push(entry); } } if (duplicates.length > 0) { duplicates.forEach(entry => entry.sort()); const paramNames = duplicates.map(entry => `[${entry}]`).join('; '); throw new Error(`Config initialization failed. Parameters in conflict: ${paramNames}`); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function validateArgToType(inputValue, expectedType, paramName) { if (typeof inputValue !== expectedType) { throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ExpectedValueOfTypeError(expectedType, paramName); } } /***/ }), /* 103 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TIME_FORMAT_SECONDS_ITEM_REGEXP: () => (/* binding */ TIME_FORMAT_SECONDS_ITEM_REGEXP), /* harmony export */ defaultParseToDateTime: () => (/* binding */ defaultParseToDateTime) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const TIME_FORMAT_SECONDS_ITEM_REGEXP = new RegExp('^ss(\\.(s+|0+))?$'); const QUICK_CHECK_REGEXP = new RegExp('^[0-9/.\\-: ]+[ap]?m?$'); const WHITESPACE_REGEXP = new RegExp('\\s+'); const DATE_SEPARATOR_REGEXP = new RegExp('[ /.-]'); const TIME_SEPARATOR = ':'; const SECONDS_PRECISION = 1000; const memoizedParseTimeFormat = memoize(parseTimeFormat); const memoizedParseDateFormat = memoize(parseDateFormat); /** * Parses a DateTime value from a string if the string matches the given date format and time format. * * Idea for more readable implementation: * - divide string into parts by a regexp [date_regexp]? [time_regexp]? [ampm_regexp]? * - start by finding the time part, because it is unambiguous '([0-9]+:[0-9:.]+ ?[ap]?m?)$', before it is the date part * - OR split by spaces - last segment is ampm token, second to last is time (with or without ampm), rest is date * If applied: * - date parsing might work differently after these changes but still according to the docs * - make sure to test edge cases like timeFormats: ['hh', 'ss.ss'] etc, string: '01-01-2019 AM', 'PM' */ function defaultParseToDateTime(text, dateFormat, timeFormat) { if (dateFormat === undefined && timeFormat === undefined) { return undefined; } let dateTimeString = text.replace(WHITESPACE_REGEXP, ' ').trim().toLowerCase(); if (!doesItLookLikeADateTimeQuickCheck(dateTimeString)) { return undefined; } let ampmToken = dateTimeString.substring(dateTimeString.length - 2); if (ampmToken === 'am' || ampmToken === 'pm') { dateTimeString = dateTimeString.substring(0, dateTimeString.length - 2).trim(); } else { ampmToken = dateTimeString.substring(dateTimeString.length - 1); if (ampmToken === 'a' || ampmToken === 'p') { dateTimeString = dateTimeString.substring(0, dateTimeString.length - 1).trim(); } else { ampmToken = undefined; } } const dateItems = dateTimeString.split(DATE_SEPARATOR_REGEXP); if (dateItems.length >= 2 && dateItems[dateItems.length - 2].includes(TIME_SEPARATOR)) { dateItems[dateItems.length - 2] = dateItems[dateItems.length - 2] + '.' + dateItems[dateItems.length - 1]; dateItems.pop(); } const timeItems = dateItems[dateItems.length - 1].split(TIME_SEPARATOR); if (ampmToken !== undefined) { timeItems.push(ampmToken); } if (dateItems.length === 1) { return defaultParseToTime(timeItems, timeFormat); } if (timeItems.length === 1) { return defaultParseToDate(dateItems, dateFormat); } const parsedDate = defaultParseToDate(dateItems.slice(0, dateItems.length - 1), dateFormat); const parsedTime = defaultParseToTime(timeItems, timeFormat); if (parsedDate === undefined) { return undefined; } else if (parsedTime === undefined) { return undefined; } else { return Object.assign(Object.assign({}, parsedDate), parsedTime); } } /** * Parses a time value from a string if the string matches the given time format. */ function defaultParseToTime(timeItems, timeFormat) { var _a, _b, _c; if (timeFormat === undefined) { return undefined; } const { itemsCount, hourItem, minuteItem, secondItem } = memoizedParseTimeFormat(timeFormat); let ampm = undefined; if (timeItems[timeItems.length - 1] === 'am' || timeItems[timeItems.length - 1] === 'a') { ampm = false; timeItems.pop(); } else if (timeItems[timeItems.length - 1] === 'pm' || timeItems[timeItems.length - 1] === 'p') { ampm = true; timeItems.pop(); } if (timeItems.length !== itemsCount) { return undefined; } const secondsParsed = Number((_a = timeItems[secondItem]) !== null && _a !== void 0 ? _a : '0'); if (!Number.isFinite(secondsParsed)) { return undefined; } const seconds = Math.round(secondsParsed * SECONDS_PRECISION) / SECONDS_PRECISION; const minutes = Number((_b = timeItems[minuteItem]) !== null && _b !== void 0 ? _b : '0'); if (!(Number.isFinite(minutes) && Number.isInteger(minutes))) { return undefined; } const hoursParsed = Number((_c = timeItems[hourItem]) !== null && _c !== void 0 ? _c : '0'); if (!(Number.isFinite(hoursParsed) && Number.isInteger(hoursParsed))) { return undefined; } if (ampm !== undefined && (hoursParsed < 0 || hoursParsed > 12)) { return undefined; } const hours = ampm !== undefined ? hoursParsed % 12 + (ampm ? 12 : 0) : hoursParsed; return { hours, minutes, seconds }; } /** * Parses a date value from a string if the string matches the given date format. */ function defaultParseToDate(dateItems, dateFormat) { var _a; if (dateFormat === undefined) { return undefined; } const { itemsCount, dayItem, monthItem, shortYearItem, longYearItem } = memoizedParseDateFormat(dateFormat); if (dateItems.length !== itemsCount) { return undefined; } const day = Number(dateItems[dayItem]); if (!(Number.isFinite(day) && Number.isInteger(day))) { return undefined; } const month = Number(dateItems[monthItem]); if (!(Number.isFinite(month) && Number.isInteger(month))) { return undefined; } if (dateItems[longYearItem] && dateItems[shortYearItem]) { return undefined; } const year = Number((_a = dateItems[longYearItem]) !== null && _a !== void 0 ? _a : dateItems[shortYearItem]); if (!(Number.isFinite(year) && Number.isInteger(year))) { return undefined; } if (dateItems[longYearItem] && (year < 1000 || year > 9999)) { return undefined; } if (dateItems[shortYearItem] && (year < 0 || year > 99)) { return undefined; } return { year, month, day }; } /** * Parses a time format string into a format object. */ function parseTimeFormat(timeFormat) { const formatLowercase = timeFormat.toLowerCase().trim(); const formatWithoutAmPmItem = formatLowercase.endsWith('am/pm') ? formatLowercase.substring(0, formatLowercase.length - 5) : formatLowercase.endsWith('a/p') ? formatLowercase.substring(0, timeFormat.length - 3) : formatLowercase; const items = formatWithoutAmPmItem.trim().split(TIME_SEPARATOR); return { itemsCount: items.length, hourItem: items.indexOf('hh'), minuteItem: items.indexOf('mm'), secondItem: items.findIndex(item => TIME_FORMAT_SECONDS_ITEM_REGEXP.test(item)) }; } /** * Parses a date format string into a format object. */ function parseDateFormat(dateFormat) { const items = dateFormat.toLowerCase().trim().split(DATE_SEPARATOR_REGEXP); return { itemsCount: items.length, dayItem: items.indexOf('dd'), monthItem: items.indexOf('mm'), shortYearItem: items.indexOf('yy'), longYearItem: items.indexOf('yyyy') }; } /** * If this function returns false, the string is not parsable as a date time. Otherwise, it might be. * This is a quick check that is used to avoid running the more expensive parsing operations. */ function doesItLookLikeADateTimeQuickCheck(text) { return QUICK_CHECK_REGEXP.test(text); } /** * Function memoization for improved performance. */ function memoize(fn) { const memoizedResults = {}; return arg => { const memoizedResult = memoizedResults[arg]; if (memoizedResult !== undefined) { return memoizedResult; } const result = fn(arg); memoizedResults[arg] = result; return result; }; } /***/ }), /* 104 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DateTimeHelper: () => (/* binding */ DateTimeHelper), /* harmony export */ instanceOfSimpleDate: () => (/* binding */ instanceOfSimpleDate), /* harmony export */ instanceOfSimpleTime: () => (/* binding */ instanceOfSimpleTime), /* harmony export */ maxDate: () => (/* binding */ maxDate), /* harmony export */ numberToSimpleTime: () => (/* binding */ numberToSimpleTime), /* harmony export */ offsetMonth: () => (/* binding */ offsetMonth), /* harmony export */ roundToNearestSecond: () => (/* binding */ roundToNearestSecond), /* harmony export */ timeToNumber: () => (/* binding */ timeToNumber), /* harmony export */ toBasisEU: () => (/* binding */ toBasisEU), /* harmony export */ truncateDayInMonth: () => (/* binding */ truncateDayInMonth) /* harmony export */ }); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const prefSumDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; const SECONDS_PER_MINUTE = 60; const MINUTES_PER_HOUR = 60; const HOURS_PER_DAY = 24; // eslint-disable-next-line @typescript-eslint/no-explicit-any function instanceOfSimpleDate(obj) { if (obj && (typeof obj === 'object' || typeof obj === 'function')) { return 'year' in obj && typeof obj.year === 'number' && 'month' in obj && typeof obj.month === 'number' && 'day' in obj && typeof obj.day === 'number'; } else { return false; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any function instanceOfSimpleTime(obj) { if (obj && (typeof obj === 'object' || typeof obj === 'function')) { return 'hours' in obj && typeof obj.hours === 'number' && 'minutes' in obj && typeof obj.minutes === 'number' && 'seconds' in obj && typeof obj.seconds === 'number'; } else { return false; } } const maxDate = { year: 9999, month: 12, day: 31 }; class DateTimeHelper { constructor(config) { this.config = config; this.minDateAbsoluteValue = this.dateToNumberFromZero(config.nullDate); this.maxDateValue = this.dateToNumber(maxDate); this.leapYear1900 = config.leapYear1900; // code below fixes epochYearStart while being leapYear1900 sensitive // if nullDate is earlier than fateful 28 Feb 1900 and 1900 is not supposed to be leap year, then we should // add two days (this is the config default) // otherwise only one day if (!this.leapYear1900 && 0 <= this.dateToNumber({ year: 1900, month: 2, day: 28 })) { this.epochYearZero = this.numberToSimpleDate(2).year; } else { this.epochYearZero = this.numberToSimpleDate(1).year; } this.parseDateTime = config.parseDateTime; } getWithinBounds(dayNumber) { return dayNumber <= this.maxDateValue && dayNumber >= 0 ? dayNumber : undefined; } dateStringToDateNumber(dateTimeString) { const { dateTime, dateFormat = '', timeFormat = '' } = this.parseDateTimeFromConfigFormats(dateTimeString); if (dateTime === undefined) { return undefined; } if (instanceOfSimpleTime(dateTime)) { if (instanceOfSimpleDate(dateTime)) { return new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.DateTimeNumber(timeToNumber(dateTime) + this.dateToNumber(dateTime), dateFormat + ' ' + timeFormat); } else { return new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.TimeNumber(timeToNumber(dateTime), timeFormat); } } else { if (instanceOfSimpleDate(dateTime)) { return new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.DateNumber(this.dateToNumber(dateTime), dateFormat); } else { return 0; } } } parseDateTimeFromConfigFormats(dateTimeString) { return this.parseDateTimeFromFormats(dateTimeString, this.config.dateFormats, this.config.timeFormats); } getNullYear() { return this.config.nullYear; } getEpochYearZero() { return this.epochYearZero; } isValidDate(date) { if (isNaN(date.year) || isNaN(date.month) || isNaN(date.day)) { return false; } else if (date.day !== Math.round(date.day) || date.month !== Math.round(date.month) || date.year !== Math.round(date.year)) { return false; } else if (date.year < 1582) { // Gregorian calendar start return false; } else if (date.month < 1 || date.month > 12) { return false; } else if (date.day < 1) { return false; } else if (this.isLeapYear(date.year) && date.month === 2) { return date.day <= 29; } else { return date.day <= numDays[date.month - 1]; } } dateToNumber(date) { return this.dateToNumberFromZero(date) - this.minDateAbsoluteValue; } relativeNumberToAbsoluteNumber(arg) { return arg + this.minDateAbsoluteValue - (this.leapYear1900 ? 1 : 0); } numberToSimpleDate(arg) { const dateNumber = Math.floor(arg) + this.minDateAbsoluteValue; let year = Math.floor(dateNumber / 365.2425); if (this.dateToNumberFromZero({ year: year + 1, month: 1, day: 1 }) <= dateNumber) { year++; } else if (this.dateToNumberFromZero({ year: year - 1, month: 1, day: 1 }) > dateNumber) { year--; } const dayOfYear = dateNumber - this.dateToNumberFromZero({ year, month: 1, day: 1 }); const month = dayToMonth(dayOfYear - (this.isLeapYear(year) && dayOfYear >= 59 ? 1 : 0)); const day = dayOfYear - prefSumDays[month] - (this.isLeapYear(year) && month > 1 ? 1 : 0); return { year, month: month + 1, day: day + 1 }; } numberToSimpleDateTime(arg) { const time = numberToSimpleTime(arg % 1); const carryDays = Math.floor(time.hours / HOURS_PER_DAY); time.hours = time.hours % HOURS_PER_DAY; const date = this.numberToSimpleDate(Math.floor(arg) + carryDays); return Object.assign(Object.assign({}, date), time); } leapYearsCount(year) { return Math.floor(year / 4) - Math.floor(year / 100) + Math.floor(year / 400) + (this.config.leapYear1900 && year >= 1900 ? 1 : 0); } daysInMonth(year, month) { if (this.isLeapYear(year) && month === 2) { return 29; } else { return numDays[month - 1]; } } endOfMonth(date) { return { year: date.year, month: date.month, day: this.daysInMonth(date.year, date.month) }; } toBasisUS(start, end) { if (start.day === 31) { start.day = 30; } if (start.day === 30 && end.day === 31) { end.day = 30; } if (start.month === 2 && start.day === this.daysInMonth(start.year, start.month)) { start.day = 30; if (end.month === 2 && end.day === this.daysInMonth(end.year, end.month)) { end.day = 30; } } return [start, end]; } yearLengthForBasis(start, end) { if (start.year !== end.year) { if (start.year + 1 !== end.year || start.month < end.month || start.month === end.month && start.day < end.day) { // this is true IFF at least one year of gap between dates return (this.leapYearsCount(end.year) - this.leapYearsCount(start.year - 1)) / (end.year - start.year + 1) + 365; } if (this.countLeapDays(end) !== this.countLeapDays({ year: start.year, month: start.month, day: start.day - 1 })) { return 366; } else { return 365; } } if (this.isLeapYear(start.year)) { return 366; } else { return 365; } } parseSingleFormat(dateString, dateFormat, timeFormat) { const dateTime = this.parseDateTime(dateString, dateFormat, timeFormat); if (instanceOfSimpleDate(dateTime)) { if (dateTime.year >= 0 && dateTime.year < 100) { if (dateTime.year < this.getNullYear()) { dateTime.year += 2000; } else { dateTime.year += 1900; } } if (!this.isValidDate(dateTime)) { return undefined; } } return dateTime; } parseDateTimeFromFormats(dateTimeString, dateFormats, timeFormats) { const dateFormatsArray = dateFormats.length === 0 ? [undefined] : dateFormats; const timeFormatsArray = timeFormats.length === 0 ? [undefined] : timeFormats; for (const dateFormat of dateFormatsArray) { for (const timeFormat of timeFormatsArray) { const dateTime = this.parseSingleFormat(dateTimeString, dateFormat, timeFormat); if (dateTime !== undefined) { return { dateTime, timeFormat, dateFormat }; } } } return {}; } countLeapDays(date) { if (date.month > 2 || date.month === 2 && date.day >= 29) { return this.leapYearsCount(date.year); } else { return this.leapYearsCount(date.year - 1); } } dateToNumberFromZero(date) { return 365 * date.year + prefSumDays[date.month - 1] + date.day - 1 + (date.month <= 2 ? this.leapYearsCount(date.year - 1) : this.leapYearsCount(date.year)); } isLeapYear(year) { if (year % 4) { return false; } else if (year % 100) { return true; } else if (year % 400) { return year === 1900 && this.config.leapYear1900; } else { return true; } } } function dayToMonth(dayOfYear) { let month = 0; if (prefSumDays[month + 6] <= dayOfYear) { month += 6; } if (prefSumDays[month + 3] <= dayOfYear) { month += 3; } if (prefSumDays[month + 2] <= dayOfYear) { month += 2; } else if (prefSumDays[month + 1] <= dayOfYear) { month += 1; } return month; } function offsetMonth(date, offset) { const totalM = 12 * date.year + date.month - 1 + offset; return { year: Math.floor(totalM / 12), month: totalM % 12 + 1, day: date.day }; } function truncateDayInMonth(date) { return { year: date.year, month: date.month, day: Math.min(date.day, numDays[date.month - 1]) }; } function roundToNearestSecond(arg) { return Math.round(arg * 3600 * 24) / (3600 * 24); } function roundToEpsilon(arg, epsilon = 1) { return Math.round(arg * epsilon) / epsilon; } // Note: The result of this function might be { hours = 24, minutes = 0, seconds = 0 } if arg < 1 but arg ≈ 1 function numberToSimpleTime(arg) { const argAsSeconds = arg * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE; const seconds = roundToEpsilon(argAsSeconds % SECONDS_PER_MINUTE, 100000) % SECONDS_PER_MINUTE; const argAsMinutes = (argAsSeconds - seconds) / SECONDS_PER_MINUTE; const minutes = Math.round(argAsMinutes % MINUTES_PER_HOUR) % MINUTES_PER_HOUR; const argAsHours = (argAsMinutes - minutes) / MINUTES_PER_HOUR; const hours = Math.round(argAsHours); return { hours, minutes, seconds }; } function timeToNumber(time) { return ((time.seconds / 60 + time.minutes) / 60 + time.hours) / 24; } function toBasisEU(date) { return { year: date.year, month: date.month, day: Math.min(30, date.day) }; } /***/ }), /* 105 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AlwaysDense: () => (/* binding */ AlwaysDense), /* harmony export */ AlwaysSparse: () => (/* binding */ AlwaysSparse), /* harmony export */ DenseSparseChooseBasedOnThreshold: () => (/* binding */ DenseSparseChooseBasedOnThreshold) /* harmony export */ }); /* harmony import */ var _DenseStrategy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94); /* harmony import */ var _SparseStrategy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(93); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class DenseSparseChooseBasedOnThreshold { constructor(threshold) { this.threshold = threshold; } call(fill) { if (fill > this.threshold) { return _DenseStrategy__WEBPACK_IMPORTED_MODULE_0__.DenseStrategy; } else { return _SparseStrategy__WEBPACK_IMPORTED_MODULE_1__.SparseStrategy; } } } class AlwaysSparse { call() { return _SparseStrategy__WEBPACK_IMPORTED_MODULE_1__.SparseStrategy; } } class AlwaysDense { call() { return _DenseStrategy__WEBPACK_IMPORTED_MODULE_0__.DenseStrategy; } } /***/ }), /* 106 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ defaultStringifyDateTime: () => (/* binding */ defaultStringifyDateTime), /* harmony export */ defaultStringifyDuration: () => (/* binding */ defaultStringifyDuration), /* harmony export */ format: () => (/* binding */ format), /* harmony export */ padLeft: () => (/* binding */ padLeft), /* harmony export */ padRight: () => (/* binding */ padRight) /* harmony export */ }); /* harmony import */ var _DateTimeDefault__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(103); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(104); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(107); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function format(value, formatArg, config, dateHelper) { const tryDateTime = config.stringifyDateTime(dateHelper.numberToSimpleDateTime(value), formatArg); // default points to defaultStringifyDateTime() if (tryDateTime !== undefined) { return tryDateTime; } const tryDuration = config.stringifyDuration((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.numberToSimpleTime)(value), formatArg); if (tryDuration !== undefined) { return tryDuration; } const expression = (0,_parser__WEBPACK_IMPORTED_MODULE_2__.parseForNumberFormat)(formatArg); if (expression !== undefined) { return numberFormat(expression.tokens, value); } return formatArg; } function padLeft(number, size) { let result = `${number}`; while (result.length < size) { result = '0' + result; } return result; } function padRight(number, size) { let result = `${number}`; while (result.length < size) { result = result + '0'; } return result; } function countChars(text, char) { return text.split(char).length - 1; } function numberFormat(tokens, value) { let result = ''; for (let i = 0; i < tokens.length; ++i) { const token = tokens[i]; if (token.type === _parser__WEBPACK_IMPORTED_MODULE_2__.TokenType.FREE_TEXT) { result += token.value; continue; } const tokenParts = token.value.split('.'); const integerFormat = tokenParts[0]; const decimalFormat = tokenParts[1] || ''; const separator = tokenParts[1] ? '.' : ''; /* get fixed-point number without trailing zeros */ const valueParts = Number(value.toFixed(decimalFormat.length)).toString().split('.'); let integerPart = valueParts[0] || ''; let decimalPart = valueParts[1] || ''; if (integerFormat.length > integerPart.length) { const padSizeInteger = countChars(integerFormat.substr(0, integerFormat.length - integerPart.length), '0'); integerPart = padLeft(integerPart, padSizeInteger + integerPart.length); } const padSizeDecimal = countChars(decimalFormat.substr(decimalPart.length, decimalFormat.length - decimalPart.length), '0'); decimalPart = padRight(decimalPart, padSizeDecimal + decimalPart.length); result += integerPart + separator + decimalPart; } return result; } function defaultStringifyDuration(time, formatArg) { const expression = (0,_parser__WEBPACK_IMPORTED_MODULE_2__.parseForDateTimeFormat)(formatArg); if (expression === undefined) { return undefined; } const tokens = expression.tokens; let result = ''; for (const token of tokens) { if (token.type === _parser__WEBPACK_IMPORTED_MODULE_2__.TokenType.FREE_TEXT) { result += token.value; continue; } switch (token.value.toLowerCase()) { case 'h': case 'hh': { result += padLeft(time.hours, token.value.length); time.hours = 0; break; } case '[hh]': { result += padLeft(time.hours, token.value.length - 2); time.hours = 0; break; } case 'm': case 'mm': { result += padLeft(time.minutes, token.value.length); time.minutes = 0; break; } case '[mm]': { result += padLeft(time.minutes + 60 * time.hours, token.value.length - 2); time.minutes = 0; time.hours = 0; break; } /* seconds */ case 's': case 'ss': { result += padLeft(Math.floor(time.seconds), token.value.length); break; } default: { if (_DateTimeDefault__WEBPACK_IMPORTED_MODULE_0__.TIME_FORMAT_SECONDS_ITEM_REGEXP.test(token.value)) { const fractionOfSecondPrecision = Math.max(token.value.length - 3, 0); result += `${time.seconds < 10 ? '0' : ''}${Math.floor(time.seconds * Math.pow(10, fractionOfSecondPrecision)) / Math.pow(10, fractionOfSecondPrecision)}`; continue; } return undefined; } } } return result; } function defaultStringifyDateTime(dateTime, formatArg) { const expression = (0,_parser__WEBPACK_IMPORTED_MODULE_2__.parseForDateTimeFormat)(formatArg); if (expression === undefined) { return undefined; } const tokens = expression.tokens; let result = ''; let minutes = false; const ampm = tokens.some(token => token.type === _parser__WEBPACK_IMPORTED_MODULE_2__.TokenType.FORMAT && (token.value === 'a/p' || token.value === 'A/P' || token.value === 'am/pm' || token.value === 'AM/PM')); for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token.type === _parser__WEBPACK_IMPORTED_MODULE_2__.TokenType.FREE_TEXT) { result += token.value; continue; } switch (token.value.toLowerCase()) { /* hours*/ case 'h': case 'hh': { minutes = true; result += padLeft(ampm ? (dateTime.hours + 11) % 12 + 1 : dateTime.hours, token.value.length); break; } /* days */ case 'd': case 'dd': { result += padLeft(dateTime.day, token.value.length); break; } /* seconds */ case 's': case 'ss': { result += padLeft(Math.floor(dateTime.seconds), token.value.length); break; } /* minutes / months */ case 'm': case 'mm': { if (i + 1 < tokens.length && tokens[i + 1].value.startsWith(':')) { minutes = true; } if (minutes) { result += padLeft(dateTime.minutes, token.value.length); } else { result += padLeft(dateTime.month, token.value.length); } minutes = true; break; } /* years */ case 'yy': { result += padLeft(dateTime.year % 100, token.value.length); break; } case 'yyyy': { result += dateTime.year; break; } /* AM / PM */ case 'am/pm': case 'a/p': { const [am, pm] = token.value.split('/'); result += dateTime.hours < 12 ? am : pm; break; } default: { if (_DateTimeDefault__WEBPACK_IMPORTED_MODULE_0__.TIME_FORMAT_SECONDS_ITEM_REGEXP.test(token.value)) { const fractionOfSecondPrecision = token.value.length - 3; result += `${dateTime.seconds < 10 ? '0' : ''}${Math.floor(dateTime.seconds * Math.pow(10, fractionOfSecondPrecision)) / Math.pow(10, fractionOfSecondPrecision)}`; continue; } return undefined; } } } return result; } /***/ }), /* 107 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FormatExpressionType: () => (/* binding */ FormatExpressionType), /* harmony export */ TokenType: () => (/* binding */ TokenType), /* harmony export */ formatToken: () => (/* binding */ formatToken), /* harmony export */ isEscapeToken: () => (/* binding */ isEscapeToken), /* harmony export */ parse: () => (/* binding */ parse), /* harmony export */ parseForDateTimeFormat: () => (/* binding */ parseForDateTimeFormat), /* harmony export */ parseForNumberFormat: () => (/* binding */ parseForNumberFormat) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const dateFormatRegex = /(\\.|dd|DD|d|D|mm|MM|m|M|YYYY|YY|yyyy|yy|HH|hh|H|h|ss(\.(0+|s+))?|s|AM\/PM|am\/pm|A\/P|a\/p|\[mm]|\[MM]|\[hh]|\[HH])/g; const numberFormatRegex = /(\\.|[#0]+(\.[#0]*)?)/g; var TokenType; (function (TokenType) { TokenType["FORMAT"] = "FORMAT"; TokenType["FREE_TEXT"] = "FREE_TEXT"; })(TokenType || (TokenType = {})); function formatToken(type, value) { return { type, value }; } var FormatExpressionType; (function (FormatExpressionType) { FormatExpressionType["DATE"] = "DATE"; FormatExpressionType["NUMBER"] = "NUMBER"; FormatExpressionType["STRING"] = "STRING"; })(FormatExpressionType || (FormatExpressionType = {})); function matchDateFormat(str) { dateFormatRegex.lastIndex = 0; const tokens = []; let m; do { m = dateFormatRegex.exec(str); if (m !== null) { tokens.push(m); } } while (m); return tokens; } function matchNumberFormat(str) { numberFormatRegex.lastIndex = 0; const numberFormatToken = numberFormatRegex.exec(str); if (numberFormatToken !== null) { return [numberFormatToken]; } else { return []; } } function createTokens(regexTokens, str) { const tokens = []; let start = 0; for (let i = 0; i < regexTokens.length; ++i) { const token = regexTokens[i]; if (token.index !== start) { const beforeToken = str.substr(start, token.index - start); tokens.push(formatToken(TokenType.FREE_TEXT, beforeToken)); } if (token[0].startsWith('\\')) { tokens.push(formatToken(TokenType.FREE_TEXT, token[0])); } else { tokens.push(formatToken(TokenType.FORMAT, token[0])); } start = token.index + token[0].length; } const lastToken = regexTokens[regexTokens.length - 1]; if (lastToken.index + lastToken[0].length < str.length) { const afterLastToken = str.substr(lastToken.index + lastToken[0].length, str.length); tokens.push(formatToken(TokenType.FREE_TEXT, afterLastToken)); } return tokens; } function parseForDateTimeFormat(str) { const dateFormatTokens = matchDateFormat(str); if (dateFormatTokens.every(elem => isEscapeToken(elem))) { return undefined; } else { return { type: FormatExpressionType.DATE, tokens: createTokens(dateFormatTokens, str) }; } } function parseForNumberFormat(str) { const numberFormatTokens = matchNumberFormat(str); if (numberFormatTokens.every(elem => isEscapeToken(elem))) { return undefined; } else { return { type: FormatExpressionType.NUMBER, tokens: createTokens(numberFormatTokens, str) }; } } function parse(str) { var _a, _b; return (_b = (_a = parseForDateTimeFormat(str)) !== null && _a !== void 0 ? _a : parseForNumberFormat(str)) !== null && _b !== void 0 ? _b : { type: FormatExpressionType.STRING, tokens: [{ type: TokenType.FREE_TEXT, value: str }] }; } function isEscapeToken(token) { return token[0].startsWith('\\'); } /***/ }), /* 108 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ checkLicenseKeyValidity: () => (/* binding */ checkLicenseKeyValidity) /* harmony export */ }); /* harmony import */ var _licenseKeyHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(109); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * List of all not valid messages which may occur. */ const consoleMessages = { invalid: () => 'The license key for HyperFormula is invalid.', expired: ({ keyValidityDate }) => 'The license key for HyperFormula expired' + ` on ${keyValidityDate}, and is not valid for the installed version.`, missing: () => 'The license key for HyperFormula is missing.' }; let _notified = false; /** * Checks if the provided license key is grammatically valid or not expired. * * @param {string} licenseKey The license key to check. * @returns {LicenseKeyValidityState} Returns the checking state. */ function checkLicenseKeyValidity(licenseKey) { const messageDescriptor = { template: "missing" /* MISSING */, vars: {} }; if (licenseKey === 'gpl-v3' || licenseKey === 'internal-use-in-handsontable') { messageDescriptor.template = "valid" /* VALID */; } else if (typeof licenseKey === 'string' && (0,_licenseKeyHelper__WEBPACK_IMPORTED_MODULE_0__.checkKeySchema)(licenseKey)) { const [day, month, year] = ("18/07/2024" || 0).split('/'); const releaseDays = Math.floor(new Date(`${month}/${day}/${year}`).getTime() / 8.64e7); const keyValidityDays = (0,_licenseKeyHelper__WEBPACK_IMPORTED_MODULE_0__.extractTime)(licenseKey); messageDescriptor.vars.keyValidityDate = formatDate(new Date((keyValidityDays + 1) * 8.64e7)); if (releaseDays > keyValidityDays) { messageDescriptor.template = "expired" /* EXPIRED */; } else { messageDescriptor.template = "valid" /* VALID */; } } else if (licenseKey !== '') { messageDescriptor.template = "invalid" /* INVALID */; } if (!_notified && messageDescriptor.template !== "valid" /* VALID */) { console.warn(consoleMessages[messageDescriptor.template](messageDescriptor.vars)); _notified = true; } return messageDescriptor.template; } /** * Formats a Date instance to hard-coded format MMMM DD, YYYY. * * @param {Date} date The date to format. * @returns {string} */ function formatDate(date) { const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const month = monthNames[date.getMonth()]; const day = date.getDate(); const year = date.getFullYear(); return `${month} ${day}, ${year}`; } /***/ }), /* 109 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ checkKeySchema: () => (/* binding */ checkKeySchema), /* harmony export */ extractTime: () => (/* binding */ extractTime) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-nocheck /* eslint-disable */ const _rl = '\x6C\x65\x6E\x67\x74\x68'; const _hd = v => parseInt(v, 16); const _pi = v => parseInt(v, 10); const _nm = v => (v + '').replace(/\-/g, ''); const _ss = (v, s, l) => v['\x73\x75\x62\x73\x74\x72'](s, l); const _cp = v => v['\x63\x6F\x64\x65\x50\x6F\x69\x6E\x74\x41\x74'](0) - 65; function extractTime(v) { return _nm(v)[_rl] === 50 >> 1 ? _hd(_ss(_nm(v), _hd('12'), _cp('\x46'))) / (_hd(_ss(_nm(v), _cp('C'), _cp('\x59') >> 4)) || (~~![][_rl] << 3) + 1) : 0; } function checkKeySchema(v) { v = (v + '').replace(/\-/g, ''); if (v[_rl] !== _cp('\x5A')) { return false; } let sp = 0; return [[0, _cp('\x47') + 1], [_cp('\x48'), _cp('\x48') - 1], [_cp('G') + _cp('H'), _cp('\x47')]].reduce((e, [a, b], c) => { e |= (_pi(`${_pi(_hd(_ss(v, ...[sp + a - (c === 3 >> 2 ? 0 : 2), b + (!c ? 0 : 2)])) + (_hd(_ss(v, ...[sp + a + b, 2])) + []).padStart(2, '0'))}`) % 97 || 2) >> 1; sp += 2; return e; }, _cp('A')) === [] + 1 >> 1; } /* eslint-enable */ /***/ }), /* 110 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ HyperFormula: () => (/* binding */ HyperFormula) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(102); /* harmony import */ var _BuildEngineFactory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(111); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); /* harmony import */ var _CellContentParser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(112); /* harmony import */ var _Config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(101); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(104); /* harmony import */ var _Destroy__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(143); /* harmony import */ var _Emitter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(144); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(77); /* harmony import */ var _i18n__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(88); /* harmony import */ var _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(130); /* harmony import */ var _Operations__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(116); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * This is a class for creating HyperFormula instance, all the following public methods * are related to this class. * * The instance can be created only by calling one of the static methods * `buildFromArray`, `buildFromSheets` or `buildEmpty` and should be disposed of with the * `destroy` method when it's no longer needed to free the resources. * * The instance can be seen as a workbook where worksheets can be created and * manipulated. They are organized within a widely known structure of columns and rows * which can be manipulated as well. The smallest possible data unit are the cells, which * may contain simple values or formulas to be calculated. * * All CRUD methods are called directly on HyperFormula instance and will trigger * corresponding lifecycle events. The events are marked accordingly, as well as thrown * errors, so they can be correctly handled. */ class HyperFormula { /** * Constructor * * @internal */ constructor(_config, _stats, _dependencyGraph, _columnSearch, _parser, _unparser, _cellContentParser, _evaluator, _lazilyTransformingAstService, _crudOperations, _exporter, _namedExpressions, _serialization, _functionRegistry) { this._config = _config; this._stats = _stats; this._dependencyGraph = _dependencyGraph; this._columnSearch = _columnSearch; this._parser = _parser; this._unparser = _unparser; this._cellContentParser = _cellContentParser; this._evaluator = _evaluator; this._lazilyTransformingAstService = _lazilyTransformingAstService; this._crudOperations = _crudOperations; this._exporter = _exporter; this._namedExpressions = _namedExpressions; this._serialization = _serialization; this._functionRegistry = _functionRegistry; this._emitter = new _Emitter__WEBPACK_IMPORTED_MODULE_8__.Emitter(); this._evaluationSuspended = false; } /** * Returns all of HyperFormula's default [configuration options](../../guide/configuration-options.md). * * @example * ```js * // returns all default configuration options * const defaultConfig = HyperFormula.defaultConfig; * ``` * * @category Static Accessors */ static get defaultConfig() { return (0,_Config__WEBPACK_IMPORTED_MODULE_5__.getDefaultConfig)(); } /** * Calls the `graph` method on the dependency graph. * Allows for executing `graph` directly, without a need to refer to `dependencyGraph`. * * @internal */ get graph() { return this.dependencyGraph.graph; } /** * Calls the `rangeMapping` method on the dependency graph. * Allows for executing `rangeMapping` directly, without a need to refer to `dependencyGraph`. * * @internal */ get rangeMapping() { return this.dependencyGraph.rangeMapping; } /** * Calls the `arrayMapping` method on the dependency graph. * Allows for executing `arrayMapping` directly, without a need to refer to `dependencyGraph`. * * @internal */ get arrayMapping() { return this.dependencyGraph.arrayMapping; } /** * Calls the `sheetMapping` method on the dependency graph. * Allows for executing `sheetMapping` directly, without a need to refer to `dependencyGraph`. * * @internal */ get sheetMapping() { return this.dependencyGraph.sheetMapping; } /** * Calls the `addressMapping` method on the dependency graph. * Allows for executing `addressMapping` directly, without a need to refer to `dependencyGraph`. * * @internal */ get addressMapping() { return this.dependencyGraph.addressMapping; } /** @internal */ get dependencyGraph() { return this._dependencyGraph; } /** @internal */ get evaluator() { return this._evaluator; } /** @internal */ get columnSearch() { return this._columnSearch; } /** @internal */ get lazilyTransformingAstService() { return this._lazilyTransformingAstService; } /** * Returns state of the validity of the license key. * * @internal */ get licenseKeyValidityState() { return this._config.licenseKeyValidityState; } /** * Builds the engine for a sheet from a two-dimensional array representation. * The engine is created with a single sheet. * Can be configured with the optional second parameter that represents a [[ConfigParams]]. * If not specified, the engine will be built with the default configuration. * * @param {Sheet} sheet - two-dimensional array representation of sheet * @param {Partial} configInput - engine configuration * @param {SerializedNamedExpression[]} namedExpressions - starting named expressions * * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata * * @example * ```js * // data represented as an array * const sheetData = [ * ['0', '=SUM(1, 2, 3)', '52'], * ['=SUM(A1:C1)', '', '=A1'], * ['2', '=SUM(A1:C1)', '91'], * ]; * * // method with optional config parameter maxColumns * const hfInstance = HyperFormula.buildFromArray(sheetData, { maxColumns: 1000 }); * ``` * * @category Factories */ static buildFromArray(sheet, configInput = {}, namedExpressions = []) { return this.buildFromEngineState(_BuildEngineFactory__WEBPACK_IMPORTED_MODULE_2__.BuildEngineFactory.buildFromSheet(sheet, configInput, namedExpressions)); } /** * Builds the engine from an object containing multiple sheets with names. * The engine is created with one or more sheets. * Can be configured with the optional second parameter that represents a [[ConfigParams]]. * If not specified the engine will be built with the default configuration. * * @param {Sheet} sheets - object with sheets definition * @param {Partial} configInput - engine configuration * @param {SerializedNamedExpression[]} namedExpressions - starting named expressions * * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when any sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata * * @example * ```js * // data represented as an object with sheets: Sheet1 and Sheet2 * const sheetData = { * 'Sheet1': [ * ['1', '', '=Sheet2!$A1'], * ['', '2', '=SUM(1, 2, 3)'], * ['=Sheet2!$A2', '2', ''], * ], * 'Sheet2': [ * ['', '4', '=Sheet1!$B1'], * ['', '8', '=SUM(9, 3, 3)'], * ['=Sheet1!$B1', '2', ''], * ], * }; * * // method with optional config parameter useColumnIndex * const hfInstance = HyperFormula.buildFromSheets(sheetData, { useColumnIndex: true }); * ``` * * @category Factories */ static buildFromSheets(sheets, configInput = {}, namedExpressions = []) { return this.buildFromEngineState(_BuildEngineFactory__WEBPACK_IMPORTED_MODULE_2__.BuildEngineFactory.buildFromSheets(sheets, configInput, namedExpressions)); } /** * Builds an empty engine instance. * Can be configured with the optional parameter that represents a [[ConfigParams]]. * If not specified the engine will be built with the default configuration. * * @param {Partial} configInput - engine configuration * @param {SerializedNamedExpression[]} namedExpressions - starting named expressions * * @example * ```js * // build with no initial data and with optional config parameter maxColumns * const hfInstance = HyperFormula.buildEmpty({ maxColumns: 1000 }); * ``` * * @category Factories */ static buildEmpty(configInput = {}, namedExpressions = []) { return this.buildFromEngineState(_BuildEngineFactory__WEBPACK_IMPORTED_MODULE_2__.BuildEngineFactory.buildEmpty(configInput, namedExpressions)); } /** * Returns registered language from its code string. * * @param {string} languageCode - code string of the translation package * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[LanguageNotRegisteredError]] when trying to retrieve not registered language * * @example * ```js * // return registered language * const language = HyperFormula.getLanguage('enGB'); * ``` * * @category Static Methods */ static getLanguage(languageCode) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(languageCode, 'string', 'languageCode'); const val = this.registeredLanguages.get(languageCode); if (val === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.LanguageNotRegisteredError(); } else { return val; } } /** * Registers language under given code string. * * For more information, see the [Localizing functions guide](/guide/localizing-functions.md). * * @param {string} languageCode - code string of the translation package * @param {RawTranslationPackage} languagePackage - translation package to be registered * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function * @throws [[LanguageAlreadyRegisteredError]] when given language is already registered * * @example * ```js * // return registered language * HyperFormula.registerLanguage('enUS', enUS); * const engine = HyperFormula.buildEmpty({language: 'enUS'}); * ``` * * @category Static Methods */ static registerLanguage(languageCode, languagePackage) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(languageCode, 'string', 'languageCode'); if (this.registeredLanguages.has(languageCode)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.LanguageAlreadyRegisteredError(); } else { this.registeredLanguages.set(languageCode, (0,_i18n__WEBPACK_IMPORTED_MODULE_10__.buildTranslationPackage)(languagePackage)); } } /** * Unregisters language that is registered under given code string. * * @param {string} languageCode - code string of the translation package * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[LanguageNotRegisteredError]] when given language is not registered * * @example * ```js * // register the language for the instance * HyperFormula.registerLanguage('plPL', plPL); * * // unregister plPL * HyperFormula.unregisterLanguage('plPL'); * ``` * * @category Static Methods */ static unregisterLanguage(languageCode) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(languageCode, 'string', 'languageCode'); if (this.registeredLanguages.has(languageCode)) { this.registeredLanguages.delete(languageCode); } else { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.LanguageNotRegisteredError(); } } /** * Returns all registered languages codes. * * @example * ```js * // should return all registered language codes: ['enGB', 'plPL'] * const registeredLanguages = HyperFormula.getRegisteredLanguagesCodes(); * ``` * * @category Static Methods */ static getRegisteredLanguagesCodes() { return Array.from(this.registeredLanguages.keys()); } /** * Registers all functions in a given plugin with optional translations. * * Note: FunctionPlugins must be registered prior to the creation of HyperFormula instances in which they are used. * HyperFormula instances created prior to the registration of a FunctionPlugin are unable to access the FunctionPlugin. * Registering a FunctionPlugin with [[custom-functions]] requires the translations parameter. * * @param {FunctionPluginDefinition} plugin - plugin class * @param {FunctionTranslationsPackage} translations - optional package of function names translations * * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata * @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function * * @example * ```js * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * * // register the plugin * HyperFormula.registerFunctionPlugin(MyExamplePlugin); * ``` * * @category Static Methods */ static registerFunctionPlugin(plugin, translations) { _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.registerFunctionPlugin(plugin, translations); } /** * Unregisters all functions defined in given plugin. * * Note: This method does not affect the existing HyperFormula instances. * * @param {FunctionPluginDefinition} plugin - plugin class * * @example * ```js * // get the class of a plugin * const registeredPluginClass = HyperFormula.getFunctionPlugin('EXAMPLE'); * * // unregister all functions defined in a plugin of ID 'EXAMPLE' * HyperFormula.unregisterFunctionPlugin(registeredPluginClass); * ``` * * @category Static Methods */ static unregisterFunctionPlugin(plugin) { _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.unregisterFunctionPlugin(plugin); } /** * Registers a function with a given id if such exists in a plugin. * * Note: This method does not affect the existing HyperFormula instances. * * @param {string} functionId - function id, e.g., 'SUMIF' * @param {FunctionPluginDefinition} plugin - plugin class * @param {FunctionTranslationsPackage} translations - translations for the function name * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[FunctionPluginValidationError]] when function with a given id does not exist in plugin or plugin class definition is not consistent with metadata * @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function * * @example * ```js * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * * // register a function * HyperFormula.registerFunction('EXAMPLE', MyExamplePlugin); * ``` * * @category Static Methods */ static registerFunction(functionId, plugin, translations) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(functionId, 'string', 'functionId'); _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.registerFunction(functionId, plugin, translations); } /** * Unregisters a function with a given id. * * Note: This method does not affect the existing HyperFormula instances. * * @param {string} functionId - function id, e.g., 'SUMIF' * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * * // register a function * HyperFormula.registerFunction('EXAMPLE', MyExamplePlugin); * * // unregister a function * HyperFormula.unregisterFunction('EXAMPLE'); * ``` * * @category Static Methods */ static unregisterFunction(functionId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(functionId, 'string', 'functionId'); _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.unregisterFunction(functionId); } /** * Clears function registry. * * Note: This method does not affect the existing HyperFormula instances. * * @example * ```js * HyperFormula.unregisterAllFunctions(); * ``` * * @category Static Methods */ static unregisterAllFunctions() { _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.unregisterAll(); } /** * Returns translated names of all registered functions for a given language * * @param {string} code - language code * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * // return a list of function names registered for enGB * const allNames = HyperFormula.getRegisteredFunctionNames('enGB'); * ``` * * @category Static Methods */ static getRegisteredFunctionNames(code) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(code, 'string', 'code'); const functionIds = _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.getRegisteredFunctionIds(); const language = this.getLanguage(code); return language.getFunctionTranslations(functionIds); } /** * Returns class of a plugin used by function with given id * * @param {string} functionId - id of a function, e.g., 'SUMIF' * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * * // register a plugin * HyperFormula.registerFunctionPlugin(MyExamplePlugin); * * // return the class of a given plugin * const myFunctionClass = HyperFormula.getFunctionPlugin('EXAMPLE'); * ``` * * @category Static Methods */ static getFunctionPlugin(functionId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(functionId, 'string', 'functionId'); return _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.getFunctionPlugin(functionId); } /** * Returns classes of all plugins registered in HyperFormula. * * @example * ```js * // return classes of all plugins * const allClasses = HyperFormula.getAllFunctionPlugins(); * ``` * * @category Static Methods */ static getAllFunctionPlugins() { return _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_11__.FunctionRegistry.getPlugins(); } static buildFromEngineState(engine) { return new HyperFormula(engine.config, engine.stats, engine.dependencyGraph, engine.columnSearch, engine.parser, engine.unparser, engine.cellContentParser, engine.evaluator, engine.lazilyTransformingAstService, engine.crudOperations, engine.exporter, engine.namedExpressions, engine.serialization, engine.functionRegistry); } /** * Returns the cell value of a given address. * Applies rounding and post-processing. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '2'], * ]); * * // get value of A1 cell, should be '6' * const A1Value = hfInstance.getCellValue({ sheet: 0, col: 0, row: 0 }); * * // get value of B1 cell, should be '2' * const B1Value = hfInstance.getCellValue({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellValue(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); return this._serialization.getCellValue(cellAddress); } /** * Returns a normalized formula string from the cell of a given address or `undefined` for an address that does not exist and empty values. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '0'], * ]); * * // should return a normalized A1 cell formula: '=SUM(1, 2, 3)' * const A1Formula = hfInstance.getCellFormula({ sheet: 0, col: 0, row: 0 }); * * // should return a normalized B1 cell formula: 'undefined' * const B1Formula = hfInstance.getCellFormula({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellFormula(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } return this._serialization.getCellFormula(cellAddress); } /** * Returns the `HYPERLINK` url for a cell of a given address or `undefined` for an address that does not exist or a cell that is not `HYPERLINK` * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=HYPERLINK("https://hyperformula.handsontable.com/", "HyperFormula")', '0'], * ]); * * // should return url of 'HYPERLINK': https://hyperformula.handsontable.com/ * const A1Hyperlink = hfInstance.getCellHyperlink({ sheet: 0, col: 0, row: 0 }); * * // should return 'undefined' for a cell that is not 'HYPERLINK' * const B1Hyperlink = hfInstance.getCellHyperlink({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellHyperlink(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); return this._serialization.getCellHyperlink(cellAddress); } /** * Returns [[RawCellContent]] with a serialized content of the cell of a given address: either a cell formula, an explicit value, or an error. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '0'], * ]); * * // should return serialized content of A1 cell: '=SUM(1, 2, 3)' * const cellA1Serialized = hfInstance.getCellSerialized({ sheet: 0, col: 0, row: 0 }); * * // should return serialized content of B1 cell: '0' * const cellB1Serialized = hfInstance.getCellSerialized({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellSerialized(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); return this._serialization.getCellSerialized(cellAddress); } /** * Returns an array of arrays of [[CellValue]] with values of all cells from [[Sheet]]. * Applies rounding and post-processing. * * @param {number} sheetId - sheet ID number * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], * ]); * * // should return all values of a sheet: [[0, 6, 0], [1, '1.0%', 0], [2, 6, 0]] * const sheetValues = hfInstance.getSheetValues(0); * ``` * * @category Sheets */ getSheetValues(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this.ensureEvaluationIsNotSuspended(); return this._serialization.getSheetValues(sheetId); } /** * Returns an array with normalized formula strings from [[Sheet]] or `undefined` for a cells that have no value. * * @param {SimpleCellAddress} sheetId - sheet ID number * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], * ]); * * // should return all formulas of a sheet: * // [ * // [undefined, '=SUM(1, 2, 3)', '=A1'], * // [undefined, '=TEXT(A2, "0.0%")', '=C1'], * // [undefined, '=SUM(A1:C1)', '=C1'], * // ]; * const sheetFormulas = hfInstance.getSheetFormulas(0); * ``` * * @category Sheets */ getSheetFormulas(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return this._serialization.getSheetFormulas(sheetId); } /** * Returns an array of arrays of [[RawCellContent]] with serialized content of cells from [[Sheet]], either a cell formula or an explicit value. * * @param {SimpleCellAddress} sheetId - sheet ID number * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], * ]); * * // should return: * // [ * // ['0', '=SUM(1, 2, 3)', '=A1'], * // ['1', '=TEXT(A2, "0.0%")', '=C1'], * // ['2', '=SUM(A1:C1)', '=C1'], * // ]; * const serializedContent = hfInstance.getSheetSerialized(0); * ``` * * @category Sheets */ getSheetSerialized(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this.ensureEvaluationIsNotSuspended(); return this._serialization.getSheetSerialized(sheetId); } /** * Returns a map containing dimensions of all sheets for the engine instance represented as a key-value pairs where keys are sheet IDs and dimensions are returned as numbers, width and height respectively. * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * Sheet1: [ * ['1', '2', '=Sheet2!$A1'], * ], * Sheet2: [ * ['3'], * ['4'], * ], * }); * * // should return the dimensions of all sheets: * // { Sheet1: { width: 3, height: 1 }, Sheet2: { width: 1, height: 2 } } * const allSheetsDimensions = hfInstance.getAllSheetsDimensions(); * ``` * * @category Sheets */ getAllSheetsDimensions() { return this._serialization.genericAllSheetsGetter(arg => this.getSheetDimensions(arg)); } /** * Returns dimensions of a specified sheet. * The sheet dimensions is represented with numbers: width and height. * * @param {number} sheetId - sheet ID number * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=Sheet2!$A1'], * ]); * * // should return provided sheet's dimensions: { width: 3, height: 1 } * const sheetDimensions = hfInstance.getSheetDimensions(0); * ``` * * @category Sheets */ getSheetDimensions(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return { width: this.dependencyGraph.getSheetWidth(sheetId), height: this.dependencyGraph.getSheetHeight(sheetId) }; } /** * Returns values of all sheets in a form of an object which property keys are strings and values are 2D arrays of [[CellValue]]. * * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '=A1+10', '3'], * ]); * * // should return all sheets values: { Sheet1: [ [ 1, 11, 3 ] ] } * const allSheetsValues = hfInstance.getAllSheetsValues(); * ``` * * @category Sheets */ getAllSheetsValues() { this.ensureEvaluationIsNotSuspended(); return this._serialization.getAllSheetsValues(); } /** * Returns formulas of all sheets in a form of an object which property keys are strings and values are 2D arrays of strings or possibly `undefined` when the call does not contain a formula. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1+10'], * ]); * * // should return only formulas: { Sheet1: [ [ undefined, undefined, '=A1+10' ] ] } * const allSheetsFormulas = hfInstance.getAllSheetsFormulas(); * ``` * @category Sheets */ getAllSheetsFormulas() { return this._serialization.getAllSheetsFormulas(); } /** * Returns formulas or values of all sheets in a form of an object which property keys are strings and values are 2D arrays of [[RawCellContent]]. * * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1+10'], * ]); * * // should return all sheets serialized content: { Sheet1: [ [ 1, 2, '=A1+10' ] ] } * const allSheetsSerialized = hfInstance.getAllSheetsSerialized(); * ``` * * @category Sheets */ getAllSheetsSerialized() { this.ensureEvaluationIsNotSuspended(); return this._serialization.getAllSheetsSerialized(); } /** * Updates the config with given new metadata. It is an expensive operation, as it might trigger rebuilding the engine and recalculation of all formulas. * * @param {Partial} newParams configuration options to be updated or added * * @throws [[ExpectedValueOfTypeError]] when some parameters of config are of wrong type (e.g., currencySymbol) * @throws [[ConfigValueEmpty]] when some parameters of config are of invalid value (e.g., currencySymbol) * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // add a config param, for example maxColumns, * // you can check the configuration with getConfig method * hfInstance.updateConfig({ maxColumns: 1000 }); * ``` * * @category Instance */ updateConfig(newParams) { const isNewConfigTheSame = Object.entries(newParams).every(([key, value]) => this._config[key] === value); if (isNewConfigTheSame) { return; } this.rebuildWithConfig(newParams); } /** * Returns current configuration of the engine instance. * * @example * ```js * // should return all config metadata including default and those which were added * const hfConfig = hfInstance.getConfig(); * ``` * * @category Instance */ getConfig() { return this._config.getConfig(); } /** * Rebuilds the HyperFormula instance preserving the current sheets data. * * @example * ```js * hfInstance.rebuildAndRecalculate(); * ``` * * @category Instance */ rebuildAndRecalculate() { this.rebuildWithConfig({}); } /** * Returns a snapshot of computation time statistics. * It returns a map with key-value pairs where keys are enums for stat type and time (number). * * @internal * * @category Instance */ getStats() { return this._stats.snapshot(); } /** * Undo the previous operation. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToUndoError]] when there is no operation running that can be undone * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ['3', ''], * ]); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); * * // undo the operation, it should return the changes * const changes = hfInstance.undo(); * ``` * * @category Undo and Redo */ undo() { this._crudOperations.undo(); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Re-do recently undone operation. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToRedoError]] when there is no operation running that can be re-done * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ['3'], * ]); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); * * // undo the operation, it should return previous values: [['1'], ['2'], ['3']] * hfInstance.undo(); * * // do a redo, it should return the values after removing the second row: [['1'], ['3']] * const changes = hfInstance.redo(); * ``` * * @category Undo and Redo */ redo() { this._crudOperations.redo(); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Checks if there is at least one operation that can be undone. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ['3'], * ]); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); * * // should return 'true', it is possible to undo last operation * // which is removing rows in this example * const isSomethingToUndo = hfInstance.isThereSomethingToUndo(); * ``` * * @category Undo and Redo */ isThereSomethingToUndo() { return this._crudOperations.isThereSomethingToUndo(); } /** * Checks if there is at least one operation that can be re-done. * * @example * ```js * hfInstance.undo(); * * // when there is an action to redo, this returns 'true' * const isSomethingToRedo = hfInstance.isThereSomethingToRedo(); * ``` * * @category Undo and Redo */ isThereSomethingToRedo() { return this._crudOperations.isThereSomethingToRedo(); } /** * Returns information whether it is possible to change the content in a rectangular area bounded by the box. * If returns `true`, doing [[setCellContents]] operation won't throw any errors. * Returns `false` if the address is invalid or the sheet does not exist. * * @param {SimpleCellAddress | SimpleCellRange} address - single cell or block of cells to check * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // top left corner * const address1 = { col: 0, row: 0, sheet: 0 }; * // bottom right corner * const address2 = { col: 1, row: 0, sheet: 0 }; * * // should return 'true' for this example, it is possible to set content of * // width 2, height 1 in the first row and column of sheet 0 * const isSettable = hfInstance.isItPossibleToSetCellContents({ start: address1, end: address2 }); * ``` * * @category Cells */ isItPossibleToSetCellContents(address) { let range; if ((0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(address)) { range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(address, address); } else if ((0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(address)) { range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(address.start, address.end); } else { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress | SimpleCellRange', 'address'); } try { this._crudOperations.ensureRangeInSizeLimits(range); for (const it of range.addresses(this._dependencyGraph)) { this._crudOperations.ensureItIsPossibleToChangeContent(it); } } catch (e) { return false; } return true; } /** * Sets the content for a block of cells of a given coordinates. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {SimpleCellAddress} topLeftCornerAddress - top left corner of block of cells * @param {(RawCellContent[][]|RawCellContent)} cellContents - array with content * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the value is not an array of arrays or a raw cell value * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * @throws [[ExpectedValueOfTypeError]] if topLeftCornerAddress argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1'], * ]); * * // should set the content, returns: * // [{ * // address: { sheet: 0, col: 3, row: 0 }, * // newValue: 2, * // }] * const changes = hfInstance.setCellContents({ col: 3, row: 0, sheet: 0 }, [['=B1']]); * ``` * * @category Cells */ setCellContents(topLeftCornerAddress, cellContents) { this._crudOperations.setCellContents(topLeftCornerAddress, cellContents); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Reorders rows of a sheet according to a source-target mapping. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - ID of a sheet to operate on * @param {[number, number][]} rowMapping - array mapping original positions to final positions of rows * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1], * [2], * [4, 5], * ]); * * // should set swap rows 0 and 2 in place, returns: * // [{ * // address: { sheet: 0, col: 0, row: 2 }, * // newValue: 1, * // }, * // { * // address: { sheet: 0, col: 1, row: 2 }, * // newValue: null, * // }, * // { * // address: { sheet: 0, col: 0, row: 0 }, * // newValue: 4, * // }, * // { * // address: { sheet: 0, col: 1, row: 0 }, * // newValue: 5, * // }] * const changes = hfInstance.swapRowIndexes(0, [[0, 2], [2, 0]]); * ``` * * @category Rows */ swapRowIndexes(sheetId, rowMapping) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.setRowOrder(sheetId, rowMapping); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Checks if it is possible to reorder rows of a sheet according to a source-target mapping. * * @param {number} sheetId - ID of a sheet to operate on * @param {[number, number][]} rowMapping - array mapping original positions to final positions of rows * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1], * [2], * [4, 5], * ]); * * // returns true * const isSwappable = hfInstance.isItPossibleToSwapRowIndexes(0, [[0, 2], [2, 0]]); * * // returns false * const isSwappable = hfInstance.isItPossibleToSwapRowIndexes(0, [[0, 1]]); * ``` * * @category Rows */ isItPossibleToSwapRowIndexes(sheetId, rowMapping) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { this._crudOperations.validateSwapRowIndexes(sheetId, rowMapping); this._crudOperations.testRowOrderForArrays(sheetId, rowMapping); return true; } catch (e) { return false; } } /** * Reorders rows of a sheet according to a permutation of 0-based indexes. * Parameter `newRowOrder` should have a form `[ newPositionForRow0, newPositionForRow1, newPositionForRow2, ... ]`. * This method might be used to [sort the rows of a sheet](../../guide/sorting-data.md). * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note: This method may trigger dependency graph recalculation. * * @param {number} sheetId - ID of a sheet to operate on * @param {number[]} newRowOrder - permutation of rows * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['A'], * ['B'], * ['C'], * ['D'] * ]); * * const newRowOrder = [0, 3, 2, 1]; // [ newPosForA, newPosForB, newPosForC, newPosForD ] * * const changes = hfInstance.setRowOrder(0, newRowOrder); * * // Sheet after this operation: [['A'], ['D'], ['C'], ['B']] * ``` * * @category Rows */ setRowOrder(sheetId, newRowOrder) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const mapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row'); return this.swapRowIndexes(sheetId, mapping); } /** * Checks if it is possible to reorder rows of a sheet according to a permutation. * * @param {number} sheetId - ID of a sheet to operate on * @param {number[]} newRowOrder - permutation of rows * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1], * [2], * [4, 5], * ]); * * // returns true * hfInstance.isItPossibleToSetRowOrder(0, [2, 1, 0]); * * // returns false * hfInstance.isItPossibleToSetRowOrder(0, [2]); * ``` * * @category Rows */ isItPossibleToSetRowOrder(sheetId, newRowOrder) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { const rowMapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row'); this._crudOperations.validateSwapRowIndexes(sheetId, rowMapping); this._crudOperations.testRowOrderForArrays(sheetId, rowMapping); return true; } catch (e) { return false; } } /** * Reorders columns of a sheet according to a source-target mapping. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - ID of a sheet to operate on * @param {[number, number][]} columnMapping - array mapping original positions to final positions of columns * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1, 2, 4], * [5] * ]); * * // should set swap columns 0 and 2 in place, returns: * // [{ * // address: { sheet: 0, col: 2, row: 0 }, * // newValue: 1, * // }, * // { * // address: { sheet: 0, col: 2, row: 1 }, * // newValue: 5, * // }, * // { * // address: { sheet: 0, col: 0, row: 0 }, * // newValue: 4, * // }, * // { * // address: { sheet: 0, col: 0, row: 1 }, * // newValue: null, * // }] * const changes = hfInstance.swapColumnIndexes(0, [[0, 2], [2, 0]]); * ``` * * @category Columns */ swapColumnIndexes(sheetId, columnMapping) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.setColumnOrder(sheetId, columnMapping); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Checks if it is possible to reorder columns of a sheet according to a source-target mapping. * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1, 2, 4], * [5] * ]); * * // returns true * hfInstance.isItPossibleToSwapColumnIndexes(0, [[0, 2], [2, 0]]); * * // returns false * hfInstance.isItPossibleToSwapColumnIndexes(0, [[0, 1]]); * ``` * * @category Columns */ isItPossibleToSwapColumnIndexes(sheetId, columnMapping) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { this._crudOperations.validateSwapColumnIndexes(sheetId, columnMapping); this._crudOperations.testColumnOrderForArrays(sheetId, columnMapping); return true; } catch (e) { return false; } } /** * Reorders columns of a sheet according to a permutation of 0-based indexes. * Parameter `newColumnOrder` should have a form `[ newPositionForColumn0, newPositionForColumn1, newPositionForColumn2, ... ]`. * This method might be used to [sort the columns of a sheet](../../guide/sorting-data.md). * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note: This method may trigger dependency graph recalculation. * * @param {number} sheetId - ID of a sheet to operate on * @param {number[]} newColumnOrder - permutation of columns * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['A', 'B', 'C', 'D'] * ]); * * const newColumnOrder = [0, 3, 2, 1]; // [ newPosForA, newPosForB, newPosForC, newPosForD ] * * const changes = hfInstance.setColumnOrder(0, newColumnOrder); * * // Sheet after this operation: [['A', 'D', 'C', 'B']] * ``` * * @category Columns */ setColumnOrder(sheetId, newColumnOrder) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const mapping = this._crudOperations.mappingFromOrder(sheetId, newColumnOrder, 'column'); return this.swapColumnIndexes(sheetId, mapping); } /** * Checks if it is possible to reorder columns of a sheet according to a permutation. * * @param {number} sheetId - ID of a sheet to operate on * @param {number[]} newColumnOrder - permutation of columns * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [1, 2, 4], * [5] * ]); * * // returns true * hfInstance.isItPossibleToSetColumnOrder(0, [2, 1, 0]); * * // returns false * hfInstance.isItPossibleToSetColumnOrder(0, [1]); * ``` * * @category Columns */ isItPossibleToSetColumnOrder(sheetId, newColumnOrder) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { const columnMapping = this._crudOperations.mappingFromOrder(sheetId, newColumnOrder, 'column'); this._crudOperations.validateSwapColumnIndexes(sheetId, columnMapping); this._crudOperations.testColumnOrderForArrays(sheetId, columnMapping); return true; } catch (e) { return false; } } /** * Returns information whether it is possible to add rows into a specified position in a given sheet. * Checks against particular rules to ascertain that addRows can be called. * If returns `true`, doing [[addRows]] operation won't throw any errors. * Returns `false` if adding rows would exceed the sheet size limit or given arguments are invalid. * * @param {number} sheetId - sheet ID in which rows will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [row, amount], where row is a row number above which the rows will be added * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], * ]); * * // should return 'true' for this example, * // it is possible to add one row in the second row of sheet 0 * const isAddable = hfInstance.isItPossibleToAddRows(0, [1, 1]); * ``` * * @category Rows */ isItPossibleToAddRows(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const normalizedIndexes = (0,_Operations__WEBPACK_IMPORTED_MODULE_12__.normalizeAddedIndexes)(indexes); try { this._crudOperations.ensureItIsPossibleToAddRows(sheetId, ...normalizedIndexes); return true; } catch (e) { return false; } } /** * Adds multiple rows into a specified position in a given sheet. * Does nothing if rows are outside effective sheet size. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID in which rows will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [row, amount], where row is a row number above which the rows will be added * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ]); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values * const changes = hfInstance.addRows(0, [0, 1]); * ``` * * @category Rows */ addRows(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.addRows(sheetId, ...indexes); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to remove rows from a specified position in a given sheet. * Checks against particular rules to ascertain that removeRows can be called. * If returns `true`, doing [[removeRows]] operation won't throw any errors. * Returns `false` if given arguments are invalid. * * @param {number} sheetId - sheet ID from which rows will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [row, amount] * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ]); * * // should return 'true' for this example * // it is possible to remove one row from row 1 of sheet 0 * const isRemovable = hfInstance.isItPossibleToRemoveRows(0, [1, 1]); * ``` * * @category Rows */ isItPossibleToRemoveRows(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const normalizedIndexes = (0,_Operations__WEBPACK_IMPORTED_MODULE_12__.normalizeRemovedIndexes)(indexes); try { this._crudOperations.ensureItIsPossibleToRemoveRows(sheetId, ...normalizedIndexes); return true; } catch (e) { return false; } } /** * Removes multiple rows from a specified position in a given sheet. * Does nothing if rows are outside the effective sheet size. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID from which rows will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [row, amount] * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ]); * * // should return: [{ sheet: 0, col: 1, row: 2, value: null }] for this example * const changes = hfInstance.removeRows(0, [1, 1]); * ``` * * @category Rows */ removeRows(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.removeRows(sheetId, ...indexes); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to add columns into a specified position in a given sheet. * Checks against particular rules to ascertain that addColumns can be called. * If returns `true`, doing [[addColumns]] operation won't throw any errors. * Returns `false` if adding columns would exceed the sheet size limit or given arguments are invalid. * * @param {number} sheetId - sheet ID in which columns will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [column, amount], where column is a column number from which new columns will be added * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // should return 'true' for this example, * // it is possible to add 1 column in sheet 0, at column 1 * const isAddable = hfInstance.isItPossibleToAddColumns(0, [1, 1]); * ``` * * @category Columns */ isItPossibleToAddColumns(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const normalizedIndexes = (0,_Operations__WEBPACK_IMPORTED_MODULE_12__.normalizeAddedIndexes)(indexes); try { this._crudOperations.ensureItIsPossibleToAddColumns(sheetId, ...normalizedIndexes); return true; } catch (e) { return false; } } /** * Adds multiple columns into a specified position in a given sheet. * Does nothing if the columns are outside the effective sheet size. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID in which columns will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [column, amount], where column is a column number from which new columns will be added * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=RAND()', '42'], * ]); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: * // [{ * // address: { sheet: 0, col: 1, row: 0 }, * // newValue: 0.92754862796338, * // }] * const changes = hfInstance.addColumns(0, [0, 1]); * ``` * * @category Columns */ addColumns(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.addColumns(sheetId, ...indexes); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to remove columns from a specified position in a given sheet. * Checks against particular rules to ascertain that removeColumns can be called. * If returns `true`, doing [[removeColumns]] operation won't throw any errors. * Returns `false` if given arguments are invalid. * * @param {number} sheetId - sheet ID from which columns will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [column, amount] * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // should return 'true' for this example * // it is possible to remove one column, in place of the second column of sheet 0 * const isRemovable = hfInstance.isItPossibleToRemoveColumns(0, [1, 1]); * ``` * * @category Columns */ isItPossibleToRemoveColumns(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const normalizedIndexes = (0,_Operations__WEBPACK_IMPORTED_MODULE_12__.normalizeRemovedIndexes)(indexes); try { this._crudOperations.ensureItIsPossibleToRemoveColumns(sheetId, ...normalizedIndexes); return true; } catch (e) { return false; } } /** * Removes multiple columns from a specified position in a given sheet. * Does nothing if columns are outside the effective sheet size. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID from which columns will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [column, amount] * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['0', '=SUM(1, 2, 3)', '=A1'], * ]); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: * // [{ * // address: { sheet: 0, col: 1, row: 0 }, * // newValue: { error: [CellError], value: '#REF!' }, * // }] * const changes = hfInstance.removeColumns(0, [0, 1]); * ``` * * @category Columns */ removeColumns(sheetId, ...indexes) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.removeColumns(sheetId, ...indexes); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to move cells to a specified position in a given sheet. * Checks against particular rules to ascertain that moveCells can be called. * If returns `true`, doing [[moveCells]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected columns, the target location includes an array or the provided address is invalid. * * @param {SimpleCellRange} source - range for a moved block * @param {SimpleCellAddress} destinationLeftCorner - upper left address of the target cell block * * @throws [[ExpectedValueOfTypeError]] if destinationLeftCorner, source, or any of basic type arguments are of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // choose the coordinates and assign them to variables * const source = { sheet: 0, col: 1, row: 0 }; * const destination = { sheet: 0, col: 3, row: 0 }; * * // should return 'true' for this example * // it is possible to move a block of width 1 and height 1 * // from the corner: column 1 and row 0 of sheet 0 * // into destination corner: column 3, row 0 of sheet 0 * const isMovable = hfInstance.isItPossibleToMoveCells({ start: source, end: source }, destination); * ``` * @category Cells */ isItPossibleToMoveCells(source, destinationLeftCorner) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(destinationLeftCorner)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner'); } if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } try { const range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); this._crudOperations.operations.ensureItIsPossibleToMoveCells(range.start, range.width(), range.height(), destinationLeftCorner); return true; } catch (e) { return false; } } /** * Moves the content of a cell block from source to the target location. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {SimpleCellRange} source - range for a moved block * @param {SimpleCellAddress} destinationLeftCorner - upper left address of the target cell block * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if destinationLeftCorner or source are of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=RAND()', '42'], * ]); * * // choose the coordinates and assign them to variables * const source = { sheet: 0, col: 1, row: 0 }; * const destination = { sheet: 0, col: 3, row: 0 }; * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: * // [{ * // address: { sheet: 0, col: 0, row: 0 }, * // newValue: 0.93524248002062, * // }] * const changes = hfInstance.moveCells({ start: source, end: source }, destination); * ``` * * @category Cells */ moveCells(source, destinationLeftCorner) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(destinationLeftCorner)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner'); } if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); this._crudOperations.moveCells(range.start, range.width(), range.height(), destinationLeftCorner); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to move a particular number of rows to a specified position in a given sheet. * Checks against particular rules to ascertain that moveRows can be called. * If returns `true`, doing [[moveRows]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected rows, the target location includes an array or the provided address is invalid. * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startRow - number of the first row to move * @param {number} numberOfRows - number of rows to move * @param {number} targetRow - row number before which rows will be moved * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ]); * * // should return 'true' for this example * // it is possible to move one row from row 0 into row 2 * const isMovable = hfInstance.isItPossibleToMoveRows(0, 0, 1, 2); * ``` * * @category Rows */ isItPossibleToMoveRows(sheetId, startRow, numberOfRows, targetRow) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(startRow, 'number', 'startRow'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(numberOfRows, 'number', 'numberOfRows'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(targetRow, 'number', 'targetRow'); try { this._crudOperations.ensureItIsPossibleToMoveRows(sheetId, startRow, numberOfRows, targetRow); return true; } catch (e) { return false; } } /** * Moves a particular number of rows to a specified position in a given sheet. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startRow - number of the first row to move * @param {number} numberOfRows - number of rows to move * @param {number} targetRow - row number before which rows will be moved * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], * ]); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values * const changes = hfInstance.moveRows(0, 0, 1, 2); * ``` * * @category Rows */ moveRows(sheetId, startRow, numberOfRows, targetRow) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(startRow, 'number', 'startRow'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(numberOfRows, 'number', 'numberOfRows'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(targetRow, 'number', 'targetRow'); this._crudOperations.moveRows(sheetId, startRow, numberOfRows, targetRow); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to move a particular number of columns to a specified position in a given sheet. * Checks against particular rules to ascertain that moveColumns can be called. * If returns `true`, doing [[moveColumns]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected columns, the target location includes an array or the provided address is invalid. * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startColumn - number of the first column to move * @param {number} numberOfColumns - number of columns to move * @param {number} targetColumn - column number before which columns will be moved * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // should return 'true' for this example * // it is possible to move one column from column 1 into column 2 of sheet 0 * const isMovable = hfInstance.isItPossibleToMoveColumns(0, 1, 1, 2); * ``` * * @category Columns */ isItPossibleToMoveColumns(sheetId, startColumn, numberOfColumns, targetColumn) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(startColumn, 'number', 'startColumn'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(numberOfColumns, 'number', 'numberOfColumns'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(targetColumn, 'number', 'targetColumn'); try { this._crudOperations.ensureItIsPossibleToMoveColumns(sheetId, startColumn, numberOfColumns, targetColumn); return true; } catch (e) { return false; } } /** * Moves a particular number of columns to a specified position in a given sheet. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startColumn - number of the first column to move * @param {number} numberOfColumns - number of columns to move * @param {number} targetColumn - column number before which columns will be moved * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3', '=RAND()', '=SUM(A1:C1)'], * ]); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: * // [{ * // address: { sheet: 0, col: 1, row: 0 }, * // newValue: 0.16210054671639, * // }, { * // address: { sheet: 0, col: 4, row: 0 }, * // newValue: 6.16210054671639, * // }] * const changes = hfInstance.moveColumns(0, 1, 1, 2); * ``` * * @category Columns */ moveColumns(sheetId, startColumn, numberOfColumns, targetColumn) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(startColumn, 'number', 'startColumn'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(numberOfColumns, 'number', 'numberOfColumns'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(targetColumn, 'number', 'targetColumn'); this._crudOperations.moveColumns(sheetId, startColumn, numberOfColumns, targetColumn); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Stores a copy of the cell block in internal clipboard for the further paste. * Returns the copied values for use in external clipboard. * * @param {SimpleCellRange} source - rectangle range to copy * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // it copies [ [ 2 ] ] * const clipboardContent = hfInstance.copy({ * start: { sheet: 0, col: 1, row: 0 }, * end: { sheet: 0, col: 1, row: 0 }, * }); * ``` * * The usage of the internal clipboard is described thoroughly in the [Clipboard Operations guide](../../guide/clipboard-operations.md). * * @category Clipboard */ copy(source) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); this._crudOperations.copy(range.start, range.width(), range.height()); return this.getRangeValues(source); } /** * Stores information of the cell block in internal clipboard for further paste. * Calling [[paste]] right after this method is equivalent to call [[moveCells]]. * Almost any CRUD operation called after this method will abort the cut operation. * Returns the cut values for use in external clipboard. * * @param {SimpleCellRange} source - rectangle range to cut * * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // returns the values that were cut: [ [ 1 ] ] * const clipboardContent = hfInstance.cut({ * start: { sheet: 0, col: 0, row: 0 }, * end: { sheet: 0, col: 0, row: 0 }, * }); * ``` * * The usage of the internal clipboard is described thoroughly in the [Clipboard Operations guide](../../guide/clipboard-operations.md). * * @category Clipboard */ cut(source) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const range = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); this._crudOperations.cut(range.start, range.width(), range.height()); return this.getRangeValues(source); } /** * When called after [[copy]] it pastes copied values and formulas into a cell block. * When called after [[cut]] it performs [[moveCells]] operation into the cell block. * Does nothing if the clipboard is empty. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {SimpleCellAddress} targetLeftCorner - upper left address of the target cell block * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * @throws [[NothingToPasteError]] when clipboard is empty * @throws [[TargetLocationHasArrayError]] when the selected target area has array inside * @throws [[ExpectedValueOfTypeError]] if targetLeftCorner is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // [ [ 2 ] ] was copied * const clipboardContent = hfInstance.copy({ * start: { sheet: 0, col: 1, row: 0 }, * end: { sheet: 0, col: 1, row: 0 }, * }); * * // returns a list of modified cells: their absolute addresses and new values * const changes = hfInstance.paste({ sheet: 0, col: 1, row: 0 }); * ``` * * The usage of the internal clipboard is described thoroughly in the [Clipboard Operations guide](../../guide/clipboard-operations.md). * * @category Clipboard */ paste(targetLeftCorner) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(targetLeftCorner)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'targetLeftCorner'); } this.ensureEvaluationIsNotSuspended(); this._crudOperations.paste(targetLeftCorner); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether there is something in the clipboard. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // copy desired content * const clipboardContent = hfInstance.copy({ * start: { sheet: 0, col: 1, row: 0 }, * end: { sheet: 0, col: 1, row: 0 }, * }); * * // returns 'false', there is content in the clipboard * const isClipboardEmpty = hfInstance.isClipboardEmpty(); * ``` * * The usage of the internal clipboard is described thoroughly in the [Clipboard Operations guide](../../guide/clipboard-operations.md). * * @category Clipboard */ isClipboardEmpty() { return this._crudOperations.isClipboardEmpty(); } /** * Clears the clipboard content. * * @example * ```js * // clears the clipboard, isClipboardEmpty() should return true if called afterwards * hfInstance.clearClipboard(); * ``` * * The usage of the internal clipboard is described thoroughly in the [Clipboard Operations guide](../../guide/clipboard-operations.md). * * @category Clipboard */ clearClipboard() { this._crudOperations.clearClipboard(); } /** * Clears the redo stack in undoRedo history. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], * ]); * * // do an operation, for example remove columns * hfInstance.removeColumns(0, [0, 1]); * * // undo the operation * hfInstance.undo(); * * // redo the operation * hfInstance.redo(); * * // clear the redo stack * hfInstance.clearRedoStack(); * ``` * * @category Undo and Redo */ clearRedoStack() { this._crudOperations.undoRedo.clearRedoStack(); } /** * Clears the undo stack in undoRedo history. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], * ]); * * // do an operation, for example remove columns * hfInstance.removeColumns(0, [0, 1]); * * // undo the operation * hfInstance.undo(); * * // clear the undo stack * hfInstance.clearUndoStack(); * ``` * * @category Undo and Redo */ clearUndoStack() { this._crudOperations.undoRedo.clearUndoStack(); } /** * Returns the cell content of a given range in a [[CellValue]][][] format. * * @param {SimpleCellRange} source - rectangular range * * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2)', '2', '10'], * ['5', '6', '7'], * ['40', '30', '20'], * ]); * * * // returns calculated cells content: [ [ 3, 2 ], [ 5, 6 ] ] * const rangeValues = hfInstance.getRangeValues({ start: { sheet: 0, col: 0, row: 0 }, end: { sheet: 0, col: 1, row: 1 } }); * ``` * * @category Ranges */ getRangeValues(source) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const cellRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); return cellRange.arrayOfAddressesInRange().map(subarray => subarray.map(address => this.getCellValue(address))); } /** * Returns cell formulas in given range. * * @param {SimpleCellRange} source - rectangular range * * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2)', '2', '10'], * ['5', '6', '7'], * ['40', '30', '20'], * ]); * * // returns cell formulas of a given range only: * // [ [ '=SUM(1, 2)', undefined ], [ undefined, undefined ] ] * const rangeFormulas = hfInstance.getRangeFormulas({ start: { sheet: 0, col: 0, row: 0 }, end: { sheet: 0, col: 1, row: 1 } }); * ``` * * @category Ranges */ getRangeFormulas(source) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const cellRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); return cellRange.arrayOfAddressesInRange().map(subarray => subarray.map(address => this.getCellFormula(address))); } /** * Returns serialized cells in given range. * * @param {SimpleCellRange} source - rectangular range * * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2)', '2', '10'], * ['5', '6', '7'], * ['40', '30', '20'], * ]); * * // should return serialized cell content for the given range: * // [ [ '=SUM(1, 2)', 2 ], [ 5, 6 ] ] * const rangeSerialized = hfInstance.getRangeSerialized({ start: { sheet: 0, col: 0, row: 0 }, end: { sheet: 0, col: 1, row: 1 } }); * ``` * * @category Ranges */ getRangeSerialized(source) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } const cellRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); return cellRange.arrayOfAddressesInRange().map(subarray => subarray.map(address => this.getCellSerialized(address))); } /** * Returns values to fill target range using source range, with properly extending the range using wrap-around heuristic. * * @param {SimpleCellRange} source of data * @param {SimpleCellRange} target range where data is intended to be put * @param {boolean} offsetsFromTarget if true, offsets are computed from target corner, otherwise from source corner * * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[ExpectedValueOfTypeError]] if source or target are of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([[1, '=A1'], ['=$A$1', '2']]); * * // should return [['2', '=$A$1', '2'], ['=A3', 1, '=C3'], ['2', '=$A$1', '2']] * hfInstance.getFillRangeData( {start: {sheet: 0, row: 0, col: 0}, end: {sheet: 0, row: 1, col: 1}}, * {start: {sheet: 0, row: 1, col: 1}, end: {sheet: 0, row: 3, col: 3}}); * ``` * * @category Ranges */ getFillRangeData(source, target, offsetsFromTarget = false) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(source)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'source'); } if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(target)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'target'); } const sourceRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(source.start, source.end); const targetRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(target.start, target.end); this.ensureEvaluationIsNotSuspended(); return targetRange.arrayOfAddressesInRange().map(subarray => subarray.map(address => { const row = ((address.row - (offsetsFromTarget ? target : source).start.row) % sourceRange.height() + sourceRange.height()) % sourceRange.height() + source.start.row; const col = ((address.col - (offsetsFromTarget ? target : source).start.col) % sourceRange.width() + sourceRange.width()) % sourceRange.width() + source.start.col; return this._serialization.getCellSerialized({ row, col, sheet: sourceRange.sheet }, address); })); } /** * Returns information whether it is possible to add a sheet to the engine. * Checks against particular rules to ascertain that addSheet can be called. * If returns `true`, doing [[addSheet]] operation won't throw any errors, and it is possible to add sheet with provided name. * Returns `false` if the chosen name is already used. * * @param {string} sheetName - sheet name, case-insensitive * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'false' because 'MySheet2' already exists * const isAddable = hfInstance.isItPossibleToAddSheet('MySheet2'); * ``` * * @category Sheets */ isItPossibleToAddSheet(sheetName) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetName, 'string', 'sheetName'); try { this._crudOperations.ensureItIsPossibleToAddSheet(sheetName); return true; } catch (e) { return false; } } /** * Adds a new sheet to the HyperFormula instance. Returns given or autogenerated name of a new sheet. * * @param {string} [sheetName] - if not specified, name is autogenerated * * @fires [[sheetAdded]] after the sheet was added * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[SheetNameAlreadyTakenError]] when sheet with a given name already exists * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'MySheet3' * const nameProvided = hfInstance.addSheet('MySheet3'); * * // should return autogenerated 'Sheet4' * // because no name was provided and 3 other ones already exist * const generatedName = hfInstance.addSheet(); * ``` * * @category Sheets */ addSheet(sheetName) { if (sheetName !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetName, 'string', 'sheetName'); } const addedSheetName = this._crudOperations.addSheet(sheetName); this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.SheetAdded, addedSheetName); return addedSheetName; } /** * Returns information whether it is possible to remove sheet for the engine. * Returns `true` if the provided sheet exists, and therefore it can be removed, doing [[removeSheet]] operation won't throw any errors. * Returns `false` otherwise * * @param {number} sheetId - sheet ID. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'true' because sheet with ID 1 exists and is removable * const isRemovable = hfInstance.isItPossibleToRemoveSheet(1); * ``` * * @category Sheets */ isItPossibleToRemoveSheet(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { this._crudOperations.ensureScopeIdIsValid(sheetId); return true; } catch (e) { return false; } } /** * Removes a sheet * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID. * * @fires [[sheetRemoved]] after the sheet was removed * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], * }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: * // [{ * // address: { sheet: 0, col: 0, row: 0 }, * // newValue: { error: [CellError], value: '#REF!' }, * // }] * const changes = hfInstance.removeSheet(1); * ``` * * @category Sheets */ removeSheet(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); const displayName = this.sheetMapping.getDisplayName(sheetId); this._crudOperations.removeSheet(sheetId); const changes = this.recomputeIfDependencyGraphNeedsIt(); this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.SheetRemoved, displayName, changes); return changes; } /** * Returns information whether it is possible to clear a specified sheet. * If returns `true`, doing [[clearSheet]] operation won't throw any errors, provided sheet exists and its content can be cleared. * Returns `false` otherwise * * @param {number} sheetId - sheet ID. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'true' because 'MySheet2' exists and can be cleared * const isClearable = hfInstance.isItPossibleToClearSheet(1); * ``` * * @category Sheets */ isItPossibleToClearSheet(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { this._crudOperations.ensureScopeIdIsValid(sheetId); return true; } catch (e) { return false; } } /** * Clears the sheet content. Double-checks if the sheet exists. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {number} sheetId - sheet ID. * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], * }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: * // [{ * // address: { sheet: 0, col: 0, row: 0 }, * // newValue: 0, * // }] * const changes = hfInstance.clearSheet(0); * ``` * * @category Sheets */ clearSheet(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.clearSheet(sheetId); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to replace the sheet content. * If returns `true`, doing [[setSheetContent]] operation won't throw any errors, the provided sheet exists and then its content can be replaced. * Returns `false` otherwise * * @param {number} sheetId - sheet ID. * @param {RawCellContent[][]} values - array of new values * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'true' because sheet of ID 0 exists * // and the provided content can be placed in this sheet * const isReplaceable = hfInstance.isItPossibleToReplaceSheetContent(0, [['50'], ['60']]); * ``` * * @category Sheets */ isItPossibleToReplaceSheetContent(sheetId, values) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); try { this._crudOperations.ensureScopeIdIsValid(sheetId); this._crudOperations.ensureItIsPossibleToChangeSheetContents(sheetId, values); return true; } catch (e) { return false; } } /** * Replaces the sheet content with new values. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * @param {number} sheetId - sheet ID. * @param {RawCellContent[][]} values - array of new values * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when values argument is not an array of arrays * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values * const changes = hfInstance.setSheetContent(0, [['50'], ['60']]); * ``` * * @category Sheets */ setSheetContent(sheetId, values) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.setSheetContent(sheetId, values); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Computes the simple (absolute) address of a cell address, based on its string representation. * - If a sheet name is present in the string representation but is not present in the engine, returns `undefined`. * - If no sheet name is present in the string representation, returns `contextSheetId` as sheet number. * * @param {string} cellAddress - string representation of cell address in A1 notation * @param {number} contextSheetId - context used in case of missing sheet in the first argument * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * * // returns { sheet: 0, col: 0, row: 0 } * const simpleCellAddress = hfInstance.simpleCellAddressFromString('A1', 0); * * // returns { sheet: 0, col: 0, row: 5 } * const simpleCellAddress = hfInstance.simpleCellAddressFromString('Sheet1!A6'); * * // returns { sheet: 0, col: 0, row: 5 } * const simpleCellAddress = hfInstance.simpleCellAddressFromString('Sheet1!$A$6'); * * // returns 'undefined', as there's no 'Sheet 2' in the HyperFormula instance * const simpleCellAddress = hfInstance.simpleCellAddressFromString('Sheet2!A6'); * ``` * * @category Helpers */ simpleCellAddressFromString(cellAddress, contextSheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(cellAddress, 'string', 'cellAddress'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(contextSheetId, 'number', 'sheetId'); return (0,_parser__WEBPACK_IMPORTED_MODULE_13__.simpleCellAddressFromString)(this.sheetMapping.get, cellAddress, contextSheetId); } /** * Computes simple (absolute) address of a cell range based on its string representation. * If sheet name is present in string representation but not present in the engine, returns `undefined`. * * @param {string} cellRange - string representation of cell range in A1 notation * @param {number} sheetId - context used in case of missing sheet in the first argument * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * * // should return { start: { sheet: 0, col: 0, row: 0 }, end: { sheet: 0, col: 1, row: 0 } } * const simpleCellAddress = hfInstance.simpleCellRangeFromString('A1:A2', 0); * ``` * * @category Helpers */ simpleCellRangeFromString(cellRange, sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(cellRange, 'string', 'cellRange'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return (0,_parser__WEBPACK_IMPORTED_MODULE_13__.simpleCellRangeFromString)(this.sheetMapping.get, cellRange, sheetId); } /** * Returns string representation of an absolute address in A1 notation or `undefined` if the sheet index is not present in the engine. * * @param {SimpleCellAddress} cellAddress - object representation of an absolute address * @param {number} sheetId - context used in case of missing sheet in the first argument * * @throws [[ExpectedValueOfTypeError]] if its arguments are of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * * // should return 'B2' * const A1Notation = hfInstance.simpleCellAddressToString({ sheet: 0, col: 1, row: 1 }, 0); * ``` * * @category Helpers */ simpleCellAddressToString(cellAddress, sheetId) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return (0,_parser__WEBPACK_IMPORTED_MODULE_13__.simpleCellAddressToString)(this.sheetMapping.fetchDisplayName, cellAddress, sheetId); } /** * Returns string representation of an absolute range in A1 notation or `undefined` if the sheet index is not present in the engine. * * Note: This method is useful only for cell ranges; does not work with column ranges and row ranges. * * @param {SimpleCellRange} cellRange - object representation of an absolute range * @param {number} sheetId - context used in case of missing sheet in the first argument * * @throws [[ExpectedValueOfTypeError]] if its arguments are of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * hfInstance.addSheet('Sheet1'); //sheetId = 1 * * // should return 'B2:C2' * const A1Notation = hfInstance.simpleCellRangeToString({ start: { sheet: 0, col: 1, row: 1 }, end: { sheet: 0, col: 2, row: 1 } }, 0); * * // should return 'Sheet1!B2:C2' * const another = hfInstance.simpleCellRangeToString({ start: { sheet: 1, col: 1, row: 1 }, end: { sheet: 1, col: 2, row: 1 } }, 0); * ``` * * @category Helpers */ simpleCellRangeToString(cellRange, sheetId) { if (!(0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(cellRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellRange', 'cellRange'); } (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return (0,_parser__WEBPACK_IMPORTED_MODULE_13__.simpleCellRangeToString)(this.sheetMapping.fetchDisplayName, cellRange, sheetId); } /** * Returns all the out-neighbors in the [dependency graph](../../guide/dependency-graph.md) for a given cell address or range. Including: * - All cells with formulas that contain the given cell address or range * - Some of the ranges that contain the given cell address or range * * The exact result depends on the optimizations applied by the HyperFormula to the dependency graph, some of which are described in the section ["Optimizations for large ranges"](../../guide/dependency-graph.md#optimizations-for-large-ranges). * * The returned array includes also named expression dependents. They are represented as cell references with sheet ID `-1`. * * @param {SimpleCellAddress | SimpleCellRange} address - object representation of an absolute address or range of addresses * * @throws [[ExpectedValueOfTypeError]] if address is not [[SimpleCellAddress]] or [[SimpleCellRange]] * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] ); * * hfInstance.getCellDependents({ sheet: 0, col: 0, row: 0}); * // returns [{ sheet: 0, col: 1, row: 0}, { sheet: 0, col: 2, row: 0}] * ``` * * @category Helpers */ getCellDependents(address) { let vertex; if ((0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(address)) { vertex = this._dependencyGraph.addressMapping.getCell(address); } else if ((0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(address)) { vertex = this._dependencyGraph.rangeMapping.getRange(address.start, address.end); } else { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress | SimpleCellRange', address); } if (vertex === undefined) { return []; } return this._dependencyGraph.getAdjacentNodesAddresses(vertex); } /** * Returns all the in-neighbors in the [dependency graph](../../guide/dependency-graph.md) for a given cell address or range. In particular: * - If the argument is a single cell, `getCellPrecedents()` returns all cells and ranges contained in that cell's formula. * - If the argument is a range of cells, `getCellPrecedents()` returns some of the cell addresses and smaller ranges contained in that range (but not all of them). The exact result depends on the optimizations applied by the HyperFormula to the dependency graph, some of which are described in the section ["Optimizations for large ranges"](../../guide/dependency-graph.md#optimizations-for-large-ranges). * * The returned array includes also named expression precedents. They are represented as cell references with sheet ID `-1`. * * @param {SimpleCellAddress | SimpleCellRange} address - object representation of an absolute address or range of addresses * * @throws [[ExpectedValueOfTypeError]] if address is of wrong type * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * * @example * ```js * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] ); * * hfInstance.getCellPrecedents({ sheet: 0, col: 2, row: 0}); * // returns [{ sheet: 0, col: 0, row: 0}, { sheet: 0, col: 1, row: 0}] * ``` * * @category Helpers */ getCellPrecedents(address) { let vertex; if ((0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(address)) { vertex = this._dependencyGraph.addressMapping.getCell(address); } else if ((0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellRange)(address)) { vertex = this._dependencyGraph.rangeMapping.getRange(address.start, address.end); } else { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress | SimpleCellRange', address); } if (vertex === undefined) { return []; } return this._dependencyGraph.dependencyQueryAddresses(vertex); } /** * Returns a unique sheet name assigned to the sheet of a given ID or `undefined` if the there is no sheet with a given ID. * * @param {number} sheetId - ID of the sheet, for which we want to retrieve name * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'MySheet2' as this sheet is the second one * const sheetName = hfInstance.getSheetName(1); * ``` * * @category Sheets */ getSheetName(sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); return this.sheetMapping.getDisplayName(sheetId); } /** * List all sheet names. * Returns an array of sheet names as strings. * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return all sheets names: ['MySheet1', 'MySheet2'] * const sheetNames = hfInstance.getSheetNames(); * ``` * * @category Sheets */ getSheetNames() { return this.sheetMapping.sheetNames(); } /** * Returns a unique sheet ID assigned to the sheet with a given name or `undefined` if the sheet does not exist. * * @param {string} sheetName - name of the sheet, for which we want to retrieve ID, case-insensitive. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return '0' because 'MySheet1' is of ID '0' * const sheetID = hfInstance.getSheetId('MySheet1'); * ``` * * @category Sheets */ getSheetId(sheetName) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetName, 'string', 'sheetName'); return this.sheetMapping.get(sheetName); } /** * Returns `true` whether sheet with a given name exists. The method accepts sheet name to be checked. * * @param {string} sheetName - name of the sheet, case-insensitive. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // should return 'true' since 'MySheet1' exists * const sheetExist = hfInstance.doesSheetExist('MySheet1'); * ``` * * @category Sheets */ doesSheetExist(sheetName) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetName, 'string', 'sheetName'); return this.sheetMapping.hasSheetWithName(sheetName); } /** * Returns the type of a cell at a given address. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], * ]); * * // should return 'FORMULA', the cell of given coordinates is of this type * const cellA1Type = hfInstance.getCellType({ sheet: 0, col: 0, row: 0 }); * * // should return 'VALUE', the cell of given coordinates is of this type * const cellB1Type = hfInstance.getCellType({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellType(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } const vertex = this.dependencyGraph.getCell(cellAddress); return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.getCellType)(vertex, cellAddress); } /** * Returns `true` if the specified cell contains a simple value. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], * ]); * * // should return 'true' since the selected cell contains a simple value * const isA1Simple = hfInstance.doesCellHaveSimpleValue({ sheet: 0, col: 0, row: 0 }); * * // should return 'false' since the selected cell does not contain a simple value * const isB1Simple = hfInstance.doesCellHaveSimpleValue({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ doesCellHaveSimpleValue(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } return this.getCellType(cellAddress) === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.VALUE; } /** * Returns `true` if the specified cell contains a formula. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], * ]); * * // should return 'true' since the A1 cell contains a formula * const A1Formula = hfInstance.doesCellHaveFormula({ sheet: 0, col: 0, row: 0 }); * * // should return 'false' since the B1 cell does not contain a formula * const B1NoFormula = hfInstance.doesCellHaveFormula({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ doesCellHaveFormula(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } const cellType = this.getCellType(cellAddress); return cellType === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.FORMULA || cellType === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.ARRAYFORMULA; } /** * Returns`true` if the specified cell is empty. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * [null, '1'], * ]); * * // should return 'true', cell of provided coordinates is empty * const isEmpty = hfInstance.isCellEmpty({ sheet: 0, col: 0, row: 0 }); * * // should return 'false', cell of provided coordinates is not empty * const isNotEmpty = hfInstance.isCellEmpty({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ isCellEmpty(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } return this.getCellType(cellAddress) === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.EMPTY; } /** * Returns `true` if a given cell is a part of an array. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['{=TRANSPOSE(B1:B1)}'], * ]); * * // should return 'true', cell of provided coordinates is a part of an array * const isPartOfArray = hfInstance.isCellPartOfArray({ sheet: 0, col: 0, row: 0 }); * ``` * * @category Cells */ isCellPartOfArray(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } const cellType = this.getCellType(cellAddress); return cellType === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.ARRAY || cellType === _Cell__WEBPACK_IMPORTED_MODULE_3__.CellType.ARRAYFORMULA; } /** * Returns type of the cell value of a given address. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '2'], * ]); * * // should return 'NUMBER', cell value type of provided coordinates is a number * const cellValue = hfInstance.getCellValueType({ sheet: 0, col: 1, row: 0 }); * * // should return 'NUMBER', cell value type of provided coordinates is a number * const cellValue = hfInstance.getCellValueType({ sheet: 0, col: 0, row: 0 }); * ``` * * @category Cells */ getCellValueType(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); const value = this.dependencyGraph.getCellValue(cellAddress); return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.getCellValueType)(value); } /** * Returns detailed type of the cell value of a given address. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1%', '1$'], * ]); * * // should return 'NUMBER_PERCENT', cell value type of provided coordinates is a number with a format inference percent. * const cellType = hfInstance.getCellValueDetailedType({ sheet: 0, col: 0, row: 0 }); * * // should return 'NUMBER_CURRENCY', cell value type of provided coordinates is a number with a format inference currency. * const cellType = hfInstance.getCellValueDetailedType({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellValueDetailedType(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); const value = this.dependencyGraph.getCellValue(cellAddress); return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.getCellValueDetailedType)(value); } /** * Returns auxiliary format information of the cell value of a given address. * The method accepts cell coordinates as object with column, row and sheet numbers. * * @param {SimpleCellAddress} cellAddress - cell coordinates * * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[EvaluationSuspendedError]] when the evaluation is suspended * @throws [[ExpectedValueOfTypeError]] if cellAddress is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1$', '1'], * ]); * * // should return '$', cell value type of provided coordinates is a number with a format inference currency, parsed as using '$' as currency. * const cellFormat = hfInstance.getCellValueFormat({ sheet: 0, col: 0, row: 0 }); * * // should return undefined, cell value type of provided coordinates is a number with no format information. * const cellFormat = hfInstance.getCellValueFormat({ sheet: 0, col: 1, row: 0 }); * ``` * * @category Cells */ getCellValueFormat(cellAddress) { if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.isSimpleCellAddress)(cellAddress)) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress'); } this.ensureEvaluationIsNotSuspended(); const value = this.dependencyGraph.getCellValue(cellAddress); return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.getCellValueFormat)(value); } /** * Returns the number of existing sheets. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ]); * * // should return the number of sheets which is '1' * const sheetsCount = hfInstance.countSheets(); * ``` * * @category Sheets */ countSheets() { return this.sheetMapping.numberOfSheets(); } /** * Returns information whether it is possible to rename sheet. * Returns `true` if the sheet with provided id exists and new name is available * Returns `false` if sheet cannot be renamed * * @param {number} sheetId - a sheet number * @param {string} newName - a name of the sheet to be given * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // returns true * hfInstance.isItPossibleToRenameSheet(0, 'MySheet0'); * ``` * * @category Sheets */ isItPossibleToRenameSheet(sheetId, newName) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(newName, 'string', 'newName'); try { this._crudOperations.ensureItIsPossibleToRenameSheet(sheetId, newName); return true; } catch (e) { return false; } } /** * Renames a specified sheet. * * @param {number} sheetId - a sheet ID * @param {string} newName - a name of the sheet to be given, if is the same as the old one the method does nothing * * @fires [[sheetRenamed]] after the sheet was renamed * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetNameAlreadyTakenError]] when the provided sheet name already exists * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // renames the sheet 'MySheet1' * hfInstance.renameSheet(0, 'MySheet0'); * ``` * * @category Sheets */ renameSheet(sheetId, newName) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(newName, 'string', 'newName'); const oldName = this._crudOperations.renameSheet(sheetId, newName); if (oldName !== undefined) { this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.SheetRenamed, oldName, newName); } } /** * Runs the provided callback as a single [batch operation](../../guide/batch-operations.md) and returns the changed cells. * * Returns [an array of cells whose values changed as a result of all batched operations](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {() => void} batchOperations - a function with operations to be performed * * @fires [[valuesUpdated]] if recalculation was triggered by this change * @fires [[evaluationSuspended]] always * @fires [[evaluationResumed]] after the recomputation of necessary values * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // multiple operations in a single callback will trigger evaluation only once * // and only one set of changes is returned as a combined result of all * // the operations that were triggered within the callback * const changes = hfInstance.batch(() => { * hfInstance.setCellContents({ col: 3, row: 0, sheet: 0 }, [['=B1']]); * hfInstance.setCellContents({ col: 4, row: 0, sheet: 0 }, [['=A1']]); * }); * ``` * * @category Batch */ batch(batchOperations) { this.suspendEvaluation(); this._crudOperations.beginUndoRedoBatchMode(); try { batchOperations(); } catch (e) { this._crudOperations.commitUndoRedoBatchMode(); this.resumeEvaluation(); throw e; } this._crudOperations.commitUndoRedoBatchMode(); return this.resumeEvaluation(); } /** * Suspends the dependency graph recalculation to start a [batch operation](../../guide/batch-operations.md). * It allows optimizing the performance. * With this method, multiple CRUD operations can be done without triggering recalculation after every operation. * Suspending evaluation should result in an overall faster calculation compared to recalculating after each operation separately. * To resume the evaluation use [[resumeEvaluation]]. * * @fires [[evaluationSuspended]] always * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // similar to batch() but operations are not within a callback, * // one method suspends the recalculation * // the second will resume calculations and return the changes * * // suspend the evaluation with this method * hfInstance.suspendEvaluation(); * * // perform operations * hfInstance.setCellContents({ col: 3, row: 0, sheet: 0 }, [['=B1']]); * hfInstance.setSheetContent(1, [['50'], ['60']]); * * // use resumeEvaluation to resume * const changes = hfInstance.resumeEvaluation(); * ``` * * @category Batch */ suspendEvaluation() { this._evaluationSuspended = true; this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.EvaluationSuspended); } /** * Resumes the dependency graph recalculation that was [suspended](../../guide/batch-operations.md) with [[suspendEvaluation]]. * It also triggers the recalculation and returns [an array of cells whose values changed as a result of all batched operations](/guide/basic-operations.md#changes-array). * * @fires [[valuesUpdated]] if recalculation was triggered by this change * @fires [[evaluationResumed]] after the recomputation of necessary values * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], * }); * * // similar to batch() but operations are not within a callback, * // one method suspends the recalculation * // the second will resume calculations and return the changes * * // first, suspend the evaluation * hfInstance.suspendEvaluation(); * * // perform operations * hfInstance.setCellContents({ col: 3, row: 0, sheet: 0 }, [['=B1']]); * hfInstance.setSheetContent(1, [['50'], ['60']]); * * // resume the evaluation * const changes = hfInstance.resumeEvaluation(); * ``` * * @category Batch */ resumeEvaluation() { this._evaluationSuspended = false; const changes = this.recomputeIfDependencyGraphNeedsIt(); this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.EvaluationResumed, changes); return changes; } /** * Checks if the dependency graph recalculation process is [suspended](../../guide/batch-operations.md) or not. * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // suspend the evaluation * hfInstance.suspendEvaluation(); * * // between suspendEvaluation() and resumeEvaluation() * // or inside batch() callback it will return 'true', otherwise 'false' * const isEvaluationSuspended = hfInstance.isEvaluationSuspended(); * * const changes = hfInstance.resumeEvaluation(); * ``` * * @category Batch */ isEvaluationSuspended() { return this._evaluationSuspended; } /** * Returns information whether it is possible to add named expression into a specific scope. * Checks against particular rules to ascertain that addNamedExpression can be called. * If returns `true`, doing [[addNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. * * @param {string} expressionName - a name of the expression to be added * @param {RawCellContent} expression - the expression * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // should return 'true' for this example, * // it is possible to add named expression to global scope * const isAddable = hfInstance.isItPossibleToAddNamedExpression('prettyName', '=Sheet1!$A$1+100'); * ``` * * @category Named Expressions */ isItPossibleToAddNamedExpression(expressionName, expression, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } try { this._crudOperations.ensureItIsPossibleToAddNamedExpression(expressionName, expression, scope); return true; } catch (e) { return false; } } /** * Adds a specified named expression. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {string} expressionName - a name of the expression to be added * @param {RawCellContent} expression - the expression * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * @param {NamedExpressionOptions?} options - additional metadata related to named expression * * @fires [[namedExpressionAdded]] always, unless [[batch]] mode is used * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NamedExpressionNameIsAlreadyTakenError]] when the named-expression name is not available. * @throws [[NamedExpressionNameIsInvalidError]] when the named-expression name is not valid * @throws [[NoRelativeAddressesAllowedError]] when the named-expression formula contains relative references * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add own expression, scope limited to 'Sheet1' (sheetId=0), the method should return a list of cells which values * // changed after the operation, their absolute addresses and new values * // for this example: * // [{ * // name: 'prettyName', * // newValue: 142, * // }] * const changes = hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * ``` * * @category Named Expressions */ addNamedExpression(expressionName, expression, scope, options) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } this._crudOperations.addNamedExpression(expressionName, expression, scope, options); const changes = this.recomputeIfDependencyGraphNeedsIt(); this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.NamedExpressionAdded, expressionName, changes); return changes; } /** * Gets specified named expression value. * Returns a [[CellValue]] or undefined if the given named expression does not exist. * * @param {string} expressionName - expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression, only 'Sheet1' (sheetId=0) considered as it is the scope * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 'Sheet1'); * * // returns the calculated value of a passed named expression, '142' for this example * const myFormula = hfInstance.getNamedExpressionValue('prettyName', 'Sheet1'); * ``` * * @category Named Expressions */ getNamedExpressionValue(expressionName, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } this.ensureEvaluationIsNotSuspended(); this._crudOperations.ensureScopeIdIsValid(scope); const namedExpression = this._namedExpressions.namedExpressionForScope(expressionName, scope); if (namedExpression) { return this._serialization.getCellValue(namedExpression.address); } else { return undefined; } } /** * Returns a normalized formula string for given named expression, or `undefined` for a named expression that does not exist or does not hold a formula. * * @param {string} expressionName - expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression in 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * * // returns a normalized formula string corresponding to the passed name from 'Sheet1' (sheetId=0), * // '=Sheet1!A1+100' for this example * const myFormula = hfInstance.getNamedExpressionFormula('prettyName', 0); * ``` * * @category Named Expressions */ getNamedExpressionFormula(expressionName, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } this._crudOperations.ensureScopeIdIsValid(scope); const namedExpression = this._namedExpressions.namedExpressionForScope(expressionName, scope); if (namedExpression === undefined) { return undefined; } else { return this._serialization.getCellFormula(namedExpression.address); } } /** * Returns a named expression, or `undefined` for a named expression that does not exist or does not hold a formula. * * @param {string} expressionName - expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression in 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * * // returns a named expression that corresponds to the passed name from 'Sheet1' (sheetId=0) * // for this example, returns: * // {name: 'prettyName', expression: '=Sheet1!$A$1+100', options: undefined, scope: 0} * const myFormula = hfInstance.getNamedExpression('prettyName', 0); * * // for a named expression that doesn't exist, returns 'undefined': * const myFormulaTwo = hfInstance.getNamedExpression('uglyName', 0); * ``` * * @category Named Expressions */ getNamedExpression(expressionName, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } const namedExpression = this._namedExpressions.namedExpressionForScope(expressionName, scope); if (namedExpression === undefined) { return undefined; } const expression = this._serialization.getCellFormula(namedExpression.address); return { name: expressionName, scope: scope, expression: expression, options: namedExpression.options }; } /** * Returns information whether it is possible to change named expression in a specific scope. * Checks against particular rules to ascertain that changeNamedExpression can be called. * If returns `true`, doing [[changeNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. * * @param {string} expressionName - an expression name, case-insensitive. * @param {RawCellContent} newExpression - a new expression * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); * * // should return 'true' for this example, * // it is possible to change named expression * const isAddable = hfInstance.isItPossibleToChangeNamedExpression('prettyName', '=Sheet1!$A$1+100'); * ``` * * @category Named Expressions */ isItPossibleToChangeNamedExpression(expressionName, newExpression, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } try { this._crudOperations.ensureItIsPossibleToChangeNamedExpression(expressionName, newExpression, scope); return true; } catch (e) { return false; } } /** * Changes a given named expression to a specified formula. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {string} expressionName - an expression name, case-insensitive. * @param {RawCellContent} newExpression - a new expression * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * @param {NamedExpressionOptions?} options - additional metadata related to named expression * * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NamedExpressionDoesNotExistError]] when the given expression does not exist. * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * @throws [[ArrayFormulasNotSupportedError]] when the named expression formula is an array formula * @throws [[NoRelativeAddressesAllowedError]] when the named expression formula contains relative references * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression, scope limited to 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * * // change the named expression * const changes = hfInstance.changeNamedExpression('prettyName', '=Sheet1!$A$1+200'); * ``` * * @category Named Expressions */ changeNamedExpression(expressionName, newExpression, scope, options) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } this._crudOperations.changeNamedExpressionExpression(expressionName, scope, newExpression, options); return this.recomputeIfDependencyGraphNeedsIt(); } /** * Returns information whether it is possible to remove named expression from a specific scope. * Checks against particular rules to ascertain that removeNamedExpression can be called. * If returns `true`, doing [[removeNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. * * @param {string} expressionName - an expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); * * // should return 'true' for this example, * // it is possible to change named expression * const isAddable = hfInstance.isItPossibleToRemoveNamedExpression('prettyName'); * ``` * * @category Named Expressions */ isItPossibleToRemoveNamedExpression(expressionName, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } try { this._crudOperations.isItPossibleToRemoveNamedExpression(expressionName, scope); return true; } catch (e) { return false; } } /** * Removes a named expression. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @param {string} expressionName - expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope * * @fires [[namedExpressionRemoved]] after the expression was removed * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NamedExpressionDoesNotExistError]] when the given expression does not exist. * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ]); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * * // remove the named expression * const changes = hfInstance.removeNamedExpression('prettyName', 0); * ``` * * @category Named Expressions */ removeNamedExpression(expressionName, scope) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(expressionName, 'string', 'expressionName'); if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } const removedNamedExpression = this._crudOperations.removeNamedExpression(expressionName, scope); if (removedNamedExpression) { const changes = this.recomputeIfDependencyGraphNeedsIt(); this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.NamedExpressionRemoved, removedNamedExpression.displayName, changes); return changes; } else { return []; // codecov note: this does not look possible - removeNamedExpression() will throw if the named expression cannot be found } } /** * Lists named expressions. * - If scope parameter is provided, returns an array of expression names defined for this scope. * - If scope parameter is undefined, returns an array of global expression names. * * @param {number?} scope - scope of the named expressions, `sheetId` for local scope or `undefined` for global scope * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ['50'], * ['60'], * ]); * * // add two named expressions and one scoped * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); * hfInstance.addNamedExpression('anotherPrettyName', '=Sheet1!$A$2+100'); * hfInstance.addNamedExpression('alsoPrettyName', '=Sheet1!$A$3+100', 0); * * // list the expressions, should return: ['prettyName', 'anotherPrettyName'] for this example * const listOfExpressions = hfInstance.listNamedExpressions(); * * // list the expressions, should return: ['alsoPrettyName'] for this example * const listOfExpressions = hfInstance.listNamedExpressions(0); * ``` * * @category Named Expressions */ listNamedExpressions(scope) { if (scope !== undefined) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(scope, 'number', 'scope'); } this._crudOperations.ensureScopeIdIsValid(scope); return this._namedExpressions.getAllNamedExpressionsNamesInScope(scope); } /** * Returns all named expressions serialized. * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ['50'], * ['60'], * ]); * * // add two named expressions and one scoped * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); * hfInstance.addNamedExpression('anotherPrettyName', '=Sheet1!$A$2+100'); * hfInstance.addNamedExpression('prettyName3', '=Sheet1!$A$3+100', 0); * * // get all expressions serialized * // should return: * // [ * // {name: 'prettyName', expression: '=Sheet1!$A$1+100', options: undefined, scope: undefined}, * // {name: 'anotherPrettyName', expression: '=Sheet1!$A$2+100', options: undefined, scope: undefined}, * // {name: 'alsoPrettyName', expression: '=Sheet1!$A$3+100', options: undefined, scope: 0} * // ] * const allExpressions = hfInstance.getAllNamedExpressionsSerialized(); * ``` * * @category Named Expressions */ getAllNamedExpressionsSerialized() { return this._serialization.getAllNamedExpressionsSerialized(); } /** * Parses and then unparses a formula. * Returns a normalized formula (e.g., restores the original capitalization of sheet names, function names, cell addresses, and named expressions). * * @param {string} formulaString - a formula in a proper format - it must start with "=" * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NotAFormulaError]] when the provided string is not a valid formula, i.e., does not start with "=" * * @example * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ['50'], * ]); * * // returns '=Sheet1!$A$1+10' * const normalizedFormula = hfInstance.normalizeFormula('=SHEET1!$A$1+10'); * * // returns '=3*$A$1' * const normalizedFormula = hfInstance.normalizeFormula('=3*$a$1'); * ``` * * @category Helpers */ normalizeFormula(formulaString) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(formulaString, 'string', 'formulaString'); const { ast, address } = this.extractTemporaryFormula(formulaString); if (ast === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.NotAFormulaError(); } return this._unparser.unparse(ast, address); } /** * Calculates fire-and-forget formula, returns the calculated value. * * @param {string} formulaString - A formula in a proper format, starting with `=`. * @param {number} sheetId - The ID of a sheet in context of which the formula gets evaluated. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type arguments is of wrong type. * @throws [[NotAFormulaError]] when the provided string is not a valid formula (i.e., doesn't start with `=`). * @throws [[NoSheetWithIdError]] when the provided `sheetID` doesn't exist. * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ * Sheet1: [['58']], * Sheet2: [['1', '2', '3'], ['4', '5', '6']] * }); * * // returns the calculated formula's value * // for this example, returns `68` * const calculatedFormula = hfInstance.calculateFormula('=A1+10', 0); * * // for this example, returns [['11', '12', '13'], ['14', '15', '16']] * const calculatedFormula = hfInstance.calculateFormula('=A1:B3+10', 1); * ``` * * @category Helpers */ calculateFormula(formulaString, sheetId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(formulaString, 'string', 'formulaString'); (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(sheetId, 'number', 'sheetId'); this._crudOperations.ensureScopeIdIsValid(sheetId); const { ast, address, dependencies } = this.extractTemporaryFormula(formulaString, sheetId); if (ast === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.NotAFormulaError(); } const internalCellValue = this.evaluator.runAndForget(ast, address, dependencies); return this._exporter.exportScalarOrRange(internalCellValue); } /** * Return a list of named expressions used by a formula. * * @param {string} formulaString - A formula in a proper format, starting with `=`. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type arguments is of wrong type. * @throws [[NotAFormulaError]] when the provided string is not a valid formula (i.e., doesn't start with `=`). * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // returns a list of named expressions used by a formula * // for this example, returns ['foo', 'bar'] * const namedExpressions = hfInstance.getNamedExpressionsFromFormula('=foo+bar*2'); * ``` * * @category Helpers */ getNamedExpressionsFromFormula(formulaString) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(formulaString, 'string', 'formulaString'); const { ast, dependencies } = this.extractTemporaryFormula(formulaString); if (ast === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.NotAFormulaError(); } const namedExpressionDependencies = dependencies.filter(dep => dep instanceof _parser__WEBPACK_IMPORTED_MODULE_13__.NamedExpressionDependency).map(namedExpr => namedExpr.name); const uniqueNamedExpressionDependencies = [...new Set(namedExpressionDependencies)]; return uniqueNamedExpressionDependencies; } /** * Validates the formula. * If the provided string starts with "=" and is a parsable formula, the method returns `true`. * The validation is purely grammatical: the method doesn't verify if the formula can be calculated or not. * * @param {string} formulaString - a formula in a proper format - it must start with "=" * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * // checks if the given string is a valid formula, should return 'true' for this example * const isFormula = hfInstance.validateFormula('=SUM(1, 2)'); * ``` * * @category Helpers */ validateFormula(formulaString) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(formulaString, 'string', 'formulaString'); const { ast } = this.extractTemporaryFormula(formulaString); return ast !== undefined; } /** * Returns translated names of all functions registered in this instance of HyperFormula * according to the language set in the configuration * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // return translated names of all functions, assign to a variable * const allNames = hfInstance.getRegisteredFunctionNames(); * ``` * * @category Custom Functions */ getRegisteredFunctionNames() { const language = HyperFormula.getLanguage(this._config.language); return language.getFunctionTranslations(this._functionRegistry.getRegisteredFunctionIds()); } /** * Returns class of a plugin used by function with given id * * @param {string} functionId - id of a function, e.g., 'SUMIF' * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * * const hfInstance = HyperFormula.buildEmpty(); * * // register a plugin * HyperFormula.registerFunctionPlugin(MyExamplePlugin); * * // get the plugin * const myPlugin = hfInstance.getFunctionPlugin('EXAMPLE'); * ``` * * @category Custom Functions */ getFunctionPlugin(functionId) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(functionId, 'string', 'functionId'); return this._functionRegistry.getFunctionPlugin(functionId); } /** * Returns classes of all plugins registered in this instance of HyperFormula * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // return classes of all plugins registered, assign to a variable * const allNames = hfInstance.getAllFunctionPlugins(); * ``` * * @category Custom Functions */ getAllFunctionPlugins() { return this._functionRegistry.getPlugins(); } /** * Interprets number as a date + time. * * @param {number} inputNumber - number of days since nullDate, should be non-negative, fractions are interpreted as hours/minutes/seconds. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // pass the number of days since nullDate * // the method should return formatted date and time, for this example: * // {year: 2020, month: 1, day: 15, hours: 2, minutes: 24, seconds: 0} * const dateTimeFromNumber = hfInstance.numberToDateTime(43845.1); * * ``` * * @category Helpers */ numberToDateTime(inputNumber) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(inputNumber, 'number', 'val'); return this._evaluator.interpreter.dateTimeHelper.numberToSimpleDateTime(inputNumber); } /** * Interprets number as a date. * * @param {number} inputNumber - number of days since nullDate, should be non-negative, fractions are ignored. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // pass the number of days since nullDate * // the method should return formatted date, for this example: * // {year: 2020, month: 1, day: 15} * const dateFromNumber = hfInstance.numberToDate(43845); * ``` * * @category Helpers */ numberToDate(inputNumber) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(inputNumber, 'number', 'val'); return this._evaluator.interpreter.dateTimeHelper.numberToSimpleDate(inputNumber); } /** * Interprets number as a time (hours/minutes/seconds). * * @param {number} inputNumber - time in 24h units. * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // pass a number to be interpreted as a time * // should return {hours: 26, minutes: 24} for this example * const timeFromNumber = hfInstance.numberToTime(1.1); * ``` * * @category Helpers */ numberToTime(inputNumber) { (0,_ArgumentSanitization__WEBPACK_IMPORTED_MODULE_1__.validateArgToType)(inputNumber, 'number', 'val'); return (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_6__.numberToSimpleTime)(inputNumber); } /** * Subscribes to an event. * For the list of all available events, see [[Listeners]]. * * @param {Event} event the name of the event to subscribe to * @param {Listener} listener to be called when event is emitted * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // subscribe to a 'sheetAdded', pass a simple handler * hfInstance.on('sheetAdded', ( ) => { console.log('foo') }); * * // add a sheet to trigger an event, * // console should print 'foo' after each time sheet is added in this example * hfInstance.addSheet('FooBar'); * ``` * * @category Events */ on(event, listener) { this._emitter.on(event, listener); } /** * Subscribes to an event once. * For the list of all available events, see [[Listeners]]. * * @param {Event} event the name of the event to subscribe to * @param {Listener} listener to be called when event is emitted * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // subscribe to a 'sheetAdded', pass a simple handler * hfInstance.once('sheetAdded', ( ) => { console.log('foo') }); * * // call addSheet twice, * // console should print 'foo' only once when the sheet is added in this example * hfInstance.addSheet('FooBar'); * hfInstance.addSheet('FooBaz'); * ``` * * @category Events */ once(event, listener) { this._emitter.once(event, listener); } /** * Unsubscribes from an event or from all events. * For the list of all available events, see [[Listeners]]. * * @param {Event} event the name of the event to subscribe to * @param {Listener} listener to be called when event is emitted * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); * * // define a simple function to be called upon emitting an event * const handler = ( ) => { console.log('baz') } * * // subscribe to a 'sheetAdded', pass the handler * hfInstance.on('sheetAdded', handler); * * // add a sheet to trigger an event, * // console should print 'baz' each time a sheet is added * hfInstance.addSheet('FooBar'); * * // unsubscribe from a 'sheetAdded' * hfInstance.off('sheetAdded', handler); * * // add a sheet, the console should not print anything * hfInstance.addSheet('FooBaz'); * ``` * * @category Events */ off(event, listener) { this._emitter.off(event, listener); } /** * Destroys instance of HyperFormula. * * @example * ```js * // destroys the instance * hfInstance.destroy(); * ``` * * @category Instance */ destroy() { (0,_Destroy__WEBPACK_IMPORTED_MODULE_7__.objectDestroy)(this); } ensureEvaluationIsNotSuspended() { if (this._evaluationSuspended) { throw new _errors__WEBPACK_IMPORTED_MODULE_9__.EvaluationSuspendedError(); } } extractTemporaryFormula(formulaString, sheetId = 1) { const parsedCellContent = this._cellContentParser.parse(formulaString); const address = { sheet: sheetId, col: 0, row: 0 }; if (!(parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_4__.CellContent.Formula)) { return { address, dependencies: [] }; } const { ast, errors, dependencies } = this._parser.parse(parsedCellContent.formula, address); if (errors.length > 0) { return { address, dependencies: [] }; } return { ast, address, dependencies }; } /** * Rebuilds the engine with new configuration. */ rebuildWithConfig(newParams) { const newConfig = this._config.mergeConfig(newParams); const configNewLanguage = this._config.mergeConfig({ language: newParams.language }); const serializedSheets = this._serialization.withNewConfig(configNewLanguage, this._namedExpressions).getAllSheetsSerialized(); const serializedNamedExpressions = this._serialization.getAllNamedExpressionsSerialized(); const newEngine = _BuildEngineFactory__WEBPACK_IMPORTED_MODULE_2__.BuildEngineFactory.rebuildWithConfig(newConfig, serializedSheets, serializedNamedExpressions, this._stats); this._config = newEngine.config; this._stats = newEngine.stats; this._dependencyGraph = newEngine.dependencyGraph; this._columnSearch = newEngine.columnSearch; this._parser = newEngine.parser; this._unparser = newEngine.unparser; this._cellContentParser = newEngine.cellContentParser; this._evaluator = newEngine.evaluator; this._lazilyTransformingAstService = newEngine.lazilyTransformingAstService; this._crudOperations = newEngine.crudOperations; this._exporter = newEngine.exporter; this._namedExpressions = newEngine.namedExpressions; this._serialization = newEngine.serialization; this._functionRegistry = newEngine.functionRegistry; } /** * Runs a recomputation starting from recently changed vertices. * * Returns [an array of cells whose values changed as a result of this operation](/guide/basic-operations.md#changes-array). * * Note that this method may trigger dependency graph recalculation. * * @fires [[valuesUpdated]] if recalculation was triggered by this change */ recomputeIfDependencyGraphNeedsIt() { if (!this._evaluationSuspended) { const changes = this._crudOperations.getAndClearContentChanges(); const verticesToRecomputeFrom = this.dependencyGraph.verticesToRecompute(); this.dependencyGraph.clearDirtyVertices(); if (verticesToRecomputeFrom.length > 0) { changes.addAll(this.evaluator.partialRun(verticesToRecomputeFrom)); } const exportedChanges = changes.exportChanges(this._exporter); if (!changes.isEmpty()) { this._emitter.emit(_Emitter__WEBPACK_IMPORTED_MODULE_8__.Events.ValuesUpdated, exportedChanges); } return exportedChanges; } else { return []; } } } /** * Version of the HyperFormula. * * @category Static Properties */ HyperFormula.version = "2.7.1"; /** * Latest build date. * * @category Static Properties */ HyperFormula.buildDate = "18/07/2024 11:23:17"; /** * A release date. * * @category Static Properties */ HyperFormula.releaseDate = "18/07/2024"; /** * When using the UMD build, this property contains all available languages to use with the [registerLanguage](#registerlanguage) method. * * For more information, see the [Localizing functions](/guide/localizing-functions.md) guide. * * @category Static Properties */ HyperFormula.languages = {}; HyperFormula.registeredLanguages = new Map(); /***/ }), /* 111 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ BuildEngineFactory: () => (/* binding */ BuildEngineFactory) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _CellContentParser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(112); /* harmony import */ var _ClipboardOperations__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(113); /* harmony import */ var _Config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(101); /* harmony import */ var _CrudOperations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(114); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(104); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(77); /* harmony import */ var _Evaluator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(127); /* harmony import */ var _Exporter__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(128); /* harmony import */ var _GraphBuilder__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(129); /* harmony import */ var _i18n__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(88); /* harmony import */ var _interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(98); /* harmony import */ var _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(130); /* harmony import */ var _interpreter_Interpreter__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(132); /* harmony import */ var _LazilyTransformingAstService__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(134); /* harmony import */ var _Lookup_SearchStrategy__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(136); /* harmony import */ var _NamedExpressions__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(115); /* harmony import */ var _NumberLiteralHelper__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(141); /* harmony import */ var _Operations__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(116); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(7); /* harmony import */ var _Serialization__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(142); /* harmony import */ var _Sheet__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(125); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(72); /* harmony import */ var _UndoRedo__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(126); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class BuildEngineFactory { static buildFromSheets(sheets, configInput = {}, namedExpressions = []) { const config = new _Config__WEBPACK_IMPORTED_MODULE_3__.Config(configInput); return this.buildEngine(config, sheets, namedExpressions); } static buildFromSheet(sheet, configInput = {}, namedExpressions = []) { const config = new _Config__WEBPACK_IMPORTED_MODULE_3__.Config(configInput); const newsheetprefix = config.translationPackage.getUITranslation(_i18n__WEBPACK_IMPORTED_MODULE_11__.UIElement.NEW_SHEET_PREFIX) + '1'; return this.buildEngine(config, { [newsheetprefix]: sheet }, namedExpressions); } static buildEmpty(configInput = {}, namedExpressions = []) { return this.buildEngine(new _Config__WEBPACK_IMPORTED_MODULE_3__.Config(configInput), {}, namedExpressions); } static rebuildWithConfig(config, sheets, namedExpressions, stats) { return this.buildEngine(config, sheets, namedExpressions, stats); } static buildEngine(config, sheets = {}, inputNamedExpressions = [], stats = config.useStats ? new _statistics__WEBPACK_IMPORTED_MODULE_23__.Statistics() : new _statistics__WEBPACK_IMPORTED_MODULE_23__.EmptyStatistics()) { stats.start(_statistics__WEBPACK_IMPORTED_MODULE_23__.StatType.BUILD_ENGINE_TOTAL); const namedExpressions = new _NamedExpressions__WEBPACK_IMPORTED_MODULE_17__.NamedExpressions(); const functionRegistry = new _interpreter_FunctionRegistry__WEBPACK_IMPORTED_MODULE_13__.FunctionRegistry(config); const lazilyTransformingAstService = new _LazilyTransformingAstService__WEBPACK_IMPORTED_MODULE_15__.LazilyTransformingAstService(stats); const dependencyGraph = _DependencyGraph__WEBPACK_IMPORTED_MODULE_6__.DependencyGraph.buildEmpty(lazilyTransformingAstService, config, functionRegistry, namedExpressions, stats); const columnSearch = (0,_Lookup_SearchStrategy__WEBPACK_IMPORTED_MODULE_16__.buildColumnSearchStrategy)(dependencyGraph, config, stats); const sheetMapping = dependencyGraph.sheetMapping; const addressMapping = dependencyGraph.addressMapping; for (const sheetName in sheets) { if (Object.prototype.hasOwnProperty.call(sheets, sheetName)) { const sheet = sheets[sheetName]; (0,_Sheet__WEBPACK_IMPORTED_MODULE_22__.validateAsSheet)(sheet); const boundaries = (0,_Sheet__WEBPACK_IMPORTED_MODULE_22__.findBoundaries)(sheet); if (boundaries.height > config.maxRows || boundaries.width > config.maxColumns) { throw new _errors__WEBPACK_IMPORTED_MODULE_7__.SheetSizeLimitExceededError(); } const sheetId = sheetMapping.addSheet(sheetName); addressMapping.autoAddSheet(sheetId, boundaries); } } const parser = new _parser__WEBPACK_IMPORTED_MODULE_20__.ParserWithCaching(config, functionRegistry, sheetMapping.get); lazilyTransformingAstService.parser = parser; const unparser = new _parser__WEBPACK_IMPORTED_MODULE_20__.Unparser(config, (0,_parser__WEBPACK_IMPORTED_MODULE_20__.buildLexerConfig)(config), sheetMapping.fetchDisplayName, namedExpressions); const dateTimeHelper = new _DateTimeHelper__WEBPACK_IMPORTED_MODULE_5__.DateTimeHelper(config); const numberLiteralHelper = new _NumberLiteralHelper__WEBPACK_IMPORTED_MODULE_18__.NumberLiteralHelper(config); const arithmeticHelper = new _interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_12__.ArithmeticHelper(config, dateTimeHelper, numberLiteralHelper); const cellContentParser = new _CellContentParser__WEBPACK_IMPORTED_MODULE_1__.CellContentParser(config, dateTimeHelper, numberLiteralHelper); const arraySizePredictor = new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySizePredictor(config, functionRegistry); const operations = new _Operations__WEBPACK_IMPORTED_MODULE_19__.Operations(config, dependencyGraph, columnSearch, cellContentParser, parser, stats, lazilyTransformingAstService, namedExpressions, arraySizePredictor); const undoRedo = new _UndoRedo__WEBPACK_IMPORTED_MODULE_24__.UndoRedo(config, operations); lazilyTransformingAstService.undoRedo = undoRedo; const clipboardOperations = new _ClipboardOperations__WEBPACK_IMPORTED_MODULE_2__.ClipboardOperations(config, dependencyGraph, operations); const crudOperations = new _CrudOperations__WEBPACK_IMPORTED_MODULE_4__.CrudOperations(config, operations, undoRedo, clipboardOperations, dependencyGraph, columnSearch, parser, cellContentParser, lazilyTransformingAstService, namedExpressions); inputNamedExpressions.forEach(entry => { crudOperations.ensureItIsPossibleToAddNamedExpression(entry.name, entry.expression, entry.scope); crudOperations.operations.addNamedExpression(entry.name, entry.expression, entry.scope, entry.options); }); const exporter = new _Exporter__WEBPACK_IMPORTED_MODULE_9__.Exporter(config, namedExpressions, sheetMapping.fetchDisplayName, lazilyTransformingAstService); const serialization = new _Serialization__WEBPACK_IMPORTED_MODULE_21__.Serialization(dependencyGraph, unparser, exporter); const interpreter = new _interpreter_Interpreter__WEBPACK_IMPORTED_MODULE_14__.Interpreter(config, dependencyGraph, columnSearch, stats, arithmeticHelper, functionRegistry, namedExpressions, serialization, arraySizePredictor, dateTimeHelper); stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_23__.StatType.GRAPH_BUILD, () => { const graphBuilder = new _GraphBuilder__WEBPACK_IMPORTED_MODULE_10__.GraphBuilder(dependencyGraph, columnSearch, parser, cellContentParser, stats, arraySizePredictor); graphBuilder.buildGraph(sheets, stats); }); const evaluator = new _Evaluator__WEBPACK_IMPORTED_MODULE_8__.Evaluator(config, stats, interpreter, lazilyTransformingAstService, dependencyGraph, columnSearch); evaluator.run(); stats.end(_statistics__WEBPACK_IMPORTED_MODULE_23__.StatType.BUILD_ENGINE_TOTAL); return { config, stats, dependencyGraph, columnSearch, parser, unparser, cellContentParser, evaluator, lazilyTransformingAstService, crudOperations, exporter, namedExpressions, serialization, functionRegistry }; } } /***/ }), /* 112 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CellContent: () => (/* binding */ CellContent), /* harmony export */ CellContentParser: () => (/* binding */ CellContentParser), /* harmony export */ isBoolean: () => (/* binding */ isBoolean), /* harmony export */ isError: () => (/* binding */ isError), /* harmony export */ isFormula: () => (/* binding */ isFormula) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(104); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(77); /* harmony import */ var _interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(98); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var CellContent; (function (CellContent) { class Number { constructor(value) { this.value = value; this.value = (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.cloneNumber)(this.value, (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.fixNegativeZero)((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(this.value))); } } CellContent.Number = Number; class String { constructor(value) { this.value = value; } } CellContent.String = String; class Boolean { constructor(value) { this.value = value; } } CellContent.Boolean = Boolean; class Empty { static getSingletonInstance() { if (!Empty.instance) { Empty.instance = new Empty(); } return Empty.instance; } } CellContent.Empty = Empty; class Formula { constructor(formula) { this.formula = formula; } } CellContent.Formula = Formula; class Error { constructor(errorType, message) { this.value = new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(errorType, message); } } CellContent.Error = Error; })(CellContent || (CellContent = {})); /** * Checks whether string looks like formula or not. * * @param text - formula */ function isFormula(text) { return text.startsWith('='); } function isBoolean(text) { const tl = text.toLowerCase(); return tl === 'true' || tl === 'false'; } function isError(text, errorMapping) { const upperCased = text.toUpperCase(); const errorRegex = /#[A-Za-z0-9\/]+[?!]?/; return errorRegex.test(upperCased) && Object.prototype.hasOwnProperty.call(errorMapping, upperCased); } class CellContentParser { constructor(config, dateHelper, numberLiteralsHelper) { this.config = config; this.dateHelper = dateHelper; this.numberLiteralsHelper = numberLiteralsHelper; } parse(content) { if (content === undefined || content === null) { return CellContent.Empty.getSingletonInstance(); } else if (typeof content === 'number') { if ((0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.isNumberOverflow)(content)) { return new CellContent.Error(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge); } else { return new CellContent.Number(content); } } else if (typeof content === 'boolean') { return new CellContent.Boolean(content); } else if (content instanceof Date) { const dateVal = this.dateHelper.dateToNumber({ day: content.getDate(), month: content.getMonth() + 1, year: content.getFullYear() }); const timeVal = (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.timeToNumber)({ hours: content.getHours(), minutes: content.getMinutes(), seconds: content.getSeconds() + content.getMilliseconds() / 1000 }); const val = dateVal + timeVal; if (val < 0) { return new CellContent.Error(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.DateBounds); } if (val % 1 === 0) { return new CellContent.Number(new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.DateNumber(val, 'Date()')); } else if (val < 1) { return new CellContent.Number(new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.TimeNumber(val, 'Date()')); } else { return new CellContent.Number(new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.DateTimeNumber(val, 'Date()')); } } else if (typeof content === 'string') { if (isBoolean(content)) { return new CellContent.Boolean(content.toLowerCase() === 'true'); } else if (isFormula(content)) { return new CellContent.Formula(content); } else if (isError(content, this.config.errorMapping)) { return new CellContent.Error(this.config.errorMapping[content.toUpperCase()]); } else { let trimmedContent = content.trim(); let mode = 0; let currency; if (trimmedContent.endsWith('%')) { mode = 1; trimmedContent = trimmedContent.slice(0, trimmedContent.length - 1); } else { const res = this.currencyMatcher(trimmedContent); if (res !== undefined) { mode = 2; [currency, trimmedContent] = res; } } const val = this.numberLiteralsHelper.numericStringToMaybeNumber(trimmedContent); if (val !== undefined) { let parseAsNum; if (mode === 1) { parseAsNum = new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.PercentNumber(val / 100); } else if (mode === 2) { parseAsNum = new _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.CurrencyNumber(val, currency); } else { parseAsNum = val; } return new CellContent.Number(parseAsNum); } const parsedDateNumber = this.dateHelper.dateStringToDateNumber(trimmedContent); if (parsedDateNumber !== undefined) { return new CellContent.Number(parsedDateNumber); } else { return new CellContent.String(content.startsWith('\'') ? content.slice(1) : content); } } } else { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.UnableToParseError(content); } } currencyMatcher(token) { for (const currency of this.config.currencySymbol) { if (token.startsWith(currency)) { return [currency, token.slice(currency.length)]; } if (token.endsWith(currency)) { return [currency, token.slice(0, token.length - currency.length)]; } } return undefined; } } /***/ }), /* 113 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ClipboardCellType: () => (/* binding */ ClipboardCellType), /* harmony export */ ClipboardOperations: () => (/* binding */ ClipboardOperations) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(77); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var ClipboardOperationType; (function (ClipboardOperationType) { ClipboardOperationType[ClipboardOperationType["COPY"] = 0] = "COPY"; ClipboardOperationType[ClipboardOperationType["CUT"] = 1] = "CUT"; })(ClipboardOperationType || (ClipboardOperationType = {})); var ClipboardCellType; (function (ClipboardCellType) { ClipboardCellType[ClipboardCellType["VALUE"] = 0] = "VALUE"; ClipboardCellType[ClipboardCellType["EMPTY"] = 1] = "EMPTY"; ClipboardCellType[ClipboardCellType["FORMULA"] = 2] = "FORMULA"; ClipboardCellType[ClipboardCellType["PARSING_ERROR"] = 3] = "PARSING_ERROR"; })(ClipboardCellType || (ClipboardCellType = {})); class Clipboard { constructor(sourceLeftCorner, width, height, type, content) { this.sourceLeftCorner = sourceLeftCorner; this.width = width; this.height = height; this.type = type; this.content = content; } *getContent(leftCorner) { if (this.content === undefined) { return; } else { for (let y = 0; y < this.height; ++y) { for (let x = 0; x < this.width; ++x) { yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + x, leftCorner.row + y), this.content[y][x]]; } } } } } class ClipboardOperations { constructor(config, dependencyGraph, operations) { this.dependencyGraph = dependencyGraph; this.operations = operations; this.maxRows = config.maxRows; this.maxColumns = config.maxColumns; } cut(leftCorner, width, height) { this.clipboard = new Clipboard(leftCorner, width, height, ClipboardOperationType.CUT); } copy(leftCorner, width, height) { const content = []; for (let y = 0; y < height; ++y) { content[y] = []; for (let x = 0; x < width; ++x) { const clipboardCell = this.operations.getClipboardCell((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + x, leftCorner.row + y)); content[y].push(clipboardCell); } } this.clipboard = new Clipboard(leftCorner, width, height, ClipboardOperationType.COPY, content); } abortCut() { if (this.clipboard && this.clipboard.type === ClipboardOperationType.CUT) { this.clear(); } } clear() { this.clipboard = undefined; } ensureItIsPossibleToCopyPaste(destinationLeftCorner) { if (this.clipboard === undefined) { return; } if ((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(destinationLeftCorner) || !this.dependencyGraph.sheetMapping.hasSheetWithId(destinationLeftCorner.sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_2__.InvalidArgumentsError('a valid target address.'); } const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(destinationLeftCorner, this.clipboard.width, this.clipboard.height); if (targetRange.exceedsSheetSizeLimits(this.maxColumns, this.maxRows)) { throw new _errors__WEBPACK_IMPORTED_MODULE_2__.SheetSizeLimitExceededError(); } if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(targetRange)) { throw new Error('It is not possible to paste onto an array'); } } isCutClipboard() { return this.clipboard !== undefined && this.clipboard.type === ClipboardOperationType.CUT; } isCopyClipboard() { return this.clipboard !== undefined && this.clipboard.type === ClipboardOperationType.COPY; } } /***/ }), /* 114 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CrudOperations: () => (/* binding */ CrudOperations) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _CellContentParser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(112); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(77); /* harmony import */ var _NamedExpressions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(115); /* harmony import */ var _Operations__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(116); /* harmony import */ var _Sheet__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(125); /* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(71); /* harmony import */ var _UndoRedo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(126); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class CrudOperations { constructor(config, operations, undoRedo, clipboardOperations, dependencyGraph, columnSearch, parser, cellContentParser, lazilyTransformingAstService, namedExpressions) { this.operations = operations; this.undoRedo = undoRedo; this.clipboardOperations = clipboardOperations; this.dependencyGraph = dependencyGraph; this.columnSearch = columnSearch; this.parser = parser; this.cellContentParser = cellContentParser; this.lazilyTransformingAstService = lazilyTransformingAstService; this.namedExpressions = namedExpressions; this.maxRows = config.maxRows; this.maxColumns = config.maxColumns; } get sheetMapping() { return this.dependencyGraph.sheetMapping; } addRows(sheet, ...indexes) { const addRowsCommand = new _Operations__WEBPACK_IMPORTED_MODULE_5__.AddRowsCommand(sheet, indexes); this.ensureItIsPossibleToAddRows(sheet, ...indexes); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); this.operations.addRows(addRowsCommand); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.AddRowsUndoEntry(addRowsCommand)); } removeRows(sheet, ...indexes) { const removeRowsCommand = new _Operations__WEBPACK_IMPORTED_MODULE_5__.RemoveRowsCommand(sheet, indexes); this.ensureItIsPossibleToRemoveRows(sheet, ...indexes); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const rowsRemovals = this.operations.removeRows(removeRowsCommand); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.RemoveRowsUndoEntry(removeRowsCommand, rowsRemovals)); } addColumns(sheet, ...indexes) { const addColumnsCommand = new _Operations__WEBPACK_IMPORTED_MODULE_5__.AddColumnsCommand(sheet, indexes); this.ensureItIsPossibleToAddColumns(sheet, ...indexes); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); this.operations.addColumns(addColumnsCommand); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.AddColumnsUndoEntry(addColumnsCommand)); } removeColumns(sheet, ...indexes) { const removeColumnsCommand = new _Operations__WEBPACK_IMPORTED_MODULE_5__.RemoveColumnsCommand(sheet, indexes); this.ensureItIsPossibleToRemoveColumns(sheet, ...indexes); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const columnsRemovals = this.operations.removeColumns(removeColumnsCommand); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.RemoveColumnsUndoEntry(removeColumnsCommand, columnsRemovals)); } moveCells(sourceLeftCorner, width, height, destinationLeftCorner) { this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const { version, overwrittenCellsData, addedGlobalNamedExpressions } = this.operations.moveCells(sourceLeftCorner, width, height, destinationLeftCorner); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.MoveCellsUndoEntry(sourceLeftCorner, width, height, destinationLeftCorner, overwrittenCellsData, addedGlobalNamedExpressions, version)); } moveRows(sheet, startRow, numberOfRows, targetRow) { this.ensureItIsPossibleToMoveRows(sheet, startRow, numberOfRows, targetRow); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const version = this.operations.moveRows(sheet, startRow, numberOfRows, targetRow); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.MoveRowsUndoEntry(sheet, startRow, numberOfRows, targetRow, version)); } moveColumns(sheet, startColumn, numberOfColumns, targetColumn) { this.ensureItIsPossibleToMoveColumns(sheet, startColumn, numberOfColumns, targetColumn); this.undoRedo.clearRedoStack(); const version = this.operations.moveColumns(sheet, startColumn, numberOfColumns, targetColumn); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.MoveColumnsUndoEntry(sheet, startColumn, numberOfColumns, targetColumn, version)); } cut(sourceLeftCorner, width, height) { this.clipboardOperations.cut(sourceLeftCorner, width, height); } ensureItIsPossibleToCopy(sourceLeftCorner, width, height) { if (!isPositiveInteger(width)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('width to be positive integer.'); } if (!isPositiveInteger(height)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('height to be positive integer.'); } } copy(sourceLeftCorner, width, height) { this.ensureItIsPossibleToCopy(sourceLeftCorner, width, height); this.clipboardOperations.copy(sourceLeftCorner, width, height); } paste(targetLeftCorner) { const clipboard = this.clipboardOperations.clipboard; if (clipboard === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NothingToPasteError(); } else if (this.clipboardOperations.isCutClipboard()) { this.moveCells(clipboard.sourceLeftCorner, clipboard.width, clipboard.height, targetLeftCorner); } else if (this.clipboardOperations.isCopyClipboard()) { this.clipboardOperations.ensureItIsPossibleToCopyPaste(targetLeftCorner); const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(targetLeftCorner, clipboard.width, clipboard.height); const oldContent = this.operations.getRangeClipboardCells(targetRange); this.undoRedo.clearRedoStack(); const addedGlobalNamedExpressions = this.operations.restoreClipboardCells(clipboard.sourceLeftCorner.sheet, clipboard.getContent(targetLeftCorner)); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.PasteUndoEntry(targetLeftCorner, oldContent, clipboard.content, addedGlobalNamedExpressions)); } } beginUndoRedoBatchMode() { this.undoRedo.beginBatchMode(); } commitUndoRedoBatchMode() { this.undoRedo.commitBatchMode(); } isClipboardEmpty() { return this.clipboardOperations.clipboard === undefined; } clearClipboard() { this.clipboardOperations.clear(); } addSheet(name) { if (name !== undefined) { this.ensureItIsPossibleToAddSheet(name); } this.undoRedo.clearRedoStack(); const addedSheetName = this.operations.addSheet(name); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.AddSheetUndoEntry(addedSheetName)); return addedSheetName; } removeSheet(sheetId) { this.ensureScopeIdIsValid(sheetId); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const originalName = this.sheetMapping.fetchDisplayName(sheetId); const oldSheetContent = this.operations.getSheetClipboardCells(sheetId); const { version, scopedNamedExpressions } = this.operations.removeSheet(sheetId); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.RemoveSheetUndoEntry(originalName, sheetId, oldSheetContent, scopedNamedExpressions, version)); } renameSheet(sheetId, newName) { this.ensureItIsPossibleToRenameSheet(sheetId, newName); const oldName = this.operations.renameSheet(sheetId, newName); if (oldName !== undefined) { this.undoRedo.clearRedoStack(); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.RenameSheetUndoEntry(sheetId, oldName, newName)); } return oldName; } clearSheet(sheetId) { this.ensureScopeIdIsValid(sheetId); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const oldSheetContent = this.operations.getSheetClipboardCells(sheetId); this.operations.clearSheet(sheetId); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.ClearSheetUndoEntry(sheetId, oldSheetContent)); } setCellContents(topLeftCornerAddress, cellContents) { if (!(cellContents instanceof Array)) { cellContents = [[cellContents]]; } else { for (let i = 0; i < cellContents.length; i++) { if (!(cellContents[i] instanceof Array)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('an array of arrays or a raw cell value.'); } } } this.ensureItIsPossibleToChangeCellContents(topLeftCornerAddress, cellContents); this.undoRedo.clearRedoStack(); const oldContents = []; for (let i = 0; i < cellContents.length; i++) { for (let j = 0; j < cellContents[i].length; j++) { const address = { sheet: topLeftCornerAddress.sheet, row: topLeftCornerAddress.row + i, col: topLeftCornerAddress.col + j }; const newContent = cellContents[i][j]; this.clipboardOperations.abortCut(); const oldContent = this.operations.setCellContent(address, newContent); oldContents.push({ address, newContent, oldContent }); } } this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.SetCellContentsUndoEntry(oldContents)); } setSheetContent(sheetId, values) { this.ensureScopeIdIsValid(sheetId); this.ensureItIsPossibleToChangeSheetContents(sheetId, values); (0,_Sheet__WEBPACK_IMPORTED_MODULE_6__.validateAsSheet)(values); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const oldSheetContent = this.operations.getSheetClipboardCells(sheetId); this.operations.setSheetContent(sheetId, values); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.SetSheetContentUndoEntry(sheetId, oldSheetContent, values)); } setRowOrder(sheetId, rowMapping) { this.validateSwapRowIndexes(sheetId, rowMapping); this.testRowOrderForArrays(sheetId, rowMapping); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const oldContent = this.operations.setRowOrder(sheetId, rowMapping); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.SetRowOrderUndoEntry(sheetId, rowMapping, oldContent)); } validateSwapRowIndexes(sheetId, rowMapping) { if (!this.sheetMapping.hasSheetWithId(sheetId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheetId); } this.validateRowOrColumnMapping(sheetId, rowMapping, 'row'); } testColumnOrderForArrays(sheetId, columnMapping) { for (const [source, target] of columnMapping) { if (source !== target) { const rowRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom({ sheet: sheetId, col: source, row: 0 }, 1, Infinity); if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(rowRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SourceLocationHasArrayError(); } } } } setColumnOrder(sheetId, columnMapping) { this.validateSwapColumnIndexes(sheetId, columnMapping); this.testColumnOrderForArrays(sheetId, columnMapping); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); const oldContent = this.operations.setColumnOrder(sheetId, columnMapping); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.SetColumnOrderUndoEntry(sheetId, columnMapping, oldContent)); } validateSwapColumnIndexes(sheetId, columnMapping) { if (!this.sheetMapping.hasSheetWithId(sheetId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheetId); } this.validateRowOrColumnMapping(sheetId, columnMapping, 'column'); } testRowOrderForArrays(sheetId, rowMapping) { for (const [source, target] of rowMapping) { if (source !== target) { const rowRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom({ sheet: sheetId, col: 0, row: source }, Infinity, 1); if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(rowRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SourceLocationHasArrayError(); } } } } mappingFromOrder(sheetId, newOrder, rowOrColumn) { if (!this.sheetMapping.hasSheetWithId(sheetId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheetId); } const limit = rowOrColumn === 'row' ? this.dependencyGraph.getSheetHeight(sheetId) : this.dependencyGraph.getSheetWidth(sheetId); if (newOrder.length !== limit) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError(`number of ${rowOrColumn}s provided to be sheet ${rowOrColumn === 'row' ? 'height' : 'width'}.`); } const ret = []; for (let i = 0; i < limit; i++) { if (newOrder[i] !== i) { ret.push([i, newOrder[i]]); } } return ret; } undo() { if (this.undoRedo.isUndoStackEmpty()) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoOperationToUndoError(); } this.clipboardOperations.abortCut(); this.undoRedo.undo(); } redo() { if (this.undoRedo.isRedoStackEmpty()) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoOperationToRedoError(); } this.clipboardOperations.abortCut(); this.undoRedo.redo(); } addNamedExpression(expressionName, expression, sheetId, options) { this.ensureItIsPossibleToAddNamedExpression(expressionName, expression, sheetId); this.operations.addNamedExpression(expressionName, expression, sheetId, options); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.AddNamedExpressionUndoEntry(expressionName, expression, sheetId, options)); } changeNamedExpressionExpression(expressionName, sheetId, newExpression, options) { this.ensureItIsPossibleToChangeNamedExpression(expressionName, newExpression, sheetId); const [oldNamedExpression, content] = this.operations.changeNamedExpressionExpression(expressionName, newExpression, sheetId, options); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.ChangeNamedExpressionUndoEntry(oldNamedExpression, newExpression, content, sheetId, options)); } removeNamedExpression(expressionName, sheetId) { this.ensureScopeIdIsValid(sheetId); const [namedExpression, content] = this.operations.removeNamedExpression(expressionName, sheetId); this.undoRedo.clearRedoStack(); this.clipboardOperations.abortCut(); this.undoRedo.saveOperation(new _UndoRedo__WEBPACK_IMPORTED_MODULE_8__.RemoveNamedExpressionUndoEntry(namedExpression, content, sheetId)); return namedExpression; } ensureItIsPossibleToAddNamedExpression(expressionName, expression, sheetId) { this.ensureScopeIdIsValid(sheetId); this.ensureNamedExpressionNameIsValid(expressionName, sheetId); this.ensureNamedExpressionIsValid(expression); } ensureItIsPossibleToChangeNamedExpression(expressionName, expression, sheetId) { this.ensureScopeIdIsValid(sheetId); if (this.namedExpressions.namedExpressionForScope(expressionName, sheetId) === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionDoesNotExistError(expressionName); } this.ensureNamedExpressionIsValid(expression); } isItPossibleToRemoveNamedExpression(expressionName, sheetId) { this.ensureScopeIdIsValid(sheetId); if (this.namedExpressions.namedExpressionForScope(expressionName, sheetId) === undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionDoesNotExistError(expressionName); } } ensureItIsPossibleToAddRows(sheet, ...indexes) { if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheet); } const sheetHeight = this.dependencyGraph.getSheetHeight(sheet); const newRowsCount = indexes.map(index => index[1]).reduce((a, b) => a + b, 0); if (sheetHeight + newRowsCount > this.maxRows) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SheetSizeLimitExceededError(); } for (const [row, numberOfRowsToAdd] of indexes) { if (!isNonnegativeInteger(row) || !isPositiveInteger(numberOfRowsToAdd)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('row number to be nonnegative and number of rows to add to be positive.'); } } } ensureItIsPossibleToRemoveRows(sheet, ...indexes) { for (const [rowStart, numberOfRows] of indexes) { const rowEnd = rowStart + numberOfRows - 1; if (!isNonnegativeInteger(rowStart) || !isNonnegativeInteger(rowEnd)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('starting and ending row to be nonnegative.'); } if (rowEnd < rowStart) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('starting row to be smaller than the ending row.'); } if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheet); } } } ensureItIsPossibleToAddColumns(sheet, ...indexes) { if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheet); } const sheetWidth = this.dependencyGraph.getSheetWidth(sheet); const newColumnsCount = indexes.map(index => index[1]).reduce((a, b) => a + b, 0); if (sheetWidth + newColumnsCount > this.maxColumns) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SheetSizeLimitExceededError(); } for (const [column, numberOfColumnsToAdd] of indexes) { if (!isNonnegativeInteger(column) || !isPositiveInteger(numberOfColumnsToAdd)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('column number to be nonnegative and number of columns to add to be positive.'); } } } ensureItIsPossibleToRemoveColumns(sheet, ...indexes) { for (const [columnStart, numberOfColumns] of indexes) { const columnEnd = columnStart + numberOfColumns - 1; if (!isNonnegativeInteger(columnStart) || !isNonnegativeInteger(columnEnd)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('starting and ending column to be nonnegative.'); } if (columnEnd < columnStart) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('starting column to be smaller than the ending column.'); } if (!this.sheetMapping.hasSheetWithId(sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheet); } } } ensureItIsPossibleToMoveRows(sheet, startRow, numberOfRows, targetRow) { this.ensureItIsPossibleToAddRows(sheet, [targetRow, numberOfRows]); const sourceStart = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, 0, startRow); const targetStart = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, 0, targetRow); if (!this.sheetMapping.hasSheetWithId(sheet) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(sourceStart) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(targetStart) || !isPositiveInteger(numberOfRows) || targetRow <= startRow + numberOfRows && targetRow >= startRow) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('a valid range of rows to move.'); } const width = this.dependencyGraph.getSheetWidth(sheet); const sourceRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(sourceStart, width, numberOfRows); if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(sourceRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SourceLocationHasArrayError(); } if (targetRow > 0 && this.dependencyGraph.arrayMapping.isFormulaArrayInAllRows(_Span__WEBPACK_IMPORTED_MODULE_7__.RowsSpan.fromNumberOfRows(sheet, targetRow - 1, 2))) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.TargetLocationHasArrayError(); } } ensureItIsPossibleToMoveColumns(sheet, startColumn, numberOfColumns, targetColumn) { this.ensureItIsPossibleToAddColumns(sheet, [targetColumn, numberOfColumns]); const sourceStart = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, startColumn, 0); const targetStart = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, targetColumn, 0); if (!this.sheetMapping.hasSheetWithId(sheet) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(sourceStart) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(targetStart) || !isPositiveInteger(numberOfColumns) || targetColumn <= startColumn + numberOfColumns && targetColumn >= startColumn) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError('a valid range of columns to move.'); } const sheetHeight = this.dependencyGraph.getSheetHeight(sheet); const sourceRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(sourceStart, numberOfColumns, sheetHeight); if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(sourceRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SourceLocationHasArrayError(); } if (targetColumn > 0 && this.dependencyGraph.arrayMapping.isFormulaArrayInAllColumns(_Span__WEBPACK_IMPORTED_MODULE_7__.ColumnsSpan.fromNumberOfColumns(sheet, targetColumn - 1, 2))) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.TargetLocationHasArrayError(); } } ensureItIsPossibleToAddSheet(name) { if (this.sheetMapping.hasSheetWithName(name)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SheetNameAlreadyTakenError(name); } } ensureItIsPossibleToRenameSheet(sheetId, name) { if (!this.sheetMapping.hasSheetWithId(sheetId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(sheetId); } const existingSheetId = this.sheetMapping.get(name); if (existingSheetId !== undefined && existingSheetId !== sheetId) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SheetNameAlreadyTakenError(name); } } ensureItIsPossibleToChangeContent(address) { if ((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(address)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidAddressError(address); } if (!this.sheetMapping.hasSheetWithId(address.sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(address.sheet); } } ensureItIsPossibleToChangeCellContents(inputAddress, content) { const boundaries = (0,_Sheet__WEBPACK_IMPORTED_MODULE_6__.findBoundaries)(content); const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(inputAddress, boundaries.width, boundaries.height); this.ensureRangeInSizeLimits(targetRange); for (const address of targetRange.addresses(this.dependencyGraph)) { this.ensureItIsPossibleToChangeContent(address); } } ensureItIsPossibleToChangeSheetContents(sheetId, content) { const boundaries = (0,_Sheet__WEBPACK_IMPORTED_MODULE_6__.findBoundaries)(content); const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheetId, 0, 0), boundaries.width, boundaries.height); this.ensureRangeInSizeLimits(targetRange); } ensureRangeInSizeLimits(range) { if (range.exceedsSheetSizeLimits(this.maxColumns, this.maxRows)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.SheetSizeLimitExceededError(); } } isThereSomethingToUndo() { return !this.undoRedo.isUndoStackEmpty(); } isThereSomethingToRedo() { return !this.undoRedo.isRedoStackEmpty(); } getAndClearContentChanges() { return this.operations.getAndClearContentChanges(); } ensureScopeIdIsValid(scopeId) { if (scopeId !== undefined && !this.sheetMapping.hasSheetWithId(scopeId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoSheetWithIdError(scopeId); } } validateRowOrColumnMapping(sheetId, rowMapping, rowOrColumn) { const limit = rowOrColumn === 'row' ? this.dependencyGraph.getSheetHeight(sheetId) : this.dependencyGraph.getSheetWidth(sheetId); const sources = rowMapping.map(([a, _]) => a).sort((a, b) => a - b); const targets = rowMapping.map(([_, b]) => b).sort((a, b) => a - b); for (let i = 0; i < sources.length; i++) { if (!isNonnegativeInteger(sources[i]) || sources[i] >= limit) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError(`${rowOrColumn} numbers to be nonnegative integers and less than sheet ${rowOrColumn === 'row' ? 'height' : 'width'}.`); } if (sources[i] === sources[i + 1]) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError(`source ${rowOrColumn} numbers to be unique.`); } if (sources[i] !== targets[i]) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.InvalidArgumentsError(`target ${rowOrColumn} numbers to be permutation of source ${rowOrColumn} numbers.`); } } } ensureNamedExpressionNameIsValid(expressionName, sheetId) { if (!this.namedExpressions.isNameValid(expressionName)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionNameIsInvalidError(expressionName); } if (!this.namedExpressions.isNameAvailable(expressionName, sheetId)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionNameIsAlreadyTakenError(expressionName); } } ensureNamedExpressionIsValid(expression) { const parsedExpression = this.cellContentParser.parse(expression); if (parsedExpression instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_2__.CellContent.Formula) { const parsingResult = this.parser.parse(parsedExpression.formula, (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(-1, 0, 0)); if ((0,_NamedExpressions__WEBPACK_IMPORTED_MODULE_4__.doesContainRelativeReferences)(parsingResult.ast)) { throw new _errors__WEBPACK_IMPORTED_MODULE_3__.NoRelativeAddressesAllowedError(); } } } } function isPositiveInteger(x) { return Number.isInteger(x) && x > 0; } function isNonnegativeInteger(x) { return Number.isInteger(x) && x >= 0; } /***/ }), /* 115 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ InternalNamedExpression: () => (/* binding */ InternalNamedExpression), /* harmony export */ NamedExpressions: () => (/* binding */ NamedExpressions), /* harmony export */ doesContainRelativeReferences: () => (/* binding */ doesContainRelativeReferences) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); /* harmony import */ var _parser_parser_consts__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class InternalNamedExpression { constructor(displayName, address, added, options) { this.displayName = displayName; this.address = address; this.added = added; this.options = options; } normalizeExpressionName() { return this.displayName.toLowerCase(); } copy() { return new InternalNamedExpression(this.displayName, this.address, this.added, this.options); } } class WorkbookStore { constructor() { this.mapping = new Map(); } has(expressionName) { return this.mapping.has(this.normalizeExpressionName(expressionName)); } isNameAvailable(expressionName) { const normalizedExpressionName = this.normalizeExpressionName(expressionName); const namedExpression = this.mapping.get(normalizedExpressionName); return !(namedExpression && namedExpression.added); } add(namedExpression) { this.mapping.set(namedExpression.normalizeExpressionName(), namedExpression); } get(expressionName) { return this.mapping.get(this.normalizeExpressionName(expressionName)); } getExisting(expressionName) { const namedExpression = this.mapping.get(this.normalizeExpressionName(expressionName)); if (namedExpression && namedExpression.added) { return namedExpression; } else { return undefined; } } remove(expressionName) { const normalizedExpressionName = this.normalizeExpressionName(expressionName); const namedExpression = this.mapping.get(normalizedExpressionName); if (namedExpression) { namedExpression.added = false; } } getAllNamedExpressions() { return Array.from(this.mapping.values()).filter(ne => ne.added); } normalizeExpressionName(expressionName) { return expressionName.toLowerCase(); } } class WorksheetStore { constructor() { this.mapping = new Map(); } add(namedExpression) { this.mapping.set(this.normalizeExpressionName(namedExpression.displayName), namedExpression); } get(expressionName) { return this.mapping.get(this.normalizeExpressionName(expressionName)); } has(expressionName) { return this.mapping.has(this.normalizeExpressionName(expressionName)); } getAllNamedExpressions() { return Array.from(this.mapping.values()).filter(ne => ne.added); } isNameAvailable(expressionName) { const normalizedExpressionName = this.normalizeExpressionName(expressionName); return !this.mapping.has(normalizedExpressionName); } remove(expressionName) { const normalizedExpressionName = this.normalizeExpressionName(expressionName); const namedExpression = this.mapping.get(normalizedExpressionName); if (namedExpression) { this.mapping.delete(normalizedExpressionName); } } normalizeExpressionName(expressionName) { return expressionName.toLowerCase(); } } class NamedExpressions { constructor() { this.nextNamedExpressionRow = 0; this.workbookStore = new WorkbookStore(); this.worksheetStores = new Map(); this.addressCache = new Map(); } isNameAvailable(expressionName, sheetId) { var _a, _b; if (sheetId === undefined) { return this.workbookStore.isNameAvailable(expressionName); } else { return (_b = (_a = this.worksheetStore(sheetId)) === null || _a === void 0 ? void 0 : _a.isNameAvailable(expressionName)) !== null && _b !== void 0 ? _b : true; } } namedExpressionInAddress(row) { const namedExpression = this.addressCache.get(row); if (namedExpression && namedExpression.added) { return namedExpression; } else { return undefined; } } namedExpressionForScope(expressionName, sheetId) { var _a; if (sheetId === undefined) { return this.workbookStore.getExisting(expressionName); } else { return (_a = this.worksheetStore(sheetId)) === null || _a === void 0 ? void 0 : _a.get(expressionName); } } nearestNamedExpression(expressionName, sheetId) { var _a, _b; return (_b = (_a = this.worksheetStore(sheetId)) === null || _a === void 0 ? void 0 : _a.get(expressionName)) !== null && _b !== void 0 ? _b : this.workbookStore.getExisting(expressionName); } isExpressionInScope(expressionName, sheetId) { var _a, _b; return (_b = (_a = this.worksheetStore(sheetId)) === null || _a === void 0 ? void 0 : _a.has(expressionName)) !== null && _b !== void 0 ? _b : false; } /** * Checks the validity of a named-expression's name. * * The name: * - Must start with a Unicode letter or with an underscore (`_`). * - Can contain only Unicode letters, numbers, underscores, and periods (`.`). * - Can't be the same as any possible reference in the A1 notation (`[A-Za-z]+[0-9]+`). * - Can't be the same as any possible reference in the R1C1 notation (`[rR][0-9]*[cC][0-9]*`). * * The naming rules follow the [OpenDocument](https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part4-formula/OpenDocument-v1.3-os-part4-formula.html#__RefHeading__1017964_715980110) standard. */ isNameValid(expressionName) { const a1CellRefRegexp = new RegExp(`^${_parser_parser_consts__WEBPACK_IMPORTED_MODULE_2__.CELL_REFERENCE_PATTERN}$`); const r1c1CellRefRegexp = new RegExp(`^${_parser_parser_consts__WEBPACK_IMPORTED_MODULE_2__.R1C1_CELL_REFERENCE_PATTERN}$`); const namedExpRegexp = new RegExp(`^${_parser_parser_consts__WEBPACK_IMPORTED_MODULE_2__.NAMED_EXPRESSION_PATTERN}$`); if (a1CellRefRegexp.test(expressionName) || r1c1CellRefRegexp.test(expressionName)) { return false; } return namedExpRegexp.test(expressionName); } addNamedExpression(expressionName, sheetId, options) { const store = sheetId === undefined ? this.workbookStore : this.worksheetStoreOrCreate(sheetId); let namedExpression = store.get(expressionName); if (namedExpression !== undefined) { namedExpression.added = true; namedExpression.displayName = expressionName; namedExpression.options = options; } else { namedExpression = new InternalNamedExpression(expressionName, this.nextAddress(), true, options); store.add(namedExpression); } this.addressCache.set(namedExpression.address.row, namedExpression); return namedExpression; } restoreNamedExpression(namedExpression, sheetId) { const store = sheetId === undefined ? this.workbookStore : this.worksheetStoreOrCreate(sheetId); namedExpression.added = true; store.add(namedExpression); this.addressCache.set(namedExpression.address.row, namedExpression); return namedExpression; } namedExpressionOrPlaceholder(expressionName, sheetId) { var _a; return (_a = this.worksheetStoreOrCreate(sheetId).get(expressionName)) !== null && _a !== void 0 ? _a : this.workbookNamedExpressionOrPlaceholder(expressionName); } workbookNamedExpressionOrPlaceholder(expressionName) { let namedExpression = this.workbookStore.get(expressionName); if (namedExpression === undefined) { namedExpression = new InternalNamedExpression(expressionName, this.nextAddress(), false); this.workbookStore.add(namedExpression); } return namedExpression; } remove(expressionName, sheetId) { let store; if (sheetId === undefined) { store = this.workbookStore; } else { store = this.worksheetStore(sheetId); } const namedExpression = store === null || store === void 0 ? void 0 : store.get(expressionName); if (store === undefined || namedExpression === undefined || !namedExpression.added) { throw Error('Named expression does not exist'); } store.remove(expressionName); if (store instanceof WorksheetStore && store.mapping.size === 0) { this.worksheetStores.delete(sheetId); } this.addressCache.delete(namedExpression.address.row); } getAllNamedExpressionsNamesInScope(sheetId) { return this.getAllNamedExpressions().filter(({ scope }) => scope === sheetId).map(ne => ne.expression.displayName); } getAllNamedExpressionsNames() { return this.getAllNamedExpressions().map(ne => ne.expression.displayName); } getAllNamedExpressions() { const storedNamedExpressions = []; this.workbookStore.getAllNamedExpressions().forEach(expr => { storedNamedExpressions.push({ expression: expr, scope: undefined }); }); this.worksheetStores.forEach((store, sheetNum) => { store.getAllNamedExpressions().forEach(expr => { storedNamedExpressions.push({ expression: expr, scope: sheetNum }); }); }); return storedNamedExpressions; } getAllNamedExpressionsForScope(scope) { var _a, _b; if (scope === undefined) { return this.workbookStore.getAllNamedExpressions(); } else { return (_b = (_a = this.worksheetStores.get(scope)) === null || _a === void 0 ? void 0 : _a.getAllNamedExpressions()) !== null && _b !== void 0 ? _b : []; } } worksheetStoreOrCreate(sheetId) { let store = this.worksheetStores.get(sheetId); if (!store) { store = new WorksheetStore(); this.worksheetStores.set(sheetId, store); } return store; } worksheetStore(sheetId) { return this.worksheetStores.get(sheetId); } nextAddress() { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS, 0, this.nextNamedExpressionRow++); } } NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS = -1; const doesContainRelativeReferences = ast => { switch (ast.type) { case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.EMPTY: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.NUMBER: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.STRING: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ERROR: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ERROR_WITH_RAW_INPUT: return false; case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.CELL_REFERENCE: return !ast.reference.isAbsolute(); case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.CELL_RANGE: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.COLUMN_RANGE: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ROW_RANGE: return !ast.start.isAbsolute(); case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.NAMED_EXPRESSION: return false; case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PERCENT_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PLUS_UNARY_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.MINUS_UNARY_OP: { return doesContainRelativeReferences(ast.value); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.CONCATENATE_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.EQUALS_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.NOT_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.LESS_THAN_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.GREATER_THAN_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.LESS_THAN_OR_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.MINUS_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PLUS_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.TIMES_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.DIV_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.POWER_OP: return doesContainRelativeReferences(ast.left) || doesContainRelativeReferences(ast.right); case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PARENTHESIS: return doesContainRelativeReferences(ast.expression); case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.FUNCTION_CALL: { return ast.args.some(arg => doesContainRelativeReferences(arg)); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ARRAY: { return ast.args.some(row => row.some(arg => doesContainRelativeReferences(arg))); } } }; /***/ }), /* 116 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddColumnsCommand: () => (/* binding */ AddColumnsCommand), /* harmony export */ AddRowsCommand: () => (/* binding */ AddRowsCommand), /* harmony export */ Operations: () => (/* binding */ Operations), /* harmony export */ RemoveColumnsCommand: () => (/* binding */ RemoveColumnsCommand), /* harmony export */ RemoveRowsCommand: () => (/* binding */ RemoveRowsCommand), /* harmony export */ normalizeAddedIndexes: () => (/* binding */ normalizeAddedIndexes), /* harmony export */ normalizeRemovedIndexes: () => (/* binding */ normalizeRemovedIndexes) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); /* harmony import */ var _CellContentParser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(112); /* harmony import */ var _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(113); /* harmony import */ var _ContentChanges__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(68); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(4); /* harmony import */ var _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(80); /* harmony import */ var _dependencyTransformers_AddColumnsTransformer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(117); /* harmony import */ var _dependencyTransformers_AddRowsTransformer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(119); /* harmony import */ var _dependencyTransformers_CleanOutOfScopeDependenciesTransformer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(120); /* harmony import */ var _dependencyTransformers_MoveCellsTransformer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(121); /* harmony import */ var _dependencyTransformers_RemoveColumnsTransformer__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(122); /* harmony import */ var _dependencyTransformers_RemoveRowsTransformer__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(123); /* harmony import */ var _dependencyTransformers_RemoveSheetTransformer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(124); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(77); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(70); /* harmony import */ var _NamedExpressions__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(115); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(7); /* harmony import */ var _Sheet__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(125); /* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(71); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(72); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RemoveRowsCommand { constructor(sheet, indexes) { this.sheet = sheet; this.indexes = indexes; } normalizedIndexes() { return normalizeRemovedIndexes(this.indexes); } rowsSpans() { return this.normalizedIndexes().map(normalizedIndex => _Span__WEBPACK_IMPORTED_MODULE_21__.RowsSpan.fromNumberOfRows(this.sheet, normalizedIndex[0], normalizedIndex[1])); } } class AddRowsCommand { constructor(sheet, indexes) { this.sheet = sheet; this.indexes = indexes; } normalizedIndexes() { return normalizeAddedIndexes(this.indexes); } rowsSpans() { return this.normalizedIndexes().map(normalizedIndex => _Span__WEBPACK_IMPORTED_MODULE_21__.RowsSpan.fromNumberOfRows(this.sheet, normalizedIndex[0], normalizedIndex[1])); } } class AddColumnsCommand { constructor(sheet, indexes) { this.sheet = sheet; this.indexes = indexes; } normalizedIndexes() { return normalizeAddedIndexes(this.indexes); } columnsSpans() { return this.normalizedIndexes().map(normalizedIndex => _Span__WEBPACK_IMPORTED_MODULE_21__.ColumnsSpan.fromNumberOfColumns(this.sheet, normalizedIndex[0], normalizedIndex[1])); } } class RemoveColumnsCommand { constructor(sheet, indexes) { this.sheet = sheet; this.indexes = indexes; } normalizedIndexes() { return normalizeRemovedIndexes(this.indexes); } columnsSpans() { return this.normalizedIndexes().map(normalizedIndex => _Span__WEBPACK_IMPORTED_MODULE_21__.ColumnsSpan.fromNumberOfColumns(this.sheet, normalizedIndex[0], normalizedIndex[1])); } } class Operations { constructor(config, dependencyGraph, columnSearch, cellContentParser, parser, stats, lazilyTransformingAstService, namedExpressions, arraySizePredictor) { this.dependencyGraph = dependencyGraph; this.columnSearch = columnSearch; this.cellContentParser = cellContentParser; this.parser = parser; this.stats = stats; this.lazilyTransformingAstService = lazilyTransformingAstService; this.namedExpressions = namedExpressions; this.arraySizePredictor = arraySizePredictor; this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_6__.ContentChanges.empty(); this.allocateNamedExpressionAddressSpace(); this.maxColumns = config.maxColumns; this.maxRows = config.maxRows; } get sheetMapping() { return this.dependencyGraph.sheetMapping; } get addressMapping() { return this.dependencyGraph.addressMapping; } removeRows(cmd) { const rowsRemovals = []; for (const rowsToRemove of cmd.rowsSpans()) { const rowsRemoval = this.doRemoveRows(rowsToRemove); if (rowsRemoval) { rowsRemovals.push(rowsRemoval); } } return rowsRemovals; } addRows(cmd) { for (const addedRows of cmd.rowsSpans()) { this.doAddRows(addedRows); } } addColumns(cmd) { for (const addedColumns of cmd.columnsSpans()) { this.doAddColumns(addedColumns); } } removeColumns(cmd) { const columnsRemovals = []; for (const columnsToRemove of cmd.columnsSpans()) { const columnsRemoval = this.doRemoveColumns(columnsToRemove); if (columnsRemoval) { columnsRemovals.push(columnsRemoval); } } return columnsRemovals; } removeSheet(sheetId) { this.dependencyGraph.removeSheet(sheetId); let version = 0; this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_RemoveSheetTransformer__WEBPACK_IMPORTED_MODULE_15__.RemoveSheetTransformer(sheetId); transformation.performEagerTransformations(this.dependencyGraph, this.parser); version = this.lazilyTransformingAstService.addTransformation(transformation); }); this.sheetMapping.removeSheet(sheetId); this.columnSearch.removeSheet(sheetId); const scopedNamedExpressions = this.namedExpressions.getAllNamedExpressionsForScope(sheetId).map(namedExpression => this.removeNamedExpression(namedExpression.normalizeExpressionName(), sheetId)); return { version: version, scopedNamedExpressions }; } removeSheetByName(sheetName) { const sheetId = this.sheetMapping.fetch(sheetName); return this.removeSheet(sheetId); } clearSheet(sheetId) { this.dependencyGraph.clearSheet(sheetId); this.columnSearch.removeSheet(sheetId); } addSheet(name) { const sheetId = this.sheetMapping.addSheet(name); const sheet = []; this.dependencyGraph.addressMapping.autoAddSheet(sheetId, (0,_Sheet__WEBPACK_IMPORTED_MODULE_20__.findBoundaries)(sheet)); return this.sheetMapping.fetchDisplayName(sheetId); } renameSheet(sheetId, newName) { return this.sheetMapping.renameSheet(sheetId, newName); } moveRows(sheet, startRow, numberOfRows, targetRow) { const rowsToAdd = _Span__WEBPACK_IMPORTED_MODULE_21__.RowsSpan.fromNumberOfRows(sheet, targetRow, numberOfRows); this.lazilyTransformingAstService.beginCombinedMode(sheet); this.doAddRows(rowsToAdd); if (targetRow < startRow) { startRow += numberOfRows; } const startAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheet, 0, startRow); const targetAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheet, 0, targetRow); this.moveCells(startAddress, Number.POSITIVE_INFINITY, numberOfRows, targetAddress); const rowsToRemove = _Span__WEBPACK_IMPORTED_MODULE_21__.RowsSpan.fromNumberOfRows(sheet, startRow, numberOfRows); this.doRemoveRows(rowsToRemove); return this.lazilyTransformingAstService.commitCombinedMode(); } moveColumns(sheet, startColumn, numberOfColumns, targetColumn) { const columnsToAdd = _Span__WEBPACK_IMPORTED_MODULE_21__.ColumnsSpan.fromNumberOfColumns(sheet, targetColumn, numberOfColumns); this.lazilyTransformingAstService.beginCombinedMode(sheet); this.doAddColumns(columnsToAdd); if (targetColumn < startColumn) { startColumn += numberOfColumns; } const startAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheet, startColumn, 0); const targetAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheet, targetColumn, 0); this.moveCells(startAddress, numberOfColumns, Number.POSITIVE_INFINITY, targetAddress); const columnsToRemove = _Span__WEBPACK_IMPORTED_MODULE_21__.ColumnsSpan.fromNumberOfColumns(sheet, startColumn, numberOfColumns); this.doRemoveColumns(columnsToRemove); return this.lazilyTransformingAstService.commitCombinedMode(); } moveCells(sourceLeftCorner, width, height, destinationLeftCorner) { this.ensureItIsPossibleToMoveCells(sourceLeftCorner, width, height, destinationLeftCorner); const sourceRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(sourceLeftCorner, width, height); const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(destinationLeftCorner, width, height); const toRight = destinationLeftCorner.col - sourceLeftCorner.col; const toBottom = destinationLeftCorner.row - sourceLeftCorner.row; const toSheet = destinationLeftCorner.sheet; const currentDataAtTarget = this.getRangeClipboardCells(targetRange); const valuesToRemove = this.dependencyGraph.rawValuesFromRange(targetRange); this.columnSearch.removeValues(valuesToRemove); const valuesToMove = this.dependencyGraph.rawValuesFromRange(sourceRange); this.columnSearch.moveValues(valuesToMove, toRight, toBottom, toSheet); let version = 0; this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_MoveCellsTransformer__WEBPACK_IMPORTED_MODULE_12__.MoveCellsTransformer(sourceRange, toRight, toBottom, toSheet); transformation.performEagerTransformations(this.dependencyGraph, this.parser); version = this.lazilyTransformingAstService.addTransformation(transformation); }); this.dependencyGraph.moveCells(sourceRange, toRight, toBottom, toSheet); const addedGlobalNamedExpressions = this.updateNamedExpressionsForMovedCells(sourceLeftCorner, width, height, destinationLeftCorner); return { version: version, overwrittenCellsData: currentDataAtTarget, addedGlobalNamedExpressions: addedGlobalNamedExpressions }; } setRowOrder(sheetId, rowMapping) { const buffer = []; let oldContent = []; for (const [source, target] of rowMapping) { if (source !== target) { const rowRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom({ sheet: sheetId, col: 0, row: source }, Infinity, 1); const row = this.getRangeClipboardCells(rowRange); oldContent = oldContent.concat(row); buffer.push(row.map(([{ sheet, col }, cell]) => [{ sheet, col, row: target }, cell])); } } buffer.forEach(row => this.restoreClipboardCells(sheetId, row.values())); return oldContent; } setColumnOrder(sheetId, columnMapping) { const buffer = []; let oldContent = []; for (const [source, target] of columnMapping) { if (source !== target) { const rowRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom({ sheet: sheetId, col: source, row: 0 }, 1, Infinity); const column = this.getRangeClipboardCells(rowRange); oldContent = oldContent.concat(column); buffer.push(column.map(([{ sheet, col: _col, row }, cell]) => [{ sheet, col: target, row }, cell])); } } buffer.forEach(column => this.restoreClipboardCells(sheetId, column.values())); return oldContent; } addNamedExpression(expressionName, expression, sheetId, options) { const namedExpression = this.namedExpressions.addNamedExpression(expressionName, sheetId, options); this.storeNamedExpressionInCell(namedExpression.address, expression); this.adjustNamedExpressionEdges(namedExpression, expressionName, sheetId); } restoreNamedExpression(namedExpression, content, sheetId) { const expressionName = namedExpression.displayName; this.restoreCell(namedExpression.address, content); const restoredNamedExpression = this.namedExpressions.restoreNamedExpression(namedExpression, sheetId); this.adjustNamedExpressionEdges(restoredNamedExpression, expressionName, sheetId); } changeNamedExpressionExpression(expressionName, newExpression, sheetId, options) { const namedExpression = this.namedExpressions.namedExpressionForScope(expressionName, sheetId); if (!namedExpression) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.NamedExpressionDoesNotExistError(expressionName); } const oldNamedExpression = namedExpression.copy(); namedExpression.options = options; const content = this.getClipboardCell(namedExpression.address); this.storeNamedExpressionInCell(namedExpression.address, newExpression); return [oldNamedExpression, content]; } removeNamedExpression(expressionName, sheetId) { const namedExpression = this.namedExpressions.namedExpressionForScope(expressionName, sheetId); if (!namedExpression) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.NamedExpressionDoesNotExistError(expressionName); } this.namedExpressions.remove(namedExpression.displayName, sheetId); const content = this.getClipboardCell(namedExpression.address); if (sheetId !== undefined) { const globalNamedExpression = this.namedExpressions.workbookNamedExpressionOrPlaceholder(expressionName); this.dependencyGraph.exchangeNode(namedExpression.address, globalNamedExpression.address); } else { this.dependencyGraph.setCellEmpty(namedExpression.address); } return [namedExpression, content]; } ensureItIsPossibleToMoveCells(sourceLeftCorner, width, height, destinationLeftCorner) { if ((0,_Cell__WEBPACK_IMPORTED_MODULE_3__.invalidSimpleCellAddress)(sourceLeftCorner) || !(isPositiveInteger(width) && isPositiveInteger(height) || isRowOrColumnRange(sourceLeftCorner, width, height)) || (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.invalidSimpleCellAddress)(destinationLeftCorner) || !this.sheetMapping.hasSheetWithId(sourceLeftCorner.sheet) || !this.sheetMapping.hasSheetWithId(destinationLeftCorner.sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.InvalidArgumentsError('a valid range of cells to move.'); } const sourceRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(sourceLeftCorner, width, height); const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(destinationLeftCorner, width, height); if (targetRange.exceedsSheetSizeLimits(this.maxColumns, this.maxRows)) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.SheetSizeLimitExceededError(); } if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(sourceRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.SourceLocationHasArrayError(); } if (this.dependencyGraph.arrayMapping.isFormulaArrayInRange(targetRange)) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.TargetLocationHasArrayError(); } } restoreClipboardCells(sourceSheetId, cells) { const addedNamedExpressions = []; for (const [address, clipboardCell] of cells) { this.restoreCell(address, clipboardCell); if (clipboardCell.type === _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.FORMULA) { const { dependencies } = this.parser.fetchCachedResult(clipboardCell.hash); addedNamedExpressions.push(...this.updateNamedExpressionsForTargetAddress(sourceSheetId, address, dependencies)); } } return addedNamedExpressions; } /** * Restores a single cell. * @param {SimpleCellAddress} address * @param {ClipboardCell} clipboardCell */ restoreCell(address, clipboardCell) { switch (clipboardCell.type) { case _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.VALUE: { this.setValueToCell(clipboardCell, address); break; } case _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.FORMULA: { this.setFormulaToCellFromCache(clipboardCell.hash, address); break; } case _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.EMPTY: { this.setCellEmpty(address); break; } case _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.PARSING_ERROR: { this.setParsingErrorToCell(clipboardCell.rawInput, clipboardCell.errors, address); break; } } } getOldContent(address) { const vertex = this.dependencyGraph.getCell(address); if (vertex === undefined || vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.EmptyCellVertex) { return [address, { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.EMPTY }]; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ValueCellVertex) { return [address, Object.assign({ type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.VALUE }, vertex.getValues())]; } else if (vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_8__.FormulaVertex) { return [vertex.getAddress(this.lazilyTransformingAstService), { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.FORMULA, hash: this.parser.computeHashFromAst(vertex.getFormula(this.lazilyTransformingAstService)) }]; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ParsingErrorVertex) { return [address, { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.PARSING_ERROR, rawInput: vertex.rawInput, errors: vertex.errors }]; } throw Error('Trying to copy unsupported type'); } getClipboardCell(address) { const vertex = this.dependencyGraph.getCell(address); if (vertex === undefined || vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.EmptyCellVertex) { return { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.EMPTY }; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ValueCellVertex) { return Object.assign({ type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.VALUE }, vertex.getValues()); } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ArrayVertex) { const val = vertex.getArrayCellValue(address); if (val === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.EmptyValue) { return { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.EMPTY }; } return { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.VALUE, parsedValue: val, rawValue: vertex.getArrayCellRawValue(address) }; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.FormulaCellVertex) { return { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.FORMULA, hash: this.parser.computeHashFromAst(vertex.getFormula(this.lazilyTransformingAstService)) }; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ParsingErrorVertex) { return { type: _ClipboardOperations__WEBPACK_IMPORTED_MODULE_5__.ClipboardCellType.PARSING_ERROR, rawInput: vertex.rawInput, errors: vertex.errors }; } throw Error('Trying to copy unsupported type'); } getSheetClipboardCells(sheet) { const sheetHeight = this.dependencyGraph.getSheetHeight(sheet); const sheetWidth = this.dependencyGraph.getSheetWidth(sheet); const arr = new Array(sheetHeight); for (let i = 0; i < sheetHeight; i++) { arr[i] = new Array(sheetWidth); for (let j = 0; j < sheetWidth; j++) { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheet, j, i); arr[i][j] = this.getClipboardCell(address); } } return arr; } getRangeClipboardCells(range) { const result = []; for (const address of range.addresses(this.dependencyGraph)) { result.push([address, this.getClipboardCell(address)]); } return result; } setCellContent(address, newCellContent) { const parsedCellContent = this.cellContentParser.parse(newCellContent); const oldContent = this.getOldContent(address); if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_4__.CellContent.Formula) { const parserResult = this.parser.parse(parsedCellContent.formula, address); const { ast, errors } = parserResult; if (errors.length > 0) { this.setParsingErrorToCell(parsedCellContent.formula, errors, address); } else { try { const size = this.arraySizePredictor.checkArraySize(ast, address); if (size.width <= 0 || size.height <= 0) { throw Error('Incorrect array size'); } this.setFormulaToCell(address, size, parserResult); } catch (error) { if (!error.message) { throw error; } const parsingError = { type: _parser__WEBPACK_IMPORTED_MODULE_19__.ParsingErrorType.InvalidRangeSize, message: 'Invalid range size.' }; this.setParsingErrorToCell(parsedCellContent.formula, [parsingError], address); } } } else if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_4__.CellContent.Empty) { this.setCellEmpty(address); } else { this.setValueToCell({ parsedValue: parsedCellContent.value, rawValue: newCellContent }, address); } return oldContent; } setSheetContent(sheetId, newSheetContent) { this.clearSheet(sheetId); for (let i = 0; i < newSheetContent.length; i++) { for (let j = 0; j < newSheetContent[i].length; j++) { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(sheetId, j, i); this.setCellContent(address, newSheetContent[i][j]); } } } setParsingErrorToCell(rawInput, errors, address) { const oldValue = this.dependencyGraph.getCellValue(address); const vertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ParsingErrorVertex(errors, rawInput); const arrayChanges = this.dependencyGraph.setParsingErrorToCell(address, vertex); this.columnSearch.remove((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.getRawValue)(oldValue), address); this.columnSearch.applyChanges(arrayChanges.getChanges()); this.changes.addAll(arrayChanges); this.changes.addChange(vertex.getCellValue(), address); } setFormulaToCell(address, size, { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies }) { const oldValue = this.dependencyGraph.getCellValue(address); const arrayChanges = this.dependencyGraph.setFormulaToCell(address, ast, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, address), size, hasVolatileFunction, hasStructuralChangeFunction); this.columnSearch.remove((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.getRawValue)(oldValue), address); this.columnSearch.applyChanges(arrayChanges.getChanges()); this.changes.addAll(arrayChanges); } setValueToCell(value, address) { const oldValue = this.dependencyGraph.getCellValue(address); const arrayChanges = this.dependencyGraph.setValueToCell(address, value); this.columnSearch.change((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.getRawValue)(oldValue), (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.getRawValue)(value.parsedValue), address); this.columnSearch.applyChanges(arrayChanges.getChanges().filter(change => !(0,_Cell__WEBPACK_IMPORTED_MODULE_3__.equalSimpleCellAddress)(change.address, address))); this.changes.addAll(arrayChanges); this.changes.addChange(value.parsedValue, address); } setCellEmpty(address) { if (this.dependencyGraph.isArrayInternalCell(address)) { return; } const oldValue = this.dependencyGraph.getCellValue(address); const arrayChanges = this.dependencyGraph.setCellEmpty(address); this.columnSearch.remove((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.getRawValue)(oldValue), address); this.columnSearch.applyChanges(arrayChanges.getChanges()); this.changes.addAll(arrayChanges); this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_17__.EmptyValue, address); } setFormulaToCellFromCache(formulaHash, address) { const { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies } = this.parser.fetchCachedResult(formulaHash); const absoluteDependencies = (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, address); const [cleanedAst] = new _dependencyTransformers_CleanOutOfScopeDependenciesTransformer__WEBPACK_IMPORTED_MODULE_11__.CleanOutOfScopeDependenciesTransformer(address.sheet).transformSingleAst(ast, address); this.parser.rememberNewAst(cleanedAst); const cleanedDependencies = (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.filterDependenciesOutOfScope)(absoluteDependencies); const size = this.arraySizePredictor.checkArraySize(ast, address); this.dependencyGraph.setFormulaToCell(address, cleanedAst, cleanedDependencies, size, hasVolatileFunction, hasStructuralChangeFunction); } /** * Returns true if row number is outside of given sheet. * @param {number} row - row number * @param {number} sheet - sheet ID number */ rowEffectivelyNotInSheet(row, sheet) { const height = this.dependencyGraph.addressMapping.getHeight(sheet); return row >= height; } getAndClearContentChanges() { const changes = this.changes; this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_6__.ContentChanges.empty(); return changes; } forceApplyPostponedTransformations() { this.dependencyGraph.forceApplyPostponedTransformations(); } /** * Removes multiple rows from sheet.
* Does nothing if rows are outside of effective sheet size. * @param {RowsSpan} rowsToRemove - rows to remove */ doRemoveRows(rowsToRemove) { if (this.rowEffectivelyNotInSheet(rowsToRemove.rowStart, rowsToRemove.sheet)) { return; } const removedCells = []; for (const [address] of this.dependencyGraph.entriesFromRowsSpan(rowsToRemove)) { removedCells.push({ address, cellType: this.getClipboardCell(address) }); } const { affectedArrays, contentChanges } = this.dependencyGraph.removeRows(rowsToRemove); this.columnSearch.applyChanges(contentChanges.getChanges()); let version = 0; this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_RemoveRowsTransformer__WEBPACK_IMPORTED_MODULE_14__.RemoveRowsTransformer(rowsToRemove); transformation.performEagerTransformations(this.dependencyGraph, this.parser); version = this.lazilyTransformingAstService.addTransformation(transformation); }); this.rewriteAffectedArrays(affectedArrays); return { version: version, removedCells, rowFrom: rowsToRemove.rowStart, rowCount: rowsToRemove.numberOfRows }; } /** * Removes multiple columns from sheet.
* Does nothing if columns are outside of effective sheet size. * @param {ColumnsSpan} columnsToRemove - columns to remove */ doRemoveColumns(columnsToRemove) { if (this.columnEffectivelyNotInSheet(columnsToRemove.columnStart, columnsToRemove.sheet)) { return; } const removedCells = []; for (const [address] of this.dependencyGraph.entriesFromColumnsSpan(columnsToRemove)) { removedCells.push({ address, cellType: this.getClipboardCell(address) }); } const { affectedArrays, contentChanges } = this.dependencyGraph.removeColumns(columnsToRemove); this.columnSearch.applyChanges(contentChanges.getChanges()); this.columnSearch.removeColumns(columnsToRemove); let version = 0; this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_RemoveColumnsTransformer__WEBPACK_IMPORTED_MODULE_13__.RemoveColumnsTransformer(columnsToRemove); transformation.performEagerTransformations(this.dependencyGraph, this.parser); version = this.lazilyTransformingAstService.addTransformation(transformation); }); this.rewriteAffectedArrays(affectedArrays); return { version: version, removedCells, columnFrom: columnsToRemove.columnStart, columnCount: columnsToRemove.numberOfColumns }; } /** * Add multiple rows to sheet.
* Does nothing if rows are outside of effective sheet size. * @param {RowsSpan} addedRows - rows to add */ doAddRows(addedRows) { if (this.rowEffectivelyNotInSheet(addedRows.rowStart, addedRows.sheet)) { return; } const { affectedArrays } = this.dependencyGraph.addRows(addedRows); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_AddRowsTransformer__WEBPACK_IMPORTED_MODULE_10__.AddRowsTransformer(addedRows); transformation.performEagerTransformations(this.dependencyGraph, this.parser); this.lazilyTransformingAstService.addTransformation(transformation); }); this.rewriteAffectedArrays(affectedArrays); } rewriteAffectedArrays(affectedArrays) { for (const arrayVertex of affectedArrays.values()) { if (arrayVertex.array.size.isRef) { continue; } const ast = arrayVertex.getFormula(this.lazilyTransformingAstService); const address = arrayVertex.getAddress(this.lazilyTransformingAstService); const hash = this.parser.computeHashFromAst(ast); this.setFormulaToCellFromCache(hash, address); } } /** * Add multiple columns to sheet
* Does nothing if columns are outside of effective sheet size * @param {ColumnsSpan} addedColumns - object containing information about columns to add */ doAddColumns(addedColumns) { if (this.columnEffectivelyNotInSheet(addedColumns.columnStart, addedColumns.sheet)) { return; } const { affectedArrays, contentChanges } = this.dependencyGraph.addColumns(addedColumns); this.columnSearch.addColumns(addedColumns); this.columnSearch.applyChanges(contentChanges.getChanges()); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_22__.StatType.TRANSFORM_ASTS, () => { const transformation = new _dependencyTransformers_AddColumnsTransformer__WEBPACK_IMPORTED_MODULE_9__.AddColumnsTransformer(addedColumns); transformation.performEagerTransformations(this.dependencyGraph, this.parser); this.lazilyTransformingAstService.addTransformation(transformation); }); this.rewriteAffectedArrays(affectedArrays); } /** * Returns true if row number is outside of given sheet. * @param {number} column - row number * @param {number} sheet - sheet ID number */ columnEffectivelyNotInSheet(column, sheet) { const width = this.dependencyGraph.addressMapping.getWidth(sheet); return column >= width; } adjustNamedExpressionEdges(namedExpression, expressionName, sheetId) { if (sheetId === undefined) { return; } const { vertex: localVertex, id: maybeLocalVertexId } = this.dependencyGraph.fetchCellOrCreateEmpty(namedExpression.address); const localVertexId = maybeLocalVertexId !== null && maybeLocalVertexId !== void 0 ? maybeLocalVertexId : this.dependencyGraph.graph.getNodeId(localVertex); const globalNamedExpression = this.namedExpressions.workbookNamedExpressionOrPlaceholder(expressionName); const { vertex: globalVertex, id: maybeGlobalVertexId } = this.dependencyGraph.fetchCellOrCreateEmpty(globalNamedExpression.address); const globalVertexId = maybeGlobalVertexId !== null && maybeGlobalVertexId !== void 0 ? maybeGlobalVertexId : this.dependencyGraph.graph.getNodeId(globalVertex); for (const adjacentNode of this.dependencyGraph.graph.adjacentNodes(globalVertex)) { if (adjacentNode instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.FormulaCellVertex && adjacentNode.getAddress(this.lazilyTransformingAstService).sheet === sheetId) { const ast = adjacentNode.getFormula(this.lazilyTransformingAstService); const formulaAddress = adjacentNode.getAddress(this.lazilyTransformingAstService); const { dependencies } = this.parser.fetchCachedResultForAst(ast); for (const dependency of (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, formulaAddress)) { if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_19__.NamedExpressionDependency && dependency.name.toLowerCase() === namedExpression.displayName.toLowerCase()) { this.dependencyGraph.graph.removeEdge(globalVertexId, adjacentNode); this.dependencyGraph.graph.addEdge(localVertexId, adjacentNode); } } } } } storeNamedExpressionInCell(address, expression) { const parsedCellContent = this.cellContentParser.parse(expression); if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_4__.CellContent.Formula) { const parsingResult = this.parser.parse(parsedCellContent.formula, (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.simpleCellAddress)(-1, 0, 0)); if ((0,_NamedExpressions__WEBPACK_IMPORTED_MODULE_18__.doesContainRelativeReferences)(parsingResult.ast)) { throw new _errors__WEBPACK_IMPORTED_MODULE_16__.NoRelativeAddressesAllowedError(); } const { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies } = parsingResult; this.dependencyGraph.setFormulaToCell(address, ast, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, address), _ArraySize__WEBPACK_IMPORTED_MODULE_2__.ArraySize.scalar(), hasVolatileFunction, hasStructuralChangeFunction); } else if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_4__.CellContent.Empty) { this.setCellEmpty(address); } else { this.setValueToCell({ parsedValue: parsedCellContent.value, rawValue: expression }, address); } } updateNamedExpressionsForMovedCells(sourceLeftCorner, width, height, destinationLeftCorner) { if (sourceLeftCorner.sheet === destinationLeftCorner.sheet) { return []; } const addedGlobalNamedExpressions = []; const targetRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(destinationLeftCorner, width, height); for (const formulaAddress of targetRange.addresses(this.dependencyGraph)) { const vertex = this.addressMapping.fetchCell(formulaAddress); if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.FormulaCellVertex && formulaAddress.sheet !== sourceLeftCorner.sheet) { const ast = vertex.getFormula(this.lazilyTransformingAstService); const { dependencies } = this.parser.fetchCachedResultForAst(ast); addedGlobalNamedExpressions.push(...this.updateNamedExpressionsForTargetAddress(sourceLeftCorner.sheet, formulaAddress, dependencies)); } } return addedGlobalNamedExpressions; } updateNamedExpressionsForTargetAddress(sourceSheet, targetAddress, dependencies) { if (sourceSheet === targetAddress.sheet) { return []; } const addedGlobalNamedExpressions = []; const vertex = this.addressMapping.fetchCell(targetAddress); for (const namedExpressionDependency of (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, targetAddress)) { if (!(namedExpressionDependency instanceof _parser__WEBPACK_IMPORTED_MODULE_19__.NamedExpressionDependency)) { continue; } const expressionName = namedExpressionDependency.name; const sourceVertex = this.dependencyGraph.fetchNamedExpressionVertex(expressionName, sourceSheet).vertex; const namedExpressionInTargetScope = this.namedExpressions.isExpressionInScope(expressionName, targetAddress.sheet); const targetScopeExpressionVertex = namedExpressionInTargetScope ? this.dependencyGraph.fetchNamedExpressionVertex(expressionName, targetAddress.sheet).vertex : this.copyOrFetchGlobalNamedExpressionVertex(expressionName, sourceVertex, addedGlobalNamedExpressions); if (targetScopeExpressionVertex !== sourceVertex) { this.dependencyGraph.graph.removeEdgeIfExists(sourceVertex, vertex); this.dependencyGraph.graph.addEdge(targetScopeExpressionVertex, vertex); } } return addedGlobalNamedExpressions; } allocateNamedExpressionAddressSpace() { this.dependencyGraph.addressMapping.addSheet(_NamedExpressions__WEBPACK_IMPORTED_MODULE_18__.NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS, new _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.SparseStrategy(0, 0)); } copyOrFetchGlobalNamedExpressionVertex(expressionName, sourceVertex, addedNamedExpressions) { let expression = this.namedExpressions.namedExpressionForScope(expressionName); if (expression === undefined) { expression = this.namedExpressions.addNamedExpression(expressionName); addedNamedExpressions.push(expression.normalizeExpressionName()); if (sourceVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.FormulaCellVertex) { const parsingResult = this.parser.fetchCachedResultForAst(sourceVertex.getFormula(this.lazilyTransformingAstService)); const { ast, hasVolatileFunction, hasStructuralChangeFunction, dependencies } = parsingResult; this.dependencyGraph.setFormulaToCell(expression.address, ast, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, expression.address), _ArraySize__WEBPACK_IMPORTED_MODULE_2__.ArraySize.scalar(), hasVolatileFunction, hasStructuralChangeFunction); } else if (sourceVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.EmptyCellVertex) { this.setCellEmpty(expression.address); } else if (sourceVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_7__.ValueCellVertex) { this.setValueToCell(sourceVertex.getValues(), expression.address); } } return this.dependencyGraph.fetchCellOrCreateEmpty(expression.address).vertex; } } function normalizeRemovedIndexes(indexes) { if (indexes.length <= 1) { return indexes; } const sorted = [...indexes].sort(([a], [b]) => a - b); /* merge overlapping and adjacent indexes */ const merged = sorted.reduce((acc, [startIndex, amount]) => { const previous = acc[acc.length - 1]; const lastIndex = previous[0] + previous[1]; if (startIndex <= lastIndex) { previous[1] += Math.max(0, amount - (lastIndex - startIndex)); } else { acc.push([startIndex, amount]); } return acc; }, [sorted[0]]); /* shift further indexes */ let shift = 0; for (let i = 0; i < merged.length; ++i) { merged[i][0] -= shift; shift += merged[i][1]; } return merged; } function normalizeAddedIndexes(indexes) { if (indexes.length <= 1) { return indexes; } const sorted = [...indexes].sort(([a], [b]) => a - b); /* merge indexes with same start */ const merged = sorted.reduce((acc, [startIndex, amount]) => { const previous = acc[acc.length - 1]; if (startIndex === previous[0]) { previous[1] = Math.max(previous[1], amount); } else { acc.push([startIndex, amount]); } return acc; }, [sorted[0]]); /* shift further indexes */ let shift = 0; for (let i = 0; i < merged.length; ++i) { merged[i][0] += shift; shift += merged[i][1]; } return merged; } function isPositiveInteger(n) { return Number.isInteger(n) && n > 0; } function isRowOrColumnRange(leftCorner, width, height) { return leftCorner.row === 0 && isPositiveInteger(width) && height === Number.POSITIVE_INFINITY || leftCorner.col === 0 && isPositiveInteger(height) && width === Number.POSITIVE_INFINITY; } /***/ }), /* 117 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddColumnsTransformer: () => (/* binding */ AddColumnsTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AddColumnsTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(columnsSpan) { super(); this.columnsSpan = columnsSpan; } get sheet() { return this.columnsSpan.sheet; } isIrreversible() { return false; } transformRowRangeAst(ast, _formulaAddress) { return ast; } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(_start, _end, _formulaAddress) { throw Error('Not implemented'); } transformColumnRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformCellAddress(dependencyAddress, formulaAddress) { const absoluteDependencySheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(dependencyAddress, formulaAddress); // Case 4 and 5 if (absoluteDependencySheet !== this.columnsSpan.sheet && formulaAddress.sheet !== this.columnsSpan.sheet) { return false; } const absolutizedDependencyAddress = dependencyAddress.toSimpleColumnAddress(formulaAddress); // Case 3 if (absoluteDependencySheet === this.columnsSpan.sheet && formulaAddress.sheet !== this.columnsSpan.sheet) { if (this.columnsSpan.columnStart <= absolutizedDependencyAddress.col) { return dependencyAddress.shiftedByColumns(this.columnsSpan.numberOfColumns); } else { return false; } } // Case 2 if (formulaAddress.sheet === this.columnsSpan.sheet && absoluteDependencySheet !== this.columnsSpan.sheet) { if (dependencyAddress.isColumnAbsolute()) { return false; } if (formulaAddress.col < this.columnsSpan.columnStart) { return false; } return dependencyAddress.shiftedByColumns(-this.columnsSpan.numberOfColumns); } // Case 1 if (dependencyAddress.isColumnAbsolute()) { if (dependencyAddress.col < this.columnsSpan.columnStart) { // Case Aa return false; } else { // Case Ab return dependencyAddress.shiftedByColumns(this.columnsSpan.numberOfColumns); } } else { const absolutizedDependencyAddress = dependencyAddress.toSimpleColumnAddress(formulaAddress); if (absolutizedDependencyAddress.col < this.columnsSpan.columnStart) { if (formulaAddress.col < this.columnsSpan.columnStart) { // Case Raa return false; } else { // Case Rab return dependencyAddress.shiftedByColumns(-this.columnsSpan.numberOfColumns); } } else { if (formulaAddress.col < this.columnsSpan.columnStart) { // Case Rba return dependencyAddress.shiftedByColumns(this.columnsSpan.numberOfColumns); } else { // Case Rbb return false; } } } } fixNodeAddress(address) { if (this.columnsSpan.sheet === address.sheet && this.columnsSpan.columnStart <= address.col) { return Object.assign(Object.assign({}, address), { col: address.col + this.columnsSpan.numberOfColumns }); } else { return address; } } transformRange(start, end, formulaAddress) { const newStart = this.transformCellAddress(start, formulaAddress); const newEnd = this.transformCellAddress(end, formulaAddress); if (newStart === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF || newEnd === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } else if (newStart || newEnd) { return [newStart || start, newEnd || end]; } else { return false; } } } /***/ }), /* 118 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Transformer: () => (/* binding */ Transformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class Transformer { performEagerTransformations(graph, parser) { for (const node of graph.arrayFormulaNodes()) { const [newAst, newAddress] = this.transformSingleAst(node.getFormula(graph.lazilyTransformingAstService), node.getAddress(graph.lazilyTransformingAstService)); const cachedAst = parser.rememberNewAst(newAst); node.setFormula(cachedAst); node.setAddress(newAddress); } } transformSingleAst(ast, address) { const newAst = this.transformAst(ast, address); const newAddress = this.fixNodeAddress(address); return [newAst, newAddress]; } transformAst(ast, address) { switch (ast.type) { case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.CELL_REFERENCE: { return this.transformCellReferenceAst(ast, address); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.CELL_RANGE: { return this.transformCellRangeAst(ast, address); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.COLUMN_RANGE: { return this.transformColumnRangeAst(ast, address); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ROW_RANGE: { return this.transformRowRangeAst(ast, address); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.EMPTY: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ERROR: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.NUMBER: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.NAMED_EXPRESSION: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ERROR_WITH_RAW_INPUT: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.STRING: { return ast; } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PERCENT_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.MINUS_UNARY_OP: case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PLUS_UNARY_OP: { return Object.assign(Object.assign({}, ast), { value: this.transformAst(ast.value, address) }); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.FUNCTION_CALL: { return Object.assign(Object.assign({}, ast), { procedureName: ast.procedureName, args: ast.args.map(arg => this.transformAst(arg, address)) }); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.PARENTHESIS: { return Object.assign(Object.assign({}, ast), { expression: this.transformAst(ast.expression, address) }); } case _parser__WEBPACK_IMPORTED_MODULE_1__.AstNodeType.ARRAY: { return Object.assign(Object.assign({}, ast), { args: ast.args.map(row => row.map(val => this.transformAst(val, address))) }); } default: { return Object.assign(Object.assign({}, ast), { left: this.transformAst(ast.left, address), right: this.transformAst(ast.right, address) }); } } } transformCellReferenceAst(ast, formulaAddress) { const newCellAddress = this.transformCellAddress(ast.reference, formulaAddress); if (newCellAddress instanceof _parser__WEBPACK_IMPORTED_MODULE_1__.CellAddress) { return Object.assign(Object.assign({}, ast), { reference: newCellAddress }); } else if (newCellAddress === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return (0,_parser__WEBPACK_IMPORTED_MODULE_1__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF)); } else { return ast; } } transformCellRangeAst(ast, formulaAddress) { const newRange = this.transformCellRange(ast.start, ast.end, formulaAddress); if (Array.isArray(newRange)) { return Object.assign(Object.assign({}, ast), { start: newRange[0], end: newRange[1] }); } else if (newRange === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return (0,_parser__WEBPACK_IMPORTED_MODULE_1__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF)); } else { return ast; } } transformColumnRangeAst(ast, formulaAddress) { const newRange = this.transformColumnRange(ast.start, ast.end, formulaAddress); if (Array.isArray(newRange)) { return Object.assign(Object.assign({}, ast), { start: newRange[0], end: newRange[1] }); } else if (newRange === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return (0,_parser__WEBPACK_IMPORTED_MODULE_1__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF)); } else { return ast; } } transformRowRangeAst(ast, formulaAddress) { const newRange = this.transformRowRange(ast.start, ast.end, formulaAddress); if (Array.isArray(newRange)) { return Object.assign(Object.assign({}, ast), { start: newRange[0], end: newRange[1] }); } else if (newRange === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return (0,_parser__WEBPACK_IMPORTED_MODULE_1__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF)); } else { return ast; } } } /***/ }), /* 119 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddRowsTransformer: () => (/* binding */ AddRowsTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AddRowsTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(rowsSpan) { super(); this.rowsSpan = rowsSpan; } get sheet() { return this.rowsSpan.sheet; } isIrreversible() { return false; } transformColumnRangeAst(ast, _formulaAddress) { return ast; } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformColumnRange(_start, _end, _formulaAddress) { throw Error('Not implemented'); } transformCellAddress(dependencyAddress, formulaAddress) { const absoluteDependencySheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(dependencyAddress, formulaAddress); // Case 4 and 5 if (absoluteDependencySheet !== this.rowsSpan.sheet && formulaAddress.sheet !== this.rowsSpan.sheet) { return false; } const absolutizedDependencyAddress = dependencyAddress.toSimpleRowAddress(formulaAddress); // Case 3 if (absoluteDependencySheet === this.rowsSpan.sheet && formulaAddress.sheet !== this.rowsSpan.sheet) { if (this.rowsSpan.rowStart <= absolutizedDependencyAddress.row) { return dependencyAddress.shiftedByRows(this.rowsSpan.numberOfRows); } else { return false; } } // Case 2 if (formulaAddress.sheet === this.rowsSpan.sheet && absoluteDependencySheet !== this.rowsSpan.sheet) { if (dependencyAddress.isRowAbsolute()) { return false; } if (formulaAddress.row < this.rowsSpan.rowStart) { return false; } return dependencyAddress.shiftedByRows(-this.rowsSpan.numberOfRows); } // Case 1 if (dependencyAddress.isRowAbsolute()) { if (dependencyAddress.row < this.rowsSpan.rowStart) { // Case Aa return false; } else { // Case Ab return dependencyAddress.shiftedByRows(this.rowsSpan.numberOfRows); } } else { if (absolutizedDependencyAddress.row < this.rowsSpan.rowStart) { if (formulaAddress.row < this.rowsSpan.rowStart) { // Case Raa return false; } else { // Case Rab return dependencyAddress.shiftedByRows(-this.rowsSpan.numberOfRows); } } else { if (formulaAddress.row < this.rowsSpan.rowStart) { // Case Rba return dependencyAddress.shiftedByRows(this.rowsSpan.numberOfRows); } else { // Case Rbb return false; } } } } fixNodeAddress(address) { if (this.rowsSpan.sheet === address.sheet && this.rowsSpan.rowStart <= address.row) { return Object.assign(Object.assign({}, address), { row: address.row + this.rowsSpan.numberOfRows }); } else { return address; } } transformRange(start, end, formulaAddress) { const newStart = this.transformCellAddress(start, formulaAddress); const newEnd = this.transformCellAddress(end, formulaAddress); if (newStart === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF || newEnd === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } else if (newStart || newEnd) { return [newStart || start, newEnd || end]; } else { return false; } } } /***/ }), /* 120 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CleanOutOfScopeDependenciesTransformer: () => (/* binding */ CleanOutOfScopeDependenciesTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class CleanOutOfScopeDependenciesTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(sheet) { super(); this.sheet = sheet; } isIrreversible() { return true; } fixNodeAddress(address) { return address; } transformCellAddress(dependencyAddress, formulaAddress) { return dependencyAddress.isInvalid(formulaAddress) ? _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF : false; } transformCellRange(start, end, formulaAddress) { return start.isInvalid(formulaAddress) || end.isInvalid(formulaAddress) ? _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF : false; } transformColumnRange(start, end, formulaAddress) { return start.isInvalid(formulaAddress) || end.isInvalid(formulaAddress) ? _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF : false; } transformRowRange(start, end, formulaAddress) { return start.isInvalid(formulaAddress) || end.isInvalid(formulaAddress) ? _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF : false; } } /***/ }), /* 121 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DependentFormulaTransformer: () => (/* binding */ DependentFormulaTransformer), /* harmony export */ MoveCellsTransformer: () => (/* binding */ MoveCellsTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); /* harmony import */ var _parser_RowAddress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class MoveCellsTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_3__.Transformer { constructor(sourceRange, toRight, toBottom, toSheet) { super(); this.sourceRange = sourceRange; this.toRight = toRight; this.toBottom = toBottom; this.toSheet = toSheet; this.dependentFormulaTransformer = new DependentFormulaTransformer(sourceRange, toRight, toBottom, toSheet); } get sheet() { return this.sourceRange.sheet; } isIrreversible() { return true; } transformSingleAst(ast, address) { if (this.sourceRange.addressInRange(address)) { const newAst = this.transformAst(ast, address); return [newAst, this.fixNodeAddress(address)]; } else { return this.dependentFormulaTransformer.transformSingleAst(ast, address); } } fixNodeAddress(address) { return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.toSheet, address.col + this.toRight, address.row + this.toBottom); } transformCellAddress(dependencyAddress, formulaAddress) { return this.transformAddress(dependencyAddress, formulaAddress); } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformColumnRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformAddress(dependencyAddress, formulaAddress) { const sourceRange = this.sourceRange; if (dependencyAddress instanceof _parser__WEBPACK_IMPORTED_MODULE_1__.CellAddress) { const absoluteDependencyAddress = dependencyAddress.toSimpleCellAddress(formulaAddress); if (sourceRange.addressInRange(absoluteDependencyAddress)) { // If dependency is internal, move only absolute dimensions return dependencyAddress.shiftAbsoluteDimensions(this.toRight, this.toBottom); } } return dependencyAddress.shiftRelativeDimensions(-this.toRight, -this.toBottom); } transformRange(start, end, formulaAddress) { const sourceRange = this.sourceRange; if (start instanceof _parser__WEBPACK_IMPORTED_MODULE_1__.CellAddress && end instanceof _parser__WEBPACK_IMPORTED_MODULE_1__.CellAddress) { const absoluteStart = start.toSimpleCellAddress(formulaAddress); const absoluteEnd = end.toSimpleCellAddress(formulaAddress); if (sourceRange.addressInRange(absoluteStart) && sourceRange.addressInRange(absoluteEnd)) { return [start.shiftAbsoluteDimensions(this.toRight, this.toBottom), end.shiftAbsoluteDimensions(this.toRight, this.toBottom)]; } } return [start.shiftRelativeDimensions(-this.toRight, -this.toBottom), end.shiftRelativeDimensions(-this.toRight, -this.toBottom)]; } } class DependentFormulaTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_3__.Transformer { constructor(sourceRange, toRight, toBottom, toSheet) { super(); this.sourceRange = sourceRange; this.toRight = toRight; this.toBottom = toBottom; this.toSheet = toSheet; } get sheet() { return this.sourceRange.sheet; } isIrreversible() { return true; } fixNodeAddress(address) { return address; } transformCellAddress(dependencyAddress, formulaAddress) { if (this.shouldMove(dependencyAddress, formulaAddress)) { return dependencyAddress.moved(this.toSheet, this.toRight, this.toBottom); } return false; } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformColumnRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } shouldMove(dependencyAddress, formulaAddress) { if (dependencyAddress instanceof _parser__WEBPACK_IMPORTED_MODULE_1__.CellAddress) { return this.sourceRange.addressInRange(dependencyAddress.toSimpleCellAddress(formulaAddress)); } else if (dependencyAddress instanceof _parser_RowAddress__WEBPACK_IMPORTED_MODULE_2__.RowAddress) { return this.sourceRange.rowInRange(dependencyAddress.toSimpleRowAddress(formulaAddress)) && !this.sourceRange.isFinite(); } else { return this.sourceRange.columnInRange(dependencyAddress.toSimpleColumnAddress(formulaAddress)) && !this.sourceRange.isFinite(); } } transformRange(start, end, formulaAddress) { const newStart = this.transformCellAddress(start, formulaAddress); const newEnd = this.transformCellAddress(end, formulaAddress); if (newStart && newEnd) { return [newStart, newEnd]; } return false; } } /***/ }), /* 122 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RemoveColumnsTransformer: () => (/* binding */ RemoveColumnsTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RemoveColumnsTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(columnsSpan) { super(); this.columnsSpan = columnsSpan; } get sheet() { return this.columnsSpan.sheet; } isIrreversible() { return true; } transformRowRangeAst(ast, _formulaAddress) { return ast; } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(_start, _end, _formulaAddress) { throw Error('Not implemented'); } transformColumnRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformCellAddress(dependencyAddress, formulaAddress) { const absoluteDependencySheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(dependencyAddress, formulaAddress); // Case 4 if (this.columnsSpan.sheet !== formulaAddress.sheet && this.columnsSpan.sheet !== absoluteDependencySheet) { return false; } // Case 3 -- removed column in same sheet where dependency is but formula in different if (this.columnsSpan.sheet !== formulaAddress.sheet && this.columnsSpan.sheet === absoluteDependencySheet) { const absoluteDependencyAddress = dependencyAddress.toSimpleColumnAddress(formulaAddress); if (absoluteDependencyAddress.col < this.columnsSpan.columnStart) { // 3.ARa return false; } else if (absoluteDependencyAddress.col > this.columnsSpan.columnEnd) { // 3.ARb return dependencyAddress.shiftedByColumns(-this.columnsSpan.numberOfColumns); } } // Case 2 -- removed column in same sheet where formula but dependency in different sheet if (this.columnsSpan.sheet === formulaAddress.sheet && this.columnsSpan.sheet !== absoluteDependencySheet) { if (dependencyAddress.isColumnAbsolute()) { // 2.A return false; } else { if (formulaAddress.col < this.columnsSpan.columnStart) { // 2.Ra return false; } else if (formulaAddress.col > this.columnsSpan.columnEnd) { // 2.Rb return dependencyAddress.shiftedByColumns(this.columnsSpan.numberOfColumns); } } } // Case 1 -- same sheet if (this.columnsSpan.sheet === formulaAddress.sheet && this.columnsSpan.sheet === absoluteDependencySheet) { if (dependencyAddress.isColumnAbsolute()) { if (dependencyAddress.col < this.columnsSpan.columnStart) { // 1.Aa return false; } else if (dependencyAddress.col > this.columnsSpan.columnEnd) { // 1.Ab return dependencyAddress.shiftedByColumns(-this.columnsSpan.numberOfColumns); } } else { const absoluteDependencyAddress = dependencyAddress.toSimpleColumnAddress(formulaAddress); if (absoluteDependencyAddress.col < this.columnsSpan.columnStart) { if (formulaAddress.col < this.columnsSpan.columnStart) { // 1.Raa return false; } else if (formulaAddress.col > this.columnsSpan.columnEnd) { // 1.Rab return dependencyAddress.shiftedByColumns(this.columnsSpan.numberOfColumns); } } else if (absoluteDependencyAddress.col > this.columnsSpan.columnEnd) { if (formulaAddress.col < this.columnsSpan.columnStart) { // 1.Rba return dependencyAddress.shiftedByColumns(-this.columnsSpan.numberOfColumns); } else if (formulaAddress.col > this.columnsSpan.columnEnd) { // 1.Rbb return false; } } } } // 1.Ac, 1.Rca, 1.Rcb, 3.Ac, 3.Rca, 3.Rcb return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } fixNodeAddress(address) { if (this.columnsSpan.sheet === address.sheet && this.columnsSpan.columnStart <= address.col) { return Object.assign(Object.assign({}, address), { col: address.col - this.columnsSpan.numberOfColumns }); } else { return address; } } transformRange(start, end, formulaAddress) { const startSheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(start, formulaAddress); let actualStart = start; let actualEnd = end; if (this.columnsSpan.sheet === startSheet) { const startSCA = start.toSimpleColumnAddress(formulaAddress); const endSCA = end.toSimpleColumnAddress(formulaAddress); if (this.columnsSpan.columnStart <= startSCA.col && this.columnsSpan.columnEnd >= endSCA.col) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } if (startSCA.col >= this.columnsSpan.columnStart && startSCA.col <= this.columnsSpan.columnEnd) { actualStart = start.shiftedByColumns(this.columnsSpan.columnEnd - startSCA.col + 1); } if (endSCA.col >= this.columnsSpan.columnStart && endSCA.col <= this.columnsSpan.columnEnd) { actualEnd = end.shiftedByColumns(-(endSCA.col - this.columnsSpan.columnStart + 1)); } } const newStart = this.transformCellAddress(actualStart, formulaAddress); const newEnd = this.transformCellAddress(actualEnd, formulaAddress); if (newStart === false && newEnd === false) { return [actualStart, actualEnd]; } else if (newStart === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF || newEnd === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { throw Error('Cannot happen'); } else { return [newStart || actualStart, newEnd || actualEnd]; } } } /***/ }), /* 123 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RemoveRowsTransformer: () => (/* binding */ RemoveRowsTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RemoveRowsTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(rowsSpan) { super(); this.rowsSpan = rowsSpan; } get sheet() { return this.rowsSpan.sheet; } isIrreversible() { return true; } transformColumnRangeAst(ast, _formulaAddress) { return ast; } transformCellAddress(dependencyAddress, formulaAddress) { const absoluteDependencySheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(dependencyAddress, formulaAddress); // Case 4 if (this.rowsSpan.sheet !== formulaAddress.sheet && this.rowsSpan.sheet !== absoluteDependencySheet) { return false; } // Case 3 -- removed row in same sheet where dependency is but formula in different if (this.rowsSpan.sheet !== formulaAddress.sheet && this.rowsSpan.sheet === absoluteDependencySheet) { const absoluteDependencyAddress = dependencyAddress.toSimpleRowAddress(formulaAddress); if (absoluteDependencyAddress.row < this.rowsSpan.rowStart) { // 3.ARa return false; } else if (absoluteDependencyAddress.row > this.rowsSpan.rowEnd) { // 3.ARb return dependencyAddress.shiftedByRows(-this.rowsSpan.numberOfRows); } } // Case 2 -- removed row in same sheet where formula but dependency in different sheet if (this.rowsSpan.sheet === formulaAddress.sheet && this.rowsSpan.sheet !== absoluteDependencySheet) { if (dependencyAddress.isRowAbsolute()) { // 2.A return false; } else { if (formulaAddress.row < this.rowsSpan.rowStart) { // 2.Ra return false; } else if (formulaAddress.row > this.rowsSpan.rowEnd) { // 2.Rb return dependencyAddress.shiftedByRows(this.rowsSpan.numberOfRows); } } } // Case 1 -- same sheet if (this.rowsSpan.sheet === formulaAddress.sheet && this.rowsSpan.sheet === absoluteDependencySheet) { if (dependencyAddress.isRowAbsolute()) { if (dependencyAddress.row < this.rowsSpan.rowStart) { // 1.Aa return false; } else if (dependencyAddress.row > this.rowsSpan.rowEnd) { // 1.Ab return dependencyAddress.shiftedByRows(-this.rowsSpan.numberOfRows); } } else { const absoluteDependencyAddress = dependencyAddress.toSimpleRowAddress(formulaAddress); if (absoluteDependencyAddress.row < this.rowsSpan.rowStart) { if (formulaAddress.row < this.rowsSpan.rowStart) { // 1.Raa return false; } else if (formulaAddress.row > this.rowsSpan.rowEnd) { // 1.Rab return dependencyAddress.shiftedByRows(this.rowsSpan.numberOfRows); } } else if (absoluteDependencyAddress.row > this.rowsSpan.rowEnd) { if (formulaAddress.row < this.rowsSpan.rowStart) { // 1.Rba return dependencyAddress.shiftedByRows(-this.rowsSpan.numberOfRows); } else if (formulaAddress.row > this.rowsSpan.rowEnd) { // 1.Rbb return false; } } } } // 1.Ac, 1.Rca, 1.Rcb, 3.Ac, 3.Rca, 3.Rcb return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } transformCellRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformRowRange(start, end, formulaAddress) { return this.transformRange(start, end, formulaAddress); } transformColumnRange(_start, _end, _formulaAddress) { throw Error('Not implemented'); } fixNodeAddress(address) { if (this.rowsSpan.sheet === address.sheet && this.rowsSpan.rowStart <= address.row) { return Object.assign(Object.assign({}, address), { row: address.row - this.rowsSpan.numberOfRows }); } else { return address; } } transformRange(start, end, formulaAddress) { const startSheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(start, formulaAddress); let actualStart = start; let actualEnd = end; if (this.rowsSpan.sheet === startSheet) { const startSCA = start.toSimpleRowAddress(formulaAddress); const endSCA = end.toSimpleRowAddress(formulaAddress); if (this.rowsSpan.rowStart <= startSCA.row && this.rowsSpan.rowEnd >= endSCA.row) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } if (startSCA.row >= this.rowsSpan.rowStart && startSCA.row <= this.rowsSpan.rowEnd) { actualStart = start.shiftedByRows(this.rowsSpan.rowEnd - startSCA.row + 1); } if (endSCA.row >= this.rowsSpan.rowStart && endSCA.row <= this.rowsSpan.rowEnd) { actualEnd = end.shiftedByRows(-(endSCA.row - this.rowsSpan.rowStart + 1)); } } const newStart = this.transformCellAddress(actualStart, formulaAddress); const newEnd = this.transformCellAddress(actualEnd, formulaAddress); if (newStart === false && newEnd === false) { return [actualStart, actualEnd]; } else if (newStart === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF || newEnd === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } else { return [newStart || actualStart, newEnd || actualEnd]; } } } /***/ }), /* 124 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RemoveSheetTransformer: () => (/* binding */ RemoveSheetTransformer) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(118); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RemoveSheetTransformer extends _Transformer__WEBPACK_IMPORTED_MODULE_1__.Transformer { constructor(sheet) { super(); this.sheet = sheet; } isIrreversible() { return true; } performEagerTransformations(graph, _parser) { for (const node of graph.arrayFormulaNodes()) { const [newAst] = this.transformSingleAst(node.getFormula(graph.lazilyTransformingAstService), node.getAddress(graph.lazilyTransformingAstService)); node.setFormula(newAst); } } fixNodeAddress(address) { return address; } transformCellAddress(dependencyAddress, _formulaAddress) { return this.transformAddress(dependencyAddress); } transformCellRange(start, _end, _formulaAddress) { return this.transformAddress(start); } transformColumnRange(start, _end, _formulaAddress) { return this.transformAddress(start); } transformRowRange(start, _end, _formulaAddress) { return this.transformAddress(start); } transformAddress(address) { if (address.sheet === this.sheet) { return _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF; } return false; } } /***/ }), /* 125 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ findBoundaries: () => (/* binding */ findBoundaries), /* harmony export */ validateAsSheet: () => (/* binding */ validateAsSheet) /* harmony export */ }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function validateAsSheet(sheet) { if (!Array.isArray(sheet)) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentsError('an array of arrays.'); } for (let i = 0; i < sheet.length; i++) { if (!Array.isArray(sheet[i])) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.InvalidArgumentsError('an array of arrays.'); } } } /** * Returns actual width, height and fill ratio of a sheet * * @param sheet - two-dimmensional array sheet representation */ function findBoundaries(sheet) { let width = 0; let height = 0; let cellsCount = 0; for (let currentRow = 0; currentRow < sheet.length; currentRow++) { let currentRowWidth = 0; for (let currentCol = 0; currentCol < sheet[currentRow].length; currentCol++) { const currentValue = sheet[currentRow][currentCol]; if (currentValue === undefined || currentValue === null) { continue; } currentRowWidth = currentCol + 1; ++cellsCount; } width = Math.max(width, currentRowWidth); if (currentRowWidth > 0) { height = currentRow + 1; } } const sheetSize = width * height; return { height: height, width: width, fill: sheetSize === 0 ? 0 : cellsCount / sheetSize }; } /***/ }), /* 126 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddColumnsUndoEntry: () => (/* binding */ AddColumnsUndoEntry), /* harmony export */ AddNamedExpressionUndoEntry: () => (/* binding */ AddNamedExpressionUndoEntry), /* harmony export */ AddRowsUndoEntry: () => (/* binding */ AddRowsUndoEntry), /* harmony export */ AddSheetUndoEntry: () => (/* binding */ AddSheetUndoEntry), /* harmony export */ BaseUndoEntry: () => (/* binding */ BaseUndoEntry), /* harmony export */ BatchUndoEntry: () => (/* binding */ BatchUndoEntry), /* harmony export */ ChangeNamedExpressionUndoEntry: () => (/* binding */ ChangeNamedExpressionUndoEntry), /* harmony export */ ClearSheetUndoEntry: () => (/* binding */ ClearSheetUndoEntry), /* harmony export */ MoveCellsUndoEntry: () => (/* binding */ MoveCellsUndoEntry), /* harmony export */ MoveColumnsUndoEntry: () => (/* binding */ MoveColumnsUndoEntry), /* harmony export */ MoveRowsUndoEntry: () => (/* binding */ MoveRowsUndoEntry), /* harmony export */ PasteUndoEntry: () => (/* binding */ PasteUndoEntry), /* harmony export */ RemoveColumnsUndoEntry: () => (/* binding */ RemoveColumnsUndoEntry), /* harmony export */ RemoveNamedExpressionUndoEntry: () => (/* binding */ RemoveNamedExpressionUndoEntry), /* harmony export */ RemoveRowsUndoEntry: () => (/* binding */ RemoveRowsUndoEntry), /* harmony export */ RemoveSheetUndoEntry: () => (/* binding */ RemoveSheetUndoEntry), /* harmony export */ RenameSheetUndoEntry: () => (/* binding */ RenameSheetUndoEntry), /* harmony export */ SetCellContentsUndoEntry: () => (/* binding */ SetCellContentsUndoEntry), /* harmony export */ SetColumnOrderUndoEntry: () => (/* binding */ SetColumnOrderUndoEntry), /* harmony export */ SetRowOrderUndoEntry: () => (/* binding */ SetRowOrderUndoEntry), /* harmony export */ SetSheetContentUndoEntry: () => (/* binding */ SetSheetContentUndoEntry), /* harmony export */ UndoRedo: () => (/* binding */ UndoRedo) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _Operations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(116); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class BaseUndoEntry {} class RemoveRowsUndoEntry extends BaseUndoEntry { constructor(command, rowsRemovals) { super(); this.command = command; this.rowsRemovals = rowsRemovals; } doUndo(undoRedo) { undoRedo.undoRemoveRows(this); } doRedo(undoRedo) { undoRedo.redoRemoveRows(this); } } class MoveCellsUndoEntry extends BaseUndoEntry { constructor(sourceLeftCorner, width, height, destinationLeftCorner, overwrittenCellsData, addedGlobalNamedExpressions, version) { super(); this.sourceLeftCorner = sourceLeftCorner; this.width = width; this.height = height; this.destinationLeftCorner = destinationLeftCorner; this.overwrittenCellsData = overwrittenCellsData; this.addedGlobalNamedExpressions = addedGlobalNamedExpressions; this.version = version; } doUndo(undoRedo) { undoRedo.undoMoveCells(this); } doRedo(undoRedo) { undoRedo.redoMoveCells(this); } } class AddRowsUndoEntry extends BaseUndoEntry { constructor(command) { super(); this.command = command; } doUndo(undoRedo) { undoRedo.undoAddRows(this); } doRedo(undoRedo) { undoRedo.redoAddRows(this); } } class SetRowOrderUndoEntry extends BaseUndoEntry { constructor(sheetId, rowMapping, oldContent) { super(); this.sheetId = sheetId; this.rowMapping = rowMapping; this.oldContent = oldContent; } doUndo(undoRedo) { undoRedo.undoSetRowOrder(this); } doRedo(undoRedo) { undoRedo.redoSetRowOrder(this); } } class SetColumnOrderUndoEntry extends BaseUndoEntry { constructor(sheetId, columnMapping, oldContent) { super(); this.sheetId = sheetId; this.columnMapping = columnMapping; this.oldContent = oldContent; } doUndo(undoRedo) { undoRedo.undoSetColumnOrder(this); } doRedo(undoRedo) { undoRedo.redoSetColumnOrder(this); } } class SetSheetContentUndoEntry extends BaseUndoEntry { constructor(sheetId, oldSheetContent, newSheetContent) { super(); this.sheetId = sheetId; this.oldSheetContent = oldSheetContent; this.newSheetContent = newSheetContent; } doUndo(undoRedo) { undoRedo.undoSetSheetContent(this); } doRedo(undoRedo) { undoRedo.redoSetSheetContent(this); } } class MoveRowsUndoEntry extends BaseUndoEntry { constructor(sheet, startRow, numberOfRows, targetRow, version) { super(); this.sheet = sheet; this.startRow = startRow; this.numberOfRows = numberOfRows; this.targetRow = targetRow; this.version = version; this.undoStart = this.startRow < this.targetRow ? this.targetRow - this.numberOfRows : this.targetRow; this.undoEnd = this.startRow > this.targetRow ? this.startRow + this.numberOfRows : this.startRow; } doUndo(undoRedo) { undoRedo.undoMoveRows(this); } doRedo(undoRedo) { undoRedo.redoMoveRows(this); } } class MoveColumnsUndoEntry extends BaseUndoEntry { constructor(sheet, startColumn, numberOfColumns, targetColumn, version) { super(); this.sheet = sheet; this.startColumn = startColumn; this.numberOfColumns = numberOfColumns; this.targetColumn = targetColumn; this.version = version; this.undoStart = this.startColumn < this.targetColumn ? this.targetColumn - this.numberOfColumns : this.targetColumn; this.undoEnd = this.startColumn > this.targetColumn ? this.startColumn + this.numberOfColumns : this.startColumn; } doUndo(undoRedo) { undoRedo.undoMoveColumns(this); } doRedo(undoRedo) { undoRedo.redoMoveColumns(this); } } class AddColumnsUndoEntry extends BaseUndoEntry { constructor(command) { super(); this.command = command; } doUndo(undoRedo) { undoRedo.undoAddColumns(this); } doRedo(undoRedo) { undoRedo.redoAddColumns(this); } } class RemoveColumnsUndoEntry extends BaseUndoEntry { constructor(command, columnsRemovals) { super(); this.command = command; this.columnsRemovals = columnsRemovals; } doUndo(undoRedo) { undoRedo.undoRemoveColumns(this); } doRedo(undoRedo) { undoRedo.redoRemoveColumns(this); } } class AddSheetUndoEntry extends BaseUndoEntry { constructor(sheetName) { super(); this.sheetName = sheetName; } doUndo(undoRedo) { undoRedo.undoAddSheet(this); } doRedo(undoRedo) { undoRedo.redoAddSheet(this); } } class RemoveSheetUndoEntry extends BaseUndoEntry { constructor(sheetName, sheetId, oldSheetContent, scopedNamedExpressions, version) { super(); this.sheetName = sheetName; this.sheetId = sheetId; this.oldSheetContent = oldSheetContent; this.scopedNamedExpressions = scopedNamedExpressions; this.version = version; } doUndo(undoRedo) { undoRedo.undoRemoveSheet(this); } doRedo(undoRedo) { undoRedo.redoRemoveSheet(this); } } class RenameSheetUndoEntry extends BaseUndoEntry { constructor(sheetId, oldName, newName) { super(); this.sheetId = sheetId; this.oldName = oldName; this.newName = newName; } doUndo(undoRedo) { undoRedo.undoRenameSheet(this); } doRedo(undoRedo) { undoRedo.redoRenameSheet(this); } } class ClearSheetUndoEntry extends BaseUndoEntry { constructor(sheetId, oldSheetContent) { super(); this.sheetId = sheetId; this.oldSheetContent = oldSheetContent; } doUndo(undoRedo) { undoRedo.undoClearSheet(this); } doRedo(undoRedo) { undoRedo.redoClearSheet(this); } } class SetCellContentsUndoEntry extends BaseUndoEntry { constructor(cellContents) { super(); this.cellContents = cellContents; } doUndo(undoRedo) { undoRedo.undoSetCellContents(this); } doRedo(undoRedo) { undoRedo.redoSetCellContents(this); } } class PasteUndoEntry extends BaseUndoEntry { constructor(targetLeftCorner, oldContent, newContent, addedGlobalNamedExpressions) { super(); this.targetLeftCorner = targetLeftCorner; this.oldContent = oldContent; this.newContent = newContent; this.addedGlobalNamedExpressions = addedGlobalNamedExpressions; } doUndo(undoRedo) { undoRedo.undoPaste(this); } doRedo(undoRedo) { undoRedo.redoPaste(this); } } class AddNamedExpressionUndoEntry extends BaseUndoEntry { constructor(name, newContent, scope, options) { super(); this.name = name; this.newContent = newContent; this.scope = scope; this.options = options; } doUndo(undoRedo) { undoRedo.undoAddNamedExpression(this); } doRedo(undoRedo) { undoRedo.redoAddNamedExpression(this); } } class RemoveNamedExpressionUndoEntry extends BaseUndoEntry { constructor(namedExpression, content, scope) { super(); this.namedExpression = namedExpression; this.content = content; this.scope = scope; } doUndo(undoRedo) { undoRedo.undoRemoveNamedExpression(this); } doRedo(undoRedo) { undoRedo.redoRemoveNamedExpression(this); } } class ChangeNamedExpressionUndoEntry extends BaseUndoEntry { constructor(namedExpression, newContent, oldContent, scope, options) { super(); this.namedExpression = namedExpression; this.newContent = newContent; this.oldContent = oldContent; this.scope = scope; this.options = options; } doUndo(undoRedo) { undoRedo.undoChangeNamedExpression(this); } doRedo(undoRedo) { undoRedo.redoChangeNamedExpression(this); } } class BatchUndoEntry extends BaseUndoEntry { constructor() { super(...arguments); this.operations = []; } add(operation) { this.operations.push(operation); } *reversedOperations() { for (let i = this.operations.length - 1; i >= 0; i--) { yield this.operations[i]; } } doUndo(undoRedo) { undoRedo.undoBatch(this); } doRedo(undoRedo) { undoRedo.redoBatch(this); } } class UndoRedo { constructor(config, operations) { this.operations = operations; this.oldData = new Map(); this.undoStack = []; this.redoStack = []; this.undoLimit = config.undoLimit; } saveOperation(operation) { if (this.batchUndoEntry !== undefined) { this.batchUndoEntry.add(operation); } else { this.addUndoEntry(operation); } } beginBatchMode() { this.batchUndoEntry = new BatchUndoEntry(); } commitBatchMode() { if (this.batchUndoEntry === undefined) { throw Error('Batch mode wasn\'t started'); } this.addUndoEntry(this.batchUndoEntry); this.batchUndoEntry = undefined; } storeDataForVersion(version, address, astHash) { if (!this.oldData.has(version)) { this.oldData.set(version, []); } const currentOldData = this.oldData.get(version); currentOldData.push([address, astHash]); } clearRedoStack() { this.redoStack = []; } clearUndoStack() { this.undoStack = []; } isUndoStackEmpty() { return this.undoStack.length === 0; } isRedoStackEmpty() { return this.redoStack.length === 0; } undo() { const operation = this.undoStack.pop(); if (!operation) { throw Error('Attempted to undo without operation on stack'); } this.undoEntry(operation); this.redoStack.push(operation); } undoBatch(batchOperation) { for (const operation of batchOperation.reversedOperations()) { this.undoEntry(operation); } } undoRemoveRows(operation) { this.operations.forceApplyPostponedTransformations(); const { command: { sheet }, rowsRemovals } = operation; for (let i = rowsRemovals.length - 1; i >= 0; --i) { const rowsRemoval = rowsRemovals[i]; this.operations.addRows(new _Operations__WEBPACK_IMPORTED_MODULE_1__.AddRowsCommand(sheet, [[rowsRemoval.rowFrom, rowsRemoval.rowCount]])); for (const { address, cellType } of rowsRemoval.removedCells) { this.operations.restoreCell(address, cellType); } this.restoreOldDataFromVersion(rowsRemoval.version - 1); } } undoRemoveColumns(operation) { this.operations.forceApplyPostponedTransformations(); const { command: { sheet }, columnsRemovals } = operation; for (let i = columnsRemovals.length - 1; i >= 0; --i) { const columnsRemoval = columnsRemovals[i]; this.operations.addColumns(new _Operations__WEBPACK_IMPORTED_MODULE_1__.AddColumnsCommand(sheet, [[columnsRemoval.columnFrom, columnsRemoval.columnCount]])); for (const { address, cellType } of columnsRemoval.removedCells) { this.operations.restoreCell(address, cellType); } this.restoreOldDataFromVersion(columnsRemoval.version - 1); } } undoAddRows(operation) { const addedRowsSpans = operation.command.rowsSpans(); for (let i = addedRowsSpans.length - 1; i >= 0; --i) { const addedRows = addedRowsSpans[i]; this.operations.removeRows(new _Operations__WEBPACK_IMPORTED_MODULE_1__.RemoveRowsCommand(operation.command.sheet, [[addedRows.rowStart, addedRows.numberOfRows]])); } } undoAddColumns(operation) { const addedColumnsSpans = operation.command.columnsSpans(); for (let i = addedColumnsSpans.length - 1; i >= 0; --i) { const addedColumns = addedColumnsSpans[i]; this.operations.removeColumns(new _Operations__WEBPACK_IMPORTED_MODULE_1__.RemoveColumnsCommand(operation.command.sheet, [[addedColumns.columnStart, addedColumns.numberOfColumns]])); } } undoSetCellContents(operation) { for (const cellContentData of operation.cellContents) { const address = cellContentData.address; const [oldContentAddress, oldContent] = cellContentData.oldContent; if (!(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.equalSimpleCellAddress)(address, oldContentAddress)) { this.operations.setCellEmpty(address); } this.operations.restoreCell(oldContentAddress, oldContent); } } undoPaste(operation) { this.restoreOperationOldContent(operation.oldContent); for (const namedExpression of operation.addedGlobalNamedExpressions) { this.operations.removeNamedExpression(namedExpression); } } undoMoveRows(operation) { const { sheet } = operation; this.operations.moveRows(sheet, operation.undoStart, operation.numberOfRows, operation.undoEnd); this.restoreOldDataFromVersion(operation.version - 1); } undoMoveColumns(operation) { const { sheet } = operation; this.operations.moveColumns(sheet, operation.undoStart, operation.numberOfColumns, operation.undoEnd); this.restoreOldDataFromVersion(operation.version - 1); } undoMoveCells(operation) { this.operations.forceApplyPostponedTransformations(); this.operations.moveCells(operation.destinationLeftCorner, operation.width, operation.height, operation.sourceLeftCorner); this.restoreOperationOldContent(operation.overwrittenCellsData); this.restoreOldDataFromVersion(operation.version - 1); for (const namedExpression of operation.addedGlobalNamedExpressions) { this.operations.removeNamedExpression(namedExpression); } } undoAddSheet(operation) { const { sheetName } = operation; this.operations.removeSheetByName(sheetName); } undoRemoveSheet(operation) { this.operations.forceApplyPostponedTransformations(); const { oldSheetContent, sheetId } = operation; this.operations.addSheet(operation.sheetName); for (let rowIndex = 0; rowIndex < oldSheetContent.length; rowIndex++) { const row = oldSheetContent[rowIndex]; for (let col = 0; col < row.length; col++) { const cellType = row[col]; const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheetId, col, rowIndex); this.operations.restoreCell(address, cellType); } } for (const [namedexpression, content] of operation.scopedNamedExpressions) { this.operations.restoreNamedExpression(namedexpression, content, sheetId); } this.restoreOldDataFromVersion(operation.version - 1); } undoRenameSheet(operation) { this.operations.renameSheet(operation.sheetId, operation.oldName); } undoClearSheet(operation) { const { oldSheetContent, sheetId } = operation; for (let rowIndex = 0; rowIndex < oldSheetContent.length; rowIndex++) { const row = oldSheetContent[rowIndex]; for (let col = 0; col < row.length; col++) { const cellType = row[col]; const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheetId, col, rowIndex); this.operations.restoreCell(address, cellType); } } } undoSetSheetContent(operation) { const { oldSheetContent, sheetId } = operation; this.operations.clearSheet(sheetId); for (let rowIndex = 0; rowIndex < oldSheetContent.length; rowIndex++) { const row = oldSheetContent[rowIndex]; for (let col = 0; col < row.length; col++) { const cellType = row[col]; const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheetId, col, rowIndex); this.operations.restoreCell(address, cellType); } } } undoAddNamedExpression(operation) { this.operations.removeNamedExpression(operation.name, operation.scope); } undoRemoveNamedExpression(operation) { this.operations.restoreNamedExpression(operation.namedExpression, operation.content, operation.scope); } undoChangeNamedExpression(operation) { this.operations.restoreNamedExpression(operation.namedExpression, operation.oldContent, operation.scope); } undoSetRowOrder(operation) { this.restoreOperationOldContent(operation.oldContent); } undoSetColumnOrder(operation) { this.restoreOperationOldContent(operation.oldContent); } redo() { const operation = this.redoStack.pop(); if (!operation) { throw Error('Attempted to redo without operation on stack'); } this.redoEntry(operation); this.undoStack.push(operation); } redoBatch(batchOperation) { for (const operation of batchOperation.operations) { this.redoEntry(operation); } } redoRemoveRows(operation) { this.operations.removeRows(operation.command); } redoMoveCells(operation) { this.operations.moveCells(operation.sourceLeftCorner, operation.width, operation.height, operation.destinationLeftCorner); } redoRemoveColumns(operation) { this.operations.removeColumns(operation.command); } redoPaste(operation) { const { targetLeftCorner, newContent } = operation; const height = newContent.length; const width = newContent[0].length; for (let y = 0; y < height; ++y) { for (let x = 0; x < width; ++x) { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(targetLeftCorner.sheet, targetLeftCorner.col + x, targetLeftCorner.row + y); this.operations.restoreCell(address, newContent[y][x]); } } } redoSetCellContents(operation) { for (const cellContentData of operation.cellContents) { this.operations.setCellContent(cellContentData.address, cellContentData.newContent); } } redoAddRows(operation) { this.operations.addRows(operation.command); } redoAddColumns(operation) { this.operations.addColumns(operation.command); } redoRemoveSheet(operation) { this.operations.removeSheetByName(operation.sheetName); } redoAddSheet(operation) { this.operations.addSheet(operation.sheetName); } redoRenameSheet(operation) { this.operations.renameSheet(operation.sheetId, operation.newName); } redoMoveRows(operation) { this.operations.moveRows(operation.sheet, operation.startRow, operation.numberOfRows, operation.targetRow); } redoMoveColumns(operation) { this.operations.moveColumns(operation.sheet, operation.startColumn, operation.numberOfColumns, operation.targetColumn); } redoClearSheet(operation) { this.operations.clearSheet(operation.sheetId); } redoSetSheetContent(operation) { const { sheetId, newSheetContent } = operation; this.operations.setSheetContent(sheetId, newSheetContent); } redoAddNamedExpression(operation) { this.operations.addNamedExpression(operation.name, operation.newContent, operation.scope, operation.options); } redoRemoveNamedExpression(operation) { this.operations.removeNamedExpression(operation.namedExpression.displayName, operation.scope); } redoChangeNamedExpression(operation) { this.operations.changeNamedExpressionExpression(operation.namedExpression.displayName, operation.newContent, operation.scope, operation.options); } redoSetRowOrder(operation) { this.operations.setRowOrder(operation.sheetId, operation.rowMapping); } redoSetColumnOrder(operation) { this.operations.setColumnOrder(operation.sheetId, operation.columnMapping); } addUndoEntry(operation) { this.undoStack.push(operation); this.undoStack.splice(0, Math.max(0, this.undoStack.length - this.undoLimit)); } undoEntry(operation) { operation.doUndo(this); } restoreOperationOldContent(oldContent) { for (const [address, clipboardCell] of oldContent) { this.operations.restoreCell(address, clipboardCell); } } redoEntry(operation) { operation.doRedo(this); } restoreOldDataFromVersion(version) { const oldDataToRestore = this.oldData.get(version) || []; for (const entryToRestore of oldDataToRestore) { const [address, hash] = entryToRestore; this.operations.setFormulaToCellFromCache(hash, address); } } } /***/ }), /* 127 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Evaluator: () => (/* binding */ Evaluator) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); /* harmony import */ var _ContentChanges__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(68); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4); /* harmony import */ var _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(80); /* harmony import */ var _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(95); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(69); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(72); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class Evaluator { constructor(config, stats, interpreter, lazilyTransformingAstService, dependencyGraph, columnSearch) { this.config = config; this.stats = stats; this.interpreter = interpreter; this.lazilyTransformingAstService = lazilyTransformingAstService; this.dependencyGraph = dependencyGraph; this.columnSearch = columnSearch; } run() { this.stats.start(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.TOP_SORT); const { sorted, cycled } = this.dependencyGraph.topSortWithScc(); this.stats.end(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.TOP_SORT); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.EVALUATION, () => { this.recomputeFormulas(cycled, sorted); }); } partialRun(vertices) { const changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty(); this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.EVALUATION, () => { this.dependencyGraph.graph.getTopSortedWithSccSubgraphFrom(vertices, vertex => { if (vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_5__.FormulaVertex) { const currentValue = vertex.isComputed() ? vertex.getCellValue() : undefined; const newCellValue = this.recomputeFormulaVertexValue(vertex); if (newCellValue !== currentValue) { const address = vertex.getAddress(this.lazilyTransformingAstService); changes.addChange(newCellValue, address); this.columnSearch.change((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__.getRawValue)(currentValue), (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__.getRawValue)(newCellValue), address); return true; } return false; } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.RangeVertex) { vertex.clearCache(); return true; } else { return true; } }, vertex => { if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.RangeVertex) { vertex.clearCache(); } else if (vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_5__.FormulaVertex) { const address = vertex.getAddress(this.lazilyTransformingAstService); this.columnSearch.remove((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__.getRawValue)(vertex.valueOrUndef()), address); const error = new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.CYCLE, undefined, vertex); vertex.setCellValue(error); changes.addChange(error, address); } }); }); return changes; } runAndForget(ast, address, dependencies) { const tmpRanges = []; for (const dep of (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(dependencies, address)) { if (dep instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) { const range = dep; if (this.dependencyGraph.getRange(range.start, range.end) === undefined) { const rangeVertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.RangeVertex(range); this.dependencyGraph.rangeMapping.setRange(rangeVertex); tmpRanges.push(rangeVertex); } } } const ret = this.evaluateAstToCellValue(ast, new _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_6__.InterpreterState(address, this.config.useArrayArithmetic)); tmpRanges.forEach(rangeVertex => { this.dependencyGraph.rangeMapping.removeRange(rangeVertex); }); return ret; } /** * Recalculates formulas in the topological sort order */ recomputeFormulas(cycled, sorted) { cycled.forEach(vertex => { if (vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_5__.FormulaVertex) { vertex.setCellValue(new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.CYCLE, undefined, vertex)); } }); sorted.forEach(vertex => { if (vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_5__.FormulaVertex) { const newCellValue = this.recomputeFormulaVertexValue(vertex); const address = vertex.getAddress(this.lazilyTransformingAstService); this.columnSearch.add((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__.getRawValue)(newCellValue), address); } else if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.RangeVertex) { vertex.clearCache(); } }); } recomputeFormulaVertexValue(vertex) { const address = vertex.getAddress(this.lazilyTransformingAstService); if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.ArrayVertex && (vertex.array.size.isRef || !this.dependencyGraph.isThereSpaceForArray(vertex))) { return vertex.setNoSpace(); } else { const formula = vertex.getFormula(this.lazilyTransformingAstService); const newCellValue = this.evaluateAstToCellValue(formula, new _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_6__.InterpreterState(address, this.config.useArrayArithmetic, vertex)); return vertex.setCellValue(newCellValue); } } evaluateAstToCellValue(ast, state) { const interpreterValue = this.interpreter.evaluateAst(ast, state); if (interpreterValue instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_8__.SimpleRangeValue) { return interpreterValue; } else if (interpreterValue === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_7__.EmptyValue && this.config.evaluateNullToZero) { return 0; } else { return interpreterValue; } } } /***/ }), /* 128 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ExportedCellChange: () => (/* binding */ ExportedCellChange), /* harmony export */ ExportedNamedExpressionChange: () => (/* binding */ ExportedNamedExpressionChange), /* harmony export */ Exporter: () => (/* binding */ Exporter) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _CellValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(69); /* harmony import */ var _NamedExpressions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(115); /* harmony import */ var _parser_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * A list of cells which values changed after the operation, their absolute addresses and new values. */ class ExportedCellChange { constructor(address, newValue) { this.address = address; this.newValue = newValue; } get col() { return this.address.col; } get row() { return this.address.row; } get sheet() { return this.address.sheet; } get value() { return this.newValue; } } class ExportedNamedExpressionChange { constructor(name, newValue) { this.name = name; this.newValue = newValue; } } class Exporter { constructor(config, namedExpressions, sheetIndexMapping, lazilyTransformingService) { this.config = config; this.namedExpressions = namedExpressions; this.sheetIndexMapping = sheetIndexMapping; this.lazilyTransformingService = lazilyTransformingService; } exportChange(change) { const value = change.value; const address = change.address; if (address.sheet === _NamedExpressions__WEBPACK_IMPORTED_MODULE_5__.NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { const namedExpression = this.namedExpressions.namedExpressionInAddress(address.row); if (!namedExpression) { throw new Error('Missing named expression'); } return new ExportedNamedExpressionChange(namedExpression.displayName, this.exportScalarOrRange(value)); } else if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { const result = []; for (const [cellValue, cellAddress] of value.entriesFromTopLeftCorner(address)) { result.push(new ExportedCellChange(cellAddress, this.exportValue(cellValue))); } return result; } else { return new ExportedCellChange(address, this.exportValue(value)); } } exportValue(value) { if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { return this.detailedError(new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ScalarExpected)); } else if (this.config.smartRounding && (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(value)) { return this.cellValueRounding((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(value)); } else if (value instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return this.detailedError(value); } else if (value === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.EmptyValue) { return null; } else { return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(value); } } exportScalarOrRange(value) { if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_4__.SimpleRangeValue) { return value.rawData().map(row => row.map(v => this.exportValue(v))); } else { return this.exportValue(value); } } detailedError(error) { var _a, _b; let address = undefined; const originAddress = (_a = error.root) === null || _a === void 0 ? void 0 : _a.getAddress(this.lazilyTransformingService); if (originAddress !== undefined) { if (originAddress.sheet === _NamedExpressions__WEBPACK_IMPORTED_MODULE_5__.NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { address = (_b = this.namedExpressions.namedExpressionInAddress(originAddress.row)) === null || _b === void 0 ? void 0 : _b.displayName; } else { address = (0,_parser_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_6__.simpleCellAddressToString)(this.sheetIndexMapping, originAddress, -1); } } return new _CellValue__WEBPACK_IMPORTED_MODULE_1__.DetailedCellError(error, this.config.translationPackage.getErrorTranslation(error.type), address); } cellValueRounding(value) { if (value === 0) { return value; } const magnitudeMultiplierExponent = Math.floor(Math.log10(Math.abs(value))); const placesMultiplier = Math.pow(10, this.config.precisionRounding - magnitudeMultiplierExponent); if (value < 0) { return -Math.round(-value * placesMultiplier) / placesMultiplier; } else { return Math.round(value * placesMultiplier) / placesMultiplier; } } } /***/ }), /* 129 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ GraphBuilder: () => (/* binding */ GraphBuilder), /* harmony export */ SimpleStrategy: () => (/* binding */ SimpleStrategy) /* harmony export */ }); /* harmony import */ var _absolutizeDependencies__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); /* harmony import */ var _CellContentParser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(112); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(72); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Service building the graph and mappings. */ class GraphBuilder { /** * Configures the building service. */ constructor(dependencyGraph, columnSearch, parser, cellContentParser, stats, arraySizePredictor) { this.dependencyGraph = dependencyGraph; this.columnSearch = columnSearch; this.parser = parser; this.cellContentParser = cellContentParser; this.stats = stats; this.arraySizePredictor = arraySizePredictor; this.buildStrategy = new SimpleStrategy(dependencyGraph, columnSearch, parser, stats, cellContentParser, arraySizePredictor); } /** * Builds graph. */ buildGraph(sheets, stats) { const dependencies = stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_6__.StatType.COLLECT_DEPENDENCIES, () => this.buildStrategy.run(sheets)); this.dependencyGraph.getAndClearContentChanges(); stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_6__.StatType.PROCESS_DEPENDENCIES, () => this.processDependencies(dependencies)); } processDependencies(dependencies) { dependencies.forEach((cellDependencies, endVertex) => { this.dependencyGraph.processCellDependencies(cellDependencies, endVertex); }); } } class SimpleStrategy { constructor(dependencyGraph, columnIndex, parser, stats, cellContentParser, arraySizePredictor) { this.dependencyGraph = dependencyGraph; this.columnIndex = columnIndex; this.parser = parser; this.stats = stats; this.cellContentParser = cellContentParser; this.arraySizePredictor = arraySizePredictor; } run(sheets) { const dependencies = new Map(); for (const sheetName in sheets) { const sheetId = this.dependencyGraph.getSheetId(sheetName); const sheet = sheets[sheetName]; for (let i = 0; i < sheet.length; ++i) { const row = sheet[i]; for (let j = 0; j < row.length; ++j) { const cellContent = row[j]; const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheetId, j, i); const parsedCellContent = this.cellContentParser.parse(cellContent); if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_3__.CellContent.Formula) { const parseResult = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_6__.StatType.PARSER, () => this.parser.parse(parsedCellContent.formula, address)); if (parseResult.errors.length > 0) { this.shrinkArrayIfNeeded(address); const vertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorVertex(parseResult.errors, parsedCellContent.formula); this.dependencyGraph.addVertex(address, vertex); } else { this.shrinkArrayIfNeeded(address); const size = this.arraySizePredictor.checkArraySize(parseResult.ast, address); if (size.isScalar()) { const vertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.FormulaCellVertex(parseResult.ast, address, 0); dependencies.set(vertex, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_0__.absolutizeDependencies)(parseResult.dependencies, address)); this.dependencyGraph.addVertex(address, vertex); if (parseResult.hasVolatileFunction) { this.dependencyGraph.markAsVolatile(vertex); } if (parseResult.hasStructuralChangeFunction) { this.dependencyGraph.markAsDependentOnStructureChange(vertex); } } else { const vertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.ArrayVertex(parseResult.ast, address, new _ArraySize__WEBPACK_IMPORTED_MODULE_1__.ArraySize(size.width, size.height)); dependencies.set(vertex, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_0__.absolutizeDependencies)(parseResult.dependencies, address)); this.dependencyGraph.addArrayVertex(address, vertex); } } } else if (parsedCellContent instanceof _CellContentParser__WEBPACK_IMPORTED_MODULE_3__.CellContent.Empty) { /* we don't care about empty cells here */ } else { this.shrinkArrayIfNeeded(address); const vertex = new _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.ValueCellVertex(parsedCellContent.value, cellContent); this.columnIndex.add((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(parsedCellContent.value), address); this.dependencyGraph.addVertex(address, vertex); } } } } return dependencies; } shrinkArrayIfNeeded(address) { const vertex = this.dependencyGraph.getCell(address); if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_4__.ArrayVertex) { this.dependencyGraph.shrinkArrayToCorner(vertex); } } } /***/ }), /* 130 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FunctionRegistry: () => (/* binding */ FunctionRegistry) /* harmony export */ }); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77); /* harmony import */ var _HyperFormula__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(110); /* harmony import */ var _plugin_VersionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(131); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function validateAndReturnMetadataFromName(functionId, plugin) { var _a; let entry = plugin.implementedFunctions[functionId]; const key = (_a = plugin.aliases) === null || _a === void 0 ? void 0 : _a[functionId]; if (key !== undefined) { if (entry !== undefined) { throw new _errors__WEBPACK_IMPORTED_MODULE_0__.AliasAlreadyExisting(functionId, plugin.name); } entry = plugin.implementedFunctions[key]; } if (entry === undefined) { throw _errors__WEBPACK_IMPORTED_MODULE_0__.FunctionPluginValidationError.functionNotDeclaredInPlugin(functionId, plugin.name); } return entry; } class FunctionRegistry { constructor(config) { this.config = config; this.functions = new Map(); this.arraySizeFunctions = new Map(); this.volatileFunctions = new Set(); this.arrayFunctions = new Set(); this.structuralChangeFunctions = new Set(); this.functionsWhichDoesNotNeedArgumentsToBeComputed = new Set(); this.functionsMetadata = new Map(); this.doesFunctionNeedArgumentToBeComputed = functionId => this.functionsWhichDoesNotNeedArgumentsToBeComputed.has(functionId); this.isFunctionVolatile = functionId => this.volatileFunctions.has(functionId); this.isArrayFunction = functionId => this.arrayFunctions.has(functionId); this.isFunctionDependentOnSheetStructureChange = functionId => this.structuralChangeFunctions.has(functionId); if (config.functionPlugins.length > 0) { this.instancePlugins = new Map(); for (const plugin of config.functionPlugins) { FunctionRegistry.loadPluginFunctions(plugin, this.instancePlugins); } } else { this.instancePlugins = new Map(FunctionRegistry.plugins); } for (const [functionId, plugin] of FunctionRegistry.protectedFunctions()) { FunctionRegistry.loadFunctionUnprotected(plugin, functionId, this.instancePlugins); } for (const [functionId, plugin] of this.instancePlugins.entries()) { this.categorizeFunction(functionId, validateAndReturnMetadataFromName(functionId, plugin)); } } static registerFunctionPlugin(plugin, translations) { this.loadPluginFunctions(plugin, this.plugins); if (translations !== undefined) { this.loadTranslations(translations); } } static registerFunction(functionId, plugin, translations) { this.loadPluginFunction(plugin, functionId, this.plugins); if (translations !== undefined) { this.loadTranslations(translations); } } static unregisterFunction(functionId) { if (this.functionIsProtected(functionId)) { throw _errors__WEBPACK_IMPORTED_MODULE_0__.ProtectedFunctionError.cannotUnregisterFunctionWithId(functionId); } this.plugins.delete(functionId); } static unregisterFunctionPlugin(plugin) { for (const protectedPlugin of this.protectedPlugins()) { if (protectedPlugin === plugin) { throw _errors__WEBPACK_IMPORTED_MODULE_0__.ProtectedFunctionError.cannotUnregisterProtectedPlugin(); } } for (const [functionId, registeredPlugin] of this.plugins.entries()) { if (registeredPlugin === plugin) { this.plugins.delete(functionId); } } } static unregisterAll() { this.plugins.clear(); } static getRegisteredFunctionIds() { return [...Array.from(this.plugins.keys()), ...Array.from(this._protectedPlugins.keys())]; } static getPlugins() { return Array.from(new Set(this.plugins.values()).values()); } static getFunctionPlugin(functionId) { if (this.functionIsProtected(functionId)) { return undefined; } else { return this.plugins.get(functionId); } } static functionIsProtected(functionId) { return this._protectedPlugins.has(functionId); } static loadTranslations(translations) { const registeredLanguages = new Set(_HyperFormula__WEBPACK_IMPORTED_MODULE_1__.HyperFormula.getRegisteredLanguagesCodes()); Object.keys(translations).forEach(code => { if (registeredLanguages.has(code)) { _HyperFormula__WEBPACK_IMPORTED_MODULE_1__.HyperFormula.getLanguage(code).extendFunctions(translations[code]); } }); } static loadPluginFunctions(plugin, registry) { Object.keys(plugin.implementedFunctions).forEach(functionName => { this.loadPluginFunction(plugin, functionName, registry); }); if (plugin.aliases !== undefined) { Object.keys(plugin.aliases).forEach(functionName => { this.loadPluginFunction(plugin, functionName, registry); }); } } static loadPluginFunction(plugin, functionId, registry) { if (this.functionIsProtected(functionId)) { throw _errors__WEBPACK_IMPORTED_MODULE_0__.ProtectedFunctionError.cannotRegisterFunctionWithId(functionId); } else { this.loadFunctionUnprotected(plugin, functionId, registry); } } static loadFunctionUnprotected(plugin, functionId, registry) { const methodName = validateAndReturnMetadataFromName(functionId, plugin).method; if (Object.prototype.hasOwnProperty.call(plugin.prototype, methodName)) { registry.set(functionId, plugin); } else { throw _errors__WEBPACK_IMPORTED_MODULE_0__.FunctionPluginValidationError.functionMethodNotFound(methodName, plugin.name); } } static *protectedFunctions() { for (const [functionId, plugin] of this._protectedPlugins) { if (plugin !== undefined) { yield [functionId, plugin]; } } } static *protectedPlugins() { for (const [, plugin] of this._protectedPlugins) { if (plugin !== undefined) { yield plugin; } } } initializePlugins(interpreter) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const instances = []; for (const [functionId, plugin] of this.instancePlugins.entries()) { let foundPluginInstance = instances.find(pluginInstance => pluginInstance instanceof plugin); if (foundPluginInstance === undefined) { foundPluginInstance = new plugin(interpreter); instances.push(foundPluginInstance); } const metadata = validateAndReturnMetadataFromName(functionId, plugin); const methodName = metadata.method; this.functions.set(functionId, [methodName, foundPluginInstance]); const arraySizeMethodName = metadata.arraySizeMethod; if (arraySizeMethodName !== undefined) { this.arraySizeFunctions.set(functionId, [arraySizeMethodName, foundPluginInstance]); } } } getFunctionPlugin(functionId) { if (FunctionRegistry.functionIsProtected(functionId)) { return undefined; } return this.instancePlugins.get(functionId); } getFunction(functionId) { const pluginEntry = this.functions.get(functionId); if (pluginEntry !== undefined && this.config.translationPackage.isFunctionTranslated(functionId)) { const [pluginFunction, pluginInstance] = pluginEntry; return (ast, state) => pluginInstance[pluginFunction](ast, state); } else { return undefined; } } getArraySizeFunction(functionId) { const pluginEntry = this.arraySizeFunctions.get(functionId); if (pluginEntry !== undefined && this.config.translationPackage.isFunctionTranslated(functionId)) { const [pluginArraySizeFunction, pluginInstance] = pluginEntry; return (ast, state) => pluginInstance[pluginArraySizeFunction](ast, state); } else { return undefined; } } getMetadata(functionId) { return this.functionsMetadata.get(functionId); } getPlugins() { const plugins = new Set(); for (const [functionId, plugin] of this.instancePlugins) { if (!FunctionRegistry.functionIsProtected(functionId)) { plugins.add(plugin); } } return Array.from(plugins); } getRegisteredFunctionIds() { return Array.from(this.functions.keys()); } categorizeFunction(functionId, functionMetadata) { if (functionMetadata.isVolatile) { this.volatileFunctions.add(functionId); } if (functionMetadata.arrayFunction) { this.arrayFunctions.add(functionId); } if (functionMetadata.doesNotNeedArgumentsToBeComputed) { this.functionsWhichDoesNotNeedArgumentsToBeComputed.add(functionId); } if (functionMetadata.isDependentOnSheetStructureChange) { this.structuralChangeFunctions.add(functionId); } this.functionsMetadata.set(functionId, functionMetadata); } } FunctionRegistry.plugins = new Map(); FunctionRegistry._protectedPlugins = new Map([['VERSION', _plugin_VersionPlugin__WEBPACK_IMPORTED_MODULE_2__.VersionPlugin], ['OFFSET', undefined]]); /***/ }), /* 131 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ VersionPlugin: () => (/* binding */ VersionPlugin) /* harmony export */ }); /* harmony import */ var _HyperFormula__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(110); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const LICENSE_STATUS_MAP = new Map([['gpl-v3', 1], ["missing" /* MISSING */, 2], ["invalid" /* INVALID */, 3], ["expired" /* EXPIRED */, 4]]); class VersionPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionPlugin { version(ast, state) { return this.runFunction(ast.args, state, this.metadata('VERSION'), () => { const { licenseKeyValidityState: validityState, licenseKey } = this.config; let status; if (LICENSE_STATUS_MAP.has(licenseKey)) { status = LICENSE_STATUS_MAP.get(licenseKey); } else if (LICENSE_STATUS_MAP.has(validityState)) { status = LICENSE_STATUS_MAP.get(validityState); } else if (validityState === "valid" /* VALID */) { status = licenseKey.slice(-5); } return `HyperFormula v${_HyperFormula__WEBPACK_IMPORTED_MODULE_0__.HyperFormula.version}, ${status}`; }); } } VersionPlugin.implementedFunctions = { 'VERSION': { method: 'version', parameters: [] } }; /***/ }), /* 132 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Interpreter: () => (/* binding */ Interpreter) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _ArrayValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(61); /* harmony import */ var _parser_Ast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(98); /* harmony import */ var _Criterion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(133); /* harmony import */ var _FunctionRegistry__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(130); /* harmony import */ var _InterpreterState__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(95); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(69); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ // noinspection TypeScriptPreferShortImport class Interpreter { constructor(config, dependencyGraph, columnSearch, stats, arithmeticHelper, functionRegistry, namedExpressions, serialization, arraySizePredictor, dateTimeHelper) { this.config = config; this.dependencyGraph = dependencyGraph; this.columnSearch = columnSearch; this.stats = stats; this.arithmeticHelper = arithmeticHelper; this.functionRegistry = functionRegistry; this.namedExpressions = namedExpressions; this.serialization = serialization; this.arraySizePredictor = arraySizePredictor; this.dateTimeHelper = dateTimeHelper; this.equalOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.eq, arg1, arg2); this.notEqualOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.neq, arg1, arg2); this.greaterThanOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.gt, arg1, arg2); this.lessThanOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.lt, arg1, arg2); this.greaterThanOrEqualOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.geq, arg1, arg2); this.lessThanOrEqualOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.leq, arg1, arg2); this.concatOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.concat, (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceScalarToString)(arg1), (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceScalarToString)(arg2)); this.plusOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.addWithEpsilon, this.arithmeticHelper.coerceScalarToNumberOrError(arg1), this.arithmeticHelper.coerceScalarToNumberOrError(arg2)); this.minusOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.subtract, this.arithmeticHelper.coerceScalarToNumberOrError(arg1), this.arithmeticHelper.coerceScalarToNumberOrError(arg2)); this.timesOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.multiply, this.arithmeticHelper.coerceScalarToNumberOrError(arg1), this.arithmeticHelper.coerceScalarToNumberOrError(arg2)); this.powerOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.pow, this.arithmeticHelper.coerceScalarToNumberOrError(arg1), this.arithmeticHelper.coerceScalarToNumberOrError(arg2)); this.divOp = (arg1, arg2) => binaryErrorWrapper(this.arithmeticHelper.divide, this.arithmeticHelper.coerceScalarToNumberOrError(arg1), this.arithmeticHelper.coerceScalarToNumberOrError(arg2)); this.unaryMinusOp = arg => unaryErrorWrapper(this.arithmeticHelper.unaryMinus, this.arithmeticHelper.coerceScalarToNumberOrError(arg)); this.percentOp = arg => unaryErrorWrapper(this.arithmeticHelper.unaryPercent, this.arithmeticHelper.coerceScalarToNumberOrError(arg)); this.unaryPlusOp = arg => this.arithmeticHelper.unaryPlus(arg); this.functionRegistry.initializePlugins(this); this.criterionBuilder = new _Criterion__WEBPACK_IMPORTED_MODULE_6__.CriterionBuilder(config); } evaluateAst(ast, state) { let val = this.evaluateAstWithoutPostprocessing(ast, state); if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_9__.isExtendedNumber)(val)) { if ((0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.isNumberOverflow)((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_9__.getRawValue)(val))) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.NaN); } else { val = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_9__.cloneNumber)(val, (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.fixNegativeZero)((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_9__.getRawValue)(val))); } } if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue && val.height() === 1 && val.width() === 1) { [[val]] = val.data; } return wrapperForRootVertex(val, state.formulaVertex); } /** * Calculates cell value from formula abstract syntax tree * * @param formula - abstract syntax tree of formula * @param formulaAddress - address of the cell in which formula is located */ evaluateAstWithoutPostprocessing(ast, state) { switch (ast.type) { case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EMPTY: { return _InterpreterValue__WEBPACK_IMPORTED_MODULE_9__.EmptyValue; } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE: { const address = ast.reference.toSimpleCellAddress(state.formulaAddress); if ((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.invalidSimpleCellAddress)(address)) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.BadRef); } return this.dependencyGraph.getCellValue(address); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER: case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.STRING: { return ast.value; } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CONCATENATE_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.concatOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EQUALS_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.equalOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NOT_EQUAL_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.notEqualOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.GREATER_THAN_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.greaterThanOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.LESS_THAN_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.lessThanOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.GREATER_THAN_OR_EQUAL_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.greaterThanOrEqualOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.LESS_THAN_OR_EQUAL_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.lessThanOrEqualOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.plusOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.minusOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.TIMES_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.timesOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.POWER_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.powerOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.DIV_OP: { const leftResult = this.evaluateAst(ast.left, state); const rightResult = this.evaluateAst(ast.right, state); return this.binaryRangeWrapper(this.divOp, leftResult, rightResult, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_UNARY_OP: { const result = this.evaluateAst(ast.value, state); return this.unaryRangeWrapper(this.unaryPlusOp, result, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_UNARY_OP: { const result = this.evaluateAst(ast.value, state); return this.unaryRangeWrapper(this.unaryMinusOp, result, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PERCENT_OP: { const result = this.evaluateAst(ast.value, state); return this.unaryRangeWrapper(this.percentOp, result, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.FUNCTION_CALL: { if (this.config.licenseKeyValidityState !== "valid" /* VALID */ && !_FunctionRegistry__WEBPACK_IMPORTED_MODULE_7__.FunctionRegistry.functionIsProtected(ast.procedureName)) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.LIC, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.LicenseKey(this.config.licenseKeyValidityState)); } const pluginFunction = this.functionRegistry.getFunction(ast.procedureName); if (pluginFunction !== undefined) { return pluginFunction(ast, new _InterpreterState__WEBPACK_IMPORTED_MODULE_8__.InterpreterState(state.formulaAddress, state.arraysFlag || this.functionRegistry.isArrayFunction(ast.procedureName), state.formulaVertex)); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.NAME, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.FunctionName(ast.procedureName)); } } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NAMED_EXPRESSION: { const namedExpression = this.namedExpressions.nearestNamedExpression(ast.expressionName, state.formulaAddress.sheet); if (namedExpression) { return this.dependencyGraph.getCellValue(namedExpression.address); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.NAME, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.NamedExpressionName(ast.expressionName)); } } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_RANGE: { if (!this.rangeSpansOneSheet(ast)) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.RangeManySheets); } const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromCellRange(ast, state.formulaAddress); const arrayVertex = this.dependencyGraph.getArray(range); if (arrayVertex) { const array = arrayVertex.array; if (array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_1__.NotComputedArray) { throw new Error('Array should be already computed'); } else if (array instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return array; } else if (array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_1__.ArrayValue) { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.fromRange(array.raw(), range, this.dependencyGraph); } else { throw new Error('Unknown array'); } } else { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyRange(range, this.dependencyGraph); } } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.COLUMN_RANGE: { if (!this.rangeSpansOneSheet(ast)) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.RangeManySheets); } const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteColumnRange.fromColumnRange(ast, state.formulaAddress); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyRange(range, this.dependencyGraph); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.ROW_RANGE: { if (!this.rangeSpansOneSheet(ast)) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.RangeManySheets); } const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteRowRange.fromRowRangeAst(ast, state.formulaAddress); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyRange(range, this.dependencyGraph); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PARENTHESIS: { return this.evaluateAst(ast.expression, state); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.ARRAY: { let totalWidth = undefined; const ret = []; for (const astRow of ast.args) { let rowHeight = undefined; const rowRet = []; for (const astIt of astRow) { const arr = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceToRange)(this.evaluateAst(astIt, state)); const height = arr.height(); if (rowHeight === undefined) { rowHeight = height; rowRet.push(...arr.data); } else if (rowHeight === height) { for (let i = 0; i < height; i++) { rowRet[i].push(...arr.data[i]); } } else { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.SizeMismatch); } } const width = rowRet[0].length; if (totalWidth === undefined) { totalWidth = width; ret.push(...rowRet); } else if (totalWidth === width) { ret.push(...rowRet); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.SizeMismatch); } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(ret); } case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.ERROR_WITH_RAW_INPUT: case _parser_Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.ERROR: { return ast.error; } } } rangeSpansOneSheet(ast) { return ast.start.sheet === ast.end.sheet; } unaryRangeWrapper(op, arg, state) { var _a; if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue && !state.arraysFlag) { arg = (_a = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceRangeToScalar)(arg, state)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.ScalarExpected); } if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg; } if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue) { const newRaw = arg.data.map(row => row.map(op)); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(newRaw); } return op(arg); } binaryRangeWrapper(op, arg1, arg2, state) { var _a, _b; if (arg1 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue && !state.arraysFlag) { arg1 = (_a = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceRangeToScalar)(arg1, state)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.ScalarExpected); } if (arg1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg1; } if (arg2 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue && !state.arraysFlag) { arg2 = (_b = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceRangeToScalar)(arg2, state)) !== null && _b !== void 0 ? _b : new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.ScalarExpected); } if (arg2 instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg2; } if (arg1 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue || arg2 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue) { if (!(arg1 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue)) { if (arg2.isAdHoc()) { const raw2 = arg2.data; for (let i = 0; i < raw2.length; i++) { for (let j = 0; j < raw2[0].length; j++) { raw2[i][j] = op(arg1, raw2[i][j]); } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(raw2); } else { arg1 = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.fromScalar(arg1); } } if (!(arg2 instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue)) { if (arg1.isAdHoc()) { const raw1 = arg1.data; for (let i = 0; i < raw1.length; i++) { for (let j = 0; j < raw1[0].length; j++) { raw1[i][j] = op(raw1[i][j], arg2); } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(raw1); } else { arg2 = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.fromScalar(arg2); } } if (arg1.width() === arg2.width() && arg1.height() === arg2.height()) { if (arg1.isAdHoc()) { const raw1 = arg1.data; const raw2 = arg2.data; for (let i = 0; i < raw1.length; i++) { for (let j = 0; j < raw1[0].length; j++) { raw1[i][j] = op(raw1[i][j], raw2[i][j]); } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(raw1); } if (arg2.isAdHoc()) { const raw1 = arg1.data; const raw2 = arg2.data; for (let i = 0; i < raw1.length; i++) { for (let j = 0; j < raw1[0].length; j++) { raw2[i][j] = op(raw1[i][j], raw2[i][j]); } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(raw2); } } const width = Math.max(arg1.width(), arg2.width()); const height = Math.max(arg1.height(), arg2.height()); const ret = Array(height); for (let i = 0; i < height; i++) { ret[i] = Array(width); } for (let i = 0; i < height; i++) { const i1 = arg1.height() !== 1 ? i : 0; const i2 = arg2.height() !== 1 ? i : 0; for (let j = 0; j < width; j++) { const j1 = arg1.width() !== 1 ? j : 0; const j2 = arg2.width() !== 1 ? j : 0; if (i1 < arg1.height() && i2 < arg2.height() && j1 < arg1.width() && j2 < arg2.width()) { ret[i][j] = op(arg1.data[i1][j1], arg2.data[i2][j2]); } else { ret[i][j] = new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.NA); } } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_10__.SimpleRangeValue.onlyValues(ret); } return op(arg1, arg2); } } function unaryErrorWrapper(op, arg) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg; } else { return op(arg); } } function binaryErrorWrapper(op, arg1, arg2) { if (arg1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg1; } else if (arg2 instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError) { return arg2; } else { return op(arg1, arg2); } } function wrapperForRootVertex(val, vertex) { if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError && vertex !== undefined) { return val.attachRootVertex(vertex); } return val; } /***/ }), /* 133 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CriterionBuilder: () => (/* binding */ CriterionBuilder), /* harmony export */ CriterionType: () => (/* binding */ CriterionType), /* harmony export */ buildCriterion: () => (/* binding */ buildCriterion), /* harmony export */ buildCriterionLambda: () => (/* binding */ buildCriterionLambda) /* harmony export */ }); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var CriterionType; (function (CriterionType) { CriterionType["GREATER_THAN"] = "GREATER_THAN"; CriterionType["GREATER_THAN_OR_EQUAL"] = "GREATER_THAN_OR_EQUAL"; CriterionType["LESS_THAN"] = "LESS_THAN"; CriterionType["LESS_THAN_OR_EQUAL"] = "LESS_THAN_OR_EQUAL"; CriterionType["NOT_EQUAL"] = "NOT_EQUAL"; CriterionType["EQUAL"] = "EQUAL"; })(CriterionType || (CriterionType = {})); const buildCriterion = (operator, value) => ({ operator, value }); class CriterionBuilder { constructor(config) { var _a, _b, _c, _d; this.trueString = (_b = (_a = config.translationPackage.getMaybeFunctionTranslation('TRUE')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'true'; this.falseString = (_d = (_c = config.translationPackage.getMaybeFunctionTranslation('FALSE')) === null || _c === void 0 ? void 0 : _c.toLowerCase()) !== null && _d !== void 0 ? _d : 'false'; } fromCellValue(raw, arithmeticHelper) { if (typeof raw !== 'string' && typeof raw !== 'boolean' && typeof raw !== 'number') { return undefined; } const criterion = this.parseCriterion(raw, arithmeticHelper); if (criterion === undefined) { return undefined; } return { raw, lambda: buildCriterionLambda(criterion, arithmeticHelper) }; } parseCriterion(criterion, arithmeticHelper) { if (typeof criterion === 'number' || typeof criterion === 'boolean') { return buildCriterion(CriterionType.EQUAL, criterion); } else if (typeof criterion === 'string') { const regexResult = ANY_CRITERION_REGEX.exec(criterion); let criterionValue; let criterionType; if (regexResult) { criterionType = StrToCriterionType(regexResult[1]); criterionValue = regexResult[2]; } else { criterionType = CriterionType.EQUAL; criterionValue = criterion; } const value = arithmeticHelper.coerceToMaybeNumber(criterionValue); const boolvalue = criterionValue.toLowerCase() === this.trueString ? true : criterionValue.toLowerCase() === this.falseString ? false : undefined; if (criterionType === undefined) { return undefined; } if (criterionValue === '') { return buildCriterion(criterionType, null); } else if (value === undefined) { if (criterionType === CriterionType.EQUAL || criterionType === CriterionType.NOT_EQUAL) { return buildCriterion(criterionType, boolvalue !== null && boolvalue !== void 0 ? boolvalue : criterionValue); } } else { return buildCriterion(criterionType, (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.getRawValue)(value)); } } return undefined; } } const ANY_CRITERION_REGEX = /([<>=]+)(.*)/; function StrToCriterionType(str) { switch (str) { case '>': return CriterionType.GREATER_THAN; case '>=': return CriterionType.GREATER_THAN_OR_EQUAL; case '<': return CriterionType.LESS_THAN; case '<=': return CriterionType.LESS_THAN_OR_EQUAL; case '<>': return CriterionType.NOT_EQUAL; case '=': return CriterionType.EQUAL; default: return undefined; } } const buildCriterionLambda = (criterion, arithmeticHelper) => { switch (criterion.operator) { case CriterionType.GREATER_THAN: { if (typeof criterion.value === 'number') { return cellValue => typeof cellValue === 'number' && arithmeticHelper.floatCmp(cellValue, criterion.value) > 0; } else { return _cellValue => false; } } case CriterionType.GREATER_THAN_OR_EQUAL: { if (typeof criterion.value === 'number') { return cellValue => typeof cellValue === 'number' && arithmeticHelper.floatCmp(cellValue, criterion.value) >= 0; } else { return _cellValue => false; } } case CriterionType.LESS_THAN: { if (typeof criterion.value === 'number') { return cellValue => typeof cellValue === 'number' && arithmeticHelper.floatCmp(cellValue, criterion.value) < 0; } else { return _cellValue => false; } } case CriterionType.LESS_THAN_OR_EQUAL: { if (typeof criterion.value === 'number') { return cellValue => typeof cellValue === 'number' && arithmeticHelper.floatCmp(cellValue, criterion.value) <= 0; } else { return _cellValue => false; } } case CriterionType.EQUAL: { if (typeof criterion.value === 'number') { return cellValue => { if (typeof cellValue === 'number') { return arithmeticHelper.floatCmp(cellValue, criterion.value) === 0; } else if (typeof cellValue === 'string') { if (cellValue === '') { return false; } const val = arithmeticHelper.coerceToMaybeNumber(cellValue); if (val === undefined) { return false; } return arithmeticHelper.floatCmp(val, criterion.value) === 0; } else { return false; } }; } else if (typeof criterion.value === 'string') { return arithmeticHelper.eqMatcherFunction(criterion.value); } else if (typeof criterion.value === 'boolean') { return cellValue => typeof cellValue === 'boolean' && cellValue === criterion.value; } else { return cellValue => cellValue === _InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.EmptyValue; } } case CriterionType.NOT_EQUAL: { if (typeof criterion.value === 'number') { return cellValue => { if (typeof cellValue === 'number') { return arithmeticHelper.floatCmp(cellValue, criterion.value) !== 0; } else if (typeof cellValue === 'string') { if (cellValue === '') { return true; } const val = arithmeticHelper.coerceToMaybeNumber(cellValue); if (val === undefined) { return true; } return arithmeticHelper.floatCmp(val, criterion.value) !== 0; } else { return true; } }; } else if (typeof criterion.value === 'string') { return arithmeticHelper.neqMatcherFunction(criterion.value); } else if (typeof criterion.value === 'boolean') { return cellValue => typeof cellValue !== 'boolean' || cellValue !== criterion.value; } else { return cellValue => cellValue !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.EmptyValue; } } } }; /***/ }), /* 134 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LazilyTransformingAstService: () => (/* binding */ LazilyTransformingAstService) /* harmony export */ }); /* harmony import */ var _dependencyTransformers_CombinedTransformer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(135); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(72); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class LazilyTransformingAstService { constructor(stats) { this.stats = stats; this.transformations = []; } version() { return this.transformations.length; } addTransformation(transformation) { if (this.combinedTransformer !== undefined) { this.combinedTransformer.add(transformation); } else { this.transformations.push(transformation); } return this.version(); } beginCombinedMode(sheet) { this.combinedTransformer = new _dependencyTransformers_CombinedTransformer__WEBPACK_IMPORTED_MODULE_0__.CombinedTransformer(sheet); } commitCombinedMode() { if (this.combinedTransformer === undefined) { throw Error('Combined mode wasn\'t started'); } this.transformations.push(this.combinedTransformer); this.combinedTransformer = undefined; return this.version(); } applyTransformations(ast, address, version) { this.stats.start(_statistics__WEBPACK_IMPORTED_MODULE_1__.StatType.TRANSFORM_ASTS_POSTPONED); for (let v = version; v < this.transformations.length; v++) { const transformation = this.transformations[v]; if (transformation.isIrreversible()) { this.undoRedo.storeDataForVersion(v, address, this.parser.computeHashFromAst(ast)); this.parser.rememberNewAst(ast); } const [newAst, newAddress] = transformation.transformSingleAst(ast, address); ast = newAst; address = newAddress; } const cachedAst = this.parser.rememberNewAst(ast); this.stats.end(_statistics__WEBPACK_IMPORTED_MODULE_1__.StatType.TRANSFORM_ASTS_POSTPONED); return [cachedAst, address, this.transformations.length]; } *getTransformationsFrom(version, filter) { for (let v = version; v < this.transformations.length; v++) { const transformation = this.transformations[v]; if (!filter || filter(transformation)) { yield transformation; } } } } /***/ }), /* 135 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CombinedTransformer: () => (/* binding */ CombinedTransformer) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class CombinedTransformer { constructor(sheet) { this.sheet = sheet; this.transformations = []; } add(transformation) { this.transformations.push(transformation); } performEagerTransformations(graph, parser) { this.transformations.forEach(transformation => transformation.performEagerTransformations(graph, parser)); } transformSingleAst(ast, address) { let [transformedAst, transformedAddress] = [ast, address]; this.transformations.forEach(transformation => { [transformedAst, transformedAddress] = transformation.transformSingleAst(transformedAst, transformedAddress); }); return [transformedAst, transformedAddress]; } isIrreversible() { return true; } } /***/ }), /* 136 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ buildColumnSearchStrategy: () => (/* binding */ buildColumnSearchStrategy) /* harmony export */ }); /* harmony import */ var _ColumnBinarySearch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(137); /* harmony import */ var _ColumnIndex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(140); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function buildColumnSearchStrategy(dependencyGraph, config, statistics) { if (config.useColumnIndex) { return new _ColumnIndex__WEBPACK_IMPORTED_MODULE_1__.ColumnIndex(dependencyGraph, config, statistics); } else { return new _ColumnBinarySearch__WEBPACK_IMPORTED_MODULE_0__.ColumnBinarySearch(dependencyGraph); } } /***/ }), /* 137 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ColumnBinarySearch: () => (/* binding */ ColumnBinarySearch) /* harmony export */ }); /* harmony import */ var _AdvancedFind__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(138); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ColumnBinarySearch extends _AdvancedFind__WEBPACK_IMPORTED_MODULE_0__.AdvancedFind { constructor(dependencyGraph) { super(dependencyGraph); this.dependencyGraph = dependencyGraph; } // eslint-disable-next-line @typescript-eslint/no-unused-vars add(value, address) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars remove(value, address) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars change(oldValue, newValue, address) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars applyChanges(contentChanges) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars addColumns(columnsSpan) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars removeColumns(columnsSpan) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars removeSheet(sheetId) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars moveValues(sourceRange, toRight, toBottom, toSheet) {} // eslint-disable-next-line @typescript-eslint/no-unused-vars removeValues(range) {} /* * WARNING: Finding lower/upper bounds in unordered ranges is not supported. When ordering === 'none', assumes matchExactly === true */ find(searchKey, rangeValue, searchOptions) { return this.basicFind(searchKey, rangeValue, 'row', searchOptions); } } /***/ }), /* 138 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AdvancedFind: () => (/* binding */ AdvancedFind) /* harmony export */ }); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70); /* harmony import */ var _interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(98); /* harmony import */ var _interpreter_binarySearch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(139); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AdvancedFind { constructor(dependencyGraph) { this.dependencyGraph = dependencyGraph; } advancedFind(keyMatcher, rangeValue) { let values; const range = rangeValue.range; if (range === undefined) { values = rangeValue.valuesFromTopLeftCorner(); } else { values = this.dependencyGraph.computeListOfValuesInRange(range); } for (let i = 0; i < values.length; i++) { if (keyMatcher((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.getRawValue)(values[i]))) { return i; } } return -1; } /* * WARNING: Finding lower/upper bounds in unordered ranges is not supported. When ordering === 'none', assumes matchExactly === true */ basicFind(searchKey, rangeValue, searchCoordinate, { ordering, matchExactly }) { const normalizedSearchKey = typeof searchKey === 'string' ? (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_1__.forceNormalizeString)(searchKey) : searchKey; const range = rangeValue.range; if (range === undefined) { return this.findNormalizedValue(normalizedSearchKey, rangeValue.valuesFromTopLeftCorner()); } if (ordering === 'none') { return this.findNormalizedValue(normalizedSearchKey, this.dependencyGraph.computeListOfValuesInRange(range)); } return (0,_interpreter_binarySearch__WEBPACK_IMPORTED_MODULE_2__.findLastOccurrenceInOrderedRange)(normalizedSearchKey, range, { searchCoordinate, orderingDirection: ordering, matchExactly }, this.dependencyGraph); } findNormalizedValue(searchKey, searchArray) { return searchArray.map(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.getRawValue).map(val => typeof val === 'string' ? (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_1__.forceNormalizeString)(val) : val).indexOf(searchKey); } } /***/ }), /* 139 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ compare: () => (/* binding */ compare), /* harmony export */ findLastMatchingIndex: () => (/* binding */ findLastMatchingIndex), /* harmony export */ findLastOccurrenceInOrderedArray: () => (/* binding */ findLastOccurrenceInOrderedArray), /* harmony export */ findLastOccurrenceInOrderedRange: () => (/* binding */ findLastOccurrenceInOrderedRange) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const NOT_FOUND = -1; /* * Searches for the searchKey in a sorted 1-D range. * * Options: * - searchCoordinate - must be set to either 'row' or 'col' to indicate the dimension of the search, * - orderingDirection - must be set to either 'asc' or 'desc' to indicate the ordering direction for the search range, * - matchExactly - when set to false, searches for the lower/upper bound. * * Semantics: * - If orderingDirection === 'asc', searches for the lower bound for the searchKey value (unless marchExactly === true). * - If orderingDirection === 'desc', searches for the upper bound for the searchKey value (unless marchExactly === true). * - If the search range contains duplicates, returns the last matching value. * - If no value in the range satisfies the above, returns -1. * * Note: this function does not normalize input strings. */ function findLastOccurrenceInOrderedRange(searchKey, range, { searchCoordinate, orderingDirection, matchExactly }, dependencyGraph) { const start = range.start[searchCoordinate]; const end = searchCoordinate === 'col' ? range.effectiveEndColumn(dependencyGraph) : range.effectiveEndRow(dependencyGraph); const getValueFromIndexFn = searchCoordinate === 'col' ? index => (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.getRawValue)(dependencyGraph.getCellValue((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(range.sheet, index, range.start.row))) : index => (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.getRawValue)(dependencyGraph.getCellValue((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(range.sheet, range.start.col, index))); const compareFn = orderingDirection === 'asc' ? (left, right) => compare(left, right) : (left, right) => -compare(left, right); const foundIndex = findLastMatchingIndex(index => compareFn(searchKey, getValueFromIndexFn(index)) >= 0, start, end); const foundValue = getValueFromIndexFn(foundIndex); if (foundIndex === NOT_FOUND || typeof foundValue !== typeof searchKey) { return NOT_FOUND; } if (matchExactly && foundValue !== searchKey) { return NOT_FOUND; } return foundIndex - start; } /* * Searches for the searchKey in a sorted array. * Param orderingDirection must be set to either 'asc' or 'desc' to indicate the ordering direction of the array. * * Semantics: * - If orderingDirection === 'asc', searches for the lower bound for the searchKey value. * - If orderingDirection === 'desc', searches for the upper bound for the searchKey value. * - If the array contains duplicates, returns the last matching value. * - If no value in the range satisfies the above, returns -1. */ function findLastOccurrenceInOrderedArray(searchKey, array, orderingDirection = 'asc') { const predicate = orderingDirection === 'asc' ? index => compare(searchKey, array[index]) >= 0 : index => -compare(searchKey, array[index]) >= 0; return findLastMatchingIndex(predicate, 0, array.length - 1); } /* * Returns: * - the last element in the range for which predicate === true or, * - value -1 if predicate === false for all elements. * Assumption: All elements for which predicate === true are before the elements for which predicate === false. */ function findLastMatchingIndex(predicate, startRange, endRange) { let start = startRange; let end = endRange; while (start < end) { const pivot = Math.ceil((start + end) / 2); if (predicate(pivot)) { start = pivot; } else { end = pivot - 1; } } if (start === end && predicate(start)) { return start; } return NOT_FOUND; } /* * numbers < strings < false < true */ function compare(left, right) { if (typeof left === typeof right) { if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue) { return 0; } return left < right ? -1 : left > right ? 1 : 0; } if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue) { return -1; } if (right === _InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue) { return 1; } if (right instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return -1; } if (typeof left === 'number' && typeof right === 'string') { return -1; } if (typeof left === 'number' && typeof right === 'boolean') { return -1; } if (typeof left === 'string' && typeof right === 'number') { return 1; } if (typeof left === 'string' && typeof right === 'boolean') { return -1; } return 1; } /***/ }), /* 140 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ColumnIndex: () => (/* binding */ ColumnIndex), /* harmony export */ findInOrderedArray: () => (/* binding */ findInOrderedArray) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _dependencyTransformers_AddRowsTransformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(119); /* harmony import */ var _dependencyTransformers_RemoveRowsTransformer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(123); /* harmony import */ var _interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98); /* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(69); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(72); /* harmony import */ var _ColumnBinarySearch__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(137); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ColumnIndex { constructor(dependencyGraph, config, stats) { this.dependencyGraph = dependencyGraph; this.config = config; this.stats = stats; this.index = new Map(); this.transformingService = this.dependencyGraph.lazilyTransformingAstService; this.binarySearchStrategy = new _ColumnBinarySearch__WEBPACK_IMPORTED_MODULE_7__.ColumnBinarySearch(dependencyGraph); } add(value, address) { if (value === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue || value instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return; } else if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) { for (const [arrayValue, cellAddress] of value.entriesFromTopLeftCorner(address)) { this.addSingleCellValue((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arrayValue), cellAddress); } } else { this.addSingleCellValue(value, address); } } remove(value, address) { if (value === undefined) { return; } if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) { for (const [arrayValue, cellAddress] of value.entriesFromTopLeftCorner(address)) { this.removeSingleValue((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arrayValue), cellAddress); } } else { this.removeSingleValue(value, address); } } change(oldValue, newValue, address) { if (oldValue === newValue) { return; } this.remove(oldValue, address); this.add(newValue, address); } applyChanges(contentChanges) { for (const change of contentChanges) { if (change.oldValue !== undefined) { this.change((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(change.oldValue), (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(change.value), change.address); } } } moveValues(sourceRange, toRight, toBottom, toSheet) { for (const [value, address] of sourceRange) { const targetAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.movedSimpleCellAddress)(address, toSheet, toRight, toBottom); this.remove(value, address); this.add(value, targetAddress); } } removeValues(range) { for (const [value, address] of range) { this.remove(value, address); } } /* * WARNING: Finding lower/upper bounds in unordered ranges is not supported. When ordering === 'none', assumes matchExactly === true */ find(searchKey, rangeValue, { ordering, matchExactly }) { const handlingDuplicates = matchExactly === true ? 'findFirst' : 'findLast'; const resultUsingColumnIndex = this.findUsingColumnIndex(searchKey, rangeValue, handlingDuplicates); return resultUsingColumnIndex !== undefined ? resultUsingColumnIndex : this.binarySearchStrategy.find(searchKey, rangeValue, { ordering, matchExactly }); } findUsingColumnIndex(key, rangeValue, handlingDuplicates) { const range = rangeValue.range; if (range === undefined) { return undefined; } this.ensureRecentData(range.sheet, range.start.col, key); const columnMap = this.getColumnMap(range.sheet, range.start.col); if (!columnMap) { return -1; } const normalizedKey = typeof key === 'string' ? (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_3__.forceNormalizeString)(key) : key; const valueIndexForTheKey = columnMap.get(normalizedKey); if (!valueIndexForTheKey || !valueIndexForTheKey.index || valueIndexForTheKey.index.length === 0) { return undefined; } const rowNumber = ColumnIndex.findRowBelongingToRange(valueIndexForTheKey, range, handlingDuplicates); return rowNumber !== undefined ? rowNumber - range.start.row : undefined; } static findRowBelongingToRange(valueIndex, range, handlingDuplicates) { const start = range.start.row; const end = range.end.row; const positionInIndex = handlingDuplicates === 'findFirst' ? findInOrderedArray(start, valueIndex.index, 'upperBound') : findInOrderedArray(end, valueIndex.index, 'lowerBound'); if (positionInIndex === -1) { return undefined; } const rowNumber = valueIndex.index[positionInIndex]; const isRowNumberBelongingToRange = rowNumber >= start && rowNumber <= end; return isRowNumberBelongingToRange ? rowNumber : undefined; } advancedFind(keyMatcher, range) { return this.binarySearchStrategy.advancedFind(keyMatcher, range); } addColumns(columnsSpan) { const sheetIndex = this.index.get(columnsSpan.sheet); if (!sheetIndex) { return; } sheetIndex.splice(columnsSpan.columnStart, 0, ...Array(columnsSpan.numberOfColumns)); } removeColumns(columnsSpan) { const sheetIndex = this.index.get(columnsSpan.sheet); if (!sheetIndex) { return; } sheetIndex.splice(columnsSpan.columnStart, columnsSpan.numberOfColumns); } removeSheet(sheetId) { this.index.delete(sheetId); } getColumnMap(sheet, col) { if (!this.index.has(sheet)) { this.index.set(sheet, []); } const sheetMap = this.index.get(sheet); // eslint-disable-line @typescript-eslint/no-non-null-assertion let columnMap = sheetMap[col]; if (!columnMap) { columnMap = new Map(); sheetMap[col] = columnMap; } return columnMap; } getValueIndex(sheet, col, value) { const columnMap = this.getColumnMap(sheet, col); let index = this.getColumnMap(sheet, col).get(value); if (!index) { index = { version: this.transformingService.version(), index: [] }; columnMap.set(value, index); } return index; } ensureRecentData(sheet, col, value) { const valueIndex = this.getValueIndex(sheet, col, value); const actualVersion = this.transformingService.version(); if (valueIndex.version === actualVersion) { return; } const relevantTransformations = this.transformingService.getTransformationsFrom(valueIndex.version, transformation => { return transformation.sheet === sheet && (transformation instanceof _dependencyTransformers_AddRowsTransformer__WEBPACK_IMPORTED_MODULE_1__.AddRowsTransformer || transformation instanceof _dependencyTransformers_RemoveRowsTransformer__WEBPACK_IMPORTED_MODULE_2__.RemoveRowsTransformer); }); for (const transformation of relevantTransformations) { if (transformation instanceof _dependencyTransformers_AddRowsTransformer__WEBPACK_IMPORTED_MODULE_1__.AddRowsTransformer) { this.addRows(col, transformation.rowsSpan, value); } else if (transformation instanceof _dependencyTransformers_RemoveRowsTransformer__WEBPACK_IMPORTED_MODULE_2__.RemoveRowsTransformer) { this.removeRows(col, transformation.rowsSpan, value); } } valueIndex.version = actualVersion; } addSingleCellValue(value, address) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_6__.StatType.BUILD_COLUMN_INDEX, () => { this.ensureRecentData(address.sheet, address.col, value); if (typeof value === 'string') { value = (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_3__.forceNormalizeString)(value); } const valueIndex = this.getValueIndex(address.sheet, address.col, value); ColumnIndex.addValue(valueIndex, address.row); }); } removeSingleValue(value, address) { this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_6__.StatType.BUILD_COLUMN_INDEX, () => { this.ensureRecentData(address.sheet, address.col, value); const columnMap = this.getColumnMap(address.sheet, address.col); if (typeof value === 'string') { value = (0,_interpreter_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_3__.forceNormalizeString)(value); } const valueIndex = columnMap.get(value); if (!valueIndex) { return; } const positionInIndex = findInOrderedArray(address.row, valueIndex.index); if (positionInIndex > -1) { valueIndex.index.splice(positionInIndex, 1); } if (valueIndex.index.length === 0) { columnMap.delete(value); } if (columnMap.size === 0) { delete this.index.get(address.sheet)[address.col]; // eslint-disable-line @typescript-eslint/no-non-null-assertion } }); } addRows(col, rowsSpan, value) { const valueIndex = this.getValueIndex(rowsSpan.sheet, col, value); ColumnIndex.shiftRows(valueIndex, rowsSpan.rowStart, rowsSpan.numberOfRows); } removeRows(col, rowsSpan, value) { const valueIndex = this.getValueIndex(rowsSpan.sheet, col, value); ColumnIndex.removeRowsFromValues(valueIndex, rowsSpan); ColumnIndex.shiftRows(valueIndex, rowsSpan.rowEnd + 1, -rowsSpan.numberOfRows); } static addValue(valueIndex, rowNumber) { const rowIndex = findInOrderedArray(rowNumber, valueIndex.index, 'lowerBound'); const isRowNumberAlreadyInIndex = valueIndex.index[rowIndex] === rowNumber; if (!isRowNumberAlreadyInIndex) { valueIndex.index.splice(rowIndex + 1, 0, rowNumber); } } static removeRowsFromValues(valueIndex, rowsSpan) { const start = findInOrderedArray(rowsSpan.rowStart, valueIndex.index, 'upperBound'); const end = findInOrderedArray(rowsSpan.rowEnd, valueIndex.index, 'lowerBound'); const isFoundSpanValid = start > -1 && end > -1 && start <= end && valueIndex.index[start] <= rowsSpan.rowEnd; if (isFoundSpanValid) { valueIndex.index.splice(start, end - start + 1); } } static shiftRows(valueIndex, afterRow, numberOfRows) { const positionInIndex = findInOrderedArray(afterRow, valueIndex.index, 'upperBound'); if (positionInIndex === -1) { return; } for (let i = positionInIndex; i < valueIndex.index.length; ++i) { valueIndex.index[i] += numberOfRows; } } } /* * Returns: * - index of the key, if the key exists in the array, * - index of the lower/upper bound (depending on handlingMisses parameter) otherwise. * Assumption: The array is ordered ascending and contains no repetitions. */ function findInOrderedArray(key, values, handlingMisses = 'upperBound') { let start = 0; let end = values.length - 1; while (start <= end) { const center = Math.floor((start + end) / 2); if (key > values[center]) { start = center + 1; } else if (key < values[center]) { end = center - 1; } else { return center; } } const foundIndex = handlingMisses === 'lowerBound' ? end : start; const isIndexInRange = foundIndex >= 0 && foundIndex <= values.length; return isIndexInRange ? foundIndex : -1; } /***/ }), /* 141 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ NumberLiteralHelper: () => (/* binding */ NumberLiteralHelper) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class NumberLiteralHelper { constructor(config) { this.config = config; const thousandSeparator = this.config.thousandSeparator === '.' ? `\\${this.config.thousandSeparator}` : this.config.thousandSeparator; const decimalSeparator = this.config.decimalSeparator === '.' ? `\\${this.config.decimalSeparator}` : this.config.decimalSeparator; this.numberPattern = new RegExp(`^([+-]?((${decimalSeparator}\\d+)|(\\d+(${thousandSeparator}\\d{3,})*(${decimalSeparator}\\d*)?)))(e[+-]?\\d+)?$`); this.allThousandSeparatorsRegex = new RegExp(`${thousandSeparator}`, 'g'); } numericStringToMaybeNumber(input) { if (this.numberPattern.test(input)) { const num = this.numericStringToNumber(input); if (isNaN(num)) { return undefined; } return num; } return undefined; } numericStringToNumber(input) { const normalized = input.replace(this.allThousandSeparatorsRegex, '').replace(this.config.decimalSeparator, '.'); return Number(normalized); } } /***/ }), /* 142 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Serialization: () => (/* binding */ Serialization) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class Serialization { constructor(dependencyGraph, unparser, exporter) { this.dependencyGraph = dependencyGraph; this.unparser = unparser; this.exporter = exporter; } getCellHyperlink(address) { const formulaVertex = this.dependencyGraph.getCell(address); if (formulaVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_1__.FormulaCellVertex) { const formula = formulaVertex.getFormula(this.dependencyGraph.lazilyTransformingAstService); if ('HYPERLINK' === formula.procedureName) { return formula.hyperlink; } } return undefined; } getCellFormula(address, targetAddress) { const formulaVertex = this.dependencyGraph.getCell(address); if (formulaVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_1__.FormulaCellVertex) { const formula = formulaVertex.getFormula(this.dependencyGraph.lazilyTransformingAstService); targetAddress = targetAddress !== null && targetAddress !== void 0 ? targetAddress : address; return this.unparser.unparse(formula, targetAddress); } else if (formulaVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_1__.ArrayVertex) { const arrayVertexAddress = formulaVertex.getAddress(this.dependencyGraph.lazilyTransformingAstService); if (arrayVertexAddress.row !== address.row || arrayVertexAddress.col !== address.col || arrayVertexAddress.sheet !== address.sheet) { return undefined; } targetAddress = targetAddress !== null && targetAddress !== void 0 ? targetAddress : address; const formula = formulaVertex.getFormula(this.dependencyGraph.lazilyTransformingAstService); if (formula !== undefined) { return this.unparser.unparse(formula, targetAddress); } } else if (formulaVertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_1__.ParsingErrorVertex) { return formulaVertex.getFormula(); } return undefined; } getCellSerialized(address, targetAddress) { var _a; return (_a = this.getCellFormula(address, targetAddress)) !== null && _a !== void 0 ? _a : this.getRawValue(address); } getCellValue(address) { return this.exporter.exportValue(this.dependencyGraph.getScalarValue(address)); } getRawValue(address) { return this.dependencyGraph.getRawValue(address); } getSheetValues(sheet) { return this.genericSheetGetter(sheet, arg => this.getCellValue(arg)); } getSheetFormulas(sheet) { return this.genericSheetGetter(sheet, arg => this.getCellFormula(arg)); } genericSheetGetter(sheet, getter) { const sheetHeight = this.dependencyGraph.getSheetHeight(sheet); const sheetWidth = this.dependencyGraph.getSheetWidth(sheet); const arr = new Array(sheetHeight); for (let i = 0; i < sheetHeight; i++) { arr[i] = new Array(sheetWidth); for (let j = 0; j < sheetWidth; j++) { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, j, i); arr[i][j] = getter(address); } for (let j = sheetWidth - 1; j >= 0; j--) { if (arr[i][j] === null || arr[i][j] === undefined) { arr[i].pop(); } else { break; } } } for (let i = sheetHeight - 1; i >= 0; i--) { if (arr[i].length === 0) { arr.pop(); } else { break; } } return arr; } genericAllSheetsGetter(sheetGetter) { const result = {}; for (const sheetName of this.dependencyGraph.sheetMapping.displayNames()) { const sheetId = this.dependencyGraph.sheetMapping.fetch(sheetName); result[sheetName] = sheetGetter(sheetId); } return result; } getSheetSerialized(sheet) { return this.genericSheetGetter(sheet, arg => this.getCellSerialized(arg)); } getAllSheetsValues() { return this.genericAllSheetsGetter(arg => this.getSheetValues(arg)); } getAllSheetsFormulas() { return this.genericAllSheetsGetter(arg => this.getSheetFormulas(arg)); } getAllSheetsSerialized() { return this.genericAllSheetsGetter(arg => this.getSheetSerialized(arg)); } getAllNamedExpressionsSerialized() { const idMap = []; let id = 0; for (const sheetName of this.dependencyGraph.sheetMapping.displayNames()) { const sheetId = this.dependencyGraph.sheetMapping.fetch(sheetName); idMap[sheetId] = id; id++; } return this.dependencyGraph.namedExpressions.getAllNamedExpressions().map(entry => { return { name: entry.expression.displayName, expression: this.getCellSerialized(entry.expression.address), scope: entry.scope !== undefined ? idMap[entry.scope] : undefined, options: entry.expression.options }; }); } withNewConfig(newConfig, namedExpressions) { const newUnparser = new _parser__WEBPACK_IMPORTED_MODULE_2__.Unparser(newConfig, (0,_parser__WEBPACK_IMPORTED_MODULE_2__.buildLexerConfig)(newConfig), this.dependencyGraph.sheetMapping.fetchDisplayName, namedExpressions); return new Serialization(this.dependencyGraph, newUnparser, this.exporter); } } /***/ }), /* 143 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ objectDestroy: () => (/* binding */ objectDestroy) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function objectDestroy(object) { for (const [key, value] of Object.entries(object)) { if (value instanceof Function) { object[key] = postMortem(value); } else { delete object[key]; } } } function postMortem(method) { return () => { throw new Error(`The "${method}" method cannot be called because this HyperFormula instance has been destroyed`); }; } /***/ }), /* 144 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Emitter: () => (/* binding */ Emitter), /* harmony export */ Events: () => (/* binding */ Events) /* harmony export */ }); /* harmony import */ var tiny_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(145); /* harmony import */ var tiny_emitter__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(tiny_emitter__WEBPACK_IMPORTED_MODULE_0__); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var Events; (function (Events) { Events["SheetAdded"] = "sheetAdded"; Events["SheetRemoved"] = "sheetRemoved"; Events["SheetRenamed"] = "sheetRenamed"; Events["NamedExpressionAdded"] = "namedExpressionAdded"; Events["NamedExpressionRemoved"] = "namedExpressionRemoved"; Events["ValuesUpdated"] = "valuesUpdated"; Events["EvaluationSuspended"] = "evaluationSuspended"; Events["EvaluationResumed"] = "evaluationResumed"; })(Events || (Events = {})); class Emitter extends tiny_emitter__WEBPACK_IMPORTED_MODULE_0__.TinyEmitter { emit(event, ...args) { super.emit(event, ...args); return this; } } /***/ }), /* 145 */ /***/ ((module) => { function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } E.prototype = { on: function (name, callback, ctx) { var e = this.e || (this.e = {}); (e[name] || (e[name] = [])).push({ fn: callback, ctx: ctx }); return this; }, once: function (name, callback, ctx) { var self = this; function listener () { self.off(name, listener); callback.apply(ctx, arguments); }; listener._ = callback return this.on(name, listener, ctx); }, emit: function (name) { var data = [].slice.call(arguments, 1); var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); var i = 0; var len = evtArr.length; for (i; i < len; i++) { evtArr[i].fn.apply(evtArr[i].ctx, data); } return this; }, off: function (name, callback) { var e = this.e || (this.e = {}); var evts = e[name]; var liveEvents = []; if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]); } } // Remove event from queue to prevent memory leak // Suggested by https://github.com/lazd // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 (liveEvents.length) ? e[name] = liveEvents : delete e[name]; return this; } }; module.exports = E; module.exports.TinyEmitter = E; /***/ }), /* 146 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const dictionary = { errors: { CYCLE: '#CYCLE!', DIV_BY_ZERO: '#DIV/0!', ERROR: '#ERROR!', NA: '#N/A', NAME: '#NAME?', NUM: '#NUM!', REF: '#REF!', SPILL: '#SPILL!', VALUE: '#VALUE!' }, functions: { FILTER: 'FILTER', ADDRESS: 'ADDRESS', 'ARRAY_CONSTRAIN': 'ARRAY_CONSTRAIN', ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', ACOT: 'ACOT', ACOTH: 'ACOTH', AND: 'AND', ARABIC: 'ARABIC', ASIN: 'ASIN', ASINH: 'ASINH', ATAN2: 'ATAN2', ATAN: 'ATAN', ATANH: 'ATANH', AVERAGE: 'AVERAGE', AVERAGEA: 'AVERAGEA', AVERAGEIF: 'AVERAGEIF', BASE: 'BASE', BIN2DEC: 'BIN2DEC', BIN2HEX: 'BIN2HEX', BIN2OCT: 'BIN2OCT', BITAND: 'BITAND', BITLSHIFT: 'BITLSHIFT', BITOR: 'BITOR', BITRSHIFT: 'BITRSHIFT', BITXOR: 'BITXOR', CEILING: 'CEILING', CHAR: 'CHAR', CHOOSE: 'CHOOSE', CLEAN: 'CLEAN', CODE: 'CODE', COLUMN: 'COLUMN', COLUMNS: 'COLUMNS', CONCATENATE: 'CONCATENATE', CORREL: 'CORREL', COS: 'COS', COSH: 'COSH', COT: 'COT', COTH: 'COTH', COUNT: 'COUNT', COUNTA: 'COUNTA', COUNTBLANK: 'COUNTBLANK', COUNTIF: 'COUNTIF', COUNTIFS: 'COUNTIFS', COUNTUNIQUE: 'COUNTUNIQUE', CSC: 'CSC', CSCH: 'CSCH', CUMIPMT: 'CUMIPMT', CUMPRINC: 'CUMPRINC', DATE: 'DATE', DATEDIF: 'DATEDIF', DATEVALUE: 'DATEVALUE', DAY: 'DAY', DAYS360: 'DAYS360', DAYS: 'DAYS', DB: 'DB', DDB: 'DDB', DEC2BIN: 'DEC2BIN', DEC2HEX: 'DEC2HEX', DEC2OCT: 'DEC2OCT', DECIMAL: 'DECIMAL', DEGREES: 'DEGREES', DELTA: 'DELTA', DOLLARDE: 'DOLLARDE', DOLLARFR: 'DOLLARFR', EDATE: 'EDATE', EFFECT: 'EFFECT', EOMONTH: 'EOMONTH', ERF: 'ERF', ERFC: 'ERFC', EVEN: 'EVEN', EXACT: 'EXACT', EXP: 'EXP', FALSE: 'FALSE', FIND: 'FIND', FORMULATEXT: 'FORMULATEXT', FV: 'FV', FVSCHEDULE: 'FVSCHEDULE', HEX2BIN: 'HEX2BIN', HEX2DEC: 'HEX2DEC', HEX2OCT: 'HEX2OCT', HLOOKUP: 'HLOOKUP', HOUR: 'HOUR', HYPERLINK: 'HYPERLINK', IF: 'IF', IFERROR: 'IFERROR', IFNA: 'IFNA', IFS: 'IFS', INDEX: 'INDEX', INT: 'INT', INTERVAL: 'INTERVAL', IPMT: 'IPMT', ISBINARY: 'ISBINARY', ISBLANK: 'ISBLANK', ISERR: 'ISERR', ISERROR: 'ISERROR', ISEVEN: 'ISEVEN', ISFORMULA: 'ISFORMULA', ISLOGICAL: 'ISLOGICAL', ISNA: 'ISNA', ISNONTEXT: 'ISNONTEXT', ISNUMBER: 'ISNUMBER', ISODD: 'ISODD', ISOWEEKNUM: 'ISOWEEKNUM', ISPMT: 'ISPMT', ISREF: 'ISREF', ISTEXT: 'ISTEXT', LEFT: 'LEFT', LEN: 'LEN', LN: 'LN', LOG10: 'LOG10', LOG: 'LOG', LOWER: 'LOWER', MATCH: 'MATCH', MAX: 'MAX', MAXA: 'MAXA', MAXIFS: 'MAXIFS', MAXPOOL: 'MAXPOOL', MEDIAN: 'MEDIAN', MEDIANPOOL: 'MEDIANPOOL', MID: 'MID', MIN: 'MIN', MINA: 'MINA', MINIFS: 'MINIFS', MINUTE: 'MINUTE', MIRR: 'MIRR', MMULT: 'MMULT', MOD: 'MOD', MONTH: 'MONTH', NA: 'NA', NETWORKDAYS: 'NETWORKDAYS', 'NETWORKDAYS.INTL': 'NETWORKDAYS.INTL', NOMINAL: 'NOMINAL', NOT: 'NOT', NOW: 'NOW', NPER: 'NPER', NPV: 'NPV', OCT2BIN: 'OCT2BIN', OCT2DEC: 'OCT2DEC', OCT2HEX: 'OCT2HEX', ODD: 'ODD', OFFSET: 'OFFSET', OR: 'OR', PI: 'PI', PMT: 'PMT', PDURATION: 'PDURATION', PRODUCT: 'PRODUCT', POWER: 'POWER', PPMT: 'PPMT', PROPER: 'PROPER', PV: 'PV', RADIANS: 'RADIANS', RAND: 'RAND', RATE: 'RATE', REPLACE: 'REPLACE', REPT: 'REPT', RIGHT: 'RIGHT', ROMAN: 'ROMAN', ROUND: 'ROUND', ROUNDDOWN: 'ROUNDDOWN', ROUNDUP: 'ROUNDUP', ROW: 'ROW', ROWS: 'ROWS', RRI: 'RRI', SEARCH: 'SEARCH', SEC: 'SEC', SECH: 'SECH', SECOND: 'SECOND', SHEET: 'SHEET', SHEETS: 'SHEETS', SIN: 'SIN', SINH: 'SINH', SLN: 'SLN', SPLIT: 'SPLIT', SQRT: 'SQRT', STDEVA: 'STDEVA', 'STDEV.P': 'STDEV.P', STDEVPA: 'STDEVPA', 'STDEV.S': 'STDEV.S', SUBSTITUTE: 'SUBSTITUTE', SUBTOTAL: 'SUBTOTAL', SUM: 'SUM', SUMIF: 'SUMIF', SUMIFS: 'SUMIFS', SUMPRODUCT: 'SUMPRODUCT', SUMSQ: 'SUMSQ', SWITCH: 'SWITCH', SYD: 'SYD', T: 'T', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'TBILLEQ', TBILLPRICE: 'TBILLPRICE', TBILLYIELD: 'TBILLYIELD', TEXT: 'TEXT', TIME: 'TIME', TIMEVALUE: 'TIMEVALUE', TODAY: 'TODAY', TRANSPOSE: 'TRANSPOSE', TRIM: 'TRIM', TRUE: 'TRUE', TRUNC: 'TRUNC', UNICHAR: 'UNICHAR', UNICODE: 'UNICODE', UPPER: 'UPPER', VARA: 'VARA', 'VAR.P': 'VAR.P', VARPA: 'VARPA', 'VAR.S': 'VAR.S', VLOOKUP: 'VLOOKUP', WEEKDAY: 'WEEKDAY', WEEKNUM: 'WEEKNUM', WORKDAY: 'WORKDAY', 'WORKDAY.INTL': 'WORKDAY.INTL', XNPV: 'XNPV', XOR: 'XOR', YEAR: 'YEAR', YEARFRAC: 'YEARFRAC', 'HF.ADD': 'HF.ADD', 'HF.CONCAT': 'HF.CONCAT', 'HF.DIVIDE': 'HF.DIVIDE', 'HF.EQ': 'HF.EQ', 'HF.GT': 'HF.GT', 'HF.GTE': 'HF.GTE', 'HF.LT': 'HF.LT', 'HF.LTE': 'HF.LTE', 'HF.MINUS': 'HF.MINUS', 'HF.MULTIPLY': 'HF.MULTIPLY', 'HF.NE': 'HF.NE', 'HF.POW': 'HF.POW', 'HF.UMINUS': 'HF.UMINUS', 'HF.UNARY_PERCENT': 'HF.UNARY_PERCENT', 'HF.UPLUS': 'HF.UPLUS', VARP: 'VARP', VAR: 'VAR', STDEVP: 'STDEVP', STDEV: 'STDEV', 'EXPON.DIST': 'EXPON.DIST', FISHER: 'FISHER', FISHERINV: 'FISHERINV', GAMMA: 'GAMMA', 'GAMMA.DIST': 'GAMMA.DIST', GAMMALN: 'GAMMALN', 'GAMMALN.PRECISE': 'GAMMALN.PRECISE', 'GAMMA.INV': 'GAMMA.INV', GAUSS: 'GAUSS', FACT: 'FACT', FACTDOUBLE: 'FACTDOUBLE', COMBIN: 'COMBIN', COMBINA: 'COMBINA', GCD: 'GCD', LCM: 'LCM', MROUND: 'MROUND', MULTINOMIAL: 'MULTINOMIAL', QUOTIENT: 'QUOTIENT', RANDBETWEEN: 'RANDBETWEEN', SERIESSUM: 'SERIESSUM', SIGN: 'SIGN', SQRTPI: 'SQRTPI', SUMX2MY2: 'SUMX2MY2', SUMX2PY2: 'SUMX2PY2', SUMXMY2: 'SUMXMY2', 'EXPONDIST': 'EXPONDIST', GAMMADIST: 'GAMMADIST', GAMMAINV: 'GAMMAINV', 'BETA.DIST': 'BETA.DIST', BETADIST: 'BETADIST', 'BETA.INV': 'BETA.INV', BETAINV: 'BETAINV', 'BINOM.DIST': 'BINOM.DIST', BINOMDIST: 'BINOMDIST', 'BINOM.INV': 'BINOM.INV', BESSELI: 'BESSELI', BESSELJ: 'BESSELJ', BESSELK: 'BESSELK', BESSELY: 'BESSELY', 'CHISQ.DIST': 'CHISQ.DIST', 'CHISQ.DIST.RT': 'CHISQ.DIST.RT', 'CHISQ.INV': 'CHISQ.INV', 'CHISQ.INV.RT': 'CHISQ.INV.RT', CHIDIST: 'CHIDIST', CHIINV: 'CHIINV', 'F.DIST': 'F.DIST', 'F.DIST.RT': 'F.DIST.RT', 'F.INV': 'F.INV', 'F.INV.RT': 'F.INV.RT', FDIST: 'FDIST', FINV: 'FINV', WEIBULL: 'WEIBULL', 'WEIBULL.DIST': 'WEIBULL.DIST', POISSON: 'POISSON', 'POISSON.DIST': 'POISSON.DIST', 'HYPGEOM.DIST': 'HYPGEOM.DIST', HYPGEOMDIST: 'HYPGEOMDIST', 'T.DIST': 'T.DIST', 'T.DIST.2T': 'T.DIST.2T', 'T.DIST.RT': 'T.DIST.RT', 'T.INV': 'T.INV', 'T.INV.2T': 'T.INV.2T', TDIST: 'TDIST', TINV: 'TINV', LOGINV: 'LOGINV', 'LOGNORM.DIST': 'LOGNORM.DIST', 'LOGNORM.INV': 'LOGNORM.INV', LOGNORMDIST: 'LOGNORMDIST', 'NORM.DIST': 'NORM.DIST', 'NORM.INV': 'NORM.INV', 'NORM.S.DIST': 'NORM.S.DIST', 'NORM.S.INV': 'NORM.S.INV', NORMDIST: 'NORMDIST', NORMINV: 'NORMINV', NORMSDIST: 'NORMSDIST', NORMSINV: 'NORMSINV', PHI: 'PHI', 'NEGBINOM.DIST': 'NEGBINOM.DIST', 'NEGBINOMDIST': 'NEGBINOMDIST', COMPLEX: 'COMPLEX', IMABS: 'IMABS', IMAGINARY: 'IMAGINARY', IMARGUMENT: 'IMARGUMENT', IMCONJUGATE: 'IMCONJUGATE', IMCOS: 'IMCOS', IMCOSH: 'IMCOSH', IMCOT: 'IMCOT', IMCSC: 'IMCSC', IMCSCH: 'IMCSCH', IMDIV: 'IMDIV', IMEXP: 'IMEXP', IMLN: 'IMLN', IMLOG10: 'IMLOG10', IMLOG2: 'IMLOG2', IMPOWER: 'IMPOWER', IMPRODUCT: 'IMPRODUCT', IMREAL: 'IMREAL', IMSEC: 'IMSEC', IMSECH: 'IMSECH', IMSIN: 'IMSIN', IMSINH: 'IMSINH', IMSQRT: 'IMSQRT', IMSUB: 'IMSUB', IMSUM: 'IMSUM', IMTAN: 'IMTAN', LARGE: 'LARGE', SMALL: 'SMALL', AVEDEV: 'AVEDEV', CONFIDENCE: 'CONFIDENCE', 'CONFIDENCE.NORM': 'CONFIDENCE.NORM', 'CONFIDENCE.T': 'CONFIDENCE.T', DEVSQ: 'DEVSQ', GEOMEAN: 'GEOMEAN', HARMEAN: 'HARMEAN', CRITBINOM: 'CRITBINOM', 'COVARIANCE.P': 'COVARIANCE.P', 'COVARIANCE.S': 'COVARIANCE.S', 'COVAR': 'COVAR', PEARSON: 'PEARSON', RSQ: 'RSQ', STANDARDIZE: 'STANDARDIZE', 'Z.TEST': 'Z.TEST', ZTEST: 'ZTEST', 'F.TEST': 'F.TEST', FTEST: 'FTEST', STEYX: 'STEYX', SLOPE: 'SLOPE', 'CHISQ.TEST': 'CHISQ.TEST', CHITEST: 'CHITEST', 'T.TEST': 'T.TEST', TTEST: 'TTEST', SKEW: 'SKEW', 'SKEW.P': 'SKEW.P', WEIBULLDIST: 'WEIBULLDIST', VARS: 'VARS', TINV2T: 'TINV2T', TDISTRT: 'TDISTRT', TDIST2T: 'TDIST2T', STDEVS: 'STDEVS', FINVRT: 'FINVRT', FDISTRT: 'FDISTRT', CHIDISTRT: 'CHIDISTRT', CHIINVRT: 'CHIINVRT', COVARIANCEP: 'COVARIANCEP', COVARIANCES: 'COVARIANCES', LOGNORMINV: 'LOGNORMINV', POISSONDIST: 'POISSONDIST', SKEWP: 'SKEWP', 'CEILING.MATH': 'CEILING.MATH', FLOOR: 'FLOOR', 'FLOOR.MATH': 'FLOOR.MATH', 'CEILING.PRECISE': 'CEILING.PRECISE', 'FLOOR.PRECISE': 'FLOOR.PRECISE', 'ISO.CEILING': 'ISO.CEILING' }, langCode: 'enGB', ui: { NEW_SHEET_PREFIX: 'Sheet' } }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (dictionary); /***/ }), /* 147 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AbsPlugin: () => (/* reexport safe */ _AbsPlugin__WEBPACK_IMPORTED_MODULE_2__.AbsPlugin), /* harmony export */ AddressPlugin: () => (/* reexport safe */ _AddressPlugin__WEBPACK_IMPORTED_MODULE_0__.AddressPlugin), /* harmony export */ ArrayPlugin: () => (/* reexport safe */ _ArrayPlugin__WEBPACK_IMPORTED_MODULE_1__.ArrayPlugin), /* harmony export */ BitShiftPlugin: () => (/* reexport safe */ _BitShiftPlugin__WEBPACK_IMPORTED_MODULE_3__.BitShiftPlugin), /* harmony export */ BitwiseLogicOperationsPlugin: () => (/* reexport safe */ _BitwiseLogicOperationsPlugin__WEBPACK_IMPORTED_MODULE_4__.BitwiseLogicOperationsPlugin), /* harmony export */ BooleanPlugin: () => (/* reexport safe */ _BooleanPlugin__WEBPACK_IMPORTED_MODULE_5__.BooleanPlugin), /* harmony export */ CharPlugin: () => (/* reexport safe */ _CharPlugin__WEBPACK_IMPORTED_MODULE_6__.CharPlugin), /* harmony export */ CodePlugin: () => (/* reexport safe */ _CodePlugin__WEBPACK_IMPORTED_MODULE_7__.CodePlugin), /* harmony export */ ComplexPlugin: () => (/* reexport safe */ _ComplexPlugin__WEBPACK_IMPORTED_MODULE_41__.ComplexPlugin), /* harmony export */ ConditionalAggregationPlugin: () => (/* reexport safe */ _ConditionalAggregationPlugin__WEBPACK_IMPORTED_MODULE_32__.ConditionalAggregationPlugin), /* harmony export */ CountBlankPlugin: () => (/* reexport safe */ _CountBlankPlugin__WEBPACK_IMPORTED_MODULE_8__.CountBlankPlugin), /* harmony export */ CountUniquePlugin: () => (/* reexport safe */ _CountUniquePlugin__WEBPACK_IMPORTED_MODULE_9__.CountUniquePlugin), /* harmony export */ DateTimePlugin: () => (/* reexport safe */ _DateTimePlugin__WEBPACK_IMPORTED_MODULE_10__.DateTimePlugin), /* harmony export */ DegreesPlugin: () => (/* reexport safe */ _DegreesPlugin__WEBPACK_IMPORTED_MODULE_11__.DegreesPlugin), /* harmony export */ DeltaPlugin: () => (/* reexport safe */ _DeltaPlugin__WEBPACK_IMPORTED_MODULE_12__.DeltaPlugin), /* harmony export */ ExpPlugin: () => (/* reexport safe */ _ExpPlugin__WEBPACK_IMPORTED_MODULE_13__.ExpPlugin), /* harmony export */ FinancialPlugin: () => (/* reexport safe */ _FinancialPlugin__WEBPACK_IMPORTED_MODULE_14__.FinancialPlugin), /* harmony export */ FormulaTextPlugin: () => (/* reexport safe */ _FormulaTextPlugin__WEBPACK_IMPORTED_MODULE_15__.FormulaTextPlugin), /* harmony export */ HyperlinkPlugin: () => (/* reexport safe */ _HyperlinkPlugin__WEBPACK_IMPORTED_MODULE_16__.HyperlinkPlugin), /* harmony export */ InformationPlugin: () => (/* reexport safe */ _InformationPlugin__WEBPACK_IMPORTED_MODULE_17__.InformationPlugin), /* harmony export */ IsEvenPlugin: () => (/* reexport safe */ _IsEvenPlugin__WEBPACK_IMPORTED_MODULE_18__.IsEvenPlugin), /* harmony export */ IsOddPlugin: () => (/* reexport safe */ _IsOddPlugin__WEBPACK_IMPORTED_MODULE_19__.IsOddPlugin), /* harmony export */ LogarithmPlugin: () => (/* reexport safe */ _LogarithmPlugin__WEBPACK_IMPORTED_MODULE_20__.LogarithmPlugin), /* harmony export */ LookupPlugin: () => (/* reexport safe */ _LookupPlugin__WEBPACK_IMPORTED_MODULE_36__.LookupPlugin), /* harmony export */ MathConstantsPlugin: () => (/* reexport safe */ _MathConstantsPlugin__WEBPACK_IMPORTED_MODULE_21__.MathConstantsPlugin), /* harmony export */ MathPlugin: () => (/* reexport safe */ _MathPlugin__WEBPACK_IMPORTED_MODULE_40__.MathPlugin), /* harmony export */ MatrixPlugin: () => (/* reexport safe */ _MatrixPlugin__WEBPACK_IMPORTED_MODULE_22__.MatrixPlugin), /* harmony export */ MedianPlugin: () => (/* reexport safe */ _MedianPlugin__WEBPACK_IMPORTED_MODULE_23__.MedianPlugin), /* harmony export */ ModuloPlugin: () => (/* reexport safe */ _ModuloPlugin__WEBPACK_IMPORTED_MODULE_24__.ModuloPlugin), /* harmony export */ NumericAggregationPlugin: () => (/* reexport safe */ _NumericAggregationPlugin__WEBPACK_IMPORTED_MODULE_25__.NumericAggregationPlugin), /* harmony export */ PowerPlugin: () => (/* reexport safe */ _PowerPlugin__WEBPACK_IMPORTED_MODULE_26__.PowerPlugin), /* harmony export */ RadiansPlugin: () => (/* reexport safe */ _RadiansPlugin__WEBPACK_IMPORTED_MODULE_27__.RadiansPlugin), /* harmony export */ RadixConversionPlugin: () => (/* reexport safe */ _RadixConversionPlugin__WEBPACK_IMPORTED_MODULE_28__.RadixConversionPlugin), /* harmony export */ RandomPlugin: () => (/* reexport safe */ _RandomPlugin__WEBPACK_IMPORTED_MODULE_29__.RandomPlugin), /* harmony export */ RomanPlugin: () => (/* reexport safe */ _RomanPlugin__WEBPACK_IMPORTED_MODULE_37__.RomanPlugin), /* harmony export */ RoundingPlugin: () => (/* reexport safe */ _RoundingPlugin__WEBPACK_IMPORTED_MODULE_30__.RoundingPlugin), /* harmony export */ SimpleArithmerticPlugin: () => (/* reexport safe */ _SimpleArithmertic__WEBPACK_IMPORTED_MODULE_38__.SimpleArithmerticPlugin), /* harmony export */ SqrtPlugin: () => (/* reexport safe */ _SqrtPlugin__WEBPACK_IMPORTED_MODULE_31__.SqrtPlugin), /* harmony export */ StatisticalAggregationPlugin: () => (/* reexport safe */ _StatisticalAggregationPlugin__WEBPACK_IMPORTED_MODULE_42__.StatisticalAggregationPlugin), /* harmony export */ StatisticalPlugin: () => (/* reexport safe */ _StatisticalPlugin__WEBPACK_IMPORTED_MODULE_39__.StatisticalPlugin), /* harmony export */ SumprodPlugin: () => (/* reexport safe */ _SumprodPlugin__WEBPACK_IMPORTED_MODULE_33__.SumprodPlugin), /* harmony export */ TextPlugin: () => (/* reexport safe */ _TextPlugin__WEBPACK_IMPORTED_MODULE_34__.TextPlugin), /* harmony export */ TrigonometryPlugin: () => (/* reexport safe */ _TrigonometryPlugin__WEBPACK_IMPORTED_MODULE_35__.TrigonometryPlugin) /* harmony export */ }); /* harmony import */ var _AddressPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(148); /* harmony import */ var _ArrayPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); /* harmony import */ var _AbsPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(150); /* harmony import */ var _BitShiftPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(151); /* harmony import */ var _BitwiseLogicOperationsPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(152); /* harmony import */ var _BooleanPlugin__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(153); /* harmony import */ var _CharPlugin__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(154); /* harmony import */ var _CodePlugin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(155); /* harmony import */ var _CountBlankPlugin__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(156); /* harmony import */ var _CountUniquePlugin__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(157); /* harmony import */ var _DateTimePlugin__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(158); /* harmony import */ var _DegreesPlugin__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(159); /* harmony import */ var _DeltaPlugin__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(160); /* harmony import */ var _ExpPlugin__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(161); /* harmony import */ var _FinancialPlugin__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(162); /* harmony import */ var _FormulaTextPlugin__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(163); /* harmony import */ var _HyperlinkPlugin__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(164); /* harmony import */ var _InformationPlugin__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(165); /* harmony import */ var _IsEvenPlugin__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(166); /* harmony import */ var _IsOddPlugin__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(167); /* harmony import */ var _LogarithmPlugin__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(168); /* harmony import */ var _MathConstantsPlugin__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(169); /* harmony import */ var _MatrixPlugin__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(170); /* harmony import */ var _MedianPlugin__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(171); /* harmony import */ var _ModuloPlugin__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(172); /* harmony import */ var _NumericAggregationPlugin__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(173); /* harmony import */ var _PowerPlugin__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(174); /* harmony import */ var _RadiansPlugin__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(175); /* harmony import */ var _RadixConversionPlugin__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(176); /* harmony import */ var _RandomPlugin__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(177); /* harmony import */ var _RoundingPlugin__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(178); /* harmony import */ var _SqrtPlugin__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(179); /* harmony import */ var _ConditionalAggregationPlugin__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(180); /* harmony import */ var _SumprodPlugin__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(183); /* harmony import */ var _TextPlugin__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(184); /* harmony import */ var _TrigonometryPlugin__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(185); /* harmony import */ var _LookupPlugin__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(186); /* harmony import */ var _RomanPlugin__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(188); /* harmony import */ var _SimpleArithmertic__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(189); /* harmony import */ var _StatisticalPlugin__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(190); /* harmony import */ var _MathPlugin__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(193); /* harmony import */ var _ComplexPlugin__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(194); /* harmony import */ var _StatisticalAggregationPlugin__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(195); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /***/ }), /* 148 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AddressPlugin: () => (/* binding */ AddressPlugin) /* harmony export */ }); /* harmony import */ var _parser_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(61); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ var AbsStyle; (function (AbsStyle) { AbsStyle[AbsStyle["FullyAbsolute"] = 1] = "FullyAbsolute"; AbsStyle[AbsStyle["RowAbsoluteColRelative"] = 2] = "RowAbsoluteColRelative"; AbsStyle[AbsStyle["RowRelativeColAbsolute"] = 3] = "RowRelativeColAbsolute"; AbsStyle[AbsStyle["FullyRelative"] = 4] = "FullyRelative"; })(AbsStyle || (AbsStyle = {})); class AddressPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionPlugin { verifyAddressArguments(row, col, abs, useA1Style) { if (useA1Style) { if (row < 1 || col < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.LessThanOne); } } else { if (AbsStyle.FullyAbsolute == abs) { if (row < 1 || col < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.LessThanOne); } } else if (AbsStyle.RowAbsoluteColRelative == abs) { if (row < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.LessThanOne); } } else if (AbsStyle.RowRelativeColAbsolute == abs) { if (col < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_3__.ErrorMessage.LessThanOne); } } } return undefined; } address(ast, state) { return this.runFunction(ast.args, state, this.metadata('ADDRESS'), (row, col, abs, useA1Style, sheetName) => { const argumentError = this.verifyAddressArguments(row, col, abs, useA1Style); if (argumentError !== undefined) { return argumentError; } const colLetter = (0,_parser_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.columnIndexToLabel)(col - 1); let sheetPrefix = ''; if (sheetName !== undefined && sheetName !== null) { sheetPrefix = `${sheetName}!`; } const r1c1ColSegment = col == 0 ? 'C' : `C[${col}]`; const r1c1RowSegment = row == 0 ? 'R' : `R[${row}]`; if (AbsStyle.FullyRelative == abs) { return useA1Style ? `${sheetPrefix}${colLetter}${row}` : `${sheetPrefix}${r1c1RowSegment}${r1c1ColSegment}`; } else if (AbsStyle.RowRelativeColAbsolute == abs) { return useA1Style ? `${sheetPrefix}$${colLetter}${row}` : `${sheetPrefix}${r1c1RowSegment}C${col}`; } else if (AbsStyle.RowAbsoluteColRelative == abs) { return useA1Style ? `${sheetPrefix}${colLetter}$${row}` : `${sheetPrefix}R${row}${r1c1ColSegment}`; } return useA1Style ? `${sheetPrefix}$${colLetter}$${row}` : `${sheetPrefix}R${row}C${col}`; }); } } AddressPlugin.implementedFunctions = { 'ADDRESS': { method: 'address', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.NUMBER, optionalArg: true, defaultValue: 1, minValue: 1, maxValue: 4 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.BOOLEAN, optionalArg: true, defaultValue: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.STRING, optionalArg: true }] } }; /***/ }), /* 149 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ArrayPlugin: () => (/* binding */ ArrayPlugin) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(98); /* harmony import */ var _InterpreterState__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(95); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ArrayPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionPlugin { arrayformula(ast, state) { return this.runFunction(ast.args, state, this.metadata('ARRAYFORMULA'), value => value); } arrayformulaArraySize(ast, state) { if (ast.args.length !== 1) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('ARRAYFORMULA'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_5__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); return subChecks[0]; } arrayconstrain(ast, state) { return this.runFunction(ast.args, state, this.metadata('ARRAY_CONSTRAIN'), (range, numRows, numCols) => { numRows = Math.min(numRows, range.height()); numCols = Math.min(numCols, range.width()); const data = range.data; const ret = []; for (let i = 0; i < numRows; i++) { ret.push(data[i].slice(0, numCols)); } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues(ret); }); } arrayconstrainArraySize(ast, state) { if (ast.args.length !== 3) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('ARRAY_CONSTRAIN'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_5__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); let { height, width } = subChecks[0]; if (ast.args[1].type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER) { height = Math.min(height, ast.args[1].value); } if (ast.args[2].type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER) { width = Math.min(width, ast.args[2].value); } if (height < 1 || width < 1 || !Number.isInteger(height) || !Number.isInteger(width)) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } return new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(width, height); } filter(ast, state) { return this.runFunction(ast.args, state, this.metadata('FILTER'), (rangeVals, ...rangeFilters) => { for (const filter of rangeFilters) { if (rangeVals.width() !== filter.width() || rangeVals.height() !== filter.height()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.EqualLength); } } if (rangeVals.width() > 1 && rangeVals.height() > 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongDimension); } const vals = rangeVals.data; const ret = []; for (let i = 0; i < rangeVals.height(); i++) { const row = []; for (let j = 0; j < rangeVals.width(); j++) { let ok = true; for (const filter of rangeFilters) { const val = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceScalarToBoolean)(filter.data[i][j]); if (val !== true) { ok = false; break; } } if (ok) { row.push(vals[i][j]); } } if (row.length > 0) { ret.push(row); } } if (ret.length > 0) { return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues(ret); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.EmptyRange); } }); } filterArraySize(ast, state) { if (ast.args.length <= 1) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('FILTER'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_5__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); const width = Math.max(...subChecks.map(val => val.width)); const height = Math.max(...subChecks.map(val => val.height)); return new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(width, height); } } ArrayPlugin.implementedFunctions = { 'ARRAYFORMULA': { method: 'arrayformula', arraySizeMethod: 'arrayformulaArraySize', arrayFunction: true, parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.ANY }] }, 'ARRAY_CONSTRAIN': { method: 'arrayconstrain', arraySizeMethod: 'arrayconstrainArraySize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.INTEGER, minValue: 1 }], vectorizationForbidden: true }, 'FILTER': { method: 'filter', arraySizeMethod: 'filterArraySize', arrayFunction: true, parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }], repeatLastArgs: 1 } }; /***/ }), /* 150 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AbsPlugin: () => (/* binding */ AbsPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AbsPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { abs(ast, state) { return this.runFunction(ast.args, state, this.metadata('ABS'), Math.abs); } } AbsPlugin.implementedFunctions = { 'ABS': { method: 'abs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 151 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ BitShiftPlugin: () => (/* binding */ BitShiftPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const MAX_48BIT_INTEGER = 281474976710655; const SHIFT_MIN_POSITIONS = -53; const SHIFT_MAX_POSITIONS = 53; class BitShiftPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { bitlshift(ast, state) { return this.runFunction(ast.args, state, this.metadata('BITLSHIFT'), shiftLeft); } bitrshift(ast, state) { return this.runFunction(ast.args, state, this.metadata('BITRSHIFT'), shiftRight); } } BitShiftPlugin.implementedFunctions = { 'BITLSHIFT': { method: 'bitlshift', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.INTEGER, minValue: SHIFT_MIN_POSITIONS, maxValue: SHIFT_MAX_POSITIONS }] }, 'BITRSHIFT': { method: 'bitrshift', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.INTEGER, minValue: SHIFT_MIN_POSITIONS, maxValue: SHIFT_MAX_POSITIONS }] } }; function shiftLeft(value, positions) { if (positions < 0) { return shiftRight(value, -positions); } else { return validate(value * Math.pow(2, positions)); } } function shiftRight(value, positions) { if (positions < 0) { return shiftLeft(value, -positions); } else { return validate(Math.floor(value / Math.pow(2, positions))); } } function validate(result) { if (result > MAX_48BIT_INTEGER) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.BitshiftLong); } else { return result; } } /***/ }), /* 152 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ BitwiseLogicOperationsPlugin: () => (/* binding */ BitwiseLogicOperationsPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class BitwiseLogicOperationsPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { bitand(ast, state) { return this.runFunction(ast.args, state, this.metadata('BITAND'), (left, right) => left & right); } bitor(ast, state) { return this.runFunction(ast.args, state, this.metadata('BITOR'), (left, right) => left | right); } bitxor(ast, state) { return this.runFunction(ast.args, state, this.metadata('BITXOR'), (left, right) => left ^ right); } } BitwiseLogicOperationsPlugin.implementedFunctions = { 'BITAND': { method: 'bitand', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }] }, 'BITOR': { method: 'bitor', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }] }, 'BITXOR': { method: 'bitxor', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.INTEGER, minValue: 0 }] } }; /***/ }), /* 153 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ BooleanPlugin: () => (/* binding */ BooleanPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing boolean functions */ class BooleanPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to TRUE() * * Returns the logical true * * @param ast * @param state */ literalTrue(ast, state) { return this.runFunction(ast.args, state, this.metadata('TRUE'), () => true); } /** * Corresponds to FALSE() * * Returns the logical false * * @param ast * @param state */ literalFalse(ast, state) { return this.runFunction(ast.args, state, this.metadata('FALSE'), () => false); } /** * Corresponds to IF(expression, value_if_true, value_if_false) * * Returns value specified as second argument if expression is true and third argument if expression is false * * @param ast * @param state */ conditionalIf(ast, state) { return this.runFunction(ast.args, state, this.metadata('IF'), (condition, arg2, arg3) => { return condition ? arg2 : arg3; }); } /** * Implementation for the IFS function. Returns the value that corresponds to the first true condition. * * @param ast * @param state */ ifs(ast, state) { return this.runFunction(ast.args, state, this.metadata('IFS'), (...args) => { for (let idx = 0; idx < args.length; idx += 2) { if (args[idx]) { return args[idx + 1]; } } return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NoConditionMet); }); } /** * Corresponds to AND(expression1, [expression2, ...]) * * Returns true if all of the provided arguments are logically true, and false if any of it is logically false * * @param ast * @param state */ and(ast, state) { return this.runFunction(ast.args, state, this.metadata('AND'), (...args) => args.filter(arg => arg !== undefined).every(arg => !!arg)); } /** * Corresponds to OR(expression1, [expression2, ...]) * * Returns true if any of the provided arguments are logically true, and false otherwise * * @param ast * @param state */ or(ast, state) { return this.runFunction(ast.args, state, this.metadata('OR'), (...args) => args.filter(arg => arg !== undefined).some(arg => arg)); } not(ast, state) { return this.runFunction(ast.args, state, this.metadata('NOT'), arg => !arg); } xor(ast, state) { return this.runFunction(ast.args, state, this.metadata('XOR'), (...args) => { let cnt = 0; args.filter(arg => arg !== undefined).forEach(arg => { if (arg) { cnt++; } }); return cnt % 2 === 1; }); } switch(ast, state) { return this.runFunction(ast.args, state, this.metadata('SWITCH'), (selector, ...args) => { const n = args.length; let i = 0; for (; i + 1 < n; i += 2) { if (args[i] instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { continue; } if (this.arithmeticHelper.eq(selector, args[i])) { return args[i + 1]; } } if (i < n) { return args[i]; } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NoDefault); } }); } iferror(ast, state) { return this.runFunction(ast.args, state, this.metadata('IFERROR'), (arg1, arg2) => { if (arg1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg2; } else { return arg1; } }); } ifna(ast, state) { return this.runFunction(ast.args, state, this.metadata('IFNA'), (arg1, arg2) => { if (arg1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError && arg1.type === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA) { return arg2; } else { return arg1; } }); } choose(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHOOSE'), (selector, ...args) => { if (selector > args.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.Selector); } return args[selector - 1]; }); } } BooleanPlugin.implementedFunctions = { 'TRUE': { method: 'literalTrue', parameters: [] }, 'FALSE': { method: 'literalFalse', parameters: [] }, 'IF': { method: 'conditionalIf', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, defaultValue: false, passSubtype: true }] }, 'IFS': { method: 'ifs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }], repeatLastArgs: 2 }, 'AND': { method: 'and', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }], repeatLastArgs: 1, expandRanges: true }, 'OR': { method: 'or', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }], repeatLastArgs: 1, expandRanges: true }, 'XOR': { method: 'xor', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }], repeatLastArgs: 1, expandRanges: true }, 'NOT': { method: 'not', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.BOOLEAN }] }, 'SWITCH': { method: 'switch', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }], repeatLastArgs: 1 }, 'IFERROR': { method: 'iferror', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }] }, 'IFNA': { method: 'ifna', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }] }, 'CHOOSE': { method: 'choose', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR, passSubtype: true }], repeatLastArgs: 1 } }; /***/ }), /* 154 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CharPlugin: () => (/* binding */ CharPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class CharPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { char(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHAR'), value => { if (value < 1 || value >= 256) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.CharacterCodeBounds); } return String.fromCharCode(Math.trunc(value)); }); } unichar(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHAR'), value => { if (value < 1 || value >= 1114112) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.CharacterCodeBounds); } return String.fromCodePoint(Math.trunc(value)); }); } } CharPlugin.implementedFunctions = { 'CHAR': { method: 'char', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'UNICHAR': { method: 'unichar', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 155 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CodePlugin: () => (/* binding */ CodePlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class CodePlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { code(ast, state) { return this.runFunction(ast.args, state, this.metadata('CODE'), value => { if (value.length === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EmptyString); } return value.charCodeAt(0); }); } unicode(ast, state) { return this.runFunction(ast.args, state, this.metadata('UNICODE'), value => { var _a; return (_a = value.codePointAt(0)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EmptyString); }); } } CodePlugin.implementedFunctions = { 'CODE': { method: 'code', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'UNICODE': { method: 'unicode', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] } }; /***/ }), /* 156 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CountBlankPlugin: () => (/* binding */ CountBlankPlugin) /* harmony export */ }); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing MEDIAN function */ class CountBlankPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionPlugin { countblank(ast, state) { return this.runFunction(ast.args, state, this.metadata('COUNTBLANK'), (...args) => { let counter = 0; args.forEach(arg => { if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.EmptyValue) { counter++; } }); return counter; }); } } CountBlankPlugin.implementedFunctions = { 'COUNTBLANK': { method: 'countblank', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.SCALAR }], repeatLastArgs: 1, expandRanges: true } }; /***/ }), /* 157 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CountUniquePlugin: () => (/* binding */ CountUniquePlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing COUNTUNIQUE function */ class CountUniquePlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionPlugin { /** * Corresponds to COUNTUNIQUE(Number1, Number2, ...). * * Returns number of unique numbers from arguments * * @param ast * @param state */ countunique(ast, state) { return this.runFunction(ast.args, state, this.metadata('COUNTUNIQUE'), (...args) => { const valuesSet = new Set(); const errorsSet = new Set(); for (const scalarValue of args) { if (scalarValue instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { errorsSet.add(scalarValue.type); } else if (scalarValue !== '') { valuesSet.add(scalarValue); } } return valuesSet.size + errorsSet.size; }); } } CountUniquePlugin.implementedFunctions = { 'COUNTUNIQUE': { method: 'countunique', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.SCALAR }], repeatLastArgs: 1, expandRanges: true } }; /***/ }), /* 158 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DateTimePlugin: () => (/* binding */ DateTimePlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(104); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _format_format__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(106); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing date-specific functions */ class DateTimePlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionPlugin { constructor() { super(...arguments); this.isoweeknumCore = day => { const absoluteDay = Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(day)); const date = this.dateTimeHelper.numberToSimpleDate(day); const yearStart = this.dateTimeHelper.dateToNumber({ year: date.year, month: 1, day: 1 }); const yearStartAbsolute = this.dateTimeHelper.relativeNumberToAbsoluteNumber(yearStart); const firstThursdayAbs = yearStartAbsolute + ((4 - yearStartAbsolute) % 7 + 7) % 7; const ret = Math.floor((absoluteDay - 1) / 7) - Math.floor((firstThursdayAbs - 1) / 7) + 1; if (ret === 0) { return this.isoweeknumCore(day - 7) + 1; } return ret; }; this.days360Core = (startDate, endDate, mode) => { const start = this.dateTimeHelper.numberToSimpleDate(startDate); const end = this.dateTimeHelper.numberToSimpleDate(endDate); let nStart, nEnd; if (mode) { nStart = (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.toBasisEU)(start); nEnd = (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.toBasisEU)(end); } else { [nStart, nEnd] = this.dateTimeHelper.toBasisUS(start, end); } return 360 * (nEnd.year - nStart.year) + 30 * (nEnd.month - nStart.month) + nEnd.day - nStart.day; }; } /** * Corresponds to DATE(year, month, day) * * Converts a provided year, month and day into date * * @param ast * @param state */ date(ast, state) { return this.runFunction(ast.args, state, this.metadata('DATE'), (year, month, day) => { const d = Math.trunc(day); let m = Math.trunc(month); let y = Math.trunc(year); if (y < this.dateTimeHelper.getEpochYearZero()) { y += this.dateTimeHelper.getEpochYearZero(); } const delta = Math.floor((m - 1) / 12); y += delta; m -= delta * 12; const date = { year: y, month: m, day: 1 }; if (this.dateTimeHelper.isValidDate(date)) { let ret = this.dateTimeHelper.dateToNumber(date) + (d - 1); ret = this.dateTimeHelper.getWithinBounds(ret); if (ret === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.DateBounds); } return ret; } return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.InvalidDate); }); } time(ast, state) { return this.runFunction(ast.args, state, this.metadata('TIME'), (h, m, s) => { const ret = (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.timeToNumber)({ hours: Math.trunc(h), minutes: Math.trunc(m), seconds: Math.trunc(s) }); if (ret < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NegativeTime); } return ret % 1; }); } /** * Implementation for the EOMONTH function */ eomonth(ast, state) { return this.runFunction(ast.args, state, this.metadata('EOMONTH'), (dateNumber, numberOfMonthsToShift) => { const date = this.dateTimeHelper.numberToSimpleDate(dateNumber); let ret = this.dateTimeHelper.dateToNumber(this.dateTimeHelper.endOfMonth((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.offsetMonth)(date, numberOfMonthsToShift))); ret = this.dateTimeHelper.getWithinBounds(ret); if (ret === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.DateBounds); } return ret; }); } day(ast, state) { return this.runFunction(ast.args, state, this.metadata('DAY'), dateNumber => this.dateTimeHelper.numberToSimpleDate(dateNumber).day); } days(ast, state) { return this.runFunction(ast.args, state, this.metadata('DAYS'), (endDate, startDate) => Math.trunc(endDate) - Math.trunc(startDate)); } /** * Corresponds to MONTH(date) * * Returns the month of the year specified by a given date * * @param ast * @param state */ month(ast, state) { return this.runFunction(ast.args, state, this.metadata('MONTH'), dateNumber => this.dateTimeHelper.numberToSimpleDate(dateNumber).month); } /** * Corresponds to YEAR(date) * * Returns the year specified by a given date * * @param ast * @param state */ year(ast, state) { return this.runFunction(ast.args, state, this.metadata('YEAR'), dateNumber => this.dateTimeHelper.numberToSimpleDate(dateNumber).year); } hour(ast, state) { return this.runFunction(ast.args, state, this.metadata('HOUR'), timeNumber => (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.numberToSimpleTime)((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.roundToNearestSecond)(timeNumber) % 1).hours); } minute(ast, state) { return this.runFunction(ast.args, state, this.metadata('MINUTE'), timeNumber => (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.numberToSimpleTime)((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.roundToNearestSecond)(timeNumber) % 1).minutes); } second(ast, state) { return this.runFunction(ast.args, state, this.metadata('SECOND'), timeNumber => (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.numberToSimpleTime)((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.roundToNearestSecond)(timeNumber) % 1).seconds); } /** * Corresponds to TEXT(number, format) * * Tries to convert number to specified date format. * * @param ast * @param state */ text(ast, state) { return this.runFunction(ast.args, state, this.metadata('TEXT'), (numberRepresentation, formatArg) => (0,_format_format__WEBPACK_IMPORTED_MODULE_3__.format)(numberRepresentation, formatArg, this.config, this.dateTimeHelper)); } weekday(ast, state) { return this.runFunction(ast.args, state, this.metadata('WEEKDAY'), (day, type) => { const absoluteDay = Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(day)); if (type === 3) { return (absoluteDay - 1) % 7; } const offset = weekdayOffsets.get(type); if (offset === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } return (absoluteDay - offset) % 7 + 1; }); } weeknum(ast, state) { return this.runFunction(ast.args, state, this.metadata('WEEKNUM'), (day, type) => { const absoluteDay = Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(day)); const date = this.dateTimeHelper.numberToSimpleDate(day); const yearStart = this.dateTimeHelper.dateToNumber({ year: date.year, month: 1, day: 1 }); const yearStartAbsolute = this.dateTimeHelper.relativeNumberToAbsoluteNumber(yearStart); if (type === 21) { return this.isoweeknumCore(day); } const offset = weekdayOffsets.get(type); if (offset === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } return Math.floor((absoluteDay - offset) / 7) - Math.floor((yearStartAbsolute - offset) / 7) + 1; }); } isoweeknum(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISOWEEKNUM'), this.isoweeknumCore); } datevalue(ast, state) { return this.runFunction(ast.args, state, this.metadata('DATEVALUE'), date => { const { dateTime } = this.dateTimeHelper.parseDateTimeFromConfigFormats(date); if (dateTime === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IncorrectDateTime); } if (!(0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.instanceOfSimpleDate)(dateTime)) { return 0; } return ((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.instanceOfSimpleTime)(dateTime) ? Math.trunc((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.timeToNumber)(dateTime)) : 0) + this.dateTimeHelper.dateToNumber(dateTime); }); } timevalue(ast, state) { return this.runFunction(ast.args, state, this.metadata('TIMEVALUE'), date => { const dateNumber = this.dateTimeHelper.dateStringToDateNumber(date); if (dateNumber === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IncorrectDateTime); } return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(dateNumber) % 1; }); } now(ast, state) { return this.runFunction(ast.args, state, this.metadata('NOW'), () => { const now = new Date(Date.now()); return (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.timeToNumber)({ hours: now.getHours(), minutes: now.getMinutes(), seconds: now.getSeconds() }) + this.dateTimeHelper.dateToNumber({ year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate() }); }); } today(ast, state) { return this.runFunction(ast.args, state, this.metadata('TODAY'), () => { const now = new Date(Date.now()); return this.dateTimeHelper.dateToNumber({ year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate() }); }); } edate(ast, state) { return this.runFunction(ast.args, state, this.metadata('EDATE'), (dateNumber, delta) => { const date = this.dateTimeHelper.numberToSimpleDate(dateNumber); const newDate = (0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.truncateDayInMonth)((0,_DateTimeHelper__WEBPACK_IMPORTED_MODULE_1__.offsetMonth)(date, delta)); let ret = this.dateTimeHelper.dateToNumber(newDate); ret = this.dateTimeHelper.getWithinBounds(ret); if (ret === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.DateBounds); } return ret; }); } datedif(ast, state) { return this.runFunction(ast.args, state, this.metadata('DATEDIF'), (startDate, endDate, unit) => { if (startDate > endDate) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.StartEndDate); } if (unit === 'D') { return Math.floor(endDate) - Math.floor(startDate); } const start = this.dateTimeHelper.numberToSimpleDate(startDate); const end = this.dateTimeHelper.numberToSimpleDate(endDate); switch (unit) { case 'M': return (end.year - start.year) * 12 + (end.month - start.month) - (end.day < start.day ? 1 : 0); case 'YM': return (12 + (end.month - start.month) - (end.day < start.day ? 1 : 0)) % 12; case 'Y': if (end.month > start.month || end.month === start.month && end.day >= start.day) { return end.year - start.year; } else { return end.year - start.year - 1; } case 'MD': if (end.day >= start.day) { return end.day - start.day; } else { const m = end.month === 1 ? 12 : end.month - 1; const y = end.month === 1 ? end.year - 1 : end.year; return this.dateTimeHelper.daysInMonth(y, m) + end.day - start.day; } case 'YD': if (end.month > start.month || end.month === start.month && end.day >= start.day) { return Math.floor(endDate) - this.dateTimeHelper.dateToNumber({ year: end.year, month: start.month, day: start.day }); } else { return Math.floor(endDate) - Math.floor(startDate) - 365 * (end.year - start.year - 1) - this.dateTimeHelper.leapYearsCount(end.year - 1) + this.dateTimeHelper.leapYearsCount(start.year); } default: return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } }); } days360(ast, state) { return this.runFunction(ast.args, state, this.metadata('DAYS360'), this.days360Core); } yearfrac(ast, state) { return this.runFunction(ast.args, state, this.metadata('YEARFRAC'), (startDate, endDate, mode) => { startDate = Math.trunc(startDate); endDate = Math.trunc(endDate); if (startDate > endDate) { [startDate, endDate] = [endDate, startDate]; } switch (mode) { case 0: return this.days360Core(startDate, endDate, false) / 360; case 1: return (endDate - startDate) / this.dateTimeHelper.yearLengthForBasis(this.dateTimeHelper.numberToSimpleDate(startDate), this.dateTimeHelper.numberToSimpleDate(endDate)); case 2: return (endDate - startDate) / 360; case 3: return (endDate - startDate) / 365; case 4: return this.days360Core(startDate, endDate, true) / 360; } throw new Error('Should not be reachable.'); }); } interval(ast, state) { return this.runFunction(ast.args, state, this.metadata('INTERVAL'), arg => { arg = Math.trunc(arg); const second = arg % 60; arg = Math.trunc(arg / 60); const minute = arg % 60; arg = Math.trunc(arg / 60); const hour = arg % 24; arg = Math.trunc(arg / 24); const day = arg % 30; arg = Math.trunc(arg / 30); const month = arg % 12; const year = Math.trunc(arg / 12); return 'P' + (year > 0 ? `${year}Y` : '') + (month > 0 ? `${month}M` : '') + (day > 0 ? `${day}D` : '') + 'T' + (hour > 0 ? `${hour}H` : '') + (minute > 0 ? `${minute}M` : '') + (second > 0 ? `${second}S` : ''); }); } networkdays(ast, state) { return this.runFunction(ast.args, state, this.metadata('NETWORKDAYS'), (start, end, holidays) => this.networkdayscore(start, end, 1, holidays)); } networkdaysintl(ast, state) { return this.runFunction(ast.args, state, this.metadata('NETWORKDAYS.INTL'), (start, end, weekend, holidays) => this.networkdayscore(start, end, weekend, holidays)); } workday(ast, state) { return this.runFunction(ast.args, state, this.metadata('WORKDAY'), (start, end, holidays) => this.workdaycore(start, end, 1, holidays)); } workdayintl(ast, state) { return this.runFunction(ast.args, state, this.metadata('WORKDAY.INTL'), (start, end, weekend, holidays) => this.workdaycore(start, end, weekend, holidays)); } networkdayscore(start, end, weekend, holidays) { start = Math.trunc(start); end = Math.trunc(end); let multiplier = 1; if (start > end) { [start, end] = [end, start]; multiplier = -1; } const weekendPattern = computeWeekendPattern(weekend); if (weekendPattern instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return weekendPattern; } const filteredHolidays = this.simpleRangeToFilteredHolidays(weekendPattern, holidays); if (filteredHolidays instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return filteredHolidays; } return multiplier * this.countWorkdays(start, end, weekendPattern, filteredHolidays); } workdaycore(start, delta, weekend, holidays) { start = Math.trunc(start); delta = Math.trunc(delta); const weekendPattern = computeWeekendPattern(weekend); if (weekendPattern instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return weekendPattern; } const filteredHolidays = this.simpleRangeToFilteredHolidays(weekendPattern, holidays); if (filteredHolidays instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return filteredHolidays; } if (delta > 0) { let upper = 1; while (this.countWorkdays(start + 1, start + upper, weekendPattern, filteredHolidays) < delta) { upper *= 2; } let lower = 1; while (lower + 1 < upper) { const mid = Math.trunc((lower + upper) / 2); if (this.countWorkdays(start + 1, start + mid, weekendPattern, filteredHolidays) < delta) { lower = mid; } else { upper = mid; } } return start + upper; } else if (delta < 0) { delta *= -1; let upper = 1; while (this.countWorkdays(start - upper, start - 1, weekendPattern, filteredHolidays) < delta) { upper *= 2; } let lower = 1; while (lower + 1 < upper) { const mid = Math.trunc((lower + upper) / 2); if (this.countWorkdays(start - mid, start - 1, weekendPattern, filteredHolidays) < delta) { lower = mid; } else { upper = mid; } } return start - upper; } else { return start; } } countWorkdays(start, end, weekendPattern, sortedHolidays) { const absoluteEnd = Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(end)); const absoluteStart = Math.floor(this.dateTimeHelper.relativeNumberToAbsoluteNumber(start)); let ans = 0; for (let i = 0; i < 7; i++) { if (weekendPattern.charAt(i) === '0') { ans += Math.floor((absoluteEnd + 6 - i) / 7); ans -= Math.floor((absoluteStart - 1 + 6 - i) / 7); } } ans -= lowerBound(end + 1, sortedHolidays) - lowerBound(start, sortedHolidays); return ans; } simpleRangeToFilteredHolidays(weekendPattern, holidays) { var _a; const holidaysArr = (_a = holidays === null || holidays === void 0 ? void 0 : holidays.valuesFromTopLeftCorner()) !== null && _a !== void 0 ? _a : []; for (const val of holidaysArr) { if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val; } } const processedHolidays = []; for (const val of holidaysArr) { if (val === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) { continue; } if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(val)) { processedHolidays.push(Math.trunc((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(val))); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } } return [...new Set(processedHolidays)].sort((a, b) => a - b).filter(arg => { const val = this.dateTimeHelper.relativeNumberToAbsoluteNumber(arg); const i = (val - 1) % 7; return weekendPattern.charAt(i) === '0'; }); } } DateTimePlugin.implementedFunctions = { 'DATE': { method: 'date', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE }, 'TIME': { method: 'time', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_TIME }, 'MONTH': { method: 'month', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'YEAR': { method: 'year', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'HOUR': { method: 'hour', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'MINUTE': { method: 'minute', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'SECOND': { method: 'second', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'TEXT': { method: 'text', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.STRING }] }, 'EOMONTH': { method: 'eomonth', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE }, 'DAY': { method: 'day', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'DAYS': { method: 'days', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'WEEKDAY': { method: 'weekday', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'WEEKNUM': { method: 'weeknum', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'ISOWEEKNUM': { method: 'isoweeknum', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'DATEVALUE': { method: 'datevalue', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.STRING }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE }, 'TIMEVALUE': { method: 'timevalue', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.STRING }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_TIME }, 'NOW': { method: 'now', parameters: [], isVolatile: true, returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME }, 'TODAY': { method: 'today', parameters: [], isVolatile: true, returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE }, 'EDATE': { method: 'edate', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE }, 'DAYS360': { method: 'days360', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.BOOLEAN, defaultValue: false }] }, 'DATEDIF': { method: 'datedif', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.STRING }] }, 'YEARFRAC': { method: 'yearfrac', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.INTEGER, defaultValue: 0, minValue: 0, maxValue: 4 }] }, 'INTERVAL': { method: 'interval', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'NETWORKDAYS': { method: 'networkdays', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.RANGE, optionalArg: true }] }, 'NETWORKDAYS.INTL': { method: 'networkdaysintl', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NOERROR, defaultValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.RANGE, optionalArg: true }] }, 'WORKDAY': { method: 'workday', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.RANGE, optionalArg: true }] }, 'WORKDAY.INTL': { method: 'workdayintl', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.NOERROR, defaultValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_5__.FunctionArgumentType.RANGE, optionalArg: true }] } }; /** * Returns i such that: * sortedArray[i-1] < val <= sortedArray[i] * */ function lowerBound(val, sortedArray) { if (sortedArray.length === 0) { return 0; } if (val <= sortedArray[0]) { return 0; } if (sortedArray[sortedArray.length - 1] < val) { return sortedArray.length; } let lower = 0; //sortedArray[lower] < val let upper = sortedArray.length - 1; //sortedArray[upper] >= val while (lower + 1 < upper) { const mid = Math.floor((upper + lower) / 2); if (sortedArray[mid] >= val) { upper = mid; } else { lower = mid; } } return upper; } function computeWeekendPattern(weekend) { var _a; if (typeof weekend !== 'number' && typeof weekend !== 'string') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } if (typeof weekend === 'string') { if (weekend.length !== 7 || !/^(0|1)*$/.test(weekend) || weekend === '1111111') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WeekendString); } else { return weekend; } } else { return (_a = workdayPatterns.get(weekend)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } } const weekdayOffsets = new Map([[1, 0], [2, 1], [11, 1], [12, 2], [13, 3], [14, 4], [15, 5], [16, 6], [17, 0]]); const workdayPatterns = new Map([[1, '0000011'], [2, '1000001'], [3, '1100000'], [4, '0110000'], [5, '0011000'], [6, '0001100'], [7, '0000110'], [11, '0000001'], [12, '1000000'], [13, '0100000'], [14, '0010000'], [15, '0001000'], [16, '0000100'], [17, '0000010']]); /***/ }), /* 159 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DegreesPlugin: () => (/* binding */ DegreesPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class DegreesPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { degrees(ast, state) { return this.runFunction(ast.args, state, this.metadata('DEGREES'), arg => arg * (180 / Math.PI)); } } DegreesPlugin.implementedFunctions = { 'DEGREES': { method: 'degrees', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 160 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DeltaPlugin: () => (/* binding */ DeltaPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class DeltaPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { delta(ast, state) { return this.runFunction(ast.args, state, this.metadata('DELTA'), (left, right) => left === right ? 1 : 0); } } DeltaPlugin.implementedFunctions = { 'DELTA': { method: 'delta', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, defaultValue: 0 }] } }; /***/ }), /* 161 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ExpPlugin: () => (/* binding */ ExpPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ExpPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { /** * Corresponds to EXP(value) * * Calculates the exponent for basis e * * @param ast * @param state */ exp(ast, state) { return this.runFunction(ast.args, state, this.metadata('EXP'), Math.exp); } } ExpPlugin.implementedFunctions = { 'EXP': { method: 'exp', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 162 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FinancialPlugin: () => (/* binding */ FinancialPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class FinancialPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionPlugin { pmt(ast, state) { return this.runFunction(ast.args, state, this.metadata('PMT'), pmtCore); } ipmt(ast, state) { return this.runFunction(ast.args, state, this.metadata('IPMT'), ipmtCore); } ppmt(ast, state) { return this.runFunction(ast.args, state, this.metadata('PPMT'), ppmtCore); } fv(ast, state) { return this.runFunction(ast.args, state, this.metadata('FV'), fvCore); } cumipmt(ast, state) { return this.runFunction(ast.args, state, this.metadata('CUMIPMT'), (rate, periods, value, start, end, type) => { if (start > end) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EndStartPeriod); } let acc = 0; for (let i = start; i <= end; i++) { acc += ipmtCore(rate, i, periods, value, 0, type); } return acc; }); } cumprinc(ast, state) { return this.runFunction(ast.args, state, this.metadata('CUMPRINC'), (rate, periods, value, start, end, type) => { if (start > end) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EndStartPeriod); } let acc = 0; for (let i = start; i <= end; i++) { acc += ppmtCore(rate, i, periods, value, 0, type); } return acc; }); } db(ast, state) { return this.runFunction(ast.args, state, this.metadata('DB'), (cost, salvage, life, period, month) => { if (month === 12 && period > life || period > life + 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.PeriodLong); } if (salvage >= cost) { return 0; } const rate = Math.round((1 - Math.pow(salvage / cost, 1 / life)) * 1000) / 1000; const initial = cost * rate * month / 12; if (period === 1) { return initial; } let total = initial; for (let i = 0; i < period - 2; i++) { total += (cost - total) * rate; } if (period === life + 1) { return (cost - total) * rate * (12 - month) / 12; } return (cost - total) * rate; }); } ddb(ast, state) { return this.runFunction(ast.args, state, this.metadata('DDB'), (cost, salvage, life, period, factor) => { if (period > life) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } let rate = factor / life; let oldValue; if (rate >= 1) { rate = 1; if (period === 1) { oldValue = cost; } else { oldValue = 0; } } else { oldValue = cost * Math.pow(1 - rate, period - 1); } const newValue = cost * Math.pow(1 - rate, period); return Math.max(oldValue - Math.max(salvage, newValue), 0); }); } dollarde(ast, state) { return this.runFunction(ast.args, state, this.metadata('DOLLARDE'), (dollar, fraction) => { if (fraction < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } fraction = Math.trunc(fraction); while (fraction > 10) { fraction /= 10; } return Math.trunc(dollar) + (dollar - Math.trunc(dollar)) * 10 / fraction; }); } dollarfr(ast, state) { return this.runFunction(ast.args, state, this.metadata('DOLLARFR'), (dollar, fraction) => { if (fraction < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } fraction = Math.trunc(fraction); while (fraction > 10) { fraction /= 10; } return Math.trunc(dollar) + (dollar - Math.trunc(dollar)) * fraction / 10; }); } effect(ast, state) { return this.runFunction(ast.args, state, this.metadata('EFFECT'), (rate, periods) => { periods = Math.trunc(periods); return Math.pow(1 + rate / periods, periods) - 1; }); } ispmt(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISPMT'), (rate, period, periods, value) => { if (periods === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return value * rate * (period / periods - 1); }); } nominal(ast, state) { return this.runFunction(ast.args, state, this.metadata('NOMINAL'), (rate, periods) => { periods = Math.trunc(periods); return (Math.pow(rate + 1, 1 / periods) - 1) * periods; }); } nper(ast, state) { return this.runFunction(ast.args, state, this.metadata('NPER'), (rate, payment, present, future, type) => { if (rate === 0) { if (payment === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return (-present - future) / payment; } if (type) { payment *= 1 + rate; } return Math.log((payment - future * rate) / (present * rate + payment)) / Math.log(1 + rate); }); } rate(ast, state) { // Newton's method: https://en.wikipedia.org/wiki/Newton%27s_method return this.runFunction(ast.args, state, this.metadata('RATE'), (periods, payment, present, future, type, guess) => { if (guess <= -1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE); } const epsMax = 1e-7; const iterMax = 50; let rate = guess; type = type ? 1 : 0; for (let i = 0; i < iterMax; i++) { if (rate <= -1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } let y; if (Math.abs(rate) < epsMax) { y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; } else { const f = Math.pow(1 + rate, periods); y = present * f + payment * (1 / rate + type) * (f - 1) + future; } if (Math.abs(y) < epsMax) { return rate; } let dy; if (Math.abs(rate) < epsMax) { dy = present * periods + payment * type * periods; } else { const f = Math.pow(1 + rate, periods); const df = periods * Math.pow(1 + rate, periods - 1); dy = present * df + payment * (1 / rate + type) * df + payment * (-1 / (rate * rate)) * (f - 1); } rate -= y / dy; } return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); }); } pv(ast, state) { return this.runFunction(ast.args, state, this.metadata('PV'), (rate, periods, payment, future, type) => { type = type ? 1 : 0; if (rate === -1) { if (periods === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } } if (rate === 0) { return -payment * periods - future; } else { return ((1 - Math.pow(1 + rate, periods)) * payment * (1 + rate * type) / rate - future) / Math.pow(1 + rate, periods); } }); } rri(ast, state) { return this.runFunction(ast.args, state, this.metadata('RRI'), (periods, present, future) => { if (present === 0 || future < 0 && present > 0 || future > 0 && present < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } return Math.pow(future / present, 1 / periods) - 1; }); } sln(ast, state) { return this.runFunction(ast.args, state, this.metadata('SLN'), (cost, salvage, life) => { if (life === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return (cost - salvage) / life; }); } syd(ast, state) { return this.runFunction(ast.args, state, this.metadata('SYD'), (cost, salvage, life, period) => { if (period > life) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } return (cost - salvage) * (life - period + 1) * 2 / (life * (life + 1)); }); } tbilleq(ast, state) { return this.runFunction(ast.args, state, this.metadata('TBILLEQ'), (settlement, maturity, discount) => { settlement = Math.round(settlement); maturity = Math.round(maturity); if (settlement >= maturity) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } const startDate = this.dateTimeHelper.numberToSimpleDate(settlement); const endDate = this.dateTimeHelper.numberToSimpleDate(maturity); if (endDate.year > startDate.year + 1 || endDate.year === startDate.year + 1 && (endDate.month > startDate.month || endDate.month === startDate.month && endDate.day > startDate.day)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } const denom = 360 - discount * (maturity - settlement); if (denom === 0) { return 0; } if (denom < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } return 365 * discount / denom; }); } tbillprice(ast, state) { return this.runFunction(ast.args, state, this.metadata('TBILLPRICE'), (settlement, maturity, discount) => { settlement = Math.round(settlement); maturity = Math.round(maturity); if (settlement >= maturity) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } const startDate = this.dateTimeHelper.numberToSimpleDate(settlement); const endDate = this.dateTimeHelper.numberToSimpleDate(maturity); if (endDate.year > startDate.year + 1 || endDate.year === startDate.year + 1 && (endDate.month > startDate.month || endDate.month === startDate.month && endDate.day > startDate.day)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } const denom = 360 - discount * (maturity - settlement); if (denom === 0) { return 0; } if (denom < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } return 100 * (1 - discount * (maturity - settlement) / 360); }); } tbillyield(ast, state) { return this.runFunction(ast.args, state, this.metadata('TBILLYIELD'), (settlement, maturity, price) => { settlement = Math.round(settlement); maturity = Math.round(maturity); if (settlement >= maturity) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } const startDate = this.dateTimeHelper.numberToSimpleDate(settlement); const endDate = this.dateTimeHelper.numberToSimpleDate(maturity); if (endDate.year > startDate.year + 1 || endDate.year === startDate.year + 1 && (endDate.month > startDate.month || endDate.month === startDate.month && endDate.day > startDate.day)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM); } return (100 - price) * 360 / (price * (maturity - settlement)); }); } fvschedule(ast, state) { return this.runFunction(ast.args, state, this.metadata('FVSCHEDULE'), (value, ratios) => { const vals = ratios.valuesFromTopLeftCorner(); for (const val of vals) { if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val; } } for (const val of vals) { if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(val)) { value *= 1 + (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getRawValue)(val); } else if (val !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.EmptyValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NumberExpected); } } return value; }); } npv(ast, state) { return this.runFunction(ast.args, state, this.metadata('NPV'), (rate, ...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } return npvCore(rate, coerced); }); } mirr(ast, state) { return this.runFunction(ast.args, state, this.metadata('MIRR'), (range, frate, rrate) => { const vals = this.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()); if (vals instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return vals; } let posFlag = false; let negFlag = false; const posValues = []; const negValues = []; for (const val of vals) { if (val > 0) { posFlag = true; posValues.push(val); negValues.push(0); } else if (val < 0) { negFlag = true; negValues.push(val); posValues.push(0); } else { negValues.push(0); posValues.push(0); } } if (!posFlag || !negFlag) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const n = vals.length; const nom = npvCore(rrate, posValues); if (nom instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return nom; } const denom = npvCore(frate, negValues); if (denom instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return denom; } return Math.pow(-nom * Math.pow(1 + rrate, n) / denom / (1 + frate), 1 / (n - 1)) - 1; }); } pduration(ast, state) { return this.runFunction(ast.args, state, this.metadata('PDURATION'), (rate, pv, fv) => (Math.log(fv) - Math.log(pv)) / Math.log(1 + rate)); } xnpv(ast, state) { return this.runFunction(ast.args, state, this.metadata('XNPV'), (rate, values, dates) => { const valArr = values.valuesFromTopLeftCorner(); for (const val of valArr) { if (typeof val !== 'number') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NumberExpected); } } const valArrNum = valArr; const dateArr = dates.valuesFromTopLeftCorner(); for (const date of dateArr) { if (typeof date !== 'number') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NumberExpected); } } const dateArrNum = dateArr; if (dateArrNum.length !== valArrNum.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const n = dateArrNum.length; let ret = 0; if (dateArrNum[0] < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } for (let i = 0; i < n; i++) { dateArrNum[i] = Math.floor(dateArrNum[i]); if (dateArrNum[i] < dateArrNum[0]) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } ret += valArrNum[i] / Math.pow(1 + rate, (dateArrNum[i] - dateArrNum[0]) / 365); } return ret; }); } } FinancialPlugin.implementedFunctions = { 'PMT': { method: 'pmt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'IPMT': { method: 'ipmt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'PPMT': { method: 'ppmt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'FV': { method: 'fv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'CUMIPMT': { method: 'cumipmt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 0, maxValue: 1 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'CUMPRINC': { method: 'cumprinc', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 0, maxValue: 1 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'DB': { method: 'db', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 1, maxValue: 12, defaultValue: 12 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'DDB': { method: 'ddb', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.INTEGER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0, defaultValue: 2 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'DOLLARDE': { method: 'dollarde', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'DOLLARFR': { method: 'dollarfr', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'EFFECT': { method: 'effect', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 1 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'ISPMT': { method: 'ispmt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }] }, 'NOMINAL': { method: 'nominal', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 1 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'NPER': { method: 'nper', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'PV': { method: 'pv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'RATE': { method: 'rate', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, defaultValue: 0.1 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'RRI': { method: 'rri', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'SLN': { method: 'sln', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'SYD': { method: 'syd', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'TBILLEQ': { method: 'tbilleq', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'TBILLPRICE': { method: 'tbillprice', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'TBILLYIELD': { method: 'tbillyield', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'FVSCHEDULE': { method: 'fvschedule', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.RANGE }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'NPV': { method: 'npv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.ANY }], repeatLastArgs: 1, returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_CURRENCY }, 'MIRR': { method: 'mirr', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }], returnNumberType: _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType.NUMBER_PERCENT }, 'PDURATION': { method: 'pduration', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: 0 }] }, 'XNPV': { method: 'xnpv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, greaterThan: -1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.RANGE }] } }; function pmtCore(rate, periods, present, future, type) { if (rate === 0) { return (-present - future) / periods; } else { const term = Math.pow(1 + rate, periods); return (future * rate + present * rate * term) * (type ? 1 / (1 + rate) : 1) / (1 - term); } } function ipmtCore(rate, period, periods, present, future, type) { const payment = pmtCore(rate, periods, present, future, type); if (period === 1) { return rate * (type ? 0 : -present); } else { return rate * (type ? fvCore(rate, period - 2, payment, present, type) - payment : fvCore(rate, period - 1, payment, present, type)); } } function fvCore(rate, periods, payment, value, type) { if (rate === 0) { return -value - payment * periods; } else { const term = Math.pow(1 + rate, periods); return payment * (type ? 1 + rate : 1) * (1 - term) / rate - value * term; } } function ppmtCore(rate, period, periods, present, future, type) { return pmtCore(rate, periods, present, future, type) - ipmtCore(rate, period, periods, present, future, type); } function npvCore(rate, args) { let acc = 0; for (let i = args.length - 1; i >= 0; i--) { acc += args[i]; if (rate === -1) { if (acc === 0) { continue; } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } } acc /= 1 + rate; } return acc; } /***/ }), /* 163 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FormulaTextPlugin: () => (/* binding */ FormulaTextPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(96); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class FormulaTextPlugin extends _index__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to FORMULATEXT(value) * * Returns a formula in a given cell as a string. * * @param ast * @param state */ formulatext(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('FORMULATEXT'), () => new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.WrongArgNumber), cellReference => { var _a; return (_a = this.serialization.getCellFormula(cellReference)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.Formula); }); } } FormulaTextPlugin.implementedFunctions = { 'FORMULATEXT': { method: 'formulatext', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NOERROR }], doesNotNeedArgumentsToBeComputed: true, isDependentOnSheetStructureChange: true, vectorizationForbidden: true } }; /***/ }), /* 164 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ HyperlinkPlugin: () => (/* binding */ HyperlinkPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class HyperlinkPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { hyperlink(ast, state) { return this.runFunction(ast.args, state, this.metadata('HYPERLINK'), (url, linkLabel) => { ast.hyperlink = url; return linkLabel !== null && linkLabel !== void 0 ? linkLabel : url; }); } } HyperlinkPlugin.implementedFunctions = { 'HYPERLINK': { method: 'hyperlink', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.STRING, optionalArg: true }] } }; /***/ }), /* 165 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ InformationPlugin: () => (/* binding */ InformationPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(69); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing information functions */ class InformationPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionPlugin { /** * Corresponds to ISBINARY(value) * * Returns true if provided value is a valid binary number * * @param ast * @param state */ isbinary(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISBINARY'), arg => /^[01]{1,10}$/.test(arg)); } /** * Corresponds to ISERR(value) * * Returns true if provided value is an error except #N/A! * * @param ast * @param state */ iserr(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISERR'), arg => arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError && arg.type !== _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA); } /** * Corresponds to ISERROR(value) * * Checks whether provided value is an error * * @param ast * @param state */ iserror(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISERROR'), arg => arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError); } /** * Corresponds to ISFORMULA(value) * * Checks whether referenced cell is a formula * * @param ast * @param state */ isformula(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('ISFORMULA'), () => new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber), reference => { const vertex = this.dependencyGraph.addressMapping.getCell(reference); return vertex instanceof _DependencyGraph_FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__.FormulaVertex; }); } /** * Corresponds to ISBLANK(value) * * Checks whether provided cell reference is empty * * @param ast * @param state */ isblank(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISBLANK'), arg => arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue); } /** * Corresponds to ISNA(value) * * Returns true if provided value is #N/A! error * * @param ast * @param state */ isna(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISNA'), arg => arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError && arg.type == _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA); } /** * Corresponds to ISNUMBER(value) * * Checks whether provided cell reference is a number * * @param ast * @param state */ isnumber(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISNUMBER'), _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber); } /** * Corresponds to ISLOGICAL(value) * * Checks whether provided cell reference is of logical type * * @param ast * @param state */ islogical(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISLOGICAL'), arg => typeof arg === 'boolean'); } /** * Corresponds to ISREF(value) * * Returns true if provided value is #REF! error * * @param ast * @param state */ isref(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISREF'), arg => arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError && (arg.type == _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF || arg.type == _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.CYCLE)); } /** * Corresponds to ISTEXT(value) * * Checks whether provided cell reference is of logical type * * @param ast * @param state */ istext(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISTEXT'), arg => typeof arg === 'string'); } /** * Corresponds to ISNONTEXT(value) * * Checks whether provided cell reference is of logical type * * @param ast * @param state */ isnontext(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISNONTEXT'), arg => !(typeof arg === 'string')); } /** * Corresponds to COLUMN(reference) * * Returns column number of a reference or a formula cell if reference not provided * * @param ast * @param state */ column(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('COLUMN'), () => state.formulaAddress.col + 1, reference => reference.col + 1); } /** * Corresponds to COLUMNS(range) * * Returns number of columns in provided range of cells * * @param ast * @param state */ columns(ast, state) { if (ast.args.length !== 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } if (ast.args.some(astIt => astIt.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.EmptyArg); } let argAst = ast.args[0]; while (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS) { argAst = argAst.expression; } if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE || argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE) { return argAst.end.col - argAst.start.col + 1; } else if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE) { return 1; } else if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE) { return this.config.maxColumns; } else { const val = this.evaluateAst(argAst, state); if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) { return val.width(); } else if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val; } else { return 1; } } } /** * Corresponds to ROW(reference) * * Returns row number of a reference or a formula cell if reference not provided * * @param ast * @param state */ row(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('ROW'), () => state.formulaAddress.row + 1, reference => reference.row + 1); } /** * Corresponds to ROWS(range) * * Returns number of rows in provided range of cells * * @param ast * @param state */ rows(ast, state) { if (ast.args.length !== 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } if (ast.args.some(astIt => astIt.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.EmptyArg); } let argAst = ast.args[0]; while (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS) { argAst = argAst.expression; } if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE || argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE) { return argAst.end.row - argAst.start.row + 1; } else if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE) { return 1; } else if (argAst.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE) { return this.config.maxRows; } else { const val = this.evaluateAst(argAst, state); if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) { return val.height(); } else if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val; } else { return 1; } } } /** * Corresponds to INDEX * * Returns specific position in 2d array. * * @param ast * @param state */ index(ast, state) { return this.runFunction(ast.args, state, this.metadata('INDEX'), (rangeValue, row, col) => { var _a, _b, _c, _d, _e, _f; if (col < 1 || row < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.LessThanOne); } if (col > rangeValue.width() || row > rangeValue.height()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge); } return (_f = (_c = (_b = (_a = rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.data) === null || _a === void 0 ? void 0 : _a[row - 1]) === null || _b === void 0 ? void 0 : _b[col - 1]) !== null && _c !== void 0 ? _c : (_e = (_d = rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.data) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e[0]) !== null && _f !== void 0 ? _f : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRangeExpected); }); } /** * Corresponds to NA() * * Returns #N/A! * * @param _ast * @param _state */ na(_ast, _state) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA); } /** * Corresponds to SHEET(value) * * Returns sheet number of a given value or a formula sheet number if no argument is provided * * @param ast * @param state */ sheet(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('SHEET'), () => state.formulaAddress.sheet + 1, reference => reference.sheet + 1, value => { const sheetNumber = this.dependencyGraph.sheetMapping.get(value); if (sheetNumber !== undefined) { return sheetNumber + 1; } else { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.SheetRef); } }); } /** * Corresponds to SHEETS(value) * * Returns number of sheet of a given reference or number of all sheets in workbook when no argument is provided. * It returns always 1 for a valid reference as 3D references are not supported. * * @param ast * @param state */ sheets(ast, state) { return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('SHEETS'), () => this.dependencyGraph.sheetMapping.numberOfSheets(), // return number of sheets if no argument () => 1, // return 1 for valid reference () => new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRefExpected) // error otherwise ); } } InformationPlugin.implementedFunctions = { 'COLUMN': { method: 'column', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NOERROR, optionalArg: true }], isDependentOnSheetStructureChange: true, doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'COLUMNS': { method: 'columns', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }], isDependentOnSheetStructureChange: true, doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'ISBINARY': { method: 'isbinary', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.STRING }] }, 'ISERR': { method: 'iserr', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISFORMULA': { method: 'isformula', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NOERROR }], doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'ISNA': { method: 'isna', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISREF': { method: 'isref', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }], vectorizationForbidden: true }, 'ISERROR': { method: 'iserror', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISBLANK': { method: 'isblank', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISNUMBER': { method: 'isnumber', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISLOGICAL': { method: 'islogical', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISTEXT': { method: 'istext', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'ISNONTEXT': { method: 'isnontext', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.SCALAR }] }, 'INDEX': { method: 'index', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'NA': { method: 'na', parameters: [] }, 'ROW': { method: 'row', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NOERROR, optionalArg: true }], isDependentOnSheetStructureChange: true, doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'ROWS': { method: 'rows', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }], isDependentOnSheetStructureChange: true, doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'SHEET': { method: 'sheet', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.STRING }], doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true }, 'SHEETS': { method: 'sheets', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.STRING }], doesNotNeedArgumentsToBeComputed: true, vectorizationForbidden: true } }; /***/ }), /* 166 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ IsEvenPlugin: () => (/* binding */ IsEvenPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class IsEvenPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { iseven(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISEVEN'), val => val % 2 === 0); } } IsEvenPlugin.implementedFunctions = { 'ISEVEN': { method: 'iseven', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 167 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ IsOddPlugin: () => (/* binding */ IsOddPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class IsOddPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { isodd(ast, state) { return this.runFunction(ast.args, state, this.metadata('ISODD'), val => val % 2 === 1); } } IsOddPlugin.implementedFunctions = { 'ISODD': { method: 'isodd', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 168 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LogarithmPlugin: () => (/* binding */ LogarithmPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class LogarithmPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { log10(ast, state) { return this.runFunction(ast.args, state, this.metadata('LOG10'), Math.log10); } log(ast, state) { return this.runFunction(ast.args, state, this.metadata('LOG'), (arg, base) => Math.log(arg) / Math.log(base)); } ln(ast, state) { return this.runFunction(ast.args, state, this.metadata('LN'), Math.log); } } LogarithmPlugin.implementedFunctions = { 'LOG10': { method: 'log10', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] }, 'LOG': { method: 'log', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, defaultValue: 10, greaterThan: 0 }] }, 'LN': { method: 'ln', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 169 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ MathConstantsPlugin: () => (/* binding */ MathConstantsPlugin), /* harmony export */ PI: () => (/* binding */ PI) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const PI = parseFloat(Math.PI.toFixed(14)); class MathConstantsPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { pi(ast, state) { return this.runFunction(ast.args, state, this.metadata('PI'), () => PI); } sqrtpi(ast, state) { return this.runFunction(ast.args, state, this.metadata('SQRTPI'), arg => Math.sqrt(PI * arg)); } } MathConstantsPlugin.implementedFunctions = { 'PI': { method: 'pi', parameters: [] }, 'SQRTPI': { method: 'sqrtpi', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, minValue: 0 }] } }; /***/ }), /* 170 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ MatrixPlugin: () => (/* binding */ MatrixPlugin) /* harmony export */ }); /* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7); /* harmony import */ var _InterpreterState__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(95); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(69); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function arraySizeForMultiplication(leftArraySize, rightArraySize) { return new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(rightArraySize.width, leftArraySize.height); } function arraySizeForPoolFunction(inputArray, windowSize, stride) { return new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(1 + (inputArray.width - windowSize) / stride, 1 + (inputArray.height - windowSize) / stride); } class MatrixPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionPlugin { mmult(ast, state) { return this.runFunction(ast.args, state, this.metadata('MMULT'), (leftMatrix, rightMatrix) => { if (!leftMatrix.hasOnlyNumbers() || !rightMatrix.hasOnlyNumbers()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NumberRange); } if (rightMatrix.height() !== leftMatrix.width()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ArrayDimensions); } const outputSize = arraySizeForMultiplication(leftMatrix.size, rightMatrix.size); const result = this.createKernel(function (a, b, width) { let sum = 0; for (let i = 0; i < width; ++i) { sum += a[this.thread.y][i] * b[i][this.thread.x]; } return sum; }, outputSize)(leftMatrix.rawNumbers(), rightMatrix.rawNumbers(), leftMatrix.width()); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.onlyNumbers(result); }); } mmultArraySize(ast, state) { if (ast.args.length !== 2) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('MMULT'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_4__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); const [left, right] = subChecks; return arraySizeForMultiplication(left, right); } maxpool(ast, state) { return this.runFunction(ast.args, state, this.metadata('MAXPOOL'), (matrix, windowSize, stride = windowSize) => { if (!matrix.hasOnlyNumbers()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NumberRange); } const outputSize = arraySizeForPoolFunction(matrix.size, windowSize, stride); const result = this.createKernel(function (a, windowSize, stride) { const leftCornerX = this.thread.x * stride; const leftCornerY = this.thread.y * stride; let currentMax = a[leftCornerY][leftCornerX]; for (let i = 0; i < windowSize; i++) { for (let j = 0; j < windowSize; j++) { currentMax = Math.max(currentMax, a[leftCornerY + i][leftCornerX + j]); } } return currentMax; }, outputSize)(matrix.rawNumbers(), windowSize, stride); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.onlyNumbers(result); }); } medianpool(ast, state) { return this.runFunction(ast.args, state, this.metadata('MEDIANPOOL'), (matrix, windowSize, stride = windowSize) => { if (!matrix.hasOnlyNumbers()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NumberRange); } const outputSize = arraySizeForPoolFunction(matrix.size, windowSize, stride); const result = this.createKernel(function (a, windowSize, stride) { const leftCornerX = this.thread.x * stride; const leftCornerY = this.thread.y * stride; let currentMax = a[leftCornerY][leftCornerX]; for (let i = 0; i < windowSize; i++) { for (let j = 0; j < windowSize; j++) { currentMax = Math.max(currentMax, a[leftCornerY + i][leftCornerX + j]); } } let currentMin = a[leftCornerY][leftCornerX]; for (let i2 = 0; i2 < windowSize; i2++) { for (let j2 = 0; j2 < windowSize; j2++) { currentMin = Math.min(currentMin, a[leftCornerY + i2][leftCornerX + j2]); } } const numberOfElements = windowSize * windowSize; let leftEnd = currentMin; let rightEnd = currentMax; let result = 42; for (let iter = 0; iter < 32; iter++) { const medianGuess = (leftEnd + rightEnd) / 2; let medianGuessCount = 0; for (let i3 = 0; i3 < windowSize; i3++) { for (let j3 = 0; j3 < windowSize; j3++) { if (a[leftCornerY + i3][leftCornerX + j3] > medianGuess) { medianGuessCount++; } } } if (windowSize % 2 === 0) { if (medianGuessCount === numberOfElements / 2) { result = medianGuess; break; } else if (medianGuessCount > numberOfElements / 2) { leftEnd = medianGuess; } else { rightEnd = medianGuess; } } else { if (medianGuessCount === (numberOfElements - 1) / 2) { result = medianGuess; break; } else if (medianGuessCount > (numberOfElements - 1) / 2) { leftEnd = medianGuess; } else { rightEnd = medianGuess; } } } return result; }, outputSize)(matrix.rawNumbers(), windowSize, stride); return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.onlyNumbers(result); }); } maxpoolArraySize(ast, state) { if (ast.args.length < 2 || ast.args.length > 3) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('MAXPOOL'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_4__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); const array = subChecks[0]; const windowArg = ast.args[1]; let window; if (windowArg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER) { window = windowArg.value; } else { window = 1; } let stride = window; if (ast.args.length === 3) { const strideArg = ast.args[2]; if (strideArg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER) { stride = strideArg.value; } else { stride = 1; // codecov: unreachable - strideArg is always type AstNodeType.NUMBER due to FunctionPlugin argument checking+coersion } } if (window > array.width || window > array.height || stride > window || (array.width - window) % stride !== 0 || (array.height - window) % stride !== 0) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } return arraySizeForPoolFunction(array, window, stride); } medianpoolArraySize(ast, state) { return this.maxpoolArraySize(ast, state); } transpose(ast, state) { return this.runFunction(ast.args, state, this.metadata('TRANSPOSE'), matrix => { const input = matrix.rawData(); const inputSize = matrix.size; const result = []; for (let i = 0; i < inputSize.width; ++i) { result[i] = []; for (let j = 0; j < inputSize.height; ++j) { result[i][j] = input[j][i]; } } return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.onlyValues(result); }); } transposeArraySize(ast, state) { if (ast.args.length !== 1) { return _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize.error(); } const metadata = this.metadata('TRANSPOSE'); const subChecks = ast.args.map(arg => { var _a; return this.arraySizeForAst(arg, new _InterpreterState__WEBPACK_IMPORTED_MODULE_4__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false))); }); const [size] = subChecks; return new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(size.height, size.width); } createKernel(kernel, outputSize) { return function (...args) { const result = []; for (let y = 0; y < outputSize.height; ++y) { result.push([]); for (let x = 0; x < outputSize.width; ++x) { result[y][x] = kernel.apply({ thread: { x, y } }, args); } } return result; }; } } MatrixPlugin.implementedFunctions = { 'MMULT': { method: 'mmult', arraySizeMethod: 'mmultArraySize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }], vectorizationForbidden: true }, 'TRANSPOSE': { method: 'transpose', arraySizeMethod: 'transposeArraySize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }], vectorizationForbidden: true }, 'MAXPOOL': { method: 'maxpool', arraySizeMethod: 'maxpoolArraySize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER, optionalArg: true }], vectorizationForbidden: true }, 'MEDIANPOOL': { method: 'medianpool', arraySizeMethod: 'medianpoolArraySize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_6__.FunctionArgumentType.NUMBER, optionalArg: true }], vectorizationForbidden: true } }; /***/ }), /* 171 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ MedianPlugin: () => (/* binding */ MedianPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing MEDIAN function */ class MedianPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to MEDIAN(Number1, Number2, ...). * * Returns a median of given numbers. * * @param ast * @param state */ median(ast, state) { return this.runFunction(ast.args, state, this.metadata('MEDIAN'), (...args) => { const values = this.arithmeticHelper.coerceNumbersExactRanges(args); if (values instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return values; } if (values.length === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.OneValue); } values.sort((a, b) => a - b); if (values.length % 2 === 0) { return (values[values.length / 2 - 1] + values[values.length / 2]) / 2; } else { return values[Math.floor(values.length / 2)]; } }); } large(ast, state) { return this.runFunction(ast.args, state, this.metadata('LARGE'), (range, n) => { const vals = this.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()); if (vals instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return vals; } vals.sort((a, b) => a - b); n = Math.trunc(n); if (n > vals.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } return vals[vals.length - n]; }); } small(ast, state) { return this.runFunction(ast.args, state, this.metadata('SMALL'), (range, n) => { const vals = this.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()); if (vals instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return vals; } vals.sort((a, b) => a - b); n = Math.trunc(n); if (n > vals.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } return vals[n - 1]; }); } } MedianPlugin.implementedFunctions = { 'MEDIAN': { method: 'median', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'LARGE': { method: 'large', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'SMALL': { method: 'small', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 1 }] } }; /***/ }), /* 172 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ModuloPlugin: () => (/* binding */ ModuloPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ModuloPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionPlugin { mod(ast, state) { return this.runFunction(ast.args, state, this.metadata('MOD'), (dividend, divisor) => { if (divisor === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } else { return dividend % divisor; } }); } } ModuloPlugin.implementedFunctions = { 'MOD': { method: 'mod', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_1__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 173 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ NumericAggregationPlugin: () => (/* binding */ NumericAggregationPlugin) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(77); /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(98); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(70); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(69); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function zeroForInfinite(value) { if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.isExtendedNumber)(value) && !Number.isFinite((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue)(value))) { return 0; } else { return value; } } class MomentsAggregate { constructor(sumsq, sum, count) { this.sumsq = sumsq; this.sum = sum; this.count = count; } static single(arg) { return new MomentsAggregate(arg * arg, arg, 1); } compose(other) { return new MomentsAggregate(this.sumsq + other.sumsq, this.sum + other.sum, this.count + other.count); } averageValue() { if (this.count > 0) { return this.sum / this.count; } else { return undefined; } } varSValue() { if (this.count > 1) { return (this.sumsq - this.sum * this.sum / this.count) / (this.count - 1); } else { return undefined; } } varPValue() { if (this.count > 0) { return (this.sumsq - this.sum * this.sum / this.count) / this.count; } else { return undefined; } } } MomentsAggregate.empty = new MomentsAggregate(0, 0, 0); class NumericAggregationPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionPlugin { constructor() { super(...arguments); this.addWithEpsilonRaw = (left, right) => this.arithmeticHelper.addWithEpsilonRaw(left, right); } /** * Corresponds to SUM(Number1, Number2, ...). * * Returns a sum of given numbers. * * @param ast * @param state */ sum(ast, state) { return this.doSum(ast.args, state); } sumsq(ast, state) { return this.reduce(ast.args, state, 0, 'SUMSQ', this.addWithEpsilonRaw, arg => Math.pow((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue)(arg), 2), strictlyNumbers); } /** * Corresponds to MAX(Number1, Number2, ...). * * Returns a max of given numbers. * * @param ast * @param state */ max(ast, state) { return this.doMax(ast.args, state); } maxa(ast, state) { const value = this.reduce(ast.args, state, Number.NEGATIVE_INFINITY, 'MAXA', (left, right) => Math.max(left, right), _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, numbersBooleans); return zeroForInfinite(value); } /** * Corresponds to MIN(Number1, Number2, ...). * * Returns a min of given numbers. * * @param ast * @param state */ min(ast, state) { return this.doMin(ast.args, state); } mina(ast, state) { const value = this.reduce(ast.args, state, Number.POSITIVE_INFINITY, 'MINA', (left, right) => Math.min(left, right), _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, numbersBooleans); return zeroForInfinite(value); } count(ast, state) { return this.doCount(ast.args, state); } counta(ast, state) { return this.doCounta(ast.args, state); } average(ast, state) { return this.doAverage(ast.args, state); } averagea(ast, state) { var _a; const result = this.reduce(ast.args, state, MomentsAggregate.empty, '_AGGREGATE_A', (left, right) => left.compose(right), arg => MomentsAggregate.single((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue)(arg)), numbersBooleans); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.averageValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } vars(ast, state) { return this.doVarS(ast.args, state); } varp(ast, state) { return this.doVarP(ast.args, state); } vara(ast, state) { var _a; const result = this.reduceAggregateA(ast.args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.varSValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } varpa(ast, state) { var _a; const result = this.reduceAggregateA(ast.args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.varPValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } stdevs(ast, state) { return this.doStdevS(ast.args, state); } stdevp(ast, state) { return this.doStdevP(ast.args, state); } stdeva(ast, state) { const result = this.reduceAggregateA(ast.args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { const val = result.varSValue(); return val === undefined ? new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO) : Math.sqrt(val); } } stdevpa(ast, state) { const result = this.reduceAggregateA(ast.args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { const val = result.varPValue(); return val === undefined ? new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO) : Math.sqrt(val); } } product(ast, state) { return this.doProduct(ast.args, state); } subtotal(ast, state) { if (ast.args.length < 2) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } const functionType = this.coerceToType(this.evaluateAst(ast.args[0], state), { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.NUMBER }, state); const args = ast.args.slice(1); switch (functionType) { case 1: case 101: return this.doAverage(args, state); case 2: case 102: return this.doCount(args, state); case 3: case 103: return this.doCounta(args, state); case 4: case 104: return this.doMax(args, state); case 5: case 105: return this.doMin(args, state); case 6: case 106: return this.doProduct(args, state); case 7: case 107: return this.doStdevS(args, state); case 8: case 108: return this.doStdevP(args, state); case 9: case 109: return this.doSum(args, state); case 10: case 110: return this.doVarS(args, state); case 11: case 111: return this.doVarP(args, state); default: return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } } reduceAggregate(args, state) { return this.reduce(args, state, MomentsAggregate.empty, '_AGGREGATE', (left, right) => { return left.compose(right); }, arg => { return MomentsAggregate.single((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue)(arg)); }, strictlyNumbers); } reduceAggregateA(args, state) { return this.reduce(args, state, MomentsAggregate.empty, '_AGGREGATE_A', (left, right) => { return left.compose(right); }, arg => { return MomentsAggregate.single((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue)(arg)); }, numbersBooleans); } doAverage(args, state) { var _a; const result = this.reduceAggregate(args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.averageValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } doVarS(args, state) { var _a; const result = this.reduceAggregate(args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.varSValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } doVarP(args, state) { var _a; const result = this.reduceAggregate(args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { return (_a = result.varPValue()) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO); } } doStdevS(args, state) { const result = this.reduceAggregate(args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { const val = result.varSValue(); return val === undefined ? new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO) : Math.sqrt(val); } } doStdevP(args, state) { const result = this.reduceAggregate(args, state); if (result instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return result; } else { const val = result.varPValue(); return val === undefined ? new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO) : Math.sqrt(val); } } doCount(args, state) { return this.reduce(args, state, 0, 'COUNT', (left, right) => left + right, _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, arg => (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.isExtendedNumber)(arg) ? 1 : 0); } doCounta(args, state) { return this.reduce(args, state, 0, 'COUNTA', (left, right) => left + right, _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, arg => arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.EmptyValue ? 0 : 1); } doMax(args, state) { const value = this.reduce(args, state, Number.NEGATIVE_INFINITY, 'MAX', (left, right) => Math.max(left, right), _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, strictlyNumbers); return zeroForInfinite(value); } doMin(args, state) { const value = this.reduce(args, state, Number.POSITIVE_INFINITY, 'MIN', (left, right) => Math.min(left, right), _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, strictlyNumbers); return zeroForInfinite(value); } doSum(args, state) { return this.reduce(args, state, 0, 'SUM', this.addWithEpsilonRaw, _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, strictlyNumbers); } doProduct(args, state) { return this.reduce(args, state, 1, 'PRODUCT', (left, right) => left * right, _InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.getRawValue, strictlyNumbers); } /** * Reduces procedure arguments with given reducing function * * @param args * @param state * @param initialAccValue - "neutral" value (equivalent of 0) * @param functionName - function name to use as cache key * @param reducingFunction - reducing function * @param mapFunction * @param coercionFunction */ reduce(args, state, initialAccValue, functionName, reducingFunction, mapFunction, coercionFunction) { if (args.length < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber); } return args.reduce((acc, arg) => { if (acc instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return acc; } if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.COLUMN_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.ROW_RANGE) { const val = this.evaluateRange(arg, state, initialAccValue, functionName, reducingFunction, mapFunction, coercionFunction); if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return val; } return reducingFunction(val, acc); } let value; value = this.evaluateAst(arg, state); if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_7__.SimpleRangeValue) { const coercedRangeValues = Array.from(value.valuesFromTopLeftCorner()).map(coercionFunction).filter(arg => arg !== undefined); return coercedRangeValues.map(arg => { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg; } else { return mapFunction(arg); } }).reduce((left, right) => { if (left instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return left; } else if (right instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return right; } else { return reducingFunction(left, right); } }, acc); } else if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) { value = coercionFunction(value); if (value === undefined) { return acc; } } else { value = this.coerceScalarToNumberOrError(value); value = coercionFunction(value); if (value === undefined) { return acc; } } if (value instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return value; } return reducingFunction(acc, mapFunction(value)); }, initialAccValue); } /** * Performs range operation on given range * * @param ast - cell range ast * @param state * @param initialAccValue - initial accumulator value for reducing function * @param functionName - function name to use as cache key * @param reducingFunction - reducing function * @param mapFunction * @param coercionFunction */ evaluateRange(ast, state, initialAccValue, functionName, reducingFunction, mapFunction, coercionFunction) { let range; try { range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromAst(ast, state.formulaAddress); } catch (err) { if (err instanceof _errors__WEBPACK_IMPORTED_MODULE_3__.SheetsNotEqual) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.RangeManySheets); } else { throw err; } } const rangeVertex = this.dependencyGraph.getRange(range.start, range.end); if (rangeVertex === undefined) { throw new Error('Range does not exists in graph'); } let value = rangeVertex.getFunctionValue(functionName); if (value === undefined) { const rangeValues = this.getRangeValues(functionName, range, rangeVertex, mapFunction, coercionFunction); value = rangeValues.reduce((arg1, arg2) => { if (arg1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg1; } else if (arg2 instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg2; } else { return reducingFunction(arg1, arg2); } }, initialAccValue); rangeVertex.setFunctionValue(functionName, value); } return value; } /** * Returns list of values for given range and function name * * If range is dependent on smaller range, list will contain value of smaller range for this function * and values of cells that are not present in smaller range * * @param functionName - function name (e.g., SUM) * @param range - cell range * @param rangeVertex * @param mapFunction * @param coercionFunction */ getRangeValues(functionName, range, rangeVertex, mapFunction, coercionFunction) { const rangeResult = []; const { smallerRangeVertex, restRange } = this.dependencyGraph.rangeMapping.findSmallerRange(range); let actualRange; if (smallerRangeVertex !== undefined && this.dependencyGraph.existsEdge(smallerRangeVertex, rangeVertex)) { const cachedValue = smallerRangeVertex.getFunctionValue(functionName); if (cachedValue !== undefined) { rangeResult.push(cachedValue); } else { for (const cellFromRange of smallerRangeVertex.range.addresses(this.dependencyGraph)) { const val = coercionFunction(this.dependencyGraph.getScalarValue(cellFromRange)); if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { rangeResult.push(val); } else if (val !== undefined) { rangeResult.push(mapFunction(val)); } } } actualRange = restRange; } else { actualRange = range; } for (const cellFromRange of actualRange.addresses(this.dependencyGraph)) { const val = coercionFunction(this.dependencyGraph.getScalarValue(cellFromRange)); if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { rangeResult.push(val); } else if (val !== undefined) { rangeResult.push(mapFunction(val)); } } return rangeResult; } } NumericAggregationPlugin.implementedFunctions = { 'SUM': { method: 'sum', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'SUMSQ': { method: 'sumsq', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'MAX': { method: 'max', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'MIN': { method: 'min', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'MAXA': { method: 'maxa', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'MINA': { method: 'mina', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'COUNT': { method: 'count', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'COUNTA': { method: 'counta', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'AVERAGE': { method: 'average', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'AVERAGEA': { method: 'averagea', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'PRODUCT': { method: 'product', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'VAR.S': { method: 'vars', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'VAR.P': { method: 'varp', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'VARA': { method: 'vara', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'VARPA': { method: 'varpa', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'STDEV.S': { method: 'stdevs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'STDEV.P': { method: 'stdevp', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'STDEVA': { method: 'stdeva', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'STDEVPA': { method: 'stdevpa', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'SUBTOTAL': { method: 'subtotal', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_8__.FunctionArgumentType.ANY }], repeatLastArgs: 1 } }; NumericAggregationPlugin.aliases = { VAR: 'VAR.S', VARP: 'VAR.P', STDEV: 'STDEV.S', STDEVP: 'STDEV.P', VARS: 'VAR.S', STDEVS: 'STDEV.S' }; function strictlyNumbers(arg) { if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.isExtendedNumber)(arg) || arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg; } else { return undefined; } } function numbersBooleans(arg) { if (typeof arg === 'boolean') { return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.coerceBooleanToNumber)(arg); } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_6__.isExtendedNumber)(arg) || arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) { return arg; } else if (typeof arg === 'string') { return 0; } else { return undefined; } } /***/ }), /* 174 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ PowerPlugin: () => (/* binding */ PowerPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class PowerPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { power(ast, state) { return this.runFunction(ast.args, state, this.metadata('POWER'), Math.pow); } } PowerPlugin.implementedFunctions = { 'POWER': { method: 'power', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 175 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RadiansPlugin: () => (/* binding */ RadiansPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RadiansPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { radians(ast, state) { return this.runFunction(ast.args, state, this.metadata('RADIANS'), arg => arg * (Math.PI / 180)); } } RadiansPlugin.implementedFunctions = { 'RADIANS': { method: 'radians', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 176 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RadixConversionPlugin: () => (/* binding */ RadixConversionPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _format_format__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(106); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const MAX_LENGTH = 10; const DECIMAL_NUMBER_OF_BITS = 255; const MIN_BASE = 2; const MAX_BASE = 36; const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; class RadixConversionPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionPlugin { dec2bin(ast, state) { return this.runFunction(ast.args, state, this.metadata('DEC2BIN'), (value, places) => decimalToBaseWithExactPadding(value, 2, places)); } dec2oct(ast, state) { return this.runFunction(ast.args, state, this.metadata('DEC2OCT'), (value, places) => decimalToBaseWithExactPadding(value, 8, places)); } dec2hex(ast, state) { return this.runFunction(ast.args, state, this.metadata('DEC2HEX'), (value, places) => decimalToBaseWithExactPadding(value, 16, places)); } bin2dec(ast, state) { return this.runFunction(ast.args, state, this.metadata('BIN2DEC'), binary => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH); if (binaryWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotBinary); } return twoComplementToDecimal(binaryWithSign, 2); }); } bin2oct(ast, state) { return this.runFunction(ast.args, state, this.metadata('BIN2OCT'), (binary, places) => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH); if (binaryWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotBinary); } return decimalToBaseWithExactPadding(twoComplementToDecimal(binaryWithSign, 2), 8, places); }); } bin2hex(ast, state) { return this.runFunction(ast.args, state, this.metadata('BIN2HEX'), (binary, places) => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH); if (binaryWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotBinary); } return decimalToBaseWithExactPadding(twoComplementToDecimal(binaryWithSign, 2), 16, places); }); } oct2dec(ast, state) { return this.runFunction(ast.args, state, this.metadata('OCT2DEC'), octal => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH); if (octalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotOctal); } return twoComplementToDecimal(octalWithSign, 8); }); } oct2bin(ast, state) { return this.runFunction(ast.args, state, this.metadata('OCT2BIN'), (octal, places) => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH); if (octalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotOctal); } return decimalToBaseWithExactPadding(twoComplementToDecimal(octalWithSign, 8), 2, places); }); } oct2hex(ast, state) { return this.runFunction(ast.args, state, this.metadata('OCT2HEX'), (octal, places) => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH); if (octalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotOctal); } return decimalToBaseWithExactPadding(twoComplementToDecimal(octalWithSign, 8), 16, places); }); } hex2dec(ast, state) { return this.runFunction(ast.args, state, this.metadata('HEX2DEC'), hexadecimal => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH); if (hexadecimalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotHex); } return twoComplementToDecimal(hexadecimalWithSign, 16); }); } hex2bin(ast, state) { return this.runFunction(ast.args, state, this.metadata('HEX2BIN'), (hexadecimal, places) => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH); if (hexadecimalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotHex); } return decimalToBaseWithExactPadding(twoComplementToDecimal(hexadecimalWithSign, 16), 2, places); }); } hex2oct(ast, state) { return this.runFunction(ast.args, state, this.metadata('HEX2OCT'), (hexadecimal, places) => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH); if (hexadecimalWithSign === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotHex); } return decimalToBaseWithExactPadding(twoComplementToDecimal(hexadecimalWithSign, 16), 8, places); }); } base(ast, state) { return this.runFunction(ast.args, state, this.metadata('BASE'), decimalToBaseWithMinimumPadding); } decimal(ast, state) { return this.runFunction(ast.args, state, this.metadata('DECIMAL'), (arg, base) => { const input = coerceStringToBase(arg, base, DECIMAL_NUMBER_OF_BITS); if (input === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NotHex); } return parseInt(input, base); }); } } RadixConversionPlugin.implementedFunctions = { 'DEC2BIN': { method: 'dec2bin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 1, maxValue: 10 }] }, 'DEC2OCT': { method: 'dec2oct', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 1, maxValue: 10 }] }, 'DEC2HEX': { method: 'dec2hex', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 1, maxValue: 10 }] }, 'BIN2DEC': { method: 'bin2dec', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }] }, 'BIN2OCT': { method: 'bin2oct', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'BIN2HEX': { method: 'bin2hex', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'OCT2DEC': { method: 'oct2dec', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }] }, 'OCT2BIN': { method: 'oct2bin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'OCT2HEX': { method: 'oct2hex', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'HEX2DEC': { method: 'hex2dec', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }] }, 'HEX2BIN': { method: 'hex2bin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'HEX2OCT': { method: 'hex2oct', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: MAX_LENGTH }] }, 'DECIMAL': { method: 'decimal', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: MIN_BASE, maxValue: MAX_BASE }] }, 'BASE': { method: 'base', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: MIN_BASE, maxValue: MAX_BASE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, optionalArg: true, minValue: 0, maxValue: DECIMAL_NUMBER_OF_BITS }] } }; function coerceStringToBase(value, base, maxLength) { const baseAlphabet = ALPHABET.substr(0, base); const regex = new RegExp(`^[${baseAlphabet}]+$`); if (value.length > maxLength || !regex.test(value)) { return undefined; } return value; } function decimalToBaseWithExactPadding(value, base, places) { if (value > maxValFromBase(base)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueBaseLarge); } if (value < minValFromBase(base)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueBaseSmall); } const result = decimalToRadixComplement(value, base); if (places === undefined || value < 0) { return result; } else if (result.length > places) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueBaseLong); } else { return (0,_format_format__WEBPACK_IMPORTED_MODULE_2__.padLeft)(result, places); } } function minValFromBase(base) { return -Math.pow(base, MAX_LENGTH) / 2; } function maxValFromBase(base) { return -minValFromBase(base) - 1; } function decimalToBaseWithMinimumPadding(value, base, places) { const result = decimalToRadixComplement(value, base); if (places !== undefined && places > result.length) { return (0,_format_format__WEBPACK_IMPORTED_MODULE_2__.padLeft)(result, places); } else { return result; } } function decimalToRadixComplement(value, base) { const offset = value < 0 ? Math.pow(base, MAX_LENGTH) : 0; return (value + offset).toString(base).toUpperCase(); } function twoComplementToDecimal(value, base) { const parsed = parseInt(value, base); const offset = Math.pow(base, MAX_LENGTH); return parsed >= offset / 2 ? parsed - offset : parsed; } /***/ }), /* 177 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RandomPlugin: () => (/* binding */ RandomPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RandomPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to RAND() * * Returns a pseudo-random floating-point random number * in the range [0,1). * * @param ast * @param state */ rand(ast, state) { return this.runFunction(ast.args, state, this.metadata('RAND'), Math.random); } randbetween(ast, state) { return this.runFunction(ast.args, state, this.metadata('RANDBETWEEN'), (lower, upper) => { if (upper < lower) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.WrongOrder); } lower = Math.ceil(lower); upper = Math.floor(upper) + 1; if (lower === upper) { upper += 1; } return lower + Math.floor(Math.random() * (upper - lower)); }); } } RandomPlugin.implementedFunctions = { 'RAND': { method: 'rand', parameters: [], isVolatile: true }, 'RANDBETWEEN': { method: 'randbetween', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }], isVolatile: true } }; /***/ }), /* 178 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RoundingPlugin: () => (/* binding */ RoundingPlugin), /* harmony export */ findNextEvenNumber: () => (/* binding */ findNextEvenNumber), /* harmony export */ findNextOddNumber: () => (/* binding */ findNextOddNumber) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function findNextOddNumber(arg) { const ceiled = Math.ceil(arg); return ceiled % 2 === 1 ? ceiled : ceiled + 1; } function findNextEvenNumber(arg) { const ceiled = Math.ceil(arg); return ceiled % 2 === 0 ? ceiled : ceiled + 1; } class RoundingPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { roundup(ast, state) { return this.runFunction(ast.args, state, this.metadata('ROUNDDOWN'), (numberToRound, places) => { const placesMultiplier = Math.pow(10, places); if (numberToRound < 0) { return -Math.ceil(-numberToRound * placesMultiplier) / placesMultiplier; } else { return Math.ceil(numberToRound * placesMultiplier) / placesMultiplier; } }); } rounddown(ast, state) { return this.runFunction(ast.args, state, this.metadata('ROUNDDOWN'), (numberToRound, places) => { const placesMultiplier = Math.pow(10, places); if (numberToRound < 0) { return -Math.floor(-numberToRound * placesMultiplier) / placesMultiplier; } else { return Math.floor(numberToRound * placesMultiplier) / placesMultiplier; } }); } round(ast, state) { return this.runFunction(ast.args, state, this.metadata('ROUND'), (numberToRound, places) => { const placesMultiplier = Math.pow(10, places); if (numberToRound < 0) { return -Math.round(-numberToRound * placesMultiplier) / placesMultiplier; } else { return Math.round(numberToRound * placesMultiplier) / placesMultiplier; } }); } intFunc(ast, state) { return this.runFunction(ast.args, state, this.metadata('INT'), coercedNumberToRound => { if (coercedNumberToRound < 0) { return -Math.floor(-coercedNumberToRound); } else { return Math.floor(coercedNumberToRound); } }); } even(ast, state) { return this.runFunction(ast.args, state, this.metadata('EVEN'), coercedNumberToRound => { if (coercedNumberToRound < 0) { return -findNextEvenNumber(-coercedNumberToRound); } else { return findNextEvenNumber(coercedNumberToRound); } }); } odd(ast, state) { return this.runFunction(ast.args, state, this.metadata('ODD'), coercedNumberToRound => { if (coercedNumberToRound < 0) { return -findNextOddNumber(-coercedNumberToRound); } else { return findNextOddNumber(coercedNumberToRound); } }); } ceilingmath(ast, state) { return this.runFunction(ast.args, state, this.metadata('CEILING.MATH'), (value, significance, mode) => { if (significance === 0 || value === 0) { return 0; } significance = Math.abs(significance); if (mode === 1 && value < 0) { significance = -significance; } return Math.ceil(value / significance) * significance; }); } ceiling(ast, state) { return this.runFunction(ast.args, state, this.metadata('CEILING'), (value, significance) => { if (value === 0) { return 0; } if (significance === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } if (value > 0 && significance < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.DistinctSigns); } return Math.ceil(value / significance) * significance; }); } ceilingprecise(ast, state) { return this.runFunction(ast.args, state, this.metadata('CEILING.PRECISE'), (value, significance) => { if (significance === 0 || value === 0) { return 0; } significance = Math.abs(significance); return Math.ceil(value / significance) * significance; }); } floormath(ast, state) { return this.runFunction(ast.args, state, this.metadata('FLOOR.MATH'), (value, significance, mode) => { if (significance === 0 || value === 0) { return 0; } significance = Math.abs(significance); if (mode === 1 && value < 0) { significance *= -1; } return Math.floor(value / significance) * significance; }); } floor(ast, state) { return this.runFunction(ast.args, state, this.metadata('FLOOR'), (value, significance) => { if (value === 0) { return 0; } if (significance === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } if (value > 0 && significance < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.DistinctSigns); } return Math.floor(value / significance) * significance; }); } floorprecise(ast, state) { return this.runFunction(ast.args, state, this.metadata('FLOOR.PRECISE'), (value, significance) => { if (significance === 0 || value === 0) { return 0; } significance = Math.abs(significance); return Math.floor(value / significance) * significance; }); } } RoundingPlugin.implementedFunctions = { 'ROUNDUP': { method: 'roundup', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'ROUNDDOWN': { method: 'rounddown', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'ROUND': { method: 'round', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'INT': { method: 'intFunc', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'EVEN': { method: 'even', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ODD': { method: 'odd', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'CEILING.MATH': { method: 'ceilingmath', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'CEILING': { method: 'ceiling', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'CEILING.PRECISE': { method: 'ceilingprecise', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'FLOOR.MATH': { method: 'floormath', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 0 }] }, 'FLOOR': { method: 'floor', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'FLOOR.PRECISE': { method: 'floorprecise', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] } }; RoundingPlugin.aliases = { 'ISO.CEILING': 'CEILING.PRECISE', 'TRUNC': 'ROUNDDOWN' }; /***/ }), /* 179 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SqrtPlugin: () => (/* binding */ SqrtPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class SqrtPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { sqrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('SQRT'), Math.sqrt); } } SqrtPlugin.implementedFunctions = { 'SQRT': { method: 'sqrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 180 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ConditionalAggregationPlugin: () => (/* binding */ ConditionalAggregationPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _CriterionFunctionCompute__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(181); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class AverageResult { constructor(sum, count) { this.sum = sum; this.count = count; } static single(arg) { return new AverageResult(arg, 1); } compose(other) { return new AverageResult(this.sum + other.sum, this.count + other.count); } averageValue() { if (this.count > 0) { return this.sum / this.count; } else { return undefined; } } } AverageResult.empty = new AverageResult(0, 0); /** Computes key for criterion function cache */ function conditionalAggregationFunctionCacheKey(functionName) { return conditions => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const conditionsStrings = conditions.map(c => `${c.conditionRange.range.sheet},${c.conditionRange.range.start.col},${c.conditionRange.range.start.row}`); return [functionName, ...conditionsStrings].join(','); }; } function zeroForInfinite(value) { if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(value) && !Number.isFinite((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(value))) { return 0; } else { return value; } } function mapToRawScalarValue(arg) { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg)) { return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg); } return undefined; } class ConditionalAggregationPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionPlugin { /** * Corresponds to SUMIF(Range, Criterion, SumRange) * * Range is the range to which criterion is to be applied. * Criterion is the criteria used to choose which cells will be included in sum. * SumRange is the range on which adding will be performed. * * @param ast * @param state */ sumif(ast, state) { const functionName = 'SUMIF'; const computeFn = (conditionRange, criterion, values) => this.computeConditionalAggregationFunction(values !== null && values !== void 0 ? values : conditionRange, [conditionRange, criterion], functionName, 0, (left, right) => this.arithmeticHelper.nonstrictadd(left, right), mapToRawScalarValue); return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } sumifs(ast, state) { const functionName = 'SUMIFS'; const computeFn = (values, ...args) => this.computeConditionalAggregationFunction(values, args, functionName, 0, (left, right) => this.arithmeticHelper.nonstrictadd(left, right), mapToRawScalarValue); return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } averageif(ast, state) { const functionName = 'AVERAGEIF'; const computeFn = (conditionRange, criterion, values) => { const averageResult = this.computeConditionalAggregationFunction(values !== null && values !== void 0 ? values : conditionRange, [conditionRange, criterion], functionName, AverageResult.empty, (left, right) => left.compose(right), arg => (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(arg) ? AverageResult.single((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(arg)) : AverageResult.empty); if (averageResult instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return averageResult; } else { return averageResult.averageValue() || new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } }; return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } /** * Corresponds to COUNTIF(Range, Criterion) * * Range is the range to which criterion is to be applied. * Criterion is the criteria used to choose which cells will be included in sum. * * Returns number of cells on which criteria evaluate to true. * * @param ast * @param state */ countif(ast, state) { const functionName = 'COUNTIF'; const computeFn = (conditionRange, criterion) => this.computeConditionalAggregationFunction(conditionRange, [conditionRange, criterion], functionName, 0, (left, right) => left + right, () => 1); return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } countifs(ast, state) { const functionName = 'COUNTIFS'; const computeFn = (...args) => this.computeConditionalAggregationFunction(args[0], args, functionName, 0, (left, right) => left + right, () => 1); return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } minifs(ast, state) { const functionName = 'MINIFS'; const composeFunction = (left, right) => { if (right === undefined || left === undefined) { return right === undefined ? left : right; } return Math.min(left, right); }; const computeFn = (values, ...args) => { const minResult = this.computeConditionalAggregationFunction(values, args, functionName, Number.POSITIVE_INFINITY, composeFunction, mapToRawScalarValue); return zeroForInfinite(minResult); }; return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } maxifs(ast, state) { const functionName = 'MAXIFS'; const composeFunction = (left, right) => { if (right === undefined || left === undefined) { return right === undefined ? left : right; } return Math.max(left, right); }; const computeFn = (values, ...args) => { const maxResult = this.computeConditionalAggregationFunction(values, args, functionName, Number.NEGATIVE_INFINITY, composeFunction, mapToRawScalarValue); return zeroForInfinite(maxResult); }; return this.runFunction(ast.args, state, this.metadata(functionName), computeFn); } computeConditionalAggregationFunction(valuesRange, conditionArgs, functionName, reduceInitialValue, composeFunction, mapFunction) { const conditions = []; for (let i = 0; i < conditionArgs.length; i += 2) { const conditionArg = conditionArgs[i]; const criterionPackage = this.interpreter.criterionBuilder.fromCellValue(conditionArgs[i + 1], this.arithmeticHelper); if (criterionPackage === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.BadCriterion); } conditions.push(new _CriterionFunctionCompute__WEBPACK_IMPORTED_MODULE_2__.Condition(conditionArg, criterionPackage)); } return new _CriterionFunctionCompute__WEBPACK_IMPORTED_MODULE_2__.CriterionFunctionCompute(this.interpreter, conditionalAggregationFunctionCacheKey(functionName), reduceInitialValue, composeFunction, mapFunction).compute(valuesRange, conditions); } } ConditionalAggregationPlugin.implementedFunctions = { SUMIF: { method: 'sumif', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE, optionalArg: true }] }, COUNTIF: { method: 'countif', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }] }, AVERAGEIF: { method: 'averageif', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE, optionalArg: true }] }, SUMIFS: { method: 'sumifs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }], repeatLastArgs: 2 }, COUNTIFS: { method: 'countifs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }], repeatLastArgs: 2 }, MINIFS: { method: 'minifs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }], repeatLastArgs: 2 }, MAXIFS: { method: 'maxifs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NOERROR }], repeatLastArgs: 2 } }; /***/ }), /* 181 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Condition: () => (/* binding */ Condition), /* harmony export */ CriterionFunctionCompute: () => (/* binding */ CriterionFunctionCompute) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _generatorUtils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(182); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ const findSmallerRangeForMany = (dependencyGraph, conditionRanges, valuesRange) => { if (valuesRange.end.row > valuesRange.start.row) { const valuesRangeEndRowLess = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(valuesRange.end.sheet, valuesRange.end.col, valuesRange.end.row - 1); const rowLessVertex = dependencyGraph.getRange(valuesRange.start, valuesRangeEndRowLess); if (rowLessVertex !== undefined) { return { smallerRangeVertex: rowLessVertex, restValuesRange: valuesRange.withStart((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(valuesRange.start.sheet, valuesRange.start.col, valuesRange.end.row)), restConditionRanges: conditionRanges.map(conditionRange => conditionRange.withStart((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(conditionRange.start.sheet, conditionRange.start.col, conditionRange.end.row))) }; } } return { restValuesRange: valuesRange, restConditionRanges: conditionRanges }; }; class CriterionFunctionCompute { constructor(interpreter, cacheKey, reduceInitialValue, composeFunction, mapFunction) { this.interpreter = interpreter; this.cacheKey = cacheKey; this.reduceInitialValue = reduceInitialValue; this.composeFunction = composeFunction; this.mapFunction = mapFunction; this.dependencyGraph = this.interpreter.dependencyGraph; } compute(simpleValuesRange, conditions) { for (const condition of conditions) { if (!condition.conditionRange.sameDimensionsAs(simpleValuesRange)) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } } const valuesRangeVertex = this.tryToGetRangeVertexForRangeValue(simpleValuesRange); const conditionsVertices = conditions.map(c => this.tryToGetRangeVertexForRangeValue(c.conditionRange)); if (valuesRangeVertex && conditionsVertices.every(e => e !== undefined)) { const fullCriterionString = conditions.map(c => c.criterionPackage.raw).join(','); const cachedResult = this.findAlreadyComputedValueInCache(valuesRangeVertex, this.cacheKey(conditions), fullCriterionString); if (cachedResult !== undefined) { this.interpreter.stats.incrementCriterionFunctionFullCacheUsed(); return cachedResult; } const cache = this.buildNewCriterionCache(this.cacheKey(conditions), conditions.map(c => c.conditionRange.range), simpleValuesRange.range); if (!cache.has(fullCriterionString)) { cache.set(fullCriterionString, [this.evaluateRangeValue(simpleValuesRange, conditions), conditions.map(condition => condition.criterionPackage.lambda)]); } valuesRangeVertex.setCriterionFunctionValues(this.cacheKey(conditions), cache); conditionsVertices.forEach(range => { if (range !== undefined) { range.addDependentCacheRange(valuesRangeVertex); } }); return cache.get(fullCriterionString)[0]; } else { return this.evaluateRangeValue(simpleValuesRange, conditions); } } tryToGetRangeVertexForRangeValue(rangeValue) { const maybeRange = rangeValue.range; if (maybeRange === undefined) { return undefined; } else { return this.dependencyGraph.getRange(maybeRange.start, maybeRange.end); } } reduceFunction(iterable) { let acc = this.reduceInitialValue; for (const val of iterable) { acc = this.composeFunction(acc, val); } return acc; } findAlreadyComputedValueInCache(rangeVertex, cacheKey, criterionString) { return rangeVertex.getCriterionFunctionValue(cacheKey, criterionString); } evaluateRangeValue(simpleValuesRange, conditions) { const criterionLambdas = conditions.map(condition => condition.criterionPackage.lambda); const values = Array.from(simpleValuesRange.valuesFromTopLeftCorner()).map(this.mapFunction)[Symbol.iterator](); const conditionsIterators = conditions.map(condition => condition.conditionRange.iterateValuesFromTopLeftCorner()); const filteredValues = ifFilter(criterionLambdas, conditionsIterators, values); return this.reduceFunction(filteredValues); } buildNewCriterionCache(cacheKey, simpleConditionRanges, simpleValuesRange) { const currentRangeVertex = this.dependencyGraph.getRange(simpleValuesRange.start, simpleValuesRange.end); const { smallerRangeVertex, restConditionRanges, restValuesRange } = findSmallerRangeForMany(this.dependencyGraph, simpleConditionRanges, simpleValuesRange); let smallerCache; if (smallerRangeVertex !== undefined && this.dependencyGraph.existsEdge(smallerRangeVertex, currentRangeVertex)) { smallerCache = smallerRangeVertex.getCriterionFunctionValues(cacheKey); } else { smallerCache = new Map(); } const newCache = new Map(); smallerCache.forEach(([value, criterionLambdas], key) => { const filteredValues = ifFilter(criterionLambdas, restConditionRanges.map(rcr => getRangeValues(this.dependencyGraph, rcr)), Array.from(getRangeValues(this.dependencyGraph, restValuesRange)).map(this.mapFunction)[Symbol.iterator]()); const newCacheValue = this.composeFunction(value, this.reduceFunction(filteredValues)); this.interpreter.stats.incrementCriterionFunctionPartialCacheUsed(); newCache.set(key, [newCacheValue, criterionLambdas]); }); return newCache; } } class Condition { constructor(conditionRange, criterionPackage) { this.conditionRange = conditionRange; this.criterionPackage = criterionPackage; } } function* getRangeValues(dependencyGraph, cellRange) { for (const cellFromRange of cellRange.addresses(dependencyGraph)) { yield (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(dependencyGraph.getScalarValue(cellFromRange)); } } function* ifFilter(criterionLambdas, conditionalIterables, computableIterable) { for (const computable of computableIterable) { const conditionalSplits = conditionalIterables.map(conditionalIterable => (0,_generatorUtils__WEBPACK_IMPORTED_MODULE_2__.split)(conditionalIterable)); if (!conditionalSplits.every(cs => Object.prototype.hasOwnProperty.call(cs, 'value'))) { return; } const conditionalFirsts = conditionalSplits.map(cs => (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.getRawValue)(cs.value)); if (zip(conditionalFirsts, criterionLambdas).every(([conditionalFirst, criterionLambda]) => criterionLambda(conditionalFirst))) { yield computable; } conditionalIterables = conditionalSplits.map(cs => cs.rest); } } function zip(arr1, arr2) { const result = []; for (let i = 0; i < Math.min(arr1.length, arr2.length); i++) { result.push([arr1[i], arr2[i]]); } return result; } /***/ }), /* 182 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ empty: () => (/* binding */ empty), /* harmony export */ first: () => (/* binding */ first), /* harmony export */ split: () => (/* binding */ split) /* harmony export */ }); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ function* empty() {} function split(iterable) { const iterator = iterable[Symbol.iterator](); const { done, value } = iterator.next(); if (done) { return { rest: empty() }; } else { return { value, rest: iterator }; } } function first(iterable) { const iterator = iterable[Symbol.iterator](); const { done, value } = iterator.next(); if (!done) { return value; } return undefined; } /***/ }), /* 183 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SumprodPlugin: () => (/* binding */ SumprodPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class SumprodPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionPlugin { sumproduct(ast, state) { return this.runFunction(ast.args, state, this.metadata('SUMPRODUCT'), (...args) => { const width = args[0].width(); const height = args[0].height(); for (const arg of args) { if (arg.width() !== width || arg.height() !== height) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } } let ret = 0; const iterators = args.map(arg => arg.iterateValuesFromTopLeftCorner()); for (let i = 0; i < width * height; i++) { let acc = 1; for (const it of iterators) { const val = it.next().value; if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return val; } const coercedVal = this.coerceScalarToNumberOrError(val); if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(coercedVal)) { acc *= (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getRawValue)(coercedVal); } else { acc = 0; } } ret += acc; } return ret; }); } } SumprodPlugin.implementedFunctions = { 'SUMPRODUCT': { method: 'sumproduct', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.RANGE }], repeatLastArgs: 1 } }; /***/ }), /* 184 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TextPlugin: () => (/* binding */ TextPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing text-specific functions */ class TextPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to CONCATENATE(value1, [value2, ...]) * * Concatenates provided arguments to one string. * * @param ast * @param state */ concatenate(ast, state) { return this.runFunction(ast.args, state, this.metadata('CONCATENATE'), (...args) => { return ''.concat(...args); }); } /** * Corresponds to SPLIT(string, index) * * Splits provided string using space separator and returns chunk at zero-based position specified by second argument * * @param ast * @param state */ split(ast, state) { return this.runFunction(ast.args, state, this.metadata('SPLIT'), (stringToSplit, indexToUse) => { const splittedString = stringToSplit.split(' '); if (indexToUse >= splittedString.length || indexToUse < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.IndexBounds); } return splittedString[indexToUse]; }); } len(ast, state) { return this.runFunction(ast.args, state, this.metadata('LEN'), arg => { return arg.length; }); } lower(ast, state) { return this.runFunction(ast.args, state, this.metadata('LOWER'), arg => { return arg.toLowerCase(); }); } trim(ast, state) { return this.runFunction(ast.args, state, this.metadata('TRIM'), arg => { return arg.replace(/^ +| +$/g, '').replace(/ +/g, ' '); }); } proper(ast, state) { return this.runFunction(ast.args, state, this.metadata('PROPER'), arg => { return arg.replace(/\p{L}+/gu, word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()); }); } clean(ast, state) { return this.runFunction(ast.args, state, this.metadata('CLEAN'), arg => { // eslint-disable-next-line no-control-regex return arg.replace(/[\u0000-\u001F]/g, ''); }); } exact(ast, state) { return this.runFunction(ast.args, state, this.metadata('EXACT'), (left, right) => { return left === right; }); } rept(ast, state) { return this.runFunction(ast.args, state, this.metadata('REPT'), (text, count) => { if (count < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NegativeCount); } return text.repeat(count); }); } right(ast, state) { return this.runFunction(ast.args, state, this.metadata('RIGHT'), (text, length) => { if (length < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NegativeLength); } else if (length === 0) { return ''; } return text.slice(-length); }); } left(ast, state) { return this.runFunction(ast.args, state, this.metadata('LEFT'), (text, length) => { if (length < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NegativeLength); } return text.slice(0, length); }); } mid(ast, state) { return this.runFunction(ast.args, state, this.metadata('MID'), (text, startPosition, numberOfChars) => { if (startPosition < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.LessThanOne); } if (numberOfChars < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NegativeLength); } return text.substring(startPosition - 1, startPosition + numberOfChars - 1); }); } replace(ast, state) { return this.runFunction(ast.args, state, this.metadata('REPLACE'), (text, startPosition, numberOfChars, newText) => { if (startPosition < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.LessThanOne); } if (numberOfChars < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NegativeLength); } return text.substring(0, startPosition - 1) + newText + text.substring(startPosition + numberOfChars - 1); }); } search(ast, state) { return this.runFunction(ast.args, state, this.metadata('SEARCH'), (pattern, text, startIndex) => { if (startIndex < 1 || startIndex > text.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.LengthBounds); } const normalizedPattern = pattern.toLowerCase(); const normalizedText = text.substring(startIndex - 1).toLowerCase(); const index = this.arithmeticHelper.requiresRegex(normalizedPattern) ? this.arithmeticHelper.searchString(normalizedPattern, normalizedText) : normalizedText.indexOf(normalizedPattern); return index > -1 ? index + startIndex : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.PatternNotFound); }); } substitute(ast, state) { return this.runFunction(ast.args, state, this.metadata('SUBSTITUTE'), (text, searchString, replacementString, occurrenceNum) => { const escapedSearchString = this.escapeRegExpSpecialCharacters(searchString); const searchRegExp = new RegExp(escapedSearchString, 'g'); if (occurrenceNum === undefined) { return text.replace(searchRegExp, replacementString); } if (occurrenceNum < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.LessThanOne); } let match; let i = 0; while ((match = searchRegExp.exec(text)) !== null) { if (occurrenceNum === ++i) { return text.substring(0, match.index) + replacementString + text.substring(searchRegExp.lastIndex); } } return text; }); } find(ast, state) { return this.runFunction(ast.args, state, this.metadata('FIND'), (pattern, text, startIndex) => { if (startIndex < 1 || startIndex > text.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.IndexBounds); } const shiftedText = text.substring(startIndex - 1); const index = shiftedText.indexOf(pattern) + startIndex; return index > 0 ? index : new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.PatternNotFound); }); } t(ast, state) { return this.runFunction(ast.args, state, this.metadata('T'), arg => { if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arg; } return typeof arg === 'string' ? arg : ''; }); } upper(ast, state) { return this.runFunction(ast.args, state, this.metadata('UPPER'), arg => { return arg.toUpperCase(); }); } escapeRegExpSpecialCharacters(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } } TextPlugin.implementedFunctions = { 'CONCATENATE': { method: 'concatenate', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }], repeatLastArgs: 1, expandRanges: true }, 'EXACT': { method: 'exact', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'SPLIT': { method: 'split', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'LEN': { method: 'len', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'LOWER': { method: 'lower', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'MID': { method: 'mid', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'TRIM': { method: 'trim', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'T': { method: 't', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.SCALAR }] }, 'PROPER': { method: 'proper', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'CLEAN': { method: 'clean', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'REPT': { method: 'rept', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'RIGHT': { method: 'right', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'LEFT': { method: 'left', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'REPLACE': { method: 'replace', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] }, 'SEARCH': { method: 'search', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'SUBSTITUTE': { method: 'substitute', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, optionalArg: true }] }, 'FIND': { method: 'find', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'UPPER': { method: 'upper', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.STRING }] } }; /***/ }), /* 185 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ TrigonometryPlugin: () => (/* binding */ TrigonometryPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /* harmony import */ var _MathConstantsPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(169); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ /** * Interpreter plugin containing trigonometric functions */ class TrigonometryPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { /** * Corresponds to ACOS(value) * * Returns the arc cosine (or inverse cosine) of a number. * * @param ast * @param state */ acos(ast, state) { return this.runFunction(ast.args, state, this.metadata('ACOS'), Math.acos); } asin(ast, state) { return this.runFunction(ast.args, state, this.metadata('ASIN'), Math.asin); } cos(ast, state) { return this.runFunction(ast.args, state, this.metadata('COS'), Math.cos); } sin(ast, state) { return this.runFunction(ast.args, state, this.metadata('SIN'), Math.sin); } tan(ast, state) { return this.runFunction(ast.args, state, this.metadata('TAN'), Math.tan); } atan(ast, state) { return this.runFunction(ast.args, state, this.metadata('ATAN'), Math.atan); } atan2(ast, state) { return this.runFunction(ast.args, state, this.metadata('ATAN2'), (x, y) => { if (x === 0 && y === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return Math.atan2(y, x); }); } cot(ast, state) { return this.runFunction(ast.args, state, this.metadata('COT'), arg => arg === 0 ? new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO) : 1 / Math.tan(arg)); } acot(ast, state) { return this.runFunction(ast.args, state, this.metadata('ACOT'), arg => arg === 0 ? _MathConstantsPlugin__WEBPACK_IMPORTED_MODULE_3__.PI / 2 : Math.atan(1 / arg)); } sec(ast, state) { return this.runFunction(ast.args, state, this.metadata('SEC'), arg => 1 / Math.cos(arg)); } csc(ast, state) { return this.runFunction(ast.args, state, this.metadata('CSC'), arg => arg === 0 ? new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO) : 1 / Math.sin(arg)); } sinh(ast, state) { return this.runFunction(ast.args, state, this.metadata('SINH'), Math.sinh); } asinh(ast, state) { return this.runFunction(ast.args, state, this.metadata('ASINH'), Math.asinh); } cosh(ast, state) { return this.runFunction(ast.args, state, this.metadata('COSH'), Math.cosh); } acosh(ast, state) { return this.runFunction(ast.args, state, this.metadata('ACOSH'), Math.acosh); } tanh(ast, state) { return this.runFunction(ast.args, state, this.metadata('TANH'), Math.tanh); } atanh(ast, state) { return this.runFunction(ast.args, state, this.metadata('ATANH'), Math.atanh); } coth(ast, state) { return this.runFunction(ast.args, state, this.metadata('COTH'), arg => arg === 0 ? new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO) : 1 / Math.tanh(arg)); } acoth(ast, state) { return this.runFunction(ast.args, state, this.metadata('ACOTH'), arg => arg === 0 ? new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NonZero) : Math.atanh(1 / arg)); } sech(ast, state) { return this.runFunction(ast.args, state, this.metadata('SECH'), arg => 1 / Math.cosh(arg)); } csch(ast, state) { return this.runFunction(ast.args, state, this.metadata('CSCH'), arg => arg === 0 ? new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO) : 1 / Math.sinh(arg)); } } TrigonometryPlugin.implementedFunctions = { 'ACOS': { method: 'acos', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ASIN': { method: 'asin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'COS': { method: 'cos', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SIN': { method: 'sin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'TAN': { method: 'tan', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ATAN': { method: 'atan', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ATAN2': { method: 'atan2', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'COT': { method: 'cot', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SEC': { method: 'sec', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'CSC': { method: 'csc', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SINH': { method: 'sinh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'COSH': { method: 'cosh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'TANH': { method: 'tanh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'COTH': { method: 'coth', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SECH': { method: 'sech', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'CSCH': { method: 'csch', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ACOT': { method: 'acot', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ASINH': { method: 'asinh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ACOSH': { method: 'acosh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ATANH': { method: 'atanh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'ACOTH': { method: 'acoth', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] } }; /***/ }), /* 186 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LookupPlugin: () => (/* binding */ LookupPlugin) /* harmony export */ }); /* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); /* harmony import */ var _Lookup_RowSearchStrategy__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(187); /* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(72); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(98); /* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class LookupPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionPlugin { constructor() { super(...arguments); this.rowSearch = new _Lookup_RowSearchStrategy__WEBPACK_IMPORTED_MODULE_3__.RowSearchStrategy(this.dependencyGraph); } /** * Corresponds to VLOOKUP(key, range, index, [sorted]) * * @param ast * @param state */ vlookup(ast, state) { return this.runFunction(ast.args, state, this.metadata('VLOOKUP'), (key, rangeValue, index, sorted) => { const range = rangeValue.range; if (range === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } if (index < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.LessThanOne); } if (index > range.width()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IndexLarge); } return this.doVlookup((0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.zeroIfEmpty)(key), rangeValue, index - 1, sorted); }); } /** * Corresponds to HLOOKUP(key, range, index, [sorted]) * * @param ast * @param state */ hlookup(ast, state) { return this.runFunction(ast.args, state, this.metadata('HLOOKUP'), (key, rangeValue, index, sorted) => { const range = rangeValue.range; if (range === undefined) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } if (index < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.LessThanOne); } if (index > range.height()) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IndexLarge); } return this.doHlookup((0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.zeroIfEmpty)(key), rangeValue, index - 1, sorted); }); } match(ast, state) { return this.runFunction(ast.args, state, this.metadata('MATCH'), (key, rangeValue, type) => { return this.doMatch((0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_5__.zeroIfEmpty)(key), rangeValue, type); }); } searchInRange(key, range, sorted, searchStrategy) { if (!sorted && typeof key === 'string' && this.arithmeticHelper.requiresRegex(key)) { return searchStrategy.advancedFind(this.arithmeticHelper.eqMatcherFunction(key), range); } else { const searchOptions = sorted ? { ordering: 'asc' } : { ordering: 'none', matchExactly: true }; return searchStrategy.find(key, range, searchOptions); } } doVlookup(key, rangeValue, index, sorted) { this.dependencyGraph.stats.start(_statistics__WEBPACK_IMPORTED_MODULE_4__.StatType.VLOOKUP); const range = rangeValue.range; let searchedRange; if (range === undefined) { searchedRange = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues(rangeValue.data.map(arg => [arg[0]])); } else { searchedRange = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyRange(_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(range.start, 1, range.height()), this.dependencyGraph); } const rowIndex = this.searchInRange(key, searchedRange, sorted, this.columnSearch); this.dependencyGraph.stats.end(_statistics__WEBPACK_IMPORTED_MODULE_4__.StatType.VLOOKUP); if (rowIndex === -1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueNotFound); } let value; if (range === undefined) { value = rangeValue.data[rowIndex][index]; } else { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.sheet, range.start.col + index, range.start.row + rowIndex); value = this.dependencyGraph.getCellValue(address); } if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } return value; } doHlookup(key, rangeValue, index, sorted) { const range = rangeValue.range; let searchedRange; if (range === undefined) { searchedRange = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues([rangeValue.data[0]]); } else { searchedRange = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyRange(_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(range.start, range.width(), 1), this.dependencyGraph); } const colIndex = this.searchInRange(key, searchedRange, sorted, this.rowSearch); if (colIndex === -1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueNotFound); } let value; if (range === undefined) { value = rangeValue.data[index][colIndex]; } else { const address = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.sheet, range.start.col + colIndex, range.start.row + index); value = this.dependencyGraph.getCellValue(address); } if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType); } return value; } doMatch(key, rangeValue, type) { if (![-1, 0, 1].includes(type)) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.BadMode); } if (rangeValue.width() > 1 && rangeValue.height() > 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA); } const searchStrategy = rangeValue.width() === 1 ? this.columnSearch : this.rowSearch; const searchOptions = type === 0 ? { ordering: 'none', matchExactly: true } : { ordering: type === -1 ? 'desc' : 'asc' }; const index = searchStrategy.find(key, rangeValue, searchOptions); if (index === -1) { return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueNotFound); } return index + 1; } } LookupPlugin.implementedFunctions = { 'VLOOKUP': { method: 'vlookup', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.BOOLEAN, defaultValue: true }] }, 'HLOOKUP': { method: 'hlookup', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.BOOLEAN, defaultValue: true }] }, 'MATCH': { method: 'match', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NOERROR }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_7__.FunctionArgumentType.NUMBER, defaultValue: 1 }] } }; /***/ }), /* 187 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RowSearchStrategy: () => (/* binding */ RowSearchStrategy) /* harmony export */ }); /* harmony import */ var _AdvancedFind__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(138); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RowSearchStrategy extends _AdvancedFind__WEBPACK_IMPORTED_MODULE_0__.AdvancedFind { constructor(dependencyGraph) { super(dependencyGraph); this.dependencyGraph = dependencyGraph; } /* * WARNING: Finding lower/upper bounds in unordered ranges is not supported. When ordering === 'none', assumes matchExactly === true */ find(searchKey, rangeValue, searchOptions) { return this.basicFind(searchKey, rangeValue, 'col', searchOptions); } } /***/ }), /* 188 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ RomanPlugin: () => (/* binding */ RomanPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class RomanPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionPlugin { roman(ast, state) { return this.runFunction(ast.args, state, this.metadata('ROMAN'), (val, mode) => { val = Math.trunc(val); if (mode === false) { mode = 4; } else if (mode === true) { mode = 0; } mode = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getRawValue)(this.coerceScalarToNumberOrError(mode)); if (mode instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return mode; } mode = Math.trunc(mode); if (mode < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } if (mode > 4) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } return romanMode(val, mode); }); } arabic(ast, state) { return this.runFunction(ast.args, state, this.metadata('ARABIC'), inputString => { inputString = inputString.trim().toUpperCase(); let minusSign = false; if (inputString.startsWith('-')) { inputString = inputString.slice(1); minusSign = true; if (inputString === '') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.InvalidRoman); } } const work = { input: inputString, acc: 0 }; eatToken(work, { token: 'MMM', val: 3000 }, { token: 'MM', val: 2000 }, { token: 'M', val: 1000 }); eatToken(work, { token: 'IM', val: 999 }, { token: 'VM', val: 995 }, { token: 'XM', val: 990 }, { token: 'LM', val: 950 }, { token: 'CM', val: 900 }); eatToken(work, { token: 'D', val: 500 }, { token: 'ID', val: 499 }, { token: 'VD', val: 495 }, { token: 'XD', val: 490 }, { token: 'LD', val: 450 }, { token: 'CD', val: 400 }); eatToken(work, { token: 'CCC', val: 300 }, { token: 'CC', val: 200 }, { token: 'C', val: 100 }); eatToken(work, { token: 'IC', val: 99 }, { token: 'VC', val: 95 }, { token: 'XC', val: 90 }); eatToken(work, { token: 'L', val: 50 }, { token: 'IL', val: 49 }, { token: 'VL', val: 45 }, { token: 'XL', val: 40 }); eatToken(work, { token: 'XXX', val: 30 }, { token: 'XX', val: 20 }, { token: 'X', val: 10 }); eatToken(work, { token: 'IX', val: 9 }); eatToken(work, { token: 'V', val: 5 }, { token: 'IV', val: 4 }); eatToken(work, { token: 'III', val: 3 }, { token: 'II', val: 2 }, { token: 'I', val: 1 }); if (work.input !== '') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.InvalidRoman); } else { return minusSign ? -work.acc : work.acc; } }); } } RomanPlugin.implementedFunctions = { 'ROMAN': { method: 'roman', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER, minValue: 1, lessThan: 4000 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NOERROR, optionalArg: true, defaultValue: 0 }] }, 'ARABIC': { method: 'arabic', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING }] } }; function eatToken(inputAcc, ...tokens) { for (const token of tokens) { if (inputAcc.input.startsWith(token.token)) { inputAcc.input = inputAcc.input.slice(token.token.length); inputAcc.acc += token.val; break; } } } function romanMode(input, mode) { const work = { val: input % 1000, acc: 'M'.repeat(Math.floor(input / 1000)) }; if (mode === 4) { absorb(work, 'IM', 999, 1000); absorb(work, 'ID', 499, 500); } if (mode >= 3) { absorb(work, 'VM', 995, 1000); absorb(work, 'VD', 495, 500); } if (mode >= 2) { absorb(work, 'XM', 990, 1000); absorb(work, 'XD', 490, 500); } if (mode >= 1) { absorb(work, 'LM', 950, 1000); absorb(work, 'LD', 450, 500); } absorb(work, 'CM', 900, 1000); absorb(work, 'CD', 400, 500); absorb(work, 'D', 500, 900); work.acc += 'C'.repeat(Math.floor(work.val / 100)); work.val %= 100; if (mode >= 2) { absorb(work, 'IC', 99, 100); absorb(work, 'IL', 49, 50); } if (mode >= 1) { absorb(work, 'VC', 95, 100); absorb(work, 'VL', 45, 50); } absorb(work, 'XC', 90, 100); absorb(work, 'XL', 40, 50); absorb(work, 'L', 50, 90); work.acc += 'X'.repeat(Math.floor(work.val / 10)); work.val %= 10; absorb(work, 'IX', 9, 10); absorb(work, 'IV', 4, 5); absorb(work, 'V', 5, 9); work.acc += 'I'.repeat(work.val); return work.acc; } function absorb(valAcc, token, lower, upper) { if (valAcc.val >= lower && valAcc.val < upper) { valAcc.val -= lower; valAcc.acc += token; } } /***/ }), /* 189 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SimpleArithmerticPlugin: () => (/* binding */ SimpleArithmerticPlugin) /* harmony export */ }); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class SimpleArithmerticPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionPlugin { add(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.ADD'), this.arithmeticHelper.addWithEpsilon); } concat(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.CONCAT'), this.arithmeticHelper.concat); } divide(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.DIVIDE'), this.arithmeticHelper.divide); } eq(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.EQ'), this.arithmeticHelper.eq); } gt(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.GT'), this.arithmeticHelper.gt); } gte(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.GTE'), this.arithmeticHelper.geq); } lt(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.LT'), this.arithmeticHelper.lt); } lte(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.LTE'), this.arithmeticHelper.leq); } minus(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.MINUS'), this.arithmeticHelper.subtract); } multiply(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.MULTIPLY'), this.arithmeticHelper.multiply); } ne(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.NE'), this.arithmeticHelper.neq); } pow(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.POW'), this.arithmeticHelper.pow); } uminus(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.UMINUS'), this.arithmeticHelper.unaryMinus); } upercent(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.UNARY_PERCENT'), this.arithmeticHelper.unaryPercent); } uplus(ast, state) { return this.runFunction(ast.args, state, this.metadata('HF.UPLUS'), this.arithmeticHelper.unaryPlus); } } SimpleArithmerticPlugin.implementedFunctions = { 'HF.ADD': { method: 'add', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.CONCAT': { method: 'concat', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.STRING, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.STRING, passSubtype: true }] }, 'HF.DIVIDE': { method: 'divide', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.EQ': { method: 'eq', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.GT': { method: 'gt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.GTE': { method: 'gte', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.LT': { method: 'lt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.LTE': { method: 'lte', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.MINUS': { method: 'minus', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.MULTIPLY': { method: 'multiply', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.NE': { method: 'ne', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NOERROR, passSubtype: true }] }, 'HF.POW': { method: 'pow', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.UMINUS': { method: 'uminus', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.UNARY_PERCENT': { method: 'upercent', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] }, 'HF.UPLUS': { method: 'uplus', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_0__.FunctionArgumentType.NUMBER, passSubtype: true }] } }; /***/ }), /* 190 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ StatisticalPlugin: () => (/* binding */ StatisticalPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _3rdparty_bessel_bessel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(191); /* harmony import */ var _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(192); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class StatisticalPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionPlugin { erf(ast, state) { return this.runFunction(ast.args, state, this.metadata('ERF'), (lowerBound, upperBound) => { if (upperBound === undefined) { return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.erf)(lowerBound); } else { return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.erf)(upperBound) - (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.erf)(lowerBound); } }); } erfc(ast, state) { return this.runFunction(ast.args, state, this.metadata('ERFC'), _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.erfc); } expondist(ast, state) { return this.runFunction(ast.args, state, this.metadata('EXPON.DIST'), (x, lambda, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.exponential.cdf(x, lambda); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.exponential.pdf(x, lambda); } }); } fisher(ast, state) { return this.runFunction(ast.args, state, this.metadata('FISHER'), x => Math.log((1 + x) / (1 - x)) / 2); } fisherinv(ast, state) { return this.runFunction(ast.args, state, this.metadata('FISHERINV'), y => 1 - 2 / (Math.exp(2 * y) + 1)); } gamma(ast, state) { return this.runFunction(ast.args, state, this.metadata('GAMMA'), _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.gammafn); } gammadist(ast, state) { return this.runFunction(ast.args, state, this.metadata('GAMMA.DIST'), (value, alphaVal, betaVal, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.gamma.cdf(value, alphaVal, betaVal); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.gamma.pdf(value, alphaVal, betaVal); } }); } gammaln(ast, state) { return this.runFunction(ast.args, state, this.metadata('GAMMALN'), _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.gammaln); } gammainv(ast, state) { return this.runFunction(ast.args, state, this.metadata('GAMMA.INV'), _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.gamma.inv); } gauss(ast, state) { return this.runFunction(ast.args, state, this.metadata('GAUSS'), z => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.cdf(z, 0, 1) - 0.5); } betadist(ast, state) { return this.runFunction(ast.args, state, this.metadata('BETA.DIST'), (x, alphaVal, betaVal, cumulative, A, B) => { if (x <= A) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } else if (x >= B) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } x = (x - A) / (B - A); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.beta.cdf(x, alphaVal, betaVal); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.beta.pdf(x, alphaVal, betaVal); } }); } betainv(ast, state) { return this.runFunction(ast.args, state, this.metadata('BETA.INV'), (x, alphaVal, betaVal, A, B) => { if (A >= B) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.WrongOrder); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.beta.inv(x, alphaVal, betaVal) * (B - A) + A; } }); } binomialdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('BINOM.DIST'), (succ, trials, prob, cumulative) => { if (succ > trials) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.WrongOrder); } succ = Math.trunc(succ); trials = Math.trunc(trials); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.binomial.cdf(succ, trials, prob); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.binomial.pdf(succ, trials, prob); } }); } binomialinv(ast, state) { return this.runFunction(ast.args, state, this.metadata('BINOM.INV'), (trials, prob, alpha) => { trials = Math.trunc(trials); let lower = -1; let upper = trials; while (upper > lower + 1) { const mid = Math.trunc((lower + upper) / 2); if (_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.binomial.cdf(mid, trials, prob) >= alpha) { upper = mid; } else { lower = mid; } } return upper; }); } besselifn(ast, state) { return this.runFunction(ast.args, state, this.metadata('BESSELI'), (x, n) => (0,_3rdparty_bessel_bessel__WEBPACK_IMPORTED_MODULE_2__.besseli)(x, Math.trunc(n))); } besseljfn(ast, state) { return this.runFunction(ast.args, state, this.metadata('BESSELJ'), (x, n) => (0,_3rdparty_bessel_bessel__WEBPACK_IMPORTED_MODULE_2__.besselj)(x, Math.trunc(n))); } besselkfn(ast, state) { return this.runFunction(ast.args, state, this.metadata('BESSELK'), (x, n) => (0,_3rdparty_bessel_bessel__WEBPACK_IMPORTED_MODULE_2__.besselk)(x, Math.trunc(n))); } besselyfn(ast, state) { return this.runFunction(ast.args, state, this.metadata('BESSELY'), (x, n) => (0,_3rdparty_bessel_bessel__WEBPACK_IMPORTED_MODULE_2__.bessely)(x, Math.trunc(n))); } chisqdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.DIST'), (x, deg, cumulative) => { deg = Math.trunc(deg); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.cdf(x, deg); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.pdf(x, deg); } }); } chisqdistrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.DIST.RT'), (x, deg) => 1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.cdf(x, Math.trunc(deg))); } chisqinv(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.INV'), (p, deg) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.inv(p, Math.trunc(deg))); } chisqinvrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.INV.RT'), (p, deg) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.inv(1.0 - p, Math.trunc(deg))); } fdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('F.DIST'), (x, deg1, deg2, cumulative) => { deg1 = Math.trunc(deg1); deg2 = Math.trunc(deg2); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.cdf(x, deg1, deg2); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.pdf(x, deg1, deg2); } }); } fdistrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('F.DIST.RT'), (x, deg1, deg2) => 1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.cdf(x, Math.trunc(deg1), Math.trunc(deg2))); } finv(ast, state) { return this.runFunction(ast.args, state, this.metadata('F.INV'), (p, deg1, deg2) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.inv(p, Math.trunc(deg1), Math.trunc(deg2))); } finvrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('F.INV.RT'), (p, deg1, deg2) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.inv(1.0 - p, Math.trunc(deg1), Math.trunc(deg2))); } weibulldist(ast, state) { return this.runFunction(ast.args, state, this.metadata('WEIBULL.DIST'), (x, shape, scale, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.weibull.cdf(x, scale, shape); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.weibull.pdf(x, scale, shape); } }); } poissondist(ast, state) { return this.runFunction(ast.args, state, this.metadata('POISSON.DIST'), (x, mean, cumulative) => { x = Math.trunc(x); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.poisson.cdf(x, mean); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.poisson.pdf(x, mean); } }); } hypgeomdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('HYPGEOM.DIST'), (s, numberS, populationS, numberPop, cumulative) => { if (s > numberS || s > populationS || numberS > numberPop || populationS > numberPop) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } if (s + numberPop < populationS + numberS) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } s = Math.trunc(s); numberS = Math.trunc(numberS); populationS = Math.trunc(populationS); numberPop = Math.trunc(numberPop); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.hypgeom.cdf(s, numberPop, populationS, numberS); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.hypgeom.pdf(s, numberPop, populationS, numberS); } }); } tdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.DIST'), (x, deg, cumulative) => { deg = Math.trunc(deg); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(x, deg); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.pdf(x, deg); } }); } tdist2t(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.DIST.2T'), (x, deg) => (1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(x, Math.trunc(deg))) * 2); } tdistrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.DIST.RT'), (x, deg) => 1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(x, Math.trunc(deg))); } tdistold(ast, state) { return this.runFunction(ast.args, state, this.metadata('TDIST'), (x, deg, mode) => mode * (1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(x, Math.trunc(deg)))); } tinv(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.INV'), (p, deg) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.inv(p, Math.trunc(deg))); } tinv2t(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.INV.2T'), (p, deg) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.inv(1 - p / 2, Math.trunc(deg))); } lognormdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('LOGNORM.DIST'), (x, mean, stddev, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.lognormal.cdf(x, mean, stddev); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.lognormal.pdf(x, mean, stddev); } }); } lognorminv(ast, state) { return this.runFunction(ast.args, state, this.metadata('LOGNORM.INV'), (p, mean, stddev) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.lognormal.inv(p, mean, stddev)); } normdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('NORM.DIST'), (x, mean, stddev, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.cdf(x, mean, stddev); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.pdf(x, mean, stddev); } }); } norminv(ast, state) { return this.runFunction(ast.args, state, this.metadata('NORM.INV'), (p, mean, stddev) => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.inv(p, mean, stddev)); } normsdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('NORM.S.DIST'), (x, cumulative) => { if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.cdf(x, 0, 1); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.pdf(x, 0, 1); } }); } normsinv(ast, state) { return this.runFunction(ast.args, state, this.metadata('NORM.S.INV'), p => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.inv(p, 0, 1)); } phi(ast, state) { return this.runFunction(ast.args, state, this.metadata('PHI'), x => _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.pdf(x, 0, 1)); } negbinomdist(ast, state) { return this.runFunction(ast.args, state, this.metadata('NEGBINOM.DIST'), (nf, ns, p, cumulative) => { nf = Math.trunc(nf); ns = Math.trunc(ns); if (cumulative) { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.negbin.cdf(nf, ns, p); } else { return _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.negbin.pdf(nf, ns, p); } }); } confidencenorm(ast, state) { return this.runFunction(ast.args, state, this.metadata('CONFIDENCE.NORM'), // eslint-disable-next-line // @ts-ignore (alpha, stddev, size) => (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normalci)(1, alpha, stddev, Math.trunc(size))[1] - 1); } confidencet(ast, state) { return this.runFunction(ast.args, state, this.metadata('CONFIDENCE.T'), (alpha, stddev, size) => { size = Math.trunc(size); if (size === 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } // eslint-disable-next-line // @ts-ignore return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.tci)(1, alpha, stddev, size)[1] - 1; }); } standardize(ast, state) { return this.runFunction(ast.args, state, this.metadata('STANDARDIZE'), (x, mean, stddev) => (x - mean) / stddev); } } StatisticalPlugin.implementedFunctions = { 'ERF': { method: 'erf', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, optionalArg: true }] }, 'ERFC': { method: 'erfc', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }] }, 'EXPON.DIST': { method: 'expondist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'FISHER': { method: 'fisher', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: -1, lessThan: 1 }] }, 'FISHERINV': { method: 'fisherinv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }] }, 'GAMMA': { method: 'gamma', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }] }, 'GAMMA.DIST': { method: 'gammadist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'GAMMALN': { method: 'gammaln', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }] }, 'GAMMA.INV': { method: 'gammainv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }] }, 'GAUSS': { method: 'gauss', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }] }, 'BETA.DIST': { method: 'betadist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'BETA.INV': { method: 'betainv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, defaultValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, defaultValue: 1 }] }, 'BINOM.DIST': { method: 'binomialdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'BINOM.INV': { method: 'binomialinv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }] }, 'BESSELI': { method: 'besselifn', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'BESSELJ': { method: 'besseljfn', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'BESSELK': { method: 'besselkfn', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'BESSELY': { method: 'besselyfn', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'CHISQ.DIST': { method: 'chisqdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1, maxValue: 1e10 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'CHISQ.DIST.RT': { method: 'chisqdistrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1, maxValue: 1e10 }] }, 'CHISQ.INV': { method: 'chisqinv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1, maxValue: 1e10 }] }, 'CHISQ.INV.RT': { method: 'chisqinvrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'F.DIST': { method: 'fdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'F.DIST.RT': { method: 'fdistrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'F.INV': { method: 'finv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'F.INV.RT': { method: 'finvrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'WEIBULL.DIST': { method: 'weibulldist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'POISSON.DIST': { method: 'poissondist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'HYPGEOM.DIST': { method: 'hypgeomdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'T.DIST': { method: 'tdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'T.DIST.2T': { method: 'tdist2t', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'T.DIST.RT': { method: 'tdistrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'TDIST': { method: 'tdistold', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.INTEGER, minValue: 1, maxValue: 2 }] }, 'T.INV': { method: 'tinv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'T.INV.2T': { method: 'tinv2t', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'LOGNORM.DIST': { method: 'lognormdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'LOGNORM.INV': { method: 'lognorminv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }] }, 'NORM.DIST': { method: 'normdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'NORM.INV': { method: 'norminv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }] }, 'NORM.S.DIST': { method: 'normsdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'NORM.S.INV': { method: 'normsinv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }] }, 'PHI': { method: 'phi', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }] }, 'NEGBINOM.DIST': { method: 'negbinomdist', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.BOOLEAN }] }, 'CONFIDENCE.NORM': { method: 'confidencenorm', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'CONFIDENCE.T': { method: 'confidencet', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0, lessThan: 1 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, minValue: 1 }] }, 'STANDARDIZE': { method: 'standardize', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, greaterThan: 0 }] } }; StatisticalPlugin.aliases = { NEGBINOMDIST: 'NEGBINOM.DIST', EXPONDIST: 'EXPON.DIST', BETADIST: 'BETA.DIST', NORMDIST: 'NORM.DIST', NORMINV: 'NORM.INV', NORMSDIST: 'NORM.S.DIST', NORMSINV: 'NORM.S.INV', LOGNORMDIST: 'LOGNORM.DIST', LOGINV: 'LOGNORM.INV', TINV: 'T.INV.2T', HYPGEOMDIST: 'HYPGEOM.DIST', POISSON: 'POISSON.DIST', WEIBULL: 'WEIBULL.DIST', FINV: 'F.INV.RT', FDIST: 'F.DIST.RT', CHIDIST: 'CHISQ.DIST.RT', CHIINV: 'CHISQ.INV.RT', GAMMADIST: 'GAMMA.DIST', 'GAMMALN.PRECISE': 'GAMMALN', GAMMAINV: 'GAMMA.INV', BETAINV: 'BETA.INV', BINOMDIST: 'BINOM.DIST', CONFIDENCE: 'CONFIDENCE.NORM', CRITBINOM: 'BINOM.INV', WEIBULLDIST: 'WEIBULL.DIST', TINV2T: 'T.INV.2T', TDISTRT: 'T.DIST.RT', TDIST2T: 'T.DIST.2T', FINVRT: 'F.INV.RT', FDISTRT: 'F.DIST.RT', CHIDISTRT: 'CHISQ.DIST.RT', CHIINVRT: 'CHISQ.INV.RT', LOGNORMINV: 'LOGNORM.INV', POISSONDIST: 'POISSON.DIST' }; /***/ }), /* 191 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ besseli: () => (/* binding */ besseli), /* harmony export */ besselj: () => (/* binding */ besselj), /* harmony export */ besselk: () => (/* binding */ besselk), /* harmony export */ bessely: () => (/* binding */ bessely) /* harmony export */ }); /** * @license bessel.js (C) 2013-present SheetJS -- http://sheetjs.com Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright (C) 2013-present SheetJS LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var M = Math; // @ts-ignore function _horner(arr, v) { for (var i = 0, z = 0; i < arr.length; ++i) { z = v * z + arr[i]; } return z; } // @ts-ignore function _bessel_iter(x, n, f0, f1, sign) { if (n === 0) { return f0; } if (n === 1) { return f1; } var tdx = 2 / x, f2 = f1; for (var o = 1; o < n; ++o) { f2 = f1 * o * tdx + sign * f0; f0 = f1; f1 = f2; } return f2; } // @ts-ignore function _bessel_wrap(bessel0, bessel1, name, nonzero, sign) { // @ts-ignore return function bessel(x, n) { if (nonzero) { if (x === 0) { return nonzero == 1 ? -Infinity : Infinity; } else if (x < 0) { return NaN; } } if (n === 0) { return bessel0(x); } if (n === 1) { return bessel1(x); } if (n < 0) { return NaN; } n |= 0; var b0 = bessel0(x), b1 = bessel1(x); return _bessel_iter(x, n, b0, b1, sign); }; } var besselj = function () { var W = 0.636619772; // 2 / Math.PI var b0_a1a = [57568490574.0, -13362590354.0, 651619640.7, -11214424.18, 77392.33017, -184.9052456].reverse(); var b0_a2a = [57568490411.0, 1029532985.0, 9494680.718, 59272.64853, 267.8532712, 1.0].reverse(); var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934935152e-7].reverse(); // @ts-ignore function bessel0(x) { var a = 0, a1 = 0, a2 = 0, y = x * x; if (x < 8) { a1 = _horner(b0_a1a, y); a2 = _horner(b0_a2a, y); a = a1 / a2; } else { var xx = x - 0.785398164; y = 64 / y; a1 = _horner(b0_a1b, y); a2 = _horner(b0_a2b, y); a = M.sqrt(W / x) * (M.cos(xx) * a1 - M.sin(xx) * a2 * 8 / x); } return a; } var b1_a1a = [72362614232.0, -7895059235.0, 242396853.1, -2972611.439, 15704.48260, -30.16036606].reverse(); var b1_a2a = [144725228442.0, 2300535178.0, 18583304.74, 99447.43394, 376.9991397, 1.0].reverse(); var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); // @ts-ignore function bessel1(x) { var a = 0, a1 = 0, a2 = 0, y = x * x, xx = M.abs(x) - 2.356194491; if (Math.abs(x) < 8) { a1 = x * _horner(b1_a1a, y); a2 = _horner(b1_a2a, y); a = a1 / a2; } else { y = 64 / y; a1 = _horner(b1_a1b, y); a2 = _horner(b1_a2b, y); a = M.sqrt(W / M.abs(x)) * (M.cos(xx) * a1 - M.sin(xx) * a2 * 8 / M.abs(x)); if (x < 0) { a = -a; } } return a; } // @ts-ignore return function besselj(x, n) { n = Math.round(n); if (!isFinite(x)) { return isNaN(x) ? x : 0; } if (n < 0) { return (n % 2 ? -1 : 1) * besselj(x, -n); } if (x < 0) { return (n % 2 ? -1 : 1) * besselj(-x, n); } if (n === 0) { return bessel0(x); } if (n === 1) { return bessel1(x); } if (x === 0) { return 0; } var ret = 0.0; if (x > n) { ret = _bessel_iter(x, n, bessel0(x), bessel1(x), -1); } else { var m = 2 * M.floor((n + M.floor(M.sqrt(40 * n))) / 2); var jsum = false; var bjp = 0.0, sum = 0.0; var bj = 1.0, bjm = 0.0; var tox = 2 / x; for (var j = m; j > 0; j--) { bjm = j * tox * bj - bjp; bjp = bj; bj = bjm; if (M.abs(bj) > 1E10) { bj *= 1E-10; bjp *= 1E-10; ret *= 1E-10; sum *= 1E-10; } if (jsum) { sum += bj; } jsum = !jsum; if (j == n) { ret = bjp; } } sum = 2.0 * sum - bj; ret /= sum; } return ret; }; }(); var bessely = function () { var W = 0.636619772; var b0_a1a = [-2957821389.0, 7062834065.0, -512359803.6, 10879881.29, -86327.92757, 228.4622733].reverse(); var b0_a2a = [40076544269.0, 745249964.8, 7189466.438, 47447.26470, 226.1030244, 1.0].reverse(); var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934945152e-7].reverse(); // @ts-ignore function bessel0(x) { var a = 0, a1 = 0, a2 = 0, y = x * x, xx = x - 0.785398164; if (x < 8) { a1 = _horner(b0_a1a, y); a2 = _horner(b0_a2a, y); a = a1 / a2 + W * besselj(x, 0) * M.log(x); } else { y = 64 / y; a1 = _horner(b0_a1b, y); a2 = _horner(b0_a2b, y); a = M.sqrt(W / x) * (M.sin(xx) * a1 + M.cos(xx) * a2 * 8 / x); } return a; } var b1_a1a = [-0.4900604943e13, 0.1275274390e13, -0.5153438139e11, 0.7349264551e9, -0.4237922726e7, 0.8511937935e4].reverse(); var b1_a2a = [0.2499580570e14, 0.4244419664e12, 0.3733650367e10, 0.2245904002e8, 0.1020426050e6, 0.3549632885e3, 1].reverse(); var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); // @ts-ignore function bessel1(x) { var a = 0, a1 = 0, a2 = 0, y = x * x, xx = x - 2.356194491; if (x < 8) { a1 = x * _horner(b1_a1a, y); a2 = _horner(b1_a2a, y); a = a1 / a2 + W * (besselj(x, 1) * M.log(x) - 1 / x); } else { y = 64 / y; a1 = _horner(b1_a1b, y); a2 = _horner(b1_a2b, y); a = M.sqrt(W / x) * (M.sin(xx) * a1 + M.cos(xx) * a2 * 8 / x); } return a; } return _bessel_wrap(bessel0, bessel1, 'BESSELY', 1, -1); }(); var besseli = function () { var b0_a = [1.0, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.360768e-1, 0.45813e-2].reverse(); var b0_b = [0.39894228, 0.1328592e-1, 0.225319e-2, -0.157565e-2, 0.916281e-2, -0.2057706e-1, 0.2635537e-1, -0.1647633e-1, 0.392377e-2].reverse(); // @ts-ignore function bessel0(x) { if (x <= 3.75) { return _horner(b0_a, x * x / (3.75 * 3.75)); } return M.exp(M.abs(x)) / M.sqrt(M.abs(x)) * _horner(b0_b, 3.75 / M.abs(x)); } var b1_a = [0.5, 0.87890594, 0.51498869, 0.15084934, 0.2658733e-1, 0.301532e-2, 0.32411e-3].reverse(); var b1_b = [0.39894228, -0.3988024e-1, -0.362018e-2, 0.163801e-2, -0.1031555e-1, 0.2282967e-1, -0.2895312e-1, 0.1787654e-1, -0.420059e-2].reverse(); // @ts-ignore function bessel1(x) { if (x < 3.75) { return x * _horner(b1_a, x * x / (3.75 * 3.75)); } return (x < 0 ? -1 : 1) * M.exp(M.abs(x)) / M.sqrt(M.abs(x)) * _horner(b1_b, 3.75 / M.abs(x)); } // @ts-ignore return function besseli(x, n) { n = Math.round(n); if (n === 0) { return bessel0(x); } if (n === 1) { return bessel1(x); } if (n < 0) { return NaN; } if (M.abs(x) === 0) { return 0; } if (x == Infinity) { return Infinity; } var ret = 0.0, j, tox = 2 / M.abs(x), bip = 0.0, bi = 1.0, bim = 0.0; var m = 2 * M.round((n + M.round(M.sqrt(40 * n))) / 2); for (j = m; j > 0; j--) { bim = j * tox * bi + bip; bip = bi; bi = bim; if (M.abs(bi) > 1E10) { bi *= 1E-10; bip *= 1E-10; ret *= 1E-10; } if (j == n) { ret = bip; } } ret *= besseli(x, 0) / bi; return x < 0 && n % 2 ? -ret : ret; }; }(); var besselk = function () { var b0_a = [-0.57721566, 0.42278420, 0.23069756, 0.3488590e-1, 0.262698e-2, 0.10750e-3, 0.74e-5].reverse(); var b0_b = [1.25331414, -0.7832358e-1, 0.2189568e-1, -0.1062446e-1, 0.587872e-2, -0.251540e-2, 0.53208e-3].reverse(); // @ts-ignore function bessel0(x) { if (x <= 2) { return -M.log(x / 2) * besseli(x, 0) + _horner(b0_a, x * x / 4); } return M.exp(-x) / M.sqrt(x) * _horner(b0_b, 2 / x); } var b1_a = [1.0, 0.15443144, -0.67278579, -0.18156897, -0.1919402e-1, -0.110404e-2, -0.4686e-4].reverse(); var b1_b = [1.25331414, 0.23498619, -0.3655620e-1, 0.1504268e-1, -0.780353e-2, 0.325614e-2, -0.68245e-3].reverse(); // @ts-ignore function bessel1(x) { if (x <= 2) { return M.log(x / 2) * besseli(x, 1) + 1 / x * _horner(b1_a, x * x / 4); } return M.exp(-x) / M.sqrt(x) * _horner(b1_b, 2 / x); } return _bessel_wrap(bessel0, bessel1, 'BESSELK', 2, 1); }(); /***/ }), /* 192 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ beta: () => (/* binding */ beta), /* harmony export */ binomial: () => (/* binding */ binomial), /* harmony export */ centralF: () => (/* binding */ centralF), /* harmony export */ chisquare: () => (/* binding */ chisquare), /* harmony export */ corrcoeff: () => (/* binding */ corrcoeff), /* harmony export */ covariance: () => (/* binding */ covariance), /* harmony export */ erf: () => (/* binding */ erf), /* harmony export */ erfc: () => (/* binding */ erfc), /* harmony export */ exponential: () => (/* binding */ exponential), /* harmony export */ factorial: () => (/* binding */ factorial), /* harmony export */ factorialln: () => (/* binding */ factorialln), /* harmony export */ gamma: () => (/* binding */ gamma), /* harmony export */ gammafn: () => (/* binding */ gammafn), /* harmony export */ gammaln: () => (/* binding */ gammaln), /* harmony export */ geomean: () => (/* binding */ geomean), /* harmony export */ hypgeom: () => (/* binding */ hypgeom), /* harmony export */ lognormal: () => (/* binding */ lognormal), /* harmony export */ mean: () => (/* binding */ mean), /* harmony export */ negbin: () => (/* binding */ negbin), /* harmony export */ normal: () => (/* binding */ normal), /* harmony export */ normalci: () => (/* binding */ normalci), /* harmony export */ poisson: () => (/* binding */ poisson), /* harmony export */ stdev: () => (/* binding */ stdev), /* harmony export */ studentt: () => (/* binding */ studentt), /* harmony export */ sumsqerr: () => (/* binding */ sumsqerr), /* harmony export */ tci: () => (/* binding */ tci), /* harmony export */ variance: () => (/* binding */ variance), /* harmony export */ weibull: () => (/* binding */ weibull) /* harmony export */ }); /** * @license Copyright (c) 2013 jStat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function erf(x) { const cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2, -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4, 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6, 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8, 6.529054439e-9, 5.059343495e-9, -9.91364156e-10, -2.27365122e-10, 9.6467911e-11, 2.394038e-12, -6.886027e-12, 8.94487e-13, 3.13092e-13, -1.12708e-13, 3.81e-16, 7.106e-15, -1.523e-15, -9.4e-17, 1.21e-16, -2.8e-17]; let j = cof.length - 1; let isneg = false; let d = 0; let dd = 0; let t, ty, tmp, res; if (x === 0) { return 0; } if (x < 0) { x = -x; isneg = true; } t = 2 / (2 + x); ty = 4 * t - 2; for (; j > 0; j--) { tmp = d; d = ty * d - dd + cof[j]; dd = tmp; } res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd); return isneg ? res - 1 : 1 - res; } function erfc(x) { return 1 - erf(x); } function erfcinv(p) { let j = 0; let x, err, t, pp; if (p >= 2) { return -100; } if (p <= 0) { return 100; } pp = p < 1 ? p : 2 - p; t = Math.sqrt(-2 * Math.log(pp / 2)); x = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t); for (; j < 2; j++) { err = erfc(x) - pp; x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err); } return p < 1 ? x : -x; } const exponential = { pdf: (x, rate) => { return x < 0 ? 0 : rate * Math.exp(-rate * x); }, cdf: (x, rate) => { return x < 0 ? 0 : 1 - Math.exp(-rate * x); } }; function gammafn(x) { const p = [-1.716185138865495, 24.76565080557592, -379.80425647094563, 629.3311553128184, 866.9662027904133, -31451.272968848367, -36144.413418691176, 66456.14382024054]; const q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192, -3107.771671572311, 22538.118420980151, 4755.8462775278811, -134659.9598649693, -115132.2596755535]; let fact = false; let n = 0; let xden = 0; let xnum = 0; let y = x; let i, z, yi, res; if (x > 171.6243769536076) { return Infinity; } if (y <= 0) { res = y % 1; if (res) { fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res); y = 1 - y; } else { return Infinity; } } yi = y; if (y < 1) { z = y++; } else { z = (y -= n = (y | 0) - 1) - 1; } for (i = 0; i < 8; ++i) { xnum = (xnum + p[i]) * z; xden = xden * z + q[i]; } res = xnum / xden + 1; if (yi < y) { res /= yi; } else if (yi > y) { for (i = 0; i < n; ++i) { res *= y; y++; } } if (fact) { res = fact / res; } return res; } const gamma = { pdf: function pdf(x, shape, scale) { if (x < 0) { return 0; } return x === 0 && shape === 1 ? 1 / scale : Math.exp((shape - 1) * Math.log(x) - x / scale - gammaln(shape) - shape * Math.log(scale)); }, cdf: function cdf(x, shape, scale) { if (x < 0) { return 0; } return lowRegGamma(shape, x / scale); }, inv: function (p, shape, scale) { return gammapinv(p, shape) * scale; } }; function gammaln(x) { let j = 0; const cof = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5]; let ser = 1.000000000190015; let xx, y, tmp; tmp = (y = xx = x) + 5.5; tmp -= (xx + 0.5) * Math.log(tmp); for (; j < 6; j++) { ser += cof[j] / ++y; } return Math.log(2.5066282746310005 * ser / xx) - tmp; } function lowRegGamma(a, x) { const aln = gammaln(a); let ap = a; let sum = 1 / a; let del = sum; let b = x + 1 - a; let c = 1 / 1.0e-30; let d = 1 / b; let h = d; let i = 1; // calculate maximum number of itterations required for a const ITMAX = -~(Math.log(a >= 1 ? a : 1 / a) * 8.5 + a * 0.4 + 17); let an; if (x < 0 || a <= 0) { return NaN; } else if (x < a + 1) { for (; i <= ITMAX; i++) { sum += del *= x / ++ap; } return sum * Math.exp(-x + a * Math.log(x) - aln); } for (; i <= ITMAX; i++) { an = -i * (i - a); b += 2; d = an * d + b; c = b + an / c; d = 1 / d; h *= d * c; } return 1 - h * Math.exp(-x + a * Math.log(x) - aln); } function gammapinv(p, a) { let j = 0; const a1 = a - 1; const EPS = 1e-8; const gln = gammaln(a); let x, err, t, u, pp; let lna1; let afac; if (p >= 1) { return Math.max(100, a + 100 * Math.sqrt(a)); } if (p <= 0) { return 0; } if (a > 1) { lna1 = Math.log(a1); afac = Math.exp(a1 * (lna1 - 1) - gln); pp = p < 0.5 ? p : 1 - p; t = Math.sqrt(-2 * Math.log(pp)); x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t; if (p < 0.5) { x = -x; } x = Math.max(1e-3, a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3)); } else { t = 1 - a * (0.253 + a * 0.12); if (p < t) { x = Math.pow(p / t, 1 / a); } else { x = 1 - Math.log(1 - (p - t) / (1 - t)); } } for (; j < 12; j++) { if (x <= 0) { return 0; } err = lowRegGamma(a, x) - p; if (a > 1) { t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1)); } else { t = Math.exp(-x + a1 * Math.log(x) - gln); } u = err / t; x -= t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1))); if (x <= 0) { x = 0.5 * (x + t); } if (Math.abs(t) < EPS * x) { break; } } return x; } const normal = { pdf: function pdf(x, mean, std) { return Math.exp(-0.5 * Math.log(2 * Math.PI) - Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std)); }, cdf: function cdf(x, mean, std) { return 0.5 * (1 + erf((x - mean) / Math.sqrt(2 * std * std))); }, inv: function (p, mean, std) { return -1.41421356237309505 * std * erfcinv(2 * p) + mean; } }; const beta = { pdf: function pdf(x, alpha, beta) { // PDF is zero outside the support if (x > 1 || x < 0) { return 0; } // PDF is one for the uniform case if (alpha == 1 && beta == 1) { return 1; } if (alpha < 512 && beta < 512) { return Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1) / betafn(alpha, beta); } else { return Math.exp((alpha - 1) * Math.log(x) + (beta - 1) * Math.log(1 - x) - betaln(alpha, beta)); } }, cdf: function cdf(x, alpha, beta) { return x > 1 || x < 0 ? +(x > 1) : ibeta(x, alpha, beta); }, inv: function inv(x, alpha, beta) { return ibetainv(x, alpha, beta); } }; function betafn(x, y) { // ensure arguments are positive if (x <= 0 || y <= 0) { return undefined; } // make sure x + y doesn't exceed the upper limit of usable values return x + y > 170 ? Math.exp(betaln(x, y)) : gammafn(x) * gammafn(y) / gammafn(x + y); } function betaln(x, y) { return gammaln(x) + gammaln(y) - gammaln(x + y); } function ibetainv(p, a, b) { var EPS = 1e-8; var a1 = a - 1; var b1 = b - 1; var j = 0; var lna, lnb, pp, t, u, err, x, al, h, w, afac; if (p <= 0) { return 0; } if (p >= 1) { return 1; } if (a >= 1 && b >= 1) { pp = p < 0.5 ? p : 1 - p; t = Math.sqrt(-2 * Math.log(pp)); x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t; if (p < 0.5) { x = -x; } al = (x * x - 3) / 6; h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1)); w = x * Math.sqrt(al + h) / h - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h)); x = a / (a + b * Math.exp(2 * w)); } else { lna = Math.log(a / (a + b)); lnb = Math.log(b / (a + b)); t = Math.exp(a * lna) / a; u = Math.exp(b * lnb) / b; w = t + u; if (p < t / w) { x = Math.pow(a * w * p, 1 / a); } else { x = 1 - Math.pow(b * w * (1 - p), 1 / b); } } afac = -gammaln(a) - gammaln(b) + gammaln(a + b); for (; j < 10; j++) { if (x === 0 || x === 1) { return x; } // @ts-ignore err = ibeta(x, a, b) - p; t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac); u = err / t; x -= t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))); if (x <= 0) { x = 0.5 * (x + t); } if (x >= 1) { x = 0.5 * (x + t + 1); } if (Math.abs(t) < EPS * x && j > 0) { break; } } return x; } function ibeta(x, a, b) { // Factors in front of the continued fraction. var bt = x === 0 || x === 1 ? 0 : Math.exp(gammaln(a + b) - gammaln(a) - gammaln(b) + a * Math.log(x) + b * Math.log(1 - x)); if (x < 0 || x > 1) { return false; } if (x < (a + 1) / (a + b + 2)) // Use continued fraction directly. { return bt * betacf(x, a, b) / a; } // else use continued fraction after making the symmetry transformation. return 1 - bt * betacf(1 - x, b, a) / b; } function betacf(x, a, b) { var fpmin = 1e-30; var m = 1; var qab = a + b; var qap = a + 1; var qam = a - 1; var c = 1; var d = 1 - qab * x / qap; var m2, aa, del, h; // These q's will be used in factors that occur in the coefficients if (Math.abs(d) < fpmin) { d = fpmin; } d = 1 / d; h = d; for (; m <= 100; m++) { m2 = 2 * m; aa = m * (b - m) * x / ((qam + m2) * (a + m2)); // One step (the even one) of the recurrence d = 1 + aa * d; if (Math.abs(d) < fpmin) { d = fpmin; } c = 1 + aa / c; if (Math.abs(c) < fpmin) { c = fpmin; } d = 1 / d; h *= d * c; aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); // Next step of the recurrence (the odd one) d = 1 + aa * d; if (Math.abs(d) < fpmin) { d = fpmin; } c = 1 + aa / c; if (Math.abs(c) < fpmin) { c = fpmin; } d = 1 / d; del = d * c; h *= del; if (Math.abs(del - 1.0) < 3e-7) { break; } } return h; } const binomial = { pdf: function (k, n, p) { return p === 0 || p === 1 ? n * p === k ? 1 : 0 : combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k); }, cdf: function (x, n, p) { var betacdf; var eps = 1e-10; if (x < 0) { return 0; } if (x >= n) { return 1; } if (p < 0 || p > 1 || n <= 0) { return NaN; } x = Math.floor(x); var z = p; var a = x + 1; var b = n - x; var s = a + b; var bt = Math.exp(gammaln(s) - gammaln(b) - gammaln(a) + a * Math.log(z) + b * Math.log(1 - z)); if (z < (a + 1) / (s + 2)) { betacdf = bt * betinc(z, a, b, eps); } else { betacdf = 1 - bt * betinc(1 - z, b, a, eps); } return Math.round((1 - betacdf) * (1 / eps)) / (1 / eps); } }; function betinc(x, a, b, eps) { var a0 = 0; var b0 = 1; var a1 = 1; var b1 = 1; var m9 = 0; var a2 = 0; var c9; while (Math.abs((a1 - a2) / a1) > eps) { a2 = a1; c9 = -(a + m9) * (a + b + m9) * x / (a + 2 * m9) / (a + 2 * m9 + 1); a0 = a1 + c9 * a0; b0 = b1 + c9 * b0; m9 = m9 + 1; c9 = m9 * (b - m9) * x / (a + 2 * m9 - 1) / (a + 2 * m9); a1 = a0 + c9 * a1; b1 = b0 + c9 * b1; a0 = a0 / b1; b0 = b0 / b1; a1 = a1 / b1; b1 = 1; } return a1 / a; } function combination(n, m) { // make sure n or m don't exceed the upper limit of usable values return n > 170 || m > 170 ? Math.exp(combinationln(n, m)) : factorial(n) / factorial(m) / factorial(n - m); } function combinationln(n, m) { return factorialln(n) - factorialln(m) - factorialln(n - m); } // natural log factorial of n function factorialln(n) { return n < 0 ? NaN : gammaln(n + 1); } // factorial of n function factorial(n) { return n < 0 ? NaN : gammafn(n + 1); } const chisquare = { pdf: function pdf(x, dof) { if (x < 0) { return 0; } return x === 0 && dof === 2 ? 0.5 : Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - dof / 2 * Math.log(2) - gammaln(dof / 2)); }, cdf: function cdf(x, dof) { if (x < 0) { return 0; } return lowRegGamma(dof / 2, x / 2); }, inv: function (p, dof) { return 2 * gammapinv(p, 0.5 * dof); } }; const centralF = { // This implementation of the pdf function avoids float overflow // See the way that R calculates this value: // https://svn.r-project.org/R/trunk/src/nmath/df.c pdf: function pdf(x, df1, df2) { var p, q, f; if (x < 0) { return 0; } if (df1 <= 2) { if (x === 0 && df1 < 2) { return Infinity; } if (x === 0 && df1 === 2) { return 1; } return 1 / betafn(df1 / 2, df2 / 2) * Math.pow(df1 / df2, df1 / 2) * Math.pow(x, df1 / 2 - 1) * Math.pow(1 + df1 / df2 * x, -(df1 + df2) / 2); } p = df1 * x / (df2 + x * df1); q = df2 / (df2 + x * df1); f = df1 * q / 2.0; return f * binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p); }, cdf: function cdf(x, df1, df2) { if (x < 0) { return 0; } return ibeta(df1 * x / (df1 * x + df2), df1 / 2, df2 / 2); }, inv: function inv(x, df1, df2) { return df2 / (df1 * (1 / ibetainv(x, df1 / 2, df2 / 2) - 1)); } }; const weibull = { pdf: function pdf(x, scale, shape) { if (x < 0 || scale < 0 || shape < 0) { return 0; } return shape / scale * Math.pow(x / scale, shape - 1) * Math.exp(-Math.pow(x / scale, shape)); }, cdf: function cdf(x, scale, shape) { return x < 0 ? 0 : 1 - Math.exp(-Math.pow(x / scale, shape)); } }; const poisson = { pdf: function pdf(k, l) { if (l < 0 || k % 1 !== 0 || k < 0) { return 0; } return Math.pow(l, k) * Math.exp(-l) / factorial(k); }, cdf: function cdf(x, l) { var k = 0; if (x < 0) { return 0; } var sum = 0; for (; k <= x; k++) { sum += poisson.pdf(k, l); } return sum; } }; const hypgeom = { pdf: function pdf(k, N, m, n) { // Hypergeometric PDF. // A simplification of the CDF algorithm below. // k = number of successes drawn // N = population size // m = number of successes in population // n = number of items drawn from population // if(k !== k | 0) { // return false; // } else if (k < 0 || k < m - (N - n)) { // It's impossible to have this few successes drawn. return 0; } else if (k > n || k > m) { // It's impossible to have this many successes drawn. return 0; } else if (m * 2 > N) { // More than half the population is successes. if (n * 2 > N) { // More than half the population is sampled. return hypgeom.pdf(N - m - n + k, N, N - m, N - n); } else { // Half or less of the population is sampled. return hypgeom.pdf(n - k, N, N - m, n); } } else if (n * 2 > N) { // Half or less is successes. return hypgeom.pdf(m - k, N, m, N - n); } else if (m < n) { // We want to have the number of things sampled to be less than the // successes available. So swap the definitions of successful and sampled. return hypgeom.pdf(k, N, n, m); } else { // If we get here, half or less of the population was sampled, half or // less of it was successes, and we had fewer sampled things than // successes. Now we can do this complicated iterative algorithm in an // efficient way. // The basic premise of the algorithm is that we partially normalize our // intermediate product to keep it in a numerically good region, and then // finish the normalization at the end. // This variable holds the scaled probability of the current number of // successes. var scaledPDF = 1; // This keeps track of how much we have normalized. var samplesDone = 0; for (var i = 0; i < k; i++) { // For every possible number of successes up to that observed... while (scaledPDF > 1 && samplesDone < n) { // Intermediate result is growing too big. Apply some of the // normalization to shrink everything. scaledPDF *= 1 - m / (N - samplesDone); // Say we've normalized by this sample already. samplesDone++; } // Work out the partially-normalized hypergeometric PDF for the next // number of successes scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); } for (; samplesDone < n; samplesDone++) { // Apply all the rest of the normalization scaledPDF *= 1 - m / (N - samplesDone); } // Bound answer sanely before returning. return Math.min(1, Math.max(0, scaledPDF)); } }, cdf: function cdf(x, N, m, n) { // Hypergeometric CDF. // This algorithm is due to Prof. Thomas S. Ferguson, , // and comes from his hypergeometric test calculator at // . // x = number of successes drawn // N = population size // m = number of successes in population // n = number of items drawn from population if (x < 0 || x < m - (N - n)) { // It's impossible to have this few successes drawn or fewer. return 0; } else if (x >= n || x >= m) { // We will always have this many successes or fewer. return 1; } else if (m * 2 > N) { // More than half the population is successes. if (n * 2 > N) { // More than half the population is sampled. return cdf(N - m - n + x, N, N - m, N - n); } else { // Half or less of the population is sampled. return 1 - hypgeom.cdf(n - x - 1, N, N - m, n); } } else if (n * 2 > N) { // Half or less is successes. return 1 - hypgeom.cdf(m - x - 1, N, m, N - n); } else if (m < n) { // We want to have the number of things sampled to be less than the // successes available. So swap the definitions of successful and sampled. return hypgeom.cdf(x, N, n, m); } else { // If we get here, half or less of the population was sampled, half or // less of it was successes, and we had fewer sampled things than // successes. Now we can do this complicated iterative algorithm in an // efficient way. // The basic premise of the algorithm is that we partially normalize our // intermediate sum to keep it in a numerically good region, and then // finish the normalization at the end. // Holds the intermediate, scaled total CDF. var scaledCDF = 1; // This variable holds the scaled probability of the current number of // successes. var scaledPDF = 1; // This keeps track of how much we have normalized. var samplesDone = 0; for (var i = 0; i < x; i++) { // For every possible number of successes up to that observed... while (scaledCDF > 1 && samplesDone < n) { // Intermediate result is growing too big. Apply some of the // normalization to shrink everything. var factor = 1 - m / (N - samplesDone); scaledPDF *= factor; scaledCDF *= factor; // Say we've normalized by this sample already. samplesDone++; } // Work out the partially-normalized hypergeometric PDF for the next // number of successes scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); // Add to the CDF answer. scaledCDF += scaledPDF; } for (; samplesDone < n; samplesDone++) { // Apply all the rest of the normalization scaledCDF *= 1 - m / (N - samplesDone); } // Bound answer sanely before returning. return Math.min(1, Math.max(0, scaledCDF)); } } }; const studentt = { pdf: function pdf(x, dof) { dof = dof > 1e100 ? 1e100 : dof; return 1 / (Math.sqrt(dof) * betafn(0.5, dof / 2)) * Math.pow(1 + x * x / dof, -((dof + 1) / 2)); }, cdf: function cdf(x, dof) { var dof2 = dof / 2; return ibeta((x + Math.sqrt(x * x + dof)) / (2 * Math.sqrt(x * x + dof)), dof2, dof2); }, inv: function (p, dof) { var x = ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5); x = Math.sqrt(dof * (1 - x) / x); return p > 0.5 ? x : -x; } }; const lognormal = { pdf: function pdf(x, mu, sigma) { if (x <= 0) { return 0; } return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) - Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) / (2 * sigma * sigma)); }, cdf: function cdf(x, mu, sigma) { if (x < 0) { return 0; } return 0.5 + 0.5 * erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma)); }, inv: function (p, mu, sigma) { return Math.exp(-1.41421356237309505 * sigma * erfcinv(2 * p) + mu); } }; const negbin = { pdf: function pdf(k, r, p) { if (k !== k >>> 0) { return false; } if (k < 0) { return 0; } return combination(k + r - 1, r - 1) * Math.pow(1 - p, k) * Math.pow(p, r); }, cdf: function cdf(x, r, p) { var sum = 0, k = 0; if (x < 0) { return 0; } for (; k <= x; k++) { sum += negbin.pdf(k, r, p); } return sum; } }; function sum(arr) { var sum = 0; var i = arr.length; while (--i >= 0) { sum += arr[i]; } return sum; } function mean(arr) { return sum(arr) / arr.length; } function sumsqerr(arr) { var meanv = mean(arr); var sum = 0; var i = arr.length; var tmp; while (--i >= 0) { tmp = arr[i] - meanv; sum += tmp * tmp; } return sum; } function variance(arr, flag) { return sumsqerr(arr) / (arr.length - (flag ? 1 : 0)); } function stdev(arr, flag) { return Math.sqrt(variance(arr, flag)); } // 2 different parameter setups // (value, alpha, sd, n) // (value, alpha, array) function normalci() { var args = [].slice.call(arguments), ans = new Array(2), change; if (args.length === 4) { change = Math.abs(normal.inv(args[1] / 2, 0, 1) * args[2] / Math.sqrt(args[3])); } else { // @ts-ignore change = Math.abs(normal.inv(args[1] / 2, 0, 1) * stdev(args[2]) / Math.sqrt(args[2].length)); } ans[0] = args[0] - change; ans[1] = args[0] + change; return ans; } function tci() { var args = [].slice.call(arguments), ans = new Array(2), change; if (args.length === 4) { change = Math.abs(studentt.inv(args[1] / 2, args[3] - 1) * args[2] / Math.sqrt(args[3])); } else { // @ts-ignore change = Math.abs(studentt.inv(args[1] / 2, args[2].length - 1) * stdev(args[2], true) / Math.sqrt(args[2].length)); } ans[0] = args[0] - change; ans[1] = args[0] + change; return ans; } function product(arr) { var prod = 1; var i = arr.length; while (--i >= 0) { prod *= arr[i]; } return prod; } function geomean(arr) { return Math.pow(product(arr), 1 / arr.length); } function covariance(arr1, arr2) { var u = mean(arr1); var v = mean(arr2); var arr1Len = arr1.length; var sq_dev = new Array(arr1Len); var i; for (i = 0; i < arr1Len; i++) { sq_dev[i] = (arr1[i] - u) * (arr2[i] - v); } return sum(sq_dev) / (arr1Len - 1); } function corrcoeff(arr1, arr2) { return covariance(arr1, arr2) / stdev(arr1, 1) / stdev(arr2, 1); } /***/ }), /* 193 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ MathPlugin: () => (/* binding */ MathPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class MathPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionPlugin { fact(ast, state) { return this.runFunction(ast.args, state, this.metadata('FACT'), arg => { arg = Math.trunc(arg); let ret = 1; for (let i = 1; i <= arg; i++) { ret *= i; } return ret; }); } factdouble(ast, state) { return this.runFunction(ast.args, state, this.metadata('FACTDOUBLE'), arg => { arg = Math.trunc(arg); let ret = 1; for (let i = arg; i >= 1; i -= 2) { ret *= i; } return ret; }); } combin(ast, state) { return this.runFunction(ast.args, state, this.metadata('COMBIN'), (n, m) => { if (m > n) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.WrongOrder); } n = Math.trunc(n); m = Math.trunc(m); return combin(n, m); }); } combina(ast, state) { return this.runFunction(ast.args, state, this.metadata('COMBINA'), (n, m) => { n = Math.trunc(n); m = Math.trunc(m); if (n + m - 1 >= 1030) { //Product #2 does not enforce this return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } if (n === 0 && m === 0) { return 1; } return combin(n + m - 1, m); }); } gcd(ast, state) { return this.runFunction(ast.args, state, this.metadata('GCD'), (...args) => { const processedArgs = this.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(args); if (processedArgs instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return processedArgs; } let ret = 0; for (const val of processedArgs) { if (val < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } ret = binaryGCD(ret, Math.trunc(val)); } if (ret > Number.MAX_SAFE_INTEGER) { //inconsistency with product #1 return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } return ret; }); } lcm(ast, state) { return this.runFunction(ast.args, state, this.metadata('LCM'), (...args) => { const processedArgs = this.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(args); if (processedArgs instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return processedArgs; } let ret = 1; for (const val of processedArgs) { if (val < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } ret = binaryLCM(ret, Math.trunc(val)); } if (ret > Number.MAX_SAFE_INTEGER) { //inconsistency with product #1 return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueLarge); } return ret; }); } mround(ast, state) { return this.runFunction(ast.args, state, this.metadata('MROUND'), (nom, denom) => { if (denom === 0) { return 0; } if (nom > 0 && denom < 0 || nom < 0 && denom > 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.DistinctSigns); } return Math.round(nom / denom) * denom; }); } multinomial(ast, state) { return this.runFunction(ast.args, state, this.metadata('MULTINOMIAL'), (...args) => { let n = 0; let ans = 1; for (let arg of args) { if (arg < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } arg = Math.trunc(arg); for (let i = 1; i <= arg; i++) { ans *= (n + i) / i; } n += arg; } return Math.round(ans); }); } quotient(ast, state) { return this.runFunction(ast.args, state, this.metadata('QUOTIENT'), (nom, denom) => { if (denom === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return Math.trunc(nom / denom); }); } seriessum(ast, state) { return this.runFunction(ast.args, state, this.metadata('SERIESSUM'), (x, n, m, range) => { const coefs = this.arithmeticHelper.manyToOnlyNumbersDropNulls(range.valuesFromTopLeftCorner()); if (coefs instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coefs; } let ret = 0; coefs.reverse(); for (const coef of coefs) { ret *= Math.pow(x, m); ret += coef; } return ret * Math.pow(x, n); }); } sign(ast, state) { return this.runFunction(ast.args, state, this.metadata('SIGN'), arg => { if (arg > 0) { return 1; } else if (arg < 0) { return -1; } else { return 0; } }); } sumx2my2(ast, state) { return this.runFunction(ast.args, state, this.metadata('SUMX2MY2'), (rangeX, rangeY) => { const valsX = rangeX.valuesFromTopLeftCorner(); const valsY = rangeY.valuesFromTopLeftCorner(); if (valsX.length !== valsY.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const n = valsX.length; let ret = 0; for (let i = 0; i < n; i++) { const valX = valsX[i]; const valY = valsY[i]; if (valX instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valX; } if (valY instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valY; } if (typeof valX === 'number' && typeof valY === 'number') { ret += Math.pow(valX, 2) - Math.pow(valY, 2); } } return ret; }); } sumx2py2(ast, state) { return this.runFunction(ast.args, state, this.metadata('SUMX2PY2'), (rangeX, rangeY) => { const valsX = rangeX.valuesFromTopLeftCorner(); const valsY = rangeY.valuesFromTopLeftCorner(); if (valsX.length !== valsY.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const n = valsX.length; let ret = 0; for (let i = 0; i < n; i++) { const valX = valsX[i]; const valY = valsY[i]; if (valX instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valX; } if (valY instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valY; } if (typeof valX === 'number' && typeof valY === 'number') { ret += Math.pow(valX, 2) + Math.pow(valY, 2); } } return ret; }); } sumxmy2(ast, state) { return this.runFunction(ast.args, state, this.metadata('SUMXMY2'), (rangeX, rangeY) => { const valsX = rangeX.valuesFromTopLeftCorner(); const valsY = rangeY.valuesFromTopLeftCorner(); if (valsX.length !== valsY.length) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const n = valsX.length; let ret = 0; for (let i = 0; i < n; i++) { const valX = valsX[i]; const valY = valsY[i]; if (valX instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valX; } if (valY instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return valY; } if (typeof valX === 'number' && typeof valY === 'number') { ret += Math.pow(valX - valY, 2); } } return ret; }); } } MathPlugin.implementedFunctions = { 'FACT': { method: 'fact', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 170 }] }, 'FACTDOUBLE': { method: 'factdouble', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0, maxValue: 288 }] }, 'COMBIN': { method: 'combin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0, lessThan: 1030 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'COMBINA': { method: 'combina', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER, minValue: 0 }] }, 'GCD': { method: 'gcd', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'LCM': { method: 'lcm', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'MROUND': { method: 'mround', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'MULTINOMIAL': { method: 'multinomial', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }], repeatLastArgs: 1, expandRanges: true }, 'QUOTIENT': { method: 'quotient', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SERIESSUM': { method: 'seriessum', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }] }, 'SIGN': { method: 'sign', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.NUMBER }] }, 'SUMX2MY2': { method: 'sumx2my2', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }] }, 'SUMX2PY2': { method: 'sumx2py2', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }] }, 'SUMXMY2': { method: 'sumxmy2', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE }] } }; function combin(n, m) { if (2 * m > n) { m = n - m; } let ret = 1; for (let i = 1; i <= m; i++) { ret *= (n - m + i) / i; } return Math.round(ret); } function binaryGCD(a, b) { if (a < b) { [a, b] = [b, a]; } while (b > 0) { [a, b] = [b, a % b]; } return a; } function binaryLCM(a, b) { if (a === 0 || b === 0) { return 0; } return a * (b / binaryGCD(a, b)); } /***/ }), /* 194 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ ComplexPlugin: () => (/* binding */ ComplexPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(98); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class ComplexPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionPlugin { complex(ast, state) { return this.runFunction(ast.args, state, this.metadata('COMPLEX'), (re, im, unit) => { if (unit !== 'i' && unit !== 'j') { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ShouldBeIorJ); } return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)([re, im], unit); }); } imabs(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMABS'), abs); } imaginary(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMAGINARY'), ([_re, im]) => im); } imreal(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMREAL'), ([re, _im]) => re); } imargument(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMARGUMENT'), ([re, im]) => { if (re === 0 && im === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return Math.atan2(im, re); }); } imconjugate(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCONJUGATE'), ([re, im]) => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)([re, -im])); } imcos(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCOS'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(cos(arg))); } imcosh(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCOSH'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(cosh(arg))); } imcot(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCOT'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div(cos(arg), sin(arg)))); } imcsc(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCSC'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div([1, 0], sin(arg)))); } imcsch(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMCSCH'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div([1, 0], sinh(arg)))); } imsec(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSEC'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div([1, 0], cos(arg)))); } imsech(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSECH'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div([1, 0], cosh(arg)))); } imsin(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSIN'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(sin(arg))); } imsinh(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSINH'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(sinh(arg))); } imtan(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMTAN'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div(sin(arg), cos(arg)))); } imdiv(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMDIV'), (arg1, arg2) => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(div(arg1, arg2))); } improduct(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMPRODUCT'), (...args) => { const coerced = this.arithmeticHelper.coerceComplexExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } let prod = [1, 0]; for (const val of coerced) { prod = mul(prod, val); } return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(prod); }); } imsum(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSUM'), (...args) => { const coerced = this.arithmeticHelper.coerceComplexExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } let sum = [0, 0]; for (const val of coerced) { sum = add(sum, val); } return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(sum); }); } imsub(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSUB'), (arg1, arg2) => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(sub(arg1, arg2))); } imexp(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMEXP'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(exp(arg))); } imln(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMLN'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(ln(arg))); } imlog10(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMLOG10'), arg => { const [re, im] = ln(arg); const c = Math.log(10); return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)([re / c, im / c]); }); } imlog2(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMLOG2'), arg => { const [re, im] = ln(arg); const c = Math.log(2); return (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)([re / c, im / c]); }); } impower(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMPOWER'), (arg, n) => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(power(arg, n))); } imsqrt(ast, state) { return this.runFunction(ast.args, state, this.metadata('IMSQRT'), arg => (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_2__.coerceComplexToString)(power(arg, 0.5))); } } ComplexPlugin.implementedFunctions = { 'COMPLEX': { method: 'complex', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.STRING, defaultValue: 'i' }] }, 'IMABS': { method: 'imabs', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMAGINARY': { method: 'imaginary', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMREAL': { method: 'imreal', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMARGUMENT': { method: 'imargument', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCONJUGATE': { method: 'imconjugate', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCOS': { method: 'imcos', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCOSH': { method: 'imcosh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCOT': { method: 'imcot', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCSC': { method: 'imcsc', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMCSCH': { method: 'imcsch', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMSEC': { method: 'imsec', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMSECH': { method: 'imsech', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMSIN': { method: 'imsin', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMSINH': { method: 'imsinh', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMTAN': { method: 'imtan', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMDIV': { method: 'imdiv', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMPRODUCT': { method: 'improduct', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'IMSUM': { method: 'imsum', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'IMSUB': { method: 'imsub', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMEXP': { method: 'imexp', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMLN': { method: 'imln', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMLOG10': { method: 'imlog10', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMLOG2': { method: 'imlog2', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] }, 'IMPOWER': { method: 'impower', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.NUMBER }] }, 'IMSQRT': { method: 'imsqrt', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_3__.FunctionArgumentType.COMPLEX }] } }; function add([re1, im1], [re2, im2]) { return [re1 + re2, im1 + im2]; } function sub([re1, im1], [re2, im2]) { return [re1 - re2, im1 - im2]; } function mul([re1, im1], [re2, im2]) { return [re1 * re2 - im1 * im2, re1 * im2 + re2 * im1]; } function div([re1, im1], [re2, im2]) { const denom = Math.pow(re2, 2) + Math.pow(im2, 2); const [nomRe, nomIm] = mul([re1, im1], [re2, -im2]); return [nomRe / denom, nomIm / denom]; } function cos([re, im]) { return [Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im)]; } function cosh([re, im]) { return [Math.cosh(re) * Math.cos(im), Math.sinh(re) * Math.sin(im)]; } function sin([re, im]) { return [Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)]; } function sinh([re, im]) { return [Math.sinh(re) * Math.cos(im), Math.cosh(re) * Math.sin(im)]; } function exp([re, im]) { return [Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)]; } function abs([re, im]) { return Math.sqrt(re * re + im * im); } function ln([re, im]) { return [Math.log(abs([re, im])), Math.atan2(im, re)]; } function power(arg, n) { const [re, im] = ln(arg); return exp([n * re, n * im]); } /***/ }), /* 195 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ StatisticalAggregationPlugin: () => (/* binding */ StatisticalAggregationPlugin) /* harmony export */ }); /* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61); /* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70); /* harmony import */ var _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(192); /* harmony import */ var _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(97); /** * @license * Copyright (c) 2024 Handsoncode. All rights reserved. */ class StatisticalAggregationPlugin extends _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionPlugin { avedev(ast, state) { return this.runFunction(ast.args, state, this.metadata('AVEDEV'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } if (coerced.length === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const avg = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(coerced); return coerced.reduce((a, b) => a + Math.abs(b - avg), 0) / coerced.length; }); } devsq(ast, state) { return this.runFunction(ast.args, state, this.metadata('DEVSQ'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } if (coerced.length === 0) { return 0; } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(coerced); }); } geomean(ast, state) { return this.runFunction(ast.args, state, this.metadata('GEOMEAN'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } if (coerced.length === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.OneValue); } for (const val of coerced) { if (val <= 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.geomean)(coerced); }); } harmean(ast, state) { return this.runFunction(ast.args, state, this.metadata('HARMEAN'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } if (coerced.length === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.OneValue); } for (const val of coerced) { if (val <= 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ValueSmall); } } return coerced.length / coerced.reduce((a, b) => a + 1 / b, 0); }); } correl(ast, state) { return this.runFunction(ast.args, state, this.metadata('CORREL'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.corrcoeff)(ret[0], ret[1]); }); } rsq(ast, state) { return this.runFunction(ast.args, state, this.metadata('RSQ'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } return Math.pow((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.corrcoeff)(ret[0], ret[1]), 2); }); } covariancep(ast, state) { return this.runFunction(ast.args, state, this.metadata('COVARIANCE.P'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.OneValue); } if (n === 1) { return 0; } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.covariance)(ret[0], ret[1]) * (n - 1) / n; }); } covariances(ast, state) { return this.runFunction(ast.args, state, this.metadata('COVARIANCE.S'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.covariance)(ret[0], ret[1]); }); } ztest(ast, state) { return this.runFunction(ast.args, state, this.metadata('Z.TEST'), (range, x, sigma) => { const vals = this.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()); if (vals instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return vals; } const n = vals.length; if (sigma === undefined) { if (n < 2) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } sigma = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.stdev)(vals, true); } if (n < 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.OneValue); } if (sigma === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return 1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.normal.cdf(((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(vals) - x) / (sigma / Math.sqrt(n)), 0, 1); }); } ftest(ast, state) { return this.runFunction(ast.args, state, this.metadata('F.TEST'), (dataX, dataY) => { const arrX = this.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()); const arrY = this.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()); if (arrX instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arrX; } if (arrY instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arrY; } if (arrX.length <= 1 || arrY.length <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const vx = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.variance)(arrX, true); const vy = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.variance)(arrY, true); if (vx === 0 || vy === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const r = vx / vy; const v = _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.centralF.cdf(r, arrX.length - 1, arrY.length - 1); return 2 * Math.min(v, 1 - v); }); } steyx(ast, state) { return this.runFunction(ast.args, state, this.metadata('STEYX'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n <= 2) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ThreeValues); } return Math.sqrt(((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(ret[0]) - Math.pow((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.covariance)(ret[0], ret[1]) * (n - 1), 2) / (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(ret[1])) / (n - 2)); }); } slope(ast, state) { return this.runFunction(ast.args, state, this.metadata('SLOPE'), (dataX, dataY) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } const n = ret[0].length; if (n <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } return (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.covariance)(ret[0], ret[1]) * (n - 1) / (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(ret[1]); }); } chisqtest(ast, state) { return this.runFunction(ast.args, state, this.metadata('CHISQ.TEST'), (dataX, dataY) => { const r = dataX.height(); const c = dataX.width(); if (dataY.height() !== r || dataY.width() !== c) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } const ret = parseTwoArrays(dataX, dataY); if (ret instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return ret; } if (ret[0].length <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } let sum = 0; for (let i = 0; i < ret[0].length; i++) { if (ret[1][i] === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } sum += Math.pow(ret[0][i] - ret[1][i], 2) / ret[1][i]; } if (sum < 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.NaN); } return 1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.chisquare.cdf(sum, r > 1 && c > 1 ? (r - 1) * (c - 1) : r * c - 1); }); } ttest(ast, state) { return this.runFunction(ast.args, state, this.metadata('T.TEST'), (dataX, dataY, tails, type) => { const arrX = this.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()); const arrY = this.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()); if (arrX instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arrX; } if (arrY instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return arrY; } const n = arrX.length; const m = arrY.length; if (type === 1) { if (m !== n) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.EqualLength); } if (n <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } const sub = Array(n); for (let i = 0; i < n; i++) { sub[i] = arrX[i] - arrY[i]; } const s = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.stdev)(sub, true); if (s === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const t = Math.abs(Math.sqrt(n) * (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(sub) / s); return tails * (1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(t, n - 1)); } else if (type === 2) { if (n <= 1 || m <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } const s = ((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(arrX) + (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.sumsqerr)(arrY)) / (n + m - 2); if (s === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const t = Math.abs(((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(arrX) - (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(arrY)) / Math.sqrt(s * (1 / n + 1 / m))); return tails * (1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(t, n + m - 2)); } else { //type === 3 if (n <= 1 || m <= 1) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.TwoValues); } const sx = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.variance)(arrX, true); const sy = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.variance)(arrY, true); if (sx === 0 && sy === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } const t = Math.abs(((0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(arrX) - (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(arrY)) / Math.sqrt(sx / n + sy / m)); const v = Math.pow(sx / n + sy / m, 2) / (Math.pow(sx / n, 2) / (n - 1) + Math.pow(sy / m, 2) / (m - 1)); return tails * (1 - _3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.studentt.cdf(t, v)); } }); } skew(ast, state) { return this.runFunction(ast.args, state, this.metadata('SKEW'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } const n = coerced.length; if (n < 3) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ThreeValues); } const avg = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(coerced); const s = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.stdev)(coerced, true); if (s === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return coerced.reduce((a, b) => a + Math.pow((b - avg) / s, 3), 0) * n / (n - 1) / (n - 2); }); } skewp(ast, state) { return this.runFunction(ast.args, state, this.metadata('SKEW.P'), (...args) => { const coerced = this.arithmeticHelper.coerceNumbersExactRanges(args); if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return coerced; } const n = coerced.length; if (n < 3) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ThreeValues); } const avg = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.mean)(coerced); const s = (0,_3rdparty_jstat_jstat__WEBPACK_IMPORTED_MODULE_3__.stdev)(coerced, false); if (s === 0) { return new _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.DIV_BY_ZERO); } return coerced.reduce((a, b) => a + Math.pow((b - avg) / s, 3), 0) / n; }); } } StatisticalAggregationPlugin.implementedFunctions = { 'AVEDEV': { method: 'avedev', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'DEVSQ': { method: 'devsq', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'GEOMEAN': { method: 'geomean', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'HARMEAN': { method: 'harmean', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'CORREL': { method: 'correl', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'RSQ': { method: 'rsq', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'COVARIANCE.P': { method: 'covariancep', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'COVARIANCE.S': { method: 'covariances', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'Z.TEST': { method: 'ztest', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.NUMBER, optionalArg: true }] }, 'F.TEST': { method: 'ftest', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'STEYX': { method: 'steyx', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'SLOPE': { method: 'slope', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'CHISQ.TEST': { method: 'chisqtest', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }] }, 'T.TEST': { method: 'ttest', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.RANGE }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.INTEGER, minValue: 1, maxValue: 2 }, { argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.INTEGER, minValue: 1, maxValue: 3 }] }, 'SKEW': { method: 'skew', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 }, 'SKEW.P': { method: 'skewp', parameters: [{ argumentType: _FunctionPlugin__WEBPACK_IMPORTED_MODULE_4__.FunctionArgumentType.ANY }], repeatLastArgs: 1 } }; StatisticalAggregationPlugin.aliases = { COVAR: 'COVARIANCE.P', FTEST: 'F.TEST', PEARSON: 'CORREL', ZTEST: 'Z.TEST', CHITEST: 'CHISQ.TEST', TTEST: 'T.TEST', COVARIANCEP: 'COVARIANCE.P', COVARIANCES: 'COVARIANCE.S', SKEWP: 'SKEW.P' }; function parseTwoArrays(dataX, dataY) { const xit = dataX.iterateValuesFromTopLeftCorner(); const yit = dataY.iterateValuesFromTopLeftCorner(); let x, y; const arrX = []; const arrY = []; while (x = xit.next(), y = yit.next(), !x.done && !y.done) { const xval = x.value; const yval = y.value; if (xval instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return xval; } else if (yval instanceof _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError) { return yval; } else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(xval) && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(yval)) { arrX.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getRawValue)(xval)); arrY.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getRawValue)(yval)); } } return [arrX, arrY]; } /***/ }), /* 196 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var _interopRequireDefault = __webpack_require__(197); exports.__esModule = true; var _base = _interopRequireWildcard(__webpack_require__(198)); exports.CellCoords = _base.CellCoords; exports.CellRange = _base.CellRange; var _registry = __webpack_require__(726); var _eventManager = _interopRequireWildcard(__webpack_require__(495)); var _translations = __webpack_require__(590); var _jquery = _interopRequireDefault(__webpack_require__(1064)); var _ghostTable = _interopRequireDefault(__webpack_require__(808)); var parseTableHelpers = _interopRequireWildcard(__webpack_require__(497)); var arrayHelpers = _interopRequireWildcard(__webpack_require__(471)); var browserHelpers = _interopRequireWildcard(__webpack_require__(474)); var dataHelpers = _interopRequireWildcard(__webpack_require__(589)); var dateHelpers = _interopRequireWildcard(__webpack_require__(775)); var featureHelpers = _interopRequireWildcard(__webpack_require__(478)); var functionHelpers = _interopRequireWildcard(__webpack_require__(473)); var mixedHelpers = _interopRequireWildcard(__webpack_require__(330)); var numberHelpers = _interopRequireWildcard(__webpack_require__(505)); var objectHelpers = _interopRequireWildcard(__webpack_require__(475)); var stringHelpers = _interopRequireWildcard(__webpack_require__(328)); var unicodeHelpers = _interopRequireWildcard(__webpack_require__(484)); var domHelpers = _interopRequireWildcard(__webpack_require__(327)); var domEventHelpers = _interopRequireWildcard(__webpack_require__(485)); var _registry2 = __webpack_require__(486); var _registry3 = __webpack_require__(508); var _registry4 = __webpack_require__(509); var _registry5 = __webpack_require__(638); var _registry6 = __webpack_require__(503); var _base2 = __webpack_require__(806); var _Handsontable$cellTyp, _Handsontable$editors, _Handsontable$rendere, _Handsontable$validat, _Handsontable$plugins; function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } (0, _registry.registerAllModules)(); (0, _jquery.default)(_base.default); // TODO: Remove this exports after rewrite tests about this module _base.default.__GhostTable = _ghostTable.default; _base.default._getListenersCounter = _eventManager.getListenersCounter; // For MemoryLeak tests _base.default._getRegisteredMapsCounter = _translations.getRegisteredMapsCounter; // For MemoryLeak tests _base.default.EventManager = _eventManager.default; // Export all helpers to the Handsontable object const HELPERS = [arrayHelpers, browserHelpers, dataHelpers, dateHelpers, featureHelpers, functionHelpers, mixedHelpers, numberHelpers, objectHelpers, stringHelpers, unicodeHelpers, parseTableHelpers]; const DOM = [domHelpers, domEventHelpers]; _base.default.helper = {}; _base.default.dom = {}; // Fill general helpers. arrayHelpers.arrayEach(HELPERS, helper => { arrayHelpers.arrayEach(Object.getOwnPropertyNames(helper), key => { if (key.charAt(0) !== '_') { _base.default.helper[key] = helper[key]; } }); }); // Fill DOM helpers. arrayHelpers.arrayEach(DOM, helper => { arrayHelpers.arrayEach(Object.getOwnPropertyNames(helper), key => { if (key.charAt(0) !== '_') { _base.default.dom[key] = helper[key]; } }); }); // Export cell types. _base.default.cellTypes = (_Handsontable$cellTyp = _base.default.cellTypes) !== null && _Handsontable$cellTyp !== void 0 ? _Handsontable$cellTyp : {}; arrayHelpers.arrayEach((0, _registry5.getRegisteredCellTypeNames)(), cellTypeName => { _base.default.cellTypes[cellTypeName] = (0, _registry5.getCellType)(cellTypeName); }); _base.default.cellTypes.registerCellType = _registry5.registerCellType; _base.default.cellTypes.getCellType = _registry5.getCellType; // Export all registered editors from the Handsontable. _base.default.editors = (_Handsontable$editors = _base.default.editors) !== null && _Handsontable$editors !== void 0 ? _Handsontable$editors : {}; arrayHelpers.arrayEach((0, _registry2.getRegisteredEditorNames)(), editorName => { _base.default.editors[`${stringHelpers.toUpperCaseFirst(editorName)}Editor`] = (0, _registry2.getEditor)(editorName); }); _base.default.editors.registerEditor = _registry2.registerEditor; _base.default.editors.getEditor = _registry2.getEditor; // Export all registered renderers from the Handsontable. _base.default.renderers = (_Handsontable$rendere = _base.default.renderers) !== null && _Handsontable$rendere !== void 0 ? _Handsontable$rendere : {}; arrayHelpers.arrayEach((0, _registry3.getRegisteredRendererNames)(), rendererName => { const renderer = (0, _registry3.getRenderer)(rendererName); if (rendererName === 'base') { _base.default.renderers.cellDecorator = renderer; } _base.default.renderers[`${stringHelpers.toUpperCaseFirst(rendererName)}Renderer`] = renderer; }); _base.default.renderers.registerRenderer = _registry3.registerRenderer; _base.default.renderers.getRenderer = _registry3.getRenderer; // Export all registered validators from the Handsontable. _base.default.validators = (_Handsontable$validat = _base.default.validators) !== null && _Handsontable$validat !== void 0 ? _Handsontable$validat : {}; arrayHelpers.arrayEach((0, _registry4.getRegisteredValidatorNames)(), validatorName => { _base.default.validators[`${stringHelpers.toUpperCaseFirst(validatorName)}Validator`] = (0, _registry4.getValidator)(validatorName); }); _base.default.validators.registerValidator = _registry4.registerValidator; _base.default.validators.getValidator = _registry4.getValidator; // Export all registered plugins from the Handsontable. // Make sure to initialize the plugin dictionary as an empty object. Otherwise, while // transpiling the files into ES and CommonJS format, the injected CoreJS helper // `import "core-js/modules/es.object.get-own-property-names";` won't be processed // by the `./config/plugin/babel/add-import-extension` babel plugin. Thus, the distribution // files will be broken. The reason is not known right now (probably it's caused by bug in // the Babel or missing something in the plugin). _base.default.plugins = (_Handsontable$plugins = _base.default.plugins) !== null && _Handsontable$plugins !== void 0 ? _Handsontable$plugins : {}; arrayHelpers.arrayEach((0, _registry6.getPluginsNames)(), pluginName => { _base.default.plugins[pluginName] = (0, _registry6.getPlugin)(pluginName); }); _base.default.plugins[`${stringHelpers.toUpperCaseFirst(_base2.BasePlugin.PLUGIN_KEY)}Plugin`] = _base2.BasePlugin; _base.default.plugins.registerPlugin = _registry6.registerPlugin; _base.default.plugins.getPlugin = _registry6.getPlugin; var _default = exports["default"] = _base.default; /***/ }), /* 197 */ /***/ ((module) => { function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /* 198 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var _interopRequireDefault = __webpack_require__(197); exports.__esModule = true; __webpack_require__(199); __webpack_require__(200); __webpack_require__(201); __webpack_require__(202); var _core = _interopRequireDefault(__webpack_require__(203)); var _rootInstance = __webpack_require__(587); var _dataMap = __webpack_require__(631); var _pluginHooks = _interopRequireDefault(__webpack_require__(487)); var _registry = __webpack_require__(609); var _registry2 = __webpack_require__(638); var _textType = __webpack_require__(716); var _baseEditor = __webpack_require__(656); var _src = __webpack_require__(511); exports.CellCoords = _src.CellCoords; exports.CellRange = _src.CellRange; // FIXME: Bug in eslint-plugin-import: https://github.com/benmosher/eslint-plugin-import/issues/1883 /* eslint-disable import/named */ /* eslint-enable import/named */ // register default mandatory cell type for the Base package (0, _registry2.registerCellType)(_textType.TextCellType); // export the `BaseEditor` class to the Handsontable global namespace Handsontable.editors = { BaseEditor: _baseEditor.BaseEditor }; /** * @param {HTMLElement} rootElement The element to which the Handsontable instance is injected. * @param {object} userSettings The user defined options. * @returns {Core} */ function Handsontable(rootElement, userSettings) { const instance = new _core.default(rootElement, userSettings || {}, _rootInstance.rootInstanceSymbol); instance.init(); return instance; } Handsontable.Core = function (rootElement) { let userSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new _core.default(rootElement, userSettings, _rootInstance.rootInstanceSymbol); }; Handsontable.DefaultSettings = (0, _dataMap.metaSchemaFactory)(); Handsontable.hooks = _pluginHooks.default.getSingleton(); Handsontable.CellCoords = _src.CellCoords; Handsontable.CellRange = _src.CellRange; Handsontable.packageName = 'handsontable'; Handsontable.buildDate = "07/02/2025 16:13:25"; Handsontable.version = "14.6.2"; Handsontable.languages = { dictionaryKeys: _registry.dictionaryKeys, getLanguageDictionary: _registry.getLanguageDictionary, getLanguagesDictionaries: _registry.getLanguagesDictionaries, registerLanguageDictionary: _registry.registerLanguageDictionary, getTranslatedPhrase: _registry.getTranslatedPhrase }; var _default = exports["default"] = Handsontable; /***/ }), /* 199 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /* 200 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /* 201 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /* 202 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /* 203 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var _interopRequireDefault = __webpack_require__(197); exports.__esModule = true; exports["default"] = Core; __webpack_require__(204); __webpack_require__(286); __webpack_require__(290); __webpack_require__(301); __webpack_require__(303); __webpack_require__(306); __webpack_require__(308); __webpack_require__(310); __webpack_require__(312); __webpack_require__(314); var _element = __webpack_require__(327); var _function = __webpack_require__(473); var _mixed = __webpack_require__(330); var _browser = __webpack_require__(474); var _editorManager = _interopRequireDefault(__webpack_require__(479)); var _eventManager = _interopRequireDefault(__webpack_require__(495)); var _object = __webpack_require__(475); var _focusManager = __webpack_require__(496); var _array = __webpack_require__(471); var _parseTable = __webpack_require__(497); var _registry = __webpack_require__(503); var _registry2 = __webpack_require__(508); var _registry3 = __webpack_require__(486); var _registry4 = __webpack_require__(509); var _string = __webpack_require__(328); var _number = __webpack_require__(505); var _tableView = _interopRequireDefault(__webpack_require__(510)); var _dataSource = _interopRequireDefault(__webpack_require__(588)); var _data = __webpack_require__(589); var _translations = __webpack_require__(590); var _rootInstance = __webpack_require__(587); var _src = __webpack_require__(511); var _pluginHooks = _interopRequireDefault(__webpack_require__(487)); var _registry5 = __webpack_require__(609); var _utils = __webpack_require__(610); var _selection = __webpack_require__(615); var _dataMap = __webpack_require__(631); var _index3 = __webpack_require__(647); var _uniqueMap = __webpack_require__(506); var _shortcuts = __webpack_require__(710); var _shortcutContexts = __webpack_require__(649); let activeGuid = null; /** * Keeps the collection of the all Handsontable instances created on the same page. The * list is then used to trigger the "afterUnlisten" hook when the "listen()" method was * called on another instance. * * @type {Map} */ const foreignHotInstances = new Map(); /** * A set of deprecated feature names. * * @type {Set} */ // eslint-disable-next-line no-unused-vars const deprecationWarns = new Set(); /* eslint-disable jsdoc/require-description-complete-sentence */ /** * Handsontable constructor. * * @core * @class Core * @description * * The `Handsontable` class (known as the `Core`) lets you modify the grid's behavior by using Handsontable's public API methods. * * ::: only-for react * To use these methods, associate a Handsontable instance with your instance * of the [`HotTable` component](@/guides/getting-started/installation/installation.md#_4-use-the-hottable-component), * by using React's `ref` feature (read more on the [Instance methods](@/guides/getting-started/react-methods/react-methods.md) page). * ::: * * ## How to call a method * * ::: only-for javascript * ```js * // create a Handsontable instance * const hot = new Handsontable(document.getElementById('example'), options); * * // call a method * hot.setDataAtCell(0, 0, 'new value'); * ``` * ::: * * ::: only-for react * ```jsx * import { useRef } from 'react'; * * const hotTableComponent = useRef(null); * * * * // access the Handsontable instance, under the `.current.hotInstance` property * // call a method * hotTableComponent.current.hotInstance.setDataAtCell(0, 0, 'new value'); * ``` * ::: * * @param {HTMLElement} rootElement The element to which the Handsontable instance is injected. * @param {object} userSettings The user defined options. * @param {boolean} [rootInstanceSymbol=false] Indicates if the instance is root of all later instances created. */ function Core(rootElement, userSettings) { var _userSettings$layoutD, _this = this; let rootInstanceSymbol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; let instance = this; const eventManager = new _eventManager.default(instance); let datamap; let dataSource; let grid; let editorManager; let focusManager; let viewportScroller; let firstRun = true; if ((0, _rootInstance.hasValidParameter)(rootInstanceSymbol)) { (0, _rootInstance.registerAsRootInstance)(this); } // TODO: check if references to DOM elements should be move to UI layer (Walkontable) /** * Reference to the container element. * * @private * @type {HTMLElement} */ this.rootElement = rootElement; /** * The nearest document over container. * * @private * @type {Document} */ this.rootDocument = rootElement.ownerDocument; /** * Window object over container's document. * * @private * @type {Window} */ this.rootWindow = this.rootDocument.defaultView; /** * A boolean to tell if the Handsontable has been fully destroyed. This is set to `true` * after `afterDestroy` hook is called. * * @memberof Core# * @member isDestroyed * @type {boolean} */ this.isDestroyed = false; /** * The counter determines how many times the render suspending was called. It allows * tracking the nested suspending calls. For each render suspend resuming call the * counter is decremented. The value equal to 0 means the render suspending feature * is disabled. * * @private * @type {number} */ this.renderSuspendedCounter = 0; /** * The counter determines how many times the execution suspending was called. It allows * tracking the nested suspending calls. For each execution suspend resuming call the * counter is decremented. The value equal to 0 means the execution suspending feature * is disabled. * * @private * @type {number} */ this.executionSuspendedCounter = 0; const layoutDirection = (_userSettings$layoutD = userSettings === null || userSettings === void 0 ? void 0 : userSettings.layoutDirection) !== null && _userSettings$layoutD !== void 0 ? _userSettings$layoutD : 'inherit'; const rootElementDirection = ['rtl', 'ltr'].includes(layoutDirection) ? layoutDirection : this.rootWindow.getComputedStyle(this.rootElement).direction; this.rootElement.setAttribute('dir', rootElementDirection); /** * Checks if the grid is rendered using the right-to-left layout direction. * * @since 12.0.0 * @memberof Core# * @function isRtl * @returns {boolean} True if RTL. */ this.isRtl = function () { return rootElementDirection === 'rtl'; }; /** * Checks if the grid is rendered using the left-to-right layout direction. * * @since 12.0.0 * @memberof Core# * @function isLtr * @returns {boolean} True if LTR. */ this.isLtr = function () { return !instance.isRtl(); }; /** * Returns 1 for LTR; -1 for RTL. Useful for calculations. * * @since 12.0.0 * @memberof Core# * @function getDirectionFactor * @returns {number} Returns 1 for LTR; -1 for RTL. */ this.getDirectionFactor = function () { return instance.isLtr() ? 1 : -1; }; userSettings.language = (0, _registry5.getValidLanguageCode)(userSettings.language); const metaManager = new _dataMap.MetaManager(instance, userSettings, [_dataMap.DynamicCellMetaMod, _dataMap.ExtendMetaPropertiesMod]); const tableMeta = metaManager.getTableMeta(); const globalMeta = metaManager.getGlobalMeta(); const pluginsRegistry = (0, _uniqueMap.createUniqueMap)(); this.container = this.rootDocument.createElement('div'); this.renderCall = false; rootElement.insertBefore(this.container, rootElement.firstChild); if ((0, _rootInstance.isRootInstance)(this)) { (0, _mixed._injectProductInfo)(userSettings.licenseKey, rootElement); } this.guid = `ht_${(0, _string.randomString)()}`; // this is the namespace for global events foreignHotInstances.set(this.guid, this); /** * Instance of index mapper which is responsible for managing the column indexes. * * @memberof Core# * @member columnIndexMapper * @type {IndexMapper} */ this.columnIndexMapper = new _translations.IndexMapper(); /** * Instance of index mapper which is responsible for managing the row indexes. * * @memberof Core# * @member rowIndexMapper * @type {IndexMapper} */ this.rowIndexMapper = new _translations.IndexMapper(); this.columnIndexMapper.addLocalHook('indexesSequenceChange', source => { instance.runHooks('afterColumnSequenceChange', source); }); this.rowIndexMapper.addLocalHook('indexesSequenceChange', source => { instance.runHooks('afterRowSequenceChange', source); }); dataSource = new _dataSource.default(instance); if (!this.rootElement.id || this.rootElement.id.substring(0, 3) === 'ht_') { this.rootElement.id = this.guid; // if root element does not have an id, assign a random id } const visualToRenderableCoords = coords => { const { row: visualRow, col: visualColumn } = coords; return instance._createCellCoords( // We just store indexes for rows and columns without headers. visualRow >= 0 ? instance.rowIndexMapper.getRenderableFromVisualIndex(visualRow) : visualRow, visualColumn >= 0 ? instance.columnIndexMapper.getRenderableFromVisualIndex(visualColumn) : visualColumn); }; const renderableToVisualCoords = coords => { const { row: renderableRow, col: renderableColumn } = coords; return instance._createCellCoords( // We just store indexes for rows and columns without headers. renderableRow >= 0 ? instance.rowIndexMapper.getVisualFromRenderableIndex(renderableRow) : renderableRow, renderableColumn >= 0 ? instance.columnIndexMapper.getVisualFromRenderableIndex(renderableColumn) : renderableColumn // eslint-disable-line max-len ); }; const findFirstNonHiddenRenderableRow = (visualRowFrom, visualRowTo) => { const dir = visualRowTo > visualRowFrom ? 1 : -1; const minIndex = Math.min(visualRowFrom, visualRowTo); const maxIndex = Math.max(visualRowFrom, visualRowTo); const rowIndex = instance.rowIndexMapper.getNearestNotHiddenIndex(visualRowFrom, dir); if (rowIndex === null || dir === 1 && rowIndex > maxIndex || dir === -1 && rowIndex < minIndex) { return null; } return rowIndex >= 0 ? instance.rowIndexMapper.getRenderableFromVisualIndex(rowIndex) : rowIndex; }; const findFirstNonHiddenRenderableColumn = (visualColumnFrom, visualColumnTo) => { const dir = visualColumnTo > visualColumnFrom ? 1 : -1; const minIndex = Math.min(visualColumnFrom, visualColumnTo); const maxIndex = Math.max(visualColumnFrom, visualColumnTo); const columnIndex = instance.columnIndexMapper.getNearestNotHiddenIndex(visualColumnFrom, dir); if (columnIndex === null || dir === 1 && columnIndex > maxIndex || dir === -1 && columnIndex < minIndex) { return null; } return columnIndex >= 0 ? instance.columnIndexMapper.getRenderableFromVisualIndex(columnIndex) : columnIndex; }; let selection = new _selection.Selection(tableMeta, { rowIndexMapper: instance.rowIndexMapper, columnIndexMapper: instance.columnIndexMapper, countCols: () => instance.countCols(), countRows: () => instance.countRows(), propToCol: prop => datamap.propToCol(prop), isEditorOpened: () => instance.getActiveEditor() ? instance.getActiveEditor().isOpened() : false, countRenderableColumns: () => this.view.countRenderableColumns(), countRenderableRows: () => this.view.countRenderableRows(), countRowHeaders: () => this.countRowHeaders(), countColHeaders: () => this.countColHeaders(), countRenderableRowsInRange: function () { return _this.view.countRenderableRowsInRange(...arguments); }, countRenderableColumnsInRange: function () { return _this.view.countRenderableColumnsInRange(...arguments); }, getShortcutManager: () => instance.getShortcutManager(), createCellCoords: (row, column) => instance._createCellCoords(row, column), createCellRange: (highlight, from, to) => instance._createCellRange(highlight, from, to), visualToRenderableCoords, renderableToVisualCoords, findFirstNonHiddenRenderableRow, findFirstNonHiddenRenderableColumn, isDisabledCellSelection: (visualRow, visualColumn) => { if (visualRow < 0 || visualColumn < 0) { return instance.getSettings().disableVisualSelection; } return instance.getCellMeta(visualRow, visualColumn).disableVisualSelection; } }); this.selection = selection; const onIndexMapperCacheUpdate = _ref => { let { hiddenIndexesChanged } = _ref; if (hiddenIndexesChanged) { this.selection.commit(); } }; this.columnIndexMapper.addLocalHook('cacheUpdated', onIndexMapperCacheUpdate); this.rowIndexMapper.addLocalHook('cacheUpdated', onIndexMapperCacheUpdate); this.selection.addLocalHook('afterSetRangeEnd', (cellCoords, isLastSelectionLayer) => { const preventScrolling = (0, _object.createObjectPropListener)(false); const selectionRange = this.selection.getSelectedRange(); const { from, to } = selectionRange.current(); const selectionLayerLevel = selectionRange.size() - 1; this.runHooks('afterSelection', from.row, from.col, to.row, to.col, preventScrolling, selectionLayerLevel); this.runHooks('afterSelectionByProp', from.row, instance.colToProp(from.col), to.row, instance.colToProp(to.col), preventScrolling, selectionLayerLevel); if (isLastSelectionLayer && (!preventScrolling.isTouched() || preventScrolling.isTouched() && !preventScrolling.value)) { viewportScroller.scrollTo(cellCoords); } const isSelectedByRowHeader = selection.isSelectedByRowHeader(); const isSelectedByColumnHeader = selection.isSelectedByColumnHeader(); // @TODO: These CSS classes are no longer needed anymore. They are used only as a indicator of the selected // rows/columns in the MergedCells plugin (via border.js#L520 in the walkontable module). After fixing // the Border class this should be removed. if (isSelectedByRowHeader && isSelectedByColumnHeader) { (0, _element.addClass)(this.rootElement, ['ht__selection--rows', 'ht__selection--columns']); } else if (isSelectedByRowHeader) { (0, _element.removeClass)(this.rootElement, 'ht__selection--columns'); (0, _element.addClass)(this.rootElement, 'ht__selection--rows'); } else if (isSelectedByColumnHeader) { (0, _element.removeClass)(this.rootElement, 'ht__selection--rows'); (0, _element.addClass)(this.rootElement, 'ht__selection--columns'); } else { (0, _element.removeClass)(this.rootElement, ['ht__selection--rows', 'ht__selection--columns']); } if (selection.getSelectionSource() !== 'shift') { editorManager.closeEditor(null); } instance.view.render(); editorManager.prepareEditor(); }); this.selection.addLocalHook('beforeSetFocus', cellCoords => { this.runHooks('beforeSelectionFocusSet', cellCoords.row, cellCoords.col); }); this.selection.addLocalHook('afterSetFocus', cellCoords => { const preventScrolling = (0, _object.createObjectPropListener)(false); this.runHooks('afterSelectionFocusSet', cellCoords.row, cellCoords.col, preventScrolling); if (!preventScrolling.isTouched() || preventScrolling.isTouched() && !preventScrolling.value) { viewportScroller.scrollTo(cellCoords); } editorManager.closeEditor(); instance.view.render(); editorManager.prepareEditor(); }); this.selection.addLocalHook('afterSelectionFinished', cellRanges => { const selectionLayerLevel = cellRanges.length - 1; const { from, to } = cellRanges[selectionLayerLevel]; this.runHooks('afterSelectionEnd', from.row, from.col, to.row, to.col, selectionLayerLevel); this.runHooks('afterSelectionEndByProp', from.row, instance.colToProp(from.col), to.row, instance.colToProp(to.col), selectionLayerLevel); }); this.selection.addLocalHook('afterIsMultipleSelection', isMultiple => { const changedIsMultiple = this.runHooks('afterIsMultipleSelection', isMultiple.value); if (isMultiple.value) { isMultiple.value = changedIsMultiple; } }); this.selection.addLocalHook('afterDeselect', () => { editorManager.closeEditor(); instance.view.render(); (0, _element.removeClass)(this.rootElement, ['ht__selection--rows', 'ht__selection--columns']); this.runHooks('afterDeselect'); }); this.selection.addLocalHook('beforeHighlightSet', () => this.runHooks('beforeSelectionHighlightSet')).addLocalHook('beforeSetRangeStart', function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this.runHooks('beforeSetRangeStart', ...args); }).addLocalHook('beforeSetRangeStartOnly', function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this.runHooks('beforeSetRangeStartOnly', ...args); }).addLocalHook('beforeSetRangeEnd', function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this.runHooks('beforeSetRangeEnd', ...args); }).addLocalHook('beforeSelectColumns', function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return _this.runHooks('beforeSelectColumns', ...args); }).addLocalHook('afterSelectColumns', function () { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } return _this.runHooks('afterSelectColumns', ...args); }).addLocalHook('beforeSelectRows', function () { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } return _this.runHooks('beforeSelectRows', ...args); }).addLocalHook('afterSelectRows', function () { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } return _this.runHooks('afterSelectRows', ...args); }).addLocalHook('beforeModifyTransformStart', function () { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } return _this.runHooks('modifyTransformStart', ...args); }).addLocalHook('afterModifyTransformStart', function () { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { args[_key9] = arguments[_key9]; } return _this.runHooks('afterModifyTransformStart', ...args); }).addLocalHook('beforeModifyTransformFocus', function () { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { args[_key10] = arguments[_key10]; } return _this.runHooks('modifyTransformFocus', ...args); }).addLocalHook('afterModifyTransformFocus', function () { for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { args[_key11] = arguments[_key11]; } return _this.runHooks('afterModifyTransformFocus', ...args); }).addLocalHook('beforeModifyTransformEnd', function () { for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { args[_key12] = arguments[_key12]; } return _this.runHooks('modifyTransformEnd', ...args); }).addLocalHook('afterModifyTransformEnd', function () { for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { args[_key13] = arguments[_key13]; } return _this.runHooks('afterModifyTransformEnd', ...args); }).addLocalHook('beforeRowWrap', function () { for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { args[_key14] = arguments[_key14]; } return _this.runHooks('beforeRowWrap', ...args); }).addLocalHook('beforeColumnWrap', function () { for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) { args[_key15] = arguments[_key15]; } return _this.runHooks('beforeColumnWrap', ...args); }).addLocalHook('insertRowRequire', totalRows => this.alter('insert_row_above', totalRows, 1, 'auto')).addLocalHook('insertColRequire', totalCols => this.alter('insert_col_start', totalCols, 1, 'auto')); grid = { /** * Inserts or removes rows and columns. * * @private * @param {string} action Possible values: "insert_row_above", "insert_row_below", "insert_col_start", "insert_col_end", * "remove_row", "remove_col". * @param {number|Array} index Row or column visual index which from the alter action will be triggered. * Alter actions such as "remove_row" and "remove_col" support array indexes in the * format `[[index, amount], [index, amount]...]` this can be used to remove * non-consecutive columns or rows in one call. * @param {number} [amount=1] Amount of rows or columns to remove. * @param {string} [source] Optional. Source of hook runner. * @param {boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. */ alter(action, index) { var _index, _index2; let amount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; let source = arguments.length > 3 ? arguments[3] : undefined; let keepEmptyRows = arguments.length > 4 ? arguments[4] : undefined; const normalizeIndexesGroup = indexes => { if (indexes.length === 0) { return []; } const sortedIndexes = [...indexes]; // Sort the indexes in ascending order. sortedIndexes.sort((_ref2, _ref3) => { let [indexA] = _ref2; let [indexB] = _ref3; if (indexA === indexB) { return 0; } return indexA > indexB ? 1 : -1; }); // Normalize the {index, amount} groups into bigger groups. const normalizedIndexes = (0, _array.arrayReduce)(sortedIndexes, (acc, _ref4) => { let [groupIndex, groupAmount] = _ref4; const previousItem = acc[acc.length - 1]; const [prevIndex, prevAmount] = previousItem; const prevLastIndex = prevIndex + prevAmount; if (groupIndex <= prevLastIndex) { const amountToAdd = Math.max(groupAmount - (prevLastIndex - groupIndex), 0); previousItem[1] += amountToAdd; } else { acc.push([groupIndex, groupAmount]); } return acc; }, [sortedIndexes[0]]); return normalizedIndexes; }; /* eslint-disable no-case-declarations */ switch (action) { case 'insert_row_below': case 'insert_row_above': const numberOfSourceRows = instance.countSourceRows(); if (tableMeta.maxRows === numberOfSourceRows) { return; } // `above` is the default behavior for creating new rows const insertRowMode = action === 'insert_row_below' ? 'below' : 'above'; // Calling the `insert_row_above` action adds a new row at the beginning of the data set. // eslint-disable-next-line no-param-reassign index = (_index = index) !== null && _index !== void 0 ? _index : insertRowMode === 'below' ? numberOfSourceRows : 0; const { delta: rowDelta, startPhysicalIndex: startRowPhysicalIndex } = datamap.createRow(index, amount, { source, mode: insertRowMode }); selection.shiftRows(instance.toVisualRow(startRowPhysicalIndex), rowDelta); break; case 'insert_col_start': case 'insert_col_end': // "start" is a default behavior for creating new columns const insertColumnMode = action === 'insert_col_end' ? 'end' : 'start'; // Calling the `insert_col_start` action adds a new column to the left of the data set. // eslint-disable-next-line no-param-reassign index = (_index2 = index) !== null && _index2 !== void 0 ? _index2 : insertColumnMode === 'end' ? instance.countSourceCols() : 0; const { delta: colDelta, startPhysicalIndex: startColumnPhysicalIndex } = datamap.createCol(index, amount, { source, mode: insertColumnMode }); if (colDelta) { if (Array.isArray(tableMeta.colHeaders)) { const spliceArray = [instance.toVisualColumn(startColumnPhysicalIndex), 0]; spliceArray.length += colDelta; // inserts empty (undefined) elements at the end of an array Array.prototype.splice.apply(tableMeta.colHeaders, spliceArray); // inserts empty (undefined) elements into the colHeader array } selection.shiftColumns(instance.toVisualColumn(startColumnPhysicalIndex), colDelta); } break; case 'remove_row': const removeRow = indexes => { let offset = 0; // Normalize the {index, amount} groups into bigger groups. (0, _array.arrayEach)(indexes, _ref5 => { let [groupIndex, groupAmount] = _ref5; const calcIndex = (0, _mixed.isEmpty)(groupIndex) ? instance.countRows() - 1 : Math.max(groupIndex - offset, 0); // If the 'index' is an integer decrease it by 'offset' otherwise pass it through to make the value // compatible with datamap.removeCol method. if (Number.isInteger(groupIndex)) { // eslint-disable-next-line no-param-reassign groupIndex = Math.max(groupIndex - offset, 0); } // TODO: for datamap.removeRow index should be passed as it is (with undefined and null values). If not, the logic // inside the datamap.removeRow breaks the removing functionality. const wasRemoved = datamap.removeRow(groupIndex, groupAmount, source); if (!wasRemoved) { return; } if (selection.isSelected()) { const { row } = instance.getSelectedRangeLast().highlight; if (row >= groupIndex && row <= groupIndex + groupAmount - 1) { editorManager.closeEditor(true); } } const totalRows = instance.countRows(); if (totalRows === 0) { selection.deselect(); } else if (source === 'ContextMenu.removeRow') { selection.refresh(); } else { selection.shiftRows(groupIndex, -groupAmount); } const fixedRowsTop = tableMeta.fixedRowsTop; if (fixedRowsTop >= calcIndex + 1) { tableMeta.fixedRowsTop -= Math.min(groupAmount, fixedRowsTop - calcIndex); } const fixedRowsBottom = tableMeta.fixedRowsBottom; if (fixedRowsBottom && calcIndex >= totalRows - fixedRowsBottom) { tableMeta.fixedRowsBottom -= Math.min(groupAmount, fixedRowsBottom); } offset += groupAmount; }); }; if (Array.isArray(index)) { removeRow(normalizeIndexesGroup(index)); } else { removeRow([[index, amount]]); } break; case 'remove_col': const removeCol = indexes => { let offset = 0; // Normalize the {index, amount} groups into bigger groups. (0, _array.arrayEach)(indexes, _ref6 => { let [groupIndex, groupAmount] = _ref6; const calcIndex = (0, _mixed.isEmpty)(groupIndex) ? instance.countCols() - 1 : Math.max(groupIndex - offset, 0); let physicalColumnIndex = instance.toPhysicalColumn(calcIndex); // If the 'index' is an integer decrease it by 'offset' otherwise pass it through to make the value // compatible with datamap.removeCol method. if (Number.isInteger(groupIndex)) { // eslint-disable-next-line no-param-reassign groupIndex = Math.max(groupIndex - offset, 0); } // TODO: for datamap.removeCol index should be passed as it is (with undefined and null values). If not, the logic // inside the datamap.removeCol breaks the removing functionality. const wasRemoved = datamap.removeCol(groupIndex, groupAmount, source); if (!wasRemoved) { return; } if (selection.isSelected()) { const { col } = instance.getSelectedRangeLast().highlight; if (col >= groupIndex && col <= groupIndex + groupAmount - 1) { editorManager.closeEditor(true); } } const totalColumns = instance.countCols(); if (totalColumns === 0) { selection.deselect(); } else if (source === 'ContextMenu.removeColumn') { selection.refresh(); } else { selection.shiftColumns(groupIndex, -groupAmount); } const fixedColumnsStart = tableMeta.fixedColumnsStart; if (fixedColumnsStart >= calcIndex + 1) { tableMeta.fixedColumnsStart -= Math.min(groupAmount, fixedColumnsStart - calcIndex); } if (Array.isArray(tableMeta.colHeaders)) { if (typeof physicalColumnIndex === 'undefined') { physicalColumnIndex = -1; } tableMeta.colHeaders.splice(physicalColumnIndex, groupAmount); } offset += groupAmount; }); }; if (Array.isArray(index)) { removeCol(normalizeIndexesGroup(index)); } else { removeCol([[index, amount]]); } break; default: throw new Error(`There is no such action "${action}"`); } instance.view.render(); if (!keepEmptyRows) { grid.adjustRowsAndCols(); // makes sure that we did not add rows that will be removed in next refresh } }, /** * Makes sure there are empty rows at the bottom of the table. * * @private */ adjustRowsAndCols() { const minRows = tableMeta.minRows; const minSpareRows = tableMeta.minSpareRows; const minCols = tableMeta.minCols; const minSpareCols = tableMeta.minSpareCols; if (minRows) { // should I add empty rows to data source to meet minRows? const nrOfRows = instance.countRows(); if (nrOfRows < minRows) { // The synchronization with cell meta is not desired here. For `minRows` option, // we don't want to touch/shift cell meta objects. datamap.createRow(nrOfRows, minRows - nrOfRows, { source: 'auto' }); } } if (minSpareRows) { const emptyRows = instance.countEmptyRows(true); // should I add empty rows to meet minSpareRows? if (emptyRows < minSpareRows) { const emptyRowsMissing = minSpareRows - emptyRows; const rowsToCreate = Math.min(emptyRowsMissing, tableMeta.maxRows - instance.countSourceRows()); // The synchronization with cell meta is not desired here. For `minSpareRows` option, // we don't want to touch/shift cell meta objects. datamap.createRow(instance.countRows(), rowsToCreate, { source: 'auto' }); } } { let emptyCols; // count currently empty cols if (minCols || minSpareCols) { emptyCols = instance.countEmptyCols(true); } let nrOfColumns = instance.countCols(); // should I add empty cols to meet minCols? if (minCols && !tableMeta.columns && nrOfColumns < minCols) { // The synchronization with cell meta is not desired here. For `minSpareRows` option, // we don't want to touch/shift cell meta objects. const colsToCreate = minCols - nrOfColumns; emptyCols += colsToCreate; datamap.createCol(nrOfColumns, colsToCreate, { source: 'auto' }); } // should I add empty cols to meet minSpareCols? if (minSpareCols && !tableMeta.columns && instance.dataType === 'array' && emptyCols < minSpareCols) { nrOfColumns = instance.countCols(); const emptyColsMissing = minSpareCols - emptyCols; const colsToCreate = Math.min(emptyColsMissing, tableMeta.maxCols - nrOfColumns); // The synchronization with cell meta is not desired here. For `minSpareRows` option, // we don't want to touch/shift cell meta objects. datamap.createCol(nrOfColumns, colsToCreate, { source: 'auto' }); } } if (instance.view) { instance.view.adjustElementsSize(); } }, /** * Populate the data from the provided 2d array from the given cell coordinates. * * @private * @param {object} start Start selection position. Visual indexes. * @param {Array} input 2d data array. * @param {object} [end] End selection position (only for drag-down mode). Visual indexes. * @param {string} [source="populateFromArray"] Source information string. * @param {string} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`. * @returns {object|undefined} Ending td in pasted area (only if any cell was changed). */ populateFromArray(start, input, end, source, method) { let r; let rlen; let c; let clen; const setData = []; const current = {}; const newDataByColumns = []; const startRow = start.row; const startColumn = start.col; rlen = input.length; if (rlen === 0) { return false; } let columnsPopulationEnd = 0; let rowsPopulationEnd = 0; if ((0, _object.isObject)(end)) { columnsPopulationEnd = end.col - startColumn + 1; rowsPopulationEnd = end.row - startRow + 1; } // insert data with specified pasteMode method switch (method) { case 'shift_down': // translate data from a list of rows to a list of columns const populatedDataByColumns = (0, _array.pivot)(input); const numberOfDataColumns = populatedDataByColumns.length; // method's argument can extend the range of data population (data would be repeated) const numberOfColumnsToPopulate = Math.max(numberOfDataColumns, columnsPopulationEnd); const pushedDownDataByRows = instance.getData().slice(startRow); // translate data from a list of rows to a list of columns const pushedDownDataByColumns = (0, _array.pivot)(pushedDownDataByRows).slice(startColumn, startColumn + numberOfColumnsToPopulate); for (c = 0; c < numberOfColumnsToPopulate; c += 1) { if (c < numberOfDataColumns) { for (r = 0, rlen = populatedDataByColumns[c].length; r < rowsPopulationEnd - rlen; r += 1) { // repeating data for rows populatedDataByColumns[c].push(populatedDataByColumns[c][r % rlen]); } if (c < pushedDownDataByColumns.length) { newDataByColumns.push(populatedDataByColumns[c].concat(pushedDownDataByColumns[c])); } else { // if before data population, there was no data in the column // we fill the required rows' newly-created cells with `null` values newDataByColumns.push(populatedDataByColumns[c].concat(new Array(pushedDownDataByRows.length).fill(null))); } } else { // Repeating data for columns. newDataByColumns.push(populatedDataByColumns[c % numberOfDataColumns].concat(pushedDownDataByColumns[c])); } } instance.populateFromArray(startRow, startColumn, (0, _array.pivot)(newDataByColumns)); break; case 'shift_right': const numberOfDataRows = input.length; // method's argument can extend the range of data population (data would be repeated) const numberOfRowsToPopulate = Math.max(numberOfDataRows, rowsPopulationEnd); const pushedRightDataByRows = instance.getData().slice(startRow).map(rowData => rowData.slice(startColumn)); for (r = 0; r < numberOfRowsToPopulate; r += 1) { if (r < numberOfDataRows) { for (c = 0, clen = input[r].length; c < columnsPopulationEnd - clen; c += 1) { // repeating data for rows input[r].push(input[r][c % clen]); } if (r < pushedRightDataByRows.length) { for (let i = 0; i < pushedRightDataByRows[r].length; i += 1) { input[r].push(pushedRightDataByRows[r][i]); } } else { // if before data population, there was no data in the row // we fill the required columns' newly-created cells with `null` values input[r].push(...new Array(pushedRightDataByRows[0].length).fill(null)); } } else { // Repeating data for columns. input.push(input[r % rlen].slice(0, numberOfRowsToPopulate).concat(pushedRightDataByRows[r])); } } instance.populateFromArray(startRow, startColumn, input); break; case 'overwrite': default: // overwrite and other not specified options current.row = start.row; current.col = start.col; let skippedRow = 0; let skippedColumn = 0; let pushData = true; let cellMeta; const getInputValue = function getInputValue(row) { let col = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; const rowValue = input[row % input.length]; if (col !== null) { return rowValue[col % rowValue.length]; } return rowValue; }; const rowInputLength = input.length; const rowSelectionLength = end ? end.row - start.row + 1 : 0; if (end) { rlen = rowSelectionLength; } else { rlen = Math.max(rowInputLength, rowSelectionLength); } for (r = 0; r < rlen; r++) { if (end && current.row > end.row && rowSelectionLength > rowInputLength || !tableMeta.allowInsertRow && current.row > instance.countRows() - 1 || current.row >= tableMeta.maxRows) { break; } const visualRow = r - skippedRow; const colInputLength = getInputValue(visualRow).length; const colSelectionLength = end ? end.col - start.col + 1 : 0; if (end) { clen = colSelectionLength; } else { clen = Math.max(colInputLength, colSelectionLength); } current.col = start.col; cellMeta = instance.getCellMeta(current.row, current.col); if ((source === 'CopyPaste.paste' || source === 'Autofill.fill') && cellMeta.skipRowOnPaste) { skippedRow += 1; current.row += 1; rlen += 1; /* eslint-disable no-continue */ continue; } skippedColumn = 0; for (c = 0; c < clen; c++) { if (end && current.col > end.col && colSelectionLength > colInputLength || !tableMeta.allowInsertColumn && current.col > instance.countCols() - 1 || current.col >= tableMeta.maxCols) { break; } cellMeta = instance.getCellMeta(current.row, current.col); if ((source === 'CopyPaste.paste' || source === 'Autofill.fill') && cellMeta.skipColumnOnPaste) { skippedColumn += 1; current.col += 1; clen += 1; continue; } if (cellMeta.readOnly && source !== 'UndoRedo.undo') { current.col += 1; /* eslint-disable no-continue */ continue; } const visualColumn = c - skippedColumn; let value = getInputValue(visualRow, visualColumn); let orgValue = instance.getDataAtCell(current.row, current.col); if (value !== null && typeof value === 'object') { // when 'value' is array and 'orgValue' is null, set 'orgValue' to // an empty array so that the null value can be compared to 'value' // as an empty value for the array context if (Array.isArray(value) && orgValue === null) orgValue = []; if (orgValue === null || typeof orgValue !== 'object') { pushData = false; } else { const orgValueSchema = (0, _object.duckSchema)(Array.isArray(orgValue) ? orgValue : orgValue[0] || orgValue); const valueSchema = (0, _object.duckSchema)(Array.isArray(value) ? value : value[0] || value); // Allow overwriting values with the same object-based schema or any array-based schema. if ((0, _object.isObjectEqual)(orgValueSchema, valueSchema) || Array.isArray(orgValueSchema) && Array.isArray(valueSchema)) { value = (0, _object.deepClone)(value); } else { pushData = false; } } } else if (orgValue !== null && typeof orgValue === 'object') { pushData = false; } if (pushData) { setData.push([current.row, current.col, value]); } pushData = true; current.col += 1; } current.row += 1; } instance.setDataAtCell(setData, null, null, source || 'populateFromArray'); break; } } }; /** * Internal function to set `language` key of settings. * * @private * @param {string} languageCode Language code for specific language i.e. 'en-US', 'pt-BR', 'de-DE'. * @fires Hooks#afterLanguageChange */ function setLanguage(languageCode) { const normalizedLanguageCode = (0, _utils.normalizeLanguageCode)(languageCode); if ((0, _registry5.hasLanguageDictionary)(normalizedLanguageCode)) { instance.runHooks('beforeLanguageChange', normalizedLanguageCode); globalMeta.language = normalizedLanguageCode; instance.runHooks('afterLanguageChange', normalizedLanguageCode); } else { (0, _utils.warnUserAboutLanguageRegistration)(languageCode); } } /** * Internal function to set `className` or `tableClassName`, depending on the key from the settings object. * * @private * @param {string} className `className` or `tableClassName` from the key in the settings object. * @param {string|string[]} classSettings String or array of strings. Contains class name(s) from settings object. */ function setClassName(className, classSettings) { const element = className === 'className' ? instance.rootElement : instance.table; if (firstRun) { (0, _element.addClass)(element, classSettings); } else { let globalMetaSettingsArray = []; let settingsArray = []; if (globalMeta[className]) { globalMetaSettingsArray = Array.isArray(globalMeta[className]) ? globalMeta[className] : (0, _array.stringToArray)(globalMeta[className]); } if (classSettings) { settingsArray = Array.isArray(classSettings) ? classSettings : (0, _array.stringToArray)(classSettings); } const classNameToRemove = (0, _array.getDifferenceOfArrays)(globalMetaSettingsArray, settingsArray); const classNameToAdd = (0, _array.getDifferenceOfArrays)(settingsArray, globalMetaSettingsArray); if (classNameToRemove.length) { (0, _element.removeClass)(element, classNameToRemove); } if (classNameToAdd.length) { (0, _element.addClass)(element, classNameToAdd); } } globalMeta[className] = classSettings; } this.init = function () { dataSource.setData(tableMeta.data); instance.runHooks('beforeInit'); if ((0, _browser.isMobileBrowser)() || (0, _browser.isIpadOS)()) { (0, _element.addClass)(instance.rootElement, 'mobile'); } this.updateSettings(tableMeta, true); this.view = new _tableView.default(this); editorManager = _editorManager.default.getInstance(instance, tableMeta, selection); viewportScroller = (0, _index3.createViewportScroller)(instance); focusManager = new _focusManager.FocusManager(instance); if ((0, _rootInstance.isRootInstance)(this)) { (0, _index3.installFocusCatcher)(instance); } instance.runHooks('init'); this.forceFullRender = true; // used when data was changed this.view.render(); // Run the logic only if it's the table's initialization and the root element is not visible. if (!!firstRun && instance.rootElement.offsetParent === null) { (0, _element.observeVisibilityChangeOnce)(instance.rootElement, () => { // Update the spreader size cache before rendering. instance.view._wt.wtOverlays.updateLastSpreaderSize(); instance.render(); instance.view.adjustElementsSize(); }); } if (typeof firstRun === 'object') { instance.runHooks('afterChange', firstRun[0], firstRun[1]); firstRun = false; } instance.runHooks('afterInit'); }; /** * @ignore * @returns {object} */ function ValidatorsQueue() { // moved this one level up so it can be used in any function here. Probably this should be moved to a separate file let resolved = false; return { validatorsInQueue: 0, valid: true, addValidatorToQueue() { this.validatorsInQueue += 1; resolved = false; }, removeValidatorFormQueue() { this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1; this.checkIfQueueIsEmpty(); }, onQueueEmpty() {}, checkIfQueueIsEmpty() { if (this.validatorsInQueue === 0 && resolved === false) { resolved = true; this.onQueueEmpty(this.valid); } } }; } /** * Get parsed number from numeric string. * * @private * @param {string} numericData Float (separated by a dot or a comma) or integer. * @returns {number} Number if we get data in parsable format, not changed value otherwise. */ function getParsedNumber(numericData) { // Unifying "float like" string. Change from value with comma determiner to value with dot determiner, // for example from `450,65` to `450.65`. const unifiedNumericData = numericData.replace(',', '.'); if (isNaN(parseFloat(unifiedNumericData)) === false) { return parseFloat(unifiedNumericData); } return numericData; } /** * @ignore * @param {Array} changes The 2D array containing information about each of the edited cells. * @param {string} source The string that identifies source of validation. * @param {Function} callback The callback function fot async validation. */ function validateChanges(changes, source, callback) { if (!changes.length) { callback(); return; } const activeEditor = instance.getActiveEditor(); const waitingForValidator = new ValidatorsQueue(); let shouldBeCanceled = true; waitingForValidator.onQueueEmpty = () => { if (activeEditor && shouldBeCanceled) { activeEditor.cancelChanges(); } callback(); // called when async validators are resolved and beforeChange was not async }; for (let i = changes.length - 1; i >= 0; i--) { const [row, prop,, newValue] = changes[i]; const visualCol = datamap.propToCol(prop); let cellProperties; if (Number.isInteger(visualCol)) { cellProperties = instance.getCellMeta(row, visualCol); } else { // If there's no requested visual column, we can use the table meta as the cell properties when retrieving // the cell validator. cellProperties = { ...Object.getPrototypeOf(tableMeta), ...tableMeta }; } if (cellProperties.type === 'numeric' && typeof newValue === 'string' && (0, _number.isNumericLike)(newValue)) { changes[i][3] = getParsedNumber(newValue); } /* eslint-disable no-loop-func */ if (instance.getCellValidator(cellProperties)) { waitingForValidator.addValidatorToQueue(); instance.validateCell(changes[i][3], cellProperties, function (index, cellPropertiesReference) { return function (result) { if (typeof result !== 'boolean') { throw new Error('Validation error: result is not boolean'); } if (result === false && cellPropertiesReference.allowInvalid === false) { shouldBeCanceled = false; changes.splice(index, 1); // cancel the change cellPropertiesReference.valid = true; // we cancelled the change, so cell value is still valid } waitingForValidator.removeValidatorFormQueue(); }; }(i, cellProperties), source); } } waitingForValidator.checkIfQueueIsEmpty(); } /** * Internal function to apply changes. Called after validateChanges. * * @private * @param {Array} changes Array in form of [row, prop, oldValue, newValue]. * @param {string} source String that identifies how this change will be described in changes array (useful in onChange callback). * @fires Hooks#beforeChangeRender * @fires Hooks#afterChange */ function applyChanges(changes, source) { for (let i = changes.length - 1; i >= 0; i--) { let skipThisChange = false; if (changes[i] === null) { changes.splice(i, 1); /* eslint-disable no-continue */ continue; } if ((changes[i][2] === null || changes[i][2] === undefined) && (changes[i][3] === null || changes[i][3] === undefined)) { /* eslint-disable no-continue */ continue; } if (tableMeta.allowInsertRow) { while (changes[i][0] > instance.countRows() - 1) { const { delta: numberOfCreatedRows } = datamap.createRow(undefined, undefined, { source }); if (numberOfCreatedRows === 0) { skipThisChange = true; break; } } } if (instance.dataType === 'array' && (!tableMeta.columns || tableMeta.columns.length === 0) && tableMeta.allowInsertColumn) { while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) { const { delta: numberOfCreatedColumns } = datamap.createCol(undefined, undefined, { source }); if (numberOfCreatedColumns === 0) { skipThisChange = true; break; } } } if (skipThisChange) { /* eslint-disable no-continue */ continue; } datamap.set(changes[i][0], changes[i][1], changes[i][3]); } const hasChanges = changes.length > 0; instance.forceFullRender = true; // used when data was changed or when all cells need to be re-rendered if (hasChanges) { grid.adjustRowsAndCols(); instance.runHooks('beforeChangeRender', changes, source); editorManager.closeEditor(); instance.view.render(); editorManager.prepareEditor(); instance.view.adjustElementsSize(); instance.runHooks('afterChange', changes, source || 'edit'); const activeEditor = instance.getActiveEditor(); if (activeEditor && (0, _mixed.isDefined)(activeEditor.refreshValue)) { activeEditor.refreshValue(); } } else { instance.view.render(); } } /** * Creates and returns the CellCoords object. * * @private * @memberof Core# * @function _createCellCoords * @param {number} row The row index. * @param {number} column The column index. * @returns {CellCoords} */ this._createCellCoords = function (row, column) { return instance.view._wt.createCellCoords(row, column); }; /** * Creates and returns the CellRange object. * * @private * @memberof Core# * @function _createCellRange * @param {CellCoords} highlight Defines the border around a cell where selection was started and to edit the cell * when you press Enter. The highlight cannot point to headers (negative values). * @param {CellCoords} from Initial coordinates. * @param {CellCoords} to Final coordinates. * @returns {CellRange} */ this._createCellRange = function (highlight, from, to) { return instance.view._wt.createCellRange(highlight, from, to); }; /** * Validate a single cell. * * @memberof Core# * @function validateCell * @param {string|number} value The value to validate. * @param {object} cellProperties The cell meta which corresponds with the value. * @param {Function} callback The callback function. * @param {string} source The string that identifies source of the validation. */ this.validateCell = function (value, cellProperties, callback, source) { let validator = instance.getCellValidator(cellProperties); // the `canBeValidated = false` argument suggests, that the cell passes validation by default. /** * @private * @function done * @param {boolean} valid Indicates if the validation was successful. * @param {boolean} [canBeValidated=true] Flag which controls the validation process. */ function done(valid) { let canBeValidated = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; // Fixes GH#3903 if (!canBeValidated || cellProperties.hidden === true) { callback(valid); return; } const col = cellProperties.visualCol; const row = cellProperties.visualRow; const td = instance.getCell(row, col, true); if (td && td.nodeName !== 'TH') { const renderableRow = instance.rowIndexMapper.getRenderableFromVisualIndex(row); const renderableColumn = instance.columnIndexMapper.getRenderableFromVisualIndex(col); instance.view._wt.getSetting('cellRenderer', renderableRow, renderableColumn, td); } callback(valid); } if ((0, _mixed.isRegExp)(validator)) { validator = function (expression) { return function (cellValue, validatorCallback) { validatorCallback(expression.test(cellValue)); }; }(validator); } if ((0, _function.isFunction)(validator)) { // eslint-disable-next-line no-param-reassign value = instance.runHooks('beforeValidate', value, cellProperties.visualRow, cellProperties.prop, source); // To provide consistent behaviour, validation should be always asynchronous instance._registerImmediate(() => { validator.call(cellProperties, value, valid => { if (!instance) { return; } // eslint-disable-next-line no-param-reassign valid = instance.runHooks('afterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source); cellProperties.valid = valid; done(valid); instance.runHooks('postAfterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source); }); }); } else { // resolve callback even if validator function was not found instance._registerImmediate(() => { cellProperties.valid = true; done(cellProperties.valid, false); }); } }; /** * @ignore * @param {number} row The visual row index. * @param {string|number} propOrCol The visual prop or column index. * @param {*} value The cell value. * @returns {Array} */ function setDataInputToArray(row, propOrCol, value) { if (Array.isArray(row)) { // it's an array of changes return row; } return [[row, propOrCol, value]]; } /** * Process changes prepared for applying to the dataset (unifying list of changes, closing an editor - when needed, * calling a hook). * * @private * @param {Array} changes Array of changes in format `[[row, col, value],...]`. * @param {string} [source] String that identifies how this change will be described in the changes array (useful in afterChange or beforeChange callback). Set to 'edit' if left empty. * @returns {Array} List of changes finally applied to the dataset. */ function processChanges(changes, source) { const activeEditor = instance.getActiveEditor(); const beforeChangeResult = instance.runHooks('beforeChange', changes, source || 'edit'); // The `beforeChange` hook could add a `null` for purpose of cancelling some dataset's change. const filteredChanges = changes.filter(change => change !== null); if (beforeChangeResult === false || filteredChanges.length === 0) { if (activeEditor) { activeEditor.cancelChanges(); } return []; } return filteredChanges; } /** * @description * Set new value to a cell. To change many cells at once (recommended way), pass an array of `changes` in format * `[[row, col, value],...]` as the first argument. * * @memberof Core# * @function setDataAtCell * @param {number|Array} row Visual row index or array of changes in format `[[row, col, value],...]`. * @param {number} [column] Visual column index. * @param {string} [value] New value. * @param {string} [source] String that identifies how this change will be described in the changes array (useful in afterChange or beforeChange callback). Set to 'edit' if left empty. */ this.setDataAtCell = function (row, column, value, source) { const input = setDataInputToArray(row, column, value); const changes = []; let changeSource = source; let i; let ilen; let prop; for (i = 0, ilen = input.length; i < ilen; i++) { if (typeof input[i] !== 'object') { throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter'); } if (typeof input[i][1] !== 'number') { throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`'); // eslint-disable-line max-len } if (input[i][1] >= this.countCols()) { prop = input[i][1]; } else { prop = datamap.colToProp(input[i][1]); } changes.push([input[i][0], prop, dataSource.getAtCell(this.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]); } if (!changeSource && typeof row === 'object') { changeSource = column; } const processedChanges = processChanges(changes, source); instance.runHooks('afterSetDataAtCell', processedChanges, changeSource); validateChanges(processedChanges, changeSource, () => { applyChanges(processedChanges, changeSource); }); }; /** * @description * Set new value to a cell. To change many cells at once (recommended way), pass an array of `changes` in format * `[[row, prop, value],...]` as the first argument. * * @memberof Core# * @function setDataAtRowProp * @param {number|Array} row Visual row index or array of changes in format `[[row, prop, value], ...]`. * @param {string} prop Property name or the source string (e.g. `'first.name'` or `'0'`). * @param {string} value Value to be set. * @param {string} [source] String that identifies how this change will be described in changes array (useful in onChange callback). */ this.setDataAtRowProp = function (row, prop, value, source) { const input = setDataInputToArray(row, prop, value); const changes = []; let changeSource = source; let i; let ilen; for (i = 0, ilen = input.length; i < ilen; i++) { changes.push([input[i][0], input[i][1], dataSource.getAtCell(this.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]); } // TODO: I don't think `prop` should be used as `changeSource` here, but removing it would be a breaking change. // We should remove it with the next major release. if (!changeSource && typeof row === 'object') { changeSource = prop; } const processedChanges = processChanges(changes, source); instance.runHooks('afterSetDataAtRowProp', processedChanges, changeSource); validateChanges(processedChanges, changeSource, () => { applyChanges(processedChanges, changeSource); }); }; /** * Listen to the keyboard input on document body. This allows Handsontable to capture keyboard events and respond * in the right way. * * @memberof Core# * @function listen * @fires Hooks#afterListen */ this.listen = function () { if (instance && !instance.isListening()) { foreignHotInstances.forEach(foreignHot => { if (instance !== foreignHot) { foreignHot.unlisten(); } }); activeGuid = instance.guid; instance.runHooks('afterListen'); } }; /** * Stop listening to keyboard input on the document body. Calling this method makes the Handsontable inactive for * any keyboard events. * * @memberof Core# * @function unlisten */ this.unlisten = function () { if (this.isListening()) { activeGuid = null; instance.runHooks('afterUnlisten'); } }; /** * Returns `true` if the current Handsontable instance is listening to keyboard input on document body. * * @memberof Core# * @function isListening * @returns {boolean} `true` if the instance is listening, `false` otherwise. */ this.isListening = function () { return activeGuid === instance.guid; }; /** * Destroys the current editor, render the table and prepares the editor of the newly selected cell. * * @memberof Core# * @function destroyEditor * @param {boolean} [revertOriginal=false] If `true`, the previous value will be restored. Otherwise, the edited value will be saved. * @param {boolean} [prepareEditorIfNeeded=true] If `true` the editor under the selected cell will be prepared to open. */ this.destroyEditor = function () { let revertOriginal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; let prepareEditorIfNeeded = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; editorManager.closeEditor(revertOriginal); instance.view.render(); if (prepareEditorIfNeeded && selection.isSelected()) { editorManager.prepareEditor(); } }; /** * Populates cells at position with 2D input array (e.g. `[[1, 2], [3, 4]]`). Use `endRow`, `endCol` when you * want to cut input when a certain row is reached. * * The `populateFromArray()` method can't change [`readOnly`](@/api/options.md#readonly) cells. * * Optional `method` argument has the same effect as pasteMode option (see {@link Options#pasteMode}). * * @memberof Core# * @function populateFromArray * @param {number} row Start visual row index. * @param {number} column Start visual column index. * @param {Array} input 2d array. * @param {number} [endRow] End visual row index (use when you want to cut input when certain row is reached). * @param {number} [endCol] End visual column index (use when you want to cut input when certain column is reached). * @param {string} [source=populateFromArray] Used to identify this call in the resulting events (beforeChange, afterChange). * @param {string} [method=overwrite] Populate method, possible values: `'shift_down'`, `'shift_right'`, `'overwrite'`. * @returns {object|undefined} Ending td in pasted area (only if any cell was changed). */ this.populateFromArray = function (row, column, input, endRow, endCol, source, method) { if (!(typeof input === 'object' && typeof input[0] === 'object')) { throw new Error('populateFromArray parameter `input` must be an array of arrays'); // API changed in 0.9-beta2, let's check if you use it correctly } const c = typeof endRow === 'number' ? instance._createCellCoords(endRow, endCol) : null; return grid.populateFromArray(instance._createCellCoords(row, column), input, c, source, method); }; /** * Adds/removes data from the column. This method works the same as Array.splice for arrays. * * @memberof Core# * @function spliceCol * @param {number} column Index of the column in which do you want to do splice. * @param {number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed. * @param {...number} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array. * @returns {Array} Returns removed portion of columns. */ this.spliceCol = function (column, index, amount) { for (var _len16 = arguments.length, elements = new Array(_len16 > 3 ? _len16 - 3 : 0), _key16 = 3; _key16 < _len16; _key16++) { elements[_key16 - 3] = arguments[_key16]; } return datamap.spliceCol(column, index, amount, ...elements); }; /** * Adds/removes data from the row. This method works the same as Array.splice for arrays. * * @memberof Core# * @function spliceRow * @param {number} row Index of column in which do you want to do splice. * @param {number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed. * @param {...number} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array. * @returns {Array} Returns removed portion of rows. */ this.spliceRow = function (row, index, amount) { for (var _len17 = arguments.length, elements = new Array(_len17 > 3 ? _len17 - 3 : 0), _key17 = 3; _key17 < _len17; _key17++) { elements[_key17 - 3] = arguments[_key17]; } return datamap.spliceRow(row, index, amount, ...elements); }; /** * Returns indexes of the currently selected cells as an array of arrays `[[startRow, startCol, endRow, endCol],...]`. * * Start row and start column are the coordinates of the active cell (where the selection was started). * * The version 0.36.0 adds a non-consecutive selection feature. Since this version, the method returns an array of arrays. * Additionally to collect the coordinates of the currently selected area (as it was previously done by the method) * you need to use `getSelectedLast` method. * * @memberof Core# * @function getSelected * @returns {Array[]|undefined} An array of arrays of the selection's coordinates. */ this.getSelected = function () { // https://github.com/handsontable/handsontable/issues/44 //cjl if (selection.isSelected()) { return (0, _array.arrayMap)(selection.getSelectedRange(), _ref7 => { let { from, to } = _ref7; return [from.row, from.col, to.row, to.col]; }); } }; /** * Returns the last coordinates applied to the table as a an array `[startRow, startCol, endRow, endCol]`. * * @since 0.36.0 * @memberof Core# * @function getSelectedLast * @returns {Array|undefined} An array of the selection's coordinates. */ this.getSelectedLast = function () { const selected = this.getSelected(); let result; if (selected && selected.length > 0) { result = selected[selected.length - 1]; } return result; }; /** * Returns the current selection as an array of CellRange objects. * * The version 0.36.0 adds a non-consecutive selection feature. Since this version, the method returns an array of arrays. * Additionally to collect the coordinates of the currently selected area (as it was previously done by the method) * you need to use `getSelectedRangeLast` method. * * @memberof Core# * @function getSelectedRange * @returns {CellRange[]|undefined} Selected range object or undefined if there is no selection. */ this.getSelectedRange = function () { // https://github.com/handsontable/handsontable/issues/44 //cjl if (selection.isSelected()) { return Array.from(selection.getSelectedRange()); } }; /** * Returns the last coordinates applied to the table as a CellRange object. * * @memberof Core# * @function getSelectedRangeLast * @since 0.36.0 * @returns {CellRange|undefined} Selected range object or undefined` if there is no selection. */ this.getSelectedRangeLast = function () { const selectedRange = this.getSelectedRange(); let result; if (selectedRange && selectedRange.length > 0) { result = selectedRange[selectedRange.length - 1]; } return result; }; /** * Erases content from cells that have been selected in the table. * * @memberof Core# * @function emptySelectedCells * @param {string} [source] String that identifies how this change will be described in the changes array (useful in afterChange or beforeChange callback). Set to 'edit' if left empty. * @since 0.36.0 */ this.emptySelectedCells = function (source) { if (!selection.isSelected() || this.countRows() === 0 || this.countCols() === 0) { return; } const changes = []; (0, _array.arrayEach)(selection.getSelectedRange(), cellRange => { if (cellRange.isSingleHeader()) { return; } const topStart = cellRange.getTopStartCorner(); const bottomEnd = cellRange.getBottomEndCorner(); (0, _number.rangeEach)(topStart.row, bottomEnd.row, row => { (0, _number.rangeEach)(topStart.col, bottomEnd.col, column => { if (!this.getCellMeta(row, column).readOnly) { changes.push([row, column, null]); } }); }); }); if (changes.length > 0) { this.setDataAtCell(changes, source); } }; /** * Checks if the table rendering process was suspended. See explanation in {@link Core#suspendRender}. * * @memberof Core# * @function isRenderSuspended * @since 8.3.0 * @returns {boolean} */ this.isRenderSuspended = function () { return this.renderSuspendedCounter > 0; }; /** * Suspends the rendering process. It's helpful to wrap the table render * cycles triggered by API calls or UI actions (or both) and call the "render" * once in the end. As a result, it improves the performance of wrapped operations. * When the table is in the suspend state, most operations will have no visual * effect until the rendering state is resumed. Resuming the state automatically * invokes the table rendering. To make sure that after executing all operations, * the table will be rendered, it's highly recommended to use the {@link Core#batchRender} * method or {@link Core#batch}, which additionally aggregates the logic execution * that happens behind the table. * * The method is intended to be used by advanced users. Suspending the rendering * process could cause visual glitches when wrongly implemented. * * Every [`suspendRender()`](@/api/core.md#suspendrender) call needs to correspond with one [`resumeRender()`](@/api/core.md#resumerender) call. * For example, if you call [`suspendRender()`](@/api/core.md#suspendrender) 5 times, you need to call [`resumeRender()`](@/api/core.md#resumerender) 5 times as well. * * @memberof Core# * @function suspendRender * @since 8.3.0 * @example * ```js * hot.suspendRender(); * hot.alter('insert_row_above', 5, 45); * hot.alter('insert_col_start', 10, 40); * hot.setDataAtCell(1, 1, 'John'); * hot.setDataAtCell(2, 2, 'Mark'); * hot.setDataAtCell(3, 3, 'Ann'); * hot.setDataAtCell(4, 4, 'Sophia'); * hot.setDataAtCell(5, 5, 'Mia'); * hot.selectCell(0, 0); * hot.resumeRender(); // It re-renders the table internally * ``` */ this.suspendRender = function () { this.renderSuspendedCounter += 1; }; /** * Resumes the rendering process. In combination with the {@link Core#suspendRender} * method it allows aggregating the table render cycles triggered by API calls or UI * actions (or both) and calls the "render" once in the end. When the table is in * the suspend state, most operations will have no visual effect until the rendering * state is resumed. Resuming the state automatically invokes the table rendering. * * The method is intended to be used by advanced users. Suspending the rendering * process could cause visual glitches when wrongly implemented. * * Every [`suspendRender()`](@/api/core.md#suspendrender) call needs to correspond with one [`resumeRender()`](@/api/core.md#resumerender) call. * For example, if you call [`suspendRender()`](@/api/core.md#suspendrender) 5 times, you need to call [`resumeRender()`](@/api/core.md#resumerender) 5 times as well. * * @memberof Core# * @function resumeRender * @since 8.3.0 * @example * ```js * hot.suspendRender(); * hot.alter('insert_row_above', 5, 45); * hot.alter('insert_col_start', 10, 40); * hot.setDataAtCell(1, 1, 'John'); * hot.setDataAtCell(2, 2, 'Mark'); * hot.setDataAtCell(3, 3, 'Ann'); * hot.setDataAtCell(4, 4, 'Sophia'); * hot.setDataAtCell(5, 5, 'Mia'); * hot.selectCell(0, 0); * hot.resumeRender(); // It re-renders the table internally * ``` */ this.resumeRender = function () { const nextValue = this.renderSuspendedCounter - 1; this.renderSuspendedCounter = Math.max(nextValue, 0); if (!this.isRenderSuspended() && nextValue === this.renderSuspendedCounter) { if (this.renderCall) { this.render(); } else { instance.view.render(); } } }; /** * Rerender the table. Calling this method starts the process of recalculating, redrawing and applying the changes * to the DOM. While rendering the table all cell renderers are recalled. * * Calling this method manually is not recommended. Handsontable tries to render itself by choosing the most * optimal moments in its lifecycle. * * @memberof Core# * @function render */ this.render = function () { if (this.view) { this.renderCall = true; this.forceFullRender = true; // used when data was changed or when all cells need to be re-rendered if (!this.isRenderSuspended()) { instance.view.render(); } } }; /** * The method aggregates multi-line API calls into a callback and postpones the * table rendering process. After the execution of the operations, the table is * rendered once. As a result, it improves the performance of wrapped operations. * Without batching, a similar case could trigger multiple table render calls. * * @memberof Core# * @function batchRender * @param {Function} wrappedOperations Batched operations wrapped in a function. * @returns {*} Returns result from the wrappedOperations callback. * @since 8.3.0 * @example * ```js * hot.batchRender(() => { * hot.alter('insert_row_above', 5, 45); * hot.alter('insert_col_start', 10, 40); * hot.setDataAtCell(1, 1, 'John'); * hot.setDataAtCell(2, 2, 'Mark'); * hot.setDataAtCell(3, 3, 'Ann'); * hot.setDataAtCell(4, 4, 'Sophia'); * hot.setDataAtCell(5, 5, 'Mia'); * hot.selectCell(0, 0); * // The table will be rendered once after executing the callback * }); * ``` */ this.batchRender = function (wrappedOperations) { this.suspendRender(); const result = wrappedOperations(); this.resumeRender(); return result; }; /** * Checks if the table indexes recalculation process was suspended. See explanation * in {@link Core#suspendExecution}. * * @memberof Core# * @function isExecutionSuspended * @since 8.3.0 * @returns {boolean} */ this.isExecutionSuspended = function () { return this.executionSuspendedCounter > 0; }; /** * Suspends the execution process. It's helpful to wrap the table logic changes * such as index changes into one call after which the cache is updated. As a result, * it improves the performance of wrapped operations. * * The method is intended to be used by advanced users. Suspending the execution * process could cause visual glitches caused by not updated the internal table cache. * * @memberof Core# * @function suspendExecution * @since 8.3.0 * @example * ```js * hot.suspendExecution(); * const filters = hot.getPlugin('filters'); * * filters.addCondition(2, 'contains', ['3']); * filters.filter(); * hot.getPlugin('columnSorting').sort({ column: 1, sortOrder: 'desc' }); * hot.resumeExecution(); // It updates the cache internally * ``` */ this.suspendExecution = function () { this.executionSuspendedCounter += 1; this.columnIndexMapper.suspendOperations(); this.rowIndexMapper.suspendOperations(); }; /** * Resumes the execution process. In combination with the {@link Core#suspendExecution} * method it allows aggregating the table logic changes after which the cache is * updated. Resuming the state automatically invokes the table cache updating process. * * The method is intended to be used by advanced users. Suspending the execution * process could cause visual glitches caused by not updated the internal table cache. * * @memberof Core# * @function resumeExecution * @param {boolean} [forceFlushChanges=false] If `true`, the table internal data cache * is recalculated after the execution of the batched operations. For nested * {@link Core#batchExecution} calls, it can be desire to recalculate the table * after each batch. * @since 8.3.0 * @example * ```js * hot.suspendExecution(); * const filters = hot.getPlugin('filters'); * * filters.addCondition(2, 'contains', ['3']); * filters.filter(); * hot.getPlugin('columnSorting').sort({ column: 1, sortOrder: 'desc' }); * hot.resumeExecution(); // It updates the cache internally * ``` */ this.resumeExecution = function () { let forceFlushChanges = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; const nextValue = this.executionSuspendedCounter - 1; this.executionSuspendedCounter = Math.max(nextValue, 0); if (!this.isExecutionSuspended() && nextValue === this.executionSuspendedCounter || forceFlushChanges) { this.columnIndexMapper.resumeOperations(); this.rowIndexMapper.resumeOperations(); } }; /** * The method aggregates multi-line API calls into a callback and postpones the * table execution process. After the execution of the operations, the internal table * cache is recalculated once. As a result, it improves the performance of wrapped * operations. Without batching, a similar case could trigger multiple table cache rebuilds. * * @memberof Core# * @function batchExecution * @param {Function} wrappedOperations Batched operations wrapped in a function. * @param {boolean} [forceFlushChanges=false] If `true`, the table internal data cache * is recalculated after the execution of the batched operations. For nested calls, * it can be a desire to recalculate the table after each batch. * @returns {*} Returns result from the wrappedOperations callback. * @since 8.3.0 * @example * ```js * hot.batchExecution(() => { * const filters = hot.getPlugin('filters'); * * filters.addCondition(2, 'contains', ['3']); * filters.filter(); * hot.getPlugin('columnSorting').sort({ column: 1, sortOrder: 'desc' }); * // The table cache will be recalculated once after executing the callback * }); * ``` */ this.batchExecution = function (wrappedOperations) { let forceFlushChanges = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; this.suspendExecution(); const result = wrappedOperations(); this.resumeExecution(forceFlushChanges); return result; }; /** * It batches the rendering process and index recalculations. The method aggregates * multi-line API calls into a callback and postpones the table rendering process * as well aggregates the table logic changes such as index changes into one call * after which the cache is updated. After the execution of the operations, the * table is rendered, and the cache is updated once. As a result, it improves the * performance of wrapped operations. * * @memberof Core# * @function batch * @param {Function} wrappedOperations Batched operations wrapped in a function. * @returns {*} Returns result from the wrappedOperations callback. * @since 8.3.0 * @example * ```js * hot.batch(() => { * hot.alter('insert_row_above', 5, 45); * hot.alter('insert_col_start', 10, 40); * hot.setDataAtCell(1, 1, 'x'); * hot.setDataAtCell(2, 2, 'c'); * hot.setDataAtCell(3, 3, 'v'); * hot.setDataAtCell(4, 4, 'b'); * hot.setDataAtCell(5, 5, 'n'); * hot.selectCell(0, 0); * * const filters = hot.getPlugin('filters'); * * filters.addCondition(2, 'contains', ['3']); * filters.filter(); * hot.getPlugin('columnSorting').sort({ column: 1, sortOrder: 'desc' }); * // The table will be re-rendered and cache will be recalculated once after executing the callback * }); * ``` */ this.batch = function (wrappedOperations) { this.suspendRender(); this.suspendExecution(); const result = wrappedOperations(); this.resumeExecution(); this.resumeRender(); return result; }; /** * Updates dimensions of the table. The method compares previous dimensions with the current ones and updates accordingly. * * @memberof Core# * @function refreshDimensions * @fires Hooks#beforeRefreshDimensions * @fires Hooks#afterRefreshDimensions */ this.refreshDimensions = function () { if (!instance.view) { return; } const { width: lastWidth, height: lastHeight } = instance.view.getLastSize(); const { width, height } = instance.rootElement.getBoundingClientRect(); const isSizeChanged = width !== lastWidth || height !== lastHeight; const isResizeBlocked = instance.runHooks('beforeRefreshDimensions', { width: lastWidth, height: lastHeight }, { width, height }, isSizeChanged) === false; if (isResizeBlocked) { return; } if (isSizeChanged || instance.view._wt.wtOverlays.scrollableElement === instance.rootWindow) { instance.view.setLastSize(width, height); instance.render(); } instance.runHooks('afterRefreshDimensions', { width: lastWidth, height: lastHeight }, { width, height }, isSizeChanged); }; /** * The `updateData()` method replaces Handsontable's [`data`](@/api/options.md#data) with a new dataset. * * The `updateData()` method: * - Keeps cells' states (e.g. cells' [formatting](@/guides/cell-features/formatting-cells/formatting-cells.md) and cells' [`readOnly`](@/api/options.md#readonly) states) * - Keeps rows' states (e.g. row order) * - Keeps columns' states (e.g. column order) * * To replace Handsontable's [`data`](@/api/options.md#data) and reset states, use the [`loadData()`](#loaddata) method. * * Read more: * - [Binding to data](@/guides/getting-started/binding-to-data/binding-to-data.md) * - [Saving data](@/guides/getting-started/saving-data/saving-data.md) * * @memberof Core# * @function updateData * @since 11.1.0 * @param {Array} data An [array of arrays](@/guides/getting-started/binding-to-data/binding-to-data.md#array-of-arrays), or an [array of objects](@/guides/getting-started/binding-to-data/binding-to-data.md#array-of-objects), that contains Handsontable's data * @param {string} [source] The source of the `updateData()` call * @fires Hooks#beforeUpdateData * @fires Hooks#afterUpdateData * @fires Hooks#afterChange */ this.updateData = function (data, source) { (0, _dataMap.replaceData)(data, newDataMap => { datamap = newDataMap; }, newDataMap => { datamap = newDataMap; instance.columnIndexMapper.fitToLength(this.getInitialColumnCount()); instance.rowIndexMapper.fitToLength(this.countSourceRows()); grid.adjustRowsAndCols(); selection.refresh(); }, { hotInstance: instance, dataMap: datamap, dataSource, internalSource: 'updateData', source, metaManager, firstRun }); }; /** * The `loadData()` method replaces Handsontable's [`data`](@/api/options.md#data) with a new dataset. * * Additionally, the `loadData()` method: * - Resets cells' states (e.g. cells' [formatting](@/guides/cell-features/formatting-cells/formatting-cells.md) and cells' [`readOnly`](@/api/options.md#readonly) states) * - Resets rows' states (e.g. row order) * - Resets columns' states (e.g. column order) * * To replace Handsontable's [`data`](@/api/options.md#data) without resetting states, use the [`updateData()`](#updatedata) method. * * Read more: * - [Binding to data](@/guides/getting-started/binding-to-data/binding-to-data.md) * - [Saving data](@/guides/getting-started/saving-data/saving-data.md) * * @memberof Core# * @function loadData * @param {Array} data An [array of arrays](@/guides/getting-started/binding-to-data/binding-to-data.md#array-of-arrays), or an [array of objects](@/guides/getting-started/binding-to-data/binding-to-data.md#array-of-objects), that contains Handsontable's data * @param {string} [source] The source of the `loadData()` call * @fires Hooks#beforeLoadData * @fires Hooks#afterLoadData * @fires Hooks#afterChange */ this.loadData = function (data, source) { (0, _dataMap.replaceData)(data, newDataMap => { datamap = newDataMap; }, () => { metaManager.clearCellsCache(); instance.initIndexMappers(); grid.adjustRowsAndCols(); selection.refresh(); if (firstRun) { firstRun = [null, 'loadData']; } }, { hotInstance: instance, dataMap: datamap, dataSource, internalSource: 'loadData', source, metaManager, firstRun }); }; /** * Gets the initial column count, calculated based on the `columns` setting. * * @private * @returns {number} The calculated number of columns. */ this.getInitialColumnCount = function () { const columnsSettings = tableMeta.columns; let finalNrOfColumns = 0; // We will check number of columns when the `columns` property was defined as an array. Columns option may // narrow down or expand displayed dataset in that case. if (Array.isArray(columnsSettings)) { finalNrOfColumns = columnsSettings.length; } else if ((0, _function.isFunction)(columnsSettings)) { if (instance.dataType === 'array') { const nrOfSourceColumns = this.countSourceCols(); for (let columnIndex = 0; columnIndex < nrOfSourceColumns; columnIndex += 1) { if (columnsSettings(columnIndex)) { finalNrOfColumns += 1; } } // Extended dataset by the `columns` property? Moved code right from the refactored `countCols` method. } else if (instance.dataType === 'object' || instance.dataType === 'function') { finalNrOfColumns = datamap.colToPropCache.length; } // In some cases we need to check columns length from the schema, i.e. `data` may be empty. } else if ((0, _mixed.isDefined)(tableMeta.dataSchema)) { const schema = datamap.getSchema(); // Schema may be defined as an array of objects. Each object will define column. finalNrOfColumns = Array.isArray(schema) ? schema.length : (0, _object.deepObjectSize)(schema); } else { // We init index mappers by length of source data to provide indexes also for skipped indexes. finalNrOfColumns = this.countSourceCols(); } return finalNrOfColumns; }; /** * Init index mapper which manage indexes assigned to the data. * * @private */ this.initIndexMappers = function () { this.columnIndexMapper.initToLength(this.getInitialColumnCount()); this.rowIndexMapper.initToLength(this.countSourceRows()); }; /** * Returns the current data object (the same one that was passed by `data` configuration option or `loadData` method, * unless some modifications have been applied (i.e. Sequence of rows/columns was changed, some row/column was skipped). * If that's the case - use the {@link Core#getSourceData} method.). * * Optionally you can provide cell range by defining `row`, `column`, `row2`, `column2` to get only a fragment of table data. * * @memberof Core# * @function getData * @param {number} [row] From visual row index. * @param {number} [column] From visual column index. * @param {number} [row2] To visual row index. * @param {number} [column2] To visual column index. * @returns {Array[]} Array with the data. * @example * ```js * // Get all data (in order how it is rendered in the table). * hot.getData(); * // Get data fragment (from top-left 0, 0 to bottom-right 3, 3). * hot.getData(3, 3); * // Get data fragment (from top-left 2, 1 to bottom-right 3, 3). * hot.getData(2, 1, 3, 3); * ``` */ this.getData = function (row, column, row2, column2) { if ((0, _mixed.isUndefined)(row)) { return datamap.getAll(); } return datamap.getRange(instance._createCellCoords(row, column), instance._createCellCoords(row2, column2), datamap.DESTINATION_RENDERER); }; /** * Returns a string value of the selected range. Each column is separated by tab, each row is separated by a new * line character. * * @memberof Core# * @function getCopyableText * @param {number} startRow From visual row index. * @param {number} startCol From visual column index. * @param {number} endRow To visual row index. * @param {number} endCol To visual column index. * @returns {string} */ this.getCopyableText = function (startRow, startCol, endRow, endCol) { return datamap.getCopyableText(instance._createCellCoords(startRow, startCol), instance._createCellCoords(endRow, endCol)); }; /** * Returns the data's copyable value at specified `row` and `column` index. * * @memberof Core# * @function getCopyableData * @param {number} row Visual row index. * @param {number} column Visual column index. * @returns {string} */ this.getCopyableData = function (row, column) { return datamap.getCopyable(row, datamap.colToProp(column)); }; /** * Returns schema provided by constructor settings. If it doesn't exist then it returns the schema based on the data * structure in the first row. * * @memberof Core# * @function getSchema * @returns {object} Schema object. */ this.getSchema = function () { return datamap.getSchema(); }; /** * Use it if you need to change configuration after initialization. The `settings` argument is an object containing the changed * settings, declared the same way as in the initial settings object. * * __Note__, that although the `updateSettings` method doesn't overwrite the previously declared settings, it might reset * the settings made post-initialization. (for example - ignore changes made using the columnResize feature). * * Since 8.0.0 passing `columns` or `data` inside `settings` objects will result in resetting states corresponding to rows and columns * (for example, row/column sequence, column width, row height, frozen columns etc.). * * Since 12.0.0 passing `data` inside `settings` objects no longer results in resetting states corresponding to rows and columns * (for example, row/column sequence, column width, row height, frozen columns etc.). * * @memberof Core# * @function updateSettings * @param {object} settings A settings object (see {@link Options}). Only provide the settings that are changed, not the whole settings object that was used for initialization. * @param {boolean} [init=false] Internally used for in initialization mode. * @example * ```js * hot.updateSettings({ * contextMenu: true, * colHeaders: true, * fixedRowsTop: 2 * }); * ``` * @fires Hooks#afterCellMetaReset * @fires Hooks#afterUpdateSettings */ this.updateSettings = function (settings) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; const dataUpdateFunction = (firstRun ? instance.loadData : instance.updateData).bind(this); let columnsAsFunc = false; let i; let j; if ((0, _mixed.isDefined)(settings.rows)) { throw new Error('The "rows" setting is no longer supported. Do you mean startRows, minRows or maxRows?'); } if ((0, _mixed.isDefined)(settings.cols)) { throw new Error('The "cols" setting is no longer supported. Do you mean startCols, minCols or maxCols?'); } if ((0, _mixed.isDefined)(settings.ganttChart)) { throw new Error('Since 8.0.0 the "ganttChart" setting is no longer supported.'); } // eslint-disable-next-line no-restricted-syntax for (i in settings) { if (i === 'data') { // Do nothing. loadData will be triggered later } else if (i === 'language') { setLanguage(settings.language); } else if (i === 'className') { setClassName('className', settings.className); } else if (i === 'tableClassName' && instance.table) { setClassName('tableClassName', settings.tableClassName); instance.view._wt.wtOverlays.syncOverlayTableClassNames(); } else if (_pluginHooks.default.getSingleton().isRegistered(i) || _pluginHooks.default.getSingleton().isDeprecated(i)) { if ((0, _function.isFunction)(settings[i]) || Array.isArray(settings[i])) { settings[i].initialHook = true; instance.addHook(i, settings[i]); } } else if (!init && (0, _object.hasOwnProperty)(settings, i)) { // Update settings globalMeta[i] = settings[i]; } } // Load data or create data map if (settings.data === undefined && tableMeta.data === undefined) { dataUpdateFunction(null, 'updateSettings'); // data source created just now } else if (settings.data !== undefined) { dataUpdateFunction(settings.data, 'updateSettings'); // data source given as option } else if (settings.columns !== undefined) { datamap.createMap(); // The `column` property has changed - dataset may be expanded or narrowed down. The `loadData` do the same. instance.initIndexMappers(); } const clen = instance.countCols(); const columnSetting = tableMeta.columns; // Init columns constructors configuration if (columnSetting && (0, _function.isFunction)(columnSetting)) { columnsAsFunc = true; } // Clear cell meta cache if (settings.cell !== undefined || settings.cells !== undefined || settings.columns !== undefined) { metaManager.clearCache(); } if (clen > 0) { for (i = 0, j = 0; i < clen; i++) { // Use settings provided by user if (columnSetting) { const column = columnsAsFunc ? columnSetting(i) : columnSetting[j]; if (column) { metaManager.updateColumnMeta(j, column); } } j += 1; } } if ((0, _mixed.isDefined)(settings.cell)) { (0, _object.objectEach)(settings.cell, cell => { instance.setCellMetaObject(cell.row, cell.col, cell); }); } instance.runHooks('afterCellMetaReset'); let currentHeight = instance.rootElement.style.height; if (currentHeight !== '') { currentHeight = parseInt(instance.rootElement.style.height, 10); } let height = settings.height; if ((0, _function.isFunction)(height)) { height = height(); } if (init) { const initialStyle = instance.rootElement.getAttribute('style'); if (initialStyle) { instance.rootElement.setAttribute('data-initialstyle', instance.rootElement.getAttribute('style')); } } if (height === null) { const initialStyle = instance.rootElement.getAttribute('data-initialstyle'); if (initialStyle && (initialStyle.indexOf('height') > -1 || initialStyle.indexOf('overflow') > -1)) { instance.rootElement.setAttribute('style', initialStyle); } else { instance.rootElement.style.height = ''; instance.rootElement.style.overflow = ''; } } else if (height !== undefined) { instance.rootElement.style.height = isNaN(height) ? `${height}` : `${height}px`; instance.rootElement.style.overflow = 'hidden'; } if (typeof settings.width !== 'undefined') { let width = settings.width; if ((0, _function.isFunction)(width)) { width = width(); } instance.rootElement.style.width = isNaN(width) ? `${width}` : `${width}px`; } if (!init) { if (instance.view) { instance.view._wt.wtViewport.resetHasOversizedColumnHeadersMarked(); instance.view._wt.exportSettingsAsClassNames(); } instance.runHooks('afterUpdateSettings', settings); } grid.adjustRowsAndCols(); if (instance.view && !firstRun) { instance.forceFullRender = true; // used when data was changed instance.view.render(); instance.view._wt.wtOverlays.adjustElementsSize(); } if (!init && instance.view && (currentHeight === '' || height === '' || height === undefined) && currentHeight !== height) { instance.view._wt.wtOverlays.updateMainScrollableElements(); } }; /** * Gets the value of the currently focused cell. * * For column headers and row headers, returns `null`. * * @memberof Core# * @function getValue * @returns {*} The value of the focused cell. */ this.getValue = function () { const sel = instance.getSelectedLast(); if (tableMeta.getValue) { if ((0, _function.isFunction)(tableMeta.getValue)) { return tableMeta.getValue.call(instance); } else if (sel) { return instance.getData()[sel[0][0]][tableMeta.getValue]; } } else if (sel) { return instance.getDataAtCell(sel[0], sel[1]); } }; /** * Returns the object settings. * * @memberof Core# * @function getSettings * @returns {TableMeta} Object containing the current table settings. */ this.getSettings = function () { return tableMeta; }; /** * Clears the data from the table (the table settings remain intact). * * @memberof Core# * @function clear */ this.clear = function () { this.selectAll(); this.emptySelectedCells(); }; /** * The `alter()` method lets you alter the grid's structure * by adding or removing rows and columns at specified positions. * * ::: tip * If you use an array of objects in your [`data`](@/api/options.md#data), the column-related actions won't work. * ::: * * ```js * // above row 10 (by visual index), insert 1 new row * hot.alter('insert_row_above', 10); * ``` * * | Action | With `index` | Without `index` | * | -------------------- | ------------ | --------------- | * | `'insert_row_above'` | Inserts rows above the `index` row. | Inserts rows above the first row. | * | `'insert_row_below'` | Inserts rows below the `index` row. | Inserts rows below the last row. | * | `'remove_row'` | Removes rows, starting from the `index` row. | Removes rows, starting from the last row. | * | `'insert_col_start'` | Inserts columns before the `index` column. | Inserts columns before the first column. | * | `'insert_col_end'` | Inserts columns after the `index` column. | Inserts columns after the last column. | * | `'remove_col'` | Removes columns, starting from the `index` column. | Removes columns, starting from the last column. | * * Additional information about `'insert_col_start'` and `'insert_col_end'`: * - Their behavior depends on your [`layoutDirection`](@/api/options.md#layoutdirection). * - If the provided `index` is higher than the actual number of columns, Handsontable doesn't generate * the columns missing in between. Instead, the new columns are inserted next to the last column. * * @memberof Core# * @function alter * @param {string} action Available operations: *
    *
  • `'insert_row_above'`
  • *
  • `'insert_row_below'`
  • *
  • `'remove_row'`
  • *
  • `'insert_col_start'`
  • *
  • `'insert_col_end'`
  • *
  • `'remove_col'`
  • *
* @param {number|number[]} [index] A visual index of the row/column before or after which the new row/column will be * inserted or removed. Can also be an array of arrays, in format `[[index, amount],...]`. * @param {number} [amount] The amount of rows or columns to be inserted or removed (default: `1`). * @param {string} [source] Source indicator. * @param {boolean} [keepEmptyRows] If set to `true`: prevents removing empty rows. * @example * ```js * // above row 10 (by visual index), insert 1 new row * hot.alter('insert_row_above', 10); * * // below row 10 (by visual index), insert 3 new rows * hot.alter('insert_row_below', 10, 3); * * // in the LTR layout direction: to the left of column 10 (by visual index), insert 3 new columns * // in the RTL layout direction: to the right of column 10 (by visual index), insert 3 new columns * hot.alter('insert_col_start', 10, 3); * * // in the LTR layout direction: to the right of column 10 (by visual index), insert 1 new column * // in the RTL layout direction: to the left of column 10 (by visual index), insert 1 new column * hot.alter('insert_col_end', 10); * * // remove 2 rows, starting from row 10 (by visual index) * hot.alter('remove_row', 10, 2); * * // remove 3 rows, starting from row 1 (by visual index) * // remove 2 rows, starting from row 5 (by visual index) * hot.alter('remove_row', [[1, 3], [5, 2]]); * ``` */ this.alter = function (action, index, amount, source, keepEmptyRows) { grid.alter(action, index, amount, source, keepEmptyRows); }; /** * Returns a TD element for the given `row` and `column` arguments, if it is rendered on screen. * Returns `null` if the TD is not rendered on screen (probably because that part of the table is not visible). * * @memberof Core# * @function getCell * @param {number} row Visual row index. * @param {number} column Visual column index. * @param {boolean} [topmost=false] If set to `true`, it returns the TD element from the topmost overlay. For example, * if the wanted cell is in the range of fixed rows, it will return a TD element from the `top` overlay. * @returns {HTMLTableCellElement|null} The cell's TD element. */ this.getCell = function (row, column) { let topmost = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; let renderableColumnIndex = column; // Handling also column headers. let renderableRowIndex = row; // Handling also row headers. if (column >= 0) { if (this.columnIndexMapper.isHidden(this.toPhysicalColumn(column))) { return null; } renderableColumnIndex = this.columnIndexMapper.getRenderableFromVisualIndex(column); } if (row >= 0) { if (this.rowIndexMapper.isHidden(this.toPhysicalRow(row))) { return null; } renderableRowIndex = this.rowIndexMapper.getRenderableFromVisualIndex(row); } if (renderableRowIndex === null || renderableColumnIndex === null || renderableRowIndex === undefined || renderableColumnIndex === undefined) { return null; } return instance.view.getCellAtCoords(instance._createCellCoords(renderableRowIndex, renderableColumnIndex), topmost); }; /** * Returns the coordinates of the cell, provided as a HTML table cell element. * * @memberof Core# * @function getCoords * @param {HTMLTableCellElement} element The HTML Element representing the cell. * @returns {CellCoords|null} Visual coordinates object. * @example * ```js * hot.getCoords(hot.getCell(1, 1)); * // it returns CellCoords object instance with props row: 1 and col: 1. * ``` */ this.getCoords = function (element) { const renderableCoords = this.view._wt.wtTable.getCoords(element); if (renderableCoords === null) { return null; } const { row: renderableRow, col: renderableColumn } = renderableCoords; let visualRow = renderableRow; let visualColumn = renderableColumn; if (renderableRow >= 0) { visualRow = this.rowIndexMapper.getVisualFromRenderableIndex(renderableRow); } if (renderableColumn >= 0) { visualColumn = this.columnIndexMapper.getVisualFromRenderableIndex(renderableColumn); } return instance._createCellCoords(visualRow, visualColumn); }; /** * Returns the property name that corresponds with the given column index. * If the data source is an array of arrays, it returns the columns index. * * @memberof Core# * @function colToProp * @param {number} column Visual column index. * @returns {string|number} Column property or physical column index. */ this.colToProp = function (column) { return datamap.colToProp(column); }; /** * Returns column index that corresponds with the given property. * * @memberof Core# * @function propToCol * @param {string|number} prop Property name or physical column index. * @returns {number} Visual column index. */ this.propToCol = function (prop) { return datamap.propToCol(prop); }; /** * Translate physical row index into visual. * * This method is useful when you want to retrieve visual row index which can be reordered, moved or trimmed * based on a physical index. * * @memberof Core# * @function toVisualRow * @param {number} row Physical row index. * @returns {number} Returns visual row index. */ this.toVisualRow = row => this.rowIndexMapper.getVisualFromPhysicalIndex(row); /** * Translate physical column index into visual. * * This method is useful when you want to retrieve visual column index which can be reordered, moved or trimmed * based on a physical index. * * @memberof Core# * @function toVisualColumn * @param {number} column Physical column index. * @returns {number} Returns visual column index. */ this.toVisualColumn = column => this.columnIndexMapper.getVisualFromPhysicalIndex(column); /** * Translate visual row index into physical. * * This method is useful when you want to retrieve physical row index based on a visual index which can be * reordered, moved or trimmed. * * @memberof Core# * @function toPhysicalRow * @param {number} row Visual row index. * @returns {number} Returns physical row index. */ this.toPhysicalRow = row => this.rowIndexMapper.getPhysicalFromVisualIndex(row); /** * Translate visual column index into physical. * * This method is useful when you want to retrieve physical column index based on a visual index which can be * reordered, moved or trimmed. * * @memberof Core# * @function toPhysicalColumn * @param {number} column Visual column index. * @returns {number} Returns physical column index. */ this.toPhysicalColumn = column => this.columnIndexMapper.getPhysicalFromVisualIndex(column); /** * @description * Returns the cell value at `row`, `column`. * * __Note__: If data is reordered, sorted or trimmed, the currently visible order will be used. * * @memberof Core# * @function getDataAtCell * @param {number} row Visual row index. * @param {number} column Visual column index. * @returns {*} Data at cell. */ this.getDataAtCell = function (row, column) { return datamap.get(row, datamap.colToProp(column)); }; /** * Returns value at visual `row` and `prop` indexes. * * __Note__: If data is reordered, sorted or trimmed, the currently visible order will be used. * * @memberof Core# * @function getDataAtRowProp * @param {number} row Visual row index. * @param {string} prop Property name. * @returns {*} Cell value. */ this.getDataAtRowProp = function (row, prop) { return datamap.get(row, prop); }; /** * @description * Returns array of column values from the data source. * * __Note__: If columns were reordered or sorted, the currently visible order will be used. * * @memberof Core# * @function getDataAtCol * @param {number} column Visual column index. * @returns {Array} Array of cell values. */ this.getDataAtCol = function (column) { const columnData = []; const dataByRows = datamap.getRange(instance._createCellCoords(0, column), instance._createCellCoords(tableMeta.data.length - 1, column), datamap.DESTINATION_RENDERER); for (let i = 0; i < dataByRows.length; i += 1) { for (let j = 0; j < dataByRows[i].length; j += 1) { columnData.push(dataByRows[i][j]); } } return columnData; }; /** * Given the object property name (e.g. `'first.name'` or `'0'`), returns an array of column's values from the table data. * You can also provide a column index as the first argument. * * @memberof Core# * @function getDataAtProp * @param {string|number} prop Property name or physical column index. * @returns {Array} Array of cell values. */ // TODO: Getting data from `datamap` should work on visual indexes. this.getDataAtProp = function (prop) { const columnData = []; const dataByRows = datamap.getRange(instance._createCellCoords(0, datamap.propToCol(prop)), instance._createCellCoords(tableMeta.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER); for (let i = 0; i < dataByRows.length; i += 1) { for (let j = 0; j < dataByRows[i].length; j += 1) { columnData.push(dataByRows[i][j]); } } return columnData; }; /** * Returns a clone of the source data object. * Optionally you can provide a cell range by using the `row`, `column`, `row2`, `column2` arguments, to get only a * fragment of the table data. * * __Note__: This method does not participate in data transformation. If the visual data of the table is reordered, * sorted or trimmed only physical indexes are correct. * * __Note__: This method may return incorrect values for cells that contain * [formulas](@/guides/formulas/formula-calculation/formula-calculation.md). This is because `getSourceData()` * operates on source data ([physical indexes](@/api/indexMapper.md)), * whereas formulas operate on visual data (visual indexes). * * @memberof Core# * @function getSourceData * @param {number} [row] From physical row index. * @param {number} [column] From physical column index (or visual index, if data type is an array of objects). * @param {number} [row2] To physical row index. * @param {number} [column2] To physical column index (or visual index, if data type is an array of objects). * @returns {Array[]|object[]} The table data. */ this.getSourceData = function (row, column, row2, column2) { let data; if (row === undefined) { data = dataSource.getData(); } else { data = dataSource.getByRange(instance._createCellCoords(row, column), instance._createCellCoords(row2, column2)); } return data; }; /** * Returns the source data object as an arrays of arrays format even when source data was provided in another format. * Optionally you can provide a cell range by using the `row`, `column`, `row2`, `column2` arguments, to get only a * fragment of the table data. * * __Note__: This method does not participate in data transformation. If the visual data of the table is reordered, * sorted or trimmed only physical indexes are correct. * * @memberof Core# * @function getSourceDataArray * @param {number} [row] From physical row index. * @param {number} [column] From physical column index (or visual index, if data type is an array of objects). * @param {number} [row2] To physical row index. * @param {number} [column2] To physical column index (or visual index, if data type is an array of objects). * @returns {Array} An array of arrays. */ this.getSourceDataArray = function (row, column, row2, column2) { let data; if (row === undefined) { data = dataSource.getData(true); } else { data = dataSource.getByRange(instance._createCellCoords(row, column), instance._createCellCoords(row2, column2), true); } return data; }; /** * Returns an array of column values from the data source. * * @memberof Core# * @function getSourceDataAtCol * @param {number} column Visual column index. * @returns {Array} Array of the column's cell values. */ // TODO: Getting data from `sourceData` should work always on physical indexes. this.getSourceDataAtCol = function (column) { return dataSource.getAtColumn(column); }; /* eslint-disable jsdoc/require-param */ /** * Set the provided value in the source data set at the provided coordinates. * * @memberof Core# * @function setSourceDataAtCell * @param {number|Array} row Physical row index or array of changes in format `[[row, prop, value], ...]`. * @param {number|string} column Physical column index / prop name. * @param {*} value The value to be set at the provided coordinates. * @param {string} [source] Source of the change as a string. */ /* eslint-enable jsdoc/require-param */ this.setSourceDataAtCell = function (row, column, value, source) { const input = setDataInputToArray(row, column, value); const isThereAnySetSourceListener = this.hasHook('afterSetSourceDataAtCell'); const changesForHook = []; if (isThereAnySetSourceListener) { (0, _array.arrayEach)(input, _ref8 => { let [changeRow, changeProp, changeValue] = _ref8; changesForHook.push([changeRow, changeProp, dataSource.getAtCell(changeRow, changeProp), // The previous value. changeValue]); }); } (0, _array.arrayEach)(input, _ref9 => { let [changeRow, changeProp, changeValue] = _ref9; dataSource.setAtCell(changeRow, changeProp, changeValue); }); if (isThereAnySetSourceListener) { this.runHooks('afterSetSourceDataAtCell', changesForHook, source); } this.render(); const activeEditor = instance.getActiveEditor(); if (activeEditor && (0, _mixed.isDefined)(activeEditor.refreshValue)) { activeEditor.refreshValue(); } }; /** * Returns a single row of the data (array or object, depending on what data format you use). * * __Note__: This method does not participate in data transformation. If the visual data of the table is reordered, * sorted or trimmed only physical indexes are correct. * * @memberof Core# * @function getSourceDataAtRow * @param {number} row Physical row index. * @returns {Array|object} Single row of data. */ this.getSourceDataAtRow = function (row) { return dataSource.getAtRow(row); }; /** * Returns a single value from the data source. * * @memberof Core# * @function getSourceDataAtCell * @param {number} row Physical row index. * @param {number} column Visual column index. * @returns {*} Cell data. */ // TODO: Getting data from `sourceData` should work always on physical indexes. this.getSourceDataAtCell = function (row, column) { return dataSource.getAtCell(row, column); }; /** * @description * Returns a single row of the data. * * __Note__: If rows were reordered, sorted or trimmed, the currently visible order will be used. * * @memberof Core# * @function getDataAtRow * @param {number} row Visual row index. * @returns {Array} Array of row's cell data. */ this.getDataAtRow = function (row) { const data = datamap.getRange(instance._createCellCoords(row, 0), instance._createCellCoords(row, this.countCols() - 1), datamap.DESTINATION_RENDERER); return data[0] || []; }; /** * @description * Returns a data type defined in the Handsontable settings under the `type` key ({@link Options#type}). * If there are cells with different types in the selected range, it returns `'mixed'`. * * __Note__: If data is reordered, sorted or trimmed, the currently visible order will be used. * * @memberof Core# * @function getDataType * @param {number} rowFrom From visual row index. * @param {number} columnFrom From visual column index. * @param {number} rowTo To visual row index. * @param {number} columnTo To visual column index. * @returns {string} Cell type (e.q: `'mixed'`, `'text'`, `'numeric'`, `'autocomplete'`). */ this.getDataType = function (rowFrom, columnFrom, rowTo, columnTo) { const coords = rowFrom === undefined ? [0, 0, this.countRows(), this.countCols()] : [rowFrom, columnFrom, rowTo, columnTo]; const [rowStart, columnStart] = coords; let [,, rowEnd, columnEnd] = coords; let previousType = null; let currentType = null; if (rowEnd === undefined) { rowEnd = rowStart; } if (columnEnd === undefined) { columnEnd = columnStart; } let type = 'mixed'; (0, _number.rangeEach)(Math.max(Math.min(rowStart, rowEnd), 0), Math.max(rowStart, rowEnd), row => { let isTypeEqual = true; (0, _number.rangeEach)(Math.max(Math.min(columnStart, columnEnd), 0), Math.max(columnStart, columnEnd), column => { const cellType = this.getCellMeta(row, column); currentType = cellType.type; if (previousType) { isTypeEqual = previousType === currentType; } else { previousType = currentType; } return isTypeEqual; }); type = isTypeEqual ? currentType : 'mixed'; return isTypeEqual; }); return type; }; /** * Remove a property defined by the `key` argument from the cell meta object for the provided `row` and `column` coordinates. * * @memberof Core# * @function removeCellMeta * @param {number} row Visual row index. * @param {number} column Visual column index. * @param {string} key Property name. * @fires Hooks#beforeRemoveCellMeta * @fires Hooks#afterRemoveCellMeta */ this.removeCellMeta = function (row, column, key) { const [physicalRow, physicalColumn] = [this.toPhysicalRow(row), this.toPhysicalColumn(column)]; let cachedValue = metaManager.getCellMetaKeyValue(physicalRow, physicalColumn, key); const hookResult = instance.runHooks('beforeRemoveCellMeta', row, column, key, cachedValue); if (hookResult !== false) { metaManager.removeCellMeta(physicalRow, physicalColumn, key); instance.runHooks('afterRemoveCellMeta', row, column, key, cachedValue); } cachedValue = null; }; /** * Removes or adds one or more rows of the cell meta objects to the cell meta collections. * * @since 0.30.0 * @memberof Core# * @function spliceCellsMeta * @param {number} visualIndex A visual index that specifies at what position to add/remove items. * @param {number} [deleteAmount=0] The number of items to be removed. If set to 0, no cell meta objects will be removed. * @param {...object} [cellMetaRows] The new cell meta row objects to be added to the cell meta collection. */ this.spliceCellsMeta = function (visualIndex) { let deleteAmount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; for (var _len18 = arguments.length, cellMetaRows = new Array(_len18 > 2 ? _len18 - 2 : 0), _key18 = 2; _key18 < _len18; _key18++) { cellMetaRows[_key18 - 2] = arguments[_key18]; } if (cellMetaRows.length > 0 && !Array.isArray(cellMetaRows[0])) { throw new Error('The 3rd argument (cellMetaRows) has to be passed as an array of cell meta objects array.'); } if (deleteAmount > 0) { metaManager.removeRow(this.toPhysicalRow(visualIndex), deleteAmount); } if (cellMetaRows.length > 0) { (0, _array.arrayEach)(cellMetaRows.reverse(), cellMetaRow => { metaManager.createRow(this.toPhysicalRow(visualIndex)); (0, _array.arrayEach)(cellMetaRow, (cellMeta, columnIndex) => this.setCellMetaObject(visualIndex, columnIndex, cellMeta)); }); } instance.render(); }; /** * Set cell meta data object defined by `prop` to the corresponding params `row` and `column`. * * @memberof Core# * @function setCellMetaObject * @param {number} row Visual row index. * @param {number} column Visual column index. * @param {object} prop Meta object. */ this.setCellMetaObject = function (row, column, prop) { if (typeof prop === 'object') { (0, _object.objectEach)(prop, (value, key) => { this.setCellMeta(row, column, key, value); }); } }; /** * Sets a property defined by the `key` property to the meta object of a cell corresponding to params `row` and `column`. * * @memberof Core# * @function setCellMeta * @param {number} row Visual row index. * @param {number} column Visual column index. * @param {string} key Property name. * @param {string} value Property value. * @fires Hooks#beforeSetCellMeta * @fires Hooks#afterSetCellMeta */ this.setCellMeta = function (row, column, key, value) { const allowSetCellMeta = instance.runHooks('beforeSetCellMeta', row, column, key, value); if (allowSetCellMeta === false) { return; } let physicalRow = row; let physicalColumn = column; if (row < this.countRows()) { physicalRow = this.toPhysicalRow(row); } if (column < this.countCols()) { physicalColumn = this.toPhysicalColumn(column); } metaManager.setCellMeta(physicalRow, physicalColumn, key, value); instance.runHooks('afterSetCellMeta', row, column, key, value); }; /** * Get all the cells meta settings at least once generated in the table (in order of cell initialization). * * @memberof Core# * @function getCellsMeta * @returns {Array} Returns an array of ColumnSettings object instances. */ this.getCellsMeta = function () { return metaManager.getCellsMeta(); }; /** * Returns the cell properties object for the given `row` and `column` coordinates. * * @memberof Core# * @function getCellMeta * @param {number} row Visual row index. * @param {number} column Visual column index. * @returns {object} The cell properties object. * @fires Hooks#beforeGetCellMeta * @fires Hooks#afterGetCellMeta */ this.getCellMeta = function (row, column) { let physicalRow = this.toPhysicalRow(row); let physicalColumn = this.toPhysicalColumn(column); if (physicalRow === null) { physicalRow = row; } if (physicalColumn === null) { physicalColumn = column; } return metaManager.getCellMeta(physicalRow, physicalColumn, { visualRow: row, visualColumn: column }); }; /** * Returns the meta information for the provided column. * * @since 14.5.0 * @memberof Core# * @function getColumnMeta * @param {number} column Visual column index. * @returns {object} */ this.getColumnMeta = function (column) { return metaManager.getColumnMeta(this.toPhysicalColumn(column)); }; /** * Returns an array of cell meta objects for specified physical row index. * * @memberof Core# * @function getCellMetaAtRow * @param {number} row Physical row index. * @returns {Array} */ this.getCellMetaAtRow = function (row) { return metaManager.getCellsMetaAtRow(row); }; /** * Checks if your [data format](@/guides/getting-started/binding-to-data/binding-to-data.md#compatible-data-types) * and [configuration options](@/guides/getting-started/configuration-options/configuration-options.md) * allow for changing the number of columns. * * Returns `false` when your data is an array of objects, * or when you use the [`columns`](@/api/options.md#columns) option. * Otherwise, returns `true`. * * @memberof Core# * @function isColumnModificationAllowed * @returns {boolean} */ this.isColumnModificationAllowed = function () { return !(instance.dataType === 'object' || tableMeta.columns); }; /** * Returns the cell renderer function by given `row` and `column` arguments. * * @memberof Core# * @function getCellRenderer * @param {number|object} rowOrMeta Visual row index or cell meta object (see {@link Core#getCellMeta}). * @param {number} column Visual column index. * @returns {Function} Returns the renderer function. * @example * ```js * // Get cell renderer using `row` and `column` coordinates. * hot.getCellRenderer(1, 1); * // Get cell renderer using cell meta object. * hot.getCellRenderer(hot.getCellMeta(1, 1)); * ``` */ this.getCellRenderer = function (rowOrMeta, column) { const cellRenderer = typeof rowOrMeta === 'number' ? instance.getCellMeta(rowOrMeta, column).renderer : rowOrMeta.renderer; if (typeof cellRenderer === 'string') { return (0, _registry2.getRenderer)(cellRenderer); } return (0, _mixed.isUndefined)(cellRenderer) ? (0, _registry2.getRenderer)('text') : cellRenderer; }; /** * Returns the cell editor class by the provided `row` and `column` arguments. * * @memberof Core# * @function getCellEditor * @param {number} rowOrMeta Visual row index or cell meta object (see {@link Core#getCellMeta}). * @param {number} column Visual column index. * @returns {Function|boolean} Returns the editor class or `false` is cell editor is disabled. * @example * ```js * // Get cell editor class using `row` and `column` coordinates. * hot.getCellEditor(1, 1); * // Get cell editor class using cell meta object. * hot.getCellEditor(hot.getCellMeta(1, 1)); * ``` */ this.getCellEditor = function (rowOrMeta, column) { const cellEditor = typeof rowOrMeta === 'number' ? instance.getCellMeta(rowOrMeta, column).editor : rowOrMeta.editor; if (typeof cellEditor === 'string') { return (0, _registry3.getEditor)(cellEditor); } return (0, _mixed.isUndefined)(cellEditor) ? (0, _registry3.getEditor)('text') : cellEditor; }; /** * Returns the cell validator by `row` and `column`. * * @memberof Core# * @function getCellValidator * @param {number|object} rowOrMeta Visual row index or cell meta object (see {@link Core#getCellMeta}). * @param {number} column Visual column index. * @returns {Function|RegExp|undefined} The validator function. * @example * ```js * // Get cell validator using `row` and `column` coordinates. * hot.getCellValidator(1, 1); * // Get cell validator using cell meta object. * hot.getCellValidator(hot.getCellMeta(1, 1)); * ``` */ this.getCellValidator = function (rowOrMeta, column) { const cellValidator = typeof rowOrMeta === 'number' ? instance.getCellMeta(rowOrMeta, column).validator : rowOrMeta.validator; if (typeof cellValidator === 'string') { return (0, _registry4.getValidator)(cellValidator); } return cellValidator; }; /** * Validates every cell in the data set, * using a [validator function](@/guides/cell-functions/cell-validator/cell-validator.md) configured for each cell. * * Doesn't validate cells that are currently [trimmed](@/guides/rows/row-trimming/row-trimming.md), * [hidden](@/guides/rows/row-hiding/row-hiding.md), or [filtered](@/guides/columns/column-filter/column-filter.md), * as such cells are not included in the data set until you bring them back again. * * After the validation, the `callback` function is fired, with the `valid` argument set to: * - `true` for valid cells * - `false` for invalid cells * * @memberof Core# * @function validateCells * @param {Function} [callback] The callback function. * @example * ```js * hot.validateCells((valid) => { * if (valid) { * // ... code for validated cells * } * }) * ``` */ this.validateCells = function (callback) { this._validateCells(callback); }; /** * Validates rows using their validator functions and calls callback when finished. * * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it * would equal `true`. * * @memberof Core# * @function validateRows * @param {Array} [rows] Array of validation target visual row indexes. * @param {Function} [callback] The callback function. * @example * ```js * hot.validateRows([3, 4, 5], (valid) => { * if (valid) { * // ... code for validated rows * } * }) * ``` */ this.validateRows = function (rows, callback) { if (!Array.isArray(rows)) { throw new Error('validateRows parameter `rows` must be an array'); } this._validateCells(callback, rows); }; /** * Validates columns using their validator functions and calls callback when finished. * * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it * would equal `true`. * * @memberof Core# * @function validateColumns * @param {Array} [columns] Array of validation target visual columns indexes. * @param {Function} [callback] The callback function. * @example * ```js * hot.validateColumns([3, 4, 5], (valid) => { * if (valid) { * // ... code for validated columns * } * }) * ``` */ this.validateColumns = function (columns, callback) { if (!Array.isArray(columns)) { throw new Error('validateColumns parameter `columns` must be an array'); } this._validateCells(callback, undefined, columns); }; /** * Validates all cells using their validator functions and calls callback when finished. * * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`. * * Private use intended. * * @private * @memberof Core# * @function _validateCells * @param {Function} [callback] The callback function. * @param {Array} [rows] An array of validation target visual row indexes. * @param {Array} [columns] An array of validation target visual column indexes. */ this._validateCells = function (callback, rows, columns) { const waitingForValidator = new ValidatorsQueue(); if (callback) { waitingForValidator.onQueueEmpty = callback; } let i = instance.countRows() - 1; while (i >= 0) { if (rows !== undefined && rows.indexOf(i) === -1) { i -= 1; continue; } let j = instance.countCols() - 1; while (j >= 0) { if (columns !== undefined && columns.indexOf(j) === -1) { j -= 1; continue; } waitingForValidator.addValidatorToQueue(); instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), result => { if (typeof result !== 'boolean') { throw new Error('Validation error: result is not boolean'); } if (result === false) { waitingForValidator.valid = false; } waitingForValidator.removeValidatorFormQueue(); }, 'validateCells'); j -= 1; } i -= 1; } waitingForValidator.checkIfQueueIsEmpty(); }; /** * Returns an array of row headers' values (if they are enabled). If param `row` was given, it returns the header of the given row as a string. * * @memberof Core# * @function getRowHeader * @param {number} [row] Visual row index. * @fires Hooks#modifyRowHeader * @returns {Array|string|number} Array of header values / single header value. */ this.getRowHeader = function (row) { let rowHeader = tableMeta.rowHeaders; let physicalRow = row; if (physicalRow !== undefined) { physicalRow = instance.runHooks('modifyRowHeader', physicalRow); } if (physicalRow === undefined) { rowHeader = []; (0, _number.rangeEach)(instance.countRows() - 1, i => { rowHeader.push(instance.getRowHeader(i)); }); } else if (Array.isArray(rowHeader) && rowHeader[physicalRow] !== undefined) { rowHeader = rowHeader[physicalRow]; } else if ((0, _function.isFunction)(rowHeader)) { rowHeader = rowHeader(physicalRow); } else if (rowHeader && typeof rowHeader !== 'string' && typeof rowHeader !== 'number') { rowHeader = physicalRow + 1; } return rowHeader; }; /** * Returns information about if this table is configured to display row headers. * * @memberof Core# * @function hasRowHeaders * @returns {boolean} `true` if the instance has the row headers enabled, `false` otherwise. */ this.hasRowHeaders = function () { return !!tableMeta.rowHeaders; }; /** * Returns information about if this table is configured to display column headers. * * @memberof Core# * @function hasColHeaders * @returns {boolean} `true` if the instance has the column headers enabled, `false` otherwise. */ this.hasColHeaders = function () { if (tableMeta.colHeaders !== undefined && tableMeta.colHeaders !== null) { // Polymer has empty value = null return !!tableMeta.colHeaders; } for (let i = 0, ilen = instance.countCols(); i < ilen; i++) { if (instance.getColHeader(i)) { return true; } } return false; }; /** * Gets the values of column headers (if column headers are [enabled](@/api/options.md#colheaders)). * * To get an array with the values of all * [bottom-most](@/guides/cell-features/clipboard/clipboard.md#copy-with-headers) column headers, * call `getColHeader()` with no arguments. * * To get the value of the bottom-most header of a specific column, use the `column` parameter. * * To get the value of a [specific-level](@/guides/columns/column-groups/column-groups.md) header * of a specific column, use the `column` and `headerLevel` parameters. * * Read more: * - [Guides: Column groups](@/guides/columns/column-groups/column-groups.md) * - [Options: `colHeaders`](@/api/options.md#colheaders) * - [Guides: Copy with headers](@/guides/cell-features/clipboard/clipboard.md#copy-with-headers) * * ```js * // get the contents of all bottom-most column headers * hot.getColHeader(); * * // get the contents of the bottom-most header of a specific column * hot.getColHeader(5); * * // get the contents of a specific column header at a specific level * hot.getColHeader(5, -2); * ``` * * @memberof Core# * @function getColHeader * @param {number} [column] A visual column index. * @param {number} [headerLevel=-1] (Since 12.3.0) Header level index. Accepts positive (0 to n) * and negative (-1 to -n) values. For positive values, 0 points to the * topmost header. For negative values, -1 points to the bottom-most * header (the header closest to the cells). * @fires Hooks#modifyColHeader * @fires Hooks#modifyColumnHeaderValue * @returns {Array|string|number} Column header values. */ this.getColHeader = function (column) { let headerLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; const columnIndex = instance.runHooks('modifyColHeader', column); if (columnIndex === undefined) { const out = []; const ilen = instance.countCols(); for (let i = 0; i < ilen; i++) { out.push(instance.getColHeader(i)); } return out; } let result = tableMeta.colHeaders; const translateVisualIndexToColumns = function (visualColumnIndex) { const arr = []; const columnsLen = instance.countCols(); let index = 0; for (; index < columnsLen; index++) { if ((0, _function.isFunction)(tableMeta.columns) && tableMeta.columns(index)) { arr.push(index); } } return arr[visualColumnIndex]; }; const physicalColumn = instance.toPhysicalColumn(columnIndex); const prop = translateVisualIndexToColumns(physicalColumn); if (tableMeta.colHeaders === false) { result = null; } else if (tableMeta.columns && (0, _function.isFunction)(tableMeta.columns) && tableMeta.columns(prop) && tableMeta.columns(prop).title) { result = tableMeta.columns(prop).title; } else if (tableMeta.columns && tableMeta.columns[physicalColumn] && tableMeta.columns[physicalColumn].title) { result = tableMeta.columns[physicalColumn].title; } else if (Array.isArray(tableMeta.colHeaders) && tableMeta.colHeaders[physicalColumn] !== undefined) { result = tableMeta.colHeaders[physicalColumn]; } else if ((0, _function.isFunction)(tableMeta.colHeaders)) { result = tableMeta.colHeaders(physicalColumn); } else if (tableMeta.colHeaders && typeof tableMeta.colHeaders !== 'string' && typeof tableMeta.colHeaders !== 'number') { result = (0, _data.spreadsheetColumnLabel)(columnIndex); // see #1458 } result = instance.runHooks('modifyColumnHeaderValue', result, column, headerLevel); return result; }; /** * Return column width from settings (no guessing). Private use intended. * * @private * @memberof Core# * @function _getColWidthFromSettings * @param {number} col Visual col index. * @returns {number} */ this._getColWidthFromSettings = function (col) { let width; // We currently don't support cell meta objects for headers (negative values) if (col >= 0) { const cellProperties = instance.getCellMeta(0, col); width = cellProperties.width; } if (width === undefined || width === tableMeta.width) { width = tableMeta.colWidths; } if (width !== undefined && width !== null) { switch (typeof width) { case 'object': // array width = width[col]; break; case 'function': width = width(col); break; default: break; } if (typeof width === 'string') { width = parseInt(width, 10); } } return width; }; /** * Returns the width of the requested column. * * @memberof Core# * @function getColWidth * @param {number} column Visual column index. * @returns {number} Column width. * @fires Hooks#modifyColWidth */ this.getColWidth = function (column) { let width = instance._getColWidthFromSettings(column); width = instance.runHooks('modifyColWidth', width, column); if (width === undefined) { width = _src.DEFAULT_COLUMN_WIDTH; } return width; }; /** * Return row height from settings (no guessing). Private use intended. * * @private * @memberof Core# * @function _getRowHeightFromSettings * @param {number} row Visual row index. * @returns {number} */ this._getRowHeightFromSettings = function (row) { let height = tableMeta.rowHeights; if (height !== undefined && height !== null) { switch (typeof height) { case 'object': // array height = height[row]; break; case 'function': height = height(row); break; default: break; } if (typeof height === 'string') { height = parseInt(height, 10); } } return height; }; /** * Returns a row's height, as recognized by Handsontable. * * Depending on your configuration, the method returns (in order of priority): * 1. The row height set by the [`ManualRowResize`](@/api/manualRowResize.md) plugin * (if the plugin is enabled). * 2. The row height set by the [`rowHeights`](@/api/options.md#rowheights) configuration option * (if the option is set). * 3. The row height as measured in the DOM by the [`AutoRowSize`](@/api/autoRowSize.md) plugin * (if the plugin is enabled). * 4. `undefined`, if neither [`ManualRowResize`](@/api/manualRowResize.md), * nor [`rowHeights`](@/api/options.md#rowheights), * nor [`AutoRowSize`](@/api/autoRowSize.md) is used. * * The height returned includes 1 px of the row's bottom border. * * Mind that this method is different from the * [`getRowHeight()`](@/api/autoRowSize.md#getrowheight) method * of the [`AutoRowSize`](@/api/autoRowSize.md) plugin. * * @memberof Core# * @function getRowHeight * @param {number} row A visual row index. * @returns {number|undefined} The height of the specified row, in pixels. * @fires Hooks#modifyRowHeight */ this.getRowHeight = function (row) { let height = instance._getRowHeightFromSettings(row); height = instance.runHooks('modifyRowHeight', height, row); return height; }; /** * Returns the total number of rows in the data source. * * @memberof Core# * @function countSourceRows * @returns {number} Total number of rows. */ this.countSourceRows = function () { return dataSource.countRows(); }; /** * Returns the total number of columns in the data source. * * @memberof Core# * @function countSourceCols * @returns {number} Total number of columns. */ this.countSourceCols = function () { return dataSource.countFirstRowKeys(); }; /** * Returns the total number of visual rows in the table. * * @memberof Core# * @function countRows * @returns {number} Total number of rows. */ this.countRows = function () { return datamap.getLength(); }; /** * Returns the total number of visible columns in the table. * * @memberof Core# * @function countCols * @returns {number} Total number of columns. */ this.countCols = function () { const maxCols = tableMeta.maxCols; const dataLen = this.columnIndexMapper.getNotTrimmedIndexesLength(); return Math.min(maxCols, dataLen); }; /** * Returns the number of rendered rows including rows that are partially or fully rendered * outside the table viewport. * * @memberof Core# * @function countRenderedRows * @returns {number} Returns -1 if table is not visible. */ this.countRenderedRows = function () { return instance.view._wt.drawn ? instance.view._wt.wtTable.getRenderedRowsCount() : -1; }; /** * Returns the number of rendered rows that are only visible in the table viewport. * The rows that are partially visible are not counted. * * @memberof Core# * @function countVisibleRows * @returns {number} Number of visible rows or -1. */ this.countVisibleRows = function () { return instance.view._wt.drawn ? instance.view._wt.wtTable.getVisibleRowsCount() : -1; }; /** * Returns the number of rendered rows including columns that are partially or fully rendered * outside the table viewport. * * @memberof Core# * @function countRenderedCols * @returns {number} Returns -1 if table is not visible. */ this.countRenderedCols = function () { return instance.view._wt.drawn ? instance.view._wt.wtTable.getRenderedColumnsCount() : -1; }; /** * Returns the number of rendered columns that are only visible in the table viewport. * The columns that are partially visible are not counted. * * @memberof Core# * @function countVisibleCols * @returns {number} Number of visible columns or -1. */ this.countVisibleCols = function () { return instance.view._wt.drawn ? instance.view._wt.wtTable.getVisibleColumnsCount() : -1; }; /** * Returns the number of rendered row headers. * * @since 14.0.0 * @memberof Core# * @function countRowHeaders * @returns {number} Number of row headers. */ this.countRowHeaders = function () { return this.view.getRowHeadersCount(); }; /** * Returns the number of rendered column headers. * * @since 14.0.0 * @memberof Core# * @function countColHeaders * @returns {number} Number of column headers. */ this.countColHeaders = function () { return this.view.getColumnHeadersCount(); }; /** * Returns the number of empty rows. If the optional ending parameter is `true`, returns the * number of empty rows at the bottom of the table. * * @memberof Core# * @function countEmptyRows * @param {boolean} [ending=false] If `true`, will only count empty rows at the end of the data source. * @returns {number} Count empty rows. */ this.countEmptyRows = function () { let ending = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; let emptyRows = 0; (0, _number.rangeEachReverse)(instance.countRows() - 1, visualIndex => { if (instance.isEmptyRow(visualIndex)) { emptyRows += 1; } else if (ending === true) { return false; } }); return emptyRows; }; /** * Returns the number of empty columns. If the optional ending parameter is `true`, returns the number of empty * columns at right hand edge of the table. * * @memberof Core# * @function countEmptyCols * @param {boolean} [ending=false] If `true`, will only count empty columns at the end of the data source row. * @returns {number} Count empty cols. */ this.countEmptyCols = function () { let ending = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; let emptyColumns = 0; (0, _number.rangeEachReverse)(instance.countCols() - 1, visualIndex => { if (instance.isEmptyCol(visualIndex)) { emptyColumns += 1; } else if (ending === true) { return false; } }); return emptyColumns; }; /** * Check if all cells in the row declared by the `row` argument are empty. * * @memberof Core# * @function isEmptyRow * @param {number} row Visual row index. * @returns {boolean} `true` if the row at the given `row` is empty, `false` otherwise. */ this.isEmptyRow = function (row) { return tableMeta.isEmptyRow.call(instance, row); }; /** * Check if all cells in the the column declared by the `column` argument are empty. * * @memberof Core# * @function isEmptyCol * @param {number} column Column index. * @returns {boolean} `true` if the column at the given `col` is empty, `false` otherwise. */ this.isEmptyCol = function (column) { return tableMeta.isEmptyCol.call(instance, column); }; /** * Select a single cell, or a single range of adjacent cells. * * To select a cell, pass its visual row and column indexes, for example: `selectCell(2, 4)`. * * To select a range, pass the visual indexes of the first and last cell in the range, for example: `selectCell(2, 4, 3, 5)`. * * If your columns have properties, you can pass those properties' values instead of column indexes, for example: `selectCell(2, 'first_name')`. * * By default, `selectCell()` also: * - Scrolls the viewport to the newly-selected cells. * - Switches the keyboard focus to Handsontable (by calling Handsontable's [`listen()`](#listen) method). * * @example * ```js * // select a single cell * hot.selectCell(2, 4); * * // select a range of cells * hot.selectCell(2, 4, 3, 5); * * // select a single cell, using a column property * hot.selectCell(2, 'first_name'); * * // select a range of cells, using column properties * hot.selectCell(2, 'first_name', 3, 'last_name'); * * // select a range of cells, without scrolling to them * hot.selectCell(2, 4, 3, 5, false); * * // select a range of cells, without switching the keyboard focus to Handsontable * hot.selectCell(2, 4, 3, 5, null, false); * ``` * * @memberof Core# * @function selectCell * @param {number} row A visual row index. * @param {number|string} column A visual column index (`number`), or a column property's value (`string`). * @param {number} [endRow] If selecting a range: the visual row index of the last cell in the range. * @param {number|string} [endColumn] If selecting a range: the visual column index (or a column property's value) of the last cell in the range. * @param {boolean} [scrollToCell=true] `true`: scroll the viewport to the newly-selected cells. `false`: keep the previous viewport. * @param {boolean} [changeListener=true] `true`: switch the keyboard focus to Handsontable. `false`: keep the previous keyboard focus. * @returns {boolean} `true`: the selection was successful, `false`: the selection failed. */ this.selectCell = function (row, column, endRow, endColumn) { let scrollToCell = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; let changeListener = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true; if ((0, _mixed.isUndefined)(row) || (0, _mixed.isUndefined)(column)) { return false; } return this.selectCells([[row, column, endRow, endColumn]], scrollToCell, changeListener); }; /** * Select multiple cells or ranges of cells, adjacent or non-adjacent. * * You can pass one of the below: * - An array of arrays (which matches the output of Handsontable's [`getSelected()`](#getselected) method). * - An array of [`CellRange`](@/api/cellRange.md) objects (which matches the output of Handsontable's [`getSelectedRange()`](#getselectedrange) method). * * To select multiple cells, pass the visual row and column indexes of each cell, for example: `hot.selectCells([[1, 1], [5, 5]])`. * * To select multiple ranges, pass the visual indexes of the first and last cell in each range, for example: `hot.selectCells([[1, 1, 2, 2], [6, 2, 0, 2]])`. * * If your columns have properties, you can pass those properties' values instead of column indexes, for example: `hot.selectCells([[1, 'first_name'], [5, 'last_name']])`. * * By default, `selectCell()` also: * - Scrolls the viewport to the newly-selected cells. * - Switches the keyboard focus to Handsontable (by calling Handsontable's [`listen()`](#listen) method). * * @example * ```js * // select non-adjacent cells * hot.selectCells([[1, 1], [5, 5], [10, 10]]); * * // select non-adjacent ranges of cells * hot.selectCells([[1, 1, 2, 2], [10, 10, 20, 20]]); * * // select cells and ranges of cells * hot.selectCells([[1, 1, 2, 2], [3, 3], [6, 2, 0, 2]]); * * // select cells, using column properties * hot.selectCells([[1, 'id', 2, 'first_name'], [3, 'full_name'], [6, 'last_name', 0, 'first_name']]); * * // select multiple ranges, using an array of `CellRange` objects * const selected = hot.getSelectedRange(); * * selected[0].from.row = 0; * selected[0].from.col = 0; * selected[0].to.row = 5; * selected[0].to.col = 5; * * selected[1].from.row = 10; * selected[1].from.col = 10; * selected[1].to.row = 20; * selected[1].to.col = 20; * * hot.selectCells(selected); * ``` * * @memberof Core# * @since 0.38.0 * @function selectCells * @param {Array[]|CellRange[]} coords Visual coordinates, * passed either as an array of arrays (`[[rowStart, columnStart, rowEnd, columnEnd], ...]`) * or as an array of [`CellRange`](@/api/cellRange.md) objects. * @param {boolean} [scrollToCell=true] `true`: scroll the viewport to the newly-selected cells. `false`: keep the previous viewport. * @param {boolean} [changeListener=true] `true`: switch the keyboard focus to Handsontable. `false`: keep the previous keyboard focus. * @returns {boolean} `true`: the selection was successful, `false`: the selection failed. */ this.selectCells = function () { let coords = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [[]]; let scrollToCell = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; let changeListener = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (scrollToCell === false) { viewportScroller.suspend(); } const wasSelected = selection.selectCells(coords); if (wasSelected && changeListener) { instance.listen(); } viewportScroller.resume(); return wasSelected; }; /** * Select column specified by `startColumn` visual index, column property or a range of columns finishing at `endColumn`. * * @example * ```js * // Select column using visual index. * hot.selectColumns(1); * // Select column using column property. * hot.selectColumns('id'); * // Select range of columns using visual indexes. * hot.selectColumns(1, 4); * // Select range of columns using visual indexes and mark the first header as highlighted. * hot.selectColumns(1, 2, -1); * // Select range of columns using visual indexes and mark the second cell as highlighted. * hot.selectColumns(2, 1, 1); * // Select range of columns using visual indexes and move the focus position somewhere in the middle of the range. * hot.selectColumns(2, 5, { row: 2, col: 3 }); * // Select range of columns using column properties. * hot.selectColumns('id', 'last_name'); * ``` * * @memberof Core# * @since 0.38.0 * @function selectColumns * @param {number} startColumn The visual column index from which the selection starts. * @param {number} [endColumn=startColumn] The visual column index to which the selection finishes. If `endColumn` * is not defined the column defined by `startColumn` will be selected. * @param {number | { row: number, col: number } | CellCoords} [focusPosition=0] The argument allows changing the cell/header focus * position. The value can take visual row index from -N to N, where negative values point to the headers and positive * values point to the cell range. An object with `row` and `col` properties also can be passed to change the focus * position horizontally. * @returns {boolean} `true` if selection was successful, `false` otherwise. */ this.selectColumns = function (startColumn) { let endColumn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : startColumn; let focusPosition = arguments.length > 2 ? arguments[2] : undefined; return selection.selectColumns(startColumn, endColumn, focusPosition); }; /** * Select row specified by `startRow` visual index or a range of rows finishing at `endRow`. * * @example * ```js * // Select row using visual index. * hot.selectRows(1); * // select a range of rows, using visual indexes. * hot.selectRows(1, 4); * // select a range of rows, using visual indexes, and mark the header as highlighted. * hot.selectRows(1, 2, -1); * // Select range of rows using visual indexes and mark the second cell as highlighted. * hot.selectRows(2, 1, 1); * // Select range of rows using visual indexes and move the focus position somewhere in the middle of the range. * hot.selectRows(2, 5, { row: 2, col: 3 }); * ``` * * @memberof Core# * @since 0.38.0 * @function selectRows * @param {number} startRow The visual row index from which the selection starts. * @param {number} [endRow=startRow] The visual row index to which the selection finishes. If `endRow` * is not defined the row defined by `startRow` will be selected. * @param {number | { row: number, col: number } | CellCoords} [focusPosition=0] The argument allows changing the cell/header focus * position. The value can take visual row index from -N to N, where negative values point to the headers and positive * values point to the cell range. An object with `row` and `col` properties also can be passed to change the focus * position vertically. * @returns {boolean} `true` if selection was successful, `false` otherwise. */ this.selectRows = function (startRow) { let endRow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : startRow; let focusPosition = arguments.length > 2 ? arguments[2] : undefined; return selection.selectRows(startRow, endRow, focusPosition); }; /** * Deselects the current cell selection on the table. * * @memberof Core# * @function deselectCell */ this.deselectCell = function () { selection.deselect(); }; /** * Select all cells in the table excluding headers and corner elements. * * The previous selection is overwritten. * * ```js * // Select all cells in the table along with row headers, including all headers and the corner cell. * // Doesn't select column headers and corner elements. * hot.selectAll(); * * // Select all cells in the table, including row headers but excluding the corner cell and column headers. * hot.selectAll(true, false); * * // Select all cells in the table, including all headers and the corner cell, but move the focus. * // highlight to position 2, 1 * hot.selectAll(-2, -1, { * focusPosition: { row: 2, col: 1 } * }); * * // Select all cells in the table, without headers and corner elements. * hot.selectAll(false); * ``` * * @since 0.38.2 * @memberof Core# * @function selectAll * @param {boolean} [includeRowHeaders=false] `true` If the selection should include the row headers, * `false` otherwise. * @param {boolean} [includeColumnHeaders=false] `true` If the selection should include the column * headers, `false` otherwise. * * @param {object} [options] Additional object with options. Since 14.0.0 * @param {{row: number, col: number} | boolean} [options.focusPosition] The argument allows changing the cell/header * focus position. The value takes an object with a `row` and `col` properties from -N to N, where * negative values point to the headers and positive values point to the cell range. If `false`, the focus * position won't be changed. Example: * ```js * hot.selectAll(0, 0, { * focusPosition: { row: 0, col: 1 }, * disableHeadersHighlight: true * }) * ``` * * @param {boolean} [options.disableHeadersHighlight] If `true`, disables highlighting the headers even when * the logical coordinates points on them. */ this.selectAll = function () { let includeRowHeaders = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; let includeColumnHeaders = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : includeRowHeaders; let options = arguments.length > 2 ? arguments[2] : undefined; viewportScroller.skipNextScrollCycle(); selection.selectAll(includeRowHeaders, includeColumnHeaders, options); }; const getIndexToScroll = (indexMapper, visualIndex) => { // Looking for a visual index on the right and then (when not found) on the left. return indexMapper.getNearestNotHiddenIndex(visualIndex, 1, true); }; /** * Scroll viewport to coordinates specified by the `row` and/or `col` object properties. * * ```js * // scroll the viewport to the visual row index (leave the horizontal scroll untouched) * hot.scrollViewportTo({ row: 50 }); * * // scroll the viewport to the passed coordinates so that the cell at 50, 50 will be snapped to * // the bottom-end table's edge. * hot.scrollViewportTo({ * row: 50, * col: 50, * verticalSnap: 'bottom', * horizontalSnap: 'end', * }); * ``` * * @memberof Core# * @function scrollViewportTo * @param {object} options A dictionary containing the following parameters: * @param {number} [options.row] Specifies the number of visual rows along the Y axis to scroll the viewport. * @param {number} [options.col] Specifies the number of visual columns along the X axis to scroll the viewport. * @param {'top' | 'bottom'} [options.verticalSnap] Determines to which edge of the table the viewport will be scrolled based on the passed coordinates. * This option is a string which must take one of the following values: * - `top`: The viewport will be scrolled to a row in such a way that it will be positioned on the top of the viewport; * - `bottom`: The viewport will be scrolled to a row in such a way that it will be positioned on the bottom of the viewport; * - If the property is not defined the vertical auto-snapping is enabled. Depending on where the viewport is scrolled from, a row will * be positioned at the top or bottom of the viewport. * @param {'start' | 'end'} [options.horizontalSnap] Determines to which edge of the table the viewport will be scrolled based on the passed coordinates. * This option is a string which must take one of the following values: * - `start`: The viewport will be scrolled to a column in such a way that it will be positioned on the start (left edge or right, if the layout direction is set to `rtl`) of the viewport; * - `end`: The viewport will be scrolled to a column in such a way that it will be positioned on the end (right edge or left, if the layout direction is set to `rtl`) of the viewport; * - If the property is not defined the horizontal auto-snapping is enabled. Depending on where the viewport is scrolled from, a column will * be positioned at the start or end of the viewport. * @param {boolean} [options.considerHiddenIndexes=true] If `true`, we handle visual indexes, otherwise we handle only indexes which * may be rendered when they are in the viewport (we don't consider hidden indexes as they aren't rendered). * @returns {boolean} `true` if viewport was scrolled, `false` otherwise. */ this.scrollViewportTo = function (options) { var _options; // Support for backward compatibility arguments: (row, col, snapToBottom, snapToRight, considerHiddenIndexes) if (typeof options === 'number') { var _arguments$; /* eslint-disable prefer-rest-params */ options = { row: arguments[0], col: arguments[1], verticalSnap: arguments[2] ? 'bottom' : 'top', horizontalSnap: arguments[3] ? 'end' : 'start', considerHiddenIndexes: (_arguments$ = arguments[4]) !== null && _arguments$ !== void 0 ? _arguments$ : true }; /* eslint-enable prefer-rest-params */ } const { row, col, verticalSnap, horizontalSnap, considerHiddenIndexes } = (_options = options) !== null && _options !== void 0 ? _options : {}; let snapToTop; let snapToBottom; let snapToInlineStart; let snapToInlineEnd; if (verticalSnap !== undefined) { snapToTop = verticalSnap === 'top'; snapToBottom = !snapToTop; } if (horizontalSnap !== undefined) { snapToInlineStart = horizontalSnap === 'start'; snapToInlineEnd = !snapToInlineStart; } let renderableRow = row; let renderableColumn = col; if (considerHiddenIndexes === undefined || considerHiddenIndexes) { const isValidRowGrid = Number.isInteger(row) && row >= 0; const isValidColumnGrid = Number.isInteger(col) && col >= 0; const visualRowToScroll = isValidRowGrid ? getIndexToScroll(this.rowIndexMapper, row) : undefined; const visualColumnToScroll = isValidColumnGrid ? getIndexToScroll(this.columnIndexMapper, col) : undefined; if (visualRowToScroll === null || visualColumnToScroll === null) { return false; } renderableRow = isValidRowGrid ? instance.rowIndexMapper.getRenderableFromVisualIndex(visualRowToScroll) : row; renderableColumn = isValidColumnGrid ? instance.columnIndexMapper.getRenderableFromVisualIndex(visualColumnToScroll) : col; } const isRowInteger = Number.isInteger(renderableRow); const isColumnInteger = Number.isInteger(renderableColumn); if (isRowInteger && renderableRow >= 0 && isColumnInteger && renderableColumn >= 0) { return instance.view.scrollViewport(instance._createCellCoords(renderableRow, renderableColumn), snapToTop, snapToInlineEnd, snapToBottom, snapToInlineStart); } if (isRowInteger && renderableRow >= 0 && (isColumnInteger && renderableColumn < 0 || !isColumnInteger)) { return instance.view.scrollViewportVertically(renderableRow, snapToTop, snapToBottom); } if (isColumnInteger && renderableColumn >= 0 && (isRowInteger && renderableRow < 0 || !isRowInteger)) { return instance.view.scrollViewportHorizontally(renderableColumn, snapToInlineEnd, snapToInlineStart); } return false; }; /** * Scrolls the viewport to coordinates specified by the currently focused cell. * * @since 14.0.0 * @memberof Core# * @fires Hooks#afterScroll * @function scrollToFocusedCell * @param {Function} callback The callback function to call after the viewport is scrolled. */ this.scrollToFocusedCell = function () { let callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : () => {}; if (!this.selection.isSelected()) { return; } this.addHookOnce('afterScroll', callback); const { highlight } = this.getSelectedRangeLast(); const isScrolled = this.scrollViewportTo(highlight.toObject()); if (isScrolled) { this.view.render(); } else { this.removeHook('afterScroll', callback); this._registerImmediate(() => callback()); } }; /** * Removes the table from the DOM and destroys the instance of the Handsontable. * * @memberof Core# * @function destroy * @fires Hooks#afterDestroy */ this.destroy = function () { instance._clearTimeouts(); instance._clearImmediates(); if (instance.view) { // in case HT is destroyed before initialization has finished instance.view.destroy(); } if (dataSource) { dataSource.destroy(); } dataSource = null; this.getShortcutManager().destroy(); metaManager.clearCache(); foreignHotInstances.delete(this.guid); if ((0, _rootInstance.isRootInstance)(instance)) { const licenseInfo = this.rootDocument.querySelector('.hot-display-license-info'); if (licenseInfo) { licenseInfo.parentNode.removeChild(licenseInfo); } } (0, _element.empty)(instance.rootElement); eventManager.destroy(); if (editorManager) { editorManager.destroy(); } // The plugin's `destroy` method is called as a consequence and it should handle // unregistration of plugin's maps. Some unregistered maps reset the cache. instance.batchExecution(() => { instance.rowIndexMapper.unregisterAll(); instance.columnIndexMapper.unregisterAll(); pluginsRegistry.getItems().forEach(_ref10 => { let [, plugin] = _ref10; plugin.destroy(); }); pluginsRegistry.clear(); instance.runHooks('afterDestroy'); }, true); _pluginHooks.default.getSingleton().destroy(instance); (0, _object.objectEach)(instance, (property, key, obj) => { // replace instance methods with post mortem if ((0, _function.isFunction)(property)) { obj[key] = postMortem(key); } else if (key !== 'guid') { // replace instance properties with null (restores memory) // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests obj[key] = null; } }); instance.isDestroyed = true; // replace private properties with null (restores memory) // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests if (datamap) { datamap.destroy(); } datamap = null; grid = null; selection = null; editorManager = null; instance = null; }; /** * Replacement for all methods after the Handsontable was destroyed. * * @private * @param {string} method The method name. * @returns {Function} */ function postMortem(method) { return () => { throw new Error(`The "${method}" method cannot be called because this Handsontable instance has been destroyed`); }; } /** * Returns the active editor class instance. * * @memberof Core# * @function getActiveEditor * @returns {BaseEditor} The active editor instance. */ this.getActiveEditor = function () { return editorManager.getActiveEditor(); }; /** * Returns the first rendered row in the DOM (usually, it is not visible in the table's viewport). * * @since 14.6.0 * @memberof Core# * @function getFirstRenderedVisibleRow * @returns {number | null} */ this.getFirstRenderedVisibleRow = function () { return instance.view.getFirstRenderedVisibleRow(); }; /** * Returns the last rendered row in the DOM (usually, it is not visible in the table's viewport). * * @since 14.6.0 * @memberof Core# * @function getLastRenderedVisibleRow * @returns {number | null} */ this.getLastRenderedVisibleRow = function () { return instance.view.getLastRenderedVisibleRow(); }; /** * Returns the first rendered column in the DOM (usually, it is not visible in the table's viewport). * * @since 14.6.0 * @memberof Core# * @function getFirstRenderedVisibleColumn * @returns {number | null} */ this.getFirstRenderedVisibleColumn = function () { return instance.view.getFirstRenderedVisibleColumn(); }; /** * Returns the last rendered column in the DOM (usually, it is not visible in the table's viewport). * * @since 14.6.0 * @memberof Core# * @function getLastRenderedVisibleColumn * @returns {number | null} */ this.getLastRenderedVisibleColumn = function () { return instance.view.getLastRenderedVisibleColumn(); }; /** * Returns the first fully visible row in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getFirstFullyVisibleRow * @returns {number | null} */ this.getFirstFullyVisibleRow = function () { return instance.view.getFirstFullyVisibleRow(); }; /** * Returns the last fully visible row in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getLastFullyVisibleRow * @returns {number | null} */ this.getLastFullyVisibleRow = function () { return instance.view.getLastFullyVisibleRow(); }; /** * Returns the first fully visible column in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getFirstFullyVisibleColumn * @returns {number | null} */ this.getFirstFullyVisibleColumn = function () { return instance.view.getFirstFullyVisibleColumn(); }; /** * Returns the last fully visible column in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getLastFullyVisibleColumn * @returns {number | null} */ this.getLastFullyVisibleColumn = function () { return instance.view.getLastFullyVisibleColumn(); }; /** * Returns the first partially visible row in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getFirstPartiallyVisibleRow * @returns {number | null} */ this.getFirstPartiallyVisibleRow = function () { return instance.view.getFirstPartiallyVisibleRow(); }; /** * Returns the last partially visible row in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getLastPartiallyVisibleRow * @returns {number | null} */ this.getLastPartiallyVisibleRow = function () { return instance.view.getLastPartiallyVisibleRow(); }; /** * Returns the first partially visible column in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getFirstPartiallyVisibleColumn * @returns {number | null} */ this.getFirstPartiallyVisibleColumn = function () { return instance.view.getFirstPartiallyVisibleColumn(); }; /** * Returns the last partially visible column in the table viewport. When the table has overlays the method returns * the first row of the main table that is not overlapped by overlay. * * @since 14.6.0 * @memberof Core# * @function getLastPartiallyVisibleColumn * @returns {number | null} */ this.getLastPartiallyVisibleColumn = function () { return instance.view.getLastPartiallyVisibleColumn(); }; /** * Returns plugin instance by provided its name. * * @memberof Core# * @function getPlugin * @param {string} pluginName The plugin name. * @returns {BasePlugin|undefined} The plugin instance or undefined if there is no plugin. */ this.getPlugin = function (pluginName) { const unifiedPluginName = (0, _string.toUpperCaseFirst)(pluginName); // Workaround for the UndoRedo plugin which, currently doesn't follow the plugin architecture. if (unifiedPluginName === 'UndoRedo') { return this.undoRedo; } return pluginsRegistry.getItem(unifiedPluginName); }; /** * Returns name of the passed plugin. * * @private * @memberof Core# * @param {BasePlugin} plugin The plugin instance. * @returns {string} */ this.getPluginName = function (plugin) { // Workaround for the UndoRedo plugin which, currently doesn't follow the plugin architecture. if (plugin === this.undoRedo) { return this.undoRedo.constructor.PLUGIN_KEY; } return pluginsRegistry.getId(plugin); }; /** * Returns the Handsontable instance. * * @memberof Core# * @function getInstance * @returns {Handsontable} The Handsontable instance. */ this.getInstance = function () { return instance; }; /** * Adds listener to the specified hook name (only for this Handsontable instance). * * @memberof Core# * @function addHook * @see Hooks#add * @param {string} key Hook name (see {@link Hooks}). * @param {Function|Array} callback Function or array of functions. * @param {number} [orderIndex] Order index of the callback. * If > 0, the callback will be added after the others, for example, with an index of 1, the callback will be added before the ones with an index of 2, 3, etc., but after the ones with an index of 0 and lower. * If < 0, the callback will be added before the others, for example, with an index of -1, the callback will be added after the ones with an index of -2, -3, etc., but before the ones with an index of 0 and higher. * If 0 or no order index is provided, the callback will be added between the "negative" and "positive" indexes. * @example * ```js * hot.addHook('beforeInit', myCallback); * ``` */ this.addHook = function (key, callback, orderIndex) { _pluginHooks.default.getSingleton().add(key, callback, instance, orderIndex); }; /** * Check if for a specified hook name there are added listeners (only for this Handsontable instance). All available * hooks you will find {@link Hooks}. * * @memberof Core# * @function hasHook * @see Hooks#has * @param {string} key Hook name. * @returns {boolean} * * @example * ```js * const hasBeforeInitListeners = hot.hasHook('beforeInit'); * ``` */ this.hasHook = function (key) { return _pluginHooks.default.getSingleton().has(key, instance) || _pluginHooks.default.getSingleton().has(key); }; /** * Adds listener to specified hook name (only for this Handsontable instance). After the listener is triggered, * it will be automatically removed. * * @memberof Core# * @function addHookOnce * @see Hooks#once * @param {string} key Hook name (see {@link Hooks}). * @param {Function|Array} callback Function or array of functions. * @param {number} [orderIndex] Order index of the callback. * If > 0, the callback will be added after the others, for example, with an index of 1, the callback will be added before the ones with an index of 2, 3, etc., but after the ones with an index of 0 and lower. * If < 0, the callback will be added before the others, for example, with an index of -1, the callback will be added after the ones with an index of -2, -3, etc., but before the ones with an index of 0 and higher. * If 0 or no order index is provided, the callback will be added between the "negative" and "positive" indexes. * @example * ```js * hot.addHookOnce('beforeInit', myCallback); * ``` */ this.addHookOnce = function (key, callback, orderIndex) { _pluginHooks.default.getSingleton().once(key, callback, instance, orderIndex); }; /** * Removes the hook listener previously registered with {@link Core#addHook}. * * @memberof Core# * @function removeHook * @see Hooks#remove * @param {string} key Hook name. * @param {Function} callback Reference to the function which has been registered using {@link Core#addHook}. * * @example * ```js * hot.removeHook('beforeInit', myCallback); * ``` */ this.removeHook = function (key, callback) { _pluginHooks.default.getSingleton().remove(key, callback, instance); }; /** * Run the callbacks for the hook provided in the `key` argument using the parameters given in the other arguments. * * @memberof Core# * @function runHooks * @see Hooks#run * @param {string} key Hook name. * @param {*} [p1] Argument passed to the callback. * @param {*} [p2] Argument passed to the callback. * @param {*} [p3] Argument passed to the callback. * @param {*} [p4] Argument passed to the callback. * @param {*} [p5] Argument passed to the callback. * @param {*} [p6] Argument passed to the callback. * @returns {*} * * @example * ```js * // Run built-in hook * hot.runHooks('beforeInit'); * // Run custom hook * hot.runHooks('customAction', 10, 'foo'); * ``` */ this.runHooks = function (key, p1, p2, p3, p4, p5, p6) { return _pluginHooks.default.getSingleton().run(instance, key, p1, p2, p3, p4, p5, p6); }; /** * Get language phrase for specified dictionary key. * * @memberof Core# * @function getTranslatedPhrase * @since 0.35.0 * @param {string} dictionaryKey Constant which is dictionary key. * @param {*} extraArguments Arguments which will be handled by formatters. * @returns {string} */ this.getTranslatedPhrase = function (dictionaryKey, extraArguments) { return (0, _registry5.getTranslatedPhrase)(tableMeta.language, dictionaryKey, extraArguments); }; /** * Converts instance into outerHTML of HTMLTableElement. * * @memberof Core# * @function toHTML * @since 7.1.0 * @returns {string} */ this.toHTML = () => (0, _parseTable.instanceToHTML)(this); /** * Converts instance into HTMLTableElement. * * @memberof Core# * @function toTableElement * @since 7.1.0 * @returns {HTMLTableElement} */ this.toTableElement = () => { const tempElement = this.rootDocument.createElement('div'); tempElement.insertAdjacentHTML('afterbegin', (0, _parseTable.instanceToHTML)(this)); return tempElement.firstElementChild; }; this.timeouts = []; /** * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called. * * @param {number|Function} handle Handler returned from setTimeout or function to execute (it will be automatically wraped * by setTimeout function). * @param {number} [delay=0] If first argument is passed as a function this argument set delay of the execution of that function. * @private */ this._registerTimeout = function (handle) { let delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; let handleFunc = handle; if (typeof handleFunc === 'function') { handleFunc = setTimeout(handleFunc, delay); } this.timeouts.push(handleFunc); }; /** * Clears all known timeouts. * * @private */ this._clearTimeouts = function () { (0, _array.arrayEach)(this.timeouts, handler => { clearTimeout(handler); }); }; this.immediates = []; /** * Execute function execution to the next event loop cycle. Purpose of this method is to clear all known timeouts when `destroy` method is called. * * @param {Function} callback Function to be delayed in execution. * @private */ this._registerImmediate = function (callback) { this.immediates.push(setImmediate(callback)); }; /** * Clears all known timeouts. * * @private */ this._clearImmediates = function () { (0, _array.arrayEach)(this.immediates, handler => { clearImmediate(handler); }); }; /** * Gets the instance of the EditorManager. * * @private * @returns {EditorManager} */ this._getEditorManager = function () { return editorManager; }; /** * Check if currently it is RTL direction. * * @private * @memberof Core# * @function isRtl * @returns {boolean} True if RTL. */ this.isRtl = function () { return instance.rootWindow.getComputedStyle(instance.rootElement).direction === 'rtl'; }; /** * Check if currently it is LTR direction. * * @private * @memberof Core# * @function isLtr * @returns {boolean} True if LTR. */ this.isLtr = function () { return !instance.isRtl(); }; /** * Returns 1 for LTR; -1 for RTL. Useful for calculations. * * @private * @memberof Core# * @function getDirectionFactor * @returns {number} Returns 1 for LTR; -1 for RTL. */ this.getDirectionFactor = function () { return instance.isLtr() ? 1 : -1; }; const shortcutManager = (0, _shortcuts.createShortcutManager)({ handleEvent() { return instance.isListening(); }, beforeKeyDown: event => { return this.runHooks('beforeKeyDown', event); }, afterKeyDown: event => { if (this.isDestroyed) { // Handsontable could be destroyed after performing action (executing a callback). return; } instance.runHooks('afterDocumentKeyDown', event); }, ownerWindow: this.rootWindow }); this.addHook('beforeOnCellMouseDown', event => { // Releasing keys as some browser/system shortcuts break events sequence (thus the `keyup` event isn't triggered). if (event.ctrlKey === false && event.metaKey === false) { shortcutManager.releasePressedKeys(); } }); /** * Returns instance of a manager responsible for handling shortcuts stored in some contexts. It run actions after * pressing key combination in active Handsontable instance. * * @memberof Core# * @since 12.0.0 * @function getShortcutManager * @returns {ShortcutManager} Instance of {@link ShortcutManager} */ this.getShortcutManager = function () { return shortcutManager; }; /** * Return the Focus Manager responsible for managing the browser's focus in the table. * * @memberof Core# * @since 14.0.0 * @function getFocusManager * @returns {FocusManager} */ this.getFocusManager = function () { return focusManager; }; (0, _registry.getPluginsNames)().forEach(pluginName => { const PluginClass = (0, _registry.getPlugin)(pluginName); pluginsRegistry.addItem(pluginName, new PluginClass(this)); }); (0, _shortcutContexts.registerAllShortcutContexts)(instance); shortcutManager.setActiveContextName('grid'); _pluginHooks.default.getSingleton().run(instance, 'construct'); } /***/ }), /* 204 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable no-unused-vars -- required for functions `.length` */ var $ = __webpack_require__(205); var globalThis = __webpack_require__(206); var apply = __webpack_require__(270); var wrapErrorConstructorWithCause = __webpack_require__(271); var WEB_ASSEMBLY = 'WebAssembly'; var WebAssembly = globalThis[WEB_ASSEMBLY]; // eslint-disable-next-line es/no-error-cause -- feature detection var FORCED = new Error('e', { cause: 7 }).cause !== 7; var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) { var O = {}; O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED); $({ global: true, constructor: true, arity: 1, forced: FORCED }, O); }; var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) { if (WebAssembly && WebAssembly[ERROR_NAME]) { var O = {}; O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED); $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O); } }; // https://tc39.es/ecma262/#sec-nativeerror exportGlobalErrorCauseWrapper('Error', function (init) { return function Error(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('EvalError', function (init) { return function EvalError(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('RangeError', function (init) { return function RangeError(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('ReferenceError', function (init) { return function ReferenceError(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('SyntaxError', function (init) { return function SyntaxError(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('TypeError', function (init) { return function TypeError(message) { return apply(init, this, arguments); }; }); exportGlobalErrorCauseWrapper('URIError', function (init) { return function URIError(message) { return apply(init, this, arguments); }; }); exportWebAssemblyErrorCauseWrapper('CompileError', function (init) { return function CompileError(message) { return apply(init, this, arguments); }; }); exportWebAssemblyErrorCauseWrapper('LinkError', function (init) { return function LinkError(message) { return apply(init, this, arguments); }; }); exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) { return function RuntimeError(message) { return apply(init, this, arguments); }; }); /***/ }), /* 205 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var getOwnPropertyDescriptor = (__webpack_require__(207).f); var createNonEnumerableProperty = __webpack_require__(245); var defineBuiltIn = __webpack_require__(249); var defineGlobalProperty = __webpack_require__(239); var copyConstructorProperties = __webpack_require__(257); var isForced = __webpack_require__(269); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.dontCallGetSet - prevent calling a getter on target options.name - the .name of the function if it does not match the key */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = globalThis; } else if (STATIC) { target = globalThis[TARGET] || defineGlobalProperty(TARGET, {}); } else { target = globalThis[TARGET] && globalThis[TARGET].prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.dontCallGetSet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty == typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } defineBuiltIn(target, key, sourceProperty, options); } }; /***/ }), /* 206 */ /***/ (function(module) { "use strict"; var check = function (it) { return it && it.Math === Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 module.exports = // eslint-disable-next-line es/no-global-this -- safe check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || // eslint-disable-next-line no-restricted-globals -- safe check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || check(typeof this == 'object' && this) || // eslint-disable-next-line no-new-func -- fallback (function () { return this; })() || Function('return this')(); /***/ }), /* 207 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var call = __webpack_require__(210); var propertyIsEnumerableModule = __webpack_require__(212); var createPropertyDescriptor = __webpack_require__(213); var toIndexedObject = __webpack_require__(214); var toPropertyKey = __webpack_require__(220); var hasOwn = __webpack_require__(240); var IE8_DOM_DEFINE = __webpack_require__(243); // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPropertyKey(P); if (IE8_DOM_DEFINE) try { return $getOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); }; /***/ }), /* 208 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fails = __webpack_require__(209); // Detect IE8's incomplete defineProperty implementation module.exports = !fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7; }); /***/ }), /* 209 */ /***/ ((module) => { "use strict"; module.exports = function (exec) { try { return !!exec(); } catch (error) { return true; } }; /***/ }), /* 210 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var NATIVE_BIND = __webpack_require__(211); var call = Function.prototype.call; module.exports = NATIVE_BIND ? call.bind(call) : function () { return call.apply(call, arguments); }; /***/ }), /* 211 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fails = __webpack_require__(209); module.exports = !fails(function () { // eslint-disable-next-line es/no-function-prototype-bind -- safe var test = (function () { /* empty */ }).bind(); // eslint-disable-next-line no-prototype-builtins -- safe return typeof test != 'function' || test.hasOwnProperty('prototype'); }); /***/ }), /* 212 */ /***/ ((__unused_webpack_module, exports) => { "use strict"; var $propertyIsEnumerable = {}.propertyIsEnumerable; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : $propertyIsEnumerable; /***/ }), /* 213 */ /***/ ((module) => { "use strict"; module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 214 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // toObject with fallback for non-array-like ES3 strings var IndexedObject = __webpack_require__(215); var requireObjectCoercible = __webpack_require__(218); module.exports = function (it) { return IndexedObject(requireObjectCoercible(it)); }; /***/ }), /* 215 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var fails = __webpack_require__(209); var classof = __webpack_require__(217); var $Object = Object; var split = uncurryThis(''.split); // fallback for non-array-like ES3 and non-enumerable old V8 strings module.exports = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins -- safe return !$Object('z').propertyIsEnumerable(0); }) ? function (it) { return classof(it) === 'String' ? split(it, '') : $Object(it); } : $Object; /***/ }), /* 216 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var NATIVE_BIND = __webpack_require__(211); var FunctionPrototype = Function.prototype; var call = FunctionPrototype.call; var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) { return function () { return call.apply(fn, arguments); }; }; /***/ }), /* 217 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var toString = uncurryThis({}.toString); var stringSlice = uncurryThis(''.slice); module.exports = function (it) { return stringSlice(toString(it), 8, -1); }; /***/ }), /* 218 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isNullOrUndefined = __webpack_require__(219); var $TypeError = TypeError; // `RequireObjectCoercible` abstract operation // https://tc39.es/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it); return it; }; /***/ }), /* 219 */ /***/ ((module) => { "use strict"; // we can't use just `it == null` since of `document.all` special case // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec module.exports = function (it) { return it === null || it === undefined; }; /***/ }), /* 220 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toPrimitive = __webpack_require__(221); var isSymbol = __webpack_require__(224); // `ToPropertyKey` abstract operation // https://tc39.es/ecma262/#sec-topropertykey module.exports = function (argument) { var key = toPrimitive(argument, 'string'); return isSymbol(key) ? key : key + ''; }; /***/ }), /* 221 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var call = __webpack_require__(210); var isObject = __webpack_require__(222); var isSymbol = __webpack_require__(224); var getMethod = __webpack_require__(231); var ordinaryToPrimitive = __webpack_require__(234); var wellKnownSymbol = __webpack_require__(235); var $TypeError = TypeError; var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); // `ToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-toprimitive module.exports = function (input, pref) { if (!isObject(input) || isSymbol(input)) return input; var exoticToPrim = getMethod(input, TO_PRIMITIVE); var result; if (exoticToPrim) { if (pref === undefined) pref = 'default'; result = call(exoticToPrim, input, pref); if (!isObject(result) || isSymbol(result)) return result; throw new $TypeError("Can't convert object to primitive value"); } if (pref === undefined) pref = 'number'; return ordinaryToPrimitive(input, pref); }; /***/ }), /* 222 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isCallable = __webpack_require__(223); module.exports = function (it) { return typeof it == 'object' ? it !== null : isCallable(it); }; /***/ }), /* 223 */ /***/ ((module) => { "use strict"; // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot var documentAll = typeof document == 'object' && document.all; // `IsCallable` abstract operation // https://tc39.es/ecma262/#sec-iscallable // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) { return typeof argument == 'function' || argument === documentAll; } : function (argument) { return typeof argument == 'function'; }; /***/ }), /* 224 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getBuiltIn = __webpack_require__(225); var isCallable = __webpack_require__(223); var isPrototypeOf = __webpack_require__(226); var USE_SYMBOL_AS_UID = __webpack_require__(227); var $Object = Object; module.exports = USE_SYMBOL_AS_UID ? function (it) { return typeof it == 'symbol'; } : function (it) { var $Symbol = getBuiltIn('Symbol'); return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); }; /***/ }), /* 225 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var isCallable = __webpack_require__(223); var aFunction = function (argument) { return isCallable(argument) ? argument : undefined; }; module.exports = function (namespace, method) { return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method]; }; /***/ }), /* 226 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); module.exports = uncurryThis({}.isPrototypeOf); /***/ }), /* 227 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable es/no-symbol -- required for testing */ var NATIVE_SYMBOL = __webpack_require__(228); module.exports = NATIVE_SYMBOL && !Symbol.sham && typeof Symbol.iterator == 'symbol'; /***/ }), /* 228 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable es/no-symbol -- required for testing */ var V8_VERSION = __webpack_require__(229); var fails = __webpack_require__(209); var globalThis = __webpack_require__(206); var $String = globalThis.String; // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing module.exports = !!Object.getOwnPropertySymbols && !fails(function () { var symbol = Symbol('symbol detection'); // Chrome 38 Symbol has incorrect toString conversion // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will, // of course, fail. return !$String(symbol) || !(Object(symbol) instanceof Symbol) || // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances !Symbol.sham && V8_VERSION && V8_VERSION < 41; }); /***/ }), /* 229 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var userAgent = __webpack_require__(230); var process = globalThis.process; var Deno = globalThis.Deno; var versions = process && process.versions || Deno && Deno.version; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); // in old Chrome, versions of V8 isn't V8 = Chrome / 10 // but their correct versions are not interesting for us version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); } // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0` // so check `userAgent` even if `.v8` exists, but 0 if (!version && userAgent) { match = userAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = userAgent.match(/Chrome\/(\d+)/); if (match) version = +match[1]; } } module.exports = version; /***/ }), /* 230 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var navigator = globalThis.navigator; var userAgent = navigator && navigator.userAgent; module.exports = userAgent ? String(userAgent) : ''; /***/ }), /* 231 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aCallable = __webpack_require__(232); var isNullOrUndefined = __webpack_require__(219); // `GetMethod` abstract operation // https://tc39.es/ecma262/#sec-getmethod module.exports = function (V, P) { var func = V[P]; return isNullOrUndefined(func) ? undefined : aCallable(func); }; /***/ }), /* 232 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isCallable = __webpack_require__(223); var tryToString = __webpack_require__(233); var $TypeError = TypeError; // `Assert: IsCallable(argument) is true` module.exports = function (argument) { if (isCallable(argument)) return argument; throw new $TypeError(tryToString(argument) + ' is not a function'); }; /***/ }), /* 233 */ /***/ ((module) => { "use strict"; var $String = String; module.exports = function (argument) { try { return $String(argument); } catch (error) { return 'Object'; } }; /***/ }), /* 234 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var call = __webpack_require__(210); var isCallable = __webpack_require__(223); var isObject = __webpack_require__(222); var $TypeError = TypeError; // `OrdinaryToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-ordinarytoprimitive module.exports = function (input, pref) { var fn, val; if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val; if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; throw new $TypeError("Can't convert object to primitive value"); }; /***/ }), /* 235 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var shared = __webpack_require__(236); var hasOwn = __webpack_require__(240); var uid = __webpack_require__(242); var NATIVE_SYMBOL = __webpack_require__(228); var USE_SYMBOL_AS_UID = __webpack_require__(227); var Symbol = globalThis.Symbol; var WellKnownSymbolsStore = shared('wks'); var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid; module.exports = function (name) { if (!hasOwn(WellKnownSymbolsStore, name)) { WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name) ? Symbol[name] : createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; /***/ }), /* 236 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var store = __webpack_require__(237); module.exports = function (key, value) { return store[key] || (store[key] = value || {}); }; /***/ }), /* 237 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var IS_PURE = __webpack_require__(238); var globalThis = __webpack_require__(206); var defineGlobalProperty = __webpack_require__(239); var SHARED = '__core-js_shared__'; var store = module.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {}); (store.versions || (store.versions = [])).push({ version: '3.38.1', mode: IS_PURE ? 'pure' : 'global', copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)', license: 'https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE', source: 'https://github.com/zloirock/core-js' }); /***/ }), /* 238 */ /***/ ((module) => { "use strict"; module.exports = false; /***/ }), /* 239 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); // eslint-disable-next-line es/no-object-defineproperty -- safe var defineProperty = Object.defineProperty; module.exports = function (key, value) { try { defineProperty(globalThis, key, { value: value, configurable: true, writable: true }); } catch (error) { globalThis[key] = value; } return value; }; /***/ }), /* 240 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var toObject = __webpack_require__(241); var hasOwnProperty = uncurryThis({}.hasOwnProperty); // `HasOwnProperty` abstract operation // https://tc39.es/ecma262/#sec-hasownproperty // eslint-disable-next-line es/no-object-hasown -- safe module.exports = Object.hasOwn || function hasOwn(it, key) { return hasOwnProperty(toObject(it), key); }; /***/ }), /* 241 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var requireObjectCoercible = __webpack_require__(218); var $Object = Object; // `ToObject` abstract operation // https://tc39.es/ecma262/#sec-toobject module.exports = function (argument) { return $Object(requireObjectCoercible(argument)); }; /***/ }), /* 242 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var id = 0; var postfix = Math.random(); var toString = uncurryThis(1.0.toString); module.exports = function (key) { return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36); }; /***/ }), /* 243 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var fails = __webpack_require__(209); var createElement = __webpack_require__(244); // Thanks to IE8 for its funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty(createElement('div'), 'a', { get: function () { return 7; } }).a !== 7; }); /***/ }), /* 244 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var isObject = __webpack_require__(222); var document = globalThis.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); module.exports = function (it) { return EXISTS ? document.createElement(it) : {}; }; /***/ }), /* 245 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var definePropertyModule = __webpack_require__(246); var createPropertyDescriptor = __webpack_require__(213); module.exports = DESCRIPTORS ? function (object, key, value) { return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 246 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var IE8_DOM_DEFINE = __webpack_require__(243); var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(247); var anObject = __webpack_require__(248); var toPropertyKey = __webpack_require__(220); var $TypeError = TypeError; // eslint-disable-next-line es/no-object-defineproperty -- safe var $defineProperty = Object.defineProperty; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var ENUMERABLE = 'enumerable'; var CONFIGURABLE = 'configurable'; var WRITABLE = 'writable'; // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { anObject(O); P = toPropertyKey(P); anObject(Attributes); if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { var current = $getOwnPropertyDescriptor(O, P); if (current && current[WRITABLE]) { O[P] = Attributes.value; Attributes = { configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], writable: false }; } } return $defineProperty(O, P, Attributes); } : $defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPropertyKey(P); anObject(Attributes); if (IE8_DOM_DEFINE) try { return $defineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 247 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var fails = __webpack_require__(209); // V8 ~ Chrome 36- // https://bugs.chromium.org/p/v8/issues/detail?id=3334 module.exports = DESCRIPTORS && fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty(function () { /* empty */ }, 'prototype', { value: 42, writable: false }).prototype !== 42; }); /***/ }), /* 248 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isObject = __webpack_require__(222); var $String = String; var $TypeError = TypeError; // `Assert: Type(argument) is Object` module.exports = function (argument) { if (isObject(argument)) return argument; throw new $TypeError($String(argument) + ' is not an object'); }; /***/ }), /* 249 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isCallable = __webpack_require__(223); var definePropertyModule = __webpack_require__(246); var makeBuiltIn = __webpack_require__(250); var defineGlobalProperty = __webpack_require__(239); module.exports = function (O, key, value, options) { if (!options) options = {}; var simple = options.enumerable; var name = options.name !== undefined ? options.name : key; if (isCallable(value)) makeBuiltIn(value, name, options); if (options.global) { if (simple) O[key] = value; else defineGlobalProperty(key, value); } else { try { if (!options.unsafe) delete O[key]; else if (O[key]) simple = true; } catch (error) { /* empty */ } if (simple) O[key] = value; else definePropertyModule.f(O, key, { value: value, enumerable: false, configurable: !options.nonConfigurable, writable: !options.nonWritable }); } return O; }; /***/ }), /* 250 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var fails = __webpack_require__(209); var isCallable = __webpack_require__(223); var hasOwn = __webpack_require__(240); var DESCRIPTORS = __webpack_require__(208); var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(251).CONFIGURABLE); var inspectSource = __webpack_require__(252); var InternalStateModule = __webpack_require__(253); var enforceInternalState = InternalStateModule.enforce; var getInternalState = InternalStateModule.get; var $String = String; // eslint-disable-next-line es/no-object-defineproperty -- safe var defineProperty = Object.defineProperty; var stringSlice = uncurryThis(''.slice); var replace = uncurryThis(''.replace); var join = uncurryThis([].join); var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () { return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8; }); var TEMPLATE = String(String).split('String'); var makeBuiltIn = module.exports = function (value, name, options) { if (stringSlice($String(name), 0, 7) === 'Symbol(') { name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']'; } if (options && options.getter) name = 'get ' + name; if (options && options.setter) name = 'set ' + name; if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) { if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true }); else value.name = name; } if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) { defineProperty(value, 'length', { value: options.arity }); } try { if (options && hasOwn(options, 'constructor') && options.constructor) { if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false }); // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable } else if (value.prototype) value.prototype = undefined; } catch (error) { /* empty */ } var state = enforceInternalState(value); if (!hasOwn(state, 'source')) { state.source = join(TEMPLATE, typeof name == 'string' ? name : ''); } return value; }; // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative // eslint-disable-next-line no-extend-native -- required Function.prototype.toString = makeBuiltIn(function toString() { return isCallable(this) && getInternalState(this).source || inspectSource(this); }, 'toString'); /***/ }), /* 251 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var hasOwn = __webpack_require__(240); var FunctionPrototype = Function.prototype; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; var EXISTS = hasOwn(FunctionPrototype, 'name'); // additional protection from minified / mangled / dropped function names var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something'; var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable)); module.exports = { EXISTS: EXISTS, PROPER: PROPER, CONFIGURABLE: CONFIGURABLE }; /***/ }), /* 252 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var isCallable = __webpack_require__(223); var store = __webpack_require__(237); var functionToString = uncurryThis(Function.toString); // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper if (!isCallable(store.inspectSource)) { store.inspectSource = function (it) { return functionToString(it); }; } module.exports = store.inspectSource; /***/ }), /* 253 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var NATIVE_WEAK_MAP = __webpack_require__(254); var globalThis = __webpack_require__(206); var isObject = __webpack_require__(222); var createNonEnumerableProperty = __webpack_require__(245); var hasOwn = __webpack_require__(240); var shared = __webpack_require__(237); var sharedKey = __webpack_require__(255); var hiddenKeys = __webpack_require__(256); var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; var TypeError = globalThis.TypeError; var WeakMap = globalThis.WeakMap; var set, get, has; var enforce = function (it) { return has(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw new TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (NATIVE_WEAK_MAP || shared.state) { var store = shared.state || (shared.state = new WeakMap()); /* eslint-disable no-self-assign -- prototype methods protection */ store.get = store.get; store.has = store.has; store.set = store.set; /* eslint-enable no-self-assign -- prototype methods protection */ set = function (it, metadata) { if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; store.set(it, metadata); return metadata; }; get = function (it) { return store.get(it) || {}; }; has = function (it) { return store.has(it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return hasOwn(it, STATE) ? it[STATE] : {}; }; has = function (it) { return hasOwn(it, STATE); }; } module.exports = { set: set, get: get, has: has, enforce: enforce, getterFor: getterFor }; /***/ }), /* 254 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var isCallable = __webpack_require__(223); var WeakMap = globalThis.WeakMap; module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap)); /***/ }), /* 255 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var shared = __webpack_require__(236); var uid = __webpack_require__(242); var keys = shared('keys'); module.exports = function (key) { return keys[key] || (keys[key] = uid(key)); }; /***/ }), /* 256 */ /***/ ((module) => { "use strict"; module.exports = {}; /***/ }), /* 257 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var hasOwn = __webpack_require__(240); var ownKeys = __webpack_require__(258); var getOwnPropertyDescriptorModule = __webpack_require__(207); var definePropertyModule = __webpack_require__(246); module.exports = function (target, source, exceptions) { var keys = ownKeys(source); var defineProperty = definePropertyModule.f; var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) { defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } } }; /***/ }), /* 258 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getBuiltIn = __webpack_require__(225); var uncurryThis = __webpack_require__(216); var getOwnPropertyNamesModule = __webpack_require__(259); var getOwnPropertySymbolsModule = __webpack_require__(268); var anObject = __webpack_require__(248); var concat = uncurryThis([].concat); // all object keys, includes non-enumerable and symbols module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule.f(anObject(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys; }; /***/ }), /* 259 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var internalObjectKeys = __webpack_require__(260); var enumBugKeys = __webpack_require__(267); var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.es/ecma262/#sec-object.getownpropertynames // eslint-disable-next-line es/no-object-getownpropertynames -- safe exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); }; /***/ }), /* 260 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var hasOwn = __webpack_require__(240); var toIndexedObject = __webpack_require__(214); var indexOf = (__webpack_require__(261).indexOf); var hiddenKeys = __webpack_require__(256); var push = uncurryThis([].push); module.exports = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key); // Don't enum bug & hidden keys while (names.length > i) if (hasOwn(O, key = names[i++])) { ~indexOf(result, key) || push(result, key); } return result; }; /***/ }), /* 261 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toIndexedObject = __webpack_require__(214); var toAbsoluteIndex = __webpack_require__(262); var lengthOfArrayLike = __webpack_require__(265); // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = lengthOfArrayLike(O); if (length === 0) return !IS_INCLUDES && -1; var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare -- NaN check if (IS_INCLUDES && el !== el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare -- NaN check if (value !== value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; module.exports = { // `Array.prototype.includes` method // https://tc39.es/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.es/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; /***/ }), /* 262 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toIntegerOrInfinity = __webpack_require__(263); var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). module.exports = function (index, length) { var integer = toIntegerOrInfinity(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; /***/ }), /* 263 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var trunc = __webpack_require__(264); // `ToIntegerOrInfinity` abstract operation // https://tc39.es/ecma262/#sec-tointegerorinfinity module.exports = function (argument) { var number = +argument; // eslint-disable-next-line no-self-compare -- NaN check return number !== number || number === 0 ? 0 : trunc(number); }; /***/ }), /* 264 */ /***/ ((module) => { "use strict"; var ceil = Math.ceil; var floor = Math.floor; // `Math.trunc` method // https://tc39.es/ecma262/#sec-math.trunc // eslint-disable-next-line es/no-math-trunc -- safe module.exports = Math.trunc || function trunc(x) { var n = +x; return (n > 0 ? floor : ceil)(n); }; /***/ }), /* 265 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toLength = __webpack_require__(266); // `LengthOfArrayLike` abstract operation // https://tc39.es/ecma262/#sec-lengthofarraylike module.exports = function (obj) { return toLength(obj.length); }; /***/ }), /* 266 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toIntegerOrInfinity = __webpack_require__(263); var min = Math.min; // `ToLength` abstract operation // https://tc39.es/ecma262/#sec-tolength module.exports = function (argument) { var len = toIntegerOrInfinity(argument); return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; /***/ }), /* 267 */ /***/ ((module) => { "use strict"; // IE8- don't enum bug keys module.exports = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /***/ }), /* 268 */ /***/ ((__unused_webpack_module, exports) => { "use strict"; // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe exports.f = Object.getOwnPropertySymbols; /***/ }), /* 269 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fails = __webpack_require__(209); var isCallable = __webpack_require__(223); var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value === POLYFILL ? true : value === NATIVE ? false : isCallable(detection) ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; module.exports = isForced; /***/ }), /* 270 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var NATIVE_BIND = __webpack_require__(211); var FunctionPrototype = Function.prototype; var apply = FunctionPrototype.apply; var call = FunctionPrototype.call; // eslint-disable-next-line es/no-reflect -- safe module.exports = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () { return call.apply(apply, arguments); }); /***/ }), /* 271 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getBuiltIn = __webpack_require__(225); var hasOwn = __webpack_require__(240); var createNonEnumerableProperty = __webpack_require__(245); var isPrototypeOf = __webpack_require__(226); var setPrototypeOf = __webpack_require__(272); var copyConstructorProperties = __webpack_require__(257); var proxyAccessor = __webpack_require__(276); var inheritIfRequired = __webpack_require__(277); var normalizeStringArgument = __webpack_require__(278); var installErrorCause = __webpack_require__(282); var installErrorStack = __webpack_require__(283); var DESCRIPTORS = __webpack_require__(208); var IS_PURE = __webpack_require__(238); module.exports = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) { var STACK_TRACE_LIMIT = 'stackTraceLimit'; var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1; var path = FULL_NAME.split('.'); var ERROR_NAME = path[path.length - 1]; var OriginalError = getBuiltIn.apply(null, path); if (!OriginalError) return; var OriginalErrorPrototype = OriginalError.prototype; // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause; if (!FORCED) return OriginalError; var BaseError = getBuiltIn('Error'); var WrappedError = wrapper(function (a, b) { var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined); var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError(); if (message !== undefined) createNonEnumerableProperty(result, 'message', message); installErrorStack(result, WrappedError, result.stack, 2); if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError); if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]); return result; }); WrappedError.prototype = OriginalErrorPrototype; if (ERROR_NAME !== 'Error') { if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError); else copyConstructorProperties(WrappedError, BaseError, { name: true }); } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) { proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT); proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace'); } copyConstructorProperties(WrappedError, OriginalError); if (!IS_PURE) try { // Safari 13- bug: WebAssembly errors does not have a proper `.name` if (OriginalErrorPrototype.name !== ERROR_NAME) { createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME); } OriginalErrorPrototype.constructor = WrappedError; } catch (error) { /* empty */ } return WrappedError; }; /***/ }), /* 272 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable no-proto -- safe */ var uncurryThisAccessor = __webpack_require__(273); var isObject = __webpack_require__(222); var requireObjectCoercible = __webpack_require__(218); var aPossiblePrototype = __webpack_require__(274); // `Object.setPrototypeOf` method // https://tc39.es/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. // eslint-disable-next-line es/no-object-setprototypeof -- safe module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); setter(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { requireObjectCoercible(O); aPossiblePrototype(proto); if (!isObject(O)) return O; if (CORRECT_SETTER) setter(O, proto); else O.__proto__ = proto; return O; }; }() : undefined); /***/ }), /* 273 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var aCallable = __webpack_require__(232); module.exports = function (object, key, method) { try { // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); } catch (error) { /* empty */ } }; /***/ }), /* 274 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isPossiblePrototype = __webpack_require__(275); var $String = String; var $TypeError = TypeError; module.exports = function (argument) { if (isPossiblePrototype(argument)) return argument; throw new $TypeError("Can't set " + $String(argument) + ' as a prototype'); }; /***/ }), /* 275 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isObject = __webpack_require__(222); module.exports = function (argument) { return isObject(argument) || argument === null; }; /***/ }), /* 276 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var defineProperty = (__webpack_require__(246).f); module.exports = function (Target, Source, key) { key in Target || defineProperty(Target, key, { configurable: true, get: function () { return Source[key]; }, set: function (it) { Source[key] = it; } }); }; /***/ }), /* 277 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isCallable = __webpack_require__(223); var isObject = __webpack_require__(222); var setPrototypeOf = __webpack_require__(272); // makes subclassing work correct for wrapped built-ins module.exports = function ($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; if ( // it can work only with native `setPrototypeOf` setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this isCallable(NewTarget = dummy.constructor) && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype ) setPrototypeOf($this, NewTargetPrototype); return $this; }; /***/ }), /* 278 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toString = __webpack_require__(279); module.exports = function (argument, $default) { return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument); }; /***/ }), /* 279 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var classof = __webpack_require__(280); var $String = String; module.exports = function (argument) { if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string'); return $String(argument); }; /***/ }), /* 280 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var TO_STRING_TAG_SUPPORT = __webpack_require__(281); var isCallable = __webpack_require__(223); var classofRaw = __webpack_require__(217); var wellKnownSymbol = __webpack_require__(235); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var $Object = Object; // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; }; /***/ }), /* 281 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var wellKnownSymbol = __webpack_require__(235); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var test = {}; test[TO_STRING_TAG] = 'z'; module.exports = String(test) === '[object z]'; /***/ }), /* 282 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isObject = __webpack_require__(222); var createNonEnumerableProperty = __webpack_require__(245); // `InstallErrorCause` abstract operation // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause module.exports = function (O, options) { if (isObject(options) && 'cause' in options) { createNonEnumerableProperty(O, 'cause', options.cause); } }; /***/ }), /* 283 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var createNonEnumerableProperty = __webpack_require__(245); var clearErrorStack = __webpack_require__(284); var ERROR_STACK_INSTALLABLE = __webpack_require__(285); // non-standard V8 var captureStackTrace = Error.captureStackTrace; module.exports = function (error, C, stack, dropEntries) { if (ERROR_STACK_INSTALLABLE) { if (captureStackTrace) captureStackTrace(error, C); else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries)); } }; /***/ }), /* 284 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var $Error = Error; var replace = uncurryThis(''.replace); var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd'); // eslint-disable-next-line redos/no-vulnerable -- safe var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/; var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST); module.exports = function (stack, dropEntries) { if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) { while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, ''); } return stack; }; /***/ }), /* 285 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var fails = __webpack_require__(209); var createPropertyDescriptor = __webpack_require__(213); module.exports = !fails(function () { var error = new Error('a'); if (!('stack' in error)) return true; // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7)); return error.stack !== 7; }); /***/ }), /* 286 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var toObject = __webpack_require__(241); var lengthOfArrayLike = __webpack_require__(265); var setArrayLength = __webpack_require__(287); var doesNotExceedSafeInteger = __webpack_require__(289); var fails = __webpack_require__(209); var INCORRECT_TO_LENGTH = fails(function () { return [].push.call({ length: 0x100000000 }, 1) !== 4294967297; }); // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError // https://bugs.chromium.org/p/v8/issues/detail?id=12681 var properErrorOnNonWritableLength = function () { try { // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty([], 'length', { writable: false }).push(); } catch (error) { return error instanceof TypeError; } }; var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength(); // `Array.prototype.push` method // https://tc39.es/ecma262/#sec-array.prototype.push $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, { // eslint-disable-next-line no-unused-vars -- required for `.length` push: function push(item) { var O = toObject(this); var len = lengthOfArrayLike(O); var argCount = arguments.length; doesNotExceedSafeInteger(len + argCount); for (var i = 0; i < argCount; i++) { O[len] = arguments[i]; len++; } setArrayLength(O, len); return len; } }); /***/ }), /* 287 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var DESCRIPTORS = __webpack_require__(208); var isArray = __webpack_require__(288); var $TypeError = TypeError; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Safari < 13 does not throw an error in this case var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () { // makes no sense without proper strict mode support if (this !== undefined) return true; try { // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty([], 'length', { writable: false }).length = 1; } catch (error) { return error instanceof TypeError; } }(); module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) { if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) { throw new $TypeError('Cannot set read only .length'); } return O.length = length; } : function (O, length) { return O.length = length; }; /***/ }), /* 288 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var classof = __webpack_require__(217); // `IsArray` abstract operation // https://tc39.es/ecma262/#sec-isarray // eslint-disable-next-line es/no-array-isarray -- safe module.exports = Array.isArray || function isArray(argument) { return classof(argument) === 'Array'; }; /***/ }), /* 289 */ /***/ ((module) => { "use strict"; var $TypeError = TypeError; var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991 module.exports = function (it) { if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded'); return it; }; /***/ }), /* 290 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var difference = __webpack_require__(291); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.difference` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, { difference: difference }); /***/ }), /* 291 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var SetHelpers = __webpack_require__(293); var clone = __webpack_require__(294); var size = __webpack_require__(297); var getSetRecord = __webpack_require__(298); var iterateSet = __webpack_require__(295); var iterateSimple = __webpack_require__(296); var has = SetHelpers.has; var remove = SetHelpers.remove; // `Set.prototype.difference` method // https://github.com/tc39/proposal-set-methods module.exports = function difference(other) { var O = aSet(this); var otherRec = getSetRecord(other); var result = clone(O); if (size(O) <= otherRec.size) iterateSet(O, function (e) { if (otherRec.includes(e)) remove(result, e); }); else iterateSimple(otherRec.getIterator(), function (e) { if (has(O, e)) remove(result, e); }); return result; }; /***/ }), /* 292 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var has = (__webpack_require__(293).has); // Perform ? RequireInternalSlot(M, [[SetData]]) module.exports = function (it) { has(it); return it; }; /***/ }), /* 293 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); // eslint-disable-next-line es/no-set -- safe var SetPrototype = Set.prototype; module.exports = { // eslint-disable-next-line es/no-set -- safe Set: Set, add: uncurryThis(SetPrototype.add), has: uncurryThis(SetPrototype.has), remove: uncurryThis(SetPrototype['delete']), proto: SetPrototype }; /***/ }), /* 294 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var SetHelpers = __webpack_require__(293); var iterate = __webpack_require__(295); var Set = SetHelpers.Set; var add = SetHelpers.add; module.exports = function (set) { var result = new Set(); iterate(set, function (it) { add(result, it); }); return result; }; /***/ }), /* 295 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); var iterateSimple = __webpack_require__(296); var SetHelpers = __webpack_require__(293); var Set = SetHelpers.Set; var SetPrototype = SetHelpers.proto; var forEach = uncurryThis(SetPrototype.forEach); var keys = uncurryThis(SetPrototype.keys); var next = keys(new Set()).next; module.exports = function (set, fn, interruptible) { return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn); }; /***/ }), /* 296 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var call = __webpack_require__(210); module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) { var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator; var next = record.next; var step, result; while (!(step = call(next, iterator)).done) { result = fn(step.value); if (result !== undefined) return result; } }; /***/ }), /* 297 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThisAccessor = __webpack_require__(273); var SetHelpers = __webpack_require__(293); module.exports = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) { return set.size; }; /***/ }), /* 298 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aCallable = __webpack_require__(232); var anObject = __webpack_require__(248); var call = __webpack_require__(210); var toIntegerOrInfinity = __webpack_require__(263); var getIteratorDirect = __webpack_require__(299); var INVALID_SIZE = 'Invalid size'; var $RangeError = RangeError; var $TypeError = TypeError; var max = Math.max; var SetRecord = function (set, intSize) { this.set = set; this.size = max(intSize, 0); this.has = aCallable(set.has); this.keys = aCallable(set.keys); }; SetRecord.prototype = { getIterator: function () { return getIteratorDirect(anObject(call(this.keys, this.set))); }, includes: function (it) { return call(this.has, this.set, it); } }; // `GetSetRecord` abstract operation // https://tc39.es/proposal-set-methods/#sec-getsetrecord module.exports = function (obj) { anObject(obj); var numSize = +obj.size; // NOTE: If size is undefined, then numSize will be NaN // eslint-disable-next-line no-self-compare -- NaN check if (numSize !== numSize) throw new $TypeError(INVALID_SIZE); var intSize = toIntegerOrInfinity(numSize); if (intSize < 0) throw new $RangeError(INVALID_SIZE); return new SetRecord(obj, intSize); }; /***/ }), /* 299 */ /***/ ((module) => { "use strict"; // `GetIteratorDirect(obj)` abstract operation // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect module.exports = function (obj) { return { iterator: obj, next: obj.next, done: false }; }; /***/ }), /* 300 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getBuiltIn = __webpack_require__(225); var createSetLike = function (size) { return { size: size, has: function () { return false; }, keys: function () { return { next: function () { return { done: true }; } }; } }; }; module.exports = function (name) { var Set = getBuiltIn('Set'); try { new Set()[name](createSetLike(0)); try { // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it // https://github.com/tc39/proposal-set-methods/pull/88 new Set()[name](createSetLike(-1)); return false; } catch (error2) { return true; } } catch (error) { return false; } }; /***/ }), /* 301 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var fails = __webpack_require__(209); var intersection = __webpack_require__(302); var setMethodAcceptSetLike = __webpack_require__(300); var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () { // eslint-disable-next-line es/no-array-from, es/no-set -- testing return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2'; }); // `Set.prototype.intersection` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, { intersection: intersection }); /***/ }), /* 302 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var SetHelpers = __webpack_require__(293); var size = __webpack_require__(297); var getSetRecord = __webpack_require__(298); var iterateSet = __webpack_require__(295); var iterateSimple = __webpack_require__(296); var Set = SetHelpers.Set; var add = SetHelpers.add; var has = SetHelpers.has; // `Set.prototype.intersection` method // https://github.com/tc39/proposal-set-methods module.exports = function intersection(other) { var O = aSet(this); var otherRec = getSetRecord(other); var result = new Set(); if (size(O) > otherRec.size) { iterateSimple(otherRec.getIterator(), function (e) { if (has(O, e)) add(result, e); }); } else { iterateSet(O, function (e) { if (otherRec.includes(e)) add(result, e); }); } return result; }; /***/ }), /* 303 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var isDisjointFrom = __webpack_require__(304); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.isDisjointFrom` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, { isDisjointFrom: isDisjointFrom }); /***/ }), /* 304 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var has = (__webpack_require__(293).has); var size = __webpack_require__(297); var getSetRecord = __webpack_require__(298); var iterateSet = __webpack_require__(295); var iterateSimple = __webpack_require__(296); var iteratorClose = __webpack_require__(305); // `Set.prototype.isDisjointFrom` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom module.exports = function isDisjointFrom(other) { var O = aSet(this); var otherRec = getSetRecord(other); if (size(O) <= otherRec.size) return iterateSet(O, function (e) { if (otherRec.includes(e)) return false; }, true) !== false; var iterator = otherRec.getIterator(); return iterateSimple(iterator, function (e) { if (has(O, e)) return iteratorClose(iterator, 'normal', false); }) !== false; }; /***/ }), /* 305 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var call = __webpack_require__(210); var anObject = __webpack_require__(248); var getMethod = __webpack_require__(231); module.exports = function (iterator, kind, value) { var innerResult, innerError; anObject(iterator); try { innerResult = getMethod(iterator, 'return'); if (!innerResult) { if (kind === 'throw') throw value; return value; } innerResult = call(innerResult, iterator); } catch (error) { innerError = true; innerResult = error; } if (kind === 'throw') throw value; if (innerError) throw innerResult; anObject(innerResult); return value; }; /***/ }), /* 306 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var isSubsetOf = __webpack_require__(307); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.isSubsetOf` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, { isSubsetOf: isSubsetOf }); /***/ }), /* 307 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var size = __webpack_require__(297); var iterate = __webpack_require__(295); var getSetRecord = __webpack_require__(298); // `Set.prototype.isSubsetOf` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf module.exports = function isSubsetOf(other) { var O = aSet(this); var otherRec = getSetRecord(other); if (size(O) > otherRec.size) return false; return iterate(O, function (e) { if (!otherRec.includes(e)) return false; }, true) !== false; }; /***/ }), /* 308 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var isSupersetOf = __webpack_require__(309); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.isSupersetOf` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, { isSupersetOf: isSupersetOf }); /***/ }), /* 309 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var has = (__webpack_require__(293).has); var size = __webpack_require__(297); var getSetRecord = __webpack_require__(298); var iterateSimple = __webpack_require__(296); var iteratorClose = __webpack_require__(305); // `Set.prototype.isSupersetOf` method // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf module.exports = function isSupersetOf(other) { var O = aSet(this); var otherRec = getSetRecord(other); if (size(O) < otherRec.size) return false; var iterator = otherRec.getIterator(); return iterateSimple(iterator, function (e) { if (!has(O, e)) return iteratorClose(iterator, 'normal', false); }) !== false; }; /***/ }), /* 310 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var symmetricDifference = __webpack_require__(311); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.symmetricDifference` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, { symmetricDifference: symmetricDifference }); /***/ }), /* 311 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var SetHelpers = __webpack_require__(293); var clone = __webpack_require__(294); var getSetRecord = __webpack_require__(298); var iterateSimple = __webpack_require__(296); var add = SetHelpers.add; var has = SetHelpers.has; var remove = SetHelpers.remove; // `Set.prototype.symmetricDifference` method // https://github.com/tc39/proposal-set-methods module.exports = function symmetricDifference(other) { var O = aSet(this); var keysIter = getSetRecord(other).getIterator(); var result = clone(O); iterateSimple(keysIter, function (e) { if (has(O, e)) remove(result, e); else add(result, e); }); return result; }; /***/ }), /* 312 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var union = __webpack_require__(313); var setMethodAcceptSetLike = __webpack_require__(300); // `Set.prototype.union` method // https://github.com/tc39/proposal-set-methods $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, { union: union }); /***/ }), /* 313 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var aSet = __webpack_require__(292); var add = (__webpack_require__(293).add); var clone = __webpack_require__(294); var getSetRecord = __webpack_require__(298); var iterateSimple = __webpack_require__(296); // `Set.prototype.union` method // https://github.com/tc39/proposal-set-methods module.exports = function union(other) { var O = aSet(this); var keysIter = getSetRecord(other).getIterator(); var result = clone(O); iterateSimple(keysIter, function (it) { add(result, it); }); return result; }; /***/ }), /* 314 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // TODO: Remove this module from `core-js@4` since it's split to modules listed below __webpack_require__(315); __webpack_require__(325); /***/ }), /* 315 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var globalThis = __webpack_require__(206); var clearImmediate = (__webpack_require__(316).clear); // `clearImmediate` method // http://w3c.github.io/setImmediate/#si-clearImmediate $({ global: true, bind: true, enumerable: true, forced: globalThis.clearImmediate !== clearImmediate }, { clearImmediate: clearImmediate }); /***/ }), /* 316 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var apply = __webpack_require__(270); var bind = __webpack_require__(317); var isCallable = __webpack_require__(223); var hasOwn = __webpack_require__(240); var fails = __webpack_require__(209); var html = __webpack_require__(319); var arraySlice = __webpack_require__(320); var createElement = __webpack_require__(244); var validateArgumentsLength = __webpack_require__(321); var IS_IOS = __webpack_require__(322); var IS_NODE = __webpack_require__(323); var set = globalThis.setImmediate; var clear = globalThis.clearImmediate; var process = globalThis.process; var Dispatch = globalThis.Dispatch; var Function = globalThis.Function; var MessageChannel = globalThis.MessageChannel; var String = globalThis.String; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var $location, defer, channel, port; fails(function () { // Deno throws a ReferenceError on `location` access without `--location` flag $location = globalThis.location; }); var run = function (id) { if (hasOwn(queue, id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var runner = function (id) { return function () { run(id); }; }; var eventListener = function (event) { run(event.data); }; var globalPostMessageDefer = function (id) { // old engines have not location.origin globalThis.postMessage(String(id), $location.protocol + '//' + $location.host); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!set || !clear) { set = function setImmediate(handler) { validateArgumentsLength(arguments.length, 1); var fn = isCallable(handler) ? handler : Function(handler); var args = arraySlice(arguments, 1); queue[++counter] = function () { apply(fn, undefined, args); }; defer(counter); return counter; }; clear = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (IS_NODE) { defer = function (id) { process.nextTick(runner(id)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(runner(id)); }; // Browsers with MessageChannel, includes WebWorkers // except iOS - https://github.com/zloirock/core-js/issues/624 } else if (MessageChannel && !IS_IOS) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = eventListener; defer = bind(port.postMessage, port); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if ( globalThis.addEventListener && isCallable(globalThis.postMessage) && !globalThis.importScripts && $location && $location.protocol !== 'file:' && !fails(globalPostMessageDefer) ) { defer = globalPostMessageDefer; globalThis.addEventListener('message', eventListener, false); // IE8- } else if (ONREADYSTATECHANGE in createElement('script')) { defer = function (id) { html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(runner(id), 0); }; } } module.exports = { set: set, clear: clear }; /***/ }), /* 317 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(318); var aCallable = __webpack_require__(232); var NATIVE_BIND = __webpack_require__(211); var bind = uncurryThis(uncurryThis.bind); // optional / simple context binding module.exports = function (fn, that) { aCallable(fn); return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 318 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var classofRaw = __webpack_require__(217); var uncurryThis = __webpack_require__(216); module.exports = function (fn) { // Nashorn bug: // https://github.com/zloirock/core-js/issues/1128 // https://github.com/zloirock/core-js/issues/1130 if (classofRaw(fn) === 'Function') return uncurryThis(fn); }; /***/ }), /* 319 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getBuiltIn = __webpack_require__(225); module.exports = getBuiltIn('document', 'documentElement'); /***/ }), /* 320 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var uncurryThis = __webpack_require__(216); module.exports = uncurryThis([].slice); /***/ }), /* 321 */ /***/ ((module) => { "use strict"; var $TypeError = TypeError; module.exports = function (passed, required) { if (passed < required) throw new $TypeError('Not enough arguments'); return passed; }; /***/ }), /* 322 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var userAgent = __webpack_require__(230); // eslint-disable-next-line redos/no-vulnerable -- safe module.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent); /***/ }), /* 323 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var ENVIRONMENT = __webpack_require__(324); module.exports = ENVIRONMENT === 'NODE'; /***/ }), /* 324 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* global Bun, Deno -- detection */ var globalThis = __webpack_require__(206); var userAgent = __webpack_require__(230); var classof = __webpack_require__(217); var userAgentStartsWith = function (string) { return userAgent.slice(0, string.length) === string; }; module.exports = (function () { if (userAgentStartsWith('Bun/')) return 'BUN'; if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE'; if (userAgentStartsWith('Deno/')) return 'DENO'; if (userAgentStartsWith('Node.js/')) return 'NODE'; if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN'; if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO'; if (classof(globalThis.process) === 'process') return 'NODE'; if (globalThis.window && globalThis.document) return 'BROWSER'; return 'REST'; })(); /***/ }), /* 325 */ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var $ = __webpack_require__(205); var globalThis = __webpack_require__(206); var setTask = (__webpack_require__(316).set); var schedulersFix = __webpack_require__(326); // https://github.com/oven-sh/bun/issues/1633 var setImmediate = globalThis.setImmediate ? schedulersFix(setTask, false) : setTask; // `setImmediate` method // http://w3c.github.io/setImmediate/#si-setImmediate $({ global: true, bind: true, enumerable: true, forced: globalThis.setImmediate !== setImmediate }, { setImmediate: setImmediate }); /***/ }), /* 326 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var globalThis = __webpack_require__(206); var apply = __webpack_require__(270); var isCallable = __webpack_require__(223); var ENVIRONMENT = __webpack_require__(324); var USER_AGENT = __webpack_require__(230); var arraySlice = __webpack_require__(320); var validateArgumentsLength = __webpack_require__(321); var Function = globalThis.Function; // dirty IE9- and Bun 0.3.0- checks var WRAP = /MSIE .\./.test(USER_AGENT) || ENVIRONMENT === 'BUN' && (function () { var version = globalThis.Bun.version.split('.'); return version.length < 3 || version[0] === '0' && (version[1] < 3 || version[1] === '3' && version[2] === '0'); })(); // IE9- / Bun 0.3.0- setTimeout / setInterval / setImmediate additional parameters fix // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers // https://github.com/oven-sh/bun/issues/1633 module.exports = function (scheduler, hasTimeArg) { var firstParamIndex = hasTimeArg ? 2 : 1; return WRAP ? function (handler, timeout /* , ...arguments */) { var boundArgs = validateArgumentsLength(arguments.length, 1) > firstParamIndex; var fn = isCallable(handler) ? handler : Function(handler); var params = boundArgs ? arraySlice(arguments, firstParamIndex) : []; var callback = boundArgs ? function () { apply(fn, this, params); } : fn; return hasTimeArg ? scheduler(callback, timeout) : scheduler(callback); } : scheduler; }; /***/ }), /* 327 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.addClass = addClass; exports.addEvent = addEvent; exports.clearTextSelection = clearTextSelection; exports.closest = closest; exports.closestDown = closestDown; exports.empty = empty; exports.fastInnerHTML = fastInnerHTML; exports.fastInnerText = fastInnerText; exports.getCaretPosition = getCaretPosition; exports.getComputedStyle = getComputedStyle; exports.getCssTransform = getCssTransform; exports.getFrameElement = getFrameElement; exports.getMaximumScrollLeft = getMaximumScrollLeft; exports.getMaximumScrollTop = getMaximumScrollTop; exports.getParent = getParent; exports.getParentWindow = getParentWindow; exports.getScrollLeft = getScrollLeft; exports.getScrollTop = getScrollTop; exports.getScrollableElement = getScrollableElement; exports.getScrollbarWidth = getScrollbarWidth; exports.getSelectionEndPosition = getSelectionEndPosition; exports.getSelectionText = getSelectionText; exports.getStyle = getStyle; exports.getTrimmingContainer = getTrimmingContainer; exports.getWindowScrollLeft = getWindowScrollLeft; exports.getWindowScrollTop = getWindowScrollTop; exports.hasAccessToParentWindow = hasAccessToParentWindow; exports.hasClass = hasClass; exports.hasHorizontalScrollbar = hasHorizontalScrollbar; exports.hasVerticalScrollbar = hasVerticalScrollbar; exports.index = index; exports.innerHeight = innerHeight; exports.innerWidth = innerWidth; exports.isChildOf = isChildOf; exports.isDetached = isDetached; exports.isInput = isInput; exports.isOutsideInput = isOutsideInput; exports.isThisHotChild = isThisHotChild; exports.isVisible = isVisible; exports.makeElementContentEditableAndSelectItsContent = makeElementContentEditableAndSelectItsContent; exports.matchesCSSRules = matchesCSSRules; exports.observeVisibilityChangeOnce = observeVisibilityChangeOnce; exports.offset = offset; exports.outerHeight = outerHeight; exports.outerWidth = outerWidth; exports.overlayContainsElement = overlayContainsElement; exports.removeAttribute = removeAttribute; exports.removeClass = removeClass; exports.removeContentEditableFromElementAndDeselect = removeContentEditableFromElementAndDeselect; exports.removeEvent = removeEvent; exports.removeTextNodes = removeTextNodes; exports.resetCssTransform = resetCssTransform; exports.runWithSelectedContendEditableElement = runWithSelectedContendEditableElement; exports.selectElementIfAllowed = selectElementIfAllowed; exports.setAttribute = setAttribute; exports.setCaretPosition = setCaretPosition; exports.setOverlayPosition = setOverlayPosition; __webpack_require__(204); __webpack_require__(286); var _string = __webpack_require__(328); var _a11y = __webpack_require__(472); /** * Get the parent of the specified node in the DOM tree. * * @param {HTMLElement} element Element from which traversing is started. * @param {number} [level=0] Traversing deep level. * @returns {HTMLElement|null} */ function getParent(element) { let level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; let iteration = -1; let parent = null; let elementToCheck = element; while (elementToCheck !== null) { if (iteration === level) { parent = elementToCheck; break; } if (elementToCheck.host && elementToCheck.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { elementToCheck = elementToCheck.host; } else { iteration += 1; elementToCheck = elementToCheck.parentNode; } } return parent; } /** * Check if the provided element is a child of the provided Handsontable container. * * @param {HTMLElement} element Element to be analyzed. * @param {HTMLElement} thisHotContainer The Handsontable container. * @returns {boolean} */ function isThisHotChild(element, thisHotContainer) { const closestHandsontableContainer = element.closest('.handsontable'); return !!closestHandsontableContainer && (closestHandsontableContainer.parentNode === thisHotContainer || closestHandsontableContainer === thisHotContainer); } /** * Gets `frameElement` of the specified frame. Returns null if it is a top frame or if script has no access to read property. * * @param {Window} frame Frame from which should be get frameElement in safe way. * @returns {HTMLIFrameElement|null} */ function getFrameElement(frame) { return Object.getPrototypeOf(frame.parent) && frame.frameElement; } /** * Gets parent frame of the specified frame. Returns null if it is a top frame or if script has no access to read property. * * @param {Window} frame Frame from which should get frameElement in a safe way. * @returns {Window|null} */ function getParentWindow(frame) { return getFrameElement(frame) && frame.parent; } /** * Checks if script has access to read from parent frame of specified frame. * * @param {Window} frame Frame from which should get frameElement in a safe way. * @returns {boolean} */ function hasAccessToParentWindow(frame) { return !!Object.getPrototypeOf(frame.parent); } /** * Goes up the DOM tree (including given element) until it finds an parent element that matches the nodes or nodes name. * This method goes up through web components. * * @param {Node} element Element from which traversing is started. * @param {Array} [nodes] Array of elements or Array of elements name (in uppercase form). * @param {Node} [until] The element until the traversing ends. * @returns {Node|null} */ function closest(element) { let nodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; let until = arguments.length > 2 ? arguments[2] : undefined; const { ELEMENT_NODE, DOCUMENT_FRAGMENT_NODE } = Node; let elementToCheck = element; while (elementToCheck !== null && elementToCheck !== undefined && elementToCheck !== until) { const { nodeType, nodeName } = elementToCheck; if (nodeType === ELEMENT_NODE && (nodes.includes(nodeName) || nodes.includes(elementToCheck))) { return elementToCheck; } const { host } = elementToCheck; if (host && nodeType === DOCUMENT_FRAGMENT_NODE) { elementToCheck = host; } else { elementToCheck = elementToCheck.parentNode; } } return null; } /** * Goes "down" the DOM tree (including given element) until it finds an element that matches the nodes or nodes name. * * @param {HTMLElement} element Element from which traversing is started. * @param {Array} nodes Array of elements or Array of elements name. * @param {HTMLElement} [until] The list of elements until the traversing ends. * @returns {HTMLElement|null} */ function closestDown(element, nodes, until) { const matched = []; let elementToCheck = element; while (elementToCheck) { elementToCheck = closest(elementToCheck, nodes, until); if (!elementToCheck || until && !until.contains(elementToCheck)) { break; } matched.push(elementToCheck); if (elementToCheck.host && elementToCheck.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { elementToCheck = elementToCheck.host; } else { elementToCheck = elementToCheck.parentNode; } } const length = matched.length; return length ? matched[length - 1] : null; } /** * Goes up the DOM tree and checks if element is child of another element. * * @param {HTMLElement} child Child element An element to check. * @param {object|string} parent Parent element OR selector of the parent element. * If string provided, function returns `true` for the first occurrence of element with that class. * @returns {boolean} */ function isChildOf(child, parent) { let node = child.parentNode; let queriedParents = []; if (typeof parent === 'string') { if (child.defaultView) { queriedParents = Array.prototype.slice.call(child.querySelectorAll(parent), 0); } else { queriedParents = Array.prototype.slice.call(child.ownerDocument.querySelectorAll(parent), 0); } } else { queriedParents.push(parent); } while (node !== null) { if (queriedParents.indexOf(node) > -1) { return true; } node = node.parentNode; } return false; } /** * Counts index of element within its parent. * WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true * for Walkotnable, otherwise would need to check for nodeType or use previousElementSibling. * * @see http://jsperf.com/sibling-index/10 * @param {Element} element The element to check. * @returns {number} */ function index(element) { let i = 0; let elementToCheck = element; if (elementToCheck.previousSibling) { /* eslint-disable no-cond-assign */ while (elementToCheck = elementToCheck.previousSibling) { i += 1; } } return i; } /** * Check if the provided overlay contains the provided element. * * @param {string} overlayType The type of the overlay. * @param {HTMLElement} element An element to check. * @param {HTMLElement} root The root element. * @returns {boolean} */ function overlayContainsElement(overlayType, element, root) { const overlayElement = root.parentElement.querySelector(`.ht_clone_${overlayType}`); return overlayElement ? overlayElement.contains(element) : null; } /** * @param {string[]} classNames The element "class" attribute string. * @returns {string[]} */ function filterEmptyClassNames(classNames) { if (!classNames || !classNames.length) { return []; } return classNames.filter(x => !!x); } /** * Filter out the RegExp entries from an array. * * @param {(string|RegExp)[]} list Array of either strings, Regexes or a mix of both. * @param {boolean} [returnBoth] If `true`, both the array without regexes and an array of regexes will be returned. * @returns {string[]|{regexFree: string[], regexes: RegExp[]}} */ function filterRegexes(list, returnBoth) { if (!list || !list.length) { return returnBoth ? { regexFree: [], regexes: [] } : []; } const regexes = []; const regexFree = []; regexFree.push(...list.filter(entry => { const isRegex = entry instanceof RegExp; if (isRegex && returnBoth) { regexes.push(entry); } return !isRegex; })); return returnBoth ? { regexFree, regexes } : regexFree; } /** * Checks if element has class name. * * @param {HTMLElement} element An element to check. * @param {string} className Class name to check. * @returns {boolean} */ function hasClass(element, className) { if (element.classList === undefined || typeof className !== 'string' || className === '') { return false; } return element.classList.contains(className); } /** * Add class name to an element. * * @param {HTMLElement} element An element to process. * @param {string|Array} className Class name as string or array of strings. */ function addClass(element, className) { if (typeof className === 'string') { className = className.split(' '); } className = filterEmptyClassNames(className); if (className.length > 0) { element.classList.add(...className); } } /** * Remove class name from an element. * * @param {HTMLElement} element An element to process. * @param {string|Array} className Class name as string or array of strings. */ function removeClass(element, className) { if (typeof className === 'string') { className = className.split(' '); } else if (className instanceof RegExp) { className = [className]; } let { regexFree: stringClasses, // eslint-disable-next-line prefer-const regexes: regexClasses } = filterRegexes(className, true); stringClasses = filterEmptyClassNames(stringClasses); if (stringClasses.length > 0) { element.classList.remove(...stringClasses); } regexClasses.forEach(regexClassName => { element.classList.forEach(currentClassName => { if (regexClassName.test(currentClassName)) { element.classList.remove(currentClassName); } }); }); } /** * Set a single attribute or multiple attributes at once. * * @param {HTMLElement} domElement The HTML element to be modified. * @param {Array[]|string} attributes If setting multiple attributes at once, `attributes` holds an array containing the * attributes to be added. Each element of the array should be an array in a form of `[attributeName, * attributeValue]`. If setting a single attribute, `attributes` holds the name of the attribute. * @param {string|number|undefined} [attributeValue] If setting a single attribute, `attributeValue` holds the attribute * value. */ function setAttribute(domElement) { let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; let attributeValue = arguments.length > 2 ? arguments[2] : undefined; if (!Array.isArray(attributes)) { attributes = [[attributes, attributeValue]]; } attributes.forEach(attributeInfo => { if (Array.isArray(attributeInfo) && attributeInfo[0] !== '') { domElement.setAttribute(...attributeInfo); } }); } /** * Remove a single attribute or multiple attributes from the provided element at once. * * @param {HTMLElement} domElement The HTML element to be processed. * @param {Array|string} attributesToRemove If removing multiple attributes, `attributesToRemove` * holds an array of attribute names to be removed from the provided element. If removing a single attribute, it * holds the attribute name. */ function removeAttribute(domElement) { let attributesToRemove = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (typeof attributesToRemove === 'string') { attributesToRemove = attributesToRemove.split(' '); } else if (attributesToRemove instanceof RegExp) { attributesToRemove = [attributesToRemove]; } const { regexFree: stringAttributes, regexes: regexAttributes } = filterRegexes(attributesToRemove, true); stringAttributes.forEach(attributeNameToRemove => { if (attributeNameToRemove !== '') { domElement.removeAttribute(attributeNameToRemove); } }); regexAttributes.forEach(attributeRegex => { domElement.getAttributeNames().forEach(attributeName => { if (attributeRegex.test(attributeName)) { domElement.removeAttribute(attributeName); } }); }); } /** * @param {HTMLElement} element An element from the text is removed. */ function removeTextNodes(element) { if (element.nodeType === 3) { element.parentNode.removeChild(element); // bye text nodes! } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(element.nodeName) > -1) { const childs = element.childNodes; for (let i = childs.length - 1; i >= 0; i--) { removeTextNodes(childs[i]); } } } /** * Remove children function * WARNING - this doesn't unload events and data attached by jQuery * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method. * * @param {HTMLElement} element An element to clear. */ function empty(element) { let child; /* eslint-disable no-cond-assign */ while (child = element.lastChild) { element.removeChild(child); } } const HTML_CHARACTERS = exports.HTML_CHARACTERS = /(<(.*)>|&(.*);)/; /** * Insert content into element trying to avoid innerHTML method. * * @param {HTMLElement} element An element to write into. * @param {string} content The text to write. * @param {boolean} [sanitizeContent=true] If `true`, the content will be sanitized before writing to the element. */ function fastInnerHTML(element, content) { let sanitizeContent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (HTML_CHARACTERS.test(content)) { element.innerHTML = sanitizeContent ? (0, _string.sanitize)(content) : content; } else { fastInnerText(element, content); } } /** * Insert text content into element. * * @param {HTMLElement} element An element to write into. * @param {string} content The text to write. */ function fastInnerText(element, content) { const child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { // fast lane - replace existing text node child.textContent = content; } else { // slow lane - empty element and insert a text node empty(element); element.appendChild(element.ownerDocument.createTextNode(content)); } } /** * Returns true if element is attached to the DOM and visible, false otherwise. * * @param {HTMLElement} element An element to check. * @returns {boolean} */ function isVisible(element) { const documentElement = element.ownerDocument.documentElement; let next = element; while (next !== documentElement) { // until reached if (next === null) { // parent detached from DOM return false; } else if (next.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { if (next.host) { // this is Web Components Shadow DOM // see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation // according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet if (next.host.impl) { // Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled return isVisible(next.host.impl); } else if (next.host) { // Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled return isVisible(next.host); } throw new Error('Lost in Web Components world'); } else { return false; // this is a node detached from document in IE8 } } else if (getComputedStyle(next).display === 'none') { return false; } next = next.parentNode; } return true; } /** * Returns elements top and left offset relative to the document. Function is not compatible with jQuery offset. * * @param {HTMLElement} element An element to get the offset position from. * @returns {object} Returns object with `top` and `left` props. */ function offset(element) { const rootDocument = element.ownerDocument; const rootWindow = rootDocument.defaultView; const documentElement = rootDocument.documentElement; let elementToCheck = element; let offsetLeft; let offsetTop; let lastElem; offsetLeft = elementToCheck.offsetLeft; offsetTop = elementToCheck.offsetTop; lastElem = elementToCheck; /* eslint-disable no-cond-assign */ while (elementToCheck = elementToCheck.offsetParent) { // from my observation, document.body always has scrollLeft/scrollTop == 0 if (elementToCheck === rootDocument.body) { break; } // If the element is inside an SVG context, the `offsetParent` can be // a that does not have properties `offsetLeft` and `offsetTop` defined. if (!('offsetLeft' in elementToCheck)) { break; } offsetLeft += elementToCheck.offsetLeft; offsetTop += elementToCheck.offsetTop; lastElem = elementToCheck; } // slow - http://jsperf.com/offset-vs-getboundingclientrect/6 if (lastElem && lastElem.style.position === 'fixed') { // if(lastElem !== document.body) { //faster but does gives false positive in Firefox offsetLeft += rootWindow.pageXOffset || documentElement.scrollLeft; offsetTop += rootWindow.pageYOffset || documentElement.scrollTop; } return { left: offsetLeft, top: offsetTop }; } /** * Returns the document's scrollTop property. * * @param {Window} [rootWindow] The document window owner. * @returns {number} */ // eslint-disable-next-line no-restricted-globals function getWindowScrollTop() { let rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; return rootWindow.scrollY; } /** * Returns the document's scrollLeft property. * * @param {Window} [rootWindow] The document window owner. * @returns {number} */ // eslint-disable-next-line no-restricted-globals function getWindowScrollLeft() { let rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; return rootWindow.scrollX; } /** * Returns the provided element's scrollTop property. * * @param {HTMLElement} element An element to get the scroll top position from. * @param {Window} [rootWindow] The document window owner. * @returns {number} */ // eslint-disable-next-line no-restricted-globals function getScrollTop(element) { let rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; if (element === rootWindow) { return getWindowScrollTop(rootWindow); } return element.scrollTop; } /** * Returns the provided element's scrollLeft property. * * @param {HTMLElement} element An element to get the scroll left position from. * @param {Window} [rootWindow] The document window owner. * @returns {number} */ // eslint-disable-next-line no-restricted-globals function getScrollLeft(element) { let rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; if (element === rootWindow) { return getWindowScrollLeft(rootWindow); } return element.scrollLeft; } /** * Returns a DOM element responsible for scrolling of the provided element. * * @param {HTMLElement} element An element to get the scrollable element from. * @returns {HTMLElement} Element's scrollable parent. */ function getScrollableElement(element) { let rootDocument = element.ownerDocument; let rootWindow = rootDocument ? rootDocument.defaultView : undefined; if (!rootDocument) { rootDocument = element.document ? element.document : element; rootWindow = rootDocument.defaultView; } const props = ['auto', 'scroll']; let el = element.parentNode; while (el && el.style && rootDocument.body !== el) { let { overflow, overflowX, overflowY } = el.style; if ([overflow, overflowX, overflowY].includes('scroll')) { return el; } else { ({ overflow, overflowX, overflowY } = rootWindow.getComputedStyle(el)); if (props.includes(overflow) || props.includes(overflowX) || props.includes(overflowY)) { return el; } } // The '+ 1' after the scrollHeight/scrollWidth is to prevent problems with zoomed out Chrome. if (el.clientHeight <= el.scrollHeight + 1 && (props.includes(overflowY) || props.includes(overflow))) { return el; } if (el.clientWidth <= el.scrollWidth + 1 && (props.includes(overflowX) || props.includes(overflow))) { return el; } el = el.parentNode; } return rootWindow; } /** * Get the maximum available `scrollTop` value for the provided element. * * @param {HTMLElement} element The element to get the maximum scroll top value from. * @returns {number} The maximum scroll top value. */ function getMaximumScrollTop(element) { return element.scrollHeight - element.clientHeight; } /** * Get the maximum available `scrollLeft` value for the provided element. * * @param {HTMLElement} element The element to get the maximum scroll left value from. * @returns {number} The maximum scroll left value. */ function getMaximumScrollLeft(element) { return element.scrollWidth - element.clientWidth; } /** * Returns a DOM element responsible for trimming the provided element. * * @param {HTMLElement} base Base element. * @returns {HTMLElement} Base element's trimming parent. */ function getTrimmingContainer(base) { const rootDocument = base.ownerDocument; const rootWindow = rootDocument.defaultView; let el = base.parentNode; while (el && el.style && rootDocument.body !== el) { if (el.style.overflow !== 'visible' && el.style.overflow !== '') { return el; } const computedStyle = getComputedStyle(el, rootWindow); const allowedProperties = ['scroll', 'hidden', 'auto']; const property = computedStyle.getPropertyValue('overflow'); const propertyY = computedStyle.getPropertyValue('overflow-y'); const propertyX = computedStyle.getPropertyValue('overflow-x'); if (allowedProperties.includes(property) || allowedProperties.includes(propertyY) || allowedProperties.includes(propertyX)) { return el; } el = el.parentNode; } return rootWindow; } /** * Returns a style property for the provided element. (Be it an inline or external style). * * @param {HTMLElement} element An element to get the style from. * @param {string} prop Wanted property. * @param {Window} [rootWindow] The document window owner. * @returns {string|undefined} Element's style property. */ // eslint-disable-next-line no-restricted-globals function getStyle(element, prop) { let rootWindow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window; if (!element) { return; } else if (element === rootWindow) { if (prop === 'width') { return `${rootWindow.innerWidth}px`; } else if (prop === 'height') { return `${rootWindow.innerHeight}px`; } return; } const styleProp = element.style[prop]; if (styleProp !== '' && styleProp !== undefined) { return styleProp; } const computedStyle = getComputedStyle(element, rootWindow); if (computedStyle[prop] !== '' && computedStyle[prop] !== undefined) { return computedStyle[prop]; } } /** * Verifies if element fit to provided CSSRule. * * @param {Element} element Element to verify with selector text. * @param {CSSRule} rule Selector text from CSSRule. * @returns {boolean} */ function matchesCSSRules(element, rule) { const { selectorText } = rule; let result = false; if (rule.type === CSSRule.STYLE_RULE && selectorText) { if (element.msMatchesSelector) { result = element.msMatchesSelector(selectorText); } else if (element.matches) { result = element.matches(selectorText); } } return result; } /** * Returns a computed style object for the provided element. (Needed if style is declared in external stylesheet). * * @param {HTMLElement} element An element to get style from. * @param {Window} [rootWindow] The document window owner. * @returns {IEElementStyle|CssStyle} Elements computed style object. */ // eslint-disable-next-line no-restricted-globals function getComputedStyle(element) { let rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; return element.currentStyle || rootWindow.getComputedStyle(element); } /** * Returns the element's outer width. * * @param {HTMLElement} element An element to get the width from. * @returns {number} Element's outer width. */ function outerWidth(element) { return element.offsetWidth; } /** * Returns the element's outer height. * * @param {HTMLElement} element An element to get the height from. * @returns {number} Element's outer height. */ function outerHeight(element) { return element.offsetHeight; } /** * Returns the element's inner height. * * @param {HTMLElement} element An element to get the height from. * @returns {number} Element's inner height. */ function innerHeight(element) { return element.clientHeight || element.innerHeight; } /** * Returns the element's inner width. * * @param {HTMLElement} element An element to get the width from. * @returns {number} Element's inner width. */ function innerWidth(element) { return element.clientWidth || element.innerWidth; } /** * @param {HTMLElement} element An element to which the event is added. * @param {string} event The event name. * @param {Function} callback The callback to add. */ function addEvent(element, event, callback) { element.addEventListener(event, callback, false); } /** * @param {HTMLElement} element An element from which the event is removed. * @param {string} event The event name. * @param {Function} callback The function reference to remove. */ function removeEvent(element, event, callback) { element.removeEventListener(event, callback, false); } /** * Returns caret position in text input. * * @author https://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea * @param {HTMLElement} el An element to check. * @returns {number} */ function getCaretPosition(el) { if (el.selectionStart) { return el.selectionStart; } return 0; } /** * Returns end of the selection in text input. * * @param {HTMLElement} el An element to check. * @returns {number} */ function getSelectionEndPosition(el) { if (el.selectionEnd) { return el.selectionEnd; } return 0; } /** * Returns text under selection. * * @param {Window} [rootWindow] The document window owner. * @returns {string} */ // eslint-disable-next-line no-restricted-globals function getSelectionText() { let rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; const rootDocument = rootWindow.document; let text = ''; if (rootWindow.getSelection) { text = rootWindow.getSelection().toString(); } else if (rootDocument.selection && rootDocument.selection.type !== 'Control') { text = rootDocument.selection.createRange().text; } return text; } /** * Cross-platform helper to clear text selection. * * @param {Window} [rootWindow] The document window owner. */ // eslint-disable-next-line no-restricted-globals function clearTextSelection() { let rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; // http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript if (rootWindow.getSelection) { if (rootWindow.getSelection().empty) { // Chrome rootWindow.getSelection().empty(); } else if (rootWindow.getSelection().removeAllRanges) { // Firefox rootWindow.getSelection().removeAllRanges(); } } } /** * Sets caret position in text input. * * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ * @param {Element} element An element to process. * @param {number} pos The selection start position. * @param {number} endPos The selection end position. */ function setCaretPosition(element, pos, endPos) { if (endPos === undefined) { endPos = pos; } if (element.setSelectionRange) { element.focus(); try { element.setSelectionRange(pos, endPos); } catch (err) { const elementParent = element.parentNode; const parentDisplayValue = elementParent.style.display; elementParent.style.display = 'block'; element.setSelectionRange(pos, endPos); elementParent.style.display = parentDisplayValue; } } } let cachedScrollbarWidth; /** * Helper to calculate scrollbar width. * Source: https://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes. * * @private * @param {Document} rootDocument The onwer of the document. * @returns {number} */ // eslint-disable-next-line no-restricted-globals function walkontableCalculateScrollbarWidth() { let rootDocument = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; const inner = rootDocument.createElement('div'); inner.style.height = '200px'; inner.style.width = '100%'; const outer = rootDocument.createElement('div'); outer.style.boxSizing = 'content-box'; outer.style.height = '150px'; outer.style.left = '0px'; outer.style.overflow = 'hidden'; outer.style.position = 'absolute'; outer.style.top = '0px'; outer.style.width = '200px'; outer.style.visibility = 'hidden'; outer.appendChild(inner); (rootDocument.body || rootDocument.documentElement).appendChild(outer); const w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; let w2 = inner.offsetWidth; if (w1 === w2) { w2 = outer.clientWidth; } (rootDocument.body || rootDocument.documentElement).removeChild(outer); return w1 - w2; } /** * Returns the computed width of the native browser scroll bar. * * @param {Document} [rootDocument] The owner of the document. * @returns {number} Width. */ // eslint-disable-next-line no-restricted-globals function getScrollbarWidth() { let rootDocument = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; if (cachedScrollbarWidth === undefined) { cachedScrollbarWidth = walkontableCalculateScrollbarWidth(rootDocument); } return cachedScrollbarWidth; } /** * Checks if the provided element has a vertical scrollbar. * * @param {HTMLElement} element An element to check. * @returns {boolean} */ function hasVerticalScrollbar(element) { return element.offsetWidth !== element.clientWidth; } /** * Checks if the provided element has a vertical scrollbar. * * @param {HTMLElement} element An element to check. * @returns {boolean} */ function hasHorizontalScrollbar(element) { return element.offsetHeight !== element.clientHeight; } /** * Sets overlay position depending on it's type and used browser. * * @param {HTMLElement} overlayElem An element to process. * @param {number|string} left The left position of the overlay. * @param {number|string} top The top position of the overlay. */ function setOverlayPosition(overlayElem, left, top) { overlayElem.style.transform = `translate3d(${left},${top},0)`; } /** * @param {HTMLElement} element An element to process. * @returns {number|Array} */ function getCssTransform(element) { let transform; if (element.style.transform && (transform = element.style.transform) !== '') { return ['transform', transform]; } return -1; } /** * @param {HTMLElement} element An element to process. */ function resetCssTransform(element) { if (element.style.transform && element.style.transform !== '') { element.style.transform = ''; } } /** * Determines if the given DOM element is an input field. * Notice: By 'input' we mean input, textarea and select nodes. * * @param {HTMLElement} element - DOM element. * @returns {boolean} */ function isInput(element) { const inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return element && (inputs.indexOf(element.nodeName) > -1 || element.contentEditable === 'true'); } /** * Determines if the given DOM element is an input field placed OUTSIDE of HOT. * Notice: By 'input' we mean input, textarea and select nodes which have defined 'data-hot-input' attribute. * * @param {HTMLElement} element - DOM element. * @returns {boolean} */ function isOutsideInput(element) { return isInput(element) && element.hasAttribute('data-hot-input') === false; } /** * Check if the given DOM element can be focused (by using "select" method). * * @param {HTMLElement} element - DOM element. */ function selectElementIfAllowed(element) { const activeElement = element.ownerDocument.activeElement; if (!isOutsideInput(activeElement)) { element.select(); } } /** * Check if the provided element is detached from DOM. * * @param {HTMLElement} element HTML element to be checked. * @returns {boolean} `true` if the element is detached, `false` otherwise. */ function isDetached(element) { return !element.parentNode; } /** * Set up an observer to recognize when the provided element first becomes visible and trigger a callback when it * happens. * * @param {HTMLElement} elementToBeObserved Element to be observed. * @param {Function} callback The callback function. */ function observeVisibilityChangeOnce(elementToBeObserved, callback) { const visibilityObserver = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting && elementToBeObserved.offsetParent !== null) { callback(); observer.unobserve(elementToBeObserved); } }); }, { root: elementToBeObserved.ownerDocument.body }); visibilityObserver.observe(elementToBeObserved); } /** * Add a `contenteditable` attribute, select the contents and optionally add the `invisibleSelection` * class to the provided element. * * @param {HTMLElement} element Element to be processed. * @param {boolean} [invisibleSelection=true] `true` if the class should be added to the element. * @param {boolean} [ariaHidden=true] `true` if the `aria-hidden` attribute should be added to the processed element. */ function makeElementContentEditableAndSelectItsContent(element) { let invisibleSelection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; let ariaHidden = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; const ownerDocument = element.ownerDocument; const range = ownerDocument.createRange(); const sel = ownerDocument.defaultView.getSelection(); setAttribute(element, 'contenteditable', true); if (ariaHidden) { setAttribute(element, ...(0, _a11y.A11Y_HIDDEN)()); } if (invisibleSelection) { addClass(element, 'invisibleSelection'); } range.selectNodeContents(element); sel.removeAllRanges(); sel.addRange(range); } /** * Remove the `contenteditable` attribute, deselect the contents and optionally remove the `invisibleSelection` * class from the provided element. * * @param {HTMLElement} selectedElement The element to be deselected. * @param {boolean} [removeInvisibleSelectionClass=true] `true` if the class should be removed from the element. */ function removeContentEditableFromElementAndDeselect(selectedElement) { let removeInvisibleSelectionClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; const sel = selectedElement.ownerDocument.defaultView.getSelection(); if (selectedElement.hasAttribute('aria-hidden')) { selectedElement.removeAttribute('aria-hidden'); } sel.removeAllRanges(); if (removeInvisibleSelectionClass) { removeClass(selectedElement, 'invisibleSelection'); } selectedElement.removeAttribute('contenteditable'); } /** * Run the provided callback while the provided element is selected and modified to have the `contenteditable` * attribute added. Optionally, the selection can be configured to be invisible. * * @param {HTMLElement} element Element to be selected. * @param {Function} callback Callback to be called. * @param {boolean} [invisibleSelection=true] `true` if the selection should be invisible. */ function runWithSelectedContendEditableElement(element, callback) { let invisibleSelection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; makeElementContentEditableAndSelectItsContent(element, invisibleSelection); callback(); removeContentEditableFromElementAndDeselect(element, invisibleSelection); } /***/ }), /* 328 */ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var _interopRequireDefault = __webpack_require__(197); exports.__esModule = true; exports.equalsIgnoreCase = equalsIgnoreCase; exports.isPercentValue = isPercentValue; exports.randomString = randomString; exports.sanitize = sanitize; exports.stripTags = stripTags; exports.substitute = substitute; exports.toUpperCaseFirst = toUpperCaseFirst; __webpack_require__(286); var _dompurify = _interopRequireDefault(__webpack_require__(329)); var _mixed = __webpack_require__(330); /** * Convert string to upper case first letter. * * @param {string} string String to convert. * @returns {string} */ function toUpperCaseFirst(string) { return string[0].toUpperCase() + string.substr(1); } /** * Compare strings case insensitively. * * @param {...string} strings Strings to compare. * @returns {boolean} */ function equalsIgnoreCase() { const unique = []; for (var _len = arguments.length, strings = new Array(_len), _key = 0; _key < _len; _key++) { strings[_key] = arguments[_key]; } let length = strings.length; while (length) { length -= 1; const string = (0, _mixed.stringify)(strings[length]).toLowerCase(); if (unique.indexOf(string) === -1) { unique.push(string); } } return unique.length === 1; } /** * Generates a random hex string. Used as namespace for Handsontable instance events. * * @returns {string} Returns 16-long character random string (eq. `'92b1bfc74ec4'`). */ function randomString() { /** * @returns {string} */ function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + s4() + s4(); } /** * Checks if value is valid percent. * * @param {string} value The value to check. * @returns {boolean} */ function isPercentValue(value) { return /^([0-9][0-9]?%$)|(^100%$)/.test(value); } /** * Substitute strings placed beetwen square brackets into value defined in `variables` object. String names defined in * square brackets must be the same as property name of `variables` object. * * @param {string} template Template string. * @param {object} variables Object which contains all available values which can be injected into template. * @returns {string} */ function substitute(template) { let variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return `${template}`.replace(/(?:\\)?\[([^[\]]+)]/g, (match, name) => { if (match.charAt(0) === '\\') { return match.substr(1, match.length - 1); } return variables[name] === undefined ? '' : variables[name]; }); } /** * Strip any HTML tag from the string. * * @param {string} string String to cut HTML from. * @returns {string} */ function stripTags(string) { return sanitize(`${string}`, { ALLOWED_TAGS: [] }); } /** * Sanitizes string from potential security vulnerabilities. * * @param {string} string String to sanitize. * @param {object} [options] DOMPurify's configuration object. * @returns {string} */ function sanitize(string, options) { return _dompurify.default.sanitize(string, options); } /***/ }), /* 329 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*! @license DOMPurify 2.5.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.5.7/LICENSE */ (function (global, factory) { true ? module.exports = factory() : 0; })(this, (function () { 'use strict'; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var freeze = Object.freeze, seal = Object.seal, create = Object.create; // eslint-disable-line import/no-mutable-exports var _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct; if (!apply) { apply = function apply(fun, thisValue, args) { return fun.apply(thisValue, args); }; } if (!freeze) { freeze = function freeze(x) { return x; }; } if (!seal) { seal = function seal(x) { return x; }; } if (!construct) { construct = function construct(Func, args) { return _construct(Func, _toConsumableArray(args)); }; } var arrayForEach = unapply(Array.prototype.forEach); var arrayPop = unapply(Array.prototype.pop); var arrayPush = unapply(Array.prototype.push); var stringToLowerCase = unapply(String.prototype.toLowerCase); var stringToString = unapply(String.prototype.toString); var stringMatch = unapply(String.prototype.match); var stringReplace = unapply(String.prototype.replace); var stringIndexOf = unapply(String.prototype.indexOf); var stringTrim = unapply(String.prototype.trim); var regExpTest = unapply(RegExp.prototype.test); var typeErrorCreate = unconstruct(TypeError); function unapply(func) { return function (thisArg) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return apply(func, thisArg, args); }; } function unconstruct(func) { return function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return construct(func, args); }; } /* Add properties to a lookup table */ function addToSet(set, array, transformCaseFunc) { var _transformCaseFunc; transformCaseFunc = (_transformCaseFunc = transformCaseFunc) !== null && _transformCaseFunc !== void 0 ? _transformCaseFunc : stringToLowerCase; if (setPrototypeOf) { // Make 'in' and truthy checks like Boolean(set.constructor) // independent of any properties defined on Object.prototype. // Prevent prototype setters from intercepting set as a this value. setPrototypeOf(set, null); } var l = array.length; while (l--) { var element = array[l]; if (typeof element === 'string') { var lcElement = transformCaseFunc(element); if (lcElement !== element) { // Config presets (e.g. tags.js, attrs.js) are immutable. if (!isFrozen(array)) { array[l] = lcElement; } element = lcElement; } } set[element] = true; } return set; } /* Shallow clone an object */ function clone(object) { var newObject = create(null); var property; for (property in object) { if (apply(hasOwnProperty, object, [property]) === true) { newObject[property] = object[property]; } } return newObject; } /* IE10 doesn't support __lookupGetter__ so lets' * simulate it. It also automatically checks * if the prop is function or getter and behaves * accordingly. */ function lookupGetter(object, prop) { while (object !== null) { var desc = getOwnPropertyDescriptor(object, prop); if (desc) { if (desc.get) { return unapply(desc.get); } if (typeof desc.value === 'function') { return unapply(desc.value); } } object = getPrototypeOf(object); } function fallbackValue(element) { console.warn('fallback value for', element); return null; } return fallbackValue; } var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default. // We still need to know them so that we can do namespace // checks properly in case one wants to add them to // allow-list. var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements, // even those that we disallow by default. var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); var text = freeze(['#text']); var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']); var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); // eslint-disable-next-line unicorn/better-regex var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm); var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape ); var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex ); var DOCTYPE_NAME = seal(/^html$/i); var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); var getGlobal = function getGlobal() { return typeof window === 'undefined' ? null : window; }; /** * Creates a no-op policy for internal use only. * Don't export this function outside this module! * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory. * @param {Document} document The document object (to determine policy name suffix) * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types * are not supported). */ var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) { if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') { return null; } // Allow the callers to control the unique policy name // by adding a data-tt-policy-suffix to the script element with the DOMPurify. // Policy creation with duplicate names throws in Trusted Types. var suffix = null; var ATTR_NAME = 'data-tt-policy-suffix'; if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) { suffix = document.currentScript.getAttribute(ATTR_NAME); } var policyName = 'dompurify' + (suffix ? '#' + suffix : ''); try { return trustedTypes.createPolicy(policyName, { createHTML: function createHTML(html) { return html; }, createScriptURL: function createScriptURL(scriptUrl) { return scriptUrl; } }); } catch (_) { // Policy creation failed (most likely another DOMPurify script has // already run). Skip creating the policy, as this will only cause errors // if TT are enforced. console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); return null; } }; function createDOMPurify() { var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); var DOMPurify = function DOMPurify(root) { return createDOMPurify(root); }; /** * Version label, exposed for easier checks * if DOMPurify is up to date or not */ DOMPurify.version = '2.5.7'; /** * Array of elements that DOMPurify removed during sanitation. * Empty if nothing was removed. */ DOMPurify.removed = []; if (!window || !window.document || window.document.nodeType !== 9) { // Not running in a browser, provide a factory function // so that you can pass your own Window DOMPurify.isSupported = false; return DOMPurify; } var originalDocument = window.document; var document = window.document; var DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window.HTMLFormElement, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes; var ElementPrototype = Element.prototype; var cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); var getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a // new document created via createHTMLDocument. As per the spec // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) // a new empty registry is used when creating a template contents owner // document, so we use that as our parent document to ensure nothing // is inherited. if (typeof HTMLTemplateElement === 'function') { var template = document.createElement('template'); if (template.content && template.content.ownerDocument) { document = template.content.ownerDocument; } } var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument); var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : ''; var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName; var importNode = originalDocument.importNode; var documentMode = {}; try { documentMode = clone(document).documentMode ? document.documentMode : {}; } catch (_) {} var hooks = {}; /** * Expose whether this browser supports running the full DOMPurify. */ DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined && documentMode !== 9; var MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE, CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT; var IS_ALLOWED_URI$1 = IS_ALLOWED_URI; /** * We consider the elements and attributes below to be safe. Ideally * don't add any new ones but feel free to remove unwanted ones. */ /* allowed element names */ var ALLOWED_TAGS = null; var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text))); /* Allowed attribute names */ var ALLOWED_ATTR = null; var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml))); /* * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements. * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. */ var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, { tagNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, allowCustomizedBuiltInElements: { writable: true, configurable: false, enumerable: true, value: false } })); /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ var FORBID_TAGS = null; /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ var FORBID_ATTR = null; /* Decide if ARIA attributes are okay */ var ALLOW_ARIA_ATTR = true; /* Decide if custom data attributes are okay */ var ALLOW_DATA_ATTR = true; /* Decide if unknown protocols are okay */ var ALLOW_UNKNOWN_PROTOCOLS = false; /* Decide if self-closing tags in attributes are allowed. * Usually removed due to a mXSS issue in jQuery 3.0 */ var ALLOW_SELF_CLOSE_IN_ATTR = true; /* Output should be safe for common template engines. * This means, DOMPurify removes data attributes, mustaches and ERB */ var SAFE_FOR_TEMPLATES = false; /* Output should be safe even for XML used within HTML and alike. * This means, DOMPurify removes comments when containing risky content. */ var SAFE_FOR_XML = true; /* Decide if document with ... should be returned */ var WHOLE_DOCUMENT = false; /* Track whether config is already set on this instance of DOMPurify. */ var SET_CONFIG = false; /* Decide if all elements (e.g. style, script) must be children of * document.body. By default, browsers might move them to document.head */ var FORCE_BODY = false; /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported). * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead */ var RETURN_DOM = false; /* Decide if a DOM `DocumentFragment` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported) */ var RETURN_DOM_FRAGMENT = false; /* Try to return a Trusted Type object instead of a string, return a string in * case Trusted Types are not supported */ var RETURN_TRUSTED_TYPE = false; /* Output should be free from DOM clobbering attacks? * This sanitizes markups named with colliding, clobberable built-in DOM APIs. */ var SANITIZE_DOM = true; /* Achieve full DOM Clobbering protection by isolating the namespace of named * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. * * HTML/DOM spec rules that enable DOM Clobbering: * - Named Access on Window (§7.3.3) * - DOM Tree Accessors (§3.1.5) * - Form Element Parent-Child Relations (§4.10.3) * - Iframe srcdoc / Nested WindowProxies (§4.8.5) * - HTMLCollection (§4.2.10.2) * * Namespace isolation is implemented by prefixing `id` and `name` attributes * with a constant string, i.e., `user-content-` */ var SANITIZE_NAMED_PROPS = false; var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; /* Keep element content when removing element? */ var KEEP_CONTENT = true; /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead * of importing it into a new Document and returning a sanitized copy */ var IN_PLACE = false; /* Allow usage of profiles like html, svg and mathMl */ var USE_PROFILES = {}; /* Tags to ignore content of when KEEP_CONTENT is true */ var FORBID_CONTENTS = null; var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); /* Tags that are safe for data: URIs */ var DATA_URI_TAGS = null; var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); /* Attributes safe for values like "javascript:" */ var URI_SAFE_ATTRIBUTES = null; var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; /* Document namespace */ var NAMESPACE = HTML_NAMESPACE; var IS_EMPTY_INPUT = false; /* Allowed XHTML+XML namespaces */ var ALLOWED_NAMESPACES = null; var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); /* Parsing of strict XHTML documents */ var PARSER_MEDIA_TYPE; var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; var DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; var transformCaseFunc; /* Keep a reference to config to pass to hooks */ var CONFIG = null; /* Ideally, do not touch anything below this line */ /* ______________________________________________ */ var formElement = document.createElement('form'); var isRegexOrFunction = function isRegexOrFunction(testValue) { return testValue instanceof RegExp || testValue instanceof Function; }; /** * _parseConfig * * @param {Object} cfg optional config literal */ // eslint-disable-next-line complexity var _parseConfig = function _parseConfig(cfg) { if (CONFIG && CONFIG === cfg) { return; } /* Shield configuration object from tampering */ if (!cfg || _typeof(cfg) !== 'object') { cfg = {}; } /* Shield configuration object from prototype pollution */ cfg = clone(cfg); PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; /* Set configuration parameters */ ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent transformCaseFunc // eslint-disable-line indent ) // eslint-disable-line indent : DEFAULT_URI_SAFE_ATTRIBUTES; DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent transformCaseFunc // eslint-disable-line indent ) // eslint-disable-line indent : DEFAULT_DATA_URI_TAGS; FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false; ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false RETURN_DOM = cfg.RETURN_DOM || false; // Default false RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false FORCE_BODY = cfg.FORCE_BODY || false; // Default false SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true IN_PLACE = cfg.IN_PLACE || false; // Default false IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1; NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; } if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; } if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') { CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; } if (SAFE_FOR_TEMPLATES) { ALLOW_DATA_ATTR = false; } if (RETURN_DOM_FRAGMENT) { RETURN_DOM = true; } /* Parse profile info */ if (USE_PROFILES) { ALLOWED_TAGS = addToSet({}, _toConsumableArray(text)); ALLOWED_ATTR = []; if (USE_PROFILES.html === true) { addToSet(ALLOWED_TAGS, html$1); addToSet(ALLOWED_ATTR, html); } if (USE_PROFILES.svg === true) { addToSet(ALLOWED_TAGS, svg$1); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.svgFilters === true) { addToSet(ALLOWED_TAGS, svgFilters); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.mathMl === true) { addToSet(ALLOWED_TAGS, mathMl$1); addToSet(ALLOWED_ATTR, mathMl); addToSet(ALLOWED_ATTR, xml); } } /* Merge configuration parameters */ if (cfg.ADD_TAGS) { if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { ALLOWED_TAGS = clone(ALLOWED_TAGS); } addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); } if (cfg.ADD_ATTR) { if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { ALLOWED_ATTR = clone(ALLOWED_ATTR); } addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); } if (cfg.ADD_URI_SAFE_ATTR) { addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); } if (cfg.FORBID_CONTENTS) { if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { FORBID_CONTENTS = clone(FORBID_CONTENTS); } addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); } /* Add #text in case KEEP_CONTENT is set to true */ if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; } /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ if (WHOLE_DOCUMENT) { addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); } /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ if (ALLOWED_TAGS.table) { addToSet(ALLOWED_TAGS, ['tbody']); delete FORBID_TAGS.tbody; } // Prevent further manipulation of configuration. // Not available in IE8, Safari 5, etc. if (freeze) { freeze(cfg); } CONFIG = cfg; }; var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); var HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); // Certain elements are allowed in both SVG and HTML // namespace. We need to specify them explicitly // so that they don't get erroneously deleted from // HTML namespace. var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); /* Keep track of all possible SVG and MathML tags * so that we can perform the namespace checks * correctly. */ var ALL_SVG_TAGS = addToSet({}, svg$1); addToSet(ALL_SVG_TAGS, svgFilters); addToSet(ALL_SVG_TAGS, svgDisallowed); var ALL_MATHML_TAGS = addToSet({}, mathMl$1); addToSet(ALL_MATHML_TAGS, mathMlDisallowed); /** * * * @param {Element} element a DOM element whose namespace is being checked * @returns {boolean} Return false if the element has a * namespace that a spec-compliant parser would never * return. Return true otherwise. */ var _checkValidNamespace = function _checkValidNamespace(element) { var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode // can be null. We just simulate parent in this case. if (!parent || !parent.tagName) { parent = { namespaceURI: NAMESPACE, tagName: 'template' }; } var tagName = stringToLowerCase(element.tagName); var parentTagName = stringToLowerCase(parent.tagName); if (!ALLOWED_NAMESPACES[element.namespaceURI]) { return false; } if (element.namespaceURI === SVG_NAMESPACE) { // The only way to switch from HTML namespace to SVG // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'svg'; } // The only way to switch from MathML to SVG is via` // svg if parent is either or MathML // text integration points. if (parent.namespaceURI === MATHML_NAMESPACE) { return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); } // We only allow elements that are defined in SVG // spec. All others are disallowed in SVG namespace. return Boolean(ALL_SVG_TAGS[tagName]); } if (element.namespaceURI === MATHML_NAMESPACE) { // The only way to switch from HTML namespace to MathML // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'math'; } // The only way to switch from SVG to MathML is via // and HTML integration points if (parent.namespaceURI === SVG_NAMESPACE) { return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; } // We only allow elements that are defined in MathML // spec. All others are disallowed in MathML namespace. return Boolean(ALL_MATHML_TAGS[tagName]); } if (element.namespaceURI === HTML_NAMESPACE) { // The only way to switch from SVG to HTML is via // HTML integration points, and from MathML to HTML // is via MathML text integration points if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { return false; } if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { return false; } // We disallow tags that are specific for MathML // or SVG and should never appear in HTML namespace return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); } // For XHTML and XML documents that support custom namespaces if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { return true; } // The code should never reach this place (this means // that the element somehow got namespace that is not // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). // Return false just in case. return false; }; /** * _forceRemove * * @param {Node} node a DOM node */ var _forceRemove = function _forceRemove(node) { arrayPush(DOMPurify.removed, { element: node }); try { // eslint-disable-next-line unicorn/prefer-dom-node-remove node.parentNode.removeChild(node); } catch (_) { try { node.outerHTML = emptyHTML; } catch (_) { node.remove(); } } }; /** * _removeAttribute * * @param {String} name an Attribute name * @param {Node} node a DOM node */ var _removeAttribute = function _removeAttribute(name, node) { try { arrayPush(DOMPurify.removed, { attribute: node.getAttributeNode(name), from: node }); } catch (_) { arrayPush(DOMPurify.removed, { attribute: null, from: node }); } node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes if (name === 'is' && !ALLOWED_ATTR[name]) { if (RETURN_DOM || RETURN_DOM_FRAGMENT) { try { _forceRemove(node); } catch (_) {} } else { try { node.setAttribute(name, ''); } catch (_) {} } } }; /** * _initDocument * * @param {String} dirty a string of dirty markup * @return {Document} a DOM, filled with the dirty markup */ var _initDocument = function _initDocument(dirty) { /* Create a HTML document */ var doc; var leadingWhitespace; if (FORCE_BODY) { dirty = '' + dirty; } else { /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ var matches = stringMatch(dirty, /^[\r\n\t ]+/); leadingWhitespace = matches && matches[0]; } if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) dirty = '' + dirty + ''; } var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; /* * Use the DOMParser API by default, fallback later if needs be * DOMParser not work for svg when has multiple root element. */ if (NAMESPACE === HTML_NAMESPACE) { try { doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); } catch (_) {} } /* Use createHTMLDocument in case DOMParser is not available */ if (!doc || !doc.documentElement) { doc = implementation.createDocument(NAMESPACE, 'template', null); try { doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; } catch (_) { // Syntax error if dirtyPayload is invalid xml } } var body = doc.body || doc.documentElement; if (dirty && leadingWhitespace) { body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); } /* Work on whole document or just its body */ if (NAMESPACE === HTML_NAMESPACE) { return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; } return WHOLE_DOCUMENT ? doc.documentElement : body; }; /** * _createIterator * * @param {Document} root document/fragment to create iterator for * @return {Iterator} iterator instance */ var _createIterator = function _createIterator(root) { return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null, false); }; /** * _isClobbered * * @param {Node} elm element to check for clobbering attacks * @return {Boolean} true if clobbered, false if safe */ var _isClobbered = function _isClobbered(elm) { return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function'); }; /** * _isNode * * @param {Node} obj object to check whether it's a DOM node * @return {Boolean} true is object is a DOM node */ var _isNode = function _isNode(object) { return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'; }; /** * _executeHook * Execute user configurable hooks * * @param {String} entryPoint Name of the hook's entry point * @param {Node} currentNode node to work on with the hook * @param {Object} data additional hook parameters */ var _executeHook = function _executeHook(entryPoint, currentNode, data) { if (!hooks[entryPoint]) { return; } arrayForEach(hooks[entryPoint], function (hook) { hook.call(DOMPurify, currentNode, data, CONFIG); }); }; /** * _sanitizeElements * * @protect nodeName * @protect textContent * @protect removeChild * * @param {Node} currentNode to check for permission to exist * @return {Boolean} true if node was killed, false if left alive */ var _sanitizeElements = function _sanitizeElements(currentNode) { var content; /* Execute a hook if present */ _executeHook('beforeSanitizeElements', currentNode, null); /* Check if element is clobbered or can clobber */ if (_isClobbered(currentNode)) { _forceRemove(currentNode); return true; } /* Check if tagname contains Unicode */ if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) { _forceRemove(currentNode); return true; } /* Now let's check the element's type and name */ var tagName = transformCaseFunc(currentNode.nodeName); /* Execute a hook if present */ _executeHook('uponSanitizeElement', currentNode, { tagName: tagName, allowedTags: ALLOWED_TAGS }); /* Detect mXSS attempts abusing namespace confusion */ if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { _forceRemove(currentNode); return true; } /* Mitigate a problem with templates inside select */ if (tagName === 'select' && regExpTest(/