@itwin/core-bentley 4.0.0-dev.4 → 4.0.0-dev.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -12
- package/lib/cjs/Assert.js +1 -1
- package/lib/cjs/Assert.js.map +1 -1
- package/lib/cjs/BeSQLite.d.ts +2 -0
- package/lib/cjs/BeSQLite.d.ts.map +1 -1
- package/lib/cjs/BeSQLite.js +2 -0
- package/lib/cjs/BeSQLite.js.map +1 -1
- package/lib/cjs/BentleyError.d.ts.map +1 -1
- package/lib/cjs/BentleyError.js +1 -0
- package/lib/cjs/BentleyError.js.map +1 -1
- package/lib/cjs/CompressedId64Set.js +4 -4
- package/lib/cjs/CompressedId64Set.js.map +1 -1
- package/lib/cjs/Logger.js +2 -4
- package/lib/cjs/Logger.js.map +1 -1
- package/lib/cjs/OneAtATimeAction.js +1 -1
- package/lib/cjs/OneAtATimeAction.js.map +1 -1
- package/lib/cjs/SortedArray.d.ts +4 -0
- package/lib/cjs/SortedArray.d.ts.map +1 -1
- package/lib/cjs/SortedArray.js +12 -0
- package/lib/cjs/SortedArray.js.map +1 -1
- package/lib/cjs/Tracing.js +4 -7
- package/lib/cjs/Tracing.js.map +1 -1
- package/lib/cjs/TypedArrayBuilder.js +3 -5
- package/lib/cjs/TypedArrayBuilder.js.map +1 -1
- package/lib/esm/Assert.js +1 -1
- package/lib/esm/Assert.js.map +1 -1
- package/lib/esm/BeSQLite.d.ts +2 -0
- package/lib/esm/BeSQLite.d.ts.map +1 -1
- package/lib/esm/BeSQLite.js +2 -0
- package/lib/esm/BeSQLite.js.map +1 -1
- package/lib/esm/BentleyError.d.ts.map +1 -1
- package/lib/esm/BentleyError.js +1 -0
- package/lib/esm/BentleyError.js.map +1 -1
- package/lib/esm/CompressedId64Set.js +4 -4
- package/lib/esm/CompressedId64Set.js.map +1 -1
- package/lib/esm/Logger.js +2 -4
- package/lib/esm/Logger.js.map +1 -1
- package/lib/esm/OneAtATimeAction.js +1 -1
- package/lib/esm/OneAtATimeAction.js.map +1 -1
- package/lib/esm/SortedArray.d.ts +4 -0
- package/lib/esm/SortedArray.d.ts.map +1 -1
- package/lib/esm/SortedArray.js +12 -0
- package/lib/esm/SortedArray.js.map +1 -1
- package/lib/esm/Tracing.js +4 -7
- package/lib/esm/Tracing.js.map +1 -1
- package/lib/esm/TypedArrayBuilder.js +3 -5
- package/lib/esm/TypedArrayBuilder.js.map +1 -1
- package/package.json +4 -4
package/lib/esm/Logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Logger.js","sourceRoot":"","sources":["../../src/Logger.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAQhE;;GAEG;AACH,MAAM,CAAN,IAAY,QAWX;AAXD,WAAY,QAAQ;IAClB,wCAAwC;IACxC,yCAAK,CAAA;IACL,8BAA8B;IAC9B,uCAAI,CAAA;IACJ,4BAA4B;IAC5B,6CAAO,CAAA;IACP,6BAA6B;IAC7B,yCAAK,CAAA;IACL,+EAA+E;IAC/E,uCAAI,CAAA;AACN,CAAC,EAXW,QAAQ,KAAR,QAAQ,QAWnB;AAkBD;;;GAGG;AACH,MAAM,OAAO,MAAM;IAmBjB,0FAA0F;IACnF,MAAM,CAAC,UAAU,CAAC,QAAsB,EAAE,UAAwB,EAAE,OAAqB,EAAE,QAAsB;QACtH,MAAM,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC5B,MAAM,CAAC,WAAW,GAAG,UAAU,CAAC;QAChC,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC;QAC1B,MAAM,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC5B,MAAM,CAAC,mBAAmB,EAAE,CAAC;QAC7B,MAAM,CAAC,iBAAiB,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C,eAAe,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,iBAAiB;IAChE,CAAC;IAEO,UAAU;QAChB,MAAM,YAAY,GAAW,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;QAClD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,qBAAqB,CAAC,WAAW,EAAE,UAAU,CAAC,SAAS,CAAC;YAC5E,OAAO;QAET,MAAM,CAAC,OAAO,CAAC,qBAAqB,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,UAAU,MAAM,EAAE,GAAG,EAAE;YAC/E,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7E,OAAO;gBACL,GAAG,KAAK,EAAE,WAAW,EAAE,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,2DAA2D;aACxH,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;;AAlCc,oBAAS,GAAa,QAAQ,CAAC,IAAI,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Logging\r\n */\r\n\r\nimport { BentleyError, IModelStatus, LoggingMetaData } from \"./BentleyError\";\r\nimport { BentleyLoggerCategory } from \"./BentleyLoggerCategory\";\r\nimport { IDisposable } from \"./Disposable\";\r\n\r\n/** Defines the *signature* for a log function.\r\n * @public\r\n */\r\nexport type LogFunction = (category: string, message: string, metaData: LoggingMetaData) => void;\r\n\r\n/** Use to categorize logging messages by severity.\r\n * @public\r\n */\r\nexport enum LogLevel {\r\n /** Tracing and debugging - low level */\r\n Trace,\r\n /** Information - mid level */\r\n Info,\r\n /** Warnings - high level */\r\n Warning,\r\n /** Errors - highest level */\r\n Error,\r\n /** Higher than any real logging level. This is used to turn a category off. */\r\n None,\r\n}\r\n\r\n/** Identifies a logging category and the LogLevel that should be used for it. The LogLevel is specified by its string name.\r\n * @public\r\n */\r\nexport interface LoggerCategoryAndLevel {\r\n category: string;\r\n logLevel: string;\r\n}\r\n\r\n/** Specifies logging levels, including the default logging level and a set of categories and levels for them.\r\n * @public\r\n */\r\nexport interface LoggerLevelsConfig {\r\n defaultLevel?: string;\r\n categoryLevels?: LoggerCategoryAndLevel[];\r\n}\r\n\r\n/** Logger allows libraries and apps to report potentially useful information about operations, and it allows apps and users to control\r\n * how or if the logged information is displayed or collected. See [Learning about Logging]($docs/learning/common/Logging.md).\r\n * @public\r\n */\r\nexport class Logger {\r\n protected static _logError: LogFunction | undefined;\r\n protected static _logWarning: LogFunction | undefined;\r\n protected static _logInfo: LogFunction | undefined;\r\n protected static _logTrace: LogFunction | undefined;\r\n /** @internal */\r\n public static logLevelChangedFn?: VoidFunction;\r\n private static _categoryFilter = new Map<string, LogLevel>(); // do not change the name of this member, it is referenced directly from node addon\r\n private static _minLevel: LogLevel | undefined = undefined; // do not change the name of this member, it is referenced directly from node addon\r\n\r\n /** Should the call stack be included when an exception is logged? */\r\n public static logExceptionCallstacks = false;\r\n\r\n /** All static metadata is combined with per-call metadata and stringified in every log message.\r\n * Static metadata can either be an object or a function that returns an object.\r\n * Use a key to identify entries in the map so the can be removed individually.\r\n * @internal */\r\n public static staticMetaData = new Map<string, LoggingMetaData>();\r\n\r\n /** Initialize the logger streams. Should be called at application initialization time. */\r\n public static initialize(logError?: LogFunction, logWarning?: LogFunction, logInfo?: LogFunction, logTrace?: LogFunction): void {\r\n Logger._logError = logError;\r\n Logger._logWarning = logWarning;\r\n Logger._logInfo = logInfo;\r\n Logger._logTrace = logTrace;\r\n Logger.turnOffLevelDefault();\r\n Logger.turnOffCategories();\r\n }\r\n\r\n /** Initialize the logger to output to the console. */\r\n public static initializeToConsole(): void {\r\n const logConsole = (level: string) => (category: string, message: string, metaData: LoggingMetaData) =>\r\n console.log(`${level} | ${category} | ${message} ${Logger.stringifyMetaData(metaData)}`); // eslint-disable-line no-console\r\n\r\n Logger.initialize(logConsole(\"Error\"), logConsole(\"Warning\"), logConsole(\"Info\"), logConsole(\"Trace\"));\r\n }\r\n\r\n /** merge the supplied metadata with all static metadata into one object */\r\n public static getMetaData(metaData?: LoggingMetaData): object {\r\n const metaObj = {};\r\n for (const meta of Logger.staticMetaData) {\r\n const val = BentleyError.getMetaData(meta[1]);\r\n if (val)\r\n Object.assign(metaObj, val);\r\n }\r\n Object.assign(metaObj, BentleyError.getMetaData(metaData)); // do this last so user supplied values take precedence\r\n return metaObj;\r\n }\r\n\r\n /** stringify the metadata for a log message by merging the supplied metadata with all static metadata into one object that is then `JSON.stringify`ed. */\r\n public static stringifyMetaData(metaData?: LoggingMetaData): string {\r\n const metaObj = this.getMetaData(metaData);\r\n return Object.keys(metaObj).length > 0 ? JSON.stringify(metaObj) : \"\";\r\n }\r\n\r\n /** Set the least severe level at which messages should be displayed by default. Call setLevel to override this default setting for specific categories. */\r\n public static setLevelDefault(minLevel: LogLevel): void {\r\n this._minLevel = minLevel;\r\n this.logLevelChangedFn?.();\r\n }\r\n\r\n /** Set the minimum logging level for the specified category. The minimum level is least severe level at which messages in the\r\n * specified category should be displayed.\r\n */\r\n public static setLevel(category: string, minLevel: LogLevel) {\r\n Logger._categoryFilter.set(category, minLevel);\r\n this.logLevelChangedFn?.();\r\n }\r\n\r\n /** Interpret a string as the name of a LogLevel */\r\n public static parseLogLevel(str: string): LogLevel {\r\n switch (str.toUpperCase()) {\r\n case \"EXCEPTION\": return LogLevel.Error;\r\n case \"FATAL\": return LogLevel.Error;\r\n case \"ERROR\": return LogLevel.Error;\r\n case \"WARNING\": return LogLevel.Warning;\r\n case \"INFO\": return LogLevel.Info;\r\n case \"TRACE\": return LogLevel.Trace;\r\n case \"DEBUG\": return LogLevel.Trace;\r\n }\r\n return LogLevel.None;\r\n }\r\n\r\n /** Set the log level for multiple categories at once. Also see [[validateProps]] */\r\n public static configureLevels(cfg: LoggerLevelsConfig) {\r\n Logger.validateProps(cfg);\r\n if (cfg.defaultLevel !== undefined) {\r\n this.setLevelDefault(Logger.parseLogLevel(cfg.defaultLevel));\r\n }\r\n if (cfg.categoryLevels !== undefined) {\r\n for (const cl of cfg.categoryLevels) {\r\n this.setLevel(cl.category, Logger.parseLogLevel(cl.logLevel));\r\n }\r\n }\r\n }\r\n\r\n private static isLogLevel(v: string) {\r\n return LogLevel.hasOwnProperty(v);\r\n }\r\n\r\n /** Check that the specified object is a valid LoggerLevelsConfig. This is useful when reading a config from a .json file. */\r\n public static validateProps(config: any) {\r\n const validProps = [\"defaultLevel\", \"categoryLevels\"];\r\n for (const prop of Object.keys(config)) {\r\n if (!validProps.includes(prop))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig - unrecognized property: ${prop}`);\r\n if (prop === \"defaultLevel\") {\r\n if (!Logger.isLogLevel(config.defaultLevel))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.defaultLevel must be a LogLevel. Invalid value: ${JSON.stringify(config.defaultLevel)}`);\r\n } else if (prop === \"categoryLevels\") {\r\n const value = config[prop];\r\n if (!Array.isArray(value))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels must be an array. Invalid value: ${JSON.stringify(value)}`);\r\n for (const item of config[prop]) {\r\n if (!item.hasOwnProperty(\"category\") || !item.hasOwnProperty(\"logLevel\"))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item must be a LoggerCategoryAndLevel {category: logLevel:}. Invalid value: ${JSON.stringify(item)}`);\r\n if (!Logger.isLogLevel(item.logLevel))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item's logLevel property must be a LogLevel. Invalid value: ${JSON.stringify(item.logLevel)}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** Get the minimum logging level for the specified category. */\r\n public static getLevel(category: string): LogLevel | undefined {\r\n // Prefer the level set for this category specifically\r\n const minLevelForThisCategory = Logger._categoryFilter.get(category);\r\n if (minLevelForThisCategory !== undefined)\r\n return minLevelForThisCategory;\r\n\r\n // Fall back on the level set for the parent of this category.\r\n const parent = category.lastIndexOf(\".\");\r\n if (parent !== -1)\r\n return Logger.getLevel(category.slice(0, parent));\r\n\r\n // Fall back on the default level.\r\n return Logger._minLevel;\r\n }\r\n\r\n /** Turns off the least severe level at which messages should be displayed by default.\r\n * This turns off logging for all messages for which no category minimum level is defined.\r\n */\r\n public static turnOffLevelDefault(): void {\r\n Logger._minLevel = undefined;\r\n }\r\n\r\n /** Turns off all category level filters previously defined with [[Logger.setLevel]].\r\n */\r\n public static turnOffCategories(): void {\r\n Logger._categoryFilter.clear();\r\n }\r\n\r\n /** Check if messages in the specified category should be displayed at this level of severity. */\r\n public static isEnabled(category: string, level: LogLevel): boolean {\r\n const minLevel = Logger.getLevel(category);\r\n return (minLevel !== undefined) && (level >= minLevel);\r\n }\r\n\r\n /** Log the specified message to the **error** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logError(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logError && Logger.isEnabled(category, LogLevel.Error))\r\n Logger._logError(category, message, metaData);\r\n }\r\n\r\n private static getExceptionMessage(err: unknown): string {\r\n const stack = Logger.logExceptionCallstacks ? `\\n${BentleyError.getErrorStack(err)}` : \"\";\r\n return BentleyError.getErrorMessage(err) + stack;\r\n }\r\n\r\n /** Log the specified exception. The special \"ExceptionType\" property will be added as metadata,\r\n * in addition to any other metadata that may be supplied by the caller, unless the\r\n * metadata supplied by the caller already includes this property.\r\n * @param category The category of the message.\r\n * @param err The exception object.\r\n * @param log The logger output function to use - defaults to Logger.logError\r\n * @param metaData Optional data for the message\r\n */\r\n public static logException(category: string, err: any, log: LogFunction = Logger.logError): void {\r\n log(category, Logger.getExceptionMessage(err), () => {\r\n return { ...BentleyError.getErrorMetadata(err), exceptionType: err.constructor.name };\r\n });\r\n }\r\n\r\n /** Log the specified message to the **warning** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logWarning(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logWarning && Logger.isEnabled(category, LogLevel.Warning))\r\n Logger._logWarning(category, message, metaData);\r\n }\r\n\r\n /** Log the specified message to the **info** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logInfo(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logInfo && Logger.isEnabled(category, LogLevel.Info))\r\n Logger._logInfo(category, message, metaData);\r\n }\r\n\r\n /** Log the specified message to the **trace** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logTrace(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logTrace && Logger.isEnabled(category, LogLevel.Trace))\r\n Logger._logTrace(category, message, metaData);\r\n }\r\n}\r\n\r\n/** Simple performance diagnostics utility.\r\n * It measures the time from construction to disposal. On disposal it logs the routine name along with\r\n * the duration in milliseconds.\r\n * It also logs the routine name at construction time so that nested calls can be disambiguated.\r\n *\r\n * The timings are logged using the log category **Performance** and log severity [[LogLevel.INFO]].\r\n * Enable those, if you want to capture timings.\r\n * @public\r\n */\r\nexport class PerfLogger implements IDisposable {\r\n private static _severity: LogLevel = LogLevel.Info;\r\n\r\n private _operation: string;\r\n private _metaData?: LoggingMetaData;\r\n private _startTimeStamp: number;\r\n\r\n public constructor(operation: string, metaData?: LoggingMetaData) {\r\n this._operation = operation;\r\n this._metaData = metaData;\r\n\r\n if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity)) {\r\n this._startTimeStamp = 0;\r\n return;\r\n }\r\n\r\n Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},START`, this._metaData);\r\n this._startTimeStamp = new Date().getTime(); // take timestamp\r\n }\r\n\r\n private logMessage(): void {\r\n const endTimeStamp: number = new Date().getTime();\r\n if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity))\r\n return;\r\n\r\n Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},END`, () => {\r\n const mdata = this._metaData ? BentleyError.getMetaData(this._metaData) : {};\r\n return {\r\n ...mdata, TimeElapsed: endTimeStamp - this._startTimeStamp, // eslint-disable-line @typescript-eslint/naming-convention\r\n };\r\n });\r\n }\r\n\r\n public dispose(): void {\r\n this.logMessage();\r\n }\r\n}\r\n\r\n"]}
|
|
1
|
+
{"version":3,"file":"Logger.js","sourceRoot":"","sources":["../../src/Logger.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAQhE;;GAEG;AACH,MAAM,CAAN,IAAY,QAWX;AAXD,WAAY,QAAQ;IAClB,wCAAwC;IACxC,yCAAK,CAAA;IACL,8BAA8B;IAC9B,uCAAI,CAAA;IACJ,4BAA4B;IAC5B,6CAAO,CAAA;IACP,6BAA6B;IAC7B,yCAAK,CAAA;IACL,+EAA+E;IAC/E,uCAAI,CAAA;AACN,CAAC,EAXW,QAAQ,KAAR,QAAQ,QAWnB;AAkBD;;;GAGG;AACH,MAAM,OAAO,MAAM;IAmBjB,0FAA0F;IACnF,MAAM,CAAC,UAAU,CAAC,QAAsB,EAAE,UAAwB,EAAE,OAAqB,EAAE,QAAsB;QACtH,MAAM,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC5B,MAAM,CAAC,WAAW,GAAG,UAAU,CAAC;QAChC,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC;QA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AI,CAAC,UAAU,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QAC9F,IAAI,CAAC,eAAe,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,iBAAiB;IAChE,CAAC;IAEO,UAAU;QAChB,MAAM,YAAY,GAAW,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;QAClD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,qBAAqB,CAAC,WAAW,EAAE,UAAU,CAAC,SAAS,CAAC;YAC5E,OAAO;QAET,MAAM,CAAC,OAAO,CAAC,qBAAqB,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,UAAU,MAAM,EAAE,GAAG,EAAE;YAC/E,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7E,OAAO;gBACL,GAAG,KAAK,EAAE,WAAW,EAAE,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,2DAA2D;aACxH,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,OAAO;QACZ,IAAI,CAAC,UAAU,EAAE,CAAC;IACpB,CAAC;;AAlCc,oBAAS,GAAa,QAAQ,CAAC,IAAI,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Logging\r\n */\r\n\r\nimport { BentleyError, IModelStatus, LoggingMetaData } from \"./BentleyError\";\r\nimport { BentleyLoggerCategory } from \"./BentleyLoggerCategory\";\r\nimport { IDisposable } from \"./Disposable\";\r\n\r\n/** Defines the *signature* for a log function.\r\n * @public\r\n */\r\nexport type LogFunction = (category: string, message: string, metaData: LoggingMetaData) => void;\r\n\r\n/** Use to categorize logging messages by severity.\r\n * @public\r\n */\r\nexport enum LogLevel {\r\n /** Tracing and debugging - low level */\r\n Trace,\r\n /** Information - mid level */\r\n Info,\r\n /** Warnings - high level */\r\n Warning,\r\n /** Errors - highest level */\r\n Error,\r\n /** Higher than any real logging level. This is used to turn a category off. */\r\n None,\r\n}\r\n\r\n/** Identifies a logging category and the LogLevel that should be used for it. The LogLevel is specified by its string name.\r\n * @public\r\n */\r\nexport interface LoggerCategoryAndLevel {\r\n category: string;\r\n logLevel: string;\r\n}\r\n\r\n/** Specifies logging levels, including the default logging level and a set of categories and levels for them.\r\n * @public\r\n */\r\nexport interface LoggerLevelsConfig {\r\n defaultLevel?: string;\r\n categoryLevels?: LoggerCategoryAndLevel[];\r\n}\r\n\r\n/** Logger allows libraries and apps to report potentially useful information about operations, and it allows apps and users to control\r\n * how or if the logged information is displayed or collected. See [Learning about Logging]($docs/learning/common/Logging.md).\r\n * @public\r\n */\r\nexport class Logger {\r\n protected static _logError: LogFunction | undefined;\r\n protected static _logWarning: LogFunction | undefined;\r\n protected static _logInfo: LogFunction | undefined;\r\n protected static _logTrace: LogFunction | undefined;\r\n /** @internal */\r\n public static logLevelChangedFn?: VoidFunction;\r\n private static _categoryFilter = new Map<string, LogLevel>(); // do not change the name of this member, it is referenced directly from node addon\r\n private static _minLevel: LogLevel | undefined = undefined; // do not change the name of this member, it is referenced directly from node addon\r\n\r\n /** Should the call stack be included when an exception is logged? */\r\n public static logExceptionCallstacks = false;\r\n\r\n /** All static metadata is combined with per-call metadata and stringified in every log message.\r\n * Static metadata can either be an object or a function that returns an object.\r\n * Use a key to identify entries in the map so the can be removed individually.\r\n * @internal */\r\n public static staticMetaData = new Map<string, LoggingMetaData>();\r\n\r\n /** Initialize the logger streams. Should be called at application initialization time. */\r\n public static initialize(logError?: LogFunction, logWarning?: LogFunction, logInfo?: LogFunction, logTrace?: LogFunction): void {\r\n Logger._logError = logError;\r\n Logger._logWarning = logWarning;\r\n Logger._logInfo = logInfo;\r\n Logger._logTrace = logTrace;\r\n Logger.turnOffLevelDefault();\r\n Logger.turnOffCategories();\r\n }\r\n\r\n /** Initialize the logger to output to the console. */\r\n public static initializeToConsole(): void {\r\n const logConsole = (level: string) => (category: string, message: string, metaData: LoggingMetaData) =>\r\n console.log(`${level} | ${category} | ${message} ${Logger.stringifyMetaData(metaData)}`); // eslint-disable-line no-console\r\n\r\n Logger.initialize(logConsole(\"Error\"), logConsole(\"Warning\"), logConsole(\"Info\"), logConsole(\"Trace\"));\r\n }\r\n\r\n /** merge the supplied metadata with all static metadata into one object */\r\n public static getMetaData(metaData?: LoggingMetaData): object {\r\n const metaObj = {};\r\n for (const meta of Logger.staticMetaData) {\r\n const val = BentleyError.getMetaData(meta[1]);\r\n if (val)\r\n Object.assign(metaObj, val);\r\n }\r\n Object.assign(metaObj, BentleyError.getMetaData(metaData)); // do this last so user supplied values take precedence\r\n return metaObj;\r\n }\r\n\r\n /** stringify the metadata for a log message by merging the supplied metadata with all static metadata into one object that is then `JSON.stringify`ed. */\r\n public static stringifyMetaData(metaData?: LoggingMetaData): string {\r\n const metaObj = this.getMetaData(metaData);\r\n return Object.keys(metaObj).length > 0 ? JSON.stringify(metaObj) : \"\";\r\n }\r\n\r\n /** Set the least severe level at which messages should be displayed by default. Call setLevel to override this default setting for specific categories. */\r\n public static setLevelDefault(minLevel: LogLevel): void {\r\n this._minLevel = minLevel;\r\n this.logLevelChangedFn?.();\r\n }\r\n\r\n /** Set the minimum logging level for the specified category. The minimum level is least severe level at which messages in the\r\n * specified category should be displayed.\r\n */\r\n public static setLevel(category: string, minLevel: LogLevel) {\r\n Logger._categoryFilter.set(category, minLevel);\r\n this.logLevelChangedFn?.();\r\n }\r\n\r\n /** Interpret a string as the name of a LogLevel */\r\n public static parseLogLevel(str: string): LogLevel {\r\n switch (str.toUpperCase()) {\r\n case \"EXCEPTION\": return LogLevel.Error;\r\n case \"FATAL\": return LogLevel.Error;\r\n case \"ERROR\": return LogLevel.Error;\r\n case \"WARNING\": return LogLevel.Warning;\r\n case \"INFO\": return LogLevel.Info;\r\n case \"TRACE\": return LogLevel.Trace;\r\n case \"DEBUG\": return LogLevel.Trace;\r\n }\r\n return LogLevel.None;\r\n }\r\n\r\n /** Set the log level for multiple categories at once. Also see [[validateProps]] */\r\n public static configureLevels(cfg: LoggerLevelsConfig) {\r\n Logger.validateProps(cfg);\r\n if (cfg.defaultLevel !== undefined) {\r\n this.setLevelDefault(Logger.parseLogLevel(cfg.defaultLevel));\r\n }\r\n if (cfg.categoryLevels !== undefined) {\r\n for (const cl of cfg.categoryLevels) {\r\n this.setLevel(cl.category, Logger.parseLogLevel(cl.logLevel));\r\n }\r\n }\r\n }\r\n\r\n private static isLogLevel(v: string) {\r\n return LogLevel.hasOwnProperty(v);\r\n }\r\n\r\n /** Check that the specified object is a valid LoggerLevelsConfig. This is useful when reading a config from a .json file. */\r\n public static validateProps(config: any) {\r\n const validProps = [\"defaultLevel\", \"categoryLevels\"];\r\n for (const prop of Object.keys(config)) {\r\n if (!validProps.includes(prop))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig - unrecognized property: ${prop}`);\r\n if (prop === \"defaultLevel\") {\r\n if (!Logger.isLogLevel(config.defaultLevel))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.defaultLevel must be a LogLevel. Invalid value: ${JSON.stringify(config.defaultLevel)}`);\r\n } else if (prop === \"categoryLevels\") {\r\n const value = config[prop];\r\n if (!Array.isArray(value))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels must be an array. Invalid value: ${JSON.stringify(value)}`);\r\n for (const item of config[prop]) {\r\n if (!item.hasOwnProperty(\"category\") || !item.hasOwnProperty(\"logLevel\"))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item must be a LoggerCategoryAndLevel {category: logLevel:}. Invalid value: ${JSON.stringify(item)}`);\r\n if (!Logger.isLogLevel(item.logLevel))\r\n throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item's logLevel property must be a LogLevel. Invalid value: ${JSON.stringify(item.logLevel)}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /** Get the minimum logging level for the specified category. */\r\n public static getLevel(category: string): LogLevel | undefined {\r\n // Prefer the level set for this category specifically\r\n const minLevelForThisCategory = Logger._categoryFilter.get(category);\r\n if (minLevelForThisCategory !== undefined)\r\n return minLevelForThisCategory;\r\n\r\n // Fall back on the level set for the parent of this category.\r\n const parent = category.lastIndexOf(\".\");\r\n if (parent !== -1)\r\n return Logger.getLevel(category.slice(0, parent));\r\n\r\n // Fall back on the default level.\r\n return Logger._minLevel;\r\n }\r\n\r\n /** Turns off the least severe level at which messages should be displayed by default.\r\n * This turns off logging for all messages for which no category minimum level is defined.\r\n */\r\n public static turnOffLevelDefault(): void {\r\n Logger._minLevel = undefined;\r\n }\r\n\r\n /** Turns off all category level filters previously defined with [[Logger.setLevel]].\r\n */\r\n public static turnOffCategories(): void {\r\n Logger._categoryFilter.clear();\r\n }\r\n\r\n /** Check if messages in the specified category should be displayed at this level of severity. */\r\n public static isEnabled(category: string, level: LogLevel): boolean {\r\n const minLevel = Logger.getLevel(category);\r\n return (minLevel !== undefined) && (level >= minLevel);\r\n }\r\n\r\n /** Log the specified message to the **error** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logError(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logError && Logger.isEnabled(category, LogLevel.Error))\r\n Logger._logError(category, message, metaData);\r\n }\r\n\r\n private static getExceptionMessage(err: unknown): string {\r\n const stack = Logger.logExceptionCallstacks ? `\\n${BentleyError.getErrorStack(err)}` : \"\";\r\n return BentleyError.getErrorMessage(err) + stack;\r\n }\r\n\r\n /** Log the specified exception. The special \"ExceptionType\" property will be added as metadata,\r\n * in addition to any other metadata that may be supplied by the caller, unless the\r\n * metadata supplied by the caller already includes this property.\r\n * @param category The category of the message.\r\n * @param err The exception object.\r\n * @param log The logger output function to use - defaults to Logger.logError\r\n * @param metaData Optional data for the message\r\n */\r\n public static logException(category: string, err: any, log: LogFunction = Logger.logError): void {\r\n log(category, Logger.getExceptionMessage(err), () => {\r\n return { ...BentleyError.getErrorMetadata(err), exceptionType: err.constructor.name };\r\n });\r\n }\r\n\r\n /** Log the specified message to the **warning** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logWarning(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logWarning && Logger.isEnabled(category, LogLevel.Warning))\r\n Logger._logWarning(category, message, metaData);\r\n }\r\n\r\n /** Log the specified message to the **info** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logInfo(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logInfo && Logger.isEnabled(category, LogLevel.Info))\r\n Logger._logInfo(category, message, metaData);\r\n }\r\n\r\n /** Log the specified message to the **trace** stream.\r\n * @param category The category of the message.\r\n * @param message The message.\r\n * @param metaData Optional data for the message\r\n */\r\n public static logTrace(category: string, message: string, metaData?: LoggingMetaData): void {\r\n if (Logger._logTrace && Logger.isEnabled(category, LogLevel.Trace))\r\n Logger._logTrace(category, message, metaData);\r\n }\r\n}\r\n\r\n/** Simple performance diagnostics utility.\r\n * It measures the time from construction to disposal. On disposal it logs the routine name along with\r\n * the duration in milliseconds.\r\n * It also logs the routine name at construction time so that nested calls can be disambiguated.\r\n *\r\n * The timings are logged using the log category **Performance** and log severity [[LogLevel.INFO]].\r\n * Enable those, if you want to capture timings.\r\n * @public\r\n */\r\nexport class PerfLogger implements IDisposable {\r\n private static _severity: LogLevel = LogLevel.Info;\r\n\r\n private _operation: string;\r\n private _metaData?: LoggingMetaData;\r\n private _startTimeStamp: number;\r\n\r\n public constructor(operation: string, metaData?: LoggingMetaData) {\r\n this._operation = operation;\r\n this._metaData = metaData;\r\n\r\n if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity)) {\r\n this._startTimeStamp = 0;\r\n return;\r\n }\r\n\r\n Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},START`, this._metaData);\r\n this._startTimeStamp = new Date().getTime(); // take timestamp\r\n }\r\n\r\n private logMessage(): void {\r\n const endTimeStamp: number = new Date().getTime();\r\n if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity))\r\n return;\r\n\r\n Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},END`, () => {\r\n const mdata = this._metaData ? BentleyError.getMetaData(this._metaData) : {};\r\n return {\r\n ...mdata, TimeElapsed: endTimeStamp - this._startTimeStamp, // eslint-disable-line @typescript-eslint/naming-convention\r\n };\r\n });\r\n }\r\n\r\n public dispose(): void {\r\n this.logMessage();\r\n }\r\n}\r\n\r\n"]}
|
|
@@ -27,7 +27,7 @@ class PromiseWithAbandon {
|
|
|
27
27
|
/** Create a Promise that is chained to the underlying Promise, but is connected to the abandon method. */
|
|
28
28
|
async init(msg) {
|
|
29
29
|
return new Promise((resolve, reject) => {
|
|
30
|
-
this.abandon = (message) => reject(new AbandonedError(message
|
|
30
|
+
this.abandon = (message) => reject(new AbandonedError(message ?? msg));
|
|
31
31
|
this._resolve = resolve;
|
|
32
32
|
});
|
|
33
33
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OneAtATimeAction.js","sourceRoot":"","sources":["../../src/OneAtATimeAction.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,YAAY;AACZ,MAAM,OAAO,cAAe,SAAQ,KAAK;CAAI;AAE7C;;;;;GAKG;AACH,MAAM,kBAAkB;IAKtB;;;OAGG;IACH,YAAoB,IAAoC,EAAU,KAAY;QAA1D,SAAI,GAAJ,IAAI,CAAgC;QAAU,UAAK,GAAL,KAAK,CAAO;IAA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C;CACF;AAED;;;;;;;;;;GAUG;AACH,MAAM,OAAO,gBAAgB;IAM3B;;OAEG;IACH,YAAY,GAAmC,EAAE,GAAG,GAAG,WAAW;QAChE,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,OAAO,CAAC,GAAG,IAAW;QACjC,MAAM,KAAK,GAAG,IAAI,kBAAkB,CAAI,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,0CAA0C;QACpG,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,8FAA8F;QAEpI,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS,EAAE,EAAE,8BAA8B;YAC9D,IAAI,IAAI,CAAC,QAAQ,EAAE,8FAA8F;gBAC/G,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,iEAAiE;YAC5F,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;SACvB;aAAM;YACL,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC,uCAAuC;YAC7D,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,8DAA8D;SAC9E;QAED,IAAI;YACF,OAAO,MAAM,OAAO,CAAC;SACtB;gBAAS;YACR,2DAA2D;YAC3D,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,2CAA2C;YACzE,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,CAAC,gBAAgB;YAC3C,IAAI,IAAI,CAAC,OAAO;gBACd,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,8DAA8D;SACvF;IACH,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Utils\r\n */\r\n\r\nimport { BentleyError } from \"./BentleyError\";\r\n\r\n/** @beta */\r\nexport class AbandonedError extends Error { }\r\n\r\n/**\r\n * An object that returns a Promise when you call [[init]], but supplies a way to abandon the promise if it is no longer relevant.\r\n * When you call abandon, the promise will be rejected. You must supply a [[run]] method to the constructor that\r\n * creates the real Promise for the underlying action. Notice that to use this class there are really two\r\n * Promises involved that are chained together. That makes this class less efficient than just using a Promise directly.\r\n */\r\nclass PromiseWithAbandon<T> {\r\n /** Method to abandon the Promise created by [[init]] while it is outstanding. The promise will be rejected. */\r\n public abandon!: (msg?: string) => void;\r\n private _resolve!: (val: any) => void;\r\n\r\n /** Create a PromiseWithAbandon. After this call you must call [[init]] to create the underlying Promise.\r\n * @param _run The method that creates the underlying Promise.\r\n * @param _args An array of args to be passed to run when [[start]] is called.\r\n */\r\n constructor(private _run: (...args: any[]) => Promise<T>, private _args: any[]) { }\r\n\r\n /** Create a Promise that is chained to the underlying Promise, but is connected to the abandon method. */\r\n public async init(msg: string): Promise<T> {\r\n return new Promise<T>((resolve, reject) => {\r\n this.abandon = (message?: string) => reject(new AbandonedError(message ?? msg));\r\n this._resolve = resolve;\r\n });\r\n }\r\n\r\n /** Call the [[run]] method supplied to the ctor to start the underlying Promise. */\r\n public async start() {\r\n try {\r\n this._resolve(await this._run(...this._args));\r\n } catch (err) {\r\n this.abandon(BentleyError.getErrorMessage(err)); // turn all errors from execution into abandoned errors, but keep the message\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Orchestrator of a one-at-a-time activity. This concept is useful only for *replaceable* operations (that is, operations where subsequent requests replace and obviate\r\n * the need for previous requests. E.g. over slow HTTP connections, without this class, the stream of requests can overwhelm the connection, and cause the HTTP\r\n * request queue to grow such that the delay to service new requests is unbounded.\r\n *\r\n * With this class, we issue the initial request immediately. When the second request arrives before the first one completes, it becomes *pending*. If subsequent\r\n * requests arrive with a pending request, the current pending request is *abandoned* (its Promise is rejected) and the new request becomes pending.\r\n * When the active request completes, the pending request (if present) is started. In this manner there will only ever be one outstanding HTTP request for this type\r\n * of operation, but the first and last request will always eventually complete.\r\n * @beta\r\n */\r\nexport class OneAtATimeAction<T> {\r\n private _active?: PromiseWithAbandon<T>;\r\n private _pending?: PromiseWithAbandon<T>;\r\n private _run: (...args: any[]) => Promise<T>;\r\n public msg: string;\r\n\r\n /** Ctor for OneAtATimePromise.\r\n * @param run The method that performs an action that creates the Promise.\r\n */\r\n constructor(run: (...args: any[]) => Promise<T>, msg = \"abandoned\") {\r\n this._run = run;\r\n this.msg = msg;\r\n }\r\n\r\n /** Add a new request to this OneAtATimePromise. The request will only run when no other outstanding requests are active.\r\n * @note Callers of this method *must* handle AbandonedError rejections.\r\n */\r\n public async request(...args: any[]): Promise<T> {\r\n const entry = new PromiseWithAbandon<T>(this._run, args); // create an \"abandon-able promise\" object\r\n const promise = entry.init(this.msg); // create the Promise from PromiseWithAbandon. Note: this must be called before we call start.\r\n\r\n if (this._active !== undefined) { // is there an active request?\r\n if (this._pending) // yes. If there is also a pending request, this one replaces it and previous one is abandoned\r\n this._pending.abandon(); // rejects previous call to this method, throwing AbandonedError.\r\n this._pending = entry;\r\n } else {\r\n this._active = entry; // this is the first request, start it.\r\n entry.start(); // eslint-disable-line @typescript-eslint/no-floating-promises\r\n }\r\n\r\n try {\r\n return await promise;\r\n } finally {\r\n // do all of this whether promise was fulfilled or rejected\r\n this._active = this._pending; // see if there's a pending request waiting\r\n this._pending = undefined; // clear pending\r\n if (this._active)\r\n this._active.start(); // eslint-disable-line @typescript-eslint/no-floating-promises\r\n }\r\n }\r\n}\r\n"]}
|
package/lib/esm/SortedArray.d.ts
CHANGED
|
@@ -128,6 +128,8 @@ export declare class ReadonlySortedArray<T> implements Iterable<T> {
|
|
|
128
128
|
* @param func The function to be applied.
|
|
129
129
|
*/
|
|
130
130
|
forEach(func: (value: T) => void): void;
|
|
131
|
+
/** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */
|
|
132
|
+
slice(start?: number, end?: number): ReadonlySortedArray<T>;
|
|
131
133
|
/**
|
|
132
134
|
* Computes the position at which the specified value should be inserted to maintain sorted order.
|
|
133
135
|
* @param value The value whose position is to be computed.
|
|
@@ -229,5 +231,7 @@ export declare class SortedArray<T> extends ReadonlySortedArray<T> {
|
|
|
229
231
|
* @returns the index of the deleted value, or -1 if no such element exists.
|
|
230
232
|
*/
|
|
231
233
|
remove(value: T): number;
|
|
234
|
+
/** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */
|
|
235
|
+
slice(start?: number, end?: number): SortedArray<T>;
|
|
232
236
|
}
|
|
233
237
|
//# sourceMappingURL=SortedArray.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SortedArray.d.ts","sourceRoot":"","sources":["../../src/SortedArray.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C;;;;GAIG;AACH,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;AAE/C;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,KAEvC;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAE7H;AAmBD;;;GAGG;AACH,oBAAY,eAAe;IACzB;;OAEG;IACH,KAAK,IAAA;IACL,mJAAmJ;IACnJ,MAAM,IAAA;IACN;;OAEG;IACH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;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,SAAQ,mBAAmB,CAAC,CAAC,CAAC;IACxD;;;;;OAKG;gBACgB,OAAO,EAAE,iBAAiB,CAAC,CAAC,CAAC,EAAE,eAAe,GAAE,eAAe,GAAG,OAAe,EAAE,KAAK,GAAE,aAAa,CAAC,CAAC,CAAgB;IAI5I,+CAA+C;IACxC,KAAK,IAAI,IAAI;IAEpB;;OAEG;IACI,YAAY,IAAI,CAAC,EAAE;IAE1B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,GAAG,GAAG,MAAM;IAE7D;;;;OAIG;IACI,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM;IAE/B,qIAAqI;IACrH,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC;CAKpE"}
|
package/lib/esm/SortedArray.js
CHANGED
|
@@ -163,6 +163,12 @@ export class ReadonlySortedArray {
|
|
|
163
163
|
for (let i = 0; i < this.length; i++)
|
|
164
164
|
func(this._array[i]);
|
|
165
165
|
}
|
|
166
|
+
/** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */
|
|
167
|
+
slice(start, end) {
|
|
168
|
+
const slice = new ReadonlySortedArray(this._compare, this._duplicatePolicy, this._clone);
|
|
169
|
+
slice._array = this._array.slice(start, end);
|
|
170
|
+
return slice;
|
|
171
|
+
}
|
|
166
172
|
/**
|
|
167
173
|
* Computes the position at which the specified value should be inserted to maintain sorted order.
|
|
168
174
|
* @param value The value whose position is to be computed.
|
|
@@ -293,5 +299,11 @@ export class SortedArray extends ReadonlySortedArray {
|
|
|
293
299
|
* @returns the index of the deleted value, or -1 if no such element exists.
|
|
294
300
|
*/
|
|
295
301
|
remove(value) { return this._remove(value); }
|
|
302
|
+
/** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */
|
|
303
|
+
slice(start, end) {
|
|
304
|
+
const slice = new SortedArray(this._compare, this._duplicatePolicy, this._clone);
|
|
305
|
+
slice._array = this._array.slice(start, end);
|
|
306
|
+
return slice;
|
|
307
|
+
}
|
|
296
308
|
}
|
|
297
309
|
//# sourceMappingURL=SortedArray.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SortedArray.js","sourceRoot":"","sources":["../../src/SortedArray.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAWH;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAI,KAAQ;IACtC,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAW,KAAQ,EAAE,IAAS,EAAE,OAAgC;IACxF,OAAO,sBAAsB,CAAC,IAAI,EAAE,CAAC,OAAU,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED,SAAS,sBAAsB,CAAI,IAAS,EAAE,SAAiC;IAC7E,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;IACvB,OAAO,GAAG,GAAG,IAAI,EAAE;QACjB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACzC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK,IAAI;YACZ,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;aAChC,IAAI,IAAI,GAAG,CAAC;YACf,IAAI,GAAG,GA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AK,QAAQ;YACxB,QAAQ,CAAC,KAAK,CAAC,CAAC;QAElB,OAAO,KAAK,CAAC,KAAK,CAAC;IACrB,CAAC;IAED;;;;OAIG;IACO,OAAO,CAAC,KAAQ;QACxB,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,KAAK,CAAC,KAAK,EAAE;YACf,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YACnC,OAAO,KAAK,CAAC,KAAK,CAAC;SACpB;aAAM;YACL,OAAO,CAAC,CAAC,CAAC;SACX;IACH,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,OAAO,WAAe,SAAQ,mBAAsB;IACxD;;;;;OAKG;IACH,YAAmB,OAA6B,EAAE,kBAA6C,KAAK,EAAE,QAA0B,YAAY;QAC1I,KAAK,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;IAED,+CAA+C;IACxC,KAAK,KAAW,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAEvC;;OAEG;IACI,YAAY,KAAU,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;IAE3D;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAQ,EAAE,QAA4B,IAAY,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAEvG;;;;OAIG;IACI,MAAM,CAAC,KAAQ,IAAY,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CAChE","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Collections\r\n */\r\n\r\nimport { OrderedComparator } from \"./Compare\";\r\n\r\n/**\r\n * A function that, given a value of type T, returns a copy of that value. Such functions are used by various collection classes.\r\n * It is up to the function to decide how deeply or shallowly the value is cloned. For example, [[shallowClone]] simply returns the input.\r\n * @public\r\n */\r\nexport type CloneFunction<T> = (value: T) => T;\r\n\r\n/**\r\n * A [[CloneFunction]] that, given a value of type T, returns the same value.\r\n * Useful as a default argument for functions that can alternatively accept custom logic for cloning values of object type.\r\n * @param value The value to clone.\r\n * @returns the input value.\r\n * @public\r\n */\r\nexport function shallowClone<T>(value: T) {\r\n return value;\r\n}\r\n\r\n/**\r\n * Given a sorted array, computes the position at which the specified value should be inserted into the array so that the array remains sorted.\r\n * @param value The value whose position is to be computed.\r\n * @param list An array of U already sorted according to the comparison criterion.\r\n * @param compare The function used to compare the value with elements in `list`.\r\n * @returns an object with 'index' corresponding to the computed position and 'equal' set to true if an equivalent element already exists at that index.\r\n * @public\r\n */\r\nexport function lowerBound<T, U = T>(value: T, list: U[], compare: OrderedComparator<T, U>): { index: number, equal: boolean } {\r\n return lowerBoundOfEquivalent(list, (element: U) => compare(value, element));\r\n}\r\n\r\nfunction lowerBoundOfEquivalent<T>(list: T[], criterion: (element: T) => number): { index: number, equal: boolean } {\r\n let low = 0;\r\n let high = list.length;\r\n while (low < high) {\r\n const mid = Math.floor((low + high) / 2);\r\n const comp = criterion(list[mid]);\r\n if (0 === comp)\r\n return { index: mid, equal: true };\r\n else if (comp < 0)\r\n high = mid;\r\n else\r\n low = mid + 1;\r\n }\r\n\r\n return { index: low, equal: false };\r\n}\r\n\r\n/** Describes how duplicate values are handled when inserting into a [[SortedArray]].\r\n * A \"duplicate\" value is one that compares equal to a value already present in the array, per the array's comparison function.\r\n * @public\r\n */\r\nexport enum DuplicatePolicy {\r\n /** The array allows duplicate values to be inserted. All duplicate values will be adjacent in the array, but the ordering between duplicate values is unspecified.\r\n * @note In the presence of duplicate values, functions like [[SortedArray.indexOf]] and [[SortedArray.findEqual]] will return one of the values - exactly which one is unspecified.\r\n */\r\n Allow,\r\n /** Duplicate values are forbidden - when attempting to insert a value equivalent to one already present, the already-present value is retained. */\r\n Retain,\r\n /** Duplicate values are forbidden - when attempting to insert a value equivalent to one already present, the already-present value is replaced by the new value.\r\n * This can be useful when the value type carries additional data that is not evaluated by the comparison function.\r\n */\r\n Replace,\r\n}\r\n\r\n/**\r\n * A read-only view of an array of some type T sorted according to some user-supplied criterion.\r\n * Duplicate elements may be present, though sub-types may enforce uniqueness of elements.\r\n * In the absence of duplicates, a ReadonlySortedArray<T> can behave like a Set<T> where T is an object and equality is determined\r\n * by some criterion other than object identity.\r\n *\r\n * Because the array is always sorted, querying for the presence of an element is performed using binary\r\n * search, which is more efficient than a linear search for reasonably large arrays.\r\n *\r\n * The comparison function must meet the following criteria, given 'lhs' and 'rhs' of type T:\r\n * - If lhs is equal to rhs, returns 0\r\n * - If lhs is less than rhs, returns a negative value\r\n * - If lhs is greater than rhs, returns a positive value\r\n * - If compare(lhs, rhs) returns 0, then compare(rhs, lhs) must also return 0\r\n * - If compare(lhs, rhs) returns a negative value, then compare(rhs, lhs) must return a positive value, and vice versa.\r\n *\r\n * Note that the array is read-only only from the perspective of its public interface. Mutation methods are defined for internal use by sub-types.\r\n *\r\n * @see [[SortedArray]] for a general-purpose mutable sorted array.\r\n * @public\r\n */\r\nexport class ReadonlySortedArray<T> implements Iterable<T> {\r\n protected _array: T[] = [];\r\n protected readonly _compare: OrderedComparator<T>;\r\n protected readonly _clone: CloneFunction<T>;\r\n protected readonly _duplicatePolicy: DuplicatePolicy;\r\n\r\n /**\r\n * Construct a new ReadonlySortedArray<T>.\r\n * @param compare The function used to compare elements within the array.\r\n * @param duplicatePolicy Policy for handling attempts to insert a value when an equivalent value already exists. If the input is a boolean, then `true` indicates [[DuplicatePolicy.Allow]], and `false` indicates [[DuplicatePolicy.Retain]].\r\n * @param clone The function invoked to clone a new element for insertion into the array. The default implementation simply returns its input.\r\n */\r\n protected constructor(compare: OrderedComparator<T>, duplicatePolicy: DuplicatePolicy | boolean = false, clone: CloneFunction<T> = shallowClone) {\r\n this._compare = compare;\r\n this._clone = clone;\r\n if (typeof duplicatePolicy === \"boolean\")\r\n duplicatePolicy = duplicatePolicy ? DuplicatePolicy.Allow : DuplicatePolicy.Retain;\r\n\r\n this._duplicatePolicy = duplicatePolicy;\r\n }\r\n\r\n /** The number of elements in the array */\r\n public get length(): number { return this._array.length; }\r\n\r\n /** Returns true if the array contains no elements. */\r\n public get isEmpty(): boolean { return 0 === this.length; }\r\n\r\n /** Returns an iterator over the contents of the array in sorted order, suitable for use in `for-of` loops. */\r\n public [Symbol.iterator](): Iterator<T> { return this._array[Symbol.iterator](); }\r\n\r\n /**\r\n * Looks up the index of an element comparing equal to the specified value using binary search.\r\n * @param value The value to search for\r\n * @returns the index of the first equivalent element found in the array, or -1 if no such element exists.\r\n */\r\n public indexOf(value: T): number {\r\n const bound = this.lowerBound(value);\r\n return bound.equal ? bound.index : -1;\r\n }\r\n\r\n /**\r\n * Returns true if this array contains at least one value comparing equal to the specified value.\r\n * @param value The value to search for\r\n * @returns true if an equivalent element exists in the array.\r\n */\r\n public contains(value: T): boolean {\r\n return -1 !== this.indexOf(value);\r\n }\r\n\r\n /**\r\n * Looks up an element comparing equal to the specified value using binary search.\r\n * @param value The value to search for\r\n * @returns the first equivalent element found in the array, or undefined if no such element exists.\r\n */\r\n public findEqual(value: T): T | undefined {\r\n const index = this.indexOf(value);\r\n return -1 !== index ? this._array[index] : undefined;\r\n }\r\n\r\n /** Find an element that compares as equivalent based on some criterion. If multiple elements are equivalent, the specific one returned is unspecified.\r\n * As an example, consider a `SortedArray<ModelState>` which uses `ModelState.id` as its ordering criterion. To find a model by its Id,\r\n * use `sortedArray.findEquivalent((element) => compareStrings(element.id, modelId))` where `modelId` is an [[Id64String]].\r\n * @param criterion A function accepting an element and returning 0 if it compares as equivalent, a negative number if it compares as \"less-than\", or a positive value if it compares as \"greater-than\".\r\n * @returns The first element found that meets the criterion, or `undefined` if no elements meet the criterion.\r\n * @see [[indexOfEquivalent]].\r\n * @public\r\n */\r\n public findEquivalent(criterion: (element: T) => number): T | undefined {\r\n const index = this.indexOfEquivalent(criterion);\r\n return -1 !== index ? this._array[index] : undefined;\r\n }\r\n\r\n /** Find the index of an element that compares as equivalent based on some criterion. If multiple elements are equivalent, the specific one returned is unspecified.\r\n * As an example, consider a `SortedArray<ModelState>` which uses `ModelState.id` as its ordering criterion. To find the index of a model by its Id,\r\n * use `sortedArray.indexOfEquivalent((element) => compareStrings(element.id, modelId))` where `modelId` is an [[Id64String]].\r\n * @param criterion A function accepting an element and returning 0 if it compares as equivalent, a negative number if the element compares as \"less-than\", or a positive value if the element compares as \"greater-than\".\r\n * @returns The index of the first element found that meets the criterion, or -1 if no elements meet the criterion.\r\n * @public\r\n */\r\n public indexOfEquivalent(criterion: (element: T) => number): number {\r\n // NB: Must invert the ordering.\r\n const bound = lowerBoundOfEquivalent(this._array, (elem: T) => 0 - criterion(elem));\r\n return bound.equal ? bound.index : -1;\r\n }\r\n\r\n /**\r\n * Looks up an element by its index in the array.\r\n * @param index The array index\r\n * @returns the element corresponding to that position in the array, or undefined if the supplied index exceeds the length of the array.\r\n */\r\n public get(index: number): T | undefined { return index < this.length ? this._array[index] : undefined; }\r\n\r\n /** Apply a function to each element in the array, in sorted order.\r\n * @param func The function to be applied.\r\n */\r\n public forEach(func: (value: T) => void): void {\r\n for (let i = 0; i < this.length; i++)\r\n func(this._array[i]);\r\n }\r\n\r\n /**\r\n * Computes the position at which the specified value should be inserted to maintain sorted order.\r\n * @param value The value whose position is to be computed.\r\n * @returns an object with 'index' corresponding to the computed position and 'equal' set to true if an equivalent element already exists at that index.\r\n */\r\n protected lowerBound(value: T): { index: number, equal: boolean } { return lowerBound(value, this._array, this._compare); }\r\n\r\n /** Clears the contents of the sorted array. */\r\n protected _clear(): void { this._array.length = 0; }\r\n\r\n /** Extracts the sorted array as a T[] and empties the contents of this ReadonlySortedArray.\r\n * @returns the contents of this ReadonlySortedArray as a T[].\r\n */\r\n protected _extractArray(): T[] {\r\n const result = this._array;\r\n this._array = [];\r\n return result;\r\n }\r\n\r\n /**\r\n * Attempts to insert a new value into the array at a position determined by the ordering.\r\n * The behavior differs based on the array's [[DuplicatePolicy]]:\r\n * If duplicates are **not** permitted, then:\r\n * - If an equivalent element already exists in the array:\r\n * - [[DuplicatePolicy.Retain]]: nothing will be inserted and the index of the existing element will be returned.\r\n * - [[DuplicatePolicy.Replace]]: the input value will overwrite the existing element at the same index and that index will be returned.\r\n * - Otherwise, the element is inserted and its index is returned.\r\n * If duplicates **are** permitted, then:\r\n * - The element will be inserted in a correct position based on the sorting criterion;\r\n * - The position of the element relative to other elements comparing as equal to it is unspecified; and\r\n * - The actual index of the newly-inserted element is returned.\r\n * If the element is to be inserted, then the supplied value will be passed to the clone function supplied to the constructor and the result will be inserted into the array.\r\n * @param value The value to insert\r\n * @param onInsert The optional callback method to call if insertion occurs with the inserted value\r\n * @returns the index in the array of the newly-inserted value, or, if duplicates are not permitted and an equivalent value already exists, the index of the equivalent value.\r\n */\r\n protected _insert(value: T, onInsert?: (value: T) => any): number {\r\n const bound = this.lowerBound(value);\r\n\r\n if (bound.equal) {\r\n switch (this._duplicatePolicy) {\r\n case DuplicatePolicy.Retain:\r\n return bound.index;\r\n case DuplicatePolicy.Replace:\r\n this._array[bound.index] = this._clone(value);\r\n if (onInsert)\r\n onInsert(value);\r\n\r\n return bound.index;\r\n }\r\n }\r\n\r\n this._array.splice(bound.index, 0, this._clone(value));\r\n if (undefined !== onInsert)\r\n onInsert(value);\r\n\r\n return bound.index;\r\n }\r\n\r\n /**\r\n * Removes the first occurrence of a value comparing equal to the specified value from the array.\r\n * @param value The value of the element to delete\r\n * @returns the index of the deleted value, or -1 if no such element exists.\r\n */\r\n protected _remove(value: T): number {\r\n const bound = this.lowerBound(value);\r\n if (bound.equal) {\r\n this._array.splice(bound.index, 1);\r\n return bound.index;\r\n } else {\r\n return -1;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Maintains an array of some type T in sorted order. The ordering is specified by a function supplied\r\n * by the user.\r\n * By default, only unique elements are permitted; attempting to insert a new element that compares\r\n * as equal to an element already in the array will not modify the contents of the array.\r\n *\r\n * This allows a SortedArray<T> to behave like a Set<T> where T is an object and equality is determined\r\n * by some criterion other than object identity.\r\n *\r\n * Because the array is always sorted, querying for the presence of an element is performed using binary\r\n * search, which is more efficient than a linear search for reasonably large arrays.\r\n *\r\n * The user can also specify how the SortedArray takes ownership of inserted values, e.g., by cloning them.\r\n *\r\n * The comparison function must meet the following criteria, given 'lhs' and 'rhs' of type T:\r\n * - If lhs is equal to rhs, returns 0\r\n * - If lhs is less than rhs, returns a negative value\r\n * - If lhs is greater than rhs, returns a positive value\r\n * - If compare(lhs, rhs) returns 0, then compare(rhs, lhs) must also return 0\r\n * - If compare(lhs, rhs) returns a negative value, then compare(rhs, lhs) must return a positive value, and vice versa.\r\n *\r\n * Modifying an element in a way that affects the comparison function will produce unpredictable results, the\r\n * most likely of which is that the array will cease to be sorted.\r\n * @public\r\n */\r\nexport class SortedArray<T> extends ReadonlySortedArray<T> {\r\n /**\r\n * Construct a new SortedArray<T>.\r\n * @param compare The function used to compare elements within the array.\r\n * @param duplicatePolicy Policy for handling attempts to insert a value when an equivalent value already exists. If the input is a boolean, then `true` indicates [[DuplicatePolicy.Allow]], and `false` indicates [[DuplicatePolicy.Retain]].\r\n * @param clone The function invoked to clone a new element for insertion into the array. The default implementation simply returns its input.\r\n */\r\n public constructor(compare: OrderedComparator<T>, duplicatePolicy: DuplicatePolicy | boolean = false, clone: CloneFunction<T> = shallowClone) {\r\n super(compare, duplicatePolicy, clone);\r\n }\r\n\r\n /** Clears the contents of the sorted array. */\r\n public clear(): void { this._clear(); }\r\n\r\n /** Extracts the sorted array as a T[] and empties the contents of this SortedArray.\r\n * @returns the contents of this SortedArray as a T[].\r\n */\r\n public extractArray(): T[] { return this._extractArray(); }\r\n\r\n /**\r\n * Attempts to insert a new value into the array at a position determined by the ordering.\r\n * The behavior differs based on whether or not duplicate elements are permitted.\r\n * If duplicates are **not** permitted, then:\r\n * - If an equivalent element already exists in the array, nothing will be inserted and the index of the existing element will be returned.\r\n * - Otherwise, the element is inserted and its index is returned.\r\n * If duplicates **are** permitted, then:\r\n * - The element will be inserted in a correct position based on the sorting criterion;\r\n * - The position of the element relative to other elements comparing as equal to it is unspecified; and\r\n * - The actual index of the newly-inserted element is returned.\r\n * If the element is to be inserted, then the supplied value will be passed to the clone function supplied to the constructor and the result will be inserted into the array.\r\n * @param value The value to insert\r\n * @param onInsert The optional callback method to call if insertion occurs with the inserted value\r\n * @returns the index in the array of the newly-inserted value, or, if duplicates are not permitted and an equivalent value already exists, the index of the equivalent value.\r\n */\r\n public insert(value: T, onInsert?: (value: T) => any): number { return this._insert(value, onInsert); }\r\n\r\n /**\r\n * Removes the first occurrence of a value comparing equal to the specified value from the array.\r\n * @param value The value of the element to delete\r\n * @returns the index of the deleted value, or -1 if no such element exists.\r\n */\r\n public remove(value: T): number { return this._remove(value); }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"SortedArray.js","sourceRoot":"","sources":["../../src/SortedArray.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAWH;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAI,KAAQ;IACtC,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAW,KAAQ,EAAE,IAAS,EAAE,OAAgC;IACxF,OAAO,sBAAsB,CAAC,IAAI,EAAE,CAAC,OAAU,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED,SAAS,sBAAsB,CAAI,IAAS,EAAE,SAAiC;IAC7E,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;IACvB,OAAO,GAAG,GAAG,IAA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AC,OAAO,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;IAED,+CAA+C;IACxC,KAAK,KAAW,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAEvC;;OAEG;IACI,YAAY,KAAU,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;IAE3D;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAQ,EAAE,QAA4B,IAAY,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAEvG;;;;OAIG;IACI,MAAM,CAAC,KAAQ,IAAY,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAE/D,qIAAqI;IACrH,KAAK,CAAC,KAAc,EAAE,GAAY;QAChD,MAAM,KAAK,GAAG,IAAI,WAAW,CAAI,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACpF,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC7C,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Collections\r\n */\r\n\r\nimport { OrderedComparator } from \"./Compare\";\r\n\r\n/**\r\n * A function that, given a value of type T, returns a copy of that value. Such functions are used by various collection classes.\r\n * It is up to the function to decide how deeply or shallowly the value is cloned. For example, [[shallowClone]] simply returns the input.\r\n * @public\r\n */\r\nexport type CloneFunction<T> = (value: T) => T;\r\n\r\n/**\r\n * A [[CloneFunction]] that, given a value of type T, returns the same value.\r\n * Useful as a default argument for functions that can alternatively accept custom logic for cloning values of object type.\r\n * @param value The value to clone.\r\n * @returns the input value.\r\n * @public\r\n */\r\nexport function shallowClone<T>(value: T) {\r\n return value;\r\n}\r\n\r\n/**\r\n * Given a sorted array, computes the position at which the specified value should be inserted into the array so that the array remains sorted.\r\n * @param value The value whose position is to be computed.\r\n * @param list An array of U already sorted according to the comparison criterion.\r\n * @param compare The function used to compare the value with elements in `list`.\r\n * @returns an object with 'index' corresponding to the computed position and 'equal' set to true if an equivalent element already exists at that index.\r\n * @public\r\n */\r\nexport function lowerBound<T, U = T>(value: T, list: U[], compare: OrderedComparator<T, U>): { index: number, equal: boolean } {\r\n return lowerBoundOfEquivalent(list, (element: U) => compare(value, element));\r\n}\r\n\r\nfunction lowerBoundOfEquivalent<T>(list: T[], criterion: (element: T) => number): { index: number, equal: boolean } {\r\n let low = 0;\r\n let high = list.length;\r\n while (low < high) {\r\n const mid = Math.floor((low + high) / 2);\r\n const comp = criterion(list[mid]);\r\n if (0 === comp)\r\n return { index: mid, equal: true };\r\n else if (comp < 0)\r\n high = mid;\r\n else\r\n low = mid + 1;\r\n }\r\n\r\n return { index: low, equal: false };\r\n}\r\n\r\n/** Describes how duplicate values are handled when inserting into a [[SortedArray]].\r\n * A \"duplicate\" value is one that compares equal to a value already present in the array, per the array's comparison function.\r\n * @public\r\n */\r\nexport enum DuplicatePolicy {\r\n /** The array allows duplicate values to be inserted. All duplicate values will be adjacent in the array, but the ordering between duplicate values is unspecified.\r\n * @note In the presence of duplicate values, functions like [[SortedArray.indexOf]] and [[SortedArray.findEqual]] will return one of the values - exactly which one is unspecified.\r\n */\r\n Allow,\r\n /** Duplicate values are forbidden - when attempting to insert a value equivalent to one already present, the already-present value is retained. */\r\n Retain,\r\n /** Duplicate values are forbidden - when attempting to insert a value equivalent to one already present, the already-present value is replaced by the new value.\r\n * This can be useful when the value type carries additional data that is not evaluated by the comparison function.\r\n */\r\n Replace,\r\n}\r\n\r\n/**\r\n * A read-only view of an array of some type T sorted according to some user-supplied criterion.\r\n * Duplicate elements may be present, though sub-types may enforce uniqueness of elements.\r\n * In the absence of duplicates, a ReadonlySortedArray<T> can behave like a Set<T> where T is an object and equality is determined\r\n * by some criterion other than object identity.\r\n *\r\n * Because the array is always sorted, querying for the presence of an element is performed using binary\r\n * search, which is more efficient than a linear search for reasonably large arrays.\r\n *\r\n * The comparison function must meet the following criteria, given 'lhs' and 'rhs' of type T:\r\n * - If lhs is equal to rhs, returns 0\r\n * - If lhs is less than rhs, returns a negative value\r\n * - If lhs is greater than rhs, returns a positive value\r\n * - If compare(lhs, rhs) returns 0, then compare(rhs, lhs) must also return 0\r\n * - If compare(lhs, rhs) returns a negative value, then compare(rhs, lhs) must return a positive value, and vice versa.\r\n *\r\n * Note that the array is read-only only from the perspective of its public interface. Mutation methods are defined for internal use by sub-types.\r\n *\r\n * @see [[SortedArray]] for a general-purpose mutable sorted array.\r\n * @public\r\n */\r\nexport class ReadonlySortedArray<T> implements Iterable<T> {\r\n protected _array: T[] = [];\r\n protected readonly _compare: OrderedComparator<T>;\r\n protected readonly _clone: CloneFunction<T>;\r\n protected readonly _duplicatePolicy: DuplicatePolicy;\r\n\r\n /**\r\n * Construct a new ReadonlySortedArray<T>.\r\n * @param compare The function used to compare elements within the array.\r\n * @param duplicatePolicy Policy for handling attempts to insert a value when an equivalent value already exists. If the input is a boolean, then `true` indicates [[DuplicatePolicy.Allow]], and `false` indicates [[DuplicatePolicy.Retain]].\r\n * @param clone The function invoked to clone a new element for insertion into the array. The default implementation simply returns its input.\r\n */\r\n protected constructor(compare: OrderedComparator<T>, duplicatePolicy: DuplicatePolicy | boolean = false, clone: CloneFunction<T> = shallowClone) {\r\n this._compare = compare;\r\n this._clone = clone;\r\n if (typeof duplicatePolicy === \"boolean\")\r\n duplicatePolicy = duplicatePolicy ? DuplicatePolicy.Allow : DuplicatePolicy.Retain;\r\n\r\n this._duplicatePolicy = duplicatePolicy;\r\n }\r\n\r\n /** The number of elements in the array */\r\n public get length(): number { return this._array.length; }\r\n\r\n /** Returns true if the array contains no elements. */\r\n public get isEmpty(): boolean { return 0 === this.length; }\r\n\r\n /** Returns an iterator over the contents of the array in sorted order, suitable for use in `for-of` loops. */\r\n public [Symbol.iterator](): Iterator<T> { return this._array[Symbol.iterator](); }\r\n\r\n /**\r\n * Looks up the index of an element comparing equal to the specified value using binary search.\r\n * @param value The value to search for\r\n * @returns the index of the first equivalent element found in the array, or -1 if no such element exists.\r\n */\r\n public indexOf(value: T): number {\r\n const bound = this.lowerBound(value);\r\n return bound.equal ? bound.index : -1;\r\n }\r\n\r\n /**\r\n * Returns true if this array contains at least one value comparing equal to the specified value.\r\n * @param value The value to search for\r\n * @returns true if an equivalent element exists in the array.\r\n */\r\n public contains(value: T): boolean {\r\n return -1 !== this.indexOf(value);\r\n }\r\n\r\n /**\r\n * Looks up an element comparing equal to the specified value using binary search.\r\n * @param value The value to search for\r\n * @returns the first equivalent element found in the array, or undefined if no such element exists.\r\n */\r\n public findEqual(value: T): T | undefined {\r\n const index = this.indexOf(value);\r\n return -1 !== index ? this._array[index] : undefined;\r\n }\r\n\r\n /** Find an element that compares as equivalent based on some criterion. If multiple elements are equivalent, the specific one returned is unspecified.\r\n * As an example, consider a `SortedArray<ModelState>` which uses `ModelState.id` as its ordering criterion. To find a model by its Id,\r\n * use `sortedArray.findEquivalent((element) => compareStrings(element.id, modelId))` where `modelId` is an [[Id64String]].\r\n * @param criterion A function accepting an element and returning 0 if it compares as equivalent, a negative number if it compares as \"less-than\", or a positive value if it compares as \"greater-than\".\r\n * @returns The first element found that meets the criterion, or `undefined` if no elements meet the criterion.\r\n * @see [[indexOfEquivalent]].\r\n * @public\r\n */\r\n public findEquivalent(criterion: (element: T) => number): T | undefined {\r\n const index = this.indexOfEquivalent(criterion);\r\n return -1 !== index ? this._array[index] : undefined;\r\n }\r\n\r\n /** Find the index of an element that compares as equivalent based on some criterion. If multiple elements are equivalent, the specific one returned is unspecified.\r\n * As an example, consider a `SortedArray<ModelState>` which uses `ModelState.id` as its ordering criterion. To find the index of a model by its Id,\r\n * use `sortedArray.indexOfEquivalent((element) => compareStrings(element.id, modelId))` where `modelId` is an [[Id64String]].\r\n * @param criterion A function accepting an element and returning 0 if it compares as equivalent, a negative number if the element compares as \"less-than\", or a positive value if the element compares as \"greater-than\".\r\n * @returns The index of the first element found that meets the criterion, or -1 if no elements meet the criterion.\r\n * @public\r\n */\r\n public indexOfEquivalent(criterion: (element: T) => number): number {\r\n // NB: Must invert the ordering.\r\n const bound = lowerBoundOfEquivalent(this._array, (elem: T) => 0 - criterion(elem));\r\n return bound.equal ? bound.index : -1;\r\n }\r\n\r\n /**\r\n * Looks up an element by its index in the array.\r\n * @param index The array index\r\n * @returns the element corresponding to that position in the array, or undefined if the supplied index exceeds the length of the array.\r\n */\r\n public get(index: number): T | undefined { return index < this.length ? this._array[index] : undefined; }\r\n\r\n /** Apply a function to each element in the array, in sorted order.\r\n * @param func The function to be applied.\r\n */\r\n public forEach(func: (value: T) => void): void {\r\n for (let i = 0; i < this.length; i++)\r\n func(this._array[i]);\r\n }\r\n\r\n /** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */\r\n public slice(start?: number, end?: number): ReadonlySortedArray<T> {\r\n const slice = new ReadonlySortedArray<T>(this._compare, this._duplicatePolicy, this._clone);\r\n slice._array = this._array.slice(start, end);\r\n return slice;\r\n }\r\n\r\n /**\r\n * Computes the position at which the specified value should be inserted to maintain sorted order.\r\n * @param value The value whose position is to be computed.\r\n * @returns an object with 'index' corresponding to the computed position and 'equal' set to true if an equivalent element already exists at that index.\r\n */\r\n protected lowerBound(value: T): { index: number, equal: boolean } { return lowerBound(value, this._array, this._compare); }\r\n\r\n /** Clears the contents of the sorted array. */\r\n protected _clear(): void { this._array.length = 0; }\r\n\r\n /** Extracts the sorted array as a T[] and empties the contents of this ReadonlySortedArray.\r\n * @returns the contents of this ReadonlySortedArray as a T[].\r\n */\r\n protected _extractArray(): T[] {\r\n const result = this._array;\r\n this._array = [];\r\n return result;\r\n }\r\n\r\n /**\r\n * Attempts to insert a new value into the array at a position determined by the ordering.\r\n * The behavior differs based on the array's [[DuplicatePolicy]]:\r\n * If duplicates are **not** permitted, then:\r\n * - If an equivalent element already exists in the array:\r\n * - [[DuplicatePolicy.Retain]]: nothing will be inserted and the index of the existing element will be returned.\r\n * - [[DuplicatePolicy.Replace]]: the input value will overwrite the existing element at the same index and that index will be returned.\r\n * - Otherwise, the element is inserted and its index is returned.\r\n * If duplicates **are** permitted, then:\r\n * - The element will be inserted in a correct position based on the sorting criterion;\r\n * - The position of the element relative to other elements comparing as equal to it is unspecified; and\r\n * - The actual index of the newly-inserted element is returned.\r\n * If the element is to be inserted, then the supplied value will be passed to the clone function supplied to the constructor and the result will be inserted into the array.\r\n * @param value The value to insert\r\n * @param onInsert The optional callback method to call if insertion occurs with the inserted value\r\n * @returns the index in the array of the newly-inserted value, or, if duplicates are not permitted and an equivalent value already exists, the index of the equivalent value.\r\n */\r\n protected _insert(value: T, onInsert?: (value: T) => any): number {\r\n const bound = this.lowerBound(value);\r\n\r\n if (bound.equal) {\r\n switch (this._duplicatePolicy) {\r\n case DuplicatePolicy.Retain:\r\n return bound.index;\r\n case DuplicatePolicy.Replace:\r\n this._array[bound.index] = this._clone(value);\r\n if (onInsert)\r\n onInsert(value);\r\n\r\n return bound.index;\r\n }\r\n }\r\n\r\n this._array.splice(bound.index, 0, this._clone(value));\r\n if (undefined !== onInsert)\r\n onInsert(value);\r\n\r\n return bound.index;\r\n }\r\n\r\n /**\r\n * Removes the first occurrence of a value comparing equal to the specified value from the array.\r\n * @param value The value of the element to delete\r\n * @returns the index of the deleted value, or -1 if no such element exists.\r\n */\r\n protected _remove(value: T): number {\r\n const bound = this.lowerBound(value);\r\n if (bound.equal) {\r\n this._array.splice(bound.index, 1);\r\n return bound.index;\r\n } else {\r\n return -1;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Maintains an array of some type T in sorted order. The ordering is specified by a function supplied\r\n * by the user.\r\n * By default, only unique elements are permitted; attempting to insert a new element that compares\r\n * as equal to an element already in the array will not modify the contents of the array.\r\n *\r\n * This allows a SortedArray<T> to behave like a Set<T> where T is an object and equality is determined\r\n * by some criterion other than object identity.\r\n *\r\n * Because the array is always sorted, querying for the presence of an element is performed using binary\r\n * search, which is more efficient than a linear search for reasonably large arrays.\r\n *\r\n * The user can also specify how the SortedArray takes ownership of inserted values, e.g., by cloning them.\r\n *\r\n * The comparison function must meet the following criteria, given 'lhs' and 'rhs' of type T:\r\n * - If lhs is equal to rhs, returns 0\r\n * - If lhs is less than rhs, returns a negative value\r\n * - If lhs is greater than rhs, returns a positive value\r\n * - If compare(lhs, rhs) returns 0, then compare(rhs, lhs) must also return 0\r\n * - If compare(lhs, rhs) returns a negative value, then compare(rhs, lhs) must return a positive value, and vice versa.\r\n *\r\n * Modifying an element in a way that affects the comparison function will produce unpredictable results, the\r\n * most likely of which is that the array will cease to be sorted.\r\n * @public\r\n */\r\nexport class SortedArray<T> extends ReadonlySortedArray<T> {\r\n /**\r\n * Construct a new SortedArray<T>.\r\n * @param compare The function used to compare elements within the array.\r\n * @param duplicatePolicy Policy for handling attempts to insert a value when an equivalent value already exists. If the input is a boolean, then `true` indicates [[DuplicatePolicy.Allow]], and `false` indicates [[DuplicatePolicy.Retain]].\r\n * @param clone The function invoked to clone a new element for insertion into the array. The default implementation simply returns its input.\r\n */\r\n public constructor(compare: OrderedComparator<T>, duplicatePolicy: DuplicatePolicy | boolean = false, clone: CloneFunction<T> = shallowClone) {\r\n super(compare, duplicatePolicy, clone);\r\n }\r\n\r\n /** Clears the contents of the sorted array. */\r\n public clear(): void { this._clear(); }\r\n\r\n /** Extracts the sorted array as a T[] and empties the contents of this SortedArray.\r\n * @returns the contents of this SortedArray as a T[].\r\n */\r\n public extractArray(): T[] { return this._extractArray(); }\r\n\r\n /**\r\n * Attempts to insert a new value into the array at a position determined by the ordering.\r\n * The behavior differs based on whether or not duplicate elements are permitted.\r\n * If duplicates are **not** permitted, then:\r\n * - If an equivalent element already exists in the array, nothing will be inserted and the index of the existing element will be returned.\r\n * - Otherwise, the element is inserted and its index is returned.\r\n * If duplicates **are** permitted, then:\r\n * - The element will be inserted in a correct position based on the sorting criterion;\r\n * - The position of the element relative to other elements comparing as equal to it is unspecified; and\r\n * - The actual index of the newly-inserted element is returned.\r\n * If the element is to be inserted, then the supplied value will be passed to the clone function supplied to the constructor and the result will be inserted into the array.\r\n * @param value The value to insert\r\n * @param onInsert The optional callback method to call if insertion occurs with the inserted value\r\n * @returns the index in the array of the newly-inserted value, or, if duplicates are not permitted and an equivalent value already exists, the index of the equivalent value.\r\n */\r\n public insert(value: T, onInsert?: (value: T) => any): number { return this._insert(value, onInsert); }\r\n\r\n /**\r\n * Removes the first occurrence of a value comparing equal to the specified value from the array.\r\n * @param value The value of the element to delete\r\n * @returns the index of the deleted value, or -1 if no such element exists.\r\n */\r\n public remove(value: T): number { return this._remove(value); }\r\n\r\n /** The equivalent of [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). */\r\n public override slice(start?: number, end?: number): SortedArray<T> {\r\n const slice = new SortedArray<T>(this._compare, this._duplicatePolicy, this._clone);\r\n slice._array = this._array.slice(start, end);\r\n return slice;\r\n }\r\n}\r\n"]}
|
package/lib/esm/Tracing.js
CHANGED
|
@@ -79,17 +79,16 @@ export class Tracing {
|
|
|
79
79
|
? Tracing._openTelemetry.context.active()
|
|
80
80
|
: Tracing._openTelemetry.trace.setSpanContext(Tracing._openTelemetry.context.active(), parentContext);
|
|
81
81
|
return Tracing._openTelemetry.context.with(Tracing._openTelemetry.trace.setSpan(parent, Tracing._tracer.startSpan(name, options, Tracing._openTelemetry.context.active())), async () => {
|
|
82
|
-
var _a, _b, _c, _d;
|
|
83
82
|
try {
|
|
84
83
|
return await fn();
|
|
85
84
|
}
|
|
86
85
|
catch (err) {
|
|
87
86
|
if (err instanceof Error) // ignore non-Error throws, such as RpcControlResponse
|
|
88
|
-
|
|
87
|
+
Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttribute("error", true);
|
|
89
88
|
throw err;
|
|
90
89
|
}
|
|
91
90
|
finally {
|
|
92
|
-
|
|
91
|
+
Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.end();
|
|
93
92
|
}
|
|
94
93
|
});
|
|
95
94
|
}
|
|
@@ -108,9 +107,8 @@ export class Tracing {
|
|
|
108
107
|
}
|
|
109
108
|
static withOpenTelemetry(base, isError = false) {
|
|
110
109
|
return (category, message, metaData) => {
|
|
111
|
-
var _a, _b;
|
|
112
110
|
try {
|
|
113
|
-
|
|
111
|
+
Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.addEvent(message, { ...flattenObject(Logger.getMetaData(metaData)), error: isError });
|
|
114
112
|
}
|
|
115
113
|
catch (_e) { } // avoid throwing random errors (with stack trace mangled by async hooks) when openTelemetry collector doesn't work
|
|
116
114
|
base(category, message, metaData);
|
|
@@ -120,8 +118,7 @@ export class Tracing {
|
|
|
120
118
|
* @param attributes The attributes to set
|
|
121
119
|
*/
|
|
122
120
|
static setAttributes(attributes) {
|
|
123
|
-
|
|
124
|
-
(_b = (_a = Tracing._openTelemetry) === null || _a === void 0 ? void 0 : _a.trace.getSpan(Tracing._openTelemetry.context.active())) === null || _b === void 0 ? void 0 : _b.setAttributes(attributes);
|
|
121
|
+
Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttributes(attributes);
|
|
125
122
|
}
|
|
126
123
|
}
|
|
127
124
|
//# sourceMappingURL=Tracing.js.map
|
package/lib/esm/Tracing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Tracing.js","sourceRoot":"","sources":["../../src/Tracing.ts"],"names":[],"mappings":"AAKA,OAAO,EAAe,MAAM,EAAE,MAAM,UAAU,CAAC;AAE/C,kGAAkG;AAClG;;;GAGG;AACH,MAAM,CAAN,IAAY,QA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AAC;QACjE,MAAM,CAAC,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC/D,CAAC;IAEO,MAAM,CAAC,iBAAiB,CAAC,IAAiB,EAAE,UAAmB,KAAK;QAC1E,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE;;YACrC,IAAI;gBACF,MAAA,MAAA,OAAO,CAAC,cAAc,0CAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,0CAAE,QAAQ,CAAC,OAAO,EAAE,EAAE,GAAG,aAAa,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;aACvK;YAAC,OAAO,EAAE,EAAE,GAAG,CAAC,mHAAmH;YACpI,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpC,CAAC,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,aAAa,CAAC,UAA0B;;QACpD,MAAA,MAAA,OAAO,CAAC,cAAc,0CAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,0CAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IAC5G,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\nimport type { ContextAPI, SpanAttributes, SpanAttributeValue, SpanContext, SpanOptions, TraceAPI, Tracer } from \"@opentelemetry/api\";\r\nimport { LogFunction, Logger } from \"./Logger\";\r\n\r\n// re-export so that consumers can construct full SpanOptions object without external dependencies\r\n/**\r\n * Mirrors the SpanKind enum from [@opentelemetry/api](https://open-telemetry.github.io/opentelemetry-js-api/enums/spankind)\r\n * @alpha\r\n */\r\nexport enum SpanKind {\r\n INTERNAL = 0,\r\n SERVER = 1,\r\n CLIENT = 2,\r\n PRODUCER = 3,\r\n CONSUMER = 4\r\n}\r\n\r\nfunction isValidPrimitive(val: unknown): val is SpanAttributeValue {\r\n return typeof val === \"string\" || typeof val === \"number\" || typeof val === \"boolean\";\r\n}\r\n\r\n// Only _homogenous_ arrays of strings, numbers, or booleans are supported as OpenTelemetry Attribute values.\r\n// Per the spec (https://opentelemetry.io/docs/reference/specification/common/common/#attribute), empty arrays and null values are supported too.\r\nfunction isValidPrimitiveArray(val: unknown): val is SpanAttributeValue {\r\n if (!Array.isArray(val))\r\n return false;\r\n\r\n let itemType;\r\n for (const x of val) {\r\n if (x === undefined || x === null)\r\n continue;\r\n\r\n if (!itemType) {\r\n itemType = typeof x;\r\n if (!isValidPrimitive(x))\r\n return false;\r\n }\r\n\r\n if (typeof x !== itemType)\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nfunction isPlainObject(obj: unknown): obj is object {\r\n return typeof obj === \"object\" && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;\r\n}\r\n\r\nfunction* getFlatEntries(obj: unknown, path = \"\"): Iterable<[string, SpanAttributeValue]> {\r\n if (isValidPrimitiveArray(obj)) {\r\n yield [path, obj];\r\n return;\r\n }\r\n\r\n // Prefer JSON serialization over flattening for any non-POJO types.\r\n // There's just too many ways trying to flatten those can go wrong (Dates, Buffers, TypedArrays, etc.)\r\n if (!isPlainObject(obj) && !Array.isArray(obj)) {\r\n yield [path, isValidPrimitive(obj) ? obj : JSON.stringify(obj)];\r\n return;\r\n }\r\n\r\n // Always serialize empty objects/arrays as empty array values\r\n const entries = Object.entries(obj);\r\n if (entries.length === 0)\r\n yield [path, []];\r\n\r\n for (const [key, val] of entries)\r\n yield* getFlatEntries(val, (path === \"\") ? key : `${path}.${key}`);\r\n}\r\n\r\nfunction flattenObject(obj: object): SpanAttributes {\r\n return Object.fromEntries(getFlatEntries(obj));\r\n}\r\n\r\n/**\r\n * Enables OpenTelemetry tracing in addition to traditional logging.\r\n * @alpha\r\n */\r\nexport class Tracing {\r\n private static _tracer?: Tracer;\r\n private static _openTelemetry?: { trace: Pick<TraceAPI, \"setSpan\" | \"setSpanContext\" | \"getSpan\">, context: Pick<ContextAPI, \"active\" | \"with\"> };\r\n\r\n /**\r\n * If OpenTelemetry tracing is enabled, creates a new span and runs the provided function in it.\r\n * If OpenTelemetry tracing is _not_ enabled, runs the provided function.\r\n * @param name name of the new span\r\n * @param fn function to run inside the new span\r\n * @param options span options\r\n * @param parentContext optional context used to retrieve parent span id\r\n */\r\n public static async withSpan<T>(name: string, fn: () => Promise<T>, options?: SpanOptions, parentContext?: SpanContext): Promise<T> {\r\n if (Tracing._tracer === undefined || Tracing._openTelemetry === undefined)\r\n return fn();\r\n\r\n // this case is for context propagation - parentContext is typically constructed from HTTP headers\r\n const parent = parentContext === undefined\r\n ? Tracing._openTelemetry.context.active()\r\n : Tracing._openTelemetry.trace.setSpanContext(Tracing._openTelemetry.context.active(), parentContext);\r\n\r\n return Tracing._openTelemetry.context.with(\r\n Tracing._openTelemetry.trace.setSpan(\r\n parent,\r\n Tracing._tracer.startSpan(name, options, Tracing._openTelemetry.context.active())\r\n ),\r\n async () => {\r\n try {\r\n return await fn();\r\n } catch (err) {\r\n if (err instanceof Error) // ignore non-Error throws, such as RpcControlResponse\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttribute(\"error\", true);\r\n throw err;\r\n } finally {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.end();\r\n }\r\n },\r\n );\r\n }\r\n\r\n /**\r\n * Enable logging to OpenTelemetry. [[Tracing.withSpan]] will be enabled, all log entries will be attached to active span as span events.\r\n * [[IModelHost.startup]] will call this automatically if it succeeds in requiring `@opentelemetry/api`.\r\n * @note Node.js OpenTelemetry SDK should be initialized by the user.\r\n */\r\n public static enableOpenTelemetry(tracer: Tracer, api: typeof Tracing._openTelemetry) {\r\n Tracing._tracer = tracer;\r\n Tracing._openTelemetry = api;\r\n Logger.logTrace = Tracing.withOpenTelemetry(Logger.logTrace);\r\n Logger.logInfo = Tracing.withOpenTelemetry(Logger.logInfo);\r\n Logger.logWarning = Tracing.withOpenTelemetry(Logger.logWarning);\r\n Logger.logError = Tracing.withOpenTelemetry(Logger.logError);\r\n }\r\n\r\n private static withOpenTelemetry(base: LogFunction, isError: boolean = false): LogFunction {\r\n return (category, message, metaData) => {\r\n try {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.addEvent(message, { ...flattenObject(Logger.getMetaData(metaData)), error: isError });\r\n } catch (_e) { } // avoid throwing random errors (with stack trace mangled by async hooks) when openTelemetry collector doesn't work\r\n base(category, message, metaData);\r\n };\r\n }\r\n\r\n /** Set attributes on currently active openTelemetry span. Doesn't do anything if openTelemetry logging is not initialized.\r\n * @param attributes The attributes to set\r\n */\r\n public static setAttributes(attributes: SpanAttributes) {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttributes(attributes);\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"Tracing.js","sourceRoot":"","sources":["../../src/Tracing.ts"],"names":[],"mappings":"AAKA,OAAO,EAAe,MAAM,EAAE,MAAM,UAAU,CAAC;AAE/C,kGAAkG;AAClG;;;GAGG;AACH,MAAM,CAAN,IAAY,QAMX;AAND,WAAY,QAAQ;IAClB,+CAAY,CAAA;IACZ,2CAAU,CAAA;IACV,2CAAU,CAAA;IACV,+CAAY,CAAA;IACZ,+CAAY,CAAA;AACd,CAAC,EANW,QAAQ,KAAR,QAAQ,QAMnB;AAED,SAAS,gBAAgB,CAAC,GAAY;IACpC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,GAAG,KAAK,SAAS,CAAC;AACxF,CAAC;AAED,6GAA6G;AAC7G,iJA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,CAAC,OAAO,EAAE,EAAE,GAAG,aAAa,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;aACvK;YAAC,OAAO,EAAE,EAAE,GAAG,CAAC,mHAAmH;YACpI,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;QACpC,CAAC,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,aAAa,CAAC,UAA0B;QACpD,OAAO,CAAC,cAAc,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IAC5G,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\nimport type { ContextAPI, SpanAttributes, SpanAttributeValue, SpanContext, SpanOptions, TraceAPI, Tracer } from \"@opentelemetry/api\";\r\nimport { LogFunction, Logger } from \"./Logger\";\r\n\r\n// re-export so that consumers can construct full SpanOptions object without external dependencies\r\n/**\r\n * Mirrors the SpanKind enum from [@opentelemetry/api](https://open-telemetry.github.io/opentelemetry-js-api/enums/spankind)\r\n * @alpha\r\n */\r\nexport enum SpanKind {\r\n INTERNAL = 0,\r\n SERVER = 1,\r\n CLIENT = 2,\r\n PRODUCER = 3,\r\n CONSUMER = 4\r\n}\r\n\r\nfunction isValidPrimitive(val: unknown): val is SpanAttributeValue {\r\n return typeof val === \"string\" || typeof val === \"number\" || typeof val === \"boolean\";\r\n}\r\n\r\n// Only _homogenous_ arrays of strings, numbers, or booleans are supported as OpenTelemetry Attribute values.\r\n// Per the spec (https://opentelemetry.io/docs/reference/specification/common/common/#attribute), empty arrays and null values are supported too.\r\nfunction isValidPrimitiveArray(val: unknown): val is SpanAttributeValue {\r\n if (!Array.isArray(val))\r\n return false;\r\n\r\n let itemType;\r\n for (const x of val) {\r\n if (x === undefined || x === null)\r\n continue;\r\n\r\n if (!itemType) {\r\n itemType = typeof x;\r\n if (!isValidPrimitive(x))\r\n return false;\r\n }\r\n\r\n if (typeof x !== itemType)\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nfunction isPlainObject(obj: unknown): obj is object {\r\n return typeof obj === \"object\" && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;\r\n}\r\n\r\nfunction* getFlatEntries(obj: unknown, path = \"\"): Iterable<[string, SpanAttributeValue]> {\r\n if (isValidPrimitiveArray(obj)) {\r\n yield [path, obj];\r\n return;\r\n }\r\n\r\n // Prefer JSON serialization over flattening for any non-POJO types.\r\n // There's just too many ways trying to flatten those can go wrong (Dates, Buffers, TypedArrays, etc.)\r\n if (!isPlainObject(obj) && !Array.isArray(obj)) {\r\n yield [path, isValidPrimitive(obj) ? obj : JSON.stringify(obj)];\r\n return;\r\n }\r\n\r\n // Always serialize empty objects/arrays as empty array values\r\n const entries = Object.entries(obj);\r\n if (entries.length === 0)\r\n yield [path, []];\r\n\r\n for (const [key, val] of entries)\r\n yield* getFlatEntries(val, (path === \"\") ? key : `${path}.${key}`);\r\n}\r\n\r\nfunction flattenObject(obj: object): SpanAttributes {\r\n return Object.fromEntries(getFlatEntries(obj));\r\n}\r\n\r\n/**\r\n * Enables OpenTelemetry tracing in addition to traditional logging.\r\n * @alpha\r\n */\r\nexport class Tracing {\r\n private static _tracer?: Tracer;\r\n private static _openTelemetry?: { trace: Pick<TraceAPI, \"setSpan\" | \"setSpanContext\" | \"getSpan\">, context: Pick<ContextAPI, \"active\" | \"with\"> };\r\n\r\n /**\r\n * If OpenTelemetry tracing is enabled, creates a new span and runs the provided function in it.\r\n * If OpenTelemetry tracing is _not_ enabled, runs the provided function.\r\n * @param name name of the new span\r\n * @param fn function to run inside the new span\r\n * @param options span options\r\n * @param parentContext optional context used to retrieve parent span id\r\n */\r\n public static async withSpan<T>(name: string, fn: () => Promise<T>, options?: SpanOptions, parentContext?: SpanContext): Promise<T> {\r\n if (Tracing._tracer === undefined || Tracing._openTelemetry === undefined)\r\n return fn();\r\n\r\n // this case is for context propagation - parentContext is typically constructed from HTTP headers\r\n const parent = parentContext === undefined\r\n ? Tracing._openTelemetry.context.active()\r\n : Tracing._openTelemetry.trace.setSpanContext(Tracing._openTelemetry.context.active(), parentContext);\r\n\r\n return Tracing._openTelemetry.context.with(\r\n Tracing._openTelemetry.trace.setSpan(\r\n parent,\r\n Tracing._tracer.startSpan(name, options, Tracing._openTelemetry.context.active())\r\n ),\r\n async () => {\r\n try {\r\n return await fn();\r\n } catch (err) {\r\n if (err instanceof Error) // ignore non-Error throws, such as RpcControlResponse\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttribute(\"error\", true);\r\n throw err;\r\n } finally {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.end();\r\n }\r\n },\r\n );\r\n }\r\n\r\n /**\r\n * Enable logging to OpenTelemetry. [[Tracing.withSpan]] will be enabled, all log entries will be attached to active span as span events.\r\n * [[IModelHost.startup]] will call this automatically if it succeeds in requiring `@opentelemetry/api`.\r\n * @note Node.js OpenTelemetry SDK should be initialized by the user.\r\n */\r\n public static enableOpenTelemetry(tracer: Tracer, api: typeof Tracing._openTelemetry) {\r\n Tracing._tracer = tracer;\r\n Tracing._openTelemetry = api;\r\n Logger.logTrace = Tracing.withOpenTelemetry(Logger.logTrace);\r\n Logger.logInfo = Tracing.withOpenTelemetry(Logger.logInfo);\r\n Logger.logWarning = Tracing.withOpenTelemetry(Logger.logWarning);\r\n Logger.logError = Tracing.withOpenTelemetry(Logger.logError);\r\n }\r\n\r\n private static withOpenTelemetry(base: LogFunction, isError: boolean = false): LogFunction {\r\n return (category, message, metaData) => {\r\n try {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.addEvent(message, { ...flattenObject(Logger.getMetaData(metaData)), error: isError });\r\n } catch (_e) { } // avoid throwing random errors (with stack trace mangled by async hooks) when openTelemetry collector doesn't work\r\n base(category, message, metaData);\r\n };\r\n }\r\n\r\n /** Set attributes on currently active openTelemetry span. Doesn't do anything if openTelemetry logging is not initialized.\r\n * @param attributes The attributes to set\r\n */\r\n public static setAttributes(attributes: SpanAttributes) {\r\n Tracing._openTelemetry?.trace.getSpan(Tracing._openTelemetry.context.active())?.setAttributes(attributes);\r\n }\r\n}\r\n"]}
|
|
@@ -23,10 +23,9 @@ import { assert } from "./Assert";
|
|
|
23
23
|
export class TypedArrayBuilder {
|
|
24
24
|
/** Constructs a new builder from the specified options, with a [[length]] of zero. */
|
|
25
25
|
constructor(constructor, options) {
|
|
26
|
-
var _a, _b;
|
|
27
26
|
this._constructor = constructor;
|
|
28
|
-
this._data = new constructor(
|
|
29
|
-
this.growthFactor = Math.max(1.0,
|
|
27
|
+
this._data = new constructor(options?.initialCapacity ?? 0);
|
|
28
|
+
this.growthFactor = Math.max(1.0, options?.growthFactor ?? 1.5);
|
|
30
29
|
this._length = 0;
|
|
31
30
|
}
|
|
32
31
|
/** The number of elements currently in the array. */
|
|
@@ -154,8 +153,7 @@ export class Uint32ArrayBuilder extends TypedArrayBuilder {
|
|
|
154
153
|
*/
|
|
155
154
|
export class UintArrayBuilder extends TypedArrayBuilder {
|
|
156
155
|
constructor(options) {
|
|
157
|
-
|
|
158
|
-
super((_a = options === null || options === void 0 ? void 0 : options.initialType) !== null && _a !== void 0 ? _a : Uint8Array, options);
|
|
156
|
+
super(options?.initialType ?? Uint8Array, options);
|
|
159
157
|
}
|
|
160
158
|
/** The number of bytes (1, 2, or 4) currently allocated per element by the underlying array.
|
|
161
159
|
* This may change as larger values are added to the array.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TypedArrayBuilder.js","sourceRoot":"","sources":["../../src/TypedArrayBuilder.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;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Ae,KAAK,CAAC,IAAI,eAAe,KAAK,CAAC,CAAC,CAAC;QAChF,IAAI,eAAe,IAAI,CAAC;YACtB,OAAO;QAET,IAAI,kBAAkB,GAAG,eAAe,CAAC;QACzC,KAAK,MAAM,KAAK,IAAI,SAAS,EAAE;YAC7B,IAAI,KAAK,GAAG,MAAM,EAAE;gBAClB,kBAAkB,GAAG,CAAC,CAAC;gBACvB,MAAM;aACP;iBAAM,IAAI,KAAK,GAAG,IAAI,EAAE;gBACvB,kBAAkB,GAAG,CAAC,CAAC;aACxB;SACF;QAED,IAAI,kBAAkB,IAAI,eAAe;YACvC,OAAO;QAET,IAAI,CAAC,YAAY,GAAG,kBAAkB,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,kBAAkB,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;QACnH,IAAI,CAAC,KAAK,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjD,CAAC;IAED,sCAAsC;IACtB,IAAI,CAAC,KAAa;QAChC,IAAI,CAAC,qBAAqB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,wCAAwC;IACxB,MAAM,CAAC,MAAiB;QACtC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;QACnC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Collections\r\n */\r\n\r\nimport { Constructor } from \"./UtilityTypes\";\r\nimport { assert } from \"./Assert\";\r\n\r\n/** Options used to construct a [[TypedArrayBuilder]].\r\n * @public\r\n */\r\nexport interface TypedArrayBuilderOptions {\r\n /** Controls how much additional memory is allocated when the TypedArray needs to be resized to accomodate more elements.\r\n * [[TypedArrayBuilder.ensureCapacity]] multiplies the required capacity by this factor to determine the new capacity.\r\n * Default: 1.5\r\n * Minimum: 1.0, which causes the TypedArray to allocate exactly the space it needs each time it is resized.\r\n */\r\n growthFactor?: number;\r\n /** The number of elements to allocate memory for in the TypedArray when creating the builder.\r\n * If you know the minimum number of elements you intend to add to the builder, you should specify that as the\r\n * initial capacity to avoid reallocations when populating the array.\r\n * Default: 0.\r\n * Minimum: 0.\r\n */\r\n initialCapacity?: number;\r\n}\r\n\r\n/** A [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) containing unsigned 8-, 16-, or 32-bit integers.\r\n * @see [[UintArrayBuilder]] to construct such an array.\r\n * @public\r\n */\r\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array;\r\n\r\n/** Incrementally builds a [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) of unsigned 8-, 16-, or 32-bit integers.\r\n * Sometimes you wish to populate a `TypedArray`, but you don't know how many elements you will need.\r\n * `TypedArray` requires you to specify the size upon construction, and does not permit you to change the size later.\r\n *\r\n * `TypedArrayBuilder` manages a `TypedArray`, permitting you to [[push]] and [[append]] elements to it. It exposes two \"size\" properties\":\r\n * - [[capacity]], the number of elements it has currently allocated space for - i.e., the length of the underlying TypedArray; and\r\n * - [[length]], the number of elements that have so far been added to it, which is never bigger than [[capacity]].\r\n * When [[capacity]] is exceeded, a new, bigger TypedArray is allocated and the contents of the previous array are copied over to it.\r\n *\r\n * Once you've finished adding elements, you can obtain the finished `TypedArray` via [[toTypedArray]].\r\n * @see [[Uint8ArrayBuilder]], [[Uint16ArrayBuilder]], and [[Uint32ArrayBuilder]] to build specific types of arrays.\r\n * @see [[UintArrayBuilder]] when you don't know the maximum number of bytes required for each element in the array.\r\n * @public\r\n */\r\nexport class TypedArrayBuilder<T extends UintArray> {\r\n /** The constructor for the specific type of array being populated. */\r\n protected _constructor: Constructor<T>;\r\n /** The underlying typed array, to be reallocated and copied when its capacity is exceeded. */\r\n protected _data: T;\r\n /** The number of elements added to the array so far. */\r\n protected _length: number;\r\n /** Multiplier applied to required capacity by [[ensureCapacity]]. */\r\n public readonly growthFactor: number;\r\n\r\n /** Constructs a new builder from the specified options, with a [[length]] of zero. */\r\n protected constructor(constructor: Constructor<T>, options?: TypedArrayBuilderOptions) {\r\n this._constructor = constructor;\r\n this._data = new constructor(options?.initialCapacity ?? 0);\r\n this.growthFactor = Math.max(1.0, options?.growthFactor ?? 1.5);\r\n this._length = 0;\r\n }\r\n\r\n /** The number of elements currently in the array. */\r\n public get length(): number {\r\n return this._length;\r\n }\r\n\r\n /** The number of elements that can fit into the memory currently allocated for the array. */\r\n public get capacity(): number {\r\n return this._data.length;\r\n }\r\n\r\n /** Like [TypedArray.at](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/at),\r\n * returns the element at the specified index, with negative integers counting back from the end of the array.\r\n * @note It is your responsibility to ensure the index falls within the bounds of the array.\r\n */\r\n public at(index: number): number {\r\n if (index < 0)\r\n index = this.length - index;\r\n\r\n const value = this._data[index];\r\n assert(value !== undefined, \"index out of bounds\");\r\n return value;\r\n }\r\n\r\n /** Ensure that [[capacity]] is at least equal to `newCapacity`.\r\n * This is used internally by methods like [[push]] and [[append]] to ensure the array has room for the element(s) to be added.\r\n * It can also be useful when you know you intend to add some number of additional elements, to minimize reallocations.\r\n *\r\n * If `newCapacity` is not greater than the current [[capacity]], this function does nothing.\r\n * Otherwise, it allocates a new `TypedArray` with room for `newCapacity * growthFactor` elements, and copies the contents of the previous `TypedArray` into it.\r\n * [[length]] remains unchanged; [[capacity]] reflects the size of the new TypeArray.\r\n */\r\n public ensureCapacity(newCapacity: number): number {\r\n if (this.capacity >= newCapacity)\r\n return this.capacity;\r\n\r\n assert(this.growthFactor >= 1.0);\r\n newCapacity = Math.ceil(newCapacity * this.growthFactor);\r\n const prevData = this._data;\r\n this._data = new this._constructor(newCapacity);\r\n this._data.set(prevData, 0);\r\n\r\n assert(this.capacity === newCapacity);\r\n return this.capacity;\r\n }\r\n\r\n /** Append the specified value, resizing if necessary. */\r\n public push(value: number): void {\r\n this.ensureCapacity(this.length + 1);\r\n this._data[this.length] = value;\r\n ++this._length;\r\n }\r\n\r\n /** Append an array of values, resizing (at most once) if necessary. */\r\n public append(values: T): void {\r\n const newLength = this.length + values.length;\r\n this.ensureCapacity(newLength);\r\n this._data.set(values, this.length);\r\n this._length = newLength;\r\n }\r\n\r\n /** Obtain the finished array.\r\n * @param includeUnusedCapacity If true, the length of the returned array will be equal to [[capacity]], with extra bytes initialized to zero; otherwise, the\r\n * returned array's length will be equal to [[length]].\r\n */\r\n public toTypedArray(includeUnusedCapacity = false): T {\r\n if (includeUnusedCapacity)\r\n return this._data;\r\n\r\n const subarray = this._data.subarray(0, this.length);\r\n assert(subarray instanceof this._constructor);\r\n assert(subarray.buffer === this._data.buffer);\r\n return subarray;\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).\r\n * @public\r\n */\r\nexport class Uint8ArrayBuilder extends TypedArrayBuilder<Uint8Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint8Array, options);\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint16Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array).\r\n * @public\r\n */\r\nexport class Uint16ArrayBuilder extends TypedArrayBuilder<Uint16Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint16Array, options);\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint32Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array).\r\n * @public\r\n */\r\nexport class Uint32ArrayBuilder extends TypedArrayBuilder<Uint32Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint32Array, options);\r\n }\r\n\r\n /** Obtain a view of the finished array as an array of bytes. */\r\n public toUint8Array(includeUnusedCapacity = false): Uint8Array {\r\n if (includeUnusedCapacity)\r\n return new Uint8Array(this._data.buffer);\r\n\r\n return new Uint8Array(this._data.buffer, 0, this.length * 4);\r\n }\r\n}\r\n\r\n/** Options used to construct a [[UintArrayBuilder]].\r\n * @public\r\n */\r\nexport interface UintArrayBuilderOptions extends TypedArrayBuilderOptions {\r\n /** The type of the initial empty `TypedArray` created by the builder. For example, if you know that you will be adding values larger than\r\n * 255 to the array, specify `{ initialType: Uint16Array }` to avoid replacing the otherwise default `Uint8Array` when the first such value is added.\r\n * Default: `Uint8Array`.\r\n */\r\n initialType?: typeof Uint8Array | typeof Uint16Array | typeof Uint32Array;\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] that can populate a [[UintArray]] with the minimum\r\n * [bytes per element](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) required.\r\n *\r\n * By default, the underlying array is a `Uint8Array`, though this can be configured via [[UintArrayBuilderOptions.initialType]].\r\n * As values are added to the array, if the bytes per element supported by the underlying array is too small to hold one of the new values, the array is\r\n * reallocated to a type large enough to hold all of the new values. For example, the following produces a `Uint8Array` because all values are less than 256:\r\n *\r\n * ```ts\r\n * const builder = new UintArrayBuilder();\r\n * builder.append([1, 2, 254, 255]);\r\n * const array = builder.toTypedArray();\r\n * assert(array instanceof Uint8Array);\r\n * ```\r\n *\r\n * However, the following produces a `Uint16Array` because one of the values is larger than 255 but none are larger than 65,535:\r\n *\r\n * ```ts\r\n * const builder = new UintArrayBuilder();\r\n * builder.append([1, 255, 257, 65535]);\r\n * const array = builder.toTypedArray();\r\n * assert(array instanceof Uint16Array);\r\n * ```\r\n *\r\n * @see [[Uint8ArrayBuilder]], [[Uint16ArrayBuilder]], or [[Uint32ArrayBuilder]] if you know the number of bytes you want to allocate for each element in the array.\r\n * @public\r\n */\r\nexport class UintArrayBuilder extends TypedArrayBuilder<UintArray> {\r\n public constructor(options?: UintArrayBuilderOptions) {\r\n super(options?.initialType ?? Uint8Array, options);\r\n }\r\n\r\n /** The number of bytes (1, 2, or 4) currently allocated per element by the underlying array.\r\n * This may change as larger values are added to the array.\r\n */\r\n public get bytesPerElement(): number {\r\n return this._data.BYTES_PER_ELEMENT;\r\n }\r\n\r\n /** Ensures that the underlying array is of a type that can contain the largest value in `newValues`.\r\n * For example, if `_data` is a `Uint16Array` and `newValues` contains any value(s) larger than 65,535, it will be replaced with a `Uint32Array`.\r\n * This method is invoked by [[push]] and [[append]].\r\n */\r\n protected ensureBytesPerElement(newValues: Iterable<number>): void {\r\n const curBytesPerElem = this.bytesPerElement;\r\n assert(curBytesPerElem === 1 || curBytesPerElem === 2 || curBytesPerElem === 4);\r\n if (curBytesPerElem >= 4)\r\n return;\r\n\r\n let neededBytesPerElem = curBytesPerElem;\r\n for (const value of newValues) {\r\n if (value > 0xffff) {\r\n neededBytesPerElem = 4;\r\n break;\r\n } else if (value > 0xff) {\r\n neededBytesPerElem = 2;\r\n }\r\n }\r\n\r\n if (neededBytesPerElem <= curBytesPerElem)\r\n return;\r\n\r\n this._constructor = neededBytesPerElem === 1 ? Uint8Array : (neededBytesPerElem === 2 ? Uint16Array : Uint32Array);\r\n this._data = new this._constructor(this._data);\r\n }\r\n\r\n /** See [[TypedArrayBuilder.push]]. */\r\n public override push(value: number): void {\r\n this.ensureBytesPerElement([value]);\r\n super.push(value);\r\n }\r\n\r\n /** See [[TypedArrayBuilder.append]]. */\r\n public override append(values: UintArray): void {\r\n this.ensureBytesPerElement(values);\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C,MAAM,CAAC,eAAe,KAAK,CAAC,IAAI,eAAe,KAAK,CAAC,IAAI,eAAe,KAAK,CAAC,CAAC,CAAC;QAChF,IAAI,eAAe,IAAI,CAAC;YACtB,OAAO;QAET,IAAI,kBAAkB,GAAG,eAAe,CAAC;QACzC,KAAK,MAAM,KAAK,IAAI,SAAS,EAAE;YAC7B,IAAI,KAAK,GAAG,MAAM,EAAE;gBAClB,kBAAkB,GAAG,CAAC,CAAC;gBACvB,MAAM;aACP;iBAAM,IAAI,KAAK,GAAG,IAAI,EAAE;gBACvB,kBAAkB,GAAG,CAAC,CAAC;aACxB;SACF;QAED,IAAI,kBAAkB,IAAI,eAAe;YACvC,OAAO;QAET,IAAI,CAAC,YAAY,GAAG,kBAAkB,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,kBAAkB,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;QACnH,IAAI,CAAC,KAAK,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjD,CAAC;IAED,sCAAsC;IACtB,IAAI,CAAC,KAAa;QAChC,IAAI,CAAC,qBAAqB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,wCAAwC;IACxB,MAAM,CAAC,MAAiB;QACtC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;QACnC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Collections\r\n */\r\n\r\nimport { Constructor } from \"./UtilityTypes\";\r\nimport { assert } from \"./Assert\";\r\n\r\n/** Options used to construct a [[TypedArrayBuilder]].\r\n * @public\r\n */\r\nexport interface TypedArrayBuilderOptions {\r\n /** Controls how much additional memory is allocated when the TypedArray needs to be resized to accomodate more elements.\r\n * [[TypedArrayBuilder.ensureCapacity]] multiplies the required capacity by this factor to determine the new capacity.\r\n * Default: 1.5\r\n * Minimum: 1.0, which causes the TypedArray to allocate exactly the space it needs each time it is resized.\r\n */\r\n growthFactor?: number;\r\n /** The number of elements to allocate memory for in the TypedArray when creating the builder.\r\n * If you know the minimum number of elements you intend to add to the builder, you should specify that as the\r\n * initial capacity to avoid reallocations when populating the array.\r\n * Default: 0.\r\n * Minimum: 0.\r\n */\r\n initialCapacity?: number;\r\n}\r\n\r\n/** A [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) containing unsigned 8-, 16-, or 32-bit integers.\r\n * @see [[UintArrayBuilder]] to construct such an array.\r\n * @public\r\n */\r\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array;\r\n\r\n/** Incrementally builds a [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) of unsigned 8-, 16-, or 32-bit integers.\r\n * Sometimes you wish to populate a `TypedArray`, but you don't know how many elements you will need.\r\n * `TypedArray` requires you to specify the size upon construction, and does not permit you to change the size later.\r\n *\r\n * `TypedArrayBuilder` manages a `TypedArray`, permitting you to [[push]] and [[append]] elements to it. It exposes two \"size\" properties\":\r\n * - [[capacity]], the number of elements it has currently allocated space for - i.e., the length of the underlying TypedArray; and\r\n * - [[length]], the number of elements that have so far been added to it, which is never bigger than [[capacity]].\r\n * When [[capacity]] is exceeded, a new, bigger TypedArray is allocated and the contents of the previous array are copied over to it.\r\n *\r\n * Once you've finished adding elements, you can obtain the finished `TypedArray` via [[toTypedArray]].\r\n * @see [[Uint8ArrayBuilder]], [[Uint16ArrayBuilder]], and [[Uint32ArrayBuilder]] to build specific types of arrays.\r\n * @see [[UintArrayBuilder]] when you don't know the maximum number of bytes required for each element in the array.\r\n * @public\r\n */\r\nexport class TypedArrayBuilder<T extends UintArray> {\r\n /** The constructor for the specific type of array being populated. */\r\n protected _constructor: Constructor<T>;\r\n /** The underlying typed array, to be reallocated and copied when its capacity is exceeded. */\r\n protected _data: T;\r\n /** The number of elements added to the array so far. */\r\n protected _length: number;\r\n /** Multiplier applied to required capacity by [[ensureCapacity]]. */\r\n public readonly growthFactor: number;\r\n\r\n /** Constructs a new builder from the specified options, with a [[length]] of zero. */\r\n protected constructor(constructor: Constructor<T>, options?: TypedArrayBuilderOptions) {\r\n this._constructor = constructor;\r\n this._data = new constructor(options?.initialCapacity ?? 0);\r\n this.growthFactor = Math.max(1.0, options?.growthFactor ?? 1.5);\r\n this._length = 0;\r\n }\r\n\r\n /** The number of elements currently in the array. */\r\n public get length(): number {\r\n return this._length;\r\n }\r\n\r\n /** The number of elements that can fit into the memory currently allocated for the array. */\r\n public get capacity(): number {\r\n return this._data.length;\r\n }\r\n\r\n /** Like [TypedArray.at](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/at),\r\n * returns the element at the specified index, with negative integers counting back from the end of the array.\r\n * @note It is your responsibility to ensure the index falls within the bounds of the array.\r\n */\r\n public at(index: number): number {\r\n if (index < 0)\r\n index = this.length - index;\r\n\r\n const value = this._data[index];\r\n assert(value !== undefined, \"index out of bounds\");\r\n return value;\r\n }\r\n\r\n /** Ensure that [[capacity]] is at least equal to `newCapacity`.\r\n * This is used internally by methods like [[push]] and [[append]] to ensure the array has room for the element(s) to be added.\r\n * It can also be useful when you know you intend to add some number of additional elements, to minimize reallocations.\r\n *\r\n * If `newCapacity` is not greater than the current [[capacity]], this function does nothing.\r\n * Otherwise, it allocates a new `TypedArray` with room for `newCapacity * growthFactor` elements, and copies the contents of the previous `TypedArray` into it.\r\n * [[length]] remains unchanged; [[capacity]] reflects the size of the new TypeArray.\r\n */\r\n public ensureCapacity(newCapacity: number): number {\r\n if (this.capacity >= newCapacity)\r\n return this.capacity;\r\n\r\n assert(this.growthFactor >= 1.0);\r\n newCapacity = Math.ceil(newCapacity * this.growthFactor);\r\n const prevData = this._data;\r\n this._data = new this._constructor(newCapacity);\r\n this._data.set(prevData, 0);\r\n\r\n assert(this.capacity === newCapacity);\r\n return this.capacity;\r\n }\r\n\r\n /** Append the specified value, resizing if necessary. */\r\n public push(value: number): void {\r\n this.ensureCapacity(this.length + 1);\r\n this._data[this.length] = value;\r\n ++this._length;\r\n }\r\n\r\n /** Append an array of values, resizing (at most once) if necessary. */\r\n public append(values: T): void {\r\n const newLength = this.length + values.length;\r\n this.ensureCapacity(newLength);\r\n this._data.set(values, this.length);\r\n this._length = newLength;\r\n }\r\n\r\n /** Obtain the finished array.\r\n * @param includeUnusedCapacity If true, the length of the returned array will be equal to [[capacity]], with extra bytes initialized to zero; otherwise, the\r\n * returned array's length will be equal to [[length]].\r\n */\r\n public toTypedArray(includeUnusedCapacity = false): T {\r\n if (includeUnusedCapacity)\r\n return this._data;\r\n\r\n const subarray = this._data.subarray(0, this.length);\r\n assert(subarray instanceof this._constructor);\r\n assert(subarray.buffer === this._data.buffer);\r\n return subarray;\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).\r\n * @public\r\n */\r\nexport class Uint8ArrayBuilder extends TypedArrayBuilder<Uint8Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint8Array, options);\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint16Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array).\r\n * @public\r\n */\r\nexport class Uint16ArrayBuilder extends TypedArrayBuilder<Uint16Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint16Array, options);\r\n }\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] for producing a [Uint32Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array).\r\n * @public\r\n */\r\nexport class Uint32ArrayBuilder extends TypedArrayBuilder<Uint32Array> {\r\n /** See [[TypedArrayBuilder]] constructor. */\r\n public constructor(options?: TypedArrayBuilderOptions) {\r\n super(Uint32Array, options);\r\n }\r\n\r\n /** Obtain a view of the finished array as an array of bytes. */\r\n public toUint8Array(includeUnusedCapacity = false): Uint8Array {\r\n if (includeUnusedCapacity)\r\n return new Uint8Array(this._data.buffer);\r\n\r\n return new Uint8Array(this._data.buffer, 0, this.length * 4);\r\n }\r\n}\r\n\r\n/** Options used to construct a [[UintArrayBuilder]].\r\n * @public\r\n */\r\nexport interface UintArrayBuilderOptions extends TypedArrayBuilderOptions {\r\n /** The type of the initial empty `TypedArray` created by the builder. For example, if you know that you will be adding values larger than\r\n * 255 to the array, specify `{ initialType: Uint16Array }` to avoid replacing the otherwise default `Uint8Array` when the first such value is added.\r\n * Default: `Uint8Array`.\r\n */\r\n initialType?: typeof Uint8Array | typeof Uint16Array | typeof Uint32Array;\r\n}\r\n\r\n/** A [[TypedArrayBuilder]] that can populate a [[UintArray]] with the minimum\r\n * [bytes per element](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) required.\r\n *\r\n * By default, the underlying array is a `Uint8Array`, though this can be configured via [[UintArrayBuilderOptions.initialType]].\r\n * As values are added to the array, if the bytes per element supported by the underlying array is too small to hold one of the new values, the array is\r\n * reallocated to a type large enough to hold all of the new values. For example, the following produces a `Uint8Array` because all values are less than 256:\r\n *\r\n * ```ts\r\n * const builder = new UintArrayBuilder();\r\n * builder.append([1, 2, 254, 255]);\r\n * const array = builder.toTypedArray();\r\n * assert(array instanceof Uint8Array);\r\n * ```\r\n *\r\n * However, the following produces a `Uint16Array` because one of the values is larger than 255 but none are larger than 65,535:\r\n *\r\n * ```ts\r\n * const builder = new UintArrayBuilder();\r\n * builder.append([1, 255, 257, 65535]);\r\n * const array = builder.toTypedArray();\r\n * assert(array instanceof Uint16Array);\r\n * ```\r\n *\r\n * @see [[Uint8ArrayBuilder]], [[Uint16ArrayBuilder]], or [[Uint32ArrayBuilder]] if you know the number of bytes you want to allocate for each element in the array.\r\n * @public\r\n */\r\nexport class UintArrayBuilder extends TypedArrayBuilder<UintArray> {\r\n public constructor(options?: UintArrayBuilderOptions) {\r\n super(options?.initialType ?? Uint8Array, options);\r\n }\r\n\r\n /** The number of bytes (1, 2, or 4) currently allocated per element by the underlying array.\r\n * This may change as larger values are added to the array.\r\n */\r\n public get bytesPerElement(): number {\r\n return this._data.BYTES_PER_ELEMENT;\r\n }\r\n\r\n /** Ensures that the underlying array is of a type that can contain the largest value in `newValues`.\r\n * For example, if `_data` is a `Uint16Array` and `newValues` contains any value(s) larger than 65,535, it will be replaced with a `Uint32Array`.\r\n * This method is invoked by [[push]] and [[append]].\r\n */\r\n protected ensureBytesPerElement(newValues: Iterable<number>): void {\r\n const curBytesPerElem = this.bytesPerElement;\r\n assert(curBytesPerElem === 1 || curBytesPerElem === 2 || curBytesPerElem === 4);\r\n if (curBytesPerElem >= 4)\r\n return;\r\n\r\n let neededBytesPerElem = curBytesPerElem;\r\n for (const value of newValues) {\r\n if (value > 0xffff) {\r\n neededBytesPerElem = 4;\r\n break;\r\n } else if (value > 0xff) {\r\n neededBytesPerElem = 2;\r\n }\r\n }\r\n\r\n if (neededBytesPerElem <= curBytesPerElem)\r\n return;\r\n\r\n this._constructor = neededBytesPerElem === 1 ? Uint8Array : (neededBytesPerElem === 2 ? Uint16Array : Uint32Array);\r\n this._data = new this._constructor(this._data);\r\n }\r\n\r\n /** See [[TypedArrayBuilder.push]]. */\r\n public override push(value: number): void {\r\n this.ensureBytesPerElement([value]);\r\n super.push(value);\r\n }\r\n\r\n /** See [[TypedArrayBuilder.append]]. */\r\n public override append(values: UintArray): void {\r\n this.ensureBytesPerElement(values);\r\n super.append(values);\r\n }\r\n}\r\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@itwin/core-bentley",
|
|
3
|
-
"version": "4.0.0-dev.
|
|
3
|
+
"version": "4.0.0-dev.41",
|
|
4
4
|
"description": "Bentley JavaScript core components",
|
|
5
5
|
"main": "lib/cjs/core-bentley.js",
|
|
6
6
|
"module": "lib/esm/core-bentley.js",
|
|
@@ -21,13 +21,13 @@
|
|
|
21
21
|
"url": "http://www.bentley.com"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@itwin/build-tools": "4.0.0-dev.
|
|
25
|
-
"@itwin/eslint-plugin": "4.0.0-dev.
|
|
24
|
+
"@itwin/build-tools": "4.0.0-dev.41",
|
|
25
|
+
"@itwin/eslint-plugin": "4.0.0-dev.31",
|
|
26
26
|
"@opentelemetry/api": "1.0.4",
|
|
27
27
|
"@types/chai": "4.3.1",
|
|
28
28
|
"@types/chai-as-promised": "^7",
|
|
29
29
|
"@types/mocha": "^8.2.2",
|
|
30
|
-
"@types/node": "18.11.5",
|
|
30
|
+
"@types/node": "^18.11.5",
|
|
31
31
|
"chai": "^4.1.2",
|
|
32
32
|
"chai-as-promised": "^7",
|
|
33
33
|
"eslint": "^7.11.0",
|