diff --git a/CHANGES.md b/CHANGES.md index 7a0c832b..40adcda8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,12 @@ # CHANGES for indexeddbshim +## 15.2.0 + +- fix: avoid problematic double-escaping of `"` in LIKE clauses (used in + multi-entry searches) +- fix: for at least one-extra-level-nested array keys, ensure proper encoding + occurs (to ensure `get` requests work properly with them) + ## 15.1.0 - fix: actually include TS fixes diff --git a/dist/IDBIndex.d.ts.map b/dist/IDBIndex.d.ts.map index d41ec3cf..1442abc2 100644 --- a/dist/IDBIndex.d.ts.map +++ b/dist/IDBIndex.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"IDBIndex.d.ts","sourceRoot":"","sources":["../src/IDBIndex.js"],"names":[],"mappings":"sBAca,MAAM;iCAIN;IACR,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,OAAO,UAAU,EAAE,OAAO,CAAC;IACpC,cAAc,EAAE;QACd,MAAM,EAAE,OAAO,CAAC;QAChB,UAAU,EAAE,OAAO,CAAA;KACpB,CAAA;IACD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,gBAAgB,EAAE,sBAAsB,EAAE,CAAC;CAC7D;2BAcS,QAAQ,GAAG;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,UAAU,EAAE,OAAO,CAAC;IACpC,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;IAChB,WAAW,EAAE,OAAO,qBAAqB,EAAE,kBAAkB,CAAC;IAC9D,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,MAAM,EAAE,MAA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W,OAAO,qBAAqB,EAAE,kBAAkB,SAChD,YAAY,GACV,IAAI,CA0JhB;IAED;;;;;OAKG;IACH,8BAJW,OAAO,qBAAqB,EAAE,kBAAkB,SAChD,YAAY,GACV,IAAI,CA0DhB;IAED;;OAEG;IAEH;;;;;;;;;;OAUG;IACH,kCATW,OAAO,qBAAqB,EAAE,kBAAkB,MAChD,cAAc,WACd,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,kBAEjC,cAAc,OACb,QAAQ,KACV,OAAO,gBACF,IAAI,CAuBhB;;4BApdoE,kBAAkB;2BAI5D,qBAAqB"} \ No newline at end of file diff --git a/dist/indexeddbshim-Key.js b/dist/indexeddbshim-Key.js index 8c63a910..dd174577 100644 --- a/dist/indexeddbshim-Key.js +++ b/dist/indexeddbshim-Key.js @@ -1,4 +1,4 @@ -/*! indexeddbshim - v15.0.4 - 9/11/2024 */ +/*! indexeddbshim - v15.2.0 - 9/11/2024 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : diff --git a/dist/indexeddbshim-Key.js.map b/dist/indexeddbshim-Key.js.map index d56ffe78..41588770 100644 --- a/dist/indexeddbshim-Key.js.map +++ b/dist/indexeddbshim-Key.js.map @@ -1 +1 @@ -{"version":3,"file":"indexeddbshim-Key.js","sources":["../src/CFG.js","../src/DOMException.js","../src/util.js","../src/cmp.js","../src/Key.js"],"sourcesContent":["/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n/**\n * @typedef {T[keyof T]} ValueOf\n * @template T\n */\n/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n\n/**\n * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi\n */\n\n/**\n * @typedef {{\n * DEBUG: boolean,\n * cacheDatabaseInstances: boolean,\n * autoName: boolean,\n * fullIDLSupport: boolean,\n * checkOrigin: boolean,\n * cursorPreloadPackSize: number,\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string,\n * registerSCA: (\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset,\n * avoidAutoShim: boolean,\n * win: {\n * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default\n * },\n * DEFAULT_DB_SIZE: number,\n * useSQLiteIndexes: boolean,\n * fs: FSApi,\n * addNonIDBGlobals: boolean,\n * replaceNonIDBGlobals: boolean,\n * escapeDatabaseName: (name: string) => string,\n * unescapeDatabaseName: (name: string) => string,\n * databaseCharacterEscapeList: string|false,\n * databaseNameLengthLimit: number|false,\n * escapeNFDForDatabaseNames: boolean,\n * addSQLiteExtension: boolean,\n * memoryDatabase: string,\n * deleteDatabaseFiles: boolean,\n * databaseBasePath: string,\n * sysDatabaseBasePath: string,\n * sqlBusyTimeout: number,\n * sqlTrace: () => void,\n * sqlProfile: () => void,\n * createIndexes: boolean\n * }} ConfigValues\n */\n\n/**\n * @typedef {ValueOf} ConfigValue\n */\n\n/** @type {{[key: string]: ConfigValue}} */\nconst map = {};\n\nconst CFG = /** @type {ConfigValues} */ ({});\n\n/**\n * @typedef {keyof ConfigValues} KeyofConfigValues\n */\n\n/**\n * @typedef {KeyofConfigValues[]} Config\n */\n\n/** @type {Config} */\n([\n // Boolean for verbose reporting\n 'DEBUG', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean (effectively defaults to true) on whether to cache WebSQL\n // `openDatabase` instances\n 'cacheDatabaseInstances',\n\n // Boolean on whether to auto-name databases (based on an\n // auto-increment) when the empty string is supplied; useful with\n // `memoryDatabase`; defaults to `false` which means the empty string\n // will be used as the (valid) database name\n 'autoName',\n\n // Determines whether the slow-performing `Object.setPrototypeOf`\n // calls required for full WebIDL compliance will be used. Probably\n // only needed for testing or environments where full introspection\n // on class relationships is required; see\n // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean on whether to perform origin checks in `IDBFactory` methods\n // Effectively defaults to `true` (must be set to `false` to cancel checks)\n 'checkOrigin',\n\n // Used by `IDBCursor` continue methods for number of records to cache;\n // Defaults to 100\n 'cursorPreloadPackSize',\n\n // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);\n // or just use the Unicode builds which invoke this method\n // automatically using the large, fully spec-compliant, regular\n // expression strings of `src/UnicodeIdentifiers.js`)\n // In the non-Unicode builds, defaults to /[$A-Z_a-z]/\n 'UnicodeIDStart',\n // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/\n 'UnicodeIDContinue',\n\n // Used by SCA.js for optional restructuring of typeson-registry\n // Structured Cloning Algorithm; should only be needed for ensuring data\n // created in 3.* versions of IndexedDBShim continue to work; see the\n // library `typeson-registry-sca-reverter` to get a function to do this\n 'registerSCA',\n\n // BROWSER-SPECIFIC CONFIG\n 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is\n // missing or poor support is known (non-Chrome Android or\n // non-Safari iOS9), the shim will be auto-applied without\n // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing\n // the shim for such cases.\n\n // -----------SQL CONFIG----------\n // Object (`window` in the browser) on which there may be an\n // `openDatabase` method (if any) for WebSQL. (The browser\n // throws if attempting to call `openDatabase` without the window\n // so this is why the config doesn't just allow the function.)\n // Defaults to `window` or `self` in browser builds or\n // a singleton object with the `openDatabase` method set to\n // the \"websql\" package in Node.\n 'win',\n\n // For internal `openDatabase` calls made by `IDBFactory` methods;\n // per the WebSQL spec, \"User agents are expected to use the display name\n // and the estimated database size to optimize the user experience.\n // For example, a user agent could use the estimated size to suggest an\n // initial quota to the user. This allows a site that is aware that it\n // will try to use hundreds of megabytes to declare this upfront, instead\n // of the user agent prompting the user for permission to increase the\n // quota every five megabytes.\"\n // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari\n 'DEFAULT_DB_SIZE',\n // Whether to create indexes on SQLite tables (and also whether to try\n // dropping)\n // Effectively defaults to `false` (ignored unless `true`)\n 'useSQLiteIndexes',\n\n // NODE-IMPINGING SETTINGS (created for sake of limitations in Node\n // or desktop file system implementation but applied by default in\n // browser for parity)\n\n // File system module with `unlink` to remove deleted database files\n 'fs',\n\n // Used when setting global shims to determine whether to try to add\n // other globals shimmed by the library (`ShimDOMException`,\n // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'addNonIDBGlobals',\n // Used when setting global shims to determine whether to try to overwrite\n // other globals shimmed by the library (`DOMException`, `DOMStringList`,\n // `Event`, `CustomEvent`, `EventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'replaceNonIDBGlobals',\n\n // Overcoming limitations with node-sqlite3/storing database name on\n // file systems\n // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n // Defaults to prefixing database with `D_`, escaping\n // `databaseCharacterEscapeList`, escaping NUL, and\n // escaping upper case letters, as well as enforcing\n // `databaseNameLengthLimit`\n 'escapeDatabaseName',\n // Not used internally; usable as a convenience method\n 'unescapeDatabaseName',\n\n // Defaults to global regex representing the following\n // (characters nevertheless commonly reserved in modern,\n // Unicode-supporting systems): 0x00-0x1F 0x7F \" * / : < > ? \\ |\n 'databaseCharacterEscapeList',\n // Defaults to 254 (shortest typical modern file length limit)\n 'databaseNameLengthLimit',\n\n // Boolean defaulting to true on whether to escape NFD-escaping\n // characters to avoid clashes on MacOS which performs NFD on files\n 'escapeNFDForDatabaseNames',\n\n // Boolean on whether to add the `.sqlite` extension to file names;\n // defaults to `true`\n 'addSQLiteExtension',\n // Various types of in-memory databases that can auto-delete\n [\n 'memoryDatabase',\n /**\n * @param {string} val\n * @throws {TypeError}\n * @returns {void}\n */\n (val) => {\n if (!(/^(?::memory:|file::memory:(\\?[^#]*)?(#.*)?)?$/u).test(\n /** @type {string} */ (val)\n )) {\n throw new TypeError(\n '`memoryDatabase` must be the empty string, \":memory:\", or a ' +\n '\"file::memory:[?queryString][#hash] URL\".'\n );\n }\n }\n ],\n\n // NODE-SPECIFIC CONFIG\n // Boolean on whether to delete the database file itself after\n // `deleteDatabase`; defaults to `true` as the database will be empty\n 'deleteDatabaseFiles',\n 'databaseBasePath',\n 'sysDatabaseBasePath',\n\n // NODE-SPECIFIC WEBSQL CONFIG\n 'sqlBusyTimeout', // Defaults to 1000\n 'sqlTrace', // Callback not used by default\n 'sqlProfile', // Callback not used by default\n\n 'createIndexes'\n]).forEach((prop) => {\n /** @type {(val: any) => void} */\n let validator;\n if (Array.isArray(prop)) {\n [prop, validator] = prop;\n }\n Object.defineProperty(CFG, prop, {\n get () {\n return map[prop];\n },\n set (val) {\n if (validator) {\n validator(val);\n }\n map[prop] = val;\n }\n });\n});\n\nexport default CFG;\n","import CFG from './CFG.js';\n\n/**\n * Creates a native DOMException, for browsers that support it.\n * @param {string} name\n * @param {string} message\n * @returns {DOMException}\n */\nfunction createNativeDOMException (name, message) {\n // @ts-expect-error It's ok\n return new DOMException.prototype.constructor(\n message,\n name || 'DOMException'\n );\n}\n\n// From web-platform-tests testharness.js name_code_map (though not in new spec)\n\n/**\n * @typedef {\"IndexSizeError\"|\"HierarchyRequestError\"|\"WrongDocumentError\"|\n * \"InvalidCharacterError\"|\"NoModificationAllowedError\"|\"NotFoundError\"|\n * \"NotSupportedError\"|\"InUseAttributeError\"|\"InvalidStateError\"|\n * \"SyntaxError\"|\"InvalidModificationError\"|\"NamespaceError\"|\n * \"InvalidAccessError\"|\"TypeMismatchError\"|\"SecurityError\"|\n * \"NetworkError\"|\"AbortError\"|\"URLMismatchError\"|\"QuotaExceededError\"|\n * \"TimeoutError\"|\"InvalidNodeTypeError\"|\"DataCloneError\"|\"EncodingError\"|\n * \"NotReadableError\"|\"UnknownError\"|\"ConstraintError\"|\"DataError\"|\n * \"TransactionInactiveError\"|\"ReadOnlyError\"|\"VersionError\"|\n * \"OperationError\"|\"NotAllowedError\"} Code\n */\n\nconst codes = {\n IndexSizeError: 1,\n HierarchyRequestError: 3,\n WrongDocumentError: 4,\n InvalidCharacterError: 5,\n NoModificationAllowedError: 7,\n NotFoundError: 8,\n NotSupportedError: 9,\n InUseAttributeError: 10,\n InvalidStateError: 11,\n SyntaxError: 12,\n InvalidModificationError: 13,\n NamespaceError: 14,\n InvalidAccessError: 15,\n TypeMismatchError: 17,\n SecurityError: 18,\n NetworkError: 19,\n AbortError: 20,\n URLMismatchError: 21,\n QuotaExceededError: 22,\n TimeoutError: 23,\n InvalidNodeTypeError: 24,\n DataCloneError: 25,\n\n EncodingError: 0,\n NotReadableError: 0,\n UnknownError: 0,\n ConstraintError: 0,\n DataError: 0,\n TransactionInactiveError: 0,\n ReadOnlyError: 0,\n VersionError: 0,\n OperationError: 0,\n NotAllowedError: 0\n};\n\n/**\n * @typedef {\"INDEX_SIZE_ERR\"|\"DOMSTRING_SIZE_ERR\"|\"HIERARCHY_REQUEST_ERR\"|\n * \"WRONG_DOCUMENT_ERR\"|\"INVALID_CHARACTER_ERR\"|\"NO_DATA_ALLOWED_ERR\"|\n * \"NO_MODIFICATION_ALLOWED_ERR\"|\"NOT_FOUND_ERR\"|\"NOT_SUPPORTED_ERR\"|\n * \"INUSE_ATTRIBUTE_ERR\"|\"INVALID_STATE_ERR\"|\"SYNTAX_ERR\"|\n * \"INVALID_MODIFICATION_ERR\"|\"NAMESPACE_ERR\"|\"INVALID_ACCESS_ERR\"|\n * \"VALIDATION_ERR\"|\"TYPE_MISMATCH_ERR\"|\"SECURITY_ERR\"|\"NETWORK_ERR\"|\n * \"ABORT_ERR\"|\"URL_MISMATCH_ERR\"|\"QUOTA_EXCEEDED_ERR\"|\"TIMEOUT_ERR\"|\n * \"INVALID_NODE_TYPE_ERR\"|\"DATA_CLONE_ERR\"} LegacyCode\n */\n\nconst legacyCodes = {\n INDEX_SIZE_ERR: 1,\n DOMSTRING_SIZE_ERR: 2,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n INVALID_CHARACTER_ERR: 5,\n NO_DATA_ALLOWED_ERR: 6,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INUSE_ATTRIBUTE_ERR: 10,\n INVALID_STATE_ERR: 11,\n SYNTAX_ERR: 12,\n INVALID_MODIFICATION_ERR: 13,\n NAMESPACE_ERR: 14,\n INVALID_ACCESS_ERR: 15,\n VALIDATION_ERR: 16,\n TYPE_MISMATCH_ERR: 17,\n SECURITY_ERR: 18,\n NETWORK_ERR: 19,\n ABORT_ERR: 20,\n URL_MISMATCH_ERR: 21,\n QUOTA_EXCEEDED_ERR: 22,\n TIMEOUT_ERR: 23,\n INVALID_NODE_TYPE_ERR: 24,\n DATA_CLONE_ERR: 25\n};\n\n/**\n *\n * @returns {typeof DOMException}\n */\nfunction createNonNativeDOMExceptionClass () {\n /**\n * @param {string|undefined} message\n * @param {Code|LegacyCode} name\n * @returns {void}\n */\n function DOMException (message, name) {\n // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message\n this[Symbol.toStringTag] = 'DOMException';\n this._code = name in codes\n ? codes[/** @type {Code} */ (name)]\n : (legacyCodes[/** @type {LegacyCode} */ (name)] || 0);\n this._name = name || 'Error';\n // We avoid `String()` in this next line as it converts Symbols\n this._message = message === undefined ? '' : ('' + message); // eslint-disable-line no-implicit-coercion -- Don't convert symbols\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._code\n });\n if (name !== undefined) {\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._name\n });\n }\n if (message !== undefined) {\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: this._message\n });\n }\n }\n\n // Necessary for W3C tests which complains if `DOMException` has properties on its \"own\" prototype\n\n // class DummyDOMException extends Error {}; // Sometimes causing problems in Node\n /* eslint-disable func-name-matching -- See above */\n /**\n * @class\n */\n const DummyDOMException = function DOMException () { /* */ };\n /* eslint-enable func-name-matching -- See above */\n DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing\n /** @type {const} */ (['name', 'message']).forEach((prop) => {\n Object.defineProperty(DummyDOMException.prototype, prop, {\n enumerable: true,\n /**\n * @this {DOMException}\n * @returns {string}\n */\n get () {\n if (!(this instanceof DOMException ||\n // @ts-expect-error Just checking\n this instanceof DummyDOMException ||\n // @ts-expect-error Just checking\n this instanceof Error)) {\n throw new TypeError('Illegal invocation');\n }\n return this[prop === 'name' ? '_name' : '_message'];\n }\n });\n });\n // DOMException uses the same `toString` as `Error`\n Object.defineProperty(DummyDOMException.prototype, 'code', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n // @ts-expect-error It's ok\n DOMException.prototype = new DummyDOMException();\n\n DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';\n Object.defineProperty(DOMException, 'prototype', {\n writable: false\n });\n\n const keys = Object.keys(codes);\n\n /** @type {(keyof codes)[]} */ (keys).forEach(\n (codeName) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n }\n );\n /** @type {(keyof legacyCodes)[]} */ (Object.keys(legacyCodes)).forEach((\n codeName\n ) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n });\n Object.defineProperty(DOMException.prototype, 'constructor', {\n writable: true,\n configurable: true,\n enumerable: false,\n value: DOMException\n });\n\n // @ts-expect-error We don't need all its properties\n return DOMException;\n}\n\nconst ShimNonNativeDOMException = createNonNativeDOMExceptionClass();\n\n/**\n * Creates a generic Error object.\n * @param {string} name\n * @param {string} message\n * @returns {Error}\n */\nfunction createNonNativeDOMException (name, message) {\n return new ShimNonNativeDOMException(message, name);\n}\n\n/**\n * @typedef {{\n * message: string|DOMString\n * }} ErrorLike\n */\n\n/**\n * Logs detailed error information to the console.\n * @param {string} name\n * @param {string} message\n * @param {string|ErrorLike|boolean|null} [error]\n * @returns {void}\n */\nfunction logError (name, message, error) {\n if (CFG.DEBUG) {\n const msg = error && typeof error === 'object' && error.message\n ? error.message\n : /** @type {string} */ (error);\n\n const method = typeof (console.error) === 'function' ? 'error' : 'log';\n console[method](name + ': ' + message + '. ' + (msg || ''));\n if (console.trace) { console.trace(); }\n }\n}\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @param {ArbitraryValue} obj\n * @returns {boolean}\n */\nfunction isErrorOrDOMErrorOrDOMException (obj) {\n return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser\n typeof obj.name === 'string';\n}\n\n/**\n * Finds the error argument. This is useful because some WebSQL callbacks\n * pass the error as the first argument, and some pass it as the second\n * argument.\n * @param {(Error|{message?: string, name?: string}|any)[]} args\n * @returns {Error|DOMException|undefined}\n */\nfunction findError (args) {\n let err;\n if (args) {\n if (args.length === 1) {\n return args[0];\n }\n for (const arg of args) {\n if (isErrorOrDOMErrorOrDOMException(arg)) {\n return arg;\n }\n if (arg && typeof arg.message === 'string') {\n err = arg;\n }\n }\n }\n return err;\n}\n\n/**\n *\n * @param {SQLError} webSQLErr\n * @returns {(DOMException|Error) & {\n * sqlError: SQLError\n * }}\n */\nfunction webSQLErrback (webSQLErr) {\n let name, message;\n switch (webSQLErr.code) {\n case 4: { // SQLError.QUOTA_ERR\n name = 'QuotaExceededError';\n message = 'The operation failed because there was not enough ' +\n 'remaining storage space, or the storage quota was reached ' +\n 'and the user declined to give more space to the database.';\n break;\n }\n /*\n // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`?\n case 7: { // SQLError.TIMEOUT_ERR\n // All transaction errors abort later, so no need to mark inactive\n name = 'TransactionInactiveError';\n message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).';\n break;\n }\n */\n default: {\n name = 'UnknownError';\n message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.';\n break;\n }\n }\n message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')';\n const err =\n /**\n * @type {(Error | DOMException) & {\n * sqlError: SQLError\n * }}\n */\n (createDOMException(name, message));\n err.sqlError = webSQLErr;\n return err;\n}\n\nlet test, useNativeDOMException = false;\n\n// Test whether we can use the browser's native DOMException class\ntry {\n test = createNativeDOMException('test name', 'test message');\n if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {\n // Native DOMException works as expected\n useNativeDOMException = true;\n }\n// eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n} catch (err) {}\n\nconst createDOMException = useNativeDOMException\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n ? /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {DOMException}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNativeDOMException(name, message);\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n : /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {Error}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNonNativeDOMException(name, message);\n };\n\nconst ShimDOMException = useNativeDOMException\n ? DOMException\n : ShimNonNativeDOMException;\n\nexport {logError, findError, ShimDOMException, createDOMException, webSQLErrback};\n","/* eslint-disable new-cap -- ToString is how it is defined */\nimport CFG from './CFG.js';\nimport expandsOnNFD from './unicode-regex.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeUnmatchedSurrogates (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return arg.replaceAll(\n /([\\uD800-\\uDBFF])(?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])/gu,\n function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {\n // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577\n // but Chrome having problems\n if (unmatchedHighSurrogate) {\n return '^2' + unmatchedHighSurrogate.codePointAt()\n .toString(16).padStart(4, '0');\n }\n return (precedingLow || '') + '^3' +\n unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');\n }\n );\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeNameForSQLiteIdentifier (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return '_' + // Prevent empty string\n escapeUnmatchedSurrogates(\n arg.replaceAll('^', '^^') // Escape our escape\n // http://www.sqlite.org/src/tktview?name=57c971fc74\n .replaceAll('\\0', '^0')\n // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names\n // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577\n // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working\n .replaceAll(/([A-Z])/gu, '^$1')\n );\n}\n\n/**\n * The escaping of unmatched surrogates was needed by Chrome but not Node.\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeSQLiteStatement (arg) {\n return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\\0', '^0'));\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeSQLiteResponse (arg) {\n return unescapeUnmatchedSurrogates(arg)\n .replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n })\n .replaceAll('^^', '^');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlEscape (arg) {\n // https://www.sqlite.org/lang_keywords.html\n // http://stackoverflow.com/a/6701665/271577\n // There is no need to escape ', `, or [], as\n // we should always be within double quotes\n // NUL should have already been stripped\n return arg.replaceAll('\"', '\"\"');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlQuote (arg) {\n return '\"' + sqlEscape(arg) + '\"';\n}\n\n/**\n * @param {string} db\n * @throws {Error}\n * @returns {string}\n */\nfunction escapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.escapeDatabaseName) {\n // We at least ensure NUL is escaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), escaping casing (including Unicode?),\n // and escaping special characters depending on file system\n return CFG.escapeDatabaseName(escapeSQLiteStatement(db));\n }\n db = 'D' + escapeNameForSQLiteIdentifier(db);\n if (CFG.escapeNFDForDatabaseNames !== false) {\n // ES6 copying of regex with different flags\n db = db.replaceAll(new RegExp(expandsOnNFD, 'gu'), function (expandable) {\n return '^4' + /** @type {Integer} */ (expandable.codePointAt(0)).toString(16).padStart(6, '0');\n });\n }\n if (CFG.databaseCharacterEscapeList !== false) {\n db = db.replace(\n (CFG.databaseCharacterEscapeList\n ? new RegExp(CFG.databaseCharacterEscapeList, 'gu')\n : /[\\u0000-\\u001F\\u007F\"*/:<>?\\\\|]/gu), // eslint-disable-line no-control-regex -- Controls needed\n function (n0) {\n // eslint-disable-next-line unicorn/prefer-code-point -- Switch to `codePointAt`?\n return '^1' + n0.charCodeAt(0).toString(16).padStart(2, '0');\n }\n );\n }\n if (CFG.databaseNameLengthLimit !== false &&\n db.length >= ((CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0))) {\n throw new Error(\n 'Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' +\n db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'\n );\n }\n return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?)\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeUnmatchedSurrogates (arg) {\n return arg\n .replaceAll(/(\\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(lowSurr, 16))\n : _;\n }).replaceAll(/(\\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(highSurr, 16))\n : _;\n });\n}\n\n/**\n * Not in use internally but supplied for convenience.\n * @param {string} db\n * @returns {string}\n */\nfunction unescapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.unescapeDatabaseName) {\n // We at least ensure NUL is unescaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), unescaping casing (including Unicode?),\n // and unescaping special characters depending on file system\n return CFG.unescapeDatabaseName(unescapeSQLiteResponse(db));\n }\n\n return unescapeUnmatchedSurrogates(\n db.slice(2) // D_\n // CFG.databaseCharacterEscapeList\n .replaceAll(/(\\^+)1([0-9a-f]{2})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n // CFG.escapeNFDForDatabaseNames\n }).replaceAll(/(\\^+)4([0-9a-f]{6})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n })\n // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above)\n ).replaceAll(/(\\^+)([A-Z])/gu, (_, esc, upperCase) => {\n return esc.length % 2\n ? esc.slice(1) + upperCase\n : _;\n }).replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n }).replaceAll('^^', '^');\n}\n\n/**\n * @param {string} store\n * @returns {string}\n */\nfunction escapeStoreNameForSQL (store) {\n return sqlQuote('S' + escapeNameForSQLiteIdentifier(store));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQL (index) {\n return sqlQuote('I' + escapeNameForSQLiteIdentifier(index));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQLKeyColumn (index) {\n return 'I' + escapeNameForSQLiteIdentifier(index);\n}\n\n/**\n * @param {string} str\n * @returns {string}\n */\nfunction sqlLIKEEscape (str) {\n // https://www.sqlite.org/lang_expr.html#like\n return sqlEscape(str).replaceAll('^', '^^');\n}\n\n/**\n * @typedef {Function} AnyClass\n */\n\n// Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?)\n/**\n *\n * @param {AnyValue} obj\n * @param {AnyClass} Clss\n * @returns {boolean}\n */\nfunction instanceOf (obj, Clss) {\n return Clss[Symbol.hasInstance](obj);\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {obj is object}\n */\nfunction isObj (obj) {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isDate (obj) {\n return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isBlob (obj) {\n return isObj(obj) && 'size' in obj && typeof obj.size === 'number' &&\n 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isRegExp (obj) {\n return isObj(obj) && 'flags' in obj && typeof obj.flags === 'string' &&\n 'exec' in obj && typeof obj.exec === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isFile (obj) {\n return isObj(obj) && 'name' in obj && typeof obj.name === 'string' &&\n 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isBinary (obj) {\n return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && (\n ('slice' in obj && typeof obj.slice === 'function') || // `TypedArray` (view on buffer) or `ArrayBuffer`\n ('getFloat64' in obj && typeof obj.getFloat64 === 'function') // `DataView` (view on buffer)\n );\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isIterable (obj) {\n return isObj(obj) && Symbol.iterator in obj &&\n typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n },\n // @ts-expect-error Deliberately errs\n set [prop] (val) {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineReadonlyOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object & {\n * [key: string]: any\n * }} obj\n * @param {string[]} listeners\n * @returns {void}\n */\nfunction defineListenerProperties (obj, listeners) {\n listeners = typeof listeners === 'string' ? [listeners] : listeners;\n listeners.forEach((listener) => {\n const o = {\n get [listener] () {\n return obj['__' + listener];\n },\n /**\n * @param {AnyValue} val\n * @returns {void}\n */\n set [listener] (val) {\n obj['__' + listener] = val;\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, listener)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners)\n Object.defineProperty(obj, listener, desc);\n });\n listeners.forEach((l) => {\n obj[l] = null;\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string|string[]} props\n * @param {null|{\n * [key: string]: any\n * }} getter\n * @returns {void}\n */\nfunction defineReadonlyProperties (obj, props, getter = null) {\n props = typeof props === 'string' ? [props] : props;\n props.forEach(function (prop) {\n let o;\n if (getter && prop in getter) {\n o = getter[prop];\n } else {\n Object.defineProperty(obj, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // We must resort to this to get \"get \" as\n // the function `name` for proper IDL\n o = {\n get [prop] () {\n return this['__' + prop];\n }\n };\n }\n\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {string} item\n * @returns {boolean}\n */\nfunction isIdentifier (item) {\n // For load-time and run-time performance, we don't provide the complete regular\n // expression for identifiers, but these can be passed in, using the expressions\n // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407\n // ID_Start (includes Other_ID_Start)\n const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]';\n // ID_Continue (includes Other_ID_Continue)\n const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]';\n const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])';\n const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\\u200C\\u200D])';\n return (new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u')).test(item);\n}\n\n/**\n *\n * @param {string|string[]} keyPathString\n * @returns {boolean}\n */\nfunction isValidKeyPathString (keyPathString) {\n return typeof keyPathString === 'string' &&\n (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every((pathComponent) => {\n return isIdentifier(pathComponent);\n }));\n}\n\n/**\n *\n * @param {string|string[]} keyPath\n * @returns {boolean}\n */\nfunction isValidKeyPath (keyPath) {\n return isValidKeyPathString(keyPath) || (\n Array.isArray(keyPath) && Boolean(keyPath.length) &&\n // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html\n // See also https://heycam.github.io/webidl/#idl-DOMString\n [...keyPath].every((pathComponent) => {\n return isValidKeyPathString(pathComponent);\n })\n );\n}\n\n/**\n * @param {number} number\n * @param {\"unsigned long long\"|\"unsigned long\"} type\n * @throws {Error|TypeError}\n * @returns {number}\n */\nfunction enforceRange (number, type) {\n number = Math.floor(Number(number));\n let max, min;\n switch (type) {\n case 'unsigned long long': {\n max = 0x1FFFFFFFFFFFFF; // 2^53 - 1\n min = 0;\n break;\n }\n case 'unsigned long': {\n max = 0xFFFFFFFF; // 2^32 - 1\n min = 0;\n break;\n }\n default:\n throw new Error('Unrecognized type supplied to enforceRange');\n }\n if (!Number.isFinite(number) ||\n number > max ||\n number < min) {\n throw new TypeError('Invalid range: ' + number);\n }\n return number;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {AnyValue} v\n * @param {boolean} [treatNullAs]\n * @returns {string}\n */\nfunction convertToDOMString (v, treatNullAs) {\n return v === null && treatNullAs ? '' : ToString(v);\n}\n\n/**\n * @param {AnyValue} o\n * @returns {string}\n */\nfunction ToString (o) { // Todo: See `es-abstract/es7`\n // `String()` will not throw with Symbols\n return '' + o; // eslint-disable-line no-implicit-coercion -- Need to throw with symbols\n}\n\n/**\n *\n * @param {AnyValue} val\n * @returns {string|string[]}\n */\nfunction convertToSequenceDOMString (val) {\n // Per , converting to a sequence works with iterables\n if (isIterable(val)) { // We don't want conversion to array to convert primitives\n // Per , converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring\n return [...val].map((item) => {\n return ToString(item);\n });\n }\n return ToString(val);\n}\n\n/**\n * @param {AnyValue} v\n * @returns {v is null|undefined}\n */\nfunction isNullish (v) {\n return v === null || v === undefined;\n}\n\nexport {escapeSQLiteStatement, unescapeSQLiteResponse,\n escapeDatabaseNameForSQLAndFiles, unescapeDatabaseNameForSQLAndFiles,\n escapeStoreNameForSQL, escapeIndexNameForSQL, escapeIndexNameForSQLKeyColumn,\n sqlLIKEEscape, sqlQuote,\n instanceOf,\n isObj, isDate, isBlob, isRegExp, isFile, isBinary, isIterable,\n defineOuterInterface, defineReadonlyOuterInterface,\n defineListenerProperties, defineReadonlyProperties,\n isValidKeyPath, enforceRange,\n convertToDOMString, convertToSequenceDOMString,\n isNullish};\n","import CFG from './CFG.js';\nimport {encode as keyEncode, decode as keyDecode} from './Key.js';\n\n/**\n * Compares two keys.\n * @param {import('./Key.js').Key} first\n * @param {import('./Key.js').Key} second\n * @returns {0|1|-1}\n */\nfunction cmp (first, second) {\n const encodedKey1 = /** @type {string} */ (keyEncode(first));\n const encodedKey2 = /** @type {string} */ (keyEncode(second));\n const result = encodedKey1 > encodedKey2\n ? 1\n : encodedKey1 === encodedKey2 ? 0 : -1;\n\n if (CFG.DEBUG) {\n // verify that the keys encoded correctly\n let decodedKey1 = keyDecode(encodedKey1);\n let decodedKey2 = keyDecode(encodedKey2);\n if (typeof first === 'object') {\n first = JSON.stringify(first);\n decodedKey1 = JSON.stringify(decodedKey1);\n }\n if (typeof second === 'object') {\n second = JSON.stringify(second);\n decodedKey2 = JSON.stringify(decodedKey2);\n }\n\n // Encoding/decoding mismatches are usually due to a loss of\n // floating-point precision\n if (decodedKey1 !== first) {\n console.warn(\n first + ' was incorrectly encoded as ' + decodedKey1\n );\n }\n if (decodedKey2 !== second) {\n console.warn(\n second + ' was incorrectly encoded as ' + decodedKey2\n );\n }\n }\n\n return result;\n}\n\nexport default cmp;\n","import {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\nimport cmp from './cmp.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView\n */\n\n/**\n * @typedef {ArrayBufferView|ArrayBuffer} BufferSource\n */\n\n/**\n * @typedef {\"number\"|\"date\"|\"string\"|\"binary\"|\"array\"} KeyType\n */\n\n/**\n * @typedef {any} Value\n */\n\n/**\n * @typedef {any} Key\n * @todo Specify possible value more precisely\n */\n\n/**\n * @typedef {KeyPath[]} KeyPathArray\n */\n/**\n * @typedef {string|KeyPathArray} KeyPath\n */\n\n/**\n* @typedef {object} KeyValueObject\n* @property {KeyType|\"NaN\"|\"null\"|\"undefined\"|\"boolean\"|\"object\"|\"symbol\"|\n* \"function\"|\"bigint\"} type If not `KeyType`, indicates invalid value\n* @property {Value} [value]\n* @property {boolean} [invalid]\n* @property {string} [message]\n* @todo Specify acceptable `value` more precisely\n*/\n\n/**\n * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive\n */\n/**\n * @typedef {ValueType[]} ValueTypeArray\n */\n/**\n * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType\n */\n\n/**\n * Encodes the keys based on their types. This is required to maintain collations\n * We leave space for future keys.\n * @type {{[key: string]: Integer|string}}\n */\nconst keyTypeToEncodedChar = {\n invalid: 100,\n number: 200,\n date: 300,\n string: 400,\n binary: 500,\n array: 600\n};\nconst keyTypes = /** @type {(KeyType|\"invalid\")[]} */ (Object.keys(keyTypeToEncodedChar));\nkeyTypes.forEach((k) => {\n keyTypeToEncodedChar[k] = String.fromCodePoint(\n /** @type {number} */ (keyTypeToEncodedChar[k])\n );\n});\n\nconst encodedCharToKeyType = keyTypes.reduce((o, k) => {\n o[keyTypeToEncodedChar[k]] = k;\n return o;\n}, /** @type {{[key: string]: KeyType|\"invalid\"}} */ ({}));\n\n/**\n * The sign values for numbers, ordered from least to greatest.\n * - \"negativeInfinity\": Sorts below all other values.\n * - \"bigNegative\": Negative values less than or equal to negative one.\n * - \"smallNegative\": Negative values between negative one and zero, noninclusive.\n * - \"smallPositive\": Positive values between zero and one, including zero but not one.\n * - \"largePositive\": Positive values greater than or equal to one.\n * - \"positiveInfinity\": Sorts above all other values.\n */\nconst signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @type {{\n * [key: string]: {\n * encode: (param: any, inArray?: boolean) => string,\n * decode: (param: string, inArray?: boolean) => any\n * }\n * }}\n */\nconst types = {\n invalid: {\n /**\n * @returns {string}\n */\n encode () {\n return keyTypeToEncodedChar.invalid + '-';\n },\n /**\n * @returns {undefined}\n */\n decode () {\n return undefined;\n }\n },\n\n // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa\n // notation.\n //\n // sign: takes a value between zero and five, inclusive. Represents infinite cases\n // and the signs of both the exponent and the fractional part of the number.\n // exponent: padded to two base-32 digits, represented by the 32's compliment in the\n // \"smallPositive\" and \"bigNegative\" cases to ensure proper lexical sorting.\n // mantissa: also called the fractional part. Normed 11-digit base-32 representation.\n // Represented by the 32's compliment in the \"smallNegative\" and \"bigNegative\"\n // cases to ensure proper lexical sorting.\n number: {\n // The encode step checks for six numeric cases and generates 14-digit encoded\n // sign-exponent-mantissa strings.\n /**\n * @param {number} key\n * @returns {string}\n */\n encode (key) {\n let key32 = key === Number.MIN_VALUE\n // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some\n // Node (and Chrome) versions with `Number.MIN_VALUE` being treated\n // as 0\n // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring\n ? '0.' + '0'.repeat(214) + '2'\n : Math.abs(key).toString(32);\n // Get the index of the decimal.\n const decimalIndex = key32.indexOf('.');\n // Remove the decimal.\n key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;\n // Get the index of the first significant digit.\n const significantDigitIndex = key32.search(/[^0]/u);\n // Truncate leading zeros.\n key32 = key32.slice(significantDigitIndex);\n let sign, exponent, mantissa;\n\n // Finite cases:\n if (Number.isFinite(\n Number(key)\n )) {\n // Negative cases:\n if (key < 0) {\n // Negative exponent case:\n if (key > -1) {\n sign = signValues.indexOf('smallNegative');\n exponent = padBase32Exponent(significantDigitIndex);\n mantissa = flipBase32(padBase32Mantissa(key32));\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigNegative');\n exponent = flipBase32(padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n ));\n mantissa = flipBase32(padBase32Mantissa(key32));\n }\n // Non-negative cases:\n // Negative exponent case:\n } else if (key < 1) {\n sign = signValues.indexOf('smallPositive');\n exponent = flipBase32(padBase32Exponent(significantDigitIndex));\n mantissa = padBase32Mantissa(key32);\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigPositive');\n exponent = padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n );\n mantissa = padBase32Mantissa(key32);\n }\n // Infinite cases:\n } else {\n exponent = zeros(2);\n mantissa = zeros(11);\n sign = signValues.indexOf(\n key > 0 ? 'positiveInfinity' : 'negativeInfinity'\n );\n }\n\n return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;\n },\n // The decode step must interpret the sign, reflip values encoded as the 32's complements,\n // apply signs to the exponent and mantissa, do the base-32 power operation, and return\n // the original JavaScript number values.\n /**\n * @param {string} key\n * @returns {number}\n */\n decode (key) {\n const sign = Number(key.slice(2, 3));\n let exponent = key.slice(3, 5);\n let mantissa = key.slice(5, 16);\n\n switch (signValues[sign]) {\n case 'negativeInfinity':\n return Number.NEGATIVE_INFINITY;\n case 'positiveInfinity':\n return Number.POSITIVE_INFINITY;\n case 'bigPositive':\n return pow32(mantissa, exponent);\n case 'smallPositive':\n exponent = negate(flipBase32(exponent));\n return pow32(mantissa, exponent);\n case 'smallNegative':\n exponent = negate(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n case 'bigNegative':\n exponent = flipBase32(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n default:\n throw new Error('Invalid number.');\n }\n }\n },\n\n // Strings are encoded as JSON strings (with quotes and unicode characters escaped).\n //\n // If the strings are in an array, then some extra encoding is done to make sorting work correctly:\n // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly\n // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.\n // To do this, each character of the string is prepended with a dash (\"-\"), and a space is added to the end of the string.\n // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,\n // the indexes of each string's characters line up with each other.\n string: {\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n encode (key, inArray) {\n if (inArray) {\n // prepend each character with a dash, and append a space to the end\n key = key.replaceAll(/(.)/gu, '-$1') + ' ';\n }\n return keyTypeToEncodedChar.string + '-' + key;\n },\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n decode (key, inArray) {\n key = key.slice(2);\n if (inArray) {\n // remove the space at the end, and the dash before each character\n key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');\n }\n return key;\n }\n },\n\n // Arrays are encoded as JSON strings.\n // An extra, value is added to each array during encoding to make\n // empty arrays sort correctly.\n array: {\n /**\n * @param {ValueTypeArray} key\n * @returns {string}\n */\n encode (key) {\n const encoded = [];\n for (const [i, item] of key.entries()) {\n const encodedItem = encode(item, true); // encode the array item\n encoded[i] = encodedItem;\n }\n encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly\n return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);\n },\n /**\n * @param {string} key\n * @returns {ValueTypeArray}\n */\n decode (key) {\n const decoded = JSON.parse(key.slice(2));\n decoded.pop(); // remove the extra item\n for (let i = 0; i < decoded.length; i++) {\n const item = decoded[i];\n const decodedItem = decode(item, true); // decode the item\n decoded[i] = decodedItem;\n }\n return decoded;\n }\n },\n\n // Dates are encoded as ISO 8601 strings, in UTC time zone.\n date: {\n /**\n * @param {Date} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.date + '-' + key.toJSON();\n },\n /**\n * @param {string} key\n * @returns {Date}\n */\n decode (key) {\n return new Date(key.slice(2));\n }\n },\n binary: {\n // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)\n /**\n * @param {BufferSource} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.binary + '-' + (key.byteLength\n ? [...getCopyBytesHeldByBufferSource(key)].map(\n (b) => String(b).padStart(3, '0')\n ) // e.g., '255,005,254,000,001,033'\n : '');\n },\n /**\n * @param {string} key\n * @returns {ArrayBuffer}\n */\n decode (key) {\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const k = key.slice(2);\n const arr = k.length ? k.split(',').map((s) => Number.parseInt(s)) : [];\n const buffer = new ArrayBuffer(arr.length);\n const uint8 = new Uint8Array(buffer);\n uint8.set(arr);\n return buffer;\n }\n }\n};\n\n/**\n * Return a padded base-32 exponent value.\n * @param {number} n\n * @returns {string}\n */\nfunction padBase32Exponent (n) {\n const exp = n.toString(32);\n return (exp.length === 1) ? '0' + exp : exp;\n}\n\n/**\n * Return a padded base-32 mantissa.\n * @param {string} s\n * @returns {string}\n */\nfunction padBase32Mantissa (s) {\n return (s + zeros(11)).slice(0, 11);\n}\n\n/**\n * Flips each digit of a base-32 encoded string.\n * @param {string} encoded\n * @returns {string}\n */\nfunction flipBase32 (encoded) {\n let flipped = '';\n for (const ch of encoded) {\n flipped += (31 - Number.parseInt(ch, 32)).toString(32);\n }\n return flipped;\n}\n\n/**\n * Base-32 power function.\n * RESEARCH: This function does not precisely decode floats because it performs\n * floating point arithmetic to recover values. But can the original values be\n * recovered exactly?\n * Someone may have already figured out a good way to store JavaScript floats as\n * binary strings and convert back. Barring a better method, however, one route\n * may be to generate decimal strings that `parseFloat` decodes predictably.\n * @param {string} mantissa\n * @param {string} exponent\n * @returns {number}\n */\nfunction pow32 (mantissa, exponent) {\n const exp = Number.parseInt(exponent, 32);\n if (exp < 0) {\n return roundToPrecision(\n Number.parseInt(mantissa, 32) * (32 ** (exp - 10))\n );\n }\n if (exp < 11) {\n const whole = mantissa.slice(0, exp);\n const wholeNum = Number.parseInt(whole, 32);\n const fraction = mantissa.slice(exp);\n const fractionNum = Number.parseInt(fraction, 32) * (32 ** (exp - 11));\n return roundToPrecision(wholeNum + fractionNum);\n }\n const expansion = mantissa + zeros(exp - 11);\n return Number.parseInt(expansion, 32);\n}\n\n/**\n * @typedef {number} Float\n */\n\n/**\n * @param {Float} num\n * @param {Float} [precision]\n * @returns {Float}\n */\nfunction roundToPrecision (num, precision = 16) {\n return Number.parseFloat(num.toPrecision(precision));\n}\n\n/**\n * Returns a string of n zeros.\n * @param {number} n\n * @returns {string}\n */\nfunction zeros (n) {\n return '0'.repeat(n);\n}\n\n/**\n * Negates numeric strings.\n * @param {string} s\n * @returns {string}\n */\nfunction negate (s) {\n return '-' + s;\n}\n\n/**\n * @param {Key} key\n * @returns {KeyType|\"invalid\"}\n */\nfunction getKeyType (key) {\n if (Array.isArray(key)) { return 'array'; }\n if (util.isDate(key)) { return 'date'; }\n if (util.isBinary(key)) { return 'binary'; }\n const keyType = typeof key;\n return ['string', 'number'].includes(keyType)\n ? /** @type {\"string\"|\"number\"} */ (keyType)\n : 'invalid';\n}\n\n/**\n * Keys must be strings, numbers (besides `NaN`), Dates (if value is not\n * `NaN`), binary objects or Arrays.\n * @param {Value} input The key input\n * @param {Value[]|null|undefined} [seen] An array of already seen keys\n * @returns {KeyValueObject}\n */\nfunction convertValueToKey (input, seen) {\n return convertValueToKeyValueDecoded(input, seen, false, true);\n}\n\n/**\n* Currently not in use.\n* @param {Value} input\n* @returns {KeyValueObject}\n*/\nfunction convertValueToMultiEntryKey (input) {\n return convertValueToKeyValueDecoded(input, null, true, true);\n}\n\n/**\n *\n * @param {BufferSource} O\n * @throws {TypeError}\n * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n * @returns {Uint8Array}\n */\nfunction getCopyBytesHeldByBufferSource (O) {\n let offset = 0;\n let length = 0;\n if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot\n const arrayBuffer = O.buffer;\n if (arrayBuffer === undefined) {\n throw new TypeError(\n 'Could not copy the bytes held by a buffer source as the buffer was undefined.'\n );\n }\n offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)\n length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)\n } else {\n length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)\n }\n // const octets = new Uint8Array(input);\n // const octets = types.binary.decode(types.binary.encode(input));\n return new Uint8Array(\n // Should allow DataView\n /** @type {ArrayBuffer} */\n (('buffer' in O && O.buffer) || O),\n offset,\n length\n );\n}\n\n/**\n* Shortcut utility to avoid returning full keys from `convertValueToKey`\n* and subsequent need to process in calling code unless `fullKeys` is\n* set; may throw.\n* @param {Value} input\n* @param {Value[]|null} [seen]\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @throws {TypeError} See `getCopyBytesHeldByBufferSource`\n* @todo Document other allowable `input`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {\n seen = seen || [];\n if (seen.includes(input)) {\n return {\n type: 'array',\n invalid: true,\n message: 'An array key cannot be circular'\n };\n }\n const type = getKeyType(input);\n const ret = {type, value: input};\n switch (type) {\n case 'number': {\n if (Number.isNaN(input)) {\n // List as 'NaN' type for convenience of consumers in reporting errors\n return {type: 'NaN', invalid: true};\n }\n\n // https://github.com/w3c/IndexedDB/issues/375\n // https://github.com/w3c/IndexedDB/pull/386\n if (Object.is(input, -0)) {\n return {type, value: 0};\n }\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'string': {\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'binary': { // May throw (if detached)\n // Get a copy of the bytes held by the buffer source\n // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n const octets = getCopyBytesHeldByBufferSource(\n /** @type {BufferSource} */ (input)\n );\n return {type: 'binary', value: octets};\n } case 'array': { // May throw (from binary)\n const arr = /** @type {Array} */ (input);\n const len = arr.length;\n seen.push(input);\n\n /** @type {(KeyValueObject|Value)[]} */\n const keys = [];\n for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated\n if (!multiEntry && !Object.hasOwn(arr, i)) {\n return {type, invalid: true, message: 'Does not have own index property'};\n }\n try {\n const entry = arr[i];\n const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry\n if (key.invalid) {\n if (multiEntry) {\n continue;\n }\n return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};\n }\n if (!multiEntry ||\n (!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||\n (fullKeys && keys.every((k) => cmp(k, key) !== 0))\n ) {\n keys.push(fullKeys ? key : key.value);\n }\n } catch (err) {\n if (!multiEntry) {\n throw err;\n }\n }\n }\n return {type, value: keys};\n } case 'date': {\n const date = /** @type {Date} */ (input);\n if (!Number.isNaN(date.getTime())) {\n return fullKeys\n ? {type, value: date.getTime()}\n : {type, value: new Date(date.getTime())};\n }\n return {type, invalid: true, message: 'Not a valid date'};\n // Falls through\n } case 'invalid': default: {\n // Other `typeof` types which are not valid keys:\n // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'\n const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors\n return {type, invalid: true, message: 'Not a valid key; type ' + type};\n }\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [fullKeys]\n * @returns {KeyValueObject}\n * @todo Document other allowable `key`?\n */\nfunction convertValueToMultiEntryKeyDecoded (key, fullKeys) {\n return convertValueToKeyValueDecoded(key, null, true, fullKeys);\n}\n\n/**\n* An internal utility.\n* @param {Value} input\n* @param {Value[]|null|undefined} [seen]\n* @throws {DOMException} `DataError`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyRethrowingAndIfInvalid (input, seen) {\n const key = convertValueToKey(input, seen);\n if (key.invalid) {\n throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);\n }\n return key;\n}\n\n/**\n *\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} multiEntry\n * @returns {KeyValueObject|KeyPathEvaluateValue}\n * @todo Document other possible return?\n */\nfunction extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {\n return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);\n}\n/**\n* Not currently in use.\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} multiEntry\n* @returns {KeyPathEvaluateValue}\n*/\nfunction evaluateKeyPathOnValue (value, keyPath, multiEntry) {\n return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);\n}\n\n/**\n* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)\n* or `{invalid: true}` (e.g., `NaN`).\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @returns {KeyValueObject|KeyPathEvaluateValue}\n* @todo Document other possible return?\n*/\nfunction extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {\n const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);\n if (r.failure) {\n return r;\n }\n if (!multiEntry) {\n return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);\n }\n return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);\n}\n\n/**\n * Unused?\n * @typedef {object} KeyPathEvaluateFailure\n * @property {boolean} failure\n */\n\n/**\n * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray\n */\n\n/**\n * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue\n */\n\n/**\n * @typedef {object} KeyPathEvaluateValue\n * @property {KeyPathEvaluateValueValue} [value]\n * @property {boolean} [failure]\n */\n\n/**\n * Returns the value of an inline key based on a key path (wrapped in an\n * object with key `value`) or `{failure: true}`\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} [multiEntry]\n * @param {boolean} [fullKeys]\n * @returns {KeyPathEvaluateValue}\n */\nfunction evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {\n if (Array.isArray(keyPath)) {\n /** @type {KeyPathEvaluateValueValueArray} */\n const result = [];\n return keyPath.some((item) => {\n const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);\n if (key.failure) {\n return true;\n }\n result.push(key.value);\n return false;\n })\n ? {failure: true}\n : {value: result};\n }\n if (keyPath === '') {\n return {value};\n }\n const identifiers = keyPath.split('.');\n return identifiers.some((idntfr) => {\n if (idntfr === 'length' && (\n typeof value === 'string' || Array.isArray(value)\n )) {\n value = value.length;\n } else if (util.isBlob(value)) {\n switch (idntfr) {\n case 'size': case 'type':\n value = /** @type {Blob} */ (value)[idntfr];\n break;\n }\n } else if (util.isFile(value)) {\n switch (idntfr) {\n case 'name': case 'lastModified':\n value = /** @type {File} */ (value)[idntfr];\n break;\n case 'lastModifiedDate':\n value = new Date(/** @type {File} */ (value).lastModified);\n break;\n }\n } else if (!util.isObj(value) || !Object.hasOwn(value, idntfr)) {\n return true;\n } else {\n value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */ (\n value\n )[idntfr];\n return value === undefined;\n }\n return false;\n })\n ? {failure: true}\n : {value};\n}\n\n/**\n * Sets the inline key value.\n * @param {{[key: string]: AnyValue}} value\n * @param {Key} key\n * @param {string} keyPath\n * @returns {void}\n */\nfunction injectKeyIntoValueUsingKeyPath (value, key, keyPath) {\n const identifiers = keyPath.split('.');\n const last = identifiers.pop();\n identifiers.forEach((identifier) => {\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n value[identifier] = {};\n }\n value = value[identifier];\n });\n value[/** @type {string} */ (last)] = key; // key is already a `keyValue` in our processing so no need to convert\n}\n\n/**\n *\n * @param {Value} value\n * @param {string} keyPath\n * @see https://github.com/w3c/IndexedDB/pull/146\n * @returns {boolean}\n */\nfunction checkKeyCouldBeInjectedIntoValue (value, keyPath) {\n const identifiers = keyPath.split('.');\n identifiers.pop();\n for (const identifier of identifiers) {\n if (!util.isObj(value)) {\n return false;\n }\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n return true;\n }\n value = /** @type {{[key: string]: Value}} */ (value)[identifier];\n }\n return util.isObj(value);\n}\n\n/**\n *\n * @param {Key} key\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range\n * @param {boolean} [checkCached]\n * @returns {boolean}\n */\nfunction isKeyInRange (key, range, checkCached) {\n let lowerMatch = range.lower === undefined;\n let upperMatch = range.upper === undefined;\n const encodedKey = encode(key, true);\n const lower = checkCached ? range.__lowerCached : encode(range.lower, true);\n const upper = checkCached ? range.__upperCached : encode(range.upper, true);\n\n if (!lowerMatch && (\n (range.lowerOpen &&\n encodedKey !== null && lower !== null && encodedKey > lower) ||\n (!range.lowerOpen && (\n (!encodedKey && !lower) ||\n (encodedKey !== null && lower !== null && encodedKey >= lower))\n )\n )) {\n lowerMatch = true;\n }\n if (!upperMatch && (\n (range.upperOpen &&\n encodedKey !== null && upper !== null && encodedKey < upper) ||\n (!range.upperOpen && (\n (!encodedKey && !upper) ||\n (encodedKey !== null && upper !== null && encodedKey <= upper))\n )\n )) {\n upperMatch = true;\n }\n\n return lowerMatch && upperMatch;\n}\n\n/**\n * Determines whether an index entry matches a multi-entry key value.\n * @param {string} encodedEntry The entry value (already encoded)\n * @param {string} encodedKey The full index key (already encoded)\n * @returns {boolean}\n */\nfunction isMultiEntryMatch (encodedEntry, encodedKey) {\n const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];\n\n if (keyType === 'array') {\n return encodedKey.indexOf(encodedEntry) > 1;\n }\n return encodedKey === encodedEntry;\n}\n\n/**\n *\n * @param {Key} keyEntry\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range\n * @returns {Key[]}\n */\nfunction findMultiEntryMatches (keyEntry, range) {\n const matches = [];\n\n if (Array.isArray(keyEntry)) {\n for (let key of keyEntry) {\n if (Array.isArray(key)) {\n if (range && range.lower === range.upper) {\n continue;\n }\n if (key.length === 1) {\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n key = key[0];\n } else {\n const nested = findMultiEntryMatches(key, range);\n if (nested.length > 0) {\n matches.push(key);\n }\n continue;\n }\n }\n\n if (util.isNullish(range) || isKeyInRange(key, range, true)) {\n matches.push(key);\n }\n }\n } else if (util.isNullish(range) || isKeyInRange(keyEntry, range, true)) {\n matches.push(keyEntry);\n }\n return matches;\n}\n\n/**\n* Not currently in use but keeping for spec parity.\n* @param {Key} key\n* @throws {Error} Upon a \"bad key\"\n* @returns {ValueType}\n*/\nfunction convertKeyToValue (key) {\n const {type, value} = key;\n switch (type) {\n case 'number': case 'string': {\n return value;\n } case 'array': {\n const array = [];\n const len = value.length;\n let index = 0;\n while (index < len) {\n const entry = convertKeyToValue(value[index]);\n array[index] = entry;\n index++;\n }\n return array;\n } case 'date': {\n return new Date(value);\n } case 'binary': {\n const len = value.length;\n const buffer = new ArrayBuffer(len);\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);\n uint8.set(value);\n return buffer;\n } case 'invalid': default:\n throw new Error('Bad key');\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {string|null}\n */\nfunction encode (key, inArray) {\n // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation\n if (key === undefined) {\n return null;\n }\n // array, date, number, string, binary (should already have detected \"invalid\")\n return types[getKeyType(key)].encode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @throws {Error} Invalid number\n * @returns {undefined|ValueType}\n */\nfunction decode (key, inArray) {\n if (typeof key !== 'string') {\n return undefined;\n }\n return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {undefined|ValueType}\n */\nfunction roundTrip (key, inArray) {\n return decode(encode(key, inArray), inArray);\n}\n\nconst MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback CurrentNumberCallback\n * @param {Integer} cn The current number\n * @returns {void}\n */\n\n/**\n* @callback SQLFailureCallback\n* @param {DOMException|Error} exception\n* @returns {void}\n*/\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {CurrentNumberCallback} func\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction getCurrentNumber (tx, store, func, sqlFailCb) {\n tx.executeSql('SELECT \"currNum\" FROM __sys__ WHERE \"name\" = ?', [\n util.escapeSQLiteStatement(store.__currentName)\n ], function (tx, data) {\n if (data.rows.length !== 1) {\n func(1);\n } else {\n func(data.rows.item(0).currNum);\n }\n }, function (tx, error) {\n sqlFailCb(createDOMException(\n 'DataError',\n 'Could not get the auto increment value for key',\n error\n ));\n return false;\n });\n}\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction assignCurrentNumber (tx, store, num, successCb, failCb) {\n const sql = 'UPDATE __sys__ SET \"currNum\" = ? WHERE \"name\" = ?';\n const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n tx.executeSql(sql, sqlValues, function () {\n successCb(num);\n }, function (tx, err) {\n failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));\n return false;\n });\n}\n\n/**\n * Bump up the auto-inc counter if the key path-resolved value is valid\n * (greater than old value and >=1) OR if a manually passed in key is\n * valid (numeric and >= 1) and >= any primaryKey.\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction setCurrentNumber (tx, store, num, successCb, failCb) {\n num = num === MAX_ALLOWED_CURRENT_NUMBER\n ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner\n : num + 1;\n return assignCurrentNumber(tx, store, num, successCb, failCb);\n}\n\n/**\n * @callback KeyForStoreCallback\n * @param {\"failure\"|null} arg1\n * @param {Integer} [arg2]\n * @param {Integer} [arg3]\n * @returns {void}\n */\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {KeyForStoreCallback} cb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction generateKeyForStore (tx, store, cb, sqlFailCb) {\n getCurrentNumber(tx, store, function (key) {\n if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See )\n cb('failure');\n return;\n }\n // Increment current number by 1 (we cannot leverage SQLite's\n // autoincrement (and decrement when not needed), as decrementing\n // will be overwritten/ignored upon the next insert)\n setCurrentNumber(\n tx, store, key,\n function () {\n cb(null, key, key);\n },\n sqlFailCb\n );\n }, sqlFailCb);\n}\n\n// Fractional or numbers exceeding the max do not get changed in the result\n// per https://github.com/w3c/IndexedDB/issues/147\n// so we do not return a key\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Key} key\n * @param {(num?: Integer) => void} successCb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {\n // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers\n // (or numbers larger than the max) are now to have the explicit effect of\n // setting the current number (up to the max), so we do not optimize them\n // out here\n if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number\n // Auto-increment attempted with a bad key;\n // we are not to change the current number, but the steps don't call for failure\n // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1\n successCb();\n } else {\n // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher\n // to determine which to use and whether to update the current number\n getCurrentNumber(tx, store, function (cn) {\n const value = Math.floor(\n Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)\n );\n const useNewKeyForAutoInc = value >= cn;\n if (useNewKeyForAutoInc) {\n setCurrentNumber(tx, store, value, function () {\n successCb(cn); // Supply old current number in case needs to be reverted\n }, sqlFailCb);\n } else { // Not updated\n successCb();\n }\n }, sqlFailCb);\n }\n}\n\nexport {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,\n convertValueToMultiEntryKeyDecoded,\n convertValueToKey,\n convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,\n extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,\n extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,\n isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,\n assignCurrentNumber,\n generateKeyForStore, possiblyUpdateKeyGenerator};\n"],"names":["map","CFG","val","test","TypeError","forEach","prop","validator","Array","isArray","_prop","_prop2","_slicedToArray","Object","defineProperty","get","set","createNativeDOMException","name","message","DOMException","prototype","constructor","codes","IndexSizeError","HierarchyRequestError","WrongDocumentError","InvalidCharacterError","NoModificationAllowedError","NotFoundError","NotSupportedError","InUseAttributeError","InvalidStateError","SyntaxError","InvalidModificationError","NamespaceError","InvalidAccessError","TypeMismatchError","SecurityError","NetworkError","AbortError","URLMismatchError","QuotaExceededError","TimeoutError","InvalidNodeTypeError","DataCloneError","EncodingError","NotReadableError","UnknownError","ConstraintError","DataError","TransactionInactiveError","ReadOnlyError","VersionError","OperationError","NotAllowedError","legacyCodes","INDEX_SIZE_ERR","DOMSTRING_SIZE_ERR","HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR","NO_DATA_ALLOWED_ERR","NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR","VALIDATION_ERR","TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR","createNonNativeDOMExceptionClass","Symbol","toStringTag","_code","_name","_message","undefined","configurable","enumerable","writable","value","DummyDOMException","create","Error","keys","codeName","ShimNonNativeDOMException","createNonNativeDOMException","logError","error","DEBUG","msg","_typeof","method","console","trace","isErrorOrDOMErrorOrDOMException","obj","useNativeDOMException","err","createDOMException","escapeUnmatchedSurrogates","arg","replaceAll","_","unmatchedHighSurrogate","precedingLow","unmatchedLowSurrogate","codePointAt","toString","padStart","escapeSQLiteStatement","isObj","isDate","getDate","isBlob","size","slice","isFile","isBinary","byteLength","getFloat64","isNullish","v","cmp","first","second","encodedKey1","keyEncode","encodedKey2","result","decodedKey1","keyDecode","decodedKey2","JSON","stringify","warn","keyTypeToEncodedChar","invalid","number","date","string","binary","array","keyTypes","k","String","fromCodePoint","encodedCharToKeyType","reduce","o","signValues","types","encode","decode","key","key32","Number","MIN_VALUE","repeat","Math","abs","decimalIndex","indexOf","replace","significantDigitIndex","search","sign","exponent","mantissa","isFinite","padBase32Exponent","flipBase32","padBase32Mantissa","length","zeros","NEGATIVE_INFINITY","POSITIVE_INFINITY","pow32","negate","inArray","encoded","_iterator","_createForOfIteratorHelper","entries","_step","s","n","done","_step$value","i","item","encodedItem","e","f","push","decoded","parse","pop","decodedItem","toJSON","Date","_toConsumableArray","getCopyBytesHeldByBufferSource","b","arr","split","parseInt","buffer","ArrayBuffer","uint8","Uint8Array","exp","flipped","_iterator2","_step2","ch","roundToPrecision","pow","whole","wholeNum","fraction","fractionNum","expansion","num","precision","arguments","parseFloat","toPrecision","getKeyType","util","keyType","includes","convertValueToKey","input","seen","convertValueToKeyValueDecoded","convertValueToMultiEntryKey","O","offset","isView","arrayBuffer","byteOffset","multiEntry","fullKeys","type","ret","isNaN","is","octets","len","_loop","hasOwn","entry","every","_ret","getTime","convertValueToMultiEntryKeyDecoded","convertValueToKeyRethrowingAndIfInvalid","extractKeyFromValueUsingKeyPath","keyPath","extractKeyValueDecodedFromValueUsingKeyPath","evaluateKeyPathOnValue","evaluateKeyPathOnValueToDecodedValue","r","failure","some","identifiers","idntfr","lastModified","injectKeyIntoValueUsingKeyPath","last","identifier","hop","checkKeyCouldBeInjectedIntoValue","_iterator3","_step3","isKeyInRange","range","checkCached","lowerMatch","lower","upperMatch","upper","encodedKey","__lowerCached","__upperCached","lowerOpen","upperOpen","isMultiEntryMatch","encodedEntry","findMultiEntryMatches","keyEntry","matches","_iterator4","_step4","nested","convertKeyToValue","index","roundTrip","MAX_ALLOWED_CURRENT_NUMBER","getCurrentNumber","tx","store","func","sqlFailCb","executeSql","__currentName","data","rows","currNum","assignCurrentNumber","successCb","failCb","sql","sqlValues","log","setCurrentNumber","generateKeyForStore","cb","possiblyUpdateKeyGenerator","cn","floor","min","useNewKeyForAutoInc"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,IAAMA,GAAG,GAAG,EAAE,CAAA;EAEd,IAAMC,GAAG,8BAAgC,EAAG,CAAA;;EAE5C;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACC;EACG;EACA,OAAO;EAAE;;EAET;EACA;EACA,wBAAwB;EAExB;EACA;EACA;EACA;EACA,UAAU;EAEV;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAAE;;EAElB;EACA;EACA,aAAa;EAEb;EACA;EACA,uBAAuB;EAEvB;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA,mBAAmB;EAEnB;EACA;EACA;EACA;EACA,aAAa;EAEb;EACA,eAAe;EAAE;EACjB;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,KAAK;EAEL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA;EACA;EACA,kBAAkB;EAElB;EACA;EACA;;EAEA;EACA,IAAI;EAEJ;EACA;EACA;EACA;EACA,kBAAkB;EAClB;EACA;EACA;EACA;EACA,sBAAsB;EAEtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA,oBAAoB;EACpB;EACA,sBAAsB;EAEtB;EACA;EACA;EACA,6BAA6B;EAC7B;EACA,yBAAyB;EAEzB;EACA;EACA,2BAA2B;EAE3B;EACA;EACA,oBAAoB;EACpB;EACA,CACI,gBAAgB;EAChB;EACR;EACA;EACA;EACA;EACQ,UAACC,GAAG,EAAK;IACL,IAAI,CAAE,gVAAgD,CAAEC,IAAI,sBACjCD,GAC3B,CAAC,EAAE;EACC,IAAA,MAAM,IAAIE,SAAS,CACf,8DAA8D,GAC9D,2CACJ,CAAC,CAAA;EACL,GAAA;EACJ,CAAC,CACJ;EAED;EACA;EACA;EACA,qBAAqB,EACrB,kBAAkB,EAClB,qBAAqB;EAErB;EACA,gBAAgB;EAAE;EAClB,UAAU;EAAE;EACZ,YAAY;EAAE;;EAEd,eAAe,CAClB,CAAEC,OAAO,CAAC,UAACC,IAAI,EAAK;EACjB;EACA,EAAA,IAAIC,SAAS,CAAA;EACb,EAAA,IAAIC,KAAK,CAACC,OAAO,CAACH,IAAI,CAAC,EAAE;MAAA,IAAAI,KAAA,GACDJ,IAAI,CAAA;EAAA,IAAA,IAAAK,MAAA,GAAAC,cAAA,CAAAF,KAAA,EAAA,C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A;EACA;EACA;IACA,IAAI,OAAOtJ,GAAG,KAAK,QAAQ,IAAIA,GAAG,GAAG,CAAC,EAAE;EAAE;EACtC;EACA;EACA;EACA6J,IAAAA,SAAS,EAAE,CAAA;EACf,GAAC,MAAM;EACH;EACA;EACAX,IAAAA,gBAAgB,CAACC,EAAE,EAAEC,KAAK,EAAE,UAAUkB,EAAE,EAAE;EACtC,MAAA,IAAMjP,KAAK,GAAGgF,IAAI,CAACkK,KAAK,CACpBlK,IAAI,CAACmK,GAAG,CAACxK,GAAG,EAAEiJ,0BAA0B,CAC5C,CAAC,CAAA;EACD,MAAA,IAAMwB,mBAAmB,GAAGpP,KAAK,IAAIiP,EAAE,CAAA;EACvC,MAAA,IAAIG,mBAAmB,EAAE;EACrBP,QAAAA,gBAAgB,CAACf,EAAE,EAAEC,KAAK,EAAE/N,KAAK,EAAE,YAAY;EAC3CwO,UAAAA,SAAS,CAACS,EAAE,CAAC,CAAC;WACjB,EAAEhB,SAAS,CAAC,CAAA;EACjB,OAAC,MAAM;EAAE;EACLO,QAAAA,SAAS,EAAE,CAAA;EACf,OAAA;OACH,EAAEP,SAAS,CAAC,CAAA;EACjB,GAAA;EACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"indexeddbshim-Key.js","sources":["../src/CFG.js","../src/DOMException.js","../src/util.js","../src/cmp.js","../src/Key.js"],"sourcesContent":["/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n/**\n * @typedef {T[keyof T]} ValueOf\n * @template T\n */\n/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n\n/**\n * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi\n */\n\n/**\n * @typedef {{\n * DEBUG: boolean,\n * cacheDatabaseInstances: boolean,\n * autoName: boolean,\n * fullIDLSupport: boolean,\n * checkOrigin: boolean,\n * cursorPreloadPackSize: number,\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string,\n * registerSCA: (\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset,\n * avoidAutoShim: boolean,\n * win: {\n * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default\n * },\n * DEFAULT_DB_SIZE: number,\n * useSQLiteIndexes: boolean,\n * fs: FSApi,\n * addNonIDBGlobals: boolean,\n * replaceNonIDBGlobals: boolean,\n * escapeDatabaseName: (name: string) => string,\n * unescapeDatabaseName: (name: string) => string,\n * databaseCharacterEscapeList: string|false,\n * databaseNameLengthLimit: number|false,\n * escapeNFDForDatabaseNames: boolean,\n * addSQLiteExtension: boolean,\n * memoryDatabase: string,\n * deleteDatabaseFiles: boolean,\n * databaseBasePath: string,\n * sysDatabaseBasePath: string,\n * sqlBusyTimeout: number,\n * sqlTrace: () => void,\n * sqlProfile: () => void,\n * createIndexes: boolean\n * }} ConfigValues\n */\n\n/**\n * @typedef {ValueOf} ConfigValue\n */\n\n/** @type {{[key: string]: ConfigValue}} */\nconst map = {};\n\nconst CFG = /** @type {ConfigValues} */ ({});\n\n/**\n * @typedef {keyof ConfigValues} KeyofConfigValues\n */\n\n/**\n * @typedef {KeyofConfigValues[]} Config\n */\n\n/** @type {Config} */\n([\n // Boolean for verbose reporting\n 'DEBUG', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean (effectively defaults to true) on whether to cache WebSQL\n // `openDatabase` instances\n 'cacheDatabaseInstances',\n\n // Boolean on whether to auto-name databases (based on an\n // auto-increment) when the empty string is supplied; useful with\n // `memoryDatabase`; defaults to `false` which means the empty string\n // will be used as the (valid) database name\n 'autoName',\n\n // Determines whether the slow-performing `Object.setPrototypeOf`\n // calls required for full WebIDL compliance will be used. Probably\n // only needed for testing or environments where full introspection\n // on class relationships is required; see\n // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean on whether to perform origin checks in `IDBFactory` methods\n // Effectively defaults to `true` (must be set to `false` to cancel checks)\n 'checkOrigin',\n\n // Used by `IDBCursor` continue methods for number of records to cache;\n // Defaults to 100\n 'cursorPreloadPackSize',\n\n // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);\n // or just use the Unicode builds which invoke this method\n // automatically using the large, fully spec-compliant, regular\n // expression strings of `src/UnicodeIdentifiers.js`)\n // In the non-Unicode builds, defaults to /[$A-Z_a-z]/\n 'UnicodeIDStart',\n // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/\n 'UnicodeIDContinue',\n\n // Used by SCA.js for optional restructuring of typeson-registry\n // Structured Cloning Algorithm; should only be needed for ensuring data\n // created in 3.* versions of IndexedDBShim continue to work; see the\n // library `typeson-registry-sca-reverter` to get a function to do this\n 'registerSCA',\n\n // BROWSER-SPECIFIC CONFIG\n 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is\n // missing or poor support is known (non-Chrome Android or\n // non-Safari iOS9), the shim will be auto-applied without\n // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing\n // the shim for such cases.\n\n // -----------SQL CONFIG----------\n // Object (`window` in the browser) on which there may be an\n // `openDatabase` method (if any) for WebSQL. (The browser\n // throws if attempting to call `openDatabase` without the window\n // so this is why the config doesn't just allow the function.)\n // Defaults to `window` or `self` in browser builds or\n // a singleton object with the `openDatabase` method set to\n // the \"websql\" package in Node.\n 'win',\n\n // For internal `openDatabase` calls made by `IDBFactory` methods;\n // per the WebSQL spec, \"User agents are expected to use the display name\n // and the estimated database size to optimize the user experience.\n // For example, a user agent could use the estimated size to suggest an\n // initial quota to the user. This allows a site that is aware that it\n // will try to use hundreds of megabytes to declare this upfront, instead\n // of the user agent prompting the user for permission to increase the\n // quota every five megabytes.\"\n // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari\n 'DEFAULT_DB_SIZE',\n // Whether to create indexes on SQLite tables (and also whether to try\n // dropping)\n // Effectively defaults to `false` (ignored unless `true`)\n 'useSQLiteIndexes',\n\n // NODE-IMPINGING SETTINGS (created for sake of limitations in Node\n // or desktop file system implementation but applied by default in\n // browser for parity)\n\n // File system module with `unlink` to remove deleted database files\n 'fs',\n\n // Used when setting global shims to determine whether to try to add\n // other globals shimmed by the library (`ShimDOMException`,\n // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'addNonIDBGlobals',\n // Used when setting global shims to determine whether to try to overwrite\n // other globals shimmed by the library (`DOMException`, `DOMStringList`,\n // `Event`, `CustomEvent`, `EventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'replaceNonIDBGlobals',\n\n // Overcoming limitations with node-sqlite3/storing database name on\n // file systems\n // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n // Defaults to prefixing database with `D_`, escaping\n // `databaseCharacterEscapeList`, escaping NUL, and\n // escaping upper case letters, as well as enforcing\n // `databaseNameLengthLimit`\n 'escapeDatabaseName',\n // Not used internally; usable as a convenience method\n 'unescapeDatabaseName',\n\n // Defaults to global regex representing the following\n // (characters nevertheless commonly reserved in modern,\n // Unicode-supporting systems): 0x00-0x1F 0x7F \" * / : < > ? \\ |\n 'databaseCharacterEscapeList',\n // Defaults to 254 (shortest typical modern file length limit)\n 'databaseNameLengthLimit',\n\n // Boolean defaulting to true on whether to escape NFD-escaping\n // characters to avoid clashes on MacOS which performs NFD on files\n 'escapeNFDForDatabaseNames',\n\n // Boolean on whether to add the `.sqlite` extension to file names;\n // defaults to `true`\n 'addSQLiteExtension',\n // Various types of in-memory databases that can auto-delete\n [\n 'memoryDatabase',\n /**\n * @param {string} val\n * @throws {TypeError}\n * @returns {void}\n */\n (val) => {\n if (!(/^(?::memory:|file::memory:(\\?[^#]*)?(#.*)?)?$/u).test(\n /** @type {string} */ (val)\n )) {\n throw new TypeError(\n '`memoryDatabase` must be the empty string, \":memory:\", or a ' +\n '\"file::memory:[?queryString][#hash] URL\".'\n );\n }\n }\n ],\n\n // NODE-SPECIFIC CONFIG\n // Boolean on whether to delete the database file itself after\n // `deleteDatabase`; defaults to `true` as the database will be empty\n 'deleteDatabaseFiles',\n 'databaseBasePath',\n 'sysDatabaseBasePath',\n\n // NODE-SPECIFIC WEBSQL CONFIG\n 'sqlBusyTimeout', // Defaults to 1000\n 'sqlTrace', // Callback not used by default\n 'sqlProfile', // Callback not used by default\n\n 'createIndexes'\n]).forEach((prop) => {\n /** @type {(val: any) => void} */\n let validator;\n if (Array.isArray(prop)) {\n [prop, validator] = prop;\n }\n Object.defineProperty(CFG, prop, {\n get () {\n return map[prop];\n },\n set (val) {\n if (validator) {\n validator(val);\n }\n map[prop] = val;\n }\n });\n});\n\nexport default CFG;\n","import CFG from './CFG.js';\n\n/**\n * Creates a native DOMException, for browsers that support it.\n * @param {string} name\n * @param {string} message\n * @returns {DOMException}\n */\nfunction createNativeDOMException (name, message) {\n // @ts-expect-error It's ok\n return new DOMException.prototype.constructor(\n message,\n name || 'DOMException'\n );\n}\n\n// From web-platform-tests testharness.js name_code_map (though not in new spec)\n\n/**\n * @typedef {\"IndexSizeError\"|\"HierarchyRequestError\"|\"WrongDocumentError\"|\n * \"InvalidCharacterError\"|\"NoModificationAllowedError\"|\"NotFoundError\"|\n * \"NotSupportedError\"|\"InUseAttributeError\"|\"InvalidStateError\"|\n * \"SyntaxError\"|\"InvalidModificationError\"|\"NamespaceError\"|\n * \"InvalidAccessError\"|\"TypeMismatchError\"|\"SecurityError\"|\n * \"NetworkError\"|\"AbortError\"|\"URLMismatchError\"|\"QuotaExceededError\"|\n * \"TimeoutError\"|\"InvalidNodeTypeError\"|\"DataCloneError\"|\"EncodingError\"|\n * \"NotReadableError\"|\"UnknownError\"|\"ConstraintError\"|\"DataError\"|\n * \"TransactionInactiveError\"|\"ReadOnlyError\"|\"VersionError\"|\n * \"OperationError\"|\"NotAllowedError\"} Code\n */\n\nconst codes = {\n IndexSizeError: 1,\n HierarchyRequestError: 3,\n WrongDocumentError: 4,\n InvalidCharacterError: 5,\n NoModificationAllowedError: 7,\n NotFoundError: 8,\n NotSupportedError: 9,\n InUseAttributeError: 10,\n InvalidStateError: 11,\n SyntaxError: 12,\n InvalidModificationError: 13,\n NamespaceError: 14,\n InvalidAccessError: 15,\n TypeMismatchError: 17,\n SecurityError: 18,\n NetworkError: 19,\n AbortError: 20,\n URLMismatchError: 21,\n QuotaExceededError: 22,\n TimeoutError: 23,\n InvalidNodeTypeError: 24,\n DataCloneError: 25,\n\n EncodingError: 0,\n NotReadableError: 0,\n UnknownError: 0,\n ConstraintError: 0,\n DataError: 0,\n TransactionInactiveError: 0,\n ReadOnlyError: 0,\n VersionError: 0,\n OperationError: 0,\n NotAllowedError: 0\n};\n\n/**\n * @typedef {\"INDEX_SIZE_ERR\"|\"DOMSTRING_SIZE_ERR\"|\"HIERARCHY_REQUEST_ERR\"|\n * \"WRONG_DOCUMENT_ERR\"|\"INVALID_CHARACTER_ERR\"|\"NO_DATA_ALLOWED_ERR\"|\n * \"NO_MODIFICATION_ALLOWED_ERR\"|\"NOT_FOUND_ERR\"|\"NOT_SUPPORTED_ERR\"|\n * \"INUSE_ATTRIBUTE_ERR\"|\"INVALID_STATE_ERR\"|\"SYNTAX_ERR\"|\n * \"INVALID_MODIFICATION_ERR\"|\"NAMESPACE_ERR\"|\"INVALID_ACCESS_ERR\"|\n * \"VALIDATION_ERR\"|\"TYPE_MISMATCH_ERR\"|\"SECURITY_ERR\"|\"NETWORK_ERR\"|\n * \"ABORT_ERR\"|\"URL_MISMATCH_ERR\"|\"QUOTA_EXCEEDED_ERR\"|\"TIMEOUT_ERR\"|\n * \"INVALID_NODE_TYPE_ERR\"|\"DATA_CLONE_ERR\"} LegacyCode\n */\n\nconst legacyCodes = {\n INDEX_SIZE_ERR: 1,\n DOMSTRING_SIZE_ERR: 2,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n INVALID_CHARACTER_ERR: 5,\n NO_DATA_ALLOWED_ERR: 6,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INUSE_ATTRIBUTE_ERR: 10,\n INVALID_STATE_ERR: 11,\n SYNTAX_ERR: 12,\n INVALID_MODIFICATION_ERR: 13,\n NAMESPACE_ERR: 14,\n INVALID_ACCESS_ERR: 15,\n VALIDATION_ERR: 16,\n TYPE_MISMATCH_ERR: 17,\n SECURITY_ERR: 18,\n NETWORK_ERR: 19,\n ABORT_ERR: 20,\n URL_MISMATCH_ERR: 21,\n QUOTA_EXCEEDED_ERR: 22,\n TIMEOUT_ERR: 23,\n INVALID_NODE_TYPE_ERR: 24,\n DATA_CLONE_ERR: 25\n};\n\n/**\n *\n * @returns {typeof DOMException}\n */\nfunction createNonNativeDOMExceptionClass () {\n /**\n * @param {string|undefined} message\n * @param {Code|LegacyCode} name\n * @returns {void}\n */\n function DOMException (message, name) {\n // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message\n this[Symbol.toStringTag] = 'DOMException';\n this._code = name in codes\n ? codes[/** @type {Code} */ (name)]\n : (legacyCodes[/** @type {LegacyCode} */ (name)] || 0);\n this._name = name || 'Error';\n // We avoid `String()` in this next line as it converts Symbols\n this._message = message === undefined ? '' : ('' + message); // eslint-disable-line no-implicit-coercion -- Don't convert symbols\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._code\n });\n if (name !== undefined) {\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._name\n });\n }\n if (message !== undefined) {\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: this._message\n });\n }\n }\n\n // Necessary for W3C tests which complains if `DOMException` has properties on its \"own\" prototype\n\n // class DummyDOMException extends Error {}; // Sometimes causing problems in Node\n /* eslint-disable func-name-matching -- See above */\n /**\n * @class\n */\n const DummyDOMException = function DOMException () { /* */ };\n /* eslint-enable func-name-matching -- See above */\n DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing\n /** @type {const} */ (['name', 'message']).forEach((prop) => {\n Object.defineProperty(DummyDOMException.prototype, prop, {\n enumerable: true,\n /**\n * @this {DOMException}\n * @returns {string}\n */\n get () {\n if (!(this instanceof DOMException ||\n // @ts-expect-error Just checking\n this instanceof DummyDOMException ||\n // @ts-expect-error Just checking\n this instanceof Error)) {\n throw new TypeError('Illegal invocation');\n }\n return this[prop === 'name' ? '_name' : '_message'];\n }\n });\n });\n // DOMException uses the same `toString` as `Error`\n Object.defineProperty(DummyDOMException.prototype, 'code', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n // @ts-expect-error It's ok\n DOMException.prototype = new DummyDOMException();\n\n DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';\n Object.defineProperty(DOMException, 'prototype', {\n writable: false\n });\n\n const keys = Object.keys(codes);\n\n /** @type {(keyof codes)[]} */ (keys).forEach(\n (codeName) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n }\n );\n /** @type {(keyof legacyCodes)[]} */ (Object.keys(legacyCodes)).forEach((\n codeName\n ) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n });\n Object.defineProperty(DOMException.prototype, 'constructor', {\n writable: true,\n configurable: true,\n enumerable: false,\n value: DOMException\n });\n\n // @ts-expect-error We don't need all its properties\n return DOMException;\n}\n\nconst ShimNonNativeDOMException = createNonNativeDOMExceptionClass();\n\n/**\n * Creates a generic Error object.\n * @param {string} name\n * @param {string} message\n * @returns {Error}\n */\nfunction createNonNativeDOMException (name, message) {\n return new ShimNonNativeDOMException(message, name);\n}\n\n/**\n * @typedef {{\n * message: string|DOMString\n * }} ErrorLike\n */\n\n/**\n * Logs detailed error information to the console.\n * @param {string} name\n * @param {string} message\n * @param {string|ErrorLike|boolean|null} [error]\n * @returns {void}\n */\nfunction logError (name, message, error) {\n if (CFG.DEBUG) {\n const msg = error && typeof error === 'object' && error.message\n ? error.message\n : /** @type {string} */ (error);\n\n const method = typeof (console.error) === 'function' ? 'error' : 'log';\n console[method](name + ': ' + message + '. ' + (msg || ''));\n if (console.trace) { console.trace(); }\n }\n}\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @param {ArbitraryValue} obj\n * @returns {boolean}\n */\nfunction isErrorOrDOMErrorOrDOMException (obj) {\n return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser\n typeof obj.name === 'string';\n}\n\n/**\n * Finds the error argument. This is useful because some WebSQL callbacks\n * pass the error as the first argument, and some pass it as the second\n * argument.\n * @param {(Error|{message?: string, name?: string}|any)[]} args\n * @returns {Error|DOMException|undefined}\n */\nfunction findError (args) {\n let err;\n if (args) {\n if (args.length === 1) {\n return args[0];\n }\n for (const arg of args) {\n if (isErrorOrDOMErrorOrDOMException(arg)) {\n return arg;\n }\n if (arg && typeof arg.message === 'string') {\n err = arg;\n }\n }\n }\n return err;\n}\n\n/**\n *\n * @param {SQLError} webSQLErr\n * @returns {(DOMException|Error) & {\n * sqlError: SQLError\n * }}\n */\nfunction webSQLErrback (webSQLErr) {\n let name, message;\n switch (webSQLErr.code) {\n case 4: { // SQLError.QUOTA_ERR\n name = 'QuotaExceededError';\n message = 'The operation failed because there was not enough ' +\n 'remaining storage space, or the storage quota was reached ' +\n 'and the user declined to give more space to the database.';\n break;\n }\n /*\n // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`?\n case 7: { // SQLError.TIMEOUT_ERR\n // All transaction errors abort later, so no need to mark inactive\n name = 'TransactionInactiveError';\n message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).';\n break;\n }\n */\n default: {\n name = 'UnknownError';\n message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.';\n break;\n }\n }\n message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')';\n const err =\n /**\n * @type {(Error | DOMException) & {\n * sqlError: SQLError\n * }}\n */\n (createDOMException(name, message));\n err.sqlError = webSQLErr;\n return err;\n}\n\nlet test, useNativeDOMException = false;\n\n// Test whether we can use the browser's native DOMException class\ntry {\n test = createNativeDOMException('test name', 'test message');\n if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {\n // Native DOMException works as expected\n useNativeDOMException = true;\n }\n// eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n} catch (err) {}\n\nconst createDOMException = useNativeDOMException\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n ? /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {DOMException}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNativeDOMException(name, message);\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n : /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {Error}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNonNativeDOMException(name, message);\n };\n\nconst ShimDOMException = useNativeDOMException\n ? DOMException\n : ShimNonNativeDOMException;\n\nexport {logError, findError, ShimDOMException, createDOMException, webSQLErrback};\n","/* eslint-disable new-cap -- ToString is how it is defined */\nimport CFG from './CFG.js';\nimport expandsOnNFD from './unicode-regex.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeUnmatchedSurrogates (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return arg.replaceAll(\n /([\\uD800-\\uDBFF])(?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])/gu,\n function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {\n // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577\n // but Chrome having problems\n if (unmatchedHighSurrogate) {\n return '^2' + unmatchedHighSurrogate.codePointAt()\n .toString(16).padStart(4, '0');\n }\n return (precedingLow || '') + '^3' +\n unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');\n }\n );\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeNameForSQLiteIdentifier (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return '_' + // Prevent empty string\n escapeUnmatchedSurrogates(\n arg.replaceAll('^', '^^') // Escape our escape\n // http://www.sqlite.org/src/tktview?name=57c971fc74\n .replaceAll('\\0', '^0')\n // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names\n // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577\n // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working\n .replaceAll(/([A-Z])/gu, '^$1')\n );\n}\n\n/**\n * The escaping of unmatched surrogates was needed by Chrome but not Node.\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeSQLiteStatement (arg) {\n return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\\0', '^0'));\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeSQLiteResponse (arg) {\n return unescapeUnmatchedSurrogates(arg)\n .replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n })\n .replaceAll('^^', '^');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlEscape (arg) {\n // https://www.sqlite.org/lang_keywords.html\n // http://stackoverflow.com/a/6701665/271577\n // There is no need to escape ', `, or [], as\n // we should always be within double quotes\n // NUL should have already been stripped\n return arg.replaceAll('\"', '\"\"');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlQuote (arg) {\n return '\"' + sqlEscape(arg) + '\"';\n}\n\n/**\n * @param {string} db\n * @throws {Error}\n * @returns {string}\n */\nfunction escapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.escapeDatabaseName) {\n // We at least ensure NUL is escaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), escaping casing (including Unicode?),\n // and escaping special characters depending on file system\n return CFG.escapeDatabaseName(escapeSQLiteStatement(db));\n }\n db = 'D' + escapeNameForSQLiteIdentifier(db);\n if (CFG.escapeNFDForDatabaseNames !== false) {\n // ES6 copying of regex with different flags\n db = db.replaceAll(new RegExp(expandsOnNFD, 'gu'), function (expandable) {\n return '^4' + /** @type {Integer} */ (expandable.codePointAt(0)).toString(16).padStart(6, '0');\n });\n }\n if (CFG.databaseCharacterEscapeList !== false) {\n db = db.replace(\n (CFG.databaseCharacterEscapeList\n ? new RegExp(CFG.databaseCharacterEscapeList, 'gu')\n : /[\\u0000-\\u001F\\u007F\"*/:<>?\\\\|]/gu), // eslint-disable-line no-control-regex -- Controls needed\n function (n0) {\n // eslint-disable-next-line unicorn/prefer-code-point -- Switch to `codePointAt`?\n return '^1' + n0.charCodeAt(0).toString(16).padStart(2, '0');\n }\n );\n }\n if (CFG.databaseNameLengthLimit !== false &&\n db.length >= ((CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0))) {\n throw new Error(\n 'Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' +\n db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'\n );\n }\n return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?)\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeUnmatchedSurrogates (arg) {\n return arg\n .replaceAll(/(\\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(lowSurr, 16))\n : _;\n }).replaceAll(/(\\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(highSurr, 16))\n : _;\n });\n}\n\n/**\n * Not in use internally but supplied for convenience.\n * @param {string} db\n * @returns {string}\n */\nfunction unescapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.unescapeDatabaseName) {\n // We at least ensure NUL is unescaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), unescaping casing (including Unicode?),\n // and unescaping special characters depending on file system\n return CFG.unescapeDatabaseName(unescapeSQLiteResponse(db));\n }\n\n return unescapeUnmatchedSurrogates(\n db.slice(2) // D_\n // CFG.databaseCharacterEscapeList\n .replaceAll(/(\\^+)1([0-9a-f]{2})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n // CFG.escapeNFDForDatabaseNames\n }).replaceAll(/(\\^+)4([0-9a-f]{6})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n })\n // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above)\n ).replaceAll(/(\\^+)([A-Z])/gu, (_, esc, upperCase) => {\n return esc.length % 2\n ? esc.slice(1) + upperCase\n : _;\n }).replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n }).replaceAll('^^', '^');\n}\n\n/**\n * @param {string} store\n * @returns {string}\n */\nfunction escapeStoreNameForSQL (store) {\n return sqlQuote('S' + escapeNameForSQLiteIdentifier(store));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQL (index) {\n return sqlQuote('I' + escapeNameForSQLiteIdentifier(index));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQLKeyColumn (index) {\n return 'I' + escapeNameForSQLiteIdentifier(index);\n}\n\n/**\n * @todo Didn't need to escape `%`. Do we still need this escape?\n * @param {string} str\n * @returns {string}\n */\nfunction sqlLIKEEscape (str) {\n // https://www.sqlite.org/lang_expr.html#like\n return str.replaceAll('^', '^^');\n}\n\n/**\n * @typedef {Function} AnyClass\n */\n\n// Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?)\n/**\n *\n * @param {AnyValue} obj\n * @param {AnyClass} Clss\n * @returns {boolean}\n */\nfunction instanceOf (obj, Clss) {\n return Clss[Symbol.hasInstance](obj);\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {obj is object}\n */\nfunction isObj (obj) {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isDate (obj) {\n return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isBlob (obj) {\n return isObj(obj) && 'size' in obj && typeof obj.size === 'number' &&\n 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isRegExp (obj) {\n return isObj(obj) && 'flags' in obj && typeof obj.flags === 'string' &&\n 'exec' in obj && typeof obj.exec === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isFile (obj) {\n return isObj(obj) && 'name' in obj && typeof obj.name === 'string' &&\n 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isBinary (obj) {\n return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && (\n ('slice' in obj && typeof obj.slice === 'function') || // `TypedArray` (view on buffer) or `ArrayBuffer`\n ('getFloat64' in obj && typeof obj.getFloat64 === 'function') // `DataView` (view on buffer)\n );\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isIterable (obj) {\n return isObj(obj) && Symbol.iterator in obj &&\n typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n },\n // @ts-expect-error Deliberately errs\n set [prop] (val) {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineReadonlyOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object & {\n * [key: string]: any\n * }} obj\n * @param {string[]} listeners\n * @returns {void}\n */\nfunction defineListenerProperties (obj, listeners) {\n listeners = typeof listeners === 'string' ? [listeners] : listeners;\n listeners.forEach((listener) => {\n const o = {\n get [listener] () {\n return obj['__' + listener];\n },\n /**\n * @param {AnyValue} val\n * @returns {void}\n */\n set [listener] (val) {\n obj['__' + listener] = val;\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, listener)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners)\n Object.defineProperty(obj, listener, desc);\n });\n listeners.forEach((l) => {\n obj[l] = null;\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string|string[]} props\n * @param {null|{\n * [key: string]: any\n * }} getter\n * @returns {void}\n */\nfunction defineReadonlyProperties (obj, props, getter = null) {\n props = typeof props === 'string' ? [props] : props;\n props.forEach(function (prop) {\n let o;\n if (getter && prop in getter) {\n o = getter[prop];\n } else {\n Object.defineProperty(obj, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // We must resort to this to get \"get \" as\n // the function `name` for proper IDL\n o = {\n get [prop] () {\n return this['__' + prop];\n }\n };\n }\n\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {string} item\n * @returns {boolean}\n */\nfunction isIdentifier (item) {\n // For load-time and run-time performance, we don't provide the complete regular\n // expression for identifiers, but these can be passed in, using the expressions\n // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407\n // ID_Start (includes Other_ID_Start)\n const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]';\n // ID_Continue (includes Other_ID_Continue)\n const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]';\n const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])';\n const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\\u200C\\u200D])';\n return (new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u')).test(item);\n}\n\n/**\n *\n * @param {string|string[]} keyPathString\n * @returns {boolean}\n */\nfunction isValidKeyPathString (keyPathString) {\n return typeof keyPathString === 'string' &&\n (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every((pathComponent) => {\n return isIdentifier(pathComponent);\n }));\n}\n\n/**\n *\n * @param {string|string[]} keyPath\n * @returns {boolean}\n */\nfunction isValidKeyPath (keyPath) {\n return isValidKeyPathString(keyPath) || (\n Array.isArray(keyPath) && Boolean(keyPath.length) &&\n // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html\n // See also https://heycam.github.io/webidl/#idl-DOMString\n [...keyPath].every((pathComponent) => {\n return isValidKeyPathString(pathComponent);\n })\n );\n}\n\n/**\n * @param {number} number\n * @param {\"unsigned long long\"|\"unsigned long\"} type\n * @throws {Error|TypeError}\n * @returns {number}\n */\nfunction enforceRange (number, type) {\n number = Math.floor(Number(number));\n let max, min;\n switch (type) {\n case 'unsigned long long': {\n max = 0x1FFFFFFFFFFFFF; // 2^53 - 1\n min = 0;\n break;\n }\n case 'unsigned long': {\n max = 0xFFFFFFFF; // 2^32 - 1\n min = 0;\n break;\n }\n default:\n throw new Error('Unrecognized type supplied to enforceRange');\n }\n if (!Number.isFinite(number) ||\n number > max ||\n number < min) {\n throw new TypeError('Invalid range: ' + number);\n }\n return number;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {AnyValue} v\n * @param {boolean} [treatNullAs]\n * @returns {string}\n */\nfunction convertToDOMString (v, treatNullAs) {\n return v === null && treatNullAs ? '' : ToString(v);\n}\n\n/**\n * @param {AnyValue} o\n * @returns {string}\n */\nfunction ToString (o) { // Todo: See `es-abstract/es7`\n // `String()` will not throw with Symbols\n return '' + o; // eslint-disable-line no-implicit-coercion -- Need to throw with symbols\n}\n\n/**\n *\n * @param {AnyValue} val\n * @returns {string|string[]}\n */\nfunction convertToSequenceDOMString (val) {\n // Per , converting to a sequence works with iterables\n if (isIterable(val)) { // We don't want conversion to array to convert primitives\n // Per , converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring\n return [...val].map((item) => {\n return ToString(item);\n });\n }\n return ToString(val);\n}\n\n/**\n * @param {AnyValue} v\n * @returns {v is null|undefined}\n */\nfunction isNullish (v) {\n return v === null || v === undefined;\n}\n\nexport {escapeSQLiteStatement, unescapeSQLiteResponse,\n escapeDatabaseNameForSQLAndFiles, unescapeDatabaseNameForSQLAndFiles,\n escapeStoreNameForSQL, escapeIndexNameForSQL, escapeIndexNameForSQLKeyColumn,\n sqlLIKEEscape, sqlQuote,\n instanceOf,\n isObj, isDate, isBlob, isRegExp, isFile, isBinary, isIterable,\n defineOuterInterface, defineReadonlyOuterInterface,\n defineListenerProperties, defineReadonlyProperties,\n isValidKeyPath, enforceRange,\n convertToDOMString, convertToSequenceDOMString,\n isNullish};\n","import CFG from './CFG.js';\nimport {encode as keyEncode, decode as keyDecode} from './Key.js';\n\n/**\n * Compares two keys.\n * @param {import('./Key.js').Key} first\n * @param {import('./Key.js').Key} second\n * @returns {0|1|-1}\n */\nfunction cmp (first, second) {\n const encodedKey1 = /** @type {string} */ (keyEncode(first));\n const encodedKey2 = /** @type {string} */ (keyEncode(second));\n const result = encodedKey1 > encodedKey2\n ? 1\n : encodedKey1 === encodedKey2 ? 0 : -1;\n\n if (CFG.DEBUG) {\n // verify that the keys encoded correctly\n let decodedKey1 = keyDecode(encodedKey1);\n let decodedKey2 = keyDecode(encodedKey2);\n if (typeof first === 'object') {\n first = JSON.stringify(first);\n decodedKey1 = JSON.stringify(decodedKey1);\n }\n if (typeof second === 'object') {\n second = JSON.stringify(second);\n decodedKey2 = JSON.stringify(decodedKey2);\n }\n\n // Encoding/decoding mismatches are usually due to a loss of\n // floating-point precision\n if (decodedKey1 !== first) {\n console.warn(\n first + ' was incorrectly encoded as ' + decodedKey1\n );\n }\n if (decodedKey2 !== second) {\n console.warn(\n second + ' was incorrectly encoded as ' + decodedKey2\n );\n }\n }\n\n return result;\n}\n\nexport default cmp;\n","import {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\nimport cmp from './cmp.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView\n */\n\n/**\n * @typedef {ArrayBufferView|ArrayBuffer} BufferSource\n */\n\n/**\n * @typedef {\"number\"|\"date\"|\"string\"|\"binary\"|\"array\"} KeyType\n */\n\n/**\n * @typedef {any} Value\n */\n\n/**\n * @typedef {any} Key\n * @todo Specify possible value more precisely\n */\n\n/**\n * @typedef {KeyPath[]} KeyPathArray\n */\n/**\n * @typedef {string|KeyPathArray} KeyPath\n */\n\n/**\n* @typedef {object} KeyValueObject\n* @property {KeyType|\"NaN\"|\"null\"|\"undefined\"|\"boolean\"|\"object\"|\"symbol\"|\n* \"function\"|\"bigint\"} type If not `KeyType`, indicates invalid value\n* @property {Value} [value]\n* @property {boolean} [invalid]\n* @property {string} [message]\n* @todo Specify acceptable `value` more precisely\n*/\n\n/**\n * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive\n */\n/**\n * @typedef {ValueType[]} ValueTypeArray\n */\n/**\n * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType\n */\n\n/**\n * Encodes the keys based on their types. This is required to maintain collations\n * We leave space for future keys.\n * @type {{[key: string]: Integer|string}}\n */\nconst keyTypeToEncodedChar = {\n invalid: 100,\n number: 200,\n date: 300,\n string: 400,\n binary: 500,\n array: 600\n};\nconst keyTypes = /** @type {(KeyType|\"invalid\")[]} */ (Object.keys(keyTypeToEncodedChar));\nkeyTypes.forEach((k) => {\n keyTypeToEncodedChar[k] = String.fromCodePoint(\n /** @type {number} */ (keyTypeToEncodedChar[k])\n );\n});\n\nconst encodedCharToKeyType = keyTypes.reduce((o, k) => {\n o[keyTypeToEncodedChar[k]] = k;\n return o;\n}, /** @type {{[key: string]: KeyType|\"invalid\"}} */ ({}));\n\n/**\n * The sign values for numbers, ordered from least to greatest.\n * - \"negativeInfinity\": Sorts below all other values.\n * - \"bigNegative\": Negative values less than or equal to negative one.\n * - \"smallNegative\": Negative values between negative one and zero, noninclusive.\n * - \"smallPositive\": Positive values between zero and one, including zero but not one.\n * - \"largePositive\": Positive values greater than or equal to one.\n * - \"positiveInfinity\": Sorts above all other values.\n */\nconst signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @type {{\n * [key: string]: {\n * encode: (param: any, inArray?: boolean) => string,\n * decode: (param: string, inArray?: boolean) => any\n * }\n * }}\n */\nconst types = {\n invalid: {\n /**\n * @returns {string}\n */\n encode () {\n return keyTypeToEncodedChar.invalid + '-';\n },\n /**\n * @returns {undefined}\n */\n decode () {\n return undefined;\n }\n },\n\n // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa\n // notation.\n //\n // sign: takes a value between zero and five, inclusive. Represents infinite cases\n // and the signs of both the exponent and the fractional part of the number.\n // exponent: padded to two base-32 digits, represented by the 32's compliment in the\n // \"smallPositive\" and \"bigNegative\" cases to ensure proper lexical sorting.\n // mantissa: also called the fractional part. Normed 11-digit base-32 representation.\n // Represented by the 32's compliment in the \"smallNegative\" and \"bigNegative\"\n // cases to ensure proper lexical sorting.\n number: {\n // The encode step checks for six numeric cases and generates 14-digit encoded\n // sign-exponent-mantissa strings.\n /**\n * @param {number} key\n * @returns {string}\n */\n encode (key) {\n let key32 = key === Number.MIN_VALUE\n // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some\n // Node (and Chrome) versions with `Number.MIN_VALUE` being treated\n // as 0\n // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring\n ? '0.' + '0'.repeat(214) + '2'\n : Math.abs(key).toString(32);\n // Get the index of the decimal.\n const decimalIndex = key32.indexOf('.');\n // Remove the decimal.\n key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;\n // Get the index of the first significant digit.\n const significantDigitIndex = key32.search(/[^0]/u);\n // Truncate leading zeros.\n key32 = key32.slice(significantDigitIndex);\n let sign, exponent, mantissa;\n\n // Finite cases:\n if (Number.isFinite(\n Number(key)\n )) {\n // Negative cases:\n if (key < 0) {\n // Negative exponent case:\n if (key > -1) {\n sign = signValues.indexOf('smallNegative');\n exponent = padBase32Exponent(significantDigitIndex);\n mantissa = flipBase32(padBase32Mantissa(key32));\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigNegative');\n exponent = flipBase32(padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n ));\n mantissa = flipBase32(padBase32Mantissa(key32));\n }\n // Non-negative cases:\n // Negative exponent case:\n } else if (key < 1) {\n sign = signValues.indexOf('smallPositive');\n exponent = flipBase32(padBase32Exponent(significantDigitIndex));\n mantissa = padBase32Mantissa(key32);\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigPositive');\n exponent = padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n );\n mantissa = padBase32Mantissa(key32);\n }\n // Infinite cases:\n } else {\n exponent = zeros(2);\n mantissa = zeros(11);\n sign = signValues.indexOf(\n key > 0 ? 'positiveInfinity' : 'negativeInfinity'\n );\n }\n\n return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;\n },\n // The decode step must interpret the sign, reflip values encoded as the 32's complements,\n // apply signs to the exponent and mantissa, do the base-32 power operation, and return\n // the original JavaScript number values.\n /**\n * @param {string} key\n * @returns {number}\n */\n decode (key) {\n const sign = Number(key.slice(2, 3));\n let exponent = key.slice(3, 5);\n let mantissa = key.slice(5, 16);\n\n switch (signValues[sign]) {\n case 'negativeInfinity':\n return Number.NEGATIVE_INFINITY;\n case 'positiveInfinity':\n return Number.POSITIVE_INFINITY;\n case 'bigPositive':\n return pow32(mantissa, exponent);\n case 'smallPositive':\n exponent = negate(flipBase32(exponent));\n return pow32(mantissa, exponent);\n case 'smallNegative':\n exponent = negate(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n case 'bigNegative':\n exponent = flipBase32(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n default:\n throw new Error('Invalid number.');\n }\n }\n },\n\n // Strings are encoded as JSON strings (with quotes and unicode characters escaped).\n //\n // If the strings are in an array, then some extra encoding is done to make sorting work correctly:\n // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly\n // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.\n // To do this, each character of the string is prepended with a dash (\"-\"), and a space is added to the end of the string.\n // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,\n // the indexes of each string's characters line up with each other.\n string: {\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n encode (key, inArray) {\n if (inArray) {\n // prepend each character with a dash, and append a space to the end\n key = key.replaceAll(/(.)/gu, '-$1') + ' ';\n }\n return keyTypeToEncodedChar.string + '-' + key;\n },\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n decode (key, inArray) {\n key = key.slice(2);\n if (inArray) {\n // remove the space at the end, and the dash before each character\n key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');\n }\n return key;\n }\n },\n\n // Arrays are encoded as JSON strings.\n // An extra, value is added to each array during encoding to make\n // empty arrays sort correctly.\n array: {\n /**\n * @param {ValueTypeArray} key\n * @returns {string}\n */\n encode (key) {\n const encoded = [];\n for (const [i, item] of key.entries()) {\n const encodedItem = encode(item, true); // encode the array item\n encoded[i] = encodedItem;\n }\n encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly\n return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);\n },\n /**\n * @param {string} key\n * @returns {ValueTypeArray}\n */\n decode (key) {\n const decoded = JSON.parse(key.slice(2));\n decoded.pop(); // remove the extra item\n for (let i = 0; i < decoded.length; i++) {\n const item = decoded[i];\n const decodedItem = decode(item, true); // decode the item\n decoded[i] = decodedItem;\n }\n return decoded;\n }\n },\n\n // Dates are encoded as ISO 8601 strings, in UTC time zone.\n date: {\n /**\n * @param {Date} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.date + '-' + key.toJSON();\n },\n /**\n * @param {string} key\n * @returns {Date}\n */\n decode (key) {\n return new Date(key.slice(2));\n }\n },\n binary: {\n // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)\n /**\n * @param {BufferSource} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.binary + '-' + (key.byteLength\n ? [...getCopyBytesHeldByBufferSource(key)].map(\n (b) => String(b).padStart(3, '0')\n ) // e.g., '255,005,254,000,001,033'\n : '');\n },\n /**\n * @param {string} key\n * @returns {ArrayBuffer}\n */\n decode (key) {\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const k = key.slice(2);\n const arr = k.length ? k.split(',').map((s) => Number.parseInt(s)) : [];\n const buffer = new ArrayBuffer(arr.length);\n const uint8 = new Uint8Array(buffer);\n uint8.set(arr);\n return buffer;\n }\n }\n};\n\n/**\n * Return a padded base-32 exponent value.\n * @param {number} n\n * @returns {string}\n */\nfunction padBase32Exponent (n) {\n const exp = n.toString(32);\n return (exp.length === 1) ? '0' + exp : exp;\n}\n\n/**\n * Return a padded base-32 mantissa.\n * @param {string} s\n * @returns {string}\n */\nfunction padBase32Mantissa (s) {\n return (s + zeros(11)).slice(0, 11);\n}\n\n/**\n * Flips each digit of a base-32 encoded string.\n * @param {string} encoded\n * @returns {string}\n */\nfunction flipBase32 (encoded) {\n let flipped = '';\n for (const ch of encoded) {\n flipped += (31 - Number.parseInt(ch, 32)).toString(32);\n }\n return flipped;\n}\n\n/**\n * Base-32 power function.\n * RESEARCH: This function does not precisely decode floats because it performs\n * floating point arithmetic to recover values. But can the original values be\n * recovered exactly?\n * Someone may have already figured out a good way to store JavaScript floats as\n * binary strings and convert back. Barring a better method, however, one route\n * may be to generate decimal strings that `parseFloat` decodes predictably.\n * @param {string} mantissa\n * @param {string} exponent\n * @returns {number}\n */\nfunction pow32 (mantissa, exponent) {\n const exp = Number.parseInt(exponent, 32);\n if (exp < 0) {\n return roundToPrecision(\n Number.parseInt(mantissa, 32) * (32 ** (exp - 10))\n );\n }\n if (exp < 11) {\n const whole = mantissa.slice(0, exp);\n const wholeNum = Number.parseInt(whole, 32);\n const fraction = mantissa.slice(exp);\n const fractionNum = Number.parseInt(fraction, 32) * (32 ** (exp - 11));\n return roundToPrecision(wholeNum + fractionNum);\n }\n const expansion = mantissa + zeros(exp - 11);\n return Number.parseInt(expansion, 32);\n}\n\n/**\n * @typedef {number} Float\n */\n\n/**\n * @param {Float} num\n * @param {Float} [precision]\n * @returns {Float}\n */\nfunction roundToPrecision (num, precision = 16) {\n return Number.parseFloat(num.toPrecision(precision));\n}\n\n/**\n * Returns a string of n zeros.\n * @param {number} n\n * @returns {string}\n */\nfunction zeros (n) {\n return '0'.repeat(n);\n}\n\n/**\n * Negates numeric strings.\n * @param {string} s\n * @returns {string}\n */\nfunction negate (s) {\n return '-' + s;\n}\n\n/**\n * @param {Key} key\n * @returns {KeyType|\"invalid\"}\n */\nfunction getKeyType (key) {\n if (Array.isArray(key)) { return 'array'; }\n if (util.isDate(key)) { return 'date'; }\n if (util.isBinary(key)) { return 'binary'; }\n const keyType = typeof key;\n return ['string', 'number'].includes(keyType)\n ? /** @type {\"string\"|\"number\"} */ (keyType)\n : 'invalid';\n}\n\n/**\n * Keys must be strings, numbers (besides `NaN`), Dates (if value is not\n * `NaN`), binary objects or Arrays.\n * @param {Value} input The key input\n * @param {Value[]|null|undefined} [seen] An array of already seen keys\n * @returns {KeyValueObject}\n */\nfunction convertValueToKey (input, seen) {\n return convertValueToKeyValueDecoded(input, seen, false, true);\n}\n\n/**\n* Currently not in use.\n* @param {Value} input\n* @returns {KeyValueObject}\n*/\nfunction convertValueToMultiEntryKey (input) {\n return convertValueToKeyValueDecoded(input, null, true, true);\n}\n\n/**\n *\n * @param {BufferSource} O\n * @throws {TypeError}\n * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n * @returns {Uint8Array}\n */\nfunction getCopyBytesHeldByBufferSource (O) {\n let offset = 0;\n let length = 0;\n if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot\n const arrayBuffer = O.buffer;\n if (arrayBuffer === undefined) {\n throw new TypeError(\n 'Could not copy the bytes held by a buffer source as the buffer was undefined.'\n );\n }\n offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)\n length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)\n } else {\n length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)\n }\n // const octets = new Uint8Array(input);\n // const octets = types.binary.decode(types.binary.encode(input));\n return new Uint8Array(\n // Should allow DataView\n /** @type {ArrayBuffer} */\n (('buffer' in O && O.buffer) || O),\n offset,\n length\n );\n}\n\n/**\n* Shortcut utility to avoid returning full keys from `convertValueToKey`\n* and subsequent need to process in calling code unless `fullKeys` is\n* set; may throw.\n* @param {Value} input\n* @param {Value[]|null} [seen]\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @throws {TypeError} See `getCopyBytesHeldByBufferSource`\n* @todo Document other allowable `input`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {\n seen = seen || [];\n if (seen.includes(input)) {\n return {\n type: 'array',\n invalid: true,\n message: 'An array key cannot be circular'\n };\n }\n const type = getKeyType(input);\n const ret = {type, value: input};\n switch (type) {\n case 'number': {\n if (Number.isNaN(input)) {\n // List as 'NaN' type for convenience of consumers in reporting errors\n return {type: 'NaN', invalid: true};\n }\n\n // https://github.com/w3c/IndexedDB/issues/375\n // https://github.com/w3c/IndexedDB/pull/386\n if (Object.is(input, -0)) {\n return {type, value: 0};\n }\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'string': {\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'binary': { // May throw (if detached)\n // Get a copy of the bytes held by the buffer source\n // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n const octets = getCopyBytesHeldByBufferSource(\n /** @type {BufferSource} */ (input)\n );\n return {type: 'binary', value: octets};\n } case 'array': { // May throw (from binary)\n const arr = /** @type {Array} */ (input);\n const len = arr.length;\n seen.push(input);\n\n /** @type {(KeyValueObject|Value)[]} */\n const keys = [];\n for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated\n if (!multiEntry && !Object.hasOwn(arr, i)) {\n return {type, invalid: true, message: 'Does not have own index property'};\n }\n try {\n const entry = arr[i];\n const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry\n if (key.invalid) {\n if (multiEntry) {\n continue;\n }\n return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};\n }\n if (!multiEntry ||\n (!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||\n (fullKeys && keys.every((k) => cmp(k, key) !== 0))\n ) {\n keys.push(fullKeys ? key : key.value);\n }\n } catch (err) {\n if (!multiEntry) {\n throw err;\n }\n }\n }\n return {type, value: keys};\n } case 'date': {\n const date = /** @type {Date} */ (input);\n if (!Number.isNaN(date.getTime())) {\n return fullKeys\n ? {type, value: date.getTime()}\n : {type, value: new Date(date.getTime())};\n }\n return {type, invalid: true, message: 'Not a valid date'};\n // Falls through\n } case 'invalid': default: {\n // Other `typeof` types which are not valid keys:\n // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'\n const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors\n return {type, invalid: true, message: 'Not a valid key; type ' + type};\n }\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [fullKeys]\n * @returns {KeyValueObject}\n * @todo Document other allowable `key`?\n */\nfunction convertValueToMultiEntryKeyDecoded (key, fullKeys) {\n return convertValueToKeyValueDecoded(key, null, true, fullKeys);\n}\n\n/**\n* An internal utility.\n* @param {Value} input\n* @param {Value[]|null|undefined} [seen]\n* @throws {DOMException} `DataError`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyRethrowingAndIfInvalid (input, seen) {\n const key = convertValueToKey(input, seen);\n if (key.invalid) {\n throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);\n }\n return key;\n}\n\n/**\n *\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} multiEntry\n * @returns {KeyValueObject|KeyPathEvaluateValue}\n * @todo Document other possible return?\n */\nfunction extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {\n return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);\n}\n/**\n* Not currently in use.\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} multiEntry\n* @returns {KeyPathEvaluateValue}\n*/\nfunction evaluateKeyPathOnValue (value, keyPath, multiEntry) {\n return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);\n}\n\n/**\n* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)\n* or `{invalid: true}` (e.g., `NaN`).\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @returns {KeyValueObject|KeyPathEvaluateValue}\n* @todo Document other possible return?\n*/\nfunction extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {\n const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);\n if (r.failure) {\n return r;\n }\n if (!multiEntry) {\n return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);\n }\n return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);\n}\n\n/**\n * Unused?\n * @typedef {object} KeyPathEvaluateFailure\n * @property {boolean} failure\n */\n\n/**\n * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray\n */\n\n/**\n * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue\n */\n\n/**\n * @typedef {object} KeyPathEvaluateValue\n * @property {KeyPathEvaluateValueValue} [value]\n * @property {boolean} [failure]\n */\n\n/**\n * Returns the value of an inline key based on a key path (wrapped in an\n * object with key `value`) or `{failure: true}`\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} [multiEntry]\n * @param {boolean} [fullKeys]\n * @returns {KeyPathEvaluateValue}\n */\nfunction evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {\n if (Array.isArray(keyPath)) {\n /** @type {KeyPathEvaluateValueValueArray} */\n const result = [];\n return keyPath.some((item) => {\n const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);\n if (key.failure) {\n return true;\n }\n result.push(key.value);\n return false;\n })\n ? {failure: true}\n : {value: result};\n }\n if (keyPath === '') {\n return {value};\n }\n const identifiers = keyPath.split('.');\n return identifiers.some((idntfr) => {\n if (idntfr === 'length' && (\n typeof value === 'string' || Array.isArray(value)\n )) {\n value = value.length;\n } else if (util.isBlob(value)) {\n switch (idntfr) {\n case 'size': case 'type':\n value = /** @type {Blob} */ (value)[idntfr];\n break;\n }\n } else if (util.isFile(value)) {\n switch (idntfr) {\n case 'name': case 'lastModified':\n value = /** @type {File} */ (value)[idntfr];\n break;\n case 'lastModifiedDate':\n value = new Date(/** @type {File} */ (value).lastModified);\n break;\n }\n } else if (!util.isObj(value) || !Object.hasOwn(value, idntfr)) {\n return true;\n } else {\n value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */ (\n value\n )[idntfr];\n return value === undefined;\n }\n return false;\n })\n ? {failure: true}\n : {value};\n}\n\n/**\n * Sets the inline key value.\n * @param {{[key: string]: AnyValue}} value\n * @param {Key} key\n * @param {string} keyPath\n * @returns {void}\n */\nfunction injectKeyIntoValueUsingKeyPath (value, key, keyPath) {\n const identifiers = keyPath.split('.');\n const last = identifiers.pop();\n identifiers.forEach((identifier) => {\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n value[identifier] = {};\n }\n value = value[identifier];\n });\n value[/** @type {string} */ (last)] = key; // key is already a `keyValue` in our processing so no need to convert\n}\n\n/**\n *\n * @param {Value} value\n * @param {string} keyPath\n * @see https://github.com/w3c/IndexedDB/pull/146\n * @returns {boolean}\n */\nfunction checkKeyCouldBeInjectedIntoValue (value, keyPath) {\n const identifiers = keyPath.split('.');\n identifiers.pop();\n for (const identifier of identifiers) {\n if (!util.isObj(value)) {\n return false;\n }\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n return true;\n }\n value = /** @type {{[key: string]: Value}} */ (value)[identifier];\n }\n return util.isObj(value);\n}\n\n/**\n *\n * @param {Key} key\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range\n * @param {boolean} [checkCached]\n * @returns {boolean}\n */\nfunction isKeyInRange (key, range, checkCached) {\n let lowerMatch = range.lower === undefined;\n let upperMatch = range.upper === undefined;\n const encodedKey = encode(key, true);\n const lower = checkCached ? range.__lowerCached : encode(range.lower, true);\n const upper = checkCached ? range.__upperCached : encode(range.upper, true);\n\n if (!lowerMatch && (\n (range.lowerOpen &&\n encodedKey !== null && lower !== null && encodedKey > lower) ||\n (!range.lowerOpen && (\n (!encodedKey && !lower) ||\n (encodedKey !== null && lower !== null && encodedKey >= lower))\n )\n )) {\n lowerMatch = true;\n }\n if (!upperMatch && (\n (range.upperOpen &&\n encodedKey !== null && upper !== null && encodedKey < upper) ||\n (!range.upperOpen && (\n (!encodedKey && !upper) ||\n (encodedKey !== null && upper !== null && encodedKey <= upper))\n )\n )) {\n upperMatch = true;\n }\n\n return lowerMatch && upperMatch;\n}\n\n/**\n * Determines whether an index entry matches a multi-entry key value.\n * @param {string} encodedEntry The entry value (already encoded)\n * @param {string} encodedKey The full index key (already encoded)\n * @returns {boolean}\n */\nfunction isMultiEntryMatch (encodedEntry, encodedKey) {\n const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];\n\n if (keyType === 'array') {\n return encodedKey.indexOf(encodedEntry) > 1;\n }\n return encodedKey === encodedEntry;\n}\n\n/**\n *\n * @param {Key} keyEntry\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range\n * @returns {Key[]}\n */\nfunction findMultiEntryMatches (keyEntry, range) {\n const matches = [];\n\n if (Array.isArray(keyEntry)) {\n for (let key of keyEntry) {\n if (Array.isArray(key)) {\n if (range && range.lower === range.upper) {\n continue;\n }\n if (key.length === 1) {\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n key = key[0];\n } else {\n const nested = findMultiEntryMatches(key, range);\n if (nested.length > 0) {\n matches.push(key);\n }\n continue;\n }\n }\n\n if (util.isNullish(range) || isKeyInRange(key, range, true)) {\n matches.push(key);\n }\n }\n } else if (util.isNullish(range) || isKeyInRange(keyEntry, range, true)) {\n matches.push(keyEntry);\n }\n return matches;\n}\n\n/**\n* Not currently in use but keeping for spec parity.\n* @param {Key} key\n* @throws {Error} Upon a \"bad key\"\n* @returns {ValueType}\n*/\nfunction convertKeyToValue (key) {\n const {type, value} = key;\n switch (type) {\n case 'number': case 'string': {\n return value;\n } case 'array': {\n const array = [];\n const len = value.length;\n let index = 0;\n while (index < len) {\n const entry = convertKeyToValue(value[index]);\n array[index] = entry;\n index++;\n }\n return array;\n } case 'date': {\n return new Date(value);\n } case 'binary': {\n const len = value.length;\n const buffer = new ArrayBuffer(len);\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);\n uint8.set(value);\n return buffer;\n } case 'invalid': default:\n throw new Error('Bad key');\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {string|null}\n */\nfunction encode (key, inArray) {\n // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation\n if (key === undefined) {\n return null;\n }\n // array, date, number, string, binary (should already have detected \"invalid\")\n return types[getKeyType(key)].encode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @throws {Error} Invalid number\n * @returns {undefined|ValueType}\n */\nfunction decode (key, inArray) {\n if (typeof key !== 'string') {\n return undefined;\n }\n return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {undefined|ValueType}\n */\nfunction roundTrip (key, inArray) {\n return decode(encode(key, inArray), inArray);\n}\n\nconst MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback CurrentNumberCallback\n * @param {Integer} cn The current number\n * @returns {void}\n */\n\n/**\n* @callback SQLFailureCallback\n* @param {DOMException|Error} exception\n* @returns {void}\n*/\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {CurrentNumberCallback} func\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction getCurrentNumber (tx, store, func, sqlFailCb) {\n tx.executeSql('SELECT \"currNum\" FROM __sys__ WHERE \"name\" = ?', [\n util.escapeSQLiteStatement(store.__currentName)\n ], function (tx, data) {\n if (data.rows.length !== 1) {\n func(1);\n } else {\n func(data.rows.item(0).currNum);\n }\n }, function (tx, error) {\n sqlFailCb(createDOMException(\n 'DataError',\n 'Could not get the auto increment value for key',\n error\n ));\n return false;\n });\n}\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction assignCurrentNumber (tx, store, num, successCb, failCb) {\n const sql = 'UPDATE __sys__ SET \"currNum\" = ? WHERE \"name\" = ?';\n const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n tx.executeSql(sql, sqlValues, function () {\n successCb(num);\n }, function (tx, err) {\n failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));\n return false;\n });\n}\n\n/**\n * Bump up the auto-inc counter if the key path-resolved value is valid\n * (greater than old value and >=1) OR if a manually passed in key is\n * valid (numeric and >= 1) and >= any primaryKey.\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction setCurrentNumber (tx, store, num, successCb, failCb) {\n num = num === MAX_ALLOWED_CURRENT_NUMBER\n ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner\n : num + 1;\n return assignCurrentNumber(tx, store, num, successCb, failCb);\n}\n\n/**\n * @callback KeyForStoreCallback\n * @param {\"failure\"|null} arg1\n * @param {Integer} [arg2]\n * @param {Integer} [arg3]\n * @returns {void}\n */\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {KeyForStoreCallback} cb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction generateKeyForStore (tx, store, cb, sqlFailCb) {\n getCurrentNumber(tx, store, function (key) {\n if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See )\n cb('failure');\n return;\n }\n // Increment current number by 1 (we cannot leverage SQLite's\n // autoincrement (and decrement when not needed), as decrementing\n // will be overwritten/ignored upon the next insert)\n setCurrentNumber(\n tx, store, key,\n function () {\n cb(null, key, key);\n },\n sqlFailCb\n );\n }, sqlFailCb);\n}\n\n// Fractional or numbers exceeding the max do not get changed in the result\n// per https://github.com/w3c/IndexedDB/issues/147\n// so we do not return a key\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Key} key\n * @param {(num?: Integer) => void} successCb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {\n // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers\n // (or numbers larger than the max) are now to have the explicit effect of\n // setting the current number (up to the max), so we do not optimize them\n // out here\n if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number\n // Auto-increment attempted with a bad key;\n // we are not to change the current number, but the steps don't call for failure\n // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1\n successCb();\n } else {\n // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher\n // to determine which to use and whether to update the current number\n getCurrentNumber(tx, store, function (cn) {\n const value = Math.floor(\n Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)\n );\n const useNewKeyForAutoInc = value >= cn;\n if (useNewKeyForAutoInc) {\n setCurrentNumber(tx, store, value, function () {\n successCb(cn); // Supply old current number in case needs to be reverted\n }, sqlFailCb);\n } else { // Not updated\n successCb();\n }\n }, sqlFailCb);\n }\n}\n\nexport {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,\n convertValueToMultiEntryKeyDecoded,\n convertValueToKey,\n convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,\n extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,\n extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,\n isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,\n assignCurrentNumber,\n generateKeyForStore, possiblyUpdateKeyGenerator};\n"],"names":["map","CFG","val","test","TypeError","forEach","prop","validator","Array","isArray","_prop","_prop2","_slicedToArray","Object","defineProperty","get","set","createNativeDOMException","name","message","DOMException","prototype","constructor","codes","IndexSizeError","HierarchyRequestError","WrongDocumentError","InvalidCharacterError","NoModificationAllowedError","NotFoundError","NotSupportedError","InUseAttributeError","InvalidStateError","SyntaxError","InvalidModificationError","NamespaceError","InvalidAccessError","TypeMismatchError","SecurityError","NetworkError","AbortError","URLMismatchError","QuotaExceededError","TimeoutError","InvalidNodeTypeError","DataCloneError","EncodingError","NotReadableError","UnknownError","ConstraintError","DataError","TransactionInactiveError","ReadOnlyError","VersionError","OperationError","NotAllowedError","legacyCodes","INDEX_SIZE_ERR","DOMSTRING_SIZE_ERR","HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR","NO_DATA_ALLOWED_ERR","NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR","VALIDATION_ERR","TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR","createNonNativeDOMExceptionClass","Symbol","toStringTag","_code","_name","_message","undefined","configurable","enumerable","writable","value","DummyDOMException","create","Error","keys","codeName","ShimNonNativeDOMException","createNonNativeDOMException","logError","error","DEBUG","msg","_typeof","method","console","trace","isErrorOrDOMErrorOrDOMException","obj","useNativeDOMException","err","createDOMException","escapeUnmatchedSurrogates","arg","replaceAll","_","unmatchedHighSurrogate","precedingLow","unmatchedLowSurrogate","codePointAt","toString","padStart","escapeSQLiteStatement","isObj","isDate","getDate","isBlob","size","slice","isFile","isBinary","byteLength","getFloat64","isNullish","v","cmp","first","second","encodedKey1","keyEncode","encodedKey2","result","decodedKey1","keyDecode","decodedKey2","JSON","stringify","warn","keyTypeToEncodedChar","invalid","number","date","string","binary","array","keyTypes","k","String","fromCodePoint","encodedCharToKeyType","reduce","o","signValues","types","encode","decode","key","key32","Number","MIN_VALUE","repeat","Math","abs","decimalIndex","indexOf","replace","significantDigitIndex","search","sign","exponent","mantissa","isFinite","padBase32Exponent","flipBase32","padBase32Mantissa","length","zeros","NEGATIVE_INFINITY","POSITIVE_INFINITY","pow32","negate","inArray","encoded","_iterator","_createForOfIteratorHelper","entries","_step","s","n","done","_step$value","i","item","encodedItem","e","f","push","decoded","parse","pop","decodedItem","toJSON","Date","_toConsumableArray","getCopyBytesHeldByBufferSource","b","arr","split","parseInt","buffer","ArrayBuffer","uint8","Uint8Array","exp","flipped","_iterator2","_step2","ch","roundToPrecision","pow","whole","wholeNum","fraction","fractionNum","expansion","num","precision","arguments","parseFloat","toPrecision","getKeyType","util","keyType","includes","convertValueToKey","input","seen","convertValueToKeyValueDecoded","convertValueToMultiEntryKey","O","offset","isView","arrayBuffer","byteOffset","multiEntry","fullKeys","type","ret","isNaN","is","octets","len","_loop","hasOwn","entry","every","_ret","getTime","convertValueToMultiEntryKeyDecoded","convertValueToKeyRethrowingAndIfInvalid","extractKeyFromValueUsingKeyPath","keyPath","extractKeyValueDecodedFromValueUsingKeyPath","evaluateKeyPathOnValue","evaluateKeyPathOnValueToDecodedValue","r","failure","some","identifiers","idntfr","lastModified","injectKeyIntoValueUsingKeyPath","last","identifier","hop","checkKeyCouldBeInjectedIntoValue","_iterator3","_step3","isKeyInRange","range","checkCached","lowerMatch","lower","upperMatch","upper","encodedKey","__lowerCached","__upperCached","lowerOpen","upperOpen","isMultiEntryMatch","encodedEntry","findMultiEntryMatches","keyEntry","matches","_iterator4","_step4","nested","convertKeyToValue","index","roundTrip","MAX_ALLOWED_CURRENT_NUMBER","getCurrentNumber","tx","store","func","sqlFailCb","executeSql","__currentName","data","rows","currNum","assignCurrentNumber","successCb","failCb","sql","sqlValues","log","setCurrentNumber","generateKeyForStore","cb","possiblyUpdateKeyGenerator","cn","floor","min","useNewKeyForAutoInc"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,IAAMA,GAAG,GAAG,EAAE,CAAA;EAEd,IAAMC,GAAG,8BAAgC,EAAG,CAAA;;EAE5C;EACA;EACA;;EAEA;EACA;EACA;;EAEA;EACC;EACG;EACA,OAAO;EAAE;;EAET;EACA;EACA,wBAAwB;EAExB;EACA;EACA;EACA;EACA,UAAU;EAEV;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAAE;;EAElB;EACA;EACA,aAAa;EAEb;EACA;EACA,uBAAuB;EAEvB;EACA;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA,mBAAmB;EAEnB;EACA;EACA;EACA;EACA,aAAa;EAEb;EACA,eAAe;EAAE;EACjB;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,KAAK;EAEL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB;EACA;EACA;EACA,kBAAkB;EAElB;EACA;EACA;;EAEA;EACA,IAAI;EAEJ;EACA;EACA;EACA;EACA,kBAAkB;EAClB;EACA;EACA;EACA;EACA,sBAAsB;EAEtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA,oBAAoB;EACpB;EACA,sBAAsB;EAEtB;EACA;EACA;EACA,6BAA6B;EAC7B;EACA,yBAAyB;EAEzB;EACA;EACA,2BAA2B;EAE3B;EACA;EACA,oBAAoB;EACpB;EACA,CACI,gBAAgB;EAChB;EACR;EACA;EACA;EACA;EACQ,UAACC,GAAG,EAAK;IACL,IAAI,CAAE,gVAAgD,CAAEC,IAAI,sBACjCD,GAC3B,CAAC,EAAE;EACC,IAAA,MAAM,IAAIE,SAAS,CACf,8DAA8D,GAC9D,2CACJ,CAAC,CAAA;EACL,GAAA;EACJ,CAAC,CACJ;EAED;EACA;EACA;EACA,qBAAqB,EACrB,kBAAkB,EAClB,qBAAqB;EAErB;EACA,gBAAgB;EAAE;EAClB,UAAU;EAAE;EACZ,YAAY;EAAE;;EAEd,eAAe,CAClB,CAAEC,OAAO,CAAC,UAACC,IAAI,EAAK;EACjB;EACA,EAAA,IAAIC,SAAS,CAAA;EACb,EAAA,IAAIC,KAAK,CAACC,OAAO,CAACH,IAAI,CAAC,EAAE;MAAA,IAAAI,KAAA,GACDJ,IAAI,CAAA;EAAA,IAAA,IAAAK,MAAA,G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AAS,EAAEP,SAAS,EAAE;EACvE;EACA;EACA;EACA;IACA,IAAI,OAAOtJ,GAAG,KAAK,QAAQ,IAAIA,GAAG,GAAG,CAAC,EAAE;EAAE;EACtC;EACA;EACA;EACA6J,IAAAA,SAAS,EAAE,CAAA;EACf,GAAC,MAAM;EACH;EACA;EACAX,IAAAA,gBAAgB,CAACC,EAAE,EAAEC,KAAK,EAAE,UAAUkB,EAAE,EAAE;EACtC,MAAA,IAAMjP,KAAK,GAAGgF,IAAI,CAACkK,KAAK,CACpBlK,IAAI,CAACmK,GAAG,CAACxK,GAAG,EAAEiJ,0BAA0B,CAC5C,CAAC,CAAA;EACD,MAAA,IAAMwB,mBAAmB,GAAGpP,KAAK,IAAIiP,EAAE,CAAA;EACvC,MAAA,IAAIG,mBAAmB,EAAE;EACrBP,QAAAA,gBAAgB,CAACf,EAAE,EAAEC,KAAK,EAAE/N,KAAK,EAAE,YAAY;EAC3CwO,UAAAA,SAAS,CAACS,EAAE,CAAC,CAAC;WACjB,EAAEhB,SAAS,CAAC,CAAA;EACjB,OAAC,MAAM;EAAE;EACLO,QAAAA,SAAS,EAAE,CAAA;EACf,OAAA;OACH,EAAEP,SAAS,CAAC,CAAA;EACjB,GAAA;EACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/dist/indexeddbshim-Key.min.js b/dist/indexeddbshim-Key.min.js index 86098707..6474e6f0 100644 --- a/dist/indexeddbshim-Key.min.js +++ b/dist/indexeddbshim-Key.min.js @@ -1,3 +1,3 @@ -/*! indexeddbshim - v15.0.4 - 9/11/2024 */ +/*! indexeddbshim - v15.2.0 - 9/11/2024 */ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).IDBKeyUtils={})}(this,(function(e){"use strict";function r(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,u=!0,c=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return u=e.done,e},e:function(e){c=!0,a=e},f:function(){try{u||null==t.return||t.return()}finally{if(c)throw a}}}}function n(e,r){return function(e){if(Array.isArray(e))return e}(e)||function(e,r){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var n,o,a,i,u=[],c=!0,l=!1;try{if(a=(t=t.call(e)).next,0===r);else for(;!(c=(n=a.call(t)).done)&&(u.push(n.value),u.length!==r);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=t.return&&(i=t.return(),Object(i)!==i))return}finally{if(l)throw o}}return u}}(e,r)||i(e,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e){return function(e){if(Array.isArray(e))return r(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||i(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function i(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}var u={},c={};function l(e,r){return new DOMException.prototype.constructor(r,e||"DOMException")}["DEBUG","cacheDatabaseInstances","autoName","fullIDLSupport","checkOrigin","cursorPreloadPackSize","UnicodeIDStart","UnicodeIDContinue","registerSCA","avoidAutoShim","win","DEFAULT_DB_SIZE","useSQLiteIndexes","fs","addNonIDBGlobals","replaceNonIDBGlobals","escapeDatabaseName","unescapeDatabaseName","databaseCharacterEscapeList","databaseNameLengthLimit","escapeNFDForDatabaseNames","addSQLiteExtension",["memoryDatabase",function(e){if(!/^(?::memory:|file::memory:(\?(?:[\0-"\$-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?(#(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?)?$/.test(e))throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a "file::memory:[?queryString][#hash] URL".')}],"deleteDatabaseFiles","databaseBasePath","sysDatabaseBasePath","sqlBusyTimeout","sqlTrace","sqlProfile","createIndexes"].forEach((function(e){var r;if(Array.isArray(e)){var t=n(e,2);e=t[0],r=t[1]}Object.defineProperty(c,e,{get:function(){return u[e]},set:function(t){r&&r(t),u[e]=t}})}));var s={IndexSizeError:1,HierarchyRequestError:3,WrongDocumentError:4,InvalidCharacterError:5,NoModificationAllowedError:7,NotFoundError:8,NotSupportedError:9,InUseAttributeError:10,InvalidStateError:11,SyntaxError:12,InvalidModificationError:13,NamespaceError:14,InvalidAccessError:15,TypeMismatchError:17,SecurityError:18,NetworkError:19,AbortError:20,URLMismatchError:21,QuotaExceededError:22,TimeoutError:23,InvalidNodeTypeError:24,DataCloneError:25,EncodingError:0,NotReadableError:0,UnknownError:0,ConstraintError:0,DataError:0,TransactionInactiveError:0,ReadOnlyError:0,VersionError:0,OperationError:0,NotAllowedError:0},f={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25};var y=function(){function e(e,r){this[Symbol.toStringTag]="DOMException",this._code=r in s?s[r]:f[r]||0,this._name=r||"Error",this._message=void 0===e?"":""+e,Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,writable:!0,value:this._code}),void 0!==r&&Object.defineProperty(this,"name",{configurable:!0,enumerable:!0,writable:!0,value:this._name}),void 0!==e&&Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,writable:!0,value:this._message})}var r=function(){};return r.prototype=Object.create(Error.prototype),["name","message"].forEach((function(t){Object.defineProperty(r.prototype,t,{enumerable:!0,get:function(){if(!(this instanceof e||this instanceof r||this instanceof Error))throw new TypeError("Illegal invocation");return this["name"===t?"_name":"_message"]}})})),Object.defineProperty(r.prototype,"code",{configurable:!0,enumerable:!0,get:function(){throw new TypeError("Illegal invocation")}}),e.prototype=new r,e.prototype[Symbol.toStringTag]="DOMExceptionPrototype",Object.defineProperty(e,"prototype",{writable:!1}),Object.keys(s).forEach((function(r){Object.defineProperty(e.prototype,r,{enumerable:!0,configurable:!1,value:s[r]}),Object.defineProperty(e,r,{enumerable:!0,configurable:!1,value:s[r]})})),Object.keys(f).forEach((function(r){Object.defineProperty(e.prototype,r,{enumerable:!0,configurable:!1,value:f[r]}),Object.defineProperty(e,r,{enumerable:!0,configurable:!1,value:f[r]})})),Object.defineProperty(e.prototype,"constructor",{writable:!0,configurable:!0,enumerable:!1,value:e}),e}();function d(e,r,t){if(c.DEBUG){var n=t&&"object"===a(t)&&t.message?t.message:t,o="function"==typeof console.error?"error":"log";console[o](e+": "+r+". "+(n||"")),console.trace&&console.trace()}}var p,v,b=!1;try{p=l("test name","test message"),(v=p)&&"object"===a(v)&&"string"==typeof v.name&&"test name"===p.name&&"test message"===p.message&&(b=!0)}catch(e){}var m=b?function(e,r,t){return d(e,r,t),l(e,r)}:function(e,r,t){return d(e,r,t),function(e,r){return new y(r,e)}(e,r)};function F(e){return function(e){return e.replaceAll(/((?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])))(?!(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))|(^|(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))((?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g,(function(e,r,t,n){return r?"^2"+r.codePointAt().toString(16).padStart(4,"0"):(t||"")+"^3"+n.codePointAt().toString(16).padStart(4,"0")}))}(e.replaceAll("^","^^").replaceAll("\0","^0"))}function D(e){return null!==e&&"object"===a(e)}function E(e){return null==e}function g(e,r){var t=k(e),n=k(r),o=t>n?1:t===n?0:-1;if(c.DEBUG){var i=G(t),u=G(n);"object"===a(e)&&(e=JSON.stringify(e),i=JSON.stringify(i)),"object"===a(r)&&(r=JSON.stringify(r),u=JSON.stringify(u)),i!==e&&console.warn(e+" was incorrectly encoded as "+i),u!==r&&console.warn(r+" was incorrectly encoded as "+u)}return o}var h={invalid:100,number:200,date:300,string:400,binary:500,array:600},N=Object.keys(h);N.forEach((function(e){h[e]=String.fromCodePoint(h[e])}));var I=N.reduce((function(e,r){return e[h[r]]=r,e}),{}),A=["negativeInfinity","bigNegative","smallNegative","smallPositive","bigPositive","positiveInfinity"],O={invalid:{encode:function(){return h.invalid+"-"},decode:function(){}},number:{encode:function(e){var r,t,n,o=e===Number.MIN_VALUE?"0."+"0".repeat(214)+"2":Math.abs(e).toString(32),a=o.indexOf("."),i=(o=-1!==a?o.replace(".",""):o).search(/(?:[\0-\/1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/);return o=o.slice(i),Number.isFinite(Number(e))?e<0?e>-1?(r=A.indexOf("smallNegative"),t=_(i),n=R(w(o))):(r=A.indexOf("bigNegative"),t=R(_(-1!==a?a:o.length)),n=R(w(o))):e<1?(r=A.indexOf("smallPositive"),t=R(_(i)),n=w(o)):(r=A.indexOf("bigPositive"),t=_(-1!==a?a:o.length),n=w(o)):(t=C(2),n=C(11),r=A.indexOf(e>0?"positiveInfinity":"negativeInfinity")),h.number+"-"+r+t+n},decode:function(e){var r=Number(e.slice(2,3)),t=e.slice(3,5),n=e.slice(5,16);switch(A[r]){case"negativeInfinity":return Number.NEGATIVE_INFINITY;case"positiveInfinity":return Number.POSITIVE_INFINITY;case"bigPositive":return S(n,t);case"smallPositive":return S(n,t=B(R(t)));case"smallNegative":return t=B(t),-S(n=R(n),t);case"bigNegative":return t=R(t),-S(n=R(n),t);default:throw new Error("Invalid number.")}}},string:{encode:function(e,r){return r&&(e=e.replaceAll(/((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g,"-$1")+" "),h.string+"-"+e},decode:function(e,r){return e=e.slice(2),r&&(e=e.slice(0,-1).replaceAll(/\x2D((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g,"$1")),e}},array:{encode:function(e){var r,o=[],a=t(e.entries());try{for(a.s();!(r=a.n()).done;){var i=n(r.value,2),u=i[0],c=k(i[1],!0);o[u]=c}}catch(e){a.e(e)}finally{a.f()}return o.push(h.invalid+"-"),h.array+"-"+JSON.stringify(o)},decode:function(e){var r=JSON.parse(e.slice(2));r.pop();for(var t=0;t1&&void 0!==arguments[1]?arguments[1]:16;return Number.parseFloat(e.toPrecision(r))}function C(e){return"0".repeat(e)}function B(e){return"-"+e}function P(e){if(Array.isArray(e))return"array";if(function(e){return D(e)&&"getDate"in e&&"function"==typeof e.getDate}(e))return"date";if(function(e){return D(e)&&"byteLength"in e&&"number"==typeof e.byteLength&&("slice"in e&&"function"==typeof e.slice||"getFloat64"in e&&"function"==typeof e.getFloat64)}(e))return"binary";var r=a(e);return["string","number"].includes(r)?r:"invalid"}function M(e,r){return x(e,r,!1,!0)}function j(e){var r=0,t=0;if(ArrayBuffer.isView(e)){if(void 0===e.buffer)throw new TypeError("Could not copy the bytes held by a buffer source as the buffer was undefined.");r=e.byteOffset,t=e.byteLength}else t=e.byteLength;return new Uint8Array("buffer"in e&&e.buffer||e,r,t)}function x(e,r,t,n){if((r=r||[]).includes(e))return{type:"array",invalid:!0,message:"An array key cannot be circular"};var o=P(e),i={type:o,value:e};switch(o){case"number":return Number.isNaN(e)?{type:"NaN",invalid:!0}:Object.is(e,-0)?{type:o,value:0}:i;case"string":return i;case"binary":return{type:"binary",value:j(e)};case"array":var u=e,c=u.length;r.push(e);for(var l,s=[],f=function(){if(!t&&!Object.hasOwn(u,y))return{v:{type:o,invalid:!0,message:"Does not have own index property"}};try{var e=x(u[y],r,!1,n);if(e.invalid)return t?0:{v:{type:o,invalid:!0,message:"Bad array entry value-to-key conversion"}};(!t||!n&&s.every((function(r){return 0!==g(r,e.value)}))||n&&s.every((function(r){return 0!==g(r,e)})))&&s.push(n?e:e.value)}catch(e){if(!t)throw e}},y=0;yi||!r.lowerOpen&&(!a&&!i||null!==a&&null!==i&&a>=i))&&(n=!0),!o&&(r.upperOpen&&null!==a&&null!==u&&a0&&o.push(u);continue}u=u[0]}(E(n)||K(u,n,!0))&&o.push(u)}}catch(e){i.e(e)}finally{i.f()}}else(E(n)||K(r,n,!0))&&o.push(r);return o},e.generateKeyForStore=function(e,r,t,n){q(e,r,(function(o){o>H?t("failure"):W(e,r,o,(function(){t(null,o,o)}),n)}),n)},e.injectKeyIntoValueUsingKeyPath=function(e,r,t){var n=t.split("."),o=n.pop();n.forEach((function(r){Object.hasOwn(e,r)||(e[r]={}),e=e[r]})),e[o]=r},e.isKeyInRange=K,e.isMultiEntryMatch=function(e,r){return"array"===I[r.slice(0,1)]?r.indexOf(e)>1:r===e},e.possiblyUpdateKeyGenerator=function(e,r,t,n,o){"number"!=typeof t||t<1?n():q(e,r,(function(a){var i=Math.floor(Math.min(t,H));i>=a?W(e,r,i,(function(){n(a)}),o):n()}),o)},e.roundTrip=function(e,r){return G(k(e,r),r)}})); //# sourceMappingURL=indexeddbshim-Key.min.js.map diff --git a/dist/indexeddbshim-Key.min.js.map b/dist/indexeddbshim-Key.min.js.map index fd0b71b0..c7bea649 100644 --- a/dist/indexeddbshim-Key.min.js.map +++ b/dist/indexeddbshim-Key.min.js.map @@ -1 +1 @@ -{"version":3,"file":"indexeddbshim-Key.min.js","sources":["../src/CFG.js","../src/DOMException.js","../src/util.js","../src/cmp.js","../src/Key.js"],"sourcesContent":["/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n/**\n * @typedef {T[keyof T]} ValueOf\n * @template T\n */\n/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n\n/**\n * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi\n */\n\n/**\n * @typedef {{\n * DEBUG: boolean,\n * cacheDatabaseInstances: boolean,\n * autoName: boolean,\n * fullIDLSupport: boolean,\n * checkOrigin: boolean,\n * cursorPreloadPackSize: number,\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string,\n * registerSCA: (\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset,\n * avoidAutoShim: boolean,\n * win: {\n * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default\n * },\n * DEFAULT_DB_SIZE: number,\n * useSQLiteIndexes: boolean,\n * fs: FSApi,\n * addNonIDBGlobals: boolean,\n * replaceNonIDBGlobals: boolean,\n * escapeDatabaseName: (name: string) => string,\n * unescapeDatabaseName: (name: string) => string,\n * databaseCharacterEscapeList: string|false,\n * databaseNameLengthLimit: number|false,\n * escapeNFDForDatabaseNames: boolean,\n * addSQLiteExtension: boolean,\n * memoryDatabase: string,\n * deleteDatabaseFiles: boolean,\n * databaseBasePath: string,\n * sysDatabaseBasePath: string,\n * sqlBusyTimeout: number,\n * sqlTrace: () => void,\n * sqlProfile: () => void,\n * createIndexes: boolean\n * }} ConfigValues\n */\n\n/**\n * @typedef {ValueOf} ConfigValue\n */\n\n/** @type {{[key: string]: ConfigValue}} */\nconst map = {};\n\nconst CFG = /** @type {ConfigValues} */ ({});\n\n/**\n * @typedef {keyof ConfigValues} KeyofConfigValues\n */\n\n/**\n * @typedef {KeyofConfigValues[]} Config\n */\n\n/** @type {Config} */\n([\n // Boolean for verbose reporting\n 'DEBUG', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean (effectively defaults to true) on whether to cache WebSQL\n // `openDatabase` instances\n 'cacheDatabaseInstances',\n\n // Boolean on whether to auto-name databases (based on an\n // auto-increment) when the empty string is supplied; useful with\n // `memoryDatabase`; defaults to `false` which means the empty string\n // will be used as the (valid) database name\n 'autoName',\n\n // Determines whether the slow-performing `Object.setPrototypeOf`\n // calls required for full WebIDL compliance will be used. Probably\n // only needed for testing or environments where full introspection\n // on class relationships is required; see\n // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean on whether to perform origin checks in `IDBFactory` methods\n // Effectively defaults to `true` (must be set to `false` to cancel checks)\n 'checkOrigin',\n\n // Used by `IDBCursor` continue methods for number of records to cache;\n // Defaults to 100\n 'cursorPreloadPackSize',\n\n // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);\n // or just use the Unicode builds which invoke this method\n // automatically using the large, fully spec-compliant, regular\n // expression strings of `src/UnicodeIdentifiers.js`)\n // In the non-Unicode builds, defaults to /[$A-Z_a-z]/\n 'UnicodeIDStart',\n // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/\n 'UnicodeIDContinue',\n\n // Used by SCA.js for optional restructuring of typeson-registry\n // Structured Cloning Algorithm; should only be needed for ensuring data\n // created in 3.* versions of IndexedDBShim continue to work; see the\n // library `typeson-registry-sca-reverter` to get a function to do this\n 'registerSCA',\n\n // BROWSER-SPECIFIC CONFIG\n 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is\n // missing or poor support is known (non-Chrome Android or\n // non-Safari iOS9), the shim will be auto-applied without\n // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing\n // the shim for such cases.\n\n // -----------SQL CONFIG----------\n // Object (`window` in the browser) on which there may be an\n // `openDatabase` method (if any) for WebSQL. (The browser\n // throws if attempting to call `openDatabase` without the window\n // so this is why the config doesn't just allow the function.)\n // Defaults to `window` or `self` in browser builds or\n // a singleton object with the `openDatabase` method set to\n // the \"websql\" package in Node.\n 'win',\n\n // For internal `openDatabase` calls made by `IDBFactory` methods;\n // per the WebSQL spec, \"User agents are expected to use the display name\n // and the estimated database size to optimize the user experience.\n // For example, a user agent could use the estimated size to suggest an\n // initial quota to the user. This allows a site that is aware that it\n // will try to use hundreds of megabytes to declare this upfront, instead\n // of the user agent prompting the user for permission to increase the\n // quota every five megabytes.\"\n // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari\n 'DEFAULT_DB_SIZE',\n // Whether to create indexes on SQLite tables (and also whether to try\n // dropping)\n // Effectively defaults to `false` (ignored unless `true`)\n 'useSQLiteIndexes',\n\n // NODE-IMPINGING SETTINGS (created for sake of limitations in Node\n // or desktop file system implementation but applied by default in\n // browser for parity)\n\n // File system module with `unlink` to remove deleted database files\n 'fs',\n\n // Used when setting global shims to determine whether to try to add\n // other globals shimmed by the library (`ShimDOMException`,\n // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'addNonIDBGlobals',\n // Used when setting global shims to determine whether to try to overwrite\n // other globals shimmed by the library (`DOMException`, `DOMStringList`,\n // `Event`, `CustomEvent`, `EventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'replaceNonIDBGlobals',\n\n // Overcoming limitations with node-sqlite3/storing database name on\n // file systems\n // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n // Defaults to prefixing database with `D_`, escaping\n // `databaseCharacterEscapeList`, escaping NUL, and\n // escaping upper case letters, as well as enforcing\n // `databaseNameLengthLimit`\n 'escapeDatabaseName',\n // Not used internally; usable as a convenience method\n 'unescapeDatabaseName',\n\n // Defaults to global regex representing the following\n // (characters nevertheless commonly reserved in modern,\n // Unicode-supporting systems): 0x00-0x1F 0x7F \" * / : < > ? \\ |\n 'databaseCharacterEscapeList',\n // Defaults to 254 (shortest typical modern file length limit)\n 'databaseNameLengthLimit',\n\n // Boolean defaulting to true on whether to escape NFD-escaping\n // characters to avoid clashes on MacOS which performs NFD on files\n 'escapeNFDForDatabaseNames',\n\n // Boolean on whether to add the `.sqlite` extension to file names;\n // defaults to `true`\n 'addSQLiteExtension',\n // Various types of in-memory databases that can auto-delete\n [\n 'memoryDatabase',\n /**\n * @param {string} val\n * @throws {TypeError}\n * @returns {void}\n */\n (val) => {\n if (!(/^(?::memory:|file::memory:(\\?[^#]*)?(#.*)?)?$/u).test(\n /** @type {string} */ (val)\n )) {\n throw new TypeError(\n '`memoryDatabase` must be the empty string, \":memory:\", or a ' +\n '\"file::memory:[?queryString][#hash] URL\".'\n );\n }\n }\n ],\n\n // NODE-SPECIFIC CONFIG\n // Boolean on whether to delete the database file itself after\n // `deleteDatabase`; defaults to `true` as the database will be empty\n 'deleteDatabaseFiles',\n 'databaseBasePath',\n 'sysDatabaseBasePath',\n\n // NODE-SPECIFIC WEBSQL CONFIG\n 'sqlBusyTimeout', // Defaults to 1000\n 'sqlTrace', // Callback not used by default\n 'sqlProfile', // Callback not used by default\n\n 'createIndexes'\n]).forEach((prop) => {\n /** @type {(val: any) => void} */\n let validator;\n if (Array.isArray(prop)) {\n [prop, validator] = prop;\n }\n Object.defineProperty(CFG, prop, {\n get () {\n return map[prop];\n },\n set (val) {\n if (validator) {\n validator(val);\n }\n map[prop] = val;\n }\n });\n});\n\nexport default CFG;\n","import CFG from './CFG.js';\n\n/**\n * Creates a native DOMException, for browsers that support it.\n * @param {string} name\n * @param {string} message\n * @returns {DOMException}\n */\nfunction createNativeDOMException (name, message) {\n // @ts-expect-error It's ok\n return new DOMException.prototype.constructor(\n message,\n name || 'DOMException'\n );\n}\n\n// From web-platform-tests testharness.js name_code_map (though not in new spec)\n\n/**\n * @typedef {\"IndexSizeError\"|\"HierarchyRequestError\"|\"WrongDocumentError\"|\n * \"InvalidCharacterError\"|\"NoModificationAllowedError\"|\"NotFoundError\"|\n * \"NotSupportedError\"|\"InUseAttributeError\"|\"InvalidStateError\"|\n * \"SyntaxError\"|\"InvalidModificationError\"|\"NamespaceError\"|\n * \"InvalidAccessError\"|\"TypeMismatchError\"|\"SecurityError\"|\n * \"NetworkError\"|\"AbortError\"|\"URLMismatchError\"|\"QuotaExceededError\"|\n * \"TimeoutError\"|\"InvalidNodeTypeError\"|\"DataCloneError\"|\"EncodingError\"|\n * \"NotReadableError\"|\"UnknownError\"|\"ConstraintError\"|\"DataError\"|\n * \"TransactionInactiveError\"|\"ReadOnlyError\"|\"VersionError\"|\n * \"OperationError\"|\"NotAllowedError\"} Code\n */\n\nconst codes = {\n IndexSizeError: 1,\n HierarchyRequestError: 3,\n WrongDocumentError: 4,\n InvalidCharacterError: 5,\n NoModificationAllowedError: 7,\n NotFoundError: 8,\n NotSupportedError: 9,\n InUseAttributeError: 10,\n InvalidStateError: 11,\n SyntaxError: 12,\n InvalidModificationError: 13,\n NamespaceError: 14,\n InvalidAccessError: 15,\n TypeMismatchError: 17,\n SecurityError: 18,\n NetworkError: 19,\n AbortError: 20,\n URLMismatchError: 21,\n QuotaExceededError: 22,\n TimeoutError: 23,\n InvalidNodeTypeError: 24,\n DataCloneError: 25,\n\n EncodingError: 0,\n NotReadableError: 0,\n UnknownError: 0,\n ConstraintError: 0,\n DataError: 0,\n TransactionInactiveError: 0,\n ReadOnlyError: 0,\n VersionError: 0,\n OperationError: 0,\n NotAllowedError: 0\n};\n\n/**\n * @typedef {\"INDEX_SIZE_ERR\"|\"DOMSTRING_SIZE_ERR\"|\"HIERARCHY_REQUEST_ERR\"|\n * \"WRONG_DOCUMENT_ERR\"|\"INVALID_CHARACTER_ERR\"|\"NO_DATA_ALLOWED_ERR\"|\n * \"NO_MODIFICATION_ALLOWED_ERR\"|\"NOT_FOUND_ERR\"|\"NOT_SUPPORTED_ERR\"|\n * \"INUSE_ATTRIBUTE_ERR\"|\"INVALID_STATE_ERR\"|\"SYNTAX_ERR\"|\n * \"INVALID_MODIFICATION_ERR\"|\"NAMESPACE_ERR\"|\"INVALID_ACCESS_ERR\"|\n * \"VALIDATION_ERR\"|\"TYPE_MISMATCH_ERR\"|\"SECURITY_ERR\"|\"NETWORK_ERR\"|\n * \"ABORT_ERR\"|\"URL_MISMATCH_ERR\"|\"QUOTA_EXCEEDED_ERR\"|\"TIMEOUT_ERR\"|\n * \"INVALID_NODE_TYPE_ERR\"|\"DATA_CLONE_ERR\"} LegacyCode\n */\n\nconst legacyCodes = {\n INDEX_SIZE_ERR: 1,\n DOMSTRING_SIZE_ERR: 2,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n INVALID_CHARACTER_ERR: 5,\n NO_DATA_ALLOWED_ERR: 6,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INUSE_ATTRIBUTE_ERR: 10,\n INVALID_STATE_ERR: 11,\n SYNTAX_ERR: 12,\n INVALID_MODIFICATION_ERR: 13,\n NAMESPACE_ERR: 14,\n INVALID_ACCESS_ERR: 15,\n VALIDATION_ERR: 16,\n TYPE_MISMATCH_ERR: 17,\n SECURITY_ERR: 18,\n NETWORK_ERR: 19,\n ABORT_ERR: 20,\n URL_MISMATCH_ERR: 21,\n QUOTA_EXCEEDED_ERR: 22,\n TIMEOUT_ERR: 23,\n INVALID_NODE_TYPE_ERR: 24,\n DATA_CLONE_ERR: 25\n};\n\n/**\n *\n * @returns {typeof DOMException}\n */\nfunction createNonNativeDOMExceptionClass () {\n /**\n * @param {string|undefined} message\n * @param {Code|LegacyCode} name\n * @returns {void}\n */\n function DOMException (message, name) {\n // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message\n this[Symbol.toStringTag] = 'DOMException';\n this._code = name in codes\n ? codes[/** @type {Code} */ (name)]\n : (legacyCodes[/** @type {LegacyCode} */ (name)] || 0);\n this._name = name || 'Error';\n // We avoid `String()` in this next line as it converts Symbols\n this._message = message === undefined ? '' : ('' + message); // eslint-disable-line no-implicit-coercion -- Don't convert symbols\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._code\n });\n if (name !== undefined) {\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._name\n });\n }\n if (message !== undefined) {\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: this._message\n });\n }\n }\n\n // Necessary for W3C tests which complains if `DOMException` has properties on its \"own\" prototype\n\n // class DummyDOMException extends Error {}; // Sometimes causing problems in Node\n /* eslint-disable func-name-matching -- See above */\n /**\n * @class\n */\n const DummyDOMException = function DOMException () { /* */ };\n /* eslint-enable func-name-matching -- See above */\n DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing\n /** @type {const} */ (['name', 'message']).forEach((prop) => {\n Object.defineProperty(DummyDOMException.prototype, prop, {\n enumerable: true,\n /**\n * @this {DOMException}\n * @returns {string}\n */\n get () {\n if (!(this instanceof DOMException ||\n // @ts-expect-error Just checking\n this instanceof DummyDOMException ||\n // @ts-expect-error Just checking\n this instanceof Error)) {\n throw new TypeError('Illegal invocation');\n }\n return this[prop === 'name' ? '_name' : '_message'];\n }\n });\n });\n // DOMException uses the same `toString` as `Error`\n Object.defineProperty(DummyDOMException.prototype, 'code', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n // @ts-expect-error It's ok\n DOMException.prototype = new DummyDOMException();\n\n DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';\n Object.defineProperty(DOMException, 'prototype', {\n writable: false\n });\n\n const keys = Object.keys(codes);\n\n /** @type {(keyof codes)[]} */ (keys).forEach(\n (codeName) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n }\n );\n /** @type {(keyof legacyCodes)[]} */ (Object.keys(legacyCodes)).forEach((\n codeName\n ) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n });\n Object.defineProperty(DOMException.prototype, 'constructor', {\n writable: true,\n configurable: true,\n enumerable: false,\n value: DOMException\n });\n\n // @ts-expect-error We don't need all its properties\n return DOMException;\n}\n\nconst ShimNonNativeDOMException = createNonNativeDOMExceptionClass();\n\n/**\n * Creates a generic Error object.\n * @param {string} name\n * @param {string} message\n * @returns {Error}\n */\nfunction createNonNativeDOMException (name, message) {\n return new ShimNonNativeDOMException(message, name);\n}\n\n/**\n * @typedef {{\n * message: string|DOMString\n * }} ErrorLike\n */\n\n/**\n * Logs detailed error information to the console.\n * @param {string} name\n * @param {string} message\n * @param {string|ErrorLike|boolean|null} [error]\n * @returns {void}\n */\nfunction logError (name, message, error) {\n if (CFG.DEBUG) {\n const msg = error && typeof error === 'object' && error.message\n ? error.message\n : /** @type {string} */ (error);\n\n const method = typeof (console.error) === 'function' ? 'error' : 'log';\n console[method](name + ': ' + message + '. ' + (msg || ''));\n if (console.trace) { console.trace(); }\n }\n}\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @param {ArbitraryValue} obj\n * @returns {boolean}\n */\nfunction isErrorOrDOMErrorOrDOMException (obj) {\n return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser\n typeof obj.name === 'string';\n}\n\n/**\n * Finds the error argument. This is useful because some WebSQL callbacks\n * pass the error as the first argument, and some pass it as the second\n * argument.\n * @param {(Error|{message?: string, name?: string}|any)[]} args\n * @returns {Error|DOMException|undefined}\n */\nfunction findError (args) {\n let err;\n if (args) {\n if (args.length === 1) {\n return args[0];\n }\n for (const arg of args) {\n if (isErrorOrDOMErrorOrDOMException(arg)) {\n return arg;\n }\n if (arg && typeof arg.message === 'string') {\n err = arg;\n }\n }\n }\n return err;\n}\n\n/**\n *\n * @param {SQLError} webSQLErr\n * @returns {(DOMException|Error) & {\n * sqlError: SQLError\n * }}\n */\nfunction webSQLErrback (webSQLErr) {\n let name, message;\n switch (webSQLErr.code) {\n case 4: { // SQLError.QUOTA_ERR\n name = 'QuotaExceededError';\n message = 'The operation failed because there was not enough ' +\n 'remaining storage space, or the storage quota was reached ' +\n 'and the user declined to give more space to the database.';\n break;\n }\n /*\n // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`?\n case 7: { // SQLError.TIMEOUT_ERR\n // All transaction errors abort later, so no need to mark inactive\n name = 'TransactionInactiveError';\n message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).';\n break;\n }\n */\n default: {\n name = 'UnknownError';\n message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.';\n break;\n }\n }\n message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')';\n const err =\n /**\n * @type {(Error | DOMException) & {\n * sqlError: SQLError\n * }}\n */\n (createDOMException(name, message));\n err.sqlError = webSQLErr;\n return err;\n}\n\nlet test, useNativeDOMException = false;\n\n// Test whether we can use the browser's native DOMException class\ntry {\n test = createNativeDOMException('test name', 'test message');\n if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {\n // Native DOMException works as expected\n useNativeDOMException = true;\n }\n// eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n} catch (err) {}\n\nconst createDOMException = useNativeDOMException\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n ? /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {DOMException}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNativeDOMException(name, message);\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n : /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {Error}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNonNativeDOMException(name, message);\n };\n\nconst ShimDOMException = useNativeDOMException\n ? DOMException\n : ShimNonNativeDOMException;\n\nexport {logError, findError, ShimDOMException, createDOMException, webSQLErrback};\n","/* eslint-disable new-cap -- ToString is how it is defined */\nimport CFG from './CFG.js';\nimport expandsOnNFD from './unicode-regex.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeUnmatchedSurrogates (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return arg.replaceAll(\n /([\\uD800-\\uDBFF])(?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])/gu,\n function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {\n // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577\n // but Chrome having problems\n if (unmatchedHighSurrogate) {\n return '^2' + unmatchedHighSurrogate.codePointAt()\n .toString(16).padStart(4, '0');\n }\n return (precedingLow || '') + '^3' +\n unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');\n }\n );\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeNameForSQLiteIdentifier (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return '_' + // Prevent empty string\n escapeUnmatchedSurrogates(\n arg.replaceAll('^', '^^') // Escape our escape\n // http://www.sqlite.org/src/tktview?name=57c971fc74\n .replaceAll('\\0', '^0')\n // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names\n // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577\n // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working\n .replaceAll(/([A-Z])/gu, '^$1')\n );\n}\n\n/**\n * The escaping of unmatched surrogates was needed by Chrome but not Node.\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeSQLiteStatement (arg) {\n return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\\0', '^0'));\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeSQLiteResponse (arg) {\n return unescapeUnmatchedSurrogates(arg)\n .replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n })\n .replaceAll('^^', '^');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlEscape (arg) {\n // https://www.sqlite.org/lang_keywords.html\n // http://stackoverflow.com/a/6701665/271577\n // There is no need to escape ', `, or [], as\n // we should always be within double quotes\n // NUL should have already been stripped\n return arg.replaceAll('\"', '\"\"');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlQuote (arg) {\n return '\"' + sqlEscape(arg) + '\"';\n}\n\n/**\n * @param {string} db\n * @throws {Error}\n * @returns {string}\n */\nfunction escapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.escapeDatabaseName) {\n // We at least ensure NUL is escaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), escaping casing (including Unicode?),\n // and escaping special characters depending on file system\n return CFG.escapeDatabaseName(escapeSQLiteStatement(db));\n }\n db = 'D' + escapeNameForSQLiteIdentifier(db);\n if (CFG.escapeNFDForDatabaseNames !== false) {\n // ES6 copying of regex with different flags\n db = db.replaceAll(new RegExp(expandsOnNFD, 'gu'), function (expandable) {\n return '^4' + /** @type {Integer} */ (expandable.codePointAt(0)).toString(16).padStart(6, '0');\n });\n }\n if (CFG.databaseCharacterEscapeList !== false) {\n db = db.replace(\n (CFG.databaseCharacterEscapeList\n ? new RegExp(CFG.databaseCharacterEscapeList, 'gu')\n : /[\\u0000-\\u001F\\u007F\"*/:<>?\\\\|]/gu), // eslint-disable-line no-control-regex -- Controls needed\n function (n0) {\n // eslint-disable-next-line unicorn/prefer-code-point -- Switch to `codePointAt`?\n return '^1' + n0.charCodeAt(0).toString(16).padStart(2, '0');\n }\n );\n }\n if (CFG.databaseNameLengthLimit !== false &&\n db.length >= ((CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0))) {\n throw new Error(\n 'Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' +\n db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'\n );\n }\n return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?)\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeUnmatchedSurrogates (arg) {\n return arg\n .replaceAll(/(\\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(lowSurr, 16))\n : _;\n }).replaceAll(/(\\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(highSurr, 16))\n : _;\n });\n}\n\n/**\n * Not in use internally but supplied for convenience.\n * @param {string} db\n * @returns {string}\n */\nfunction unescapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.unescapeDatabaseName) {\n // We at least ensure NUL is unescaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), unescaping casing (including Unicode?),\n // and unescaping special characters depending on file system\n return CFG.unescapeDatabaseName(unescapeSQLiteResponse(db));\n }\n\n return unescapeUnmatchedSurrogates(\n db.slice(2) // D_\n // CFG.databaseCharacterEscapeList\n .replaceAll(/(\\^+)1([0-9a-f]{2})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n // CFG.escapeNFDForDatabaseNames\n }).replaceAll(/(\\^+)4([0-9a-f]{6})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n })\n // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above)\n ).replaceAll(/(\\^+)([A-Z])/gu, (_, esc, upperCase) => {\n return esc.length % 2\n ? esc.slice(1) + upperCase\n : _;\n }).replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n }).replaceAll('^^', '^');\n}\n\n/**\n * @param {string} store\n * @returns {string}\n */\nfunction escapeStoreNameForSQL (store) {\n return sqlQuote('S' + escapeNameForSQLiteIdentifier(store));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQL (index) {\n return sqlQuote('I' + escapeNameForSQLiteIdentifier(index));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQLKeyColumn (index) {\n return 'I' + escapeNameForSQLiteIdentifier(index);\n}\n\n/**\n * @param {string} str\n * @returns {string}\n */\nfunction sqlLIKEEscape (str) {\n // https://www.sqlite.org/lang_expr.html#like\n return sqlEscape(str).replaceAll('^', '^^');\n}\n\n/**\n * @typedef {Function} AnyClass\n */\n\n// Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?)\n/**\n *\n * @param {AnyValue} obj\n * @param {AnyClass} Clss\n * @returns {boolean}\n */\nfunction instanceOf (obj, Clss) {\n return Clss[Symbol.hasInstance](obj);\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {obj is object}\n */\nfunction isObj (obj) {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isDate (obj) {\n return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isBlob (obj) {\n return isObj(obj) && 'size' in obj && typeof obj.size === 'number' &&\n 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isRegExp (obj) {\n return isObj(obj) && 'flags' in obj && typeof obj.flags === 'string' &&\n 'exec' in obj && typeof obj.exec === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isFile (obj) {\n return isObj(obj) && 'name' in obj && typeof obj.name === 'string' &&\n 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isBinary (obj) {\n return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && (\n ('slice' in obj && typeof obj.slice === 'function') || // `TypedArray` (view on buffer) or `ArrayBuffer`\n ('getFloat64' in obj && typeof obj.getFloat64 === 'function') // `DataView` (view on buffer)\n );\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isIterable (obj) {\n return isObj(obj) && Symbol.iterator in obj &&\n typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n },\n // @ts-expect-error Deliberately errs\n set [prop] (val) {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineReadonlyOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object & {\n * [key: string]: any\n * }} obj\n * @param {string[]} listeners\n * @returns {void}\n */\nfunction defineListenerProperties (obj, listeners) {\n listeners = typeof listeners === 'string' ? [listeners] : listeners;\n listeners.forEach((listener) => {\n const o = {\n get [listener] () {\n return obj['__' + listener];\n },\n /**\n * @param {AnyValue} val\n * @returns {void}\n */\n set [listener] (val) {\n obj['__' + listener] = val;\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, listener)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners)\n Object.defineProperty(obj, listener, desc);\n });\n listeners.forEach((l) => {\n obj[l] = null;\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string|string[]} props\n * @param {null|{\n * [key: string]: any\n * }} getter\n * @returns {void}\n */\nfunction defineReadonlyProperties (obj, props, getter = null) {\n props = typeof props === 'string' ? [props] : props;\n props.forEach(function (prop) {\n let o;\n if (getter && prop in getter) {\n o = getter[prop];\n } else {\n Object.defineProperty(obj, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // We must resort to this to get \"get \" as\n // the function `name` for proper IDL\n o = {\n get [prop] () {\n return this['__' + prop];\n }\n };\n }\n\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {string} item\n * @returns {boolean}\n */\nfunction isIdentifier (item) {\n // For load-time and run-time performance, we don't provide the complete regular\n // expression for identifiers, but these can be passed in, using the expressions\n // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407\n // ID_Start (includes Other_ID_Start)\n const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]';\n // ID_Continue (includes Other_ID_Continue)\n const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]';\n const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])';\n const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\\u200C\\u200D])';\n return (new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u')).test(item);\n}\n\n/**\n *\n * @param {string|string[]} keyPathString\n * @returns {boolean}\n */\nfunction isValidKeyPathString (keyPathString) {\n return typeof keyPathString === 'string' &&\n (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every((pathComponent) => {\n return isIdentifier(pathComponent);\n }));\n}\n\n/**\n *\n * @param {string|string[]} keyPath\n * @returns {boolean}\n */\nfunction isValidKeyPath (keyPath) {\n return isValidKeyPathString(keyPath) || (\n Array.isArray(keyPath) && Boolean(keyPath.length) &&\n // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html\n // See also https://heycam.github.io/webidl/#idl-DOMString\n [...keyPath].every((pathComponent) => {\n return isValidKeyPathString(pathComponent);\n })\n );\n}\n\n/**\n * @param {number} number\n * @param {\"unsigned long long\"|\"unsigned long\"} type\n * @throws {Error|TypeError}\n * @returns {number}\n */\nfunction enforceRange (number, type) {\n number = Math.floor(Number(number));\n let max, min;\n switch (type) {\n case 'unsigned long long': {\n max = 0x1FFFFFFFFFFFFF; // 2^53 - 1\n min = 0;\n break;\n }\n case 'unsigned long': {\n max = 0xFFFFFFFF; // 2^32 - 1\n min = 0;\n break;\n }\n default:\n throw new Error('Unrecognized type supplied to enforceRange');\n }\n if (!Number.isFinite(number) ||\n number > max ||\n number < min) {\n throw new TypeError('Invalid range: ' + number);\n }\n return number;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {AnyValue} v\n * @param {boolean} [treatNullAs]\n * @returns {string}\n */\nfunction convertToDOMString (v, treatNullAs) {\n return v === null && treatNullAs ? '' : ToString(v);\n}\n\n/**\n * @param {AnyValue} o\n * @returns {string}\n */\nfunction ToString (o) { // Todo: See `es-abstract/es7`\n // `String()` will not throw with Symbols\n return '' + o; // eslint-disable-line no-implicit-coercion -- Need to throw with symbols\n}\n\n/**\n *\n * @param {AnyValue} val\n * @returns {string|string[]}\n */\nfunction convertToSequenceDOMString (val) {\n // Per , converting to a sequence works with iterables\n if (isIterable(val)) { // We don't want conversion to array to convert primitives\n // Per , converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring\n return [...val].map((item) => {\n return ToString(item);\n });\n }\n return ToString(val);\n}\n\n/**\n * @param {AnyValue} v\n * @returns {v is null|undefined}\n */\nfunction isNullish (v) {\n return v === null || v === undefined;\n}\n\nexport {escapeSQLiteStatement, unescapeSQLiteResponse,\n escapeDatabaseNameForSQLAndFiles, unescapeDatabaseNameForSQLAndFiles,\n escapeStoreNameForSQL, escapeIndexNameForSQL, escapeIndexNameForSQLKeyColumn,\n sqlLIKEEscape, sqlQuote,\n instanceOf,\n isObj, isDate, isBlob, isRegExp, isFile, isBinary, isIterable,\n defineOuterInterface, defineReadonlyOuterInterface,\n defineListenerProperties, defineReadonlyProperties,\n isValidKeyPath, enforceRange,\n convertToDOMString, convertToSequenceDOMString,\n isNullish};\n","import CFG from './CFG.js';\nimport {encode as keyEncode, decode as keyDecode} from './Key.js';\n\n/**\n * Compares two keys.\n * @param {import('./Key.js').Key} first\n * @param {import('./Key.js').Key} second\n * @returns {0|1|-1}\n */\nfunction cmp (first, second) {\n const encodedKey1 = /** @type {string} */ (keyEncode(first));\n const encodedKey2 = /** @type {string} */ (keyEncode(second));\n const result = encodedKey1 > encodedKey2\n ? 1\n : encodedKey1 === encodedKey2 ? 0 : -1;\n\n if (CFG.DEBUG) {\n // verify that the keys encoded correctly\n let decodedKey1 = keyDecode(encodedKey1);\n let decodedKey2 = keyDecode(encodedKey2);\n if (typeof first === 'object') {\n first = JSON.stringify(first);\n decodedKey1 = JSON.stringify(decodedKey1);\n }\n if (typeof second === 'object') {\n second = JSON.stringify(second);\n decodedKey2 = JSON.stringify(decodedKey2);\n }\n\n // Encoding/decoding mismatches are usually due to a loss of\n // floating-point precision\n if (decodedKey1 !== first) {\n console.warn(\n first + ' was incorrectly encoded as ' + decodedKey1\n );\n }\n if (decodedKey2 !== second) {\n console.warn(\n second + ' was incorrectly encoded as ' + decodedKey2\n );\n }\n }\n\n return result;\n}\n\nexport default cmp;\n","import {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\nimport cmp from './cmp.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView\n */\n\n/**\n * @typedef {ArrayBufferView|ArrayBuffer} BufferSource\n */\n\n/**\n * @typedef {\"number\"|\"date\"|\"string\"|\"binary\"|\"array\"} KeyType\n */\n\n/**\n * @typedef {any} Value\n */\n\n/**\n * @typedef {any} Key\n * @todo Specify possible value more precisely\n */\n\n/**\n * @typedef {KeyPath[]} KeyPathArray\n */\n/**\n * @typedef {string|KeyPathArray} KeyPath\n */\n\n/**\n* @typedef {object} KeyValueObject\n* @property {KeyType|\"NaN\"|\"null\"|\"undefined\"|\"boolean\"|\"object\"|\"symbol\"|\n* \"function\"|\"bigint\"} type If not `KeyType`, indicates invalid value\n* @property {Value} [value]\n* @property {boolean} [invalid]\n* @property {string} [message]\n* @todo Specify acceptable `value` more precisely\n*/\n\n/**\n * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive\n */\n/**\n * @typedef {ValueType[]} ValueTypeArray\n */\n/**\n * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType\n */\n\n/**\n * Encodes the keys based on their types. This is required to maintain collations\n * We leave space for future keys.\n * @type {{[key: string]: Integer|string}}\n */\nconst keyTypeToEncodedChar = {\n invalid: 100,\n number: 200,\n date: 300,\n string: 400,\n binary: 500,\n array: 600\n};\nconst keyTypes = /** @type {(KeyType|\"invalid\")[]} */ (Object.keys(keyTypeToEncodedChar));\nkeyTypes.forEach((k) => {\n keyTypeToEncodedChar[k] = String.fromCodePoint(\n /** @type {number} */ (keyTypeToEncodedChar[k])\n );\n});\n\nconst encodedCharToKeyType = keyTypes.reduce((o, k) => {\n o[keyTypeToEncodedChar[k]] = k;\n return o;\n}, /** @type {{[key: string]: KeyType|\"invalid\"}} */ ({}));\n\n/**\n * The sign values for numbers, ordered from least to greatest.\n * - \"negativeInfinity\": Sorts below all other values.\n * - \"bigNegative\": Negative values less than or equal to negative one.\n * - \"smallNegative\": Negative values between negative one and zero, noninclusive.\n * - \"smallPositive\": Positive values between zero and one, including zero but not one.\n * - \"largePositive\": Positive values greater than or equal to one.\n * - \"positiveInfinity\": Sorts above all other values.\n */\nconst signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @type {{\n * [key: string]: {\n * encode: (param: any, inArray?: boolean) => string,\n * decode: (param: string, inArray?: boolean) => any\n * }\n * }}\n */\nconst types = {\n invalid: {\n /**\n * @returns {string}\n */\n encode () {\n return keyTypeToEncodedChar.invalid + '-';\n },\n /**\n * @returns {undefined}\n */\n decode () {\n return undefined;\n }\n },\n\n // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa\n // notation.\n //\n // sign: takes a value between zero and five, inclusive. Represents infinite cases\n // and the signs of both the exponent and the fractional part of the number.\n // exponent: padded to two base-32 digits, represented by the 32's compliment in the\n // \"smallPositive\" and \"bigNegative\" cases to ensure proper lexical sorting.\n // mantissa: also called the fractional part. Normed 11-digit base-32 representation.\n // Represented by the 32's compliment in the \"smallNegative\" and \"bigNegative\"\n // cases to ensure proper lexical sorting.\n number: {\n // The encode step checks for six numeric cases and generates 14-digit encoded\n // sign-exponent-mantissa strings.\n /**\n * @param {number} key\n * @returns {string}\n */\n encode (key) {\n let key32 = key === Number.MIN_VALUE\n // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some\n // Node (and Chrome) versions with `Number.MIN_VALUE` being treated\n // as 0\n // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring\n ? '0.' + '0'.repeat(214) + '2'\n : Math.abs(key).toString(32);\n // Get the index of the decimal.\n const decimalIndex = key32.indexOf('.');\n // Remove the decimal.\n key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;\n // Get the index of the first significant digit.\n const significantDigitIndex = key32.search(/[^0]/u);\n // Truncate leading zeros.\n key32 = key32.slice(significantDigitIndex);\n let sign, exponent, mantissa;\n\n // Finite cases:\n if (Number.isFinite(\n Number(key)\n )) {\n // Negative cases:\n if (key < 0) {\n // Negative exponent case:\n if (key > -1) {\n sign = signValues.indexOf('smallNegative');\n exponent = padBase32Exponent(significantDigitIndex);\n mantissa = flipBase32(padBase32Mantissa(key32));\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigNegative');\n exponent = flipBase32(padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n ));\n mantissa = flipBase32(padBase32Mantissa(key32));\n }\n // Non-negative cases:\n // Negative exponent case:\n } else if (key < 1) {\n sign = signValues.indexOf('smallPositive');\n exponent = flipBase32(padBase32Exponent(significantDigitIndex));\n mantissa = padBase32Mantissa(key32);\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigPositive');\n exponent = padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n );\n mantissa = padBase32Mantissa(key32);\n }\n // Infinite cases:\n } else {\n exponent = zeros(2);\n mantissa = zeros(11);\n sign = signValues.indexOf(\n key > 0 ? 'positiveInfinity' : 'negativeInfinity'\n );\n }\n\n return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;\n },\n // The decode step must interpret the sign, reflip values encoded as the 32's complements,\n // apply signs to the exponent and mantissa, do the base-32 power operation, and return\n // the original JavaScript number values.\n /**\n * @param {string} key\n * @returns {number}\n */\n decode (key) {\n const sign = Number(key.slice(2, 3));\n let exponent = key.slice(3, 5);\n let mantissa = key.slice(5, 16);\n\n switch (signValues[sign]) {\n case 'negativeInfinity':\n return Number.NEGATIVE_INFINITY;\n case 'positiveInfinity':\n return Number.POSITIVE_INFINITY;\n case 'bigPositive':\n return pow32(mantissa, exponent);\n case 'smallPositive':\n exponent = negate(flipBase32(exponent));\n return pow32(mantissa, exponent);\n case 'smallNegative':\n exponent = negate(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n case 'bigNegative':\n exponent = flipBase32(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n default:\n throw new Error('Invalid number.');\n }\n }\n },\n\n // Strings are encoded as JSON strings (with quotes and unicode characters escaped).\n //\n // If the strings are in an array, then some extra encoding is done to make sorting work correctly:\n // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly\n // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.\n // To do this, each character of the string is prepended with a dash (\"-\"), and a space is added to the end of the string.\n // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,\n // the indexes of each string's characters line up with each other.\n string: {\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n encode (key, inArray) {\n if (inArray) {\n // prepend each character with a dash, and append a space to the end\n key = key.replaceAll(/(.)/gu, '-$1') + ' ';\n }\n return keyTypeToEncodedChar.string + '-' + key;\n },\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n decode (key, inArray) {\n key = key.slice(2);\n if (inArray) {\n // remove the space at the end, and the dash before each character\n key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');\n }\n return key;\n }\n },\n\n // Arrays are encoded as JSON strings.\n // An extra, value is added to each array during encoding to make\n // empty arrays sort correctly.\n array: {\n /**\n * @param {ValueTypeArray} key\n * @returns {string}\n */\n encode (key) {\n const encoded = [];\n for (const [i, item] of key.entries()) {\n const encodedItem = encode(item, true); // encode the array item\n encoded[i] = encodedItem;\n }\n encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly\n return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);\n },\n /**\n * @param {string} key\n * @returns {ValueTypeArray}\n */\n decode (key) {\n const decoded = JSON.parse(key.slice(2));\n decoded.pop(); // remove the extra item\n for (let i = 0; i < decoded.length; i++) {\n const item = decoded[i];\n const decodedItem = decode(item, true); // decode the item\n decoded[i] = decodedItem;\n }\n return decoded;\n }\n },\n\n // Dates are encoded as ISO 8601 strings, in UTC time zone.\n date: {\n /**\n * @param {Date} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.date + '-' + key.toJSON();\n },\n /**\n * @param {string} key\n * @returns {Date}\n */\n decode (key) {\n return new Date(key.slice(2));\n }\n },\n binary: {\n // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)\n /**\n * @param {BufferSource} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.binary + '-' + (key.byteLength\n ? [...getCopyBytesHeldByBufferSource(key)].map(\n (b) => String(b).padStart(3, '0')\n ) // e.g., '255,005,254,000,001,033'\n : '');\n },\n /**\n * @param {string} key\n * @returns {ArrayBuffer}\n */\n decode (key) {\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const k = key.slice(2);\n const arr = k.length ? k.split(',').map((s) => Number.parseInt(s)) : [];\n const buffer = new ArrayBuffer(arr.length);\n const uint8 = new Uint8Array(buffer);\n uint8.set(arr);\n return buffer;\n }\n }\n};\n\n/**\n * Return a padded base-32 exponent value.\n * @param {number} n\n * @returns {string}\n */\nfunction padBase32Exponent (n) {\n const exp = n.toString(32);\n return (exp.length === 1) ? '0' + exp : exp;\n}\n\n/**\n * Return a padded base-32 mantissa.\n * @param {string} s\n * @returns {string}\n */\nfunction padBase32Mantissa (s) {\n return (s + zeros(11)).slice(0, 11);\n}\n\n/**\n * Flips each digit of a base-32 encoded string.\n * @param {string} encoded\n * @returns {string}\n */\nfunction flipBase32 (encoded) {\n let flipped = '';\n for (const ch of encoded) {\n flipped += (31 - Number.parseInt(ch, 32)).toString(32);\n }\n return flipped;\n}\n\n/**\n * Base-32 power function.\n * RESEARCH: This function does not precisely decode floats because it performs\n * floating point arithmetic to recover values. But can the original values be\n * recovered exactly?\n * Someone may have already figured out a good way to store JavaScript floats as\n * binary strings and convert back. Barring a better method, however, one route\n * may be to generate decimal strings that `parseFloat` decodes predictably.\n * @param {string} mantissa\n * @param {string} exponent\n * @returns {number}\n */\nfunction pow32 (mantissa, exponent) {\n const exp = Number.parseInt(exponent, 32);\n if (exp < 0) {\n return roundToPrecision(\n Number.parseInt(mantissa, 32) * (32 ** (exp - 10))\n );\n }\n if (exp < 11) {\n const whole = mantissa.slice(0, exp);\n const wholeNum = Number.parseInt(whole, 32);\n const fraction = mantissa.slice(exp);\n const fractionNum = Number.parseInt(fraction, 32) * (32 ** (exp - 11));\n return roundToPrecision(wholeNum + fractionNum);\n }\n const expansion = mantissa + zeros(exp - 11);\n return Number.parseInt(expansion, 32);\n}\n\n/**\n * @typedef {number} Float\n */\n\n/**\n * @param {Float} num\n * @param {Float} [precision]\n * @returns {Float}\n */\nfunction roundToPrecision (num, precision = 16) {\n return Number.parseFloat(num.toPrecision(precision));\n}\n\n/**\n * Returns a string of n zeros.\n * @param {number} n\n * @returns {string}\n */\nfunction zeros (n) {\n return '0'.repeat(n);\n}\n\n/**\n * Negates numeric strings.\n * @param {string} s\n * @returns {string}\n */\nfunction negate (s) {\n return '-' + s;\n}\n\n/**\n * @param {Key} key\n * @returns {KeyType|\"invalid\"}\n */\nfunction getKeyType (key) {\n if (Array.isArray(key)) { return 'array'; }\n if (util.isDate(key)) { return 'date'; }\n if (util.isBinary(key)) { return 'binary'; }\n const keyType = typeof key;\n return ['string', 'number'].includes(keyType)\n ? /** @type {\"string\"|\"number\"} */ (keyType)\n : 'invalid';\n}\n\n/**\n * Keys must be strings, numbers (besides `NaN`), Dates (if value is not\n * `NaN`), binary objects or Arrays.\n * @param {Value} input The key input\n * @param {Value[]|null|undefined} [seen] An array of already seen keys\n * @returns {KeyValueObject}\n */\nfunction convertValueToKey (input, seen) {\n return convertValueToKeyValueDecoded(input, seen, false, true);\n}\n\n/**\n* Currently not in use.\n* @param {Value} input\n* @returns {KeyValueObject}\n*/\nfunction convertValueToMultiEntryKey (input) {\n return convertValueToKeyValueDecoded(input, null, true, true);\n}\n\n/**\n *\n * @param {BufferSource} O\n * @throws {TypeError}\n * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n * @returns {Uint8Array}\n */\nfunction getCopyBytesHeldByBufferSource (O) {\n let offset = 0;\n let length = 0;\n if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot\n const arrayBuffer = O.buffer;\n if (arrayBuffer === undefined) {\n throw new TypeError(\n 'Could not copy the bytes held by a buffer source as the buffer was undefined.'\n );\n }\n offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)\n length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)\n } else {\n length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)\n }\n // const octets = new Uint8Array(input);\n // const octets = types.binary.decode(types.binary.encode(input));\n return new Uint8Array(\n // Should allow DataView\n /** @type {ArrayBuffer} */\n (('buffer' in O && O.buffer) || O),\n offset,\n length\n );\n}\n\n/**\n* Shortcut utility to avoid returning full keys from `convertValueToKey`\n* and subsequent need to process in calling code unless `fullKeys` is\n* set; may throw.\n* @param {Value} input\n* @param {Value[]|null} [seen]\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @throws {TypeError} See `getCopyBytesHeldByBufferSource`\n* @todo Document other allowable `input`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {\n seen = seen || [];\n if (seen.includes(input)) {\n return {\n type: 'array',\n invalid: true,\n message: 'An array key cannot be circular'\n };\n }\n const type = getKeyType(input);\n const ret = {type, value: input};\n switch (type) {\n case 'number': {\n if (Number.isNaN(input)) {\n // List as 'NaN' type for convenience of consumers in reporting errors\n return {type: 'NaN', invalid: true};\n }\n\n // https://github.com/w3c/IndexedDB/issues/375\n // https://github.com/w3c/IndexedDB/pull/386\n if (Object.is(input, -0)) {\n return {type, value: 0};\n }\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'string': {\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'binary': { // May throw (if detached)\n // Get a copy of the bytes held by the buffer source\n // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n const octets = getCopyBytesHeldByBufferSource(\n /** @type {BufferSource} */ (input)\n );\n return {type: 'binary', value: octets};\n } case 'array': { // May throw (from binary)\n const arr = /** @type {Array} */ (input);\n const len = arr.length;\n seen.push(input);\n\n /** @type {(KeyValueObject|Value)[]} */\n const keys = [];\n for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated\n if (!multiEntry && !Object.hasOwn(arr, i)) {\n return {type, invalid: true, message: 'Does not have own index property'};\n }\n try {\n const entry = arr[i];\n const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry\n if (key.invalid) {\n if (multiEntry) {\n continue;\n }\n return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};\n }\n if (!multiEntry ||\n (!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||\n (fullKeys && keys.every((k) => cmp(k, key) !== 0))\n ) {\n keys.push(fullKeys ? key : key.value);\n }\n } catch (err) {\n if (!multiEntry) {\n throw err;\n }\n }\n }\n return {type, value: keys};\n } case 'date': {\n const date = /** @type {Date} */ (input);\n if (!Number.isNaN(date.getTime())) {\n return fullKeys\n ? {type, value: date.getTime()}\n : {type, value: new Date(date.getTime())};\n }\n return {type, invalid: true, message: 'Not a valid date'};\n // Falls through\n } case 'invalid': default: {\n // Other `typeof` types which are not valid keys:\n // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'\n const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors\n return {type, invalid: true, message: 'Not a valid key; type ' + type};\n }\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [fullKeys]\n * @returns {KeyValueObject}\n * @todo Document other allowable `key`?\n */\nfunction convertValueToMultiEntryKeyDecoded (key, fullKeys) {\n return convertValueToKeyValueDecoded(key, null, true, fullKeys);\n}\n\n/**\n* An internal utility.\n* @param {Value} input\n* @param {Value[]|null|undefined} [seen]\n* @throws {DOMException} `DataError`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyRethrowingAndIfInvalid (input, seen) {\n const key = convertValueToKey(input, seen);\n if (key.invalid) {\n throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);\n }\n return key;\n}\n\n/**\n *\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} multiEntry\n * @returns {KeyValueObject|KeyPathEvaluateValue}\n * @todo Document other possible return?\n */\nfunction extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {\n return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);\n}\n/**\n* Not currently in use.\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} multiEntry\n* @returns {KeyPathEvaluateValue}\n*/\nfunction evaluateKeyPathOnValue (value, keyPath, multiEntry) {\n return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);\n}\n\n/**\n* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)\n* or `{invalid: true}` (e.g., `NaN`).\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @returns {KeyValueObject|KeyPathEvaluateValue}\n* @todo Document other possible return?\n*/\nfunction extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {\n const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);\n if (r.failure) {\n return r;\n }\n if (!multiEntry) {\n return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);\n }\n return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);\n}\n\n/**\n * Unused?\n * @typedef {object} KeyPathEvaluateFailure\n * @property {boolean} failure\n */\n\n/**\n * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray\n */\n\n/**\n * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue\n */\n\n/**\n * @typedef {object} KeyPathEvaluateValue\n * @property {KeyPathEvaluateValueValue} [value]\n * @property {boolean} [failure]\n */\n\n/**\n * Returns the value of an inline key based on a key path (wrapped in an\n * object with key `value`) or `{failure: true}`\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} [multiEntry]\n * @param {boolean} [fullKeys]\n * @returns {KeyPathEvaluateValue}\n */\nfunction evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {\n if (Array.isArray(keyPath)) {\n /** @type {KeyPathEvaluateValueValueArray} */\n const result = [];\n return keyPath.some((item) => {\n const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);\n if (key.failure) {\n return true;\n }\n result.push(key.value);\n return false;\n })\n ? {failure: true}\n : {value: result};\n }\n if (keyPath === '') {\n return {value};\n }\n const identifiers = keyPath.split('.');\n return identifiers.some((idntfr) => {\n if (idntfr === 'length' && (\n typeof value === 'string' || Array.isArray(value)\n )) {\n value = value.length;\n } else if (util.isBlob(value)) {\n switch (idntfr) {\n case 'size': case 'type':\n value = /** @type {Blob} */ (value)[idntfr];\n break;\n }\n } else if (util.isFile(value)) {\n switch (idntfr) {\n case 'name': case 'lastModified':\n value = /** @type {File} */ (value)[idntfr];\n break;\n case 'lastModifiedDate':\n value = new Date(/** @type {File} */ (value).lastModified);\n break;\n }\n } else if (!util.isObj(value) || !Object.hasOwn(value, idntfr)) {\n return true;\n } else {\n value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */ (\n value\n )[idntfr];\n return value === undefined;\n }\n return false;\n })\n ? {failure: true}\n : {value};\n}\n\n/**\n * Sets the inline key value.\n * @param {{[key: string]: AnyValue}} value\n * @param {Key} key\n * @param {string} keyPath\n * @returns {void}\n */\nfunction injectKeyIntoValueUsingKeyPath (value, key, keyPath) {\n const identifiers = keyPath.split('.');\n const last = identifiers.pop();\n identifiers.forEach((identifier) => {\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n value[identifier] = {};\n }\n value = value[identifier];\n });\n value[/** @type {string} */ (last)] = key; // key is already a `keyValue` in our processing so no need to convert\n}\n\n/**\n *\n * @param {Value} value\n * @param {string} keyPath\n * @see https://github.com/w3c/IndexedDB/pull/146\n * @returns {boolean}\n */\nfunction checkKeyCouldBeInjectedIntoValue (value, keyPath) {\n const identifiers = keyPath.split('.');\n identifiers.pop();\n for (const identifier of identifiers) {\n if (!util.isObj(value)) {\n return false;\n }\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n return true;\n }\n value = /** @type {{[key: string]: Value}} */ (value)[identifier];\n }\n return util.isObj(value);\n}\n\n/**\n *\n * @param {Key} key\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range\n * @param {boolean} [checkCached]\n * @returns {boolean}\n */\nfunction isKeyInRange (key, range, checkCached) {\n let lowerMatch = range.lower === undefined;\n let upperMatch = range.upper === undefined;\n const encodedKey = encode(key, true);\n const lower = checkCached ? range.__lowerCached : encode(range.lower, true);\n const upper = checkCached ? range.__upperCached : encode(range.upper, true);\n\n if (!lowerMatch && (\n (range.lowerOpen &&\n encodedKey !== null && lower !== null && encodedKey > lower) ||\n (!range.lowerOpen && (\n (!encodedKey && !lower) ||\n (encodedKey !== null && lower !== null && encodedKey >= lower))\n )\n )) {\n lowerMatch = true;\n }\n if (!upperMatch && (\n (range.upperOpen &&\n encodedKey !== null && upper !== null && encodedKey < upper) ||\n (!range.upperOpen && (\n (!encodedKey && !upper) ||\n (encodedKey !== null && upper !== null && encodedKey <= upper))\n )\n )) {\n upperMatch = true;\n }\n\n return lowerMatch && upperMatch;\n}\n\n/**\n * Determines whether an index entry matches a multi-entry key value.\n * @param {string} encodedEntry The entry value (already encoded)\n * @param {string} encodedKey The full index key (already encoded)\n * @returns {boolean}\n */\nfunction isMultiEntryMatch (encodedEntry, encodedKey) {\n const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];\n\n if (keyType === 'array') {\n return encodedKey.indexOf(encodedEntry) > 1;\n }\n return encodedKey === encodedEntry;\n}\n\n/**\n *\n * @param {Key} keyEntry\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range\n * @returns {Key[]}\n */\nfunction findMultiEntryMatches (keyEntry, range) {\n const matches = [];\n\n if (Array.isArray(keyEntry)) {\n for (let key of keyEntry) {\n if (Array.isArray(key)) {\n if (range && range.lower === range.upper) {\n continue;\n }\n if (key.length === 1) {\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n key = key[0];\n } else {\n const nested = findMultiEntryMatches(key, range);\n if (nested.length > 0) {\n matches.push(key);\n }\n continue;\n }\n }\n\n if (util.isNullish(range) || isKeyInRange(key, range, true)) {\n matches.push(key);\n }\n }\n } else if (util.isNullish(range) || isKeyInRange(keyEntry, range, true)) {\n matches.push(keyEntry);\n }\n return matches;\n}\n\n/**\n* Not currently in use but keeping for spec parity.\n* @param {Key} key\n* @throws {Error} Upon a \"bad key\"\n* @returns {ValueType}\n*/\nfunction convertKeyToValue (key) {\n const {type, value} = key;\n switch (type) {\n case 'number': case 'string': {\n return value;\n } case 'array': {\n const array = [];\n const len = value.length;\n let index = 0;\n while (index < len) {\n const entry = convertKeyToValue(value[index]);\n array[index] = entry;\n index++;\n }\n return array;\n } case 'date': {\n return new Date(value);\n } case 'binary': {\n const len = value.length;\n const buffer = new ArrayBuffer(len);\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);\n uint8.set(value);\n return buffer;\n } case 'invalid': default:\n throw new Error('Bad key');\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {string|null}\n */\nfunction encode (key, inArray) {\n // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation\n if (key === undefined) {\n return null;\n }\n // array, date, number, string, binary (should already have detected \"invalid\")\n return types[getKeyType(key)].encode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @throws {Error} Invalid number\n * @returns {undefined|ValueType}\n */\nfunction decode (key, inArray) {\n if (typeof key !== 'string') {\n return undefined;\n }\n return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {undefined|ValueType}\n */\nfunction roundTrip (key, inArray) {\n return decode(encode(key, inArray), inArray);\n}\n\nconst MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback CurrentNumberCallback\n * @param {Integer} cn The current number\n * @returns {void}\n */\n\n/**\n* @callback SQLFailureCallback\n* @param {DOMException|Error} exception\n* @returns {void}\n*/\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {CurrentNumberCallback} func\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction getCurrentNumber (tx, store, func, sqlFailCb) {\n tx.executeSql('SELECT \"currNum\" FROM __sys__ WHERE \"name\" = ?', [\n util.escapeSQLiteStatement(store.__currentName)\n ], function (tx, data) {\n if (data.rows.length !== 1) {\n func(1);\n } else {\n func(data.rows.item(0).currNum);\n }\n }, function (tx, error) {\n sqlFailCb(createDOMException(\n 'DataError',\n 'Could not get the auto increment value for key',\n error\n ));\n return false;\n });\n}\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction assignCurrentNumber (tx, store, num, successCb, failCb) {\n const sql = 'UPDATE __sys__ SET \"currNum\" = ? WHERE \"name\" = ?';\n const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n tx.executeSql(sql, sqlValues, function () {\n successCb(num);\n }, function (tx, err) {\n failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));\n return false;\n });\n}\n\n/**\n * Bump up the auto-inc counter if the key path-resolved value is valid\n * (greater than old value and >=1) OR if a manually passed in key is\n * valid (numeric and >= 1) and >= any primaryKey.\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction setCurrentNumber (tx, store, num, successCb, failCb) {\n num = num === MAX_ALLOWED_CURRENT_NUMBER\n ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner\n : num + 1;\n return assignCurrentNumber(tx, store, num, successCb, failCb);\n}\n\n/**\n * @callback KeyForStoreCallback\n * @param {\"failure\"|null} arg1\n * @param {Integer} [arg2]\n * @param {Integer} [arg3]\n * @returns {void}\n */\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {KeyForStoreCallback} cb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction generateKeyForStore (tx, store, cb, sqlFailCb) {\n getCurrentNumber(tx, store, function (key) {\n if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See )\n cb('failure');\n return;\n }\n // Increment current number by 1 (we cannot leverage SQLite's\n // autoincrement (and decrement when not needed), as decrementing\n // will be overwritten/ignored upon the next insert)\n setCurrentNumber(\n tx, store, key,\n function () {\n cb(null, key, key);\n },\n sqlFailCb\n );\n }, sqlFailCb);\n}\n\n// Fractional or numbers exceeding the max do not get changed in the result\n// per https://github.com/w3c/IndexedDB/issues/147\n// so we do not return a key\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Key} key\n * @param {(num?: Integer) => void} successCb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {\n // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers\n // (or numbers larger than the max) are now to have the explicit effect of\n // setting the current number (up to the max), so we do not optimize them\n // out here\n if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number\n // Auto-increment attempted with a bad key;\n // we are not to change the current number, but the steps don't call for failure\n // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1\n successCb();\n } else {\n // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher\n // to determine which to use and whether to update the current number\n getCurrentNumber(tx, store, function (cn) {\n const value = Math.floor(\n Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)\n );\n const useNewKeyForAutoInc = value >= cn;\n if (useNewKeyForAutoInc) {\n setCurrentNumber(tx, store, value, function () {\n successCb(cn); // Supply old current number in case needs to be reverted\n }, sqlFailCb);\n } else { // Not updated\n successCb();\n }\n }, sqlFailCb);\n }\n}\n\nexport {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,\n convertValueToMultiEntryKeyDecoded,\n convertValueToKey,\n convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,\n extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,\n extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,\n isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,\n assignCurrentNumber,\n generateKeyForStore, possiblyUpdateKeyGenerator};\n"],"names":["map","CFG","createNativeDOMException","name","message","DOMException","prototype","constructor","val","test","TypeError","forEach","prop","validator","Array","isArray","_prop2","_slicedToArray","Object","defineProperty","get","set","codes","IndexSizeError","HierarchyRequestError","WrongDocumentError","InvalidCharacterError","NoModificationAllowedError","NotFoundError","NotSupportedError","InUseAttributeError","InvalidStateError","SyntaxError","InvalidModificationError","NamespaceError","InvalidAccessError","TypeMismatchError","SecurityError","NetworkError","AbortError","URLMismatchError","QuotaExceededError","TimeoutError","InvalidNodeTypeError","DataCloneError","EncodingError","NotReadableError","UnknownError","ConstraintError","DataError","TransactionInactiveError","ReadOnlyError","VersionError","OperationError","NotAllowedError","legacyCodes","INDEX_SIZE_ERR","DOMSTRING_SIZE_ERR","HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR","NO_DATA_ALLOWED_ERR","NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR","VALIDATION_ERR","TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR","ShimNonNativeDOMException","this","Symbol","toStringTag","_code","_name","_message","undefined","configurable","enumerable","writable","value","DummyDOMException","create","Error","keys","codeName","createNonNativeDOMExceptionClass","logError","error","DEBUG","msg","_typeof","method","console","trace","obj","useNativeDOMException","err","createDOMException","createNonNativeDOMException","escapeSQLiteStatement","arg","replaceAll","_","unmatchedHighSurrogate","precedingLow","unmatchedLowSurrogate","codePointAt","toString","padStart","escapeUnmatchedSurrogates","isObj","isNullish","v","cmp","first","second","encodedKey1","keyEncode","encodedKey2","result","decodedKey1","keyDecode","decodedKey2","JSON","stringify","warn","keyTypeToEncodedChar","invalid","number","date","string","binary","array","keyTypes","k","String","fromCodePoint","encodedCharToKeyType","reduce","o","signValues","types","encode","decode","key","sign","exponent","mantissa","key32","Number","MIN_VALUE","repeat","Math","abs","decimalIndex","indexOf","significantDigitIndex","replace","search","slice","isFinite","padBase32Exponent","flipBase32","padBase32Mantissa","length","zeros","NEGATIVE_INFINITY","POSITIVE_INFINITY","pow32","negate","inArray","_step","encoded","_iterator","_createForOfIteratorHelper","entries","s","n","done","_step$value","i","encodedItem","e","f","push","decoded","parse","pop","decodedItem","toJSON","Date","byteLength","_toConsumableArray","getCopyBytesHeldByBufferSource","b","arr","split","parseInt","buffer","ArrayBuffer","Uint8Array","exp","_step2","flipped","_iterator2","ch","roundToPrecision","pow","whole","wholeNum","fraction","expansion","num","precision","arguments","parseFloat","toPrecision","getKeyType","getDate","util","getFloat64","keyType","includes","convertValueToKey","input","seen","convertValueToKeyValueDecoded","O","offset","isView","byteOffset","multiEntry","fullKeys","type","ret","isNaN","is","len","_ret","_loop","hasOwn","every","getTime","convertValueToMultiEntryKeyDecoded","extractKeyValueDecodedFromValueUsingKeyPath","keyPath","r","evaluateKeyPathOnValueToDecodedValue","failure","some","item","idntfr","size","lastModified","isKeyInRange","range","checkCached","lowerMatch","lower","upperMatch","upper","encodedKey","__lowerCached","__upperCached","lowerOpen","upperOpen","MAX_ALLOWED_CURRENT_NUMBER","getCurrentNumber","tx","store","func","sqlFailCb","executeSql","__currentName","data","rows","currNum","assignCurrentNumber","successCb","failCb","sql","sqlValues","log","setCurrentNumber","identifiers","_step3","_iterator3","identifier","convertKeyToValue","index","entry","findMultiEntryMatches","keyEntry","matches","_step4","_iterator4","cb","last","encodedEntry","cn","floor","min"],"mappings":";84EAuDA,IAAMA,EAAM,CAAA,EAENC,EAAmC,CAAA,ECjDzC,SAASC,EAA0BC,EAAMC,GAErC,OAAO,IAAIC,aAAaC,UAAUC,YAC9BH,EACAD,GAAQ,eAEhB,CDsDC,CAEG,QAIA,yBAMA,WAOA,iBAIA,cAIA,wBAOA,iBAEA,oBAMA,cAGA,gBAcA,MAWA,kBAIA,mBAOA,KAMA,mBAKA,uBASA,qBAEA,uBAKA,8BAEA,0BAIA,4BAIA,qBAEA,CACI,iBAMA,SAACK,GACG,IAAM,iVAAkDC,KAC7BD,GAEvB,MAAM,IAAIE,UACN,wGAIZ,GAMJ,sBACA,mBACA,sBAGA,iBACA,WACA,aAEA,iBACDC,SAAQ,SAACC,GAER,IAAIC,EACJ,GAAIC,MAAMC,QAAQH,GAAO,CAAA,IACGI,EAAAC,EAAJL,EAAI,GAAvBA,EAAII,EAAA,GAAEH,EAASG,EAAA,EACpB,CACAE,OAAOC,eAAelB,EAAKW,EAAM,CAC7BQ,IAAG,WACC,OAAOpB,EAAIY,EACd,EACDS,IAAAA,SAAKb,GACGK,GACAA,EAAUL,GAEdR,EAAIY,GAAQJ,CAChB,GAER,IC9MA,IAAMc,EAAQ,CACVC,eAAgB,EAChBC,sBAAuB,EACvBC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G,EAAW1G,QAAQ+I,GAAgB,EAEvCrC,IAAeqC,CAC1B,+BAoPA,SAAqC9B,EAAIC,EAAO7H,EAAKsI,EAAWP,GAKzC,iBAAR/H,GAAoBA,EAAM,EAIjCsI,IAIAX,EAAiBC,EAAIC,GAAO,SAAU8B,GAClC,IAAM5N,EAAQyE,KAAKoJ,MACfpJ,KAAKqJ,IAAI7J,EAAK0H,IAEU3L,GAAS4N,EAEjChB,EAAiBf,EAAIC,EAAO9L,GAAO,WAC/BuM,EAAUqB,EACb,GAAE5B,GAEHO,GAEP,GAAEP,EAEX,cAlKA,SAAoB/H,EAAK0B,GACrB,OAAO3B,EAAOD,EAAOE,EAAK0B,GAAUA,EACxC"} \ No newline at end of file +{"version":3,"file":"indexeddbshim-Key.min.js","sources":["../src/CFG.js","../src/DOMException.js","../src/util.js","../src/cmp.js","../src/Key.js"],"sourcesContent":["/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n/**\n * @typedef {T[keyof T]} ValueOf\n * @template T\n */\n/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n\n/**\n * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi\n */\n\n/**\n * @typedef {{\n * DEBUG: boolean,\n * cacheDatabaseInstances: boolean,\n * autoName: boolean,\n * fullIDLSupport: boolean,\n * checkOrigin: boolean,\n * cursorPreloadPackSize: number,\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string,\n * registerSCA: (\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset,\n * avoidAutoShim: boolean,\n * win: {\n * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default\n * },\n * DEFAULT_DB_SIZE: number,\n * useSQLiteIndexes: boolean,\n * fs: FSApi,\n * addNonIDBGlobals: boolean,\n * replaceNonIDBGlobals: boolean,\n * escapeDatabaseName: (name: string) => string,\n * unescapeDatabaseName: (name: string) => string,\n * databaseCharacterEscapeList: string|false,\n * databaseNameLengthLimit: number|false,\n * escapeNFDForDatabaseNames: boolean,\n * addSQLiteExtension: boolean,\n * memoryDatabase: string,\n * deleteDatabaseFiles: boolean,\n * databaseBasePath: string,\n * sysDatabaseBasePath: string,\n * sqlBusyTimeout: number,\n * sqlTrace: () => void,\n * sqlProfile: () => void,\n * createIndexes: boolean\n * }} ConfigValues\n */\n\n/**\n * @typedef {ValueOf} ConfigValue\n */\n\n/** @type {{[key: string]: ConfigValue}} */\nconst map = {};\n\nconst CFG = /** @type {ConfigValues} */ ({});\n\n/**\n * @typedef {keyof ConfigValues} KeyofConfigValues\n */\n\n/**\n * @typedef {KeyofConfigValues[]} Config\n */\n\n/** @type {Config} */\n([\n // Boolean for verbose reporting\n 'DEBUG', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean (effectively defaults to true) on whether to cache WebSQL\n // `openDatabase` instances\n 'cacheDatabaseInstances',\n\n // Boolean on whether to auto-name databases (based on an\n // auto-increment) when the empty string is supplied; useful with\n // `memoryDatabase`; defaults to `false` which means the empty string\n // will be used as the (valid) database name\n 'autoName',\n\n // Determines whether the slow-performing `Object.setPrototypeOf`\n // calls required for full WebIDL compliance will be used. Probably\n // only needed for testing or environments where full introspection\n // on class relationships is required; see\n // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean on whether to perform origin checks in `IDBFactory` methods\n // Effectively defaults to `true` (must be set to `false` to cancel checks)\n 'checkOrigin',\n\n // Used by `IDBCursor` continue methods for number of records to cache;\n // Defaults to 100\n 'cursorPreloadPackSize',\n\n // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);\n // or just use the Unicode builds which invoke this method\n // automatically using the large, fully spec-compliant, regular\n // expression strings of `src/UnicodeIdentifiers.js`)\n // In the non-Unicode builds, defaults to /[$A-Z_a-z]/\n 'UnicodeIDStart',\n // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/\n 'UnicodeIDContinue',\n\n // Used by SCA.js for optional restructuring of typeson-registry\n // Structured Cloning Algorithm; should only be needed for ensuring data\n // created in 3.* versions of IndexedDBShim continue to work; see the\n // library `typeson-registry-sca-reverter` to get a function to do this\n 'registerSCA',\n\n // BROWSER-SPECIFIC CONFIG\n 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is\n // missing or poor support is known (non-Chrome Android or\n // non-Safari iOS9), the shim will be auto-applied without\n // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing\n // the shim for such cases.\n\n // -----------SQL CONFIG----------\n // Object (`window` in the browser) on which there may be an\n // `openDatabase` method (if any) for WebSQL. (The browser\n // throws if attempting to call `openDatabase` without the window\n // so this is why the config doesn't just allow the function.)\n // Defaults to `window` or `self` in browser builds or\n // a singleton object with the `openDatabase` method set to\n // the \"websql\" package in Node.\n 'win',\n\n // For internal `openDatabase` calls made by `IDBFactory` methods;\n // per the WebSQL spec, \"User agents are expected to use the display name\n // and the estimated database size to optimize the user experience.\n // For example, a user agent could use the estimated size to suggest an\n // initial quota to the user. This allows a site that is aware that it\n // will try to use hundreds of megabytes to declare this upfront, instead\n // of the user agent prompting the user for permission to increase the\n // quota every five megabytes.\"\n // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari\n 'DEFAULT_DB_SIZE',\n // Whether to create indexes on SQLite tables (and also whether to try\n // dropping)\n // Effectively defaults to `false` (ignored unless `true`)\n 'useSQLiteIndexes',\n\n // NODE-IMPINGING SETTINGS (created for sake of limitations in Node\n // or desktop file system implementation but applied by default in\n // browser for parity)\n\n // File system module with `unlink` to remove deleted database files\n 'fs',\n\n // Used when setting global shims to determine whether to try to add\n // other globals shimmed by the library (`ShimDOMException`,\n // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'addNonIDBGlobals',\n // Used when setting global shims to determine whether to try to overwrite\n // other globals shimmed by the library (`DOMException`, `DOMStringList`,\n // `Event`, `CustomEvent`, `EventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'replaceNonIDBGlobals',\n\n // Overcoming limitations with node-sqlite3/storing database name on\n // file systems\n // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n // Defaults to prefixing database with `D_`, escaping\n // `databaseCharacterEscapeList`, escaping NUL, and\n // escaping upper case letters, as well as enforcing\n // `databaseNameLengthLimit`\n 'escapeDatabaseName',\n // Not used internally; usable as a convenience method\n 'unescapeDatabaseName',\n\n // Defaults to global regex representing the following\n // (characters nevertheless commonly reserved in modern,\n // Unicode-supporting systems): 0x00-0x1F 0x7F \" * / : < > ? \\ |\n 'databaseCharacterEscapeList',\n // Defaults to 254 (shortest typical modern file length limit)\n 'databaseNameLengthLimit',\n\n // Boolean defaulting to true on whether to escape NFD-escaping\n // characters to avoid clashes on MacOS which performs NFD on files\n 'escapeNFDForDatabaseNames',\n\n // Boolean on whether to add the `.sqlite` extension to file names;\n // defaults to `true`\n 'addSQLiteExtension',\n // Various types of in-memory databases that can auto-delete\n [\n 'memoryDatabase',\n /**\n * @param {string} val\n * @throws {TypeError}\n * @returns {void}\n */\n (val) => {\n if (!(/^(?::memory:|file::memory:(\\?[^#]*)?(#.*)?)?$/u).test(\n /** @type {string} */ (val)\n )) {\n throw new TypeError(\n '`memoryDatabase` must be the empty string, \":memory:\", or a ' +\n '\"file::memory:[?queryString][#hash] URL\".'\n );\n }\n }\n ],\n\n // NODE-SPECIFIC CONFIG\n // Boolean on whether to delete the database file itself after\n // `deleteDatabase`; defaults to `true` as the database will be empty\n 'deleteDatabaseFiles',\n 'databaseBasePath',\n 'sysDatabaseBasePath',\n\n // NODE-SPECIFIC WEBSQL CONFIG\n 'sqlBusyTimeout', // Defaults to 1000\n 'sqlTrace', // Callback not used by default\n 'sqlProfile', // Callback not used by default\n\n 'createIndexes'\n]).forEach((prop) => {\n /** @type {(val: any) => void} */\n let validator;\n if (Array.isArray(prop)) {\n [prop, validator] = prop;\n }\n Object.defineProperty(CFG, prop, {\n get () {\n return map[prop];\n },\n set (val) {\n if (validator) {\n validator(val);\n }\n map[prop] = val;\n }\n });\n});\n\nexport default CFG;\n","import CFG from './CFG.js';\n\n/**\n * Creates a native DOMException, for browsers that support it.\n * @param {string} name\n * @param {string} message\n * @returns {DOMException}\n */\nfunction createNativeDOMException (name, message) {\n // @ts-expect-error It's ok\n return new DOMException.prototype.constructor(\n message,\n name || 'DOMException'\n );\n}\n\n// From web-platform-tests testharness.js name_code_map (though not in new spec)\n\n/**\n * @typedef {\"IndexSizeError\"|\"HierarchyRequestError\"|\"WrongDocumentError\"|\n * \"InvalidCharacterError\"|\"NoModificationAllowedError\"|\"NotFoundError\"|\n * \"NotSupportedError\"|\"InUseAttributeError\"|\"InvalidStateError\"|\n * \"SyntaxError\"|\"InvalidModificationError\"|\"NamespaceError\"|\n * \"InvalidAccessError\"|\"TypeMismatchError\"|\"SecurityError\"|\n * \"NetworkError\"|\"AbortError\"|\"URLMismatchError\"|\"QuotaExceededError\"|\n * \"TimeoutError\"|\"InvalidNodeTypeError\"|\"DataCloneError\"|\"EncodingError\"|\n * \"NotReadableError\"|\"UnknownError\"|\"ConstraintError\"|\"DataError\"|\n * \"TransactionInactiveError\"|\"ReadOnlyError\"|\"VersionError\"|\n * \"OperationError\"|\"NotAllowedError\"} Code\n */\n\nconst codes = {\n IndexSizeError: 1,\n HierarchyRequestError: 3,\n WrongDocumentError: 4,\n InvalidCharacterError: 5,\n NoModificationAllowedError: 7,\n NotFoundError: 8,\n NotSupportedError: 9,\n InUseAttributeError: 10,\n InvalidStateError: 11,\n SyntaxError: 12,\n InvalidModificationError: 13,\n NamespaceError: 14,\n InvalidAccessError: 15,\n TypeMismatchError: 17,\n SecurityError: 18,\n NetworkError: 19,\n AbortError: 20,\n URLMismatchError: 21,\n QuotaExceededError: 22,\n TimeoutError: 23,\n InvalidNodeTypeError: 24,\n DataCloneError: 25,\n\n EncodingError: 0,\n NotReadableError: 0,\n UnknownError: 0,\n ConstraintError: 0,\n DataError: 0,\n TransactionInactiveError: 0,\n ReadOnlyError: 0,\n VersionError: 0,\n OperationError: 0,\n NotAllowedError: 0\n};\n\n/**\n * @typedef {\"INDEX_SIZE_ERR\"|\"DOMSTRING_SIZE_ERR\"|\"HIERARCHY_REQUEST_ERR\"|\n * \"WRONG_DOCUMENT_ERR\"|\"INVALID_CHARACTER_ERR\"|\"NO_DATA_ALLOWED_ERR\"|\n * \"NO_MODIFICATION_ALLOWED_ERR\"|\"NOT_FOUND_ERR\"|\"NOT_SUPPORTED_ERR\"|\n * \"INUSE_ATTRIBUTE_ERR\"|\"INVALID_STATE_ERR\"|\"SYNTAX_ERR\"|\n * \"INVALID_MODIFICATION_ERR\"|\"NAMESPACE_ERR\"|\"INVALID_ACCESS_ERR\"|\n * \"VALIDATION_ERR\"|\"TYPE_MISMATCH_ERR\"|\"SECURITY_ERR\"|\"NETWORK_ERR\"|\n * \"ABORT_ERR\"|\"URL_MISMATCH_ERR\"|\"QUOTA_EXCEEDED_ERR\"|\"TIMEOUT_ERR\"|\n * \"INVALID_NODE_TYPE_ERR\"|\"DATA_CLONE_ERR\"} LegacyCode\n */\n\nconst legacyCodes = {\n INDEX_SIZE_ERR: 1,\n DOMSTRING_SIZE_ERR: 2,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n INVALID_CHARACTER_ERR: 5,\n NO_DATA_ALLOWED_ERR: 6,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INUSE_ATTRIBUTE_ERR: 10,\n INVALID_STATE_ERR: 11,\n SYNTAX_ERR: 12,\n INVALID_MODIFICATION_ERR: 13,\n NAMESPACE_ERR: 14,\n INVALID_ACCESS_ERR: 15,\n VALIDATION_ERR: 16,\n TYPE_MISMATCH_ERR: 17,\n SECURITY_ERR: 18,\n NETWORK_ERR: 19,\n ABORT_ERR: 20,\n URL_MISMATCH_ERR: 21,\n QUOTA_EXCEEDED_ERR: 22,\n TIMEOUT_ERR: 23,\n INVALID_NODE_TYPE_ERR: 24,\n DATA_CLONE_ERR: 25\n};\n\n/**\n *\n * @returns {typeof DOMException}\n */\nfunction createNonNativeDOMExceptionClass () {\n /**\n * @param {string|undefined} message\n * @param {Code|LegacyCode} name\n * @returns {void}\n */\n function DOMException (message, name) {\n // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message\n this[Symbol.toStringTag] = 'DOMException';\n this._code = name in codes\n ? codes[/** @type {Code} */ (name)]\n : (legacyCodes[/** @type {LegacyCode} */ (name)] || 0);\n this._name = name || 'Error';\n // We avoid `String()` in this next line as it converts Symbols\n this._message = message === undefined ? '' : ('' + message); // eslint-disable-line no-implicit-coercion -- Don't convert symbols\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._code\n });\n if (name !== undefined) {\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._name\n });\n }\n if (message !== undefined) {\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: this._message\n });\n }\n }\n\n // Necessary for W3C tests which complains if `DOMException` has properties on its \"own\" prototype\n\n // class DummyDOMException extends Error {}; // Sometimes causing problems in Node\n /* eslint-disable func-name-matching -- See above */\n /**\n * @class\n */\n const DummyDOMException = function DOMException () { /* */ };\n /* eslint-enable func-name-matching -- See above */\n DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing\n /** @type {const} */ (['name', 'message']).forEach((prop) => {\n Object.defineProperty(DummyDOMException.prototype, prop, {\n enumerable: true,\n /**\n * @this {DOMException}\n * @returns {string}\n */\n get () {\n if (!(this instanceof DOMException ||\n // @ts-expect-error Just checking\n this instanceof DummyDOMException ||\n // @ts-expect-error Just checking\n this instanceof Error)) {\n throw new TypeError('Illegal invocation');\n }\n return this[prop === 'name' ? '_name' : '_message'];\n }\n });\n });\n // DOMException uses the same `toString` as `Error`\n Object.defineProperty(DummyDOMException.prototype, 'code', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n // @ts-expect-error It's ok\n DOMException.prototype = new DummyDOMException();\n\n DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';\n Object.defineProperty(DOMException, 'prototype', {\n writable: false\n });\n\n const keys = Object.keys(codes);\n\n /** @type {(keyof codes)[]} */ (keys).forEach(\n (codeName) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n }\n );\n /** @type {(keyof legacyCodes)[]} */ (Object.keys(legacyCodes)).forEach((\n codeName\n ) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n });\n Object.defineProperty(DOMException.prototype, 'constructor', {\n writable: true,\n configurable: true,\n enumerable: false,\n value: DOMException\n });\n\n // @ts-expect-error We don't need all its properties\n return DOMException;\n}\n\nconst ShimNonNativeDOMException = createNonNativeDOMExceptionClass();\n\n/**\n * Creates a generic Error object.\n * @param {string} name\n * @param {string} message\n * @returns {Error}\n */\nfunction createNonNativeDOMException (name, message) {\n return new ShimNonNativeDOMException(message, name);\n}\n\n/**\n * @typedef {{\n * message: string|DOMString\n * }} ErrorLike\n */\n\n/**\n * Logs detailed error information to the console.\n * @param {string} name\n * @param {string} message\n * @param {string|ErrorLike|boolean|null} [error]\n * @returns {void}\n */\nfunction logError (name, message, error) {\n if (CFG.DEBUG) {\n const msg = error && typeof error === 'object' && error.message\n ? error.message\n : /** @type {string} */ (error);\n\n const method = typeof (console.error) === 'function' ? 'error' : 'log';\n console[method](name + ': ' + message + '. ' + (msg || ''));\n if (console.trace) { console.trace(); }\n }\n}\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @param {ArbitraryValue} obj\n * @returns {boolean}\n */\nfunction isErrorOrDOMErrorOrDOMException (obj) {\n return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser\n typeof obj.name === 'string';\n}\n\n/**\n * Finds the error argument. This is useful because some WebSQL callbacks\n * pass the error as the first argument, and some pass it as the second\n * argument.\n * @param {(Error|{message?: string, name?: string}|any)[]} args\n * @returns {Error|DOMException|undefined}\n */\nfunction findError (args) {\n let err;\n if (args) {\n if (args.length === 1) {\n return args[0];\n }\n for (const arg of args) {\n if (isErrorOrDOMErrorOrDOMException(arg)) {\n return arg;\n }\n if (arg && typeof arg.message === 'string') {\n err = arg;\n }\n }\n }\n return err;\n}\n\n/**\n *\n * @param {SQLError} webSQLErr\n * @returns {(DOMException|Error) & {\n * sqlError: SQLError\n * }}\n */\nfunction webSQLErrback (webSQLErr) {\n let name, message;\n switch (webSQLErr.code) {\n case 4: { // SQLError.QUOTA_ERR\n name = 'QuotaExceededError';\n message = 'The operation failed because there was not enough ' +\n 'remaining storage space, or the storage quota was reached ' +\n 'and the user declined to give more space to the database.';\n break;\n }\n /*\n // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`?\n case 7: { // SQLError.TIMEOUT_ERR\n // All transaction errors abort later, so no need to mark inactive\n name = 'TransactionInactiveError';\n message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).';\n break;\n }\n */\n default: {\n name = 'UnknownError';\n message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.';\n break;\n }\n }\n message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')';\n const err =\n /**\n * @type {(Error | DOMException) & {\n * sqlError: SQLError\n * }}\n */\n (createDOMException(name, message));\n err.sqlError = webSQLErr;\n return err;\n}\n\nlet test, useNativeDOMException = false;\n\n// Test whether we can use the browser's native DOMException class\ntry {\n test = createNativeDOMException('test name', 'test message');\n if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {\n // Native DOMException works as expected\n useNativeDOMException = true;\n }\n// eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n} catch (err) {}\n\nconst createDOMException = useNativeDOMException\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n ? /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {DOMException}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNativeDOMException(name, message);\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n : /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {Error}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNonNativeDOMException(name, message);\n };\n\nconst ShimDOMException = useNativeDOMException\n ? DOMException\n : ShimNonNativeDOMException;\n\nexport {logError, findError, ShimDOMException, createDOMException, webSQLErrback};\n","/* eslint-disable new-cap -- ToString is how it is defined */\nimport CFG from './CFG.js';\nimport expandsOnNFD from './unicode-regex.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeUnmatchedSurrogates (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return arg.replaceAll(\n /([\\uD800-\\uDBFF])(?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])/gu,\n function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {\n // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577\n // but Chrome having problems\n if (unmatchedHighSurrogate) {\n return '^2' + unmatchedHighSurrogate.codePointAt()\n .toString(16).padStart(4, '0');\n }\n return (precedingLow || '') + '^3' +\n unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');\n }\n );\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeNameForSQLiteIdentifier (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return '_' + // Prevent empty string\n escapeUnmatchedSurrogates(\n arg.replaceAll('^', '^^') // Escape our escape\n // http://www.sqlite.org/src/tktview?name=57c971fc74\n .replaceAll('\\0', '^0')\n // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names\n // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577\n // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working\n .replaceAll(/([A-Z])/gu, '^$1')\n );\n}\n\n/**\n * The escaping of unmatched surrogates was needed by Chrome but not Node.\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeSQLiteStatement (arg) {\n return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\\0', '^0'));\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeSQLiteResponse (arg) {\n return unescapeUnmatchedSurrogates(arg)\n .replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n })\n .replaceAll('^^', '^');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlEscape (arg) {\n // https://www.sqlite.org/lang_keywords.html\n // http://stackoverflow.com/a/6701665/271577\n // There is no need to escape ', `, or [], as\n // we should always be within double quotes\n // NUL should have already been stripped\n return arg.replaceAll('\"', '\"\"');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlQuote (arg) {\n return '\"' + sqlEscape(arg) + '\"';\n}\n\n/**\n * @param {string} db\n * @throws {Error}\n * @returns {string}\n */\nfunction escapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.escapeDatabaseName) {\n // We at least ensure NUL is escaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), escaping casing (including Unicode?),\n // and escaping special characters depending on file system\n return CFG.escapeDatabaseName(escapeSQLiteStatement(db));\n }\n db = 'D' + escapeNameForSQLiteIdentifier(db);\n if (CFG.escapeNFDForDatabaseNames !== false) {\n // ES6 copying of regex with different flags\n db = db.replaceAll(new RegExp(expandsOnNFD, 'gu'), function (expandable) {\n return '^4' + /** @type {Integer} */ (expandable.codePointAt(0)).toString(16).padStart(6, '0');\n });\n }\n if (CFG.databaseCharacterEscapeList !== false) {\n db = db.replace(\n (CFG.databaseCharacterEscapeList\n ? new RegExp(CFG.databaseCharacterEscapeList, 'gu')\n : /[\\u0000-\\u001F\\u007F\"*/:<>?\\\\|]/gu), // eslint-disable-line no-control-regex -- Controls needed\n function (n0) {\n // eslint-disable-next-line unicorn/prefer-code-point -- Switch to `codePointAt`?\n return '^1' + n0.charCodeAt(0).toString(16).padStart(2, '0');\n }\n );\n }\n if (CFG.databaseNameLengthLimit !== false &&\n db.length >= ((CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0))) {\n throw new Error(\n 'Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' +\n db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'\n );\n }\n return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?)\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeUnmatchedSurrogates (arg) {\n return arg\n .replaceAll(/(\\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(lowSurr, 16))\n : _;\n }).replaceAll(/(\\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(highSurr, 16))\n : _;\n });\n}\n\n/**\n * Not in use internally but supplied for convenience.\n * @param {string} db\n * @returns {string}\n */\nfunction unescapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.unescapeDatabaseName) {\n // We at least ensure NUL is unescaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), unescaping casing (including Unicode?),\n // and unescaping special characters depending on file system\n return CFG.unescapeDatabaseName(unescapeSQLiteResponse(db));\n }\n\n return unescapeUnmatchedSurrogates(\n db.slice(2) // D_\n // CFG.databaseCharacterEscapeList\n .replaceAll(/(\\^+)1([0-9a-f]{2})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n // CFG.escapeNFDForDatabaseNames\n }).replaceAll(/(\\^+)4([0-9a-f]{6})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n })\n // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above)\n ).replaceAll(/(\\^+)([A-Z])/gu, (_, esc, upperCase) => {\n return esc.length % 2\n ? esc.slice(1) + upperCase\n : _;\n }).replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n }).replaceAll('^^', '^');\n}\n\n/**\n * @param {string} store\n * @returns {string}\n */\nfunction escapeStoreNameForSQL (store) {\n return sqlQuote('S' + escapeNameForSQLiteIdentifier(store));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQL (index) {\n return sqlQuote('I' + escapeNameForSQLiteIdentifier(index));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQLKeyColumn (index) {\n return 'I' + escapeNameForSQLiteIdentifier(index);\n}\n\n/**\n * @todo Didn't need to escape `%`. Do we still need this escape?\n * @param {string} str\n * @returns {string}\n */\nfunction sqlLIKEEscape (str) {\n // https://www.sqlite.org/lang_expr.html#like\n return str.replaceAll('^', '^^');\n}\n\n/**\n * @typedef {Function} AnyClass\n */\n\n// Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?)\n/**\n *\n * @param {AnyValue} obj\n * @param {AnyClass} Clss\n * @returns {boolean}\n */\nfunction instanceOf (obj, Clss) {\n return Clss[Symbol.hasInstance](obj);\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {obj is object}\n */\nfunction isObj (obj) {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isDate (obj) {\n return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isBlob (obj) {\n return isObj(obj) && 'size' in obj && typeof obj.size === 'number' &&\n 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isRegExp (obj) {\n return isObj(obj) && 'flags' in obj && typeof obj.flags === 'string' &&\n 'exec' in obj && typeof obj.exec === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isFile (obj) {\n return isObj(obj) && 'name' in obj && typeof obj.name === 'string' &&\n 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isBinary (obj) {\n return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && (\n ('slice' in obj && typeof obj.slice === 'function') || // `TypedArray` (view on buffer) or `ArrayBuffer`\n ('getFloat64' in obj && typeof obj.getFloat64 === 'function') // `DataView` (view on buffer)\n );\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isIterable (obj) {\n return isObj(obj) && Symbol.iterator in obj &&\n typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n },\n // @ts-expect-error Deliberately errs\n set [prop] (val) {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineReadonlyOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object & {\n * [key: string]: any\n * }} obj\n * @param {string[]} listeners\n * @returns {void}\n */\nfunction defineListenerProperties (obj, listeners) {\n listeners = typeof listeners === 'string' ? [listeners] : listeners;\n listeners.forEach((listener) => {\n const o = {\n get [listener] () {\n return obj['__' + listener];\n },\n /**\n * @param {AnyValue} val\n * @returns {void}\n */\n set [listener] (val) {\n obj['__' + listener] = val;\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, listener)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners)\n Object.defineProperty(obj, listener, desc);\n });\n listeners.forEach((l) => {\n obj[l] = null;\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string|string[]} props\n * @param {null|{\n * [key: string]: any\n * }} getter\n * @returns {void}\n */\nfunction defineReadonlyProperties (obj, props, getter = null) {\n props = typeof props === 'string' ? [props] : props;\n props.forEach(function (prop) {\n let o;\n if (getter && prop in getter) {\n o = getter[prop];\n } else {\n Object.defineProperty(obj, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // We must resort to this to get \"get \" as\n // the function `name` for proper IDL\n o = {\n get [prop] () {\n return this['__' + prop];\n }\n };\n }\n\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {string} item\n * @returns {boolean}\n */\nfunction isIdentifier (item) {\n // For load-time and run-time performance, we don't provide the complete regular\n // expression for identifiers, but these can be passed in, using the expressions\n // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407\n // ID_Start (includes Other_ID_Start)\n const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]';\n // ID_Continue (includes Other_ID_Continue)\n const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]';\n const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])';\n const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\\u200C\\u200D])';\n return (new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u')).test(item);\n}\n\n/**\n *\n * @param {string|string[]} keyPathString\n * @returns {boolean}\n */\nfunction isValidKeyPathString (keyPathString) {\n return typeof keyPathString === 'string' &&\n (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every((pathComponent) => {\n return isIdentifier(pathComponent);\n }));\n}\n\n/**\n *\n * @param {string|string[]} keyPath\n * @returns {boolean}\n */\nfunction isValidKeyPath (keyPath) {\n return isValidKeyPathString(keyPath) || (\n Array.isArray(keyPath) && Boolean(keyPath.length) &&\n // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html\n // See also https://heycam.github.io/webidl/#idl-DOMString\n [...keyPath].every((pathComponent) => {\n return isValidKeyPathString(pathComponent);\n })\n );\n}\n\n/**\n * @param {number} number\n * @param {\"unsigned long long\"|\"unsigned long\"} type\n * @throws {Error|TypeError}\n * @returns {number}\n */\nfunction enforceRange (number, type) {\n number = Math.floor(Number(number));\n let max, min;\n switch (type) {\n case 'unsigned long long': {\n max = 0x1FFFFFFFFFFFFF; // 2^53 - 1\n min = 0;\n break;\n }\n case 'unsigned long': {\n max = 0xFFFFFFFF; // 2^32 - 1\n min = 0;\n break;\n }\n default:\n throw new Error('Unrecognized type supplied to enforceRange');\n }\n if (!Number.isFinite(number) ||\n number > max ||\n number < min) {\n throw new TypeError('Invalid range: ' + number);\n }\n return number;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {AnyValue} v\n * @param {boolean} [treatNullAs]\n * @returns {string}\n */\nfunction convertToDOMString (v, treatNullAs) {\n return v === null && treatNullAs ? '' : ToString(v);\n}\n\n/**\n * @param {AnyValue} o\n * @returns {string}\n */\nfunction ToString (o) { // Todo: See `es-abstract/es7`\n // `String()` will not throw with Symbols\n return '' + o; // eslint-disable-line no-implicit-coercion -- Need to throw with symbols\n}\n\n/**\n *\n * @param {AnyValue} val\n * @returns {string|string[]}\n */\nfunction convertToSequenceDOMString (val) {\n // Per , converting to a sequence works with iterables\n if (isIterable(val)) { // We don't want conversion to array to convert primitives\n // Per , converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring\n return [...val].map((item) => {\n return ToString(item);\n });\n }\n return ToString(val);\n}\n\n/**\n * @param {AnyValue} v\n * @returns {v is null|undefined}\n */\nfunction isNullish (v) {\n return v === null || v === undefined;\n}\n\nexport {escapeSQLiteStatement, unescapeSQLiteResponse,\n escapeDatabaseNameForSQLAndFiles, unescapeDatabaseNameForSQLAndFiles,\n escapeStoreNameForSQL, escapeIndexNameForSQL, escapeIndexNameForSQLKeyColumn,\n sqlLIKEEscape, sqlQuote,\n instanceOf,\n isObj, isDate, isBlob, isRegExp, isFile, isBinary, isIterable,\n defineOuterInterface, defineReadonlyOuterInterface,\n defineListenerProperties, defineReadonlyProperties,\n isValidKeyPath, enforceRange,\n convertToDOMString, convertToSequenceDOMString,\n isNullish};\n","import CFG from './CFG.js';\nimport {encode as keyEncode, decode as keyDecode} from './Key.js';\n\n/**\n * Compares two keys.\n * @param {import('./Key.js').Key} first\n * @param {import('./Key.js').Key} second\n * @returns {0|1|-1}\n */\nfunction cmp (first, second) {\n const encodedKey1 = /** @type {string} */ (keyEncode(first));\n const encodedKey2 = /** @type {string} */ (keyEncode(second));\n const result = encodedKey1 > encodedKey2\n ? 1\n : encodedKey1 === encodedKey2 ? 0 : -1;\n\n if (CFG.DEBUG) {\n // verify that the keys encoded correctly\n let decodedKey1 = keyDecode(encodedKey1);\n let decodedKey2 = keyDecode(encodedKey2);\n if (typeof first === 'object') {\n first = JSON.stringify(first);\n decodedKey1 = JSON.stringify(decodedKey1);\n }\n if (typeof second === 'object') {\n second = JSON.stringify(second);\n decodedKey2 = JSON.stringify(decodedKey2);\n }\n\n // Encoding/decoding mismatches are usually due to a loss of\n // floating-point precision\n if (decodedKey1 !== first) {\n console.warn(\n first + ' was incorrectly encoded as ' + decodedKey1\n );\n }\n if (decodedKey2 !== second) {\n console.warn(\n second + ' was incorrectly encoded as ' + decodedKey2\n );\n }\n }\n\n return result;\n}\n\nexport default cmp;\n","import {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\nimport cmp from './cmp.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView\n */\n\n/**\n * @typedef {ArrayBufferView|ArrayBuffer} BufferSource\n */\n\n/**\n * @typedef {\"number\"|\"date\"|\"string\"|\"binary\"|\"array\"} KeyType\n */\n\n/**\n * @typedef {any} Value\n */\n\n/**\n * @typedef {any} Key\n * @todo Specify possible value more precisely\n */\n\n/**\n * @typedef {KeyPath[]} KeyPathArray\n */\n/**\n * @typedef {string|KeyPathArray} KeyPath\n */\n\n/**\n* @typedef {object} KeyValueObject\n* @property {KeyType|\"NaN\"|\"null\"|\"undefined\"|\"boolean\"|\"object\"|\"symbol\"|\n* \"function\"|\"bigint\"} type If not `KeyType`, indicates invalid value\n* @property {Value} [value]\n* @property {boolean} [invalid]\n* @property {string} [message]\n* @todo Specify acceptable `value` more precisely\n*/\n\n/**\n * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive\n */\n/**\n * @typedef {ValueType[]} ValueTypeArray\n */\n/**\n * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType\n */\n\n/**\n * Encodes the keys based on their types. This is required to maintain collations\n * We leave space for future keys.\n * @type {{[key: string]: Integer|string}}\n */\nconst keyTypeToEncodedChar = {\n invalid: 100,\n number: 200,\n date: 300,\n string: 400,\n binary: 500,\n array: 600\n};\nconst keyTypes = /** @type {(KeyType|\"invalid\")[]} */ (Object.keys(keyTypeToEncodedChar));\nkeyTypes.forEach((k) => {\n keyTypeToEncodedChar[k] = String.fromCodePoint(\n /** @type {number} */ (keyTypeToEncodedChar[k])\n );\n});\n\nconst encodedCharToKeyType = keyTypes.reduce((o, k) => {\n o[keyTypeToEncodedChar[k]] = k;\n return o;\n}, /** @type {{[key: string]: KeyType|\"invalid\"}} */ ({}));\n\n/**\n * The sign values for numbers, ordered from least to greatest.\n * - \"negativeInfinity\": Sorts below all other values.\n * - \"bigNegative\": Negative values less than or equal to negative one.\n * - \"smallNegative\": Negative values between negative one and zero, noninclusive.\n * - \"smallPositive\": Positive values between zero and one, including zero but not one.\n * - \"largePositive\": Positive values greater than or equal to one.\n * - \"positiveInfinity\": Sorts above all other values.\n */\nconst signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @type {{\n * [key: string]: {\n * encode: (param: any, inArray?: boolean) => string,\n * decode: (param: string, inArray?: boolean) => any\n * }\n * }}\n */\nconst types = {\n invalid: {\n /**\n * @returns {string}\n */\n encode () {\n return keyTypeToEncodedChar.invalid + '-';\n },\n /**\n * @returns {undefined}\n */\n decode () {\n return undefined;\n }\n },\n\n // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa\n // notation.\n //\n // sign: takes a value between zero and five, inclusive. Represents infinite cases\n // and the signs of both the exponent and the fractional part of the number.\n // exponent: padded to two base-32 digits, represented by the 32's compliment in the\n // \"smallPositive\" and \"bigNegative\" cases to ensure proper lexical sorting.\n // mantissa: also called the fractional part. Normed 11-digit base-32 representation.\n // Represented by the 32's compliment in the \"smallNegative\" and \"bigNegative\"\n // cases to ensure proper lexical sorting.\n number: {\n // The encode step checks for six numeric cases and generates 14-digit encoded\n // sign-exponent-mantissa strings.\n /**\n * @param {number} key\n * @returns {string}\n */\n encode (key) {\n let key32 = key === Number.MIN_VALUE\n // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some\n // Node (and Chrome) versions with `Number.MIN_VALUE` being treated\n // as 0\n // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring\n ? '0.' + '0'.repeat(214) + '2'\n : Math.abs(key).toString(32);\n // Get the index of the decimal.\n const decimalIndex = key32.indexOf('.');\n // Remove the decimal.\n key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;\n // Get the index of the first significant digit.\n const significantDigitIndex = key32.search(/[^0]/u);\n // Truncate leading zeros.\n key32 = key32.slice(significantDigitIndex);\n let sign, exponent, mantissa;\n\n // Finite cases:\n if (Number.isFinite(\n Number(key)\n )) {\n // Negative cases:\n if (key < 0) {\n // Negative exponent case:\n if (key > -1) {\n sign = signValues.indexOf('smallNegative');\n exponent = padBase32Exponent(significantDigitIndex);\n mantissa = flipBase32(padBase32Mantissa(key32));\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigNegative');\n exponent = flipBase32(padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n ));\n mantissa = flipBase32(padBase32Mantissa(key32));\n }\n // Non-negative cases:\n // Negative exponent case:\n } else if (key < 1) {\n sign = signValues.indexOf('smallPositive');\n exponent = flipBase32(padBase32Exponent(significantDigitIndex));\n mantissa = padBase32Mantissa(key32);\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigPositive');\n exponent = padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n );\n mantissa = padBase32Mantissa(key32);\n }\n // Infinite cases:\n } else {\n exponent = zeros(2);\n mantissa = zeros(11);\n sign = signValues.indexOf(\n key > 0 ? 'positiveInfinity' : 'negativeInfinity'\n );\n }\n\n return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;\n },\n // The decode step must interpret the sign, reflip values encoded as the 32's complements,\n // apply signs to the exponent and mantissa, do the base-32 power operation, and return\n // the original JavaScript number values.\n /**\n * @param {string} key\n * @returns {number}\n */\n decode (key) {\n const sign = Number(key.slice(2, 3));\n let exponent = key.slice(3, 5);\n let mantissa = key.slice(5, 16);\n\n switch (signValues[sign]) {\n case 'negativeInfinity':\n return Number.NEGATIVE_INFINITY;\n case 'positiveInfinity':\n return Number.POSITIVE_INFINITY;\n case 'bigPositive':\n return pow32(mantissa, exponent);\n case 'smallPositive':\n exponent = negate(flipBase32(exponent));\n return pow32(mantissa, exponent);\n case 'smallNegative':\n exponent = negate(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n case 'bigNegative':\n exponent = flipBase32(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n default:\n throw new Error('Invalid number.');\n }\n }\n },\n\n // Strings are encoded as JSON strings (with quotes and unicode characters escaped).\n //\n // If the strings are in an array, then some extra encoding is done to make sorting work correctly:\n // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly\n // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.\n // To do this, each character of the string is prepended with a dash (\"-\"), and a space is added to the end of the string.\n // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,\n // the indexes of each string's characters line up with each other.\n string: {\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n encode (key, inArray) {\n if (inArray) {\n // prepend each character with a dash, and append a space to the end\n key = key.replaceAll(/(.)/gu, '-$1') + ' ';\n }\n return keyTypeToEncodedChar.string + '-' + key;\n },\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n decode (key, inArray) {\n key = key.slice(2);\n if (inArray) {\n // remove the space at the end, and the dash before each character\n key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');\n }\n return key;\n }\n },\n\n // Arrays are encoded as JSON strings.\n // An extra, value is added to each array during encoding to make\n // empty arrays sort correctly.\n array: {\n /**\n * @param {ValueTypeArray} key\n * @returns {string}\n */\n encode (key) {\n const encoded = [];\n for (const [i, item] of key.entries()) {\n const encodedItem = encode(item, true); // encode the array item\n encoded[i] = encodedItem;\n }\n encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly\n return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);\n },\n /**\n * @param {string} key\n * @returns {ValueTypeArray}\n */\n decode (key) {\n const decoded = JSON.parse(key.slice(2));\n decoded.pop(); // remove the extra item\n for (let i = 0; i < decoded.length; i++) {\n const item = decoded[i];\n const decodedItem = decode(item, true); // decode the item\n decoded[i] = decodedItem;\n }\n return decoded;\n }\n },\n\n // Dates are encoded as ISO 8601 strings, in UTC time zone.\n date: {\n /**\n * @param {Date} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.date + '-' + key.toJSON();\n },\n /**\n * @param {string} key\n * @returns {Date}\n */\n decode (key) {\n return new Date(key.slice(2));\n }\n },\n binary: {\n // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)\n /**\n * @param {BufferSource} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.binary + '-' + (key.byteLength\n ? [...getCopyBytesHeldByBufferSource(key)].map(\n (b) => String(b).padStart(3, '0')\n ) // e.g., '255,005,254,000,001,033'\n : '');\n },\n /**\n * @param {string} key\n * @returns {ArrayBuffer}\n */\n decode (key) {\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const k = key.slice(2);\n const arr = k.length ? k.split(',').map((s) => Number.parseInt(s)) : [];\n const buffer = new ArrayBuffer(arr.length);\n const uint8 = new Uint8Array(buffer);\n uint8.set(arr);\n return buffer;\n }\n }\n};\n\n/**\n * Return a padded base-32 exponent value.\n * @param {number} n\n * @returns {string}\n */\nfunction padBase32Exponent (n) {\n const exp = n.toString(32);\n return (exp.length === 1) ? '0' + exp : exp;\n}\n\n/**\n * Return a padded base-32 mantissa.\n * @param {string} s\n * @returns {string}\n */\nfunction padBase32Mantissa (s) {\n return (s + zeros(11)).slice(0, 11);\n}\n\n/**\n * Flips each digit of a base-32 encoded string.\n * @param {string} encoded\n * @returns {string}\n */\nfunction flipBase32 (encoded) {\n let flipped = '';\n for (const ch of encoded) {\n flipped += (31 - Number.parseInt(ch, 32)).toString(32);\n }\n return flipped;\n}\n\n/**\n * Base-32 power function.\n * RESEARCH: This function does not precisely decode floats because it performs\n * floating point arithmetic to recover values. But can the original values be\n * recovered exactly?\n * Someone may have already figured out a good way to store JavaScript floats as\n * binary strings and convert back. Barring a better method, however, one route\n * may be to generate decimal strings that `parseFloat` decodes predictably.\n * @param {string} mantissa\n * @param {string} exponent\n * @returns {number}\n */\nfunction pow32 (mantissa, exponent) {\n const exp = Number.parseInt(exponent, 32);\n if (exp < 0) {\n return roundToPrecision(\n Number.parseInt(mantissa, 32) * (32 ** (exp - 10))\n );\n }\n if (exp < 11) {\n const whole = mantissa.slice(0, exp);\n const wholeNum = Number.parseInt(whole, 32);\n const fraction = mantissa.slice(exp);\n const fractionNum = Number.parseInt(fraction, 32) * (32 ** (exp - 11));\n return roundToPrecision(wholeNum + fractionNum);\n }\n const expansion = mantissa + zeros(exp - 11);\n return Number.parseInt(expansion, 32);\n}\n\n/**\n * @typedef {number} Float\n */\n\n/**\n * @param {Float} num\n * @param {Float} [precision]\n * @returns {Float}\n */\nfunction roundToPrecision (num, precision = 16) {\n return Number.parseFloat(num.toPrecision(precision));\n}\n\n/**\n * Returns a string of n zeros.\n * @param {number} n\n * @returns {string}\n */\nfunction zeros (n) {\n return '0'.repeat(n);\n}\n\n/**\n * Negates numeric strings.\n * @param {string} s\n * @returns {string}\n */\nfunction negate (s) {\n return '-' + s;\n}\n\n/**\n * @param {Key} key\n * @returns {KeyType|\"invalid\"}\n */\nfunction getKeyType (key) {\n if (Array.isArray(key)) { return 'array'; }\n if (util.isDate(key)) { return 'date'; }\n if (util.isBinary(key)) { return 'binary'; }\n const keyType = typeof key;\n return ['string', 'number'].includes(keyType)\n ? /** @type {\"string\"|\"number\"} */ (keyType)\n : 'invalid';\n}\n\n/**\n * Keys must be strings, numbers (besides `NaN`), Dates (if value is not\n * `NaN`), binary objects or Arrays.\n * @param {Value} input The key input\n * @param {Value[]|null|undefined} [seen] An array of already seen keys\n * @returns {KeyValueObject}\n */\nfunction convertValueToKey (input, seen) {\n return convertValueToKeyValueDecoded(input, seen, false, true);\n}\n\n/**\n* Currently not in use.\n* @param {Value} input\n* @returns {KeyValueObject}\n*/\nfunction convertValueToMultiEntryKey (input) {\n return convertValueToKeyValueDecoded(input, null, true, true);\n}\n\n/**\n *\n * @param {BufferSource} O\n * @throws {TypeError}\n * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n * @returns {Uint8Array}\n */\nfunction getCopyBytesHeldByBufferSource (O) {\n let offset = 0;\n let length = 0;\n if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot\n const arrayBuffer = O.buffer;\n if (arrayBuffer === undefined) {\n throw new TypeError(\n 'Could not copy the bytes held by a buffer source as the buffer was undefined.'\n );\n }\n offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)\n length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)\n } else {\n length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)\n }\n // const octets = new Uint8Array(input);\n // const octets = types.binary.decode(types.binary.encode(input));\n return new Uint8Array(\n // Should allow DataView\n /** @type {ArrayBuffer} */\n (('buffer' in O && O.buffer) || O),\n offset,\n length\n );\n}\n\n/**\n* Shortcut utility to avoid returning full keys from `convertValueToKey`\n* and subsequent need to process in calling code unless `fullKeys` is\n* set; may throw.\n* @param {Value} input\n* @param {Value[]|null} [seen]\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @throws {TypeError} See `getCopyBytesHeldByBufferSource`\n* @todo Document other allowable `input`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {\n seen = seen || [];\n if (seen.includes(input)) {\n return {\n type: 'array',\n invalid: true,\n message: 'An array key cannot be circular'\n };\n }\n const type = getKeyType(input);\n const ret = {type, value: input};\n switch (type) {\n case 'number': {\n if (Number.isNaN(input)) {\n // List as 'NaN' type for convenience of consumers in reporting errors\n return {type: 'NaN', invalid: true};\n }\n\n // https://github.com/w3c/IndexedDB/issues/375\n // https://github.com/w3c/IndexedDB/pull/386\n if (Object.is(input, -0)) {\n return {type, value: 0};\n }\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'string': {\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'binary': { // May throw (if detached)\n // Get a copy of the bytes held by the buffer source\n // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n const octets = getCopyBytesHeldByBufferSource(\n /** @type {BufferSource} */ (input)\n );\n return {type: 'binary', value: octets};\n } case 'array': { // May throw (from binary)\n const arr = /** @type {Array} */ (input);\n const len = arr.length;\n seen.push(input);\n\n /** @type {(KeyValueObject|Value)[]} */\n const keys = [];\n for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated\n if (!multiEntry && !Object.hasOwn(arr, i)) {\n return {type, invalid: true, message: 'Does not have own index property'};\n }\n try {\n const entry = arr[i];\n const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry\n if (key.invalid) {\n if (multiEntry) {\n continue;\n }\n return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};\n }\n if (!multiEntry ||\n (!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||\n (fullKeys && keys.every((k) => cmp(k, key) !== 0))\n ) {\n keys.push(fullKeys ? key : key.value);\n }\n } catch (err) {\n if (!multiEntry) {\n throw err;\n }\n }\n }\n return {type, value: keys};\n } case 'date': {\n const date = /** @type {Date} */ (input);\n if (!Number.isNaN(date.getTime())) {\n return fullKeys\n ? {type, value: date.getTime()}\n : {type, value: new Date(date.getTime())};\n }\n return {type, invalid: true, message: 'Not a valid date'};\n // Falls through\n } case 'invalid': default: {\n // Other `typeof` types which are not valid keys:\n // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'\n const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors\n return {type, invalid: true, message: 'Not a valid key; type ' + type};\n }\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [fullKeys]\n * @returns {KeyValueObject}\n * @todo Document other allowable `key`?\n */\nfunction convertValueToMultiEntryKeyDecoded (key, fullKeys) {\n return convertValueToKeyValueDecoded(key, null, true, fullKeys);\n}\n\n/**\n* An internal utility.\n* @param {Value} input\n* @param {Value[]|null|undefined} [seen]\n* @throws {DOMException} `DataError`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyRethrowingAndIfInvalid (input, seen) {\n const key = convertValueToKey(input, seen);\n if (key.invalid) {\n throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);\n }\n return key;\n}\n\n/**\n *\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} multiEntry\n * @returns {KeyValueObject|KeyPathEvaluateValue}\n * @todo Document other possible return?\n */\nfunction extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {\n return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);\n}\n/**\n* Not currently in use.\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} multiEntry\n* @returns {KeyPathEvaluateValue}\n*/\nfunction evaluateKeyPathOnValue (value, keyPath, multiEntry) {\n return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);\n}\n\n/**\n* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)\n* or `{invalid: true}` (e.g., `NaN`).\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @returns {KeyValueObject|KeyPathEvaluateValue}\n* @todo Document other possible return?\n*/\nfunction extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {\n const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);\n if (r.failure) {\n return r;\n }\n if (!multiEntry) {\n return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);\n }\n return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);\n}\n\n/**\n * Unused?\n * @typedef {object} KeyPathEvaluateFailure\n * @property {boolean} failure\n */\n\n/**\n * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray\n */\n\n/**\n * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue\n */\n\n/**\n * @typedef {object} KeyPathEvaluateValue\n * @property {KeyPathEvaluateValueValue} [value]\n * @property {boolean} [failure]\n */\n\n/**\n * Returns the value of an inline key based on a key path (wrapped in an\n * object with key `value`) or `{failure: true}`\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} [multiEntry]\n * @param {boolean} [fullKeys]\n * @returns {KeyPathEvaluateValue}\n */\nfunction evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {\n if (Array.isArray(keyPath)) {\n /** @type {KeyPathEvaluateValueValueArray} */\n const result = [];\n return keyPath.some((item) => {\n const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);\n if (key.failure) {\n return true;\n }\n result.push(key.value);\n return false;\n })\n ? {failure: true}\n : {value: result};\n }\n if (keyPath === '') {\n return {value};\n }\n const identifiers = keyPath.split('.');\n return identifiers.some((idntfr) => {\n if (idntfr === 'length' && (\n typeof value === 'string' || Array.isArray(value)\n )) {\n value = value.length;\n } else if (util.isBlob(value)) {\n switch (idntfr) {\n case 'size': case 'type':\n value = /** @type {Blob} */ (value)[idntfr];\n break;\n }\n } else if (util.isFile(value)) {\n switch (idntfr) {\n case 'name': case 'lastModified':\n value = /** @type {File} */ (value)[idntfr];\n break;\n case 'lastModifiedDate':\n value = new Date(/** @type {File} */ (value).lastModified);\n break;\n }\n } else if (!util.isObj(value) || !Object.hasOwn(value, idntfr)) {\n return true;\n } else {\n value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */ (\n value\n )[idntfr];\n return value === undefined;\n }\n return false;\n })\n ? {failure: true}\n : {value};\n}\n\n/**\n * Sets the inline key value.\n * @param {{[key: string]: AnyValue}} value\n * @param {Key} key\n * @param {string} keyPath\n * @returns {void}\n */\nfunction injectKeyIntoValueUsingKeyPath (value, key, keyPath) {\n const identifiers = keyPath.split('.');\n const last = identifiers.pop();\n identifiers.forEach((identifier) => {\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n value[identifier] = {};\n }\n value = value[identifier];\n });\n value[/** @type {string} */ (last)] = key; // key is already a `keyValue` in our processing so no need to convert\n}\n\n/**\n *\n * @param {Value} value\n * @param {string} keyPath\n * @see https://github.com/w3c/IndexedDB/pull/146\n * @returns {boolean}\n */\nfunction checkKeyCouldBeInjectedIntoValue (value, keyPath) {\n const identifiers = keyPath.split('.');\n identifiers.pop();\n for (const identifier of identifiers) {\n if (!util.isObj(value)) {\n return false;\n }\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n return true;\n }\n value = /** @type {{[key: string]: Value}} */ (value)[identifier];\n }\n return util.isObj(value);\n}\n\n/**\n *\n * @param {Key} key\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range\n * @param {boolean} [checkCached]\n * @returns {boolean}\n */\nfunction isKeyInRange (key, range, checkCached) {\n let lowerMatch = range.lower === undefined;\n let upperMatch = range.upper === undefined;\n const encodedKey = encode(key, true);\n const lower = checkCached ? range.__lowerCached : encode(range.lower, true);\n const upper = checkCached ? range.__upperCached : encode(range.upper, true);\n\n if (!lowerMatch && (\n (range.lowerOpen &&\n encodedKey !== null && lower !== null && encodedKey > lower) ||\n (!range.lowerOpen && (\n (!encodedKey && !lower) ||\n (encodedKey !== null && lower !== null && encodedKey >= lower))\n )\n )) {\n lowerMatch = true;\n }\n if (!upperMatch && (\n (range.upperOpen &&\n encodedKey !== null && upper !== null && encodedKey < upper) ||\n (!range.upperOpen && (\n (!encodedKey && !upper) ||\n (encodedKey !== null && upper !== null && encodedKey <= upper))\n )\n )) {\n upperMatch = true;\n }\n\n return lowerMatch && upperMatch;\n}\n\n/**\n * Determines whether an index entry matches a multi-entry key value.\n * @param {string} encodedEntry The entry value (already encoded)\n * @param {string} encodedKey The full index key (already encoded)\n * @returns {boolean}\n */\nfunction isMultiEntryMatch (encodedEntry, encodedKey) {\n const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];\n\n if (keyType === 'array') {\n return encodedKey.indexOf(encodedEntry) > 1;\n }\n return encodedKey === encodedEntry;\n}\n\n/**\n *\n * @param {Key} keyEntry\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range\n * @returns {Key[]}\n */\nfunction findMultiEntryMatches (keyEntry, range) {\n const matches = [];\n\n if (Array.isArray(keyEntry)) {\n for (let key of keyEntry) {\n if (Array.isArray(key)) {\n if (range && range.lower === range.upper) {\n continue;\n }\n if (key.length === 1) {\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n key = key[0];\n } else {\n const nested = findMultiEntryMatches(key, range);\n if (nested.length > 0) {\n matches.push(key);\n }\n continue;\n }\n }\n\n if (util.isNullish(range) || isKeyInRange(key, range, true)) {\n matches.push(key);\n }\n }\n } else if (util.isNullish(range) || isKeyInRange(keyEntry, range, true)) {\n matches.push(keyEntry);\n }\n return matches;\n}\n\n/**\n* Not currently in use but keeping for spec parity.\n* @param {Key} key\n* @throws {Error} Upon a \"bad key\"\n* @returns {ValueType}\n*/\nfunction convertKeyToValue (key) {\n const {type, value} = key;\n switch (type) {\n case 'number': case 'string': {\n return value;\n } case 'array': {\n const array = [];\n const len = value.length;\n let index = 0;\n while (index < len) {\n const entry = convertKeyToValue(value[index]);\n array[index] = entry;\n index++;\n }\n return array;\n } case 'date': {\n return new Date(value);\n } case 'binary': {\n const len = value.length;\n const buffer = new ArrayBuffer(len);\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);\n uint8.set(value);\n return buffer;\n } case 'invalid': default:\n throw new Error('Bad key');\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {string|null}\n */\nfunction encode (key, inArray) {\n // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation\n if (key === undefined) {\n return null;\n }\n // array, date, number, string, binary (should already have detected \"invalid\")\n return types[getKeyType(key)].encode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @throws {Error} Invalid number\n * @returns {undefined|ValueType}\n */\nfunction decode (key, inArray) {\n if (typeof key !== 'string') {\n return undefined;\n }\n return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {undefined|ValueType}\n */\nfunction roundTrip (key, inArray) {\n return decode(encode(key, inArray), inArray);\n}\n\nconst MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback CurrentNumberCallback\n * @param {Integer} cn The current number\n * @returns {void}\n */\n\n/**\n* @callback SQLFailureCallback\n* @param {DOMException|Error} exception\n* @returns {void}\n*/\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {CurrentNumberCallback} func\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction getCurrentNumber (tx, store, func, sqlFailCb) {\n tx.executeSql('SELECT \"currNum\" FROM __sys__ WHERE \"name\" = ?', [\n util.escapeSQLiteStatement(store.__currentName)\n ], function (tx, data) {\n if (data.rows.length !== 1) {\n func(1);\n } else {\n func(data.rows.item(0).currNum);\n }\n }, function (tx, error) {\n sqlFailCb(createDOMException(\n 'DataError',\n 'Could not get the auto increment value for key',\n error\n ));\n return false;\n });\n}\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction assignCurrentNumber (tx, store, num, successCb, failCb) {\n const sql = 'UPDATE __sys__ SET \"currNum\" = ? WHERE \"name\" = ?';\n const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n tx.executeSql(sql, sqlValues, function () {\n successCb(num);\n }, function (tx, err) {\n failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));\n return false;\n });\n}\n\n/**\n * Bump up the auto-inc counter if the key path-resolved value is valid\n * (greater than old value and >=1) OR if a manually passed in key is\n * valid (numeric and >= 1) and >= any primaryKey.\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction setCurrentNumber (tx, store, num, successCb, failCb) {\n num = num === MAX_ALLOWED_CURRENT_NUMBER\n ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner\n : num + 1;\n return assignCurrentNumber(tx, store, num, successCb, failCb);\n}\n\n/**\n * @callback KeyForStoreCallback\n * @param {\"failure\"|null} arg1\n * @param {Integer} [arg2]\n * @param {Integer} [arg3]\n * @returns {void}\n */\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {KeyForStoreCallback} cb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction generateKeyForStore (tx, store, cb, sqlFailCb) {\n getCurrentNumber(tx, store, function (key) {\n if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See )\n cb('failure');\n return;\n }\n // Increment current number by 1 (we cannot leverage SQLite's\n // autoincrement (and decrement when not needed), as decrementing\n // will be overwritten/ignored upon the next insert)\n setCurrentNumber(\n tx, store, key,\n function () {\n cb(null, key, key);\n },\n sqlFailCb\n );\n }, sqlFailCb);\n}\n\n// Fractional or numbers exceeding the max do not get changed in the result\n// per https://github.com/w3c/IndexedDB/issues/147\n// so we do not return a key\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Key} key\n * @param {(num?: Integer) => void} successCb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {\n // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers\n // (or numbers larger than the max) are now to have the explicit effect of\n // setting the current number (up to the max), so we do not optimize them\n // out here\n if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number\n // Auto-increment attempted with a bad key;\n // we are not to change the current number, but the steps don't call for failure\n // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1\n successCb();\n } else {\n // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher\n // to determine which to use and whether to update the current number\n getCurrentNumber(tx, store, function (cn) {\n const value = Math.floor(\n Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)\n );\n const useNewKeyForAutoInc = value >= cn;\n if (useNewKeyForAutoInc) {\n setCurrentNumber(tx, store, value, function () {\n successCb(cn); // Supply old current number in case needs to be reverted\n }, sqlFailCb);\n } else { // Not updated\n successCb();\n }\n }, sqlFailCb);\n }\n}\n\nexport {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,\n convertValueToMultiEntryKeyDecoded,\n convertValueToKey,\n convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,\n extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,\n extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,\n isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,\n assignCurrentNumber,\n generateKeyForStore, possiblyUpdateKeyGenerator};\n"],"names":["map","CFG","createNativeDOMException","name","message","DOMException","prototype","constructor","val","test","TypeError","forEach","prop","validator","Array","isArray","_prop2","_slicedToArray","Object","defineProperty","get","set","codes","IndexSizeError","HierarchyRequestError","WrongDocumentError","InvalidCharacterError","NoModificationAllowedError","NotFoundError","NotSupportedError","InUseAttributeError","InvalidStateError","SyntaxError","InvalidModificationError","NamespaceError","InvalidAccessError","TypeMismatchError","SecurityError","NetworkError","AbortError","URLMismatchError","QuotaExceededError","TimeoutError","InvalidNodeTypeError","DataCloneError","EncodingError","NotReadableError","UnknownError","ConstraintError","DataError","TransactionInactiveError","ReadOnlyError","VersionError","OperationError","NotAllowedError","legacyCodes","INDEX_SIZE_ERR","DOMSTRING_SIZE_ERR","HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR","NO_DATA_ALLOWED_ERR","NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR","VALIDATION_ERR","TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR","ShimNonNativeDOMException","this","Symbol","toStringTag","_code","_name","_message","undefined","configurable","enumerable","writable","value","DummyDOMException","create","Error","keys","codeName","createNonNativeDOMExceptionClass","logError","error","DEBUG","msg","_typeof","method","console","trace","obj","useNativeDOMException","err","createDOMException","createNonNativeDOMException","escapeSQLiteStatement","arg","replaceAll","_","unmatchedHighSurrogate","precedingLow","unmatchedLowSurrogate","codePointAt","toString","padStart","escapeUnmatchedSurrogates","isObj","isNullish","v","cmp","first","second","encodedKey1","keyEncode","encodedKey2","result","decodedKey1","keyDecode","decodedKey2","JSON","stringify","warn","keyTypeToEncodedChar","invalid","number","date","string","binary","array","keyTypes","k","String","fromCodePoint","encodedCharToKeyType","reduce","o","signValues","types","encode","decode","key","sign","exponent","mantissa","key32","Number","MIN_VALUE","repeat","Math","abs","decimalIndex","indexOf","significantDigitIndex","replace","search","slice","isFinite","padBase32Exponent","flipBase32","padBase32Mantissa","length","zeros","NEGATIVE_INFINITY","POSITIVE_INFINITY","pow32","negate","inArray","_step","encoded","_iterator","_createForOfIteratorHelper","entries","s","n","done","_step$value","i","encodedItem","e","f","push","decoded","parse","pop","decodedItem","toJSON","Date","byteLength","_toConsumableArray","getCopyBytesHeldByBufferSource","b","arr","split","parseInt","buffer","ArrayBuffer","Uint8Array","exp","_step2","flipped","_iterator2","ch","roundToPrecision","pow","whole","wholeNum","fraction","expansion","num","precision","arguments","parseFloat","toPrecision","getKeyType","getDate","util","getFloat64","keyType","includes","convertValueToKey","input","seen","convertValueToKeyValueDecoded","O","offset","isView","byteOffset","multiEntry","fullKeys","type","ret","isNaN","is","len","_ret","_loop","hasOwn","every","getTime","convertValueToMultiEntryKeyDecoded","extractKeyValueDecodedFromValueUsingKeyPath","keyPath","r","evaluateKeyPathOnValueToDecodedValue","failure","some","item","idntfr","size","lastModified","isKeyInRange","range","checkCached","lowerMatch","lower","upperMatch","upper","encodedKey","__lowerCached","__upperCached","lowerOpen","upperOpen","MAX_ALLOWED_CURRENT_NUMBER","getCurrentNumber","tx","store","func","sqlFailCb","executeSql","__currentName","data","rows","currNum","assignCurrentNumber","successCb","failCb","sql","sqlValues","log","setCurrentNumber","identifiers","_step3","_iterator3","identifier","convertKeyToValue","index","entry","findMultiEntryMatches","keyEntry","matches","_step4","_iterator4","cb","last","encodedEntry","cn","floor","min"],"mappings":";84EAuDA,IAAMA,EAAM,CAAA,EAENC,EAAmC,CAAA,ECjDzC,SAASC,EAA0BC,EAAMC,GAErC,OAAO,IAAIC,aAAaC,UAAUC,YAC9BH,EACAD,GAAQ,eAEhB,CDsDC,CAEG,QAIA,yBAMA,WAOA,iBAIA,cAIA,wBAOA,iBAEA,oBAMA,cAGA,gBAcA,MAWA,kBAIA,mBAOA,KAMA,mBAKA,uBASA,qBAEA,uBAKA,8BAEA,0BAIA,4BAIA,qBAEA,CACI,iBAMA,SAACK,GACG,IAAM,iVAAkDC,KAC7BD,GAEvB,MAAM,IAAIE,UACN,wGAIZ,GAMJ,sBACA,mBACA,sBAGA,iBACA,WACA,aAEA,iBACDC,SAAQ,SAACC,GAER,IAAIC,EACJ,GAAIC,MAAMC,QAAQH,GAAO,CAAA,IACGI,EAAAC,EAAJL,EAAI,GAAvBA,EAAII,EAAA,GAAEH,EAASG,EAAA,EACpB,CACAE,OAAOC,eAAelB,EAAKW,EAAM,CAC7BQ,IAAG,WACC,OAAOpB,EAAIY,EACd,EACDS,IAAAA,SAAKb,GACGK,GACAA,EAAUL,GAEdR,EAAIY,GAAQJ,CAChB,GAER,IC9MA,IAAMc,EAAQ,CACVC,eAAgB,EAChBC,sBAAuB,EACvBC,mBAAoB,EACpBC,sBAAuB,EACvBC,2BAA4B,EAC5BC,cAAe,EACfC,kBAAmB,EACnBC,oBAAqB,GACrBC,kBAAmB,GACnBC,YAAa,GACbC,yBAA0B,GAC1BC,eAAgB,GAChBC,mBAAoB,GACpBC,kBAAmB,GACnBC,cAAe,GACfC,aAAc,GACdC,WAAY,GACZC,iBAAkB,GAClBC,mBAAoB,GACpBC,aAAc,GACdC,qBAAsB,GACtBC,eAAgB,GAEhBC,cAAe,EACfC,iBAAkB,EAClBC,aAAc,EACdC,gBAAiB,EACjBC,UAAW,EACXC,yBAA0B,EAC1BC,cAAe,EACfC,aAAc,EACdC,eAAg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D,EAAOE,EAAK0B,GAAUA,EACxC"} \ No newline at end of file diff --git a/dist/indexeddbshim-UnicodeIdentifiers-node.cjs b/dist/indexeddbshim-UnicodeIdentifiers-node.cjs index b249a1b5..6bee4410 100644 --- a/dist/indexeddbshim-UnicodeIdentifiers-node.cjs +++ b/dist/indexeddbshim-UnicodeIdentifiers-node.cjs @@ -1,4 +1,4 @@ -/*! indexeddbshim - v15.0.4 - 9/11/2024 */ +/*! indexeddbshim - v15.2.0 - 9/11/2024 */ 'use strict'; @@ -1313,12 +1313,13 @@ function escapeIndexNameForSQLKeyColumn(index) { } /** + * @todo Didn't need to escape `%`. Do we still need this escape? * @param {string} str * @returns {string} */ function sqlLIKEEscape(str) { // https://www.sqlite.org/lang_expr.html#like - return sqlEscape(str).replaceAll('^', '^^'); + return str.replaceAll('^', '^^'); } /** @@ -7151,8 +7152,11 @@ function executeFetchIndexData(count, unboundedDisallowed, index, hasKey, range, */ check => rowKey.includes(check)) || // More precise than our SQL - isMultiEntryMatch(/** @type {string} */ - encodedKey, row[escapedIndexNameForKeyCol]))) { + isMultiEntryMatch( + // Added `JSON.stringify` as was having problems with + // `JSON.stringify` encoding added to nested + // array keys + JSON.stringify(encodedKey).slice(1, -1), row[escapedIndexNameForKeyCol]))) { recordCount++; record = row; } else if (!hasKey && !multiChecks) { @@ -7225,7 +7229,13 @@ function buildFetchIndexDataSQL(nullDisallowed, index, range, opType, multiCheck sql.push(')'); } else if (index.multiEntry) { sql.push('AND', escapeIndexNameForSQL(index.name), "LIKE ? ESCAPE '^'"); - sqlValues.push('%' + sqlLIKEEscape(/** @type {string} */encode$1(range, index.multiEntry)) + '%'); + if (Array.isArray(range)) { + // Todo: For nesting deeper than one level, we probably need to + // run `JSON.stringify` again + sqlValues.push('%' + sqlLIKEEscape(JSON.stringify(/** @type {string} */encode$1(range, index.multiEntry)).slice(1, -1)) + '%'); + } else { + sqlValues.push('%' + sqlLIKEEscape(/** @type {string} */encode$1(range, index.multiEntry)) + '%'); + } } else { const convertedRange = convertValueToKeyRange(range, nullDisallowed); setSQLForKeyRange(convertedRange, escapeIndexNameForSQL(index.name), sql, sqlValues, true, false); diff --git a/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map b/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map index 518d4123..58a371b7 100644 --- a/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map +++ b/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map @@ -1 +1 @@ -{"version":3,"file":"indexeddbshim-UnicodeIdentifiers-node.cjs","sources":["../node_modules/eventtargeter/dist/index-es.js","../src/CFG.js","../src/unicode-regex.js","../src/util.js","../src/Event.js","../src/IDBVersionChangeEvent.js","../src/DOMException.js","../src/IDBRequest.js","../node_modules/sync-promise-expanded/index.js","../src/cmp.js","../src/Key.js","../src/IDBKeyRange.js","../src/DOMStringList.js","../src/IDBTransaction.js","../node_modules/typeson-registry/dist/index.min.js","../src/Sca.js","../src/IDBIndex.js","../src/IDBObjectStore.js","../src/IDBDatabase.js","../src/IDBFactory.js","../src/IDBCursor.js","../src/setGlobalVars.js","../node_modules/immediate/lib/nextTick.js","../node_modules/immediate/lib/queueMicrotask.js","../node_modules/immediate/lib/mutation.js","../node_modules/immediate/lib/messageChannel.js","../node_modules/immediate/lib/stateChange.js","../node_modules/immediate/lib/timeout.js","../node_modules/immediate/lib/index.js","../node_modules/tiny-queue/index.js","../node_modules/noop-fn/index.js","../node_modules/websql-configurable/lib/websql/WebSQLResultSet.js","../node_modules/websql-configurable/lib/websql/WebSQLTransaction.js","../node_modules/websql-configurable/lib/websql/WebSQLDatabase.js","../node_modules/websql-configurable/lib/custom.js","../node_modules/file-uri-to-path/index.js","../node_modules/bindings/bindings.js","../node_modules/sqlite3/lib/sqlite3-binding.js","../node_modules/sqlite3/lib/trace.js","../node_modules/sqlite3/lib/sqlite3.js","../node_modules/websql-configurable/lib/sqlite/SQLiteResult.js","../node_modules/websql-configurable/lib/sqlite/SQLiteDatabase.js","../src/nodeWebSQL.js","../src/UnicodeIdentifiers.js","../src/node-UnicodeIdentifiers.js"],"sourcesContent":["function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}\n\n/* eslint-disable n/no-sync -- Want sync naming */\n/* eslint-disable no-restricted-syntax -- Instanceof checks */\n/* eslint-disable unicorn/no-this-assignment -- TS */\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback InvokeCurrentListeners\n * @param {AllListeners} listeners\n * @param {EventWithProps} eventCopy\n * @param {string} type\n * @param {boolean} [checkOnListeners]\n * @returns {boolean}\n */\n\n/**\n * @typedef {{\n * defaultSync?: boolean,\n * extraProperties?: string[],\n * legacyOutputDidListenersThrowFlag?: boolean\n * }} CustomOptions\n */\n/**\n * @typedef {{\n * __legacyOutputDidListenersThrowError: unknown,\n * target: EventTarget & {\n * invokeCurrentListeners: InvokeCurrentListeners,\n * _earlyListeners: AllListeners,\n * _listeners: AllListeners,\n * _lateListeners: AllListeners,\n * _defaultListeners: AllListeners\n * },\n * composed: boolean,\n * currentTarget: EventTarget,\n * eventPhase: 0|1|2|3\n * defaultPrevented: boolean,\n * type: string,\n * bubbles: boolean,\n * cancelable: boolean,\n * isTrusted: boolean,\n * timeStamp: Integer,\n * initEvent: (type: string, bubbles: boolean, cancelable: boolean) => void,\n * preventDefault: () => void,\n * composedPath: () => void,\n * detail: any,\n * initCustomEvent: (\n * type: string, canBubble: boolean, cancelable: boolean,\n * detail: any\n * ) => void\n * }} EventWithProps\n */\n\n// Todo: Switch to ES6 classes\n\nvar phases = {\n NONE: 0,\n CAPTURING_PHASE: 1,\n AT_TARGET: 2,\n BUBBLING_PHASE: 3\n};\nvar ShimDOMException = typeof DOMException === 'undefined'\n// Todo: Better polyfill (if even needed here)\n/* eslint-disable no-shadow -- Polyfill */\n// eslint-disable-next-line operator-linebreak -- TS/JSDoc needs\n?\n/**\n * @param {string} msg\n * @param {string} name\n * @returns {Error}\n */\nfunction DOMException(msg, name) {\n // No need for `toString` as same as for `Error`\n /* eslint-enable no-shadow -- Polyfill */\n var err = new Error(msg);\n err.name = name;\n return err;\n} : DOMException;\nvar ev = new WeakMap();\nvar evCfg = new WeakMap();\n\n// Todo: Set _ev argument outside of this function\n\n/* eslint-disable func-name-matching -- Shim vs. Polyfill */\n/* eslint-disable no-shadow -- Polyfilling */\n/**\n* We use an adapter class rather than a proxy not only for compatibility\n* but also since we have to clone native event properties anyways in order\n* to properly set `target`, etc.\n* The regular DOM method `dispatchEvent` won't work with this polyfill as\n* it expects a native event.\n* @class\n* @param {string} type\n*/\nvar ShimEvent = /** @type {unknown} */function Event(type) {\n var _this = this;\n /* eslint-enable func-name-matching -- Shim vs. Polyfill */\n /* eslint-enable no-shadow -- Polyfilling */\n // For WebIDL checks of function's `length`, we check `arguments` for the optional arguments\n // @ts-expect-error\n this[Symbol.toStringTag] = 'Event';\n this.toString = function () {\n return '[object Event]';\n };\n // eslint-disable-next-line prefer-rest-params -- Don't want to change signature\n var _arguments = Array.prototype.slice.call(arguments),\n evInit = _arguments[1],\n _ev = _arguments[2];\n if (!arguments.length) {\n throw new TypeError(\"Failed to construct 'Event': 1 argument required, but only 0 present.\");\n }\n evInit = evInit || {};\n _ev = _ev || {};\n\n /** @type {EventWithProps} */\n var _evCfg = {};\n if ('composed' in evInit) {\n _evCfg.composed = evInit.composed;\n }\n\n // _evCfg.isTrusted = true; // We are not always using this for user-created events\n // _evCfg.timeStamp = new Date().valueOf(); // This is no longer a timestamp, but monotonic (elapsed?)\n\n ev.set(this, _ev);\n evCfg.set(this, _evCfg);\n var that = /** @type {unknown} */this;\n /** @type {ShimEvent} */\n that.initEvent(type, evInit.bubbles, evInit.cancelable);\n ['target', 'currentTarget', 'eventPhase', 'defaultPrevented'].forEach(function (pr) {\n var prop = /** @type {\"target\"|\"currentTarget\"|\"eventPhase\"|\"defaultPrevented\"} */\n pr;\n Object.defineProperty(_this, prop, {\n get: function get() {\n return (/* prop in _evCfg && */_evCfg[prop] !== undefined ? _evCfg[prop] : prop in _ev ? _ev[prop] :\n // Defaults\n prop === 'eventPhase' ? 0 : prop === 'defaultPrevented' ? false : null\n );\n }\n });\n });\n var props = [\n // Event\n 'type', 'bubbles', 'cancelable',\n // Defaults to false\n 'isTrusted', 'timeStamp', 'initEvent',\n // Other event properties (not used by our code)\n 'composedPath', 'composed'];\n if (this.toString() === '[object CustomEvent]') {\n props.push('detail', 'initCustomEvent');\n }\n Object.defineProperties(this, props.reduce(function (obj, pr) {\n var prop =\n /**\n * @type {\"type\"|\"bubbles\"|\"cancelable\"|\"isTrusted\"|\n * \"timeStamp\"|\"initEvent\"|\"composedPath\"|\"composed\"|\n * \"detail\"|\"initCustomEvent\"\n * }\n */\n pr;\n obj[prop] = {\n get: function get() {\n return prop in _evCfg ? _evCfg[prop] : prop in _ev ? _ev[prop] : ['bubbles', 'cancelable', 'composed'].includes(prop) ? false : undefined;\n }\n };\n return obj;\n }, /** @type {{[key: string]: any}} */{}));\n};\n\n// @ts-expect-error Casting doesn't work\nShimEvent.prototype.preventDefault = function () {\n // @ts-expect-error Needed for exporting\n if (!(this instanceof ShimEvent)) {\n throw new TypeError('Illegal invocation');\n }\n var _ev = ev.get(this);\n var _evCfg = evCfg.get(this);\n if (this.cancelable && !_evCfg._passive) {\n _evCfg.defaultPrevented = true;\n if (typeof _ev.preventDefault === 'function') {\n // Prevent any predefined defaults\n _ev.preventDefault();\n }\n }\n};\n\n// @ts-expect-error Casting doesn't work\nShimEvent.prototype.stopImmediatePropagation = function () {\n var _evCfg = evCfg.get(this);\n _evCfg._stopImmediatePropagation = true;\n};\n\n// @ts-expect-error Casting doesn't work\nShimEvent.prototype.stopPropagation = function () {\n var _evCfg = evCfg.get(this);\n _evCfg._stopPropagation = true;\n};\n\n// @ts-expect-error Casting doesn't work\nShimEvent.prototype.initEvent = function (type, bubbles, cancelable) {\n // Chrome currently has function length 1 only but WebIDL says 3\n // const bubbles = arguments[1];\n // const cancelable = arguments[2];\n var _evCfg = evCfg.get(this);\n if (_evCfg._dispatched) {\n return;\n }\n Object.defineProperty(this, 'type', {\n enumerable: true,\n configurable: true,\n get: function get() {\n return type;\n }\n });\n Object.defineProperty(this, 'bubbles', {\n enumerable: true,\n configurable: true,\n get: function get() {\n return bubbles;\n }\n });\n Object.defineProperty(this, 'cancelable', {\n enumerable: true,\n configurable: true,\n get: function get() {\n return cancelable;\n }\n });\n _evCfg.type = type;\n if (bubbles !== undefined) {\n _evCfg.bubbles = bubbles;\n }\n if (cancelable !== undefined) {\n _evCfg.cancelable = cancelable;\n }\n};\n['type', 'target', 'currentTarget'].forEach(function (prop) {\n // @ts-expect-error Casting doesn't work\n Object.defineProperty(ShimEvent.prototype, prop, {\n enumerable: true,\n configurable: true,\n get: function get() {\n throw new TypeError('Illegal invocation');\n }\n });\n});\n['eventPhase', 'defaultPrevented', 'bubbles', 'cancelable', 'timeStamp'].forEach(function (prop) {\n // @ts-expect-error Casting doesn't work\n Object.defineProperty(ShimEvent.prototype, prop, {\n enumerable: true,\n configurable: true,\n get: function get() {\n throw new TypeError('Illegal invocation');\n }\n });\n});\n['NONE', 'CAPTURING_PHASE', 'AT_TARGET', 'BUBBLING_PHASE'].forEach(function (prop, i) {\n Object.defineProperty(ShimEvent, prop, {\n enumerable: true,\n writable: false,\n value: i\n });\n // @ts-expect-error Casting doesn't work\n Object.defineProperty(ShimEvent.prototype, prop, {\n writable: false,\n value: i\n });\n});\n// @ts-expect-error Casting doesn't work\nShimEvent[Symbol.toStringTag] = 'Function';\n\n// @ts-expect-error Casting doesn't work\nShimEvent.prototype[Symbol.toStringTag] = 'EventPrototype';\nObject.defineProperty(ShimEvent, 'prototype', {\n writable: false\n});\n\n/* eslint-disable func-name-matching -- Polyfill */\n/* eslint-disable no-shadow -- Polyfill */\n/**\n * @class\n * @param {string} type\n */\nvar ShimCustomEvent = /** @type {unknown} */function CustomEvent(type) {\n /* eslint-enable func-name-matching -- Polyfill */\n /* eslint-enable no-shadow -- Polyfill */\n\n // eslint-disable-next-line prefer-rest-params -- Keep signature\n var _arguments2 = Array.prototype.slice.call(arguments),\n evInit = _arguments2[1],\n _ev = _arguments2[2];\n // @ts-expect-error Casting doesn't work\n ShimEvent.call(this, type, evInit, _ev);\n // @ts-expect-error\n this[Symbol.toStringTag] = 'CustomEvent';\n this.toString = function () {\n return '[object CustomEvent]';\n };\n // var _evCfg = evCfg.get(this);\n evInit = evInit || {};\n // @ts-ignore\n this.initCustomEvent(type, evInit.bubbles, evInit.cancelable, 'detail' in evInit ? evInit.detail : null);\n};\n// @ts-expect-error Casting doesn't work\nObject.defineProperty(ShimCustomEvent.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: ShimCustomEvent\n});\n// @ts-expect-error Casting doesn't work\nShimCustomEvent.prototype.initCustomEvent = function (type, bubbles, cancelable, detail) {\n // @ts-expect-error Needed for exporting\n if (!(this instanceof ShimCustomEvent)) {\n throw new TypeError('Illegal invocation');\n }\n var _evCfg = evCfg.get(this);\n // @ts-expect-error Casting doesn't work\n ShimCustomEvent.call(this, type, {\n bubbles: bubbles,\n cancelable: cancelable,\n detail: detail\n // eslint-disable-next-line prefer-rest-params -- Keep signature\n }, arguments[4]);\n if (_evCfg._dispatched) {\n return;\n }\n if (detail !== undefined) {\n _evCfg.detail = detail;\n }\n Object.defineProperty(this, 'detail', {\n get: function get() {\n return _evCfg.detail;\n }\n });\n};\n// @ts-expect-error Casting doesn't work\nShimCustomEvent[Symbol.toStringTag] = 'Function';\n// @ts-expect-error Casting doesn't work\nShimCustomEvent.prototype[Symbol.toStringTag] = 'CustomEventPrototype';\n\n// @ts-expect-error Casting doesn't work\nObject.defineProperty(ShimCustomEvent.prototype, 'detail', {\n enumerable: true,\n configurable: true,\n get: function get() {\n throw new TypeError('Illegal invocation');\n }\n});\nObject.defineProperty(ShimCustomEvent, 'prototype', {\n writable: false\n});\n\n/**\n *\n * @param {EventWithProps} e\n * @returns {EventWithProps}\n */\nfunction copyEvent(e) {\n var bubbles = e.bubbles,\n cancelable = e.cancelable,\n detail = e.detail,\n type = e.type;\n if ('detail' in e) {\n // @ts-expect-error Casting doesn't work\n return new ShimCustomEvent(type, {\n bubbles: bubbles,\n cancelable: cancelable,\n detail: detail\n }, e);\n }\n // @ts-expect-error Casting doesn't work\n return new ShimEvent(type, {\n bubbles: bubbles,\n cancelable: cancelable\n }, e);\n}\n\n/**\n* @typedef {object} ListenerOptions\n* @property {boolean} [once] Remove listener after invoking once\n* @property {boolean} [passive] Don't allow `preventDefault`\n* @property {boolean} [capture] Use `_children` and set `eventPhase`\n*/\n\n/**\n* @typedef {object} ListenerAndOptions\n* @property {Listener} listener\n* @property {ListenerOptions} options\n*/\n\n/**\n* @typedef {object} ListenerInfo\n* @property {ListenerAndOptions[]} listenersByTypeOptions\n* @property {ListenerOptions} options\n* @property {ListenerAndOptions[]} listenersByType\n*/\n\n/**\n* @callback Listener\n* @param {EventWithProps} e\n* @returns {boolean}\n*/\n\n/**\n * Keys are event types.\n * @typedef {{[key: string]: Listener[]}} Listeners\n */\n\n/**\n * @typedef {{\n * [type: string]: ListenerAndOptions[]\n * }} AllListeners\n */\n\n/**\n *\n * @param {AllListeners} listeners\n * @param {string} type\n * @param {boolean|ListenerOptions} options\n * @returns {ListenerInfo}\n */\nfunction getListenersOptions(listeners, type, options) {\n var listenersByType = listeners[type];\n if (listenersByType === undefined) listeners[type] = listenersByType = [];\n var opts = typeof options === 'boolean' ? {\n capture: options\n } : options || {};\n var stringifiedOptions = JSON.stringify(opts);\n var listenersByTypeOptions = listenersByType.filter(function (obj) {\n return stringifiedOptions === JSON.stringify(obj.options);\n });\n return {\n listenersByTypeOptions: listenersByTypeOptions,\n options: opts,\n listenersByType: listenersByType\n };\n}\nvar methods = {\n /**\n * @param {AllListeners} listeners\n * @param {Listener} listener\n * @param {string} type\n * @param {boolean|ListenerOptions} options\n * @returns {void}\n */\n addListener: function addListener(listeners, listener, type, options) {\n var listenersOptions = getListenersOptions(listeners, type, options);\n var listenersByTypeOptions = listenersOptions.listenersByTypeOptions;\n options = listenersOptions.options;\n var listenersByType = listenersOptions.listenersByType;\n if (listenersByTypeOptions.some(function (l) {\n return l.listener === listener;\n })) return;\n listenersByType.push({\n listener: listener,\n options: options\n });\n },\n /**\n * @param {AllListeners} listeners\n * @param {Listener} listener\n * @param {string} type\n * @param {boolean|ListenerOptions} options\n * @returns {void}\n */\n removeListener: function removeListener(listeners, listener, type, options) {\n var listenersOptions = getListenersOptions(listeners, type, options);\n var listenersByType = listenersOptions.listenersByType;\n var stringifiedOptions = JSON.stringify(listenersOptions.options);\n listenersByType.some(function (l, i) {\n if (l.listener === listener && stringifiedOptions === JSON.stringify(l.options)) {\n listenersByType.splice(i, 1);\n if (!listenersByType.length) delete listeners[type];\n return true;\n }\n return false;\n });\n },\n /**\n *\n * @param {AllListeners} listeners\n * @param {Listener} listener\n * @param {string} type\n * @param {boolean|ListenerOptions} options\n * @returns {boolean}\n */\n hasListener: function hasListener(listeners, listener, type, options) {\n var listenersOptions = getListenersOptions(listeners, type, options);\n var listenersByTypeOptions = listenersOptions.listenersByTypeOptions;\n return listenersByTypeOptions.some(function (l) {\n return l.listener === listener;\n });\n }\n};\n\n/* eslint-disable no-shadow -- Polyfill */\n/**\n * @class\n */\nfunction EventTarget() {\n /* eslint-enable no-shadow -- Polyfill */\n throw new TypeError('Illegal constructor');\n}\n\n/**\n * @typedef {\"addEarlyEventListener\"|\"removeEarlyEventListener\"|\"hasEarlyEventListener\"|\n * \"addEventListener\"|\"removeEventListener\"|\"hasEventListener\"|\n * \"addLateEventListener\"|\"removeLateEventListener\"|\"hasLateEventListener\"|\n * \"addDefaultEventListener\"|\"removeDefaultEventListener\"|\"hasDefaultEventListener\"\n * } ListenerName\n */\nObject.assign(EventTarget.prototype, ['Early', '', 'Late', 'Default'].reduce(function ( /** @type {{[key: string]: Function}} */\nobj, listenerType) {\n ['add', 'remove', 'has'].forEach(function (method) {\n var mainMethod = /** @type {ListenerName} */method + listenerType + 'EventListener';\n /**\n * @param {string} type\n * @param {Listener|{handleEvent: Listener}} listener\n * @this {EventTarget & {\n * _earlyListeners: AllListeners,\n * _listeners: AllListeners,\n * _lateListeners: AllListeners,\n * _defaultListeners: AllListeners,\n * }}\n * @returns {boolean|void}\n */\n obj[mainMethod] = function (type, listener) {\n // eslint-disable-next-line prefer-rest-params -- Keep signature\n var options = arguments[2]; // We keep the listener `length` as per WebIDL\n if (arguments.length < 2) throw new TypeError('2 or more arguments required');\n if (typeof type !== 'string') {\n // @ts-expect-error It's ok to construct\n throw new ShimDOMException('UNSPECIFIED_EVENT_TYPE_ERR', 'UNSPECIFIED_EVENT_TYPE_ERR');\n }\n try {\n // As per code such as the following, handleEvent may throw,\n // but is uncaught\n // https://github.com/web-platform-tests/wpt/blob/master/IndexedDB/fire-error-event-exception.html#L54-L56\n if ('handleEvent' in listener && listener.handleEvent.bind) {\n listener = listener.handleEvent.bind(listener);\n }\n } catch (err) {\n // eslint-disable-next-line no-console -- Feedback to user\n console.log('Uncaught `handleEvent` error', err);\n }\n var arrStr = /** @type {\"_earlyListeners\"|\"_listeners\"|\"_lateListeners\"|\"_defaultListeners\"} */\n '_' + listenerType.toLowerCase() + (listenerType === '' ? 'l' : 'L') + 'isteners';\n if (!this[arrStr]) {\n Object.defineProperty(this, arrStr, {\n value: {}\n });\n }\n var meth = /** @type {\"addListener\"|\"removeListener\"|\"hasListener\"} */\n method + 'Listener';\n return methods[meth](this[arrStr], /** @type {Listener} */listener, type, options);\n };\n });\n return obj;\n}, {}));\nObject.assign(EventTarget.prototype, {\n _legacyOutputDidListenersThrowCheck: undefined,\n /**\n * @param {CustomOptions} customOptions\n * @this {EventTarget.prototype}\n * @returns {void}\n */\n __setOptions: function __setOptions(customOptions) {\n customOptions = customOptions || {};\n // Todo: Make into event properties?\n this._defaultSync = customOptions.defaultSync;\n this._extraProperties = customOptions.extraProperties || [];\n if (customOptions.legacyOutputDidListenersThrowFlag) {\n // IndexedDB\n this._legacyOutputDidListenersThrowCheck = true;\n this._extraProperties.push('__legacyOutputDidListenersThrowError');\n }\n },\n /**\n * @param {ShimEvent} e\n * @this {EventTarget & {\n * _dispatchEvent: (e: ShimEvent|ShimCustomEvent, setTarget: boolean) => boolean,\n * }}\n * @returns {boolean}\n */\n dispatchEvent: function dispatchEvent(e) {\n return this._dispatchEvent(e, true);\n },\n /**\n * @param {EventWithProps} e\n * @param {boolean} setTarget\n * @this {EventTarget.prototype & {\n * _earlyListeners: AllListeners,\n * _listeners: AllListeners,\n * _lateListeners: AllListeners,\n * _defaultListeners: AllListeners,\n * }}\n * @returns {boolean}\n */\n _dispatchEvent: function _dispatchEvent(e, setTarget) {\n var _this2 = this;\n ['early', '', 'late', 'default'].forEach(function (listenerType) {\n var arrStr = /** @type {\"_earlyListeners\"|\"_listeners\"|\"_lateListeners\"|\"_defaultListeners\"} */\n '_' + listenerType + (listenerType === '' ? 'l' : 'L') + 'isteners';\n if (!_this2[arrStr]) {\n Object.defineProperty(_this2, arrStr, {\n value: {}\n });\n }\n });\n var _evCfg = evCfg.get(e);\n if (_evCfg && setTarget && _evCfg._dispatched) {\n // @ts-expect-error It's ok to construct\n throw new ShimDOMException('The object is in an invalid state.', 'InvalidStateError');\n }\n\n /** @type {EventWithProps} */\n var eventCopy;\n if (_evCfg) {\n eventCopy = e;\n } else {\n eventCopy = copyEvent(e);\n _evCfg = evCfg.get(eventCopy);\n _evCfg._dispatched = true;\n\n /** @type {string[]} */\n this._extraProperties.forEach(function (prop) {\n if (prop in e) {\n /** @type {{[key: string]: any}} */eventCopy[prop] = /** @type {{[key: string]: any}} */e[prop]; // Todo: Put internal to `ShimEvent`?\n }\n });\n }\n\n var _eventCopy = eventCopy,\n type = _eventCopy.type;\n\n /**\n *\n * @returns {void}\n */\n function finishEventDispatch() {\n _evCfg.eventPhase = phases.NONE;\n _evCfg.currentTarget = null;\n delete _evCfg._children;\n }\n /**\n *\n * @returns {void}\n */\n function invokeDefaults() {\n // Ignore stopPropagation from defaults\n _evCfg._stopImmediatePropagation = undefined;\n _evCfg._stopPropagation = undefined;\n // We check here for whether we should invoke since may have changed since timeout (if late listener prevented default)\n if (!eventCopy.defaultPrevented || !_evCfg.cancelable) {\n // 2nd check should be redundant\n _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke default listeners\n eventCopy.target.invokeCurrentListeners(eventCopy.target._defaultListeners, eventCopy, type);\n }\n finishEventDispatch();\n }\n var continueEventDispatch = function continueEventDispatch() {\n // Ignore stop propagation of user now\n _evCfg._stopImmediatePropagation = undefined;\n _evCfg._stopPropagation = undefined;\n if (!_this2._defaultSync) {\n setTimeout(invokeDefaults, 0);\n } else invokeDefaults();\n _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke late listeners\n // Sync default might have stopped\n if (!_evCfg._stopPropagation) {\n _evCfg._stopImmediatePropagation = undefined;\n _evCfg._stopPropagation = undefined;\n // We could allow stopPropagation by only executing upon (_evCfg._stopPropagation)\n eventCopy.target.invokeCurrentListeners(eventCopy.target._lateListeners, eventCopy, type);\n }\n finishEventDispatch();\n return !eventCopy.defaultPrevented;\n };\n if (setTarget) _evCfg.target = this;\n switch ('eventPhase' in eventCopy && eventCopy.eventPhase) {\n case phases.CAPTURING_PHASE:\n {\n if (_evCfg._stopPropagation) {\n return continueEventDispatch();\n }\n this.invokeCurrentListeners(this._listeners, eventCopy, type);\n var child = _evCfg._children && _evCfg._children.length && _evCfg._children.pop();\n if (!child || child === eventCopy.target) {\n _evCfg.eventPhase = phases.AT_TARGET;\n }\n if (child) child._defaultSync = this._defaultSync;\n return (child || this)._dispatchEvent(eventCopy, false);\n }\n case phases.AT_TARGET:\n if (_evCfg._stopPropagation) {\n return continueEventDispatch();\n }\n this.invokeCurrentListeners(this._listeners, eventCopy, type, true);\n if (!_evCfg.bubbles) {\n return continueEventDispatch();\n }\n _evCfg.eventPhase = phases.BUBBLING_PHASE;\n return this._dispatchEvent(eventCopy, false);\n case phases.BUBBLING_PHASE:\n {\n if (_evCfg._stopPropagation) {\n return continueEventDispatch();\n }\n var parent = this.__getParent && this.__getParent();\n if (!parent) {\n return continueEventDispatch();\n }\n parent.invokeCurrentListeners(parent._listeners, eventCopy, type, true);\n parent._defaultSync = this._defaultSync;\n return parent._dispatchEvent(eventCopy, false);\n }\n case phases.NONE:\n default:\n {\n _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke early listeners\n this.invokeCurrentListeners(this._earlyListeners, eventCopy, type);\n if (!('__getParent' in this)) {\n _evCfg.eventPhase = phases.AT_TARGET;\n return this._dispatchEvent(eventCopy, false);\n }\n\n /* eslint-disable consistent-this -- Readability */\n var par = this;\n var root_ = this;\n /* eslint-enable consistent-this -- Readability */\n while (par.__getParent && (par = par.__getParent()) !== null) {\n if (!_evCfg._children) {\n _evCfg._children = [];\n }\n _evCfg._children.push(root_);\n root_ = par;\n }\n root_._defaultSync = this._defaultSync;\n _evCfg.eventPhase = phases.CAPTURING_PHASE;\n return root_._dispatchEvent(eventCopy, false);\n }\n }\n },\n /**\n * @type {InvokeCurrentListeners}\n * @this {EventTarget.prototype & {[key: string]: Listener}}\n */\n invokeCurrentListeners: function invokeCurrentListeners(listeners, eventCopy, type, checkOnListeners) {\n var _this3 = this;\n var _evCfg = evCfg.get(eventCopy);\n _evCfg.currentTarget = this;\n var listOpts = getListenersOptions(listeners, type, {});\n // eslint-disable-next-line unicorn/prefer-spread -- Performance?\n var listenersByType = listOpts.listenersByType.concat();\n var dummyIPos = listenersByType.length ? 1 : 0;\n listenersByType.some(function (listenerObj, i) {\n var onListener = checkOnListeners ? _this3['on' + type] : null;\n if (_evCfg._stopImmediatePropagation) return true;\n if (i === dummyIPos && typeof onListener === 'function') {\n // We don't splice this in as could be overwritten; executes here per\n // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handlers-14\n _this3.tryCatch(eventCopy, function () {\n var ret = onListener.call(eventCopy.currentTarget, eventCopy);\n if (ret === false) {\n eventCopy.preventDefault();\n }\n });\n }\n var options = listenerObj.options;\n var once = options.once,\n passive = options.passive,\n capture = options.capture;\n _evCfg._passive = passive;\n if (capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.CAPTURING_PHASE || eventCopy.eventPhase === phases.AT_TARGET || !capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.BUBBLING_PHASE) {\n var listener = listenerObj.listener;\n _this3.tryCatch(eventCopy, function () {\n listener.call(eventCopy.currentTarget, eventCopy);\n });\n if (once) {\n _this3.removeEventListener(type, listener, options);\n }\n }\n return false;\n });\n this.tryCatch(eventCopy, function () {\n var onListener = checkOnListeners ? _this3['on' + type] : null;\n if (typeof onListener === 'function' && listenersByType.length < 2) {\n var ret = onListener.call(eventCopy.currentTarget, eventCopy); // Won't have executed if too short\n if (ret === false) {\n eventCopy.preventDefault();\n }\n }\n });\n return !eventCopy.defaultPrevented;\n },\n /* eslint-disable promise/prefer-await-to-callbacks -- Try-catch */\n /**\n * @param {EventWithProps} evt\n * @param {() => void} cb\n * @returns {void}\n */\n tryCatch: function tryCatch(evt, cb) {\n /* eslint-enable promise/prefer-await-to-callbacks -- Try-catch */\n try {\n // Per MDN: Exceptions thrown by event handlers are reported\n // as uncaught exceptions; the event handlers run on a nested\n // callstack: they block the caller until they complete, but\n // exceptions do not propagate to the caller.\n // eslint-disable-next-line promise/prefer-await-to-callbacks, n/callback-return -- Try-catch\n cb();\n } catch (err) {\n this.triggerErrorEvent(err, evt);\n }\n },\n /**\n * @param {unknown} err\n * @param {EventWithProps} evt\n * @returns {void}\n */\n triggerErrorEvent: function triggerErrorEvent(err, evt) {\n var error = err;\n if (typeof err === 'string') {\n error = new Error('Uncaught exception: ' + err);\n }\n var triggerGlobalErrorEvent;\n var useNodeImpl = false;\n if (typeof window === 'undefined' || typeof ErrorEvent === 'undefined' || window && (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) === 'object' && !window.dispatchEvent) {\n useNodeImpl = true;\n triggerGlobalErrorEvent = function triggerGlobalErrorEvent() {\n setTimeout(function () {\n // Node won't be able to catch in this way if we throw in the main thread\n // console.log(err); // Should we auto-log for user?\n throw error; // Let user listen to `process.on('uncaughtException', (err) => {});`\n });\n };\n } else {\n triggerGlobalErrorEvent = function triggerGlobalErrorEvent() {\n // See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror\n // and https://github.com/w3c/IndexedDB/issues/49\n\n // Note that a regular Event will properly trigger\n // `window.addEventListener('error')` handlers, but it will not trigger\n // `window.onerror` as per https://html.spec.whatwg.org/multipage/webappapis.html#handler-onerror\n // Note also that the following line won't handle `window.addEventListener` handlers\n // if (window.onerror) window.onerror(error.message, err.fileName, err.lineNumber, error.columnNumber, error);\n\n // `ErrorEvent` properly triggers `window.onerror` and `window.addEventListener('error')` handlers\n var errEv = new ErrorEvent('error', {\n error: err,\n message: /** @type {Error} */error.message || '',\n // We can't get the actually useful user's values!\n filename: /** @type {Error & {fileName: string}} */error.fileName || '',\n lineno: /** @type {Error & {lineNumber: Integer}} */error.lineNumber || 0,\n colno: /** @type {Error & {columnNumber: Integer}} */error.columnNumber || 0\n });\n window.dispatchEvent(errEv);\n // console.log(err); // Should we auto-log for user?\n };\n }\n\n // Todo: This really should always run here but as we can't set the global\n // `window` (e.g., using jsdom) since `setGlobalVars` becomes unable to\n // shim `indexedDB` in such a case currently (apparently due to\n // ), we can't\n // avoid the above Node implementation (which, while providing some\n // fallback mechanism, is unstable)\n if (!useNodeImpl || !this._legacyOutputDidListenersThrowCheck) triggerGlobalErrorEvent();\n\n // See https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke and\n // https://github.com/w3c/IndexedDB/issues/140 (also https://github.com/w3c/IndexedDB/issues/49 )\n if (this._legacyOutputDidListenersThrowCheck) {\n evt.__legacyOutputDidListenersThrowError = error;\n }\n }\n});\nEventTarget.prototype[Symbol.toStringTag] = 'EventTargetPrototype';\nObject.defineProperty(EventTarget, 'prototype', {\n writable: false\n});\nvar ShimEventTarget = EventTarget;\nvar EventTargetFactory = {\n /**\n * @param {CustomOptions} customOptions\n * @returns {EventTarget}\n */\n createInstance: function createInstance(customOptions) {\n /* eslint-disable func-name-matching -- Shim vs. Polyfill */\n /* eslint-disable no-shadow -- Polyfill */\n /**\n * @class\n * @this {typeof ShimEventTarget.prototype}\n */\n var ET = /** @type {unknown} */function EventTarget() {\n /* eslint-enable no-shadow -- Polyfill */\n /* eslint-enable func-name-matching -- Shim vs. Polyfill */\n this.__setOptions(customOptions);\n };\n // @ts-expect-error Casting doesn't work\n ET.prototype = ShimEventTarget.prototype;\n // @ts-expect-error Casting doesn't work\n return new ET();\n }\n};\nEventTarget.ShimEvent = ShimEvent;\nEventTarget.ShimCustomEvent = ShimCustomEvent;\nEventTarget.ShimDOMException = ShimDOMException;\nEventTarget.ShimEventTarget = EventTarget;\nEventTarget.EventTargetFactory = EventTargetFactory;\n\n/**\n * @returns {void}\n */\nfunction setPrototypeOfCustomEvent() {\n // TODO: IDL needs but reported as slow!\n Object.setPrototypeOf(ShimCustomEvent, /** @type {object} */ShimEvent);\n // @ts-expect-error How to overcome?\n Object.setPrototypeOf(ShimCustomEvent.prototype, ShimEvent.prototype);\n}\n\nexport { EventTargetFactory, ShimCustomEvent, ShimDOMException, ShimEvent, EventTarget as ShimEventTarget, setPrototypeOfCustomEvent };\n","/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n/**\n * @typedef {T[keyof T]} ValueOf\n * @template T\n */\n/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */\n\n/**\n * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi\n */\n\n/**\n * @typedef {{\n * DEBUG: boolean,\n * cacheDatabaseInstances: boolean,\n * autoName: boolean,\n * fullIDLSupport: boolean,\n * checkOrigin: boolean,\n * cursorPreloadPackSize: number,\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string,\n * registerSCA: (\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset,\n * avoidAutoShim: boolean,\n * win: {\n * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default\n * },\n * DEFAULT_DB_SIZE: number,\n * useSQLiteIndexes: boolean,\n * fs: FSApi,\n * addNonIDBGlobals: boolean,\n * replaceNonIDBGlobals: boolean,\n * escapeDatabaseName: (name: string) => string,\n * unescapeDatabaseName: (name: string) => string,\n * databaseCharacterEscapeList: string|false,\n * databaseNameLengthLimit: number|false,\n * escapeNFDForDatabaseNames: boolean,\n * addSQLiteExtension: boolean,\n * memoryDatabase: string,\n * deleteDatabaseFiles: boolean,\n * databaseBasePath: string,\n * sysDatabaseBasePath: string,\n * sqlBusyTimeout: number,\n * sqlTrace: () => void,\n * sqlProfile: () => void,\n * createIndexes: boolean\n * }} ConfigValues\n */\n\n/**\n * @typedef {ValueOf} ConfigValue\n */\n\n/** @type {{[key: string]: ConfigValue}} */\nconst map = {};\n\nconst CFG = /** @type {ConfigValues} */ ({});\n\n/**\n * @typedef {keyof ConfigValues} KeyofConfigValues\n */\n\n/**\n * @typedef {KeyofConfigValues[]} Config\n */\n\n/** @type {Config} */\n([\n // Boolean for verbose reporting\n 'DEBUG', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean (effectively defaults to true) on whether to cache WebSQL\n // `openDatabase` instances\n 'cacheDatabaseInstances',\n\n // Boolean on whether to auto-name databases (based on an\n // auto-increment) when the empty string is supplied; useful with\n // `memoryDatabase`; defaults to `false` which means the empty string\n // will be used as the (valid) database name\n 'autoName',\n\n // Determines whether the slow-performing `Object.setPrototypeOf`\n // calls required for full WebIDL compliance will be used. Probably\n // only needed for testing or environments where full introspection\n // on class relationships is required; see\n // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`)\n\n // Boolean on whether to perform origin checks in `IDBFactory` methods\n // Effectively defaults to `true` (must be set to `false` to cancel checks)\n 'checkOrigin',\n\n // Used by `IDBCursor` continue methods for number of records to cache;\n // Defaults to 100\n 'cursorPreloadPackSize',\n\n // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);\n // or just use the Unicode builds which invoke this method\n // automatically using the large, fully spec-compliant, regular\n // expression strings of `src/UnicodeIdentifiers.js`)\n // In the non-Unicode builds, defaults to /[$A-Z_a-z]/\n 'UnicodeIDStart',\n // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/\n 'UnicodeIDContinue',\n\n // Used by SCA.js for optional restructuring of typeson-registry\n // Structured Cloning Algorithm; should only be needed for ensuring data\n // created in 3.* versions of IndexedDBShim continue to work; see the\n // library `typeson-registry-sca-reverter` to get a function to do this\n 'registerSCA',\n\n // BROWSER-SPECIFIC CONFIG\n 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is\n // missing or poor support is known (non-Chrome Android or\n // non-Safari iOS9), the shim will be auto-applied without\n // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing\n // the shim for such cases.\n\n // -----------SQL CONFIG----------\n // Object (`window` in the browser) on which there may be an\n // `openDatabase` method (if any) for WebSQL. (The browser\n // throws if attempting to call `openDatabase` without the window\n // so this is why the config doesn't just allow the function.)\n // Defaults to `window` or `self` in browser builds or\n // a singleton object with the `openDatabase` method set to\n // the \"websql\" package in Node.\n 'win',\n\n // For internal `openDatabase` calls made by `IDBFactory` methods;\n // per the WebSQL spec, \"User agents are expected to use the display name\n // and the estimated database size to optimize the user experience.\n // For example, a user agent could use the estimated size to suggest an\n // initial quota to the user. This allows a site that is aware that it\n // will try to use hundreds of megabytes to declare this upfront, instead\n // of the user agent prompting the user for permission to increase the\n // quota every five megabytes.\"\n // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari\n 'DEFAULT_DB_SIZE',\n // Whether to create indexes on SQLite tables (and also whether to try\n // dropping)\n // Effectively defaults to `false` (ignored unless `true`)\n 'useSQLiteIndexes',\n\n // NODE-IMPINGING SETTINGS (created for sake of limitations in Node\n // or desktop file system implementation but applied by default in\n // browser for parity)\n\n // File system module with `unlink` to remove deleted database files\n 'fs',\n\n // Used when setting global shims to determine whether to try to add\n // other globals shimmed by the library (`ShimDOMException`,\n // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'addNonIDBGlobals',\n // Used when setting global shims to determine whether to try to overwrite\n // other globals shimmed by the library (`DOMException`, `DOMStringList`,\n // `Event`, `CustomEvent`, `EventTarget`)\n // Effectively defaults to `false` (ignored unless `true`)\n 'replaceNonIDBGlobals',\n\n // Overcoming limitations with node-sqlite3/storing database name on\n // file systems\n // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words\n // Defaults to prefixing database with `D_`, escaping\n // `databaseCharacterEscapeList`, escaping NUL, and\n // escaping upper case letters, as well as enforcing\n // `databaseNameLengthLimit`\n 'escapeDatabaseName',\n // Not used internally; usable as a convenience method\n 'unescapeDatabaseName',\n\n // Defaults to global regex representing the following\n // (characters nevertheless commonly reserved in modern,\n // Unicode-supporting systems): 0x00-0x1F 0x7F \" * / : < > ? \\ |\n 'databaseCharacterEscapeList',\n // Defaults to 254 (shortest typical modern file length limit)\n 'databaseNameLengthLimit',\n\n // Boolean defaulting to true on whether to escape NFD-escaping\n // characters to avoid clashes on MacOS which performs NFD on files\n 'escapeNFDForDatabaseNames',\n\n // Boolean on whether to add the `.sqlite` extension to file names;\n // defaults to `true`\n 'addSQLiteExtension',\n // Various types of in-memory databases that can auto-delete\n [\n 'memoryDatabase',\n /**\n * @param {string} val\n * @throws {TypeError}\n * @returns {void}\n */\n (val) => {\n if (!(/^(?::memory:|file::memory:(\\?[^#]*)?(#.*)?)?$/u).test(\n /** @type {string} */ (val)\n )) {\n throw new TypeError(\n '`memoryDatabase` must be the empty string, \":memory:\", or a ' +\n '\"file::memory:[?queryString][#hash] URL\".'\n );\n }\n }\n ],\n\n // NODE-SPECIFIC CONFIG\n // Boolean on whether to delete the database file itself after\n // `deleteDatabase`; defaults to `true` as the database will be empty\n 'deleteDatabaseFiles',\n 'databaseBasePath',\n 'sysDatabaseBasePath',\n\n // NODE-SPECIFIC WEBSQL CONFIG\n 'sqlBusyTimeout', // Defaults to 1000\n 'sqlTrace', // Callback not used by default\n 'sqlProfile', // Callback not used by default\n\n 'createIndexes'\n]).forEach((prop) => {\n /** @type {(val: any) => void} */\n let validator;\n if (Array.isArray(prop)) {\n [prop, validator] = prop;\n }\n Object.defineProperty(CFG, prop, {\n get () {\n return map[prop];\n },\n set (val) {\n if (validator) {\n validator(val);\n }\n map[prop] = val;\n }\n });\n});\n\nexport default CFG;\n","// @ts-nocheck\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar regex=/[\\xC0-\\xC5\\xC7-\\xCF\\xD1-\\xD6\\xD9-\\xDD\\xE0-\\xE5\\xE7-\\xEF\\xF1-\\xF6\\xF9-\\xFD\\xFF-\\u010F\\u0112-\\u0125\\u0128-\\u0130\\u0134-\\u0137\\u0139-\\u013E\\u0143-\\u0148\\u014C-\\u0151\\u0154-\\u0165\\u0168-\\u017E\\u01A0\\u01A1\\u01AF\\u01B0\\u01CD-\\u01DC\\u01DE-\\u01E3\\u01E6-\\u01F0\\u01F4\\u01F5\\u01F8-\\u021B\\u021E\\u021F\\u0226-\\u0233\\u0344\\u0385\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u0390\\u03AA-\\u03B0\\u03CA-\\u03CE\\u03D3\\u03D4\\u0400\\u0401\\u0403\\u0407\\u040C-\\u040E\\u0419\\u0439\\u0450\\u0451\\u0453\\u0457\\u045C-\\u045E\\u0476\\u0477\\u04C1\\u04C2\\u04D0-\\u04D3\\u04D6\\u04D7\\u04DA-\\u04DF\\u04E2-\\u04E7\\u04EA-\\u04F5\\u04F8\\u04F9\\u0622-\\u0626\\u06C0\\u06C2\\u06D3\\u0929\\u0931\\u0934\\u0958-\\u095F\\u09CB\\u09CC\\u09DC\\u09DD\\u09DF\\u0A33\\u0A36\\u0A59-\\u0A5B\\u0A5E\\u0B48\\u0B4B\\u0B4C\\u0B5C\\u0B5D\\u0B94\\u0BCA-\\u0BCC\\u0C48\\u0CC0\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0D4A-\\u0D4C\\u0DDA\\u0DDC-\\u0DDE\\u0F43\\u0F4D\\u0F52\\u0F57\\u0F5C\\u0F69\\u0F73\\u0F75\\u0F76\\u0F78\\u0F81\\u0F93\\u0F9D\\u0FA2\\u0FA7\\u0FAC\\u0FB9\\u1026\\u1B06\\u1B08\\u1B0A\\u1B0C\\u1B0E\\u1B12\\u1B3B\\u1B3D\\u1B40\\u1B41\\u1B43\\u1E00-\\u1E99\\u1E9B\\u1EA0-\\u1EF9\\u1F00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FC1-\\u1FC4\\u1FC6-\\u1FD3\\u1FD6-\\u1FDB\\u1FDD-\\u1FEE\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u212B\\u219A\\u219B\\u21AE\\u21CD-\\u21CF\\u2204\\u2209\\u220C\\u2224\\u2226\\u2241\\u2244\\u2247\\u2249\\u2260\\u2262\\u226D-\\u2271\\u2274\\u2275\\u2278\\u2279\\u2280\\u2281\\u2284\\u2285\\u2288\\u2289\\u22AC-\\u22AF\\u22E0-\\u22E3\\u22EA-\\u22ED\\u2ADC\\u304C\\u304E\\u3050\\u3052\\u3054\\u3056\\u3058\\u305A\\u305C\\u305E\\u3060\\u3062\\u3065\\u3067\\u3069\\u3070\\u3071\\u3073\\u3074\\u3076\\u3077\\u3079\\u307A\\u307C\\u307D\\u3094\\u309E\\u30AC\\u30AE\\u30B0\\u30B2\\u30B4\\u30B6\\u30B8\\u30BA\\u30BC\\u30BE\\u30C0\\u30C2\\u30C5\\u30C7\\u30C9\\u30D0\\u30D1\\u30D3\\u30D4\\u30D6\\u30D7\\u30D9\\u30DA\\u30DC\\u30DD\\u30F4\\u30F7-\\u30FA\\u30FE\\uAC00-\\uD7A3\\uFB1D\\uFB1F\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFB4E]|\\uD804[\\uDC9A\\uDC9C\\uDCAB\\uDD2E\\uDD2F\\uDF4B\\uDF4C]|\\uD805[\\uDCBB\\uDCBC\\uDCBE\\uDDBA\\uDDBB]|\\uD806\\uDD38|\\uD834[\\uDD5E-\\uDD64\\uDDBB-\\uDDC0]/;\n\nvar regex$1 = /*@__PURE__*/getDefaultExportFromCjs(regex);\n\nexport { regex$1 as default };\n","/* eslint-disable new-cap -- ToString is how it is defined */\nimport CFG from './CFG.js';\nimport expandsOnNFD from './unicode-regex.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeUnmatchedSurrogates (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return arg.replaceAll(\n /([\\uD800-\\uDBFF])(?![\\uDC00-\\uDFFF])|(^|[^\\uD800-\\uDBFF])([\\uDC00-\\uDFFF])/gu,\n function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {\n // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577\n // but Chrome having problems\n if (unmatchedHighSurrogate) {\n return '^2' + unmatchedHighSurrogate.codePointAt()\n .toString(16).padStart(4, '0');\n }\n return (precedingLow || '') + '^3' +\n unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');\n }\n );\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeNameForSQLiteIdentifier (arg) {\n // http://stackoverflow.com/a/6701665/271577\n return '_' + // Prevent empty string\n escapeUnmatchedSurrogates(\n arg.replaceAll('^', '^^') // Escape our escape\n // http://www.sqlite.org/src/tktview?name=57c971fc74\n .replaceAll('\\0', '^0')\n // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names\n // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577\n // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working\n .replaceAll(/([A-Z])/gu, '^$1')\n );\n}\n\n/**\n * The escaping of unmatched surrogates was needed by Chrome but not Node.\n * @param {string} arg\n * @returns {string}\n */\nfunction escapeSQLiteStatement (arg) {\n return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\\0', '^0'));\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeSQLiteResponse (arg) {\n return unescapeUnmatchedSurrogates(arg)\n .replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n })\n .replaceAll('^^', '^');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlEscape (arg) {\n // https://www.sqlite.org/lang_keywords.html\n // http://stackoverflow.com/a/6701665/271577\n // There is no need to escape ', `, or [], as\n // we should always be within double quotes\n // NUL should have already been stripped\n return arg.replaceAll('\"', '\"\"');\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction sqlQuote (arg) {\n return '\"' + sqlEscape(arg) + '\"';\n}\n\n/**\n * @param {string} db\n * @throws {Error}\n * @returns {string}\n */\nfunction escapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.escapeDatabaseName) {\n // We at least ensure NUL is escaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), escaping casing (including Unicode?),\n // and escaping special characters depending on file system\n return CFG.escapeDatabaseName(escapeSQLiteStatement(db));\n }\n db = 'D' + escapeNameForSQLiteIdentifier(db);\n if (CFG.escapeNFDForDatabaseNames !== false) {\n // ES6 copying of regex with different flags\n db = db.replaceAll(new RegExp(expandsOnNFD, 'gu'), function (expandable) {\n return '^4' + /** @type {Integer} */ (expandable.codePointAt(0)).toString(16).padStart(6, '0');\n });\n }\n if (CFG.databaseCharacterEscapeList !== false) {\n db = db.replace(\n (CFG.databaseCharacterEscapeList\n ? new RegExp(CFG.databaseCharacterEscapeList, 'gu')\n : /[\\u0000-\\u001F\\u007F\"*/:<>?\\\\|]/gu), // eslint-disable-line no-control-regex -- Controls needed\n function (n0) {\n // eslint-disable-next-line unicorn/prefer-code-point -- Switch to `codePointAt`?\n return '^1' + n0.charCodeAt(0).toString(16).padStart(2, '0');\n }\n );\n }\n if (CFG.databaseNameLengthLimit !== false &&\n db.length >= ((CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0))) {\n throw new Error(\n 'Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' +\n db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'\n );\n }\n return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?)\n}\n\n/**\n * @param {string} arg\n * @returns {string}\n */\nfunction unescapeUnmatchedSurrogates (arg) {\n return arg\n .replaceAll(/(\\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(lowSurr, 16))\n : _;\n }).replaceAll(/(\\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(highSurr, 16))\n : _;\n });\n}\n\n/**\n * Not in use internally but supplied for convenience.\n * @param {string} db\n * @returns {string}\n */\nfunction unescapeDatabaseNameForSQLAndFiles (db) {\n if (CFG.unescapeDatabaseName) {\n // We at least ensure NUL is unescaped by default, but we need to still\n // handle empty string and possibly also length (potentially\n // throwing if too long), unescaping casing (including Unicode?),\n // and unescaping special characters depending on file system\n return CFG.unescapeDatabaseName(unescapeSQLiteResponse(db));\n }\n\n return unescapeUnmatchedSurrogates(\n db.slice(2) // D_\n // CFG.databaseCharacterEscapeList\n .replaceAll(/(\\^+)1([0-9a-f]{2})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n // CFG.escapeNFDForDatabaseNames\n }).replaceAll(/(\\^+)4([0-9a-f]{6})/gu, (_, esc, hex) => {\n return esc.length % 2\n ? esc.slice(1) + String.fromCodePoint(Number.parseInt(hex, 16))\n : _;\n })\n // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above)\n ).replaceAll(/(\\^+)([A-Z])/gu, (_, esc, upperCase) => {\n return esc.length % 2\n ? esc.slice(1) + upperCase\n : _;\n }).replaceAll(/(\\^+)0/gu, (_, esc) => {\n return esc.length % 2\n ? esc.slice(1) + '\\0'\n : _;\n }).replaceAll('^^', '^');\n}\n\n/**\n * @param {string} store\n * @returns {string}\n */\nfunction escapeStoreNameForSQL (store) {\n return sqlQuote('S' + escapeNameForSQLiteIdentifier(store));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQL (index) {\n return sqlQuote('I' + escapeNameForSQLiteIdentifier(index));\n}\n\n/**\n * @param {string} index\n * @returns {string}\n */\nfunction escapeIndexNameForSQLKeyColumn (index) {\n return 'I' + escapeNameForSQLiteIdentifier(index);\n}\n\n/**\n * @param {string} str\n * @returns {string}\n */\nfunction sqlLIKEEscape (str) {\n // https://www.sqlite.org/lang_expr.html#like\n return sqlEscape(str).replaceAll('^', '^^');\n}\n\n/**\n * @typedef {Function} AnyClass\n */\n\n// Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?)\n/**\n *\n * @param {AnyValue} obj\n * @param {AnyClass} Clss\n * @returns {boolean}\n */\nfunction instanceOf (obj, Clss) {\n return Clss[Symbol.hasInstance](obj);\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {obj is object}\n */\nfunction isObj (obj) {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isDate (obj) {\n return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isBlob (obj) {\n return isObj(obj) && 'size' in obj && typeof obj.size === 'number' &&\n 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isRegExp (obj) {\n return isObj(obj) && 'flags' in obj && typeof obj.flags === 'string' &&\n 'exec' in obj && typeof obj.exec === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @returns {boolean}\n */\nfunction isFile (obj) {\n return isObj(obj) && 'name' in obj && typeof obj.name === 'string' &&\n 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isBinary (obj) {\n return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && (\n ('slice' in obj && typeof obj.slice === 'function') || // `TypedArray` (view on buffer) or `ArrayBuffer`\n ('getFloat64' in obj && typeof obj.getFloat64 === 'function') // `DataView` (view on buffer)\n );\n}\n\n/**\n *\n * @param {AnyValue} obj\n * @returns {boolean}\n */\nfunction isIterable (obj) {\n return isObj(obj) && Symbol.iterator in obj &&\n typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n },\n // @ts-expect-error Deliberately errs\n set [prop] (val) {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string[]} props\n * @returns {void}\n */\nfunction defineReadonlyOuterInterface (obj, props) {\n props.forEach((prop) => {\n const o = {\n get [prop] () {\n throw new TypeError('Illegal invocation');\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {object & {\n * [key: string]: any\n * }} obj\n * @param {string[]} listeners\n * @returns {void}\n */\nfunction defineListenerProperties (obj, listeners) {\n listeners = typeof listeners === 'string' ? [listeners] : listeners;\n listeners.forEach((listener) => {\n const o = {\n get [listener] () {\n return obj['__' + listener];\n },\n /**\n * @param {AnyValue} val\n * @returns {void}\n */\n set [listener] (val) {\n obj['__' + listener] = val;\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, listener)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners)\n Object.defineProperty(obj, listener, desc);\n });\n listeners.forEach((l) => {\n obj[l] = null;\n });\n}\n\n/**\n *\n * @param {object} obj\n * @param {string|string[]} props\n * @param {null|{\n * [key: string]: any\n * }} getter\n * @returns {void}\n */\nfunction defineReadonlyProperties (obj, props, getter = null) {\n props = typeof props === 'string' ? [props] : props;\n props.forEach(function (prop) {\n let o;\n if (getter && prop in getter) {\n o = getter[prop];\n } else {\n Object.defineProperty(obj, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // We must resort to this to get \"get \" as\n // the function `name` for proper IDL\n o = {\n get [prop] () {\n return this['__' + prop];\n }\n };\n }\n\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(obj, prop, desc);\n });\n}\n\n/**\n *\n * @param {string} item\n * @returns {boolean}\n */\nfunction isIdentifier (item) {\n // For load-time and run-time performance, we don't provide the complete regular\n // expression for identifiers, but these can be passed in, using the expressions\n // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407\n // ID_Start (includes Other_ID_Start)\n const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]';\n // ID_Continue (includes Other_ID_Continue)\n const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]';\n const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])';\n const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\\u200C\\u200D])';\n return (new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u')).test(item);\n}\n\n/**\n *\n * @param {string|string[]} keyPathString\n * @returns {boolean}\n */\nfunction isValidKeyPathString (keyPathString) {\n return typeof keyPathString === 'string' &&\n (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every((pathComponent) => {\n return isIdentifier(pathComponent);\n }));\n}\n\n/**\n *\n * @param {string|string[]} keyPath\n * @returns {boolean}\n */\nfunction isValidKeyPath (keyPath) {\n return isValidKeyPathString(keyPath) || (\n Array.isArray(keyPath) && Boolean(keyPath.length) &&\n // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html\n // See also https://heycam.github.io/webidl/#idl-DOMString\n [...keyPath].every((pathComponent) => {\n return isValidKeyPathString(pathComponent);\n })\n );\n}\n\n/**\n * @param {number} number\n * @param {\"unsigned long long\"|\"unsigned long\"} type\n * @throws {Error|TypeError}\n * @returns {number}\n */\nfunction enforceRange (number, type) {\n number = Math.floor(Number(number));\n let max, min;\n switch (type) {\n case 'unsigned long long': {\n max = 0x1FFFFFFFFFFFFF; // 2^53 - 1\n min = 0;\n break;\n }\n case 'unsigned long': {\n max = 0xFFFFFFFF; // 2^32 - 1\n min = 0;\n break;\n }\n default:\n throw new Error('Unrecognized type supplied to enforceRange');\n }\n if (!Number.isFinite(number) ||\n number > max ||\n number < min) {\n throw new TypeError('Invalid range: ' + number);\n }\n return number;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {AnyValue} v\n * @param {boolean} [treatNullAs]\n * @returns {string}\n */\nfunction convertToDOMString (v, treatNullAs) {\n return v === null && treatNullAs ? '' : ToString(v);\n}\n\n/**\n * @param {AnyValue} o\n * @returns {string}\n */\nfunction ToString (o) { // Todo: See `es-abstract/es7`\n // `String()` will not throw with Symbols\n return '' + o; // eslint-disable-line no-implicit-coercion -- Need to throw with symbols\n}\n\n/**\n *\n * @param {AnyValue} val\n * @returns {string|string[]}\n */\nfunction convertToSequenceDOMString (val) {\n // Per , converting to a sequence works with iterables\n if (isIterable(val)) { // We don't want conversion to array to convert primitives\n // Per , converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring\n return [...val].map((item) => {\n return ToString(item);\n });\n }\n return ToString(val);\n}\n\n/**\n * @param {AnyValue} v\n * @returns {v is null|undefined}\n */\nfunction isNullish (v) {\n return v === null || v === undefined;\n}\n\nexport {escapeSQLiteStatement, unescapeSQLiteResponse,\n escapeDatabaseNameForSQLAndFiles, unescapeDatabaseNameForSQLAndFiles,\n escapeStoreNameForSQL, escapeIndexNameForSQL, escapeIndexNameForSQLKeyColumn,\n sqlLIKEEscape, sqlQuote,\n instanceOf,\n isObj, isDate, isBlob, isRegExp, isFile, isBinary, isIterable,\n defineOuterInterface, defineReadonlyOuterInterface,\n defineListenerProperties, defineReadonlyProperties,\n isValidKeyPath, enforceRange,\n convertToDOMString, convertToSequenceDOMString,\n isNullish};\n","import {ShimEventTarget, ShimEvent, ShimCustomEvent} from 'eventtargeter';\nimport * as util from './util.js';\n\n/**\n * @typedef {Error} DebuggingError\n */\n\n/**\n *\n * @param {string} type\n * @param {DebuggingError|null} [debug]\n * @param {EventInit} [evInit]\n * @returns {Event & {\n * __legacyOutputDidListenersThrowError?: boolean\n * }}\n */\nfunction createEvent (type, debug, evInit) {\n // @ts-expect-error It's ok\n const ev = new ShimEvent(type, evInit);\n ev.debug = debug;\n return ev;\n}\n\n// We don't add within polyfill repo as might not always be the desired implementation\nObject.defineProperty(ShimEvent, Symbol.hasInstance, {\n /**\n * @typedef {any} AnyValue\n */\n value:\n /**\n * @param {AnyValue} obj\n * @returns {boolean}\n */\n (obj) => util.isObj(obj) && 'target' in obj && 'bubbles' in obj && typeof obj.bubbles === 'boolean'\n});\n\nexport {createEvent, ShimEvent, ShimCustomEvent, ShimEventTarget};\n","import {ShimEvent} from './Event.js';\nimport * as util from './util.js';\n\nconst readonlyProperties = ['oldVersion', 'newVersion'];\n\n/**\n * Babel apparently having a problem adding `hasInstance` to a class,\n * so we are redefining as a function.\n * @class\n * @param {string} type\n */\nfunction IDBVersionChangeEvent (type /* , eventInitDict */) { // eventInitDict is a IDBVersionChangeEventInit (but is not defined as a global)\n // @ts-expect-error It's passing only one!\n ShimEvent.call(this, type);\n this[Symbol.toStringTag] = 'IDBVersionChangeEvent';\n this.toString = function () {\n return '[object IDBVersionChangeEvent]';\n };\n // eslint-disable-next-line prefer-rest-params -- API\n this.__eventInitDict = arguments[1] || {};\n}\n\n// @ts-expect-error It's ok\nIDBVersionChangeEvent.prototype = Object.create(ShimEvent.prototype);\n\nIDBVersionChangeEvent.prototype[Symbol.toStringTag] = 'IDBVersionChangeEventPrototype';\n\n/**\n * @typedef {number} Integer\n */\n\nreadonlyProperties.forEach((prop) => {\n // Ensure for proper interface testing that \"get \" is the function name\n const o = {\n /**\n * @returns {Integer|null}\n */\n get [prop] () {\n if (!(this instanceof IDBVersionChangeEvent)) {\n throw new TypeError('Illegal invocation');\n }\n return (this.__eventInitDict && this.__eventInitDict[prop]) || (prop === 'oldVersion' ? 0 : null);\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(IDBVersionChangeEvent.prototype, prop, desc);\n});\n\nObject.defineProperty(IDBVersionChangeEvent, Symbol.hasInstance, {\n /**\n * @typedef {any} AnyValue\n */\n value:\n /**\n * @param {AnyValue} obj\n * @returns {boolean}\n */\n (obj) => util.isObj(obj) && 'oldVersion' in obj &&\n 'defaultPrevented' in obj && typeof obj.defaultPrevented === 'boolean'\n});\n\nObject.defineProperty(IDBVersionChangeEvent.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBVersionChangeEvent\n});\n\nObject.defineProperty(IDBVersionChangeEvent, 'prototype', {\n writable: false\n});\n\nexport default IDBVersionChangeEvent;\n","import CFG from './CFG.js';\n\n/**\n * Creates a native DOMException, for browsers that support it.\n * @param {string} name\n * @param {string} message\n * @returns {DOMException}\n */\nfunction createNativeDOMException (name, message) {\n // @ts-expect-error It's ok\n return new DOMException.prototype.constructor(\n message,\n name || 'DOMException'\n );\n}\n\n// From web-platform-tests testharness.js name_code_map (though not in new spec)\n\n/**\n * @typedef {\"IndexSizeError\"|\"HierarchyRequestError\"|\"WrongDocumentError\"|\n * \"InvalidCharacterError\"|\"NoModificationAllowedError\"|\"NotFoundError\"|\n * \"NotSupportedError\"|\"InUseAttributeError\"|\"InvalidStateError\"|\n * \"SyntaxError\"|\"InvalidModificationError\"|\"NamespaceError\"|\n * \"InvalidAccessError\"|\"TypeMismatchError\"|\"SecurityError\"|\n * \"NetworkError\"|\"AbortError\"|\"URLMismatchError\"|\"QuotaExceededError\"|\n * \"TimeoutError\"|\"InvalidNodeTypeError\"|\"DataCloneError\"|\"EncodingError\"|\n * \"NotReadableError\"|\"UnknownError\"|\"ConstraintError\"|\"DataError\"|\n * \"TransactionInactiveError\"|\"ReadOnlyError\"|\"VersionError\"|\n * \"OperationError\"|\"NotAllowedError\"} Code\n */\n\nconst codes = {\n IndexSizeError: 1,\n HierarchyRequestError: 3,\n WrongDocumentError: 4,\n InvalidCharacterError: 5,\n NoModificationAllowedError: 7,\n NotFoundError: 8,\n NotSupportedError: 9,\n InUseAttributeError: 10,\n InvalidStateError: 11,\n SyntaxError: 12,\n InvalidModificationError: 13,\n NamespaceError: 14,\n InvalidAccessError: 15,\n TypeMismatchError: 17,\n SecurityError: 18,\n NetworkError: 19,\n AbortError: 20,\n URLMismatchError: 21,\n QuotaExceededError: 22,\n TimeoutError: 23,\n InvalidNodeTypeError: 24,\n DataCloneError: 25,\n\n EncodingError: 0,\n NotReadableError: 0,\n UnknownError: 0,\n ConstraintError: 0,\n DataError: 0,\n TransactionInactiveError: 0,\n ReadOnlyError: 0,\n VersionError: 0,\n OperationError: 0,\n NotAllowedError: 0\n};\n\n/**\n * @typedef {\"INDEX_SIZE_ERR\"|\"DOMSTRING_SIZE_ERR\"|\"HIERARCHY_REQUEST_ERR\"|\n * \"WRONG_DOCUMENT_ERR\"|\"INVALID_CHARACTER_ERR\"|\"NO_DATA_ALLOWED_ERR\"|\n * \"NO_MODIFICATION_ALLOWED_ERR\"|\"NOT_FOUND_ERR\"|\"NOT_SUPPORTED_ERR\"|\n * \"INUSE_ATTRIBUTE_ERR\"|\"INVALID_STATE_ERR\"|\"SYNTAX_ERR\"|\n * \"INVALID_MODIFICATION_ERR\"|\"NAMESPACE_ERR\"|\"INVALID_ACCESS_ERR\"|\n * \"VALIDATION_ERR\"|\"TYPE_MISMATCH_ERR\"|\"SECURITY_ERR\"|\"NETWORK_ERR\"|\n * \"ABORT_ERR\"|\"URL_MISMATCH_ERR\"|\"QUOTA_EXCEEDED_ERR\"|\"TIMEOUT_ERR\"|\n * \"INVALID_NODE_TYPE_ERR\"|\"DATA_CLONE_ERR\"} LegacyCode\n */\n\nconst legacyCodes = {\n INDEX_SIZE_ERR: 1,\n DOMSTRING_SIZE_ERR: 2,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n INVALID_CHARACTER_ERR: 5,\n NO_DATA_ALLOWED_ERR: 6,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INUSE_ATTRIBUTE_ERR: 10,\n INVALID_STATE_ERR: 11,\n SYNTAX_ERR: 12,\n INVALID_MODIFICATION_ERR: 13,\n NAMESPACE_ERR: 14,\n INVALID_ACCESS_ERR: 15,\n VALIDATION_ERR: 16,\n TYPE_MISMATCH_ERR: 17,\n SECURITY_ERR: 18,\n NETWORK_ERR: 19,\n ABORT_ERR: 20,\n URL_MISMATCH_ERR: 21,\n QUOTA_EXCEEDED_ERR: 22,\n TIMEOUT_ERR: 23,\n INVALID_NODE_TYPE_ERR: 24,\n DATA_CLONE_ERR: 25\n};\n\n/**\n *\n * @returns {typeof DOMException}\n */\nfunction createNonNativeDOMExceptionClass () {\n /**\n * @param {string|undefined} message\n * @param {Code|LegacyCode} name\n * @returns {void}\n */\n function DOMException (message, name) {\n // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message\n this[Symbol.toStringTag] = 'DOMException';\n this._code = name in codes\n ? codes[/** @type {Code} */ (name)]\n : (legacyCodes[/** @type {LegacyCode} */ (name)] || 0);\n this._name = name || 'Error';\n // We avoid `String()` in this next line as it converts Symbols\n this._message = message === undefined ? '' : ('' + message); // eslint-disable-line no-implicit-coercion -- Don't convert symbols\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._code\n });\n if (name !== undefined) {\n Object.defineProperty(this, 'name', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: this._name\n });\n }\n if (message !== undefined) {\n Object.defineProperty(this, 'message', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: this._message\n });\n }\n }\n\n // Necessary for W3C tests which complains if `DOMException` has properties on its \"own\" prototype\n\n // class DummyDOMException extends Error {}; // Sometimes causing problems in Node\n /* eslint-disable func-name-matching -- See above */\n /**\n * @class\n */\n const DummyDOMException = function DOMException () { /* */ };\n /* eslint-enable func-name-matching -- See above */\n DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing\n /** @type {const} */ (['name', 'message']).forEach((prop) => {\n Object.defineProperty(DummyDOMException.prototype, prop, {\n enumerable: true,\n /**\n * @this {DOMException}\n * @returns {string}\n */\n get () {\n if (!(this instanceof DOMException ||\n // @ts-expect-error Just checking\n this instanceof DummyDOMException ||\n // @ts-expect-error Just checking\n this instanceof Error)) {\n throw new TypeError('Illegal invocation');\n }\n return this[prop === 'name' ? '_name' : '_message'];\n }\n });\n });\n // DOMException uses the same `toString` as `Error`\n Object.defineProperty(DummyDOMException.prototype, 'code', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n // @ts-expect-error It's ok\n DOMException.prototype = new DummyDOMException();\n\n DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';\n Object.defineProperty(DOMException, 'prototype', {\n writable: false\n });\n\n const keys = Object.keys(codes);\n\n /** @type {(keyof codes)[]} */ (keys).forEach(\n (codeName) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: codes[codeName]\n });\n }\n );\n /** @type {(keyof legacyCodes)[]} */ (Object.keys(legacyCodes)).forEach((\n codeName\n ) => {\n Object.defineProperty(DOMException.prototype, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n Object.defineProperty(DOMException, codeName, {\n enumerable: true,\n configurable: false,\n value: legacyCodes[codeName]\n });\n });\n Object.defineProperty(DOMException.prototype, 'constructor', {\n writable: true,\n configurable: true,\n enumerable: false,\n value: DOMException\n });\n\n // @ts-expect-error We don't need all its properties\n return DOMException;\n}\n\nconst ShimNonNativeDOMException = createNonNativeDOMExceptionClass();\n\n/**\n * Creates a generic Error object.\n * @param {string} name\n * @param {string} message\n * @returns {Error}\n */\nfunction createNonNativeDOMException (name, message) {\n return new ShimNonNativeDOMException(message, name);\n}\n\n/**\n * @typedef {{\n * message: string|DOMString\n * }} ErrorLike\n */\n\n/**\n * Logs detailed error information to the console.\n * @param {string} name\n * @param {string} message\n * @param {string|ErrorLike|boolean|null} [error]\n * @returns {void}\n */\nfunction logError (name, message, error) {\n if (CFG.DEBUG) {\n const msg = error && typeof error === 'object' && error.message\n ? error.message\n : /** @type {string} */ (error);\n\n const method = typeof (console.error) === 'function' ? 'error' : 'log';\n console[method](name + ': ' + message + '. ' + (msg || ''));\n if (console.trace) { console.trace(); }\n }\n}\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @param {ArbitraryValue} obj\n * @returns {boolean}\n */\nfunction isErrorOrDOMErrorOrDOMException (obj) {\n return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser\n typeof obj.name === 'string';\n}\n\n/**\n * Finds the error argument. This is useful because some WebSQL callbacks\n * pass the error as the first argument, and some pass it as the second\n * argument.\n * @param {(Error|{message?: string, name?: string}|any)[]} args\n * @returns {Error|DOMException|undefined}\n */\nfunction findError (args) {\n let err;\n if (args) {\n if (args.length === 1) {\n return args[0];\n }\n for (const arg of args) {\n if (isErrorOrDOMErrorOrDOMException(arg)) {\n return arg;\n }\n if (arg && typeof arg.message === 'string') {\n err = arg;\n }\n }\n }\n return err;\n}\n\n/**\n *\n * @param {SQLError} webSQLErr\n * @returns {(DOMException|Error) & {\n * sqlError: SQLError\n * }}\n */\nfunction webSQLErrback (webSQLErr) {\n let name, message;\n switch (webSQLErr.code) {\n case 4: { // SQLError.QUOTA_ERR\n name = 'QuotaExceededError';\n message = 'The operation failed because there was not enough ' +\n 'remaining storage space, or the storage quota was reached ' +\n 'and the user declined to give more space to the database.';\n break;\n }\n /*\n // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`?\n case 7: { // SQLError.TIMEOUT_ERR\n // All transaction errors abort later, so no need to mark inactive\n name = 'TransactionInactiveError';\n message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).';\n break;\n }\n */\n default: {\n name = 'UnknownError';\n message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.';\n break;\n }\n }\n message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')';\n const err =\n /**\n * @type {(Error | DOMException) & {\n * sqlError: SQLError\n * }}\n */\n (createDOMException(name, message));\n err.sqlError = webSQLErr;\n return err;\n}\n\nlet test, useNativeDOMException = false;\n\n// Test whether we can use the browser's native DOMException class\ntry {\n test = createNativeDOMException('test name', 'test message');\n if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {\n // Native DOMException works as expected\n useNativeDOMException = true;\n }\n// eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n} catch (err) {}\n\nconst createDOMException = useNativeDOMException\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n ? /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {DOMException}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNativeDOMException(name, message);\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc\n : /**\n * @param {string} name\n * @param {string} message\n * @param {ErrorLike} [error]\n * @returns {Error}\n */\n function (name, message, error) {\n logError(name, message, error);\n return createNonNativeDOMException(name, message);\n };\n\nconst ShimDOMException = useNativeDOMException\n ? DOMException\n : ShimNonNativeDOMException;\n\nexport {logError, findError, ShimDOMException, createDOMException, webSQLErrback};\n","import {EventTargetFactory} from 'eventtargeter';\nimport {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\n\nconst listeners = ['onsuccess', 'onerror'];\nconst readonlyProperties = ['source', 'transaction', 'readyState'];\nconst doneFlagGetters = ['result', 'error'];\n\n/**\n * The IDBRequest Object that is returns for all async calls.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#request-api\n * @class\n */\nfunction IDBRequest () {\n throw new TypeError('Illegal constructor');\n}\n\n/**\n * @typedef {IDBRequest & EventTarget & import('eventtargeter').ShimEventTarget & {\n * transaction: import('./IDBTransaction.js').IDBTransactionFull,\n * __done: boolean,\n * __result: import('./IDBDatabase.js').IDBDatabaseFull|undefined,\n * __error: null|DOMException|Error,\n * __source: null|import('./IDBDatabase.js').IDBDatabaseFull|\n * import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull,\n * __transaction: undefined|null|\n * import('./IDBTransaction.js').IDBTransactionFull,\n * addLateEventListener: (ev: string, listener: (e: Event & {\n * __legacyOutputDidListenersThrowError: boolean\n * }) => void) => void\n * addDefaultEventListener: (ev: string, listener: (e: Event & {\n * __legacyOutputDidListenersThrowError: boolean\n * }) => void) => void\n * }} IDBRequestFull\n */\n\n/* eslint-disable func-name-matching -- Polyfill */\n/**\n * @class\n * @this {IDBRequestFull}\n */\nIDBRequest.__super = function IDBRequest () {\n // @ts-expect-error It's ok\n this[Symbol.toStringTag] = 'IDBRequest';\n // @ts-expect-error Part of `ShimEventTarget`\n this.__setOptions({\n legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB\n });\n doneFlagGetters.forEach((prop) => {\n Object.defineProperty(this, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n Object.defineProperty(this, prop, {\n enumerable: true,\n configurable: true,\n get () {\n if (!this.__done) {\n throw createDOMException('InvalidStateError', \"Can't get \" + prop + '; the request is still pending.');\n }\n return this['__' + prop];\n }\n });\n });\n util.defineReadonlyProperties(this, readonlyProperties, {\n readyState: {\n /**\n * @this {IDBRequestFull}\n * @returns {\"done\"|\"pending\"}\n */\n get readyState () {\n return this.__done ? 'done' : 'pending';\n }\n }\n });\n util.defineListenerProperties(this, listeners);\n\n this.__result = undefined;\n this.__error = this.__source = this.__transaction = null;\n this.__done = false;\n};\n/* eslint-enable func-name-matching -- Polyfill */\n\n/**\n * @returns {IDBRequestFull}\n */\nIDBRequest.__createInstance = function () {\n // @ts-expect-error Casting this causes other errors\n return new IDBRequest.__super();\n};\n\n// @ts-expect-error It's ok\nIDBRequest.prototype = EventTargetFactory.createInstance({extraProperties: ['debug']});\nIDBRequest.prototype[Symbol.toStringTag] = 'IDBRequestPrototype';\n\n/**\n * @this {IDBRequestFull}\n * @returns {import('./IDBTransaction.js').IDBTransactionFull|null|undefined}\n */\nIDBRequest.prototype.__getParent = function () {\n if (this.toString() === '[object IDBOpenDBRequest]') {\n return null;\n }\n return this.__transaction;\n};\n\n// Illegal invocations\nutil.defineReadonlyOuterInterface(IDBRequest.prototype, readonlyProperties);\nutil.defineReadonlyOuterInterface(IDBRequest.prototype, doneFlagGetters);\n\nutil.defineOuterInterface(IDBRequest.prototype, listeners);\n\nObject.defineProperty(IDBRequest.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBRequest\n});\nIDBRequest.__super.prototype = IDBRequest.prototype;\n\nObject.defineProperty(IDBRequest, 'prototype', {\n writable: false\n});\n\nconst openListeners = ['onblocked', 'onupgradeneeded'];\n\n/**\n * @typedef {IDBRequestFull & IDBOpenDBRequest & {}} IDBOpenDBRequestFull\n */\n\n/**\n * The IDBOpenDBRequest called when a database is opened.\n * @class\n */\nfunction IDBOpenDBRequest () {\n throw new TypeError('Illegal constructor');\n}\n\n// @ts-expect-error It's ok\nIDBOpenDBRequest.prototype = Object.create(IDBRequest.prototype);\n\nObject.defineProperty(IDBOpenDBRequest.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBOpenDBRequest\n});\n\nconst IDBOpenDBRequestAlias = IDBOpenDBRequest;\n/**\n * @returns {IDBRequestFull & IDBOpenDBRequest}\n */\nIDBOpenDBRequest.__createInstance = function () {\n /**\n * @class\n * @this {IDBOpenDBRequestFull}\n */\n function IDBOpenDBRequest () {\n IDBRequest.__super.call(this);\n\n // @ts-expect-error It's ok\n this[Symbol.toStringTag] = 'IDBOpenDBRequest';\n // @ts-expect-error It's ok\n this.__setOptions({\n legacyOutputDidListenersThrowFlag: true, // Event hook for IndexedB\n extraProperties: ['oldVersion', 'newVersion', 'debug']\n }); // Ensure EventTarget preserves our properties\n util.defineListenerProperties(this, openListeners);\n }\n IDBOpenDBRequest.prototype = IDBOpenDBRequestAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBOpenDBRequest();\n};\n\nutil.defineOuterInterface(IDBOpenDBRequest.prototype, openListeners);\n\nIDBOpenDBRequest.prototype[Symbol.toStringTag] = 'IDBOpenDBRequestPrototype';\n\nObject.defineProperty(IDBOpenDBRequest, 'prototype', {\n writable: false\n});\n\nexport {IDBRequest, IDBOpenDBRequest};\n","/* eslint-disable promise/prefer-await-to-callbacks -- Needed for API */\n/* eslint-disable promise/catch-or-return, n/callback-return,\n promise/always-return -- Not needed */\n/* eslint-disable unicorn/no-this-assignment -- Clarity */\n// Since [immediate](https://github.com/calvinmetcalf/immediate) is\n// not doing the trick for our WebSQL transactions (at least in Node),\n// we are forced to make the promises run fully synchronously.\n\n// Todo: Use ES6 classes\n\n/**\n * @typedef {any} ArbitraryValue\n */\n\n/**\n * @callback Resolve\n * @param {ArbitraryValue} val\n * @returns {void}\n */\n/**\n * @callback Reject\n * @param {ArbitraryValue} reason\n * @returns {void}\n */\n/**\n * @callback Settle\n * @returns {void}\n */\n\n/**\n * @callback ResolveReject\n * @param {Resolve} resolve\n * @param {Reject} reject\n * @returns {void}\n */\n\n/**\n * @callback OnFulfilled\n * @param {ArbitraryValue} resolve\n * @returns {void}\n */\n\n/**\n * @typedef {[(Settle|Resolve)[], (Settle|Reject)[]]} Callbacks\n */\n\n/**\n *\n * @param {PromiseLike} p\n * @returns {boolean}\n */\nfunction isPromise (p) {\n return p && typeof p.then === 'function';\n}\n/**\n *\n * @param {PromiseLike} prom\n * @param {(err: Error) => void} reject\n * @returns {void}\n */\nfunction addReject (prom, reject) {\n // Use this style for sake of non-Promise thenables (e.g., jQuery Deferred)\n prom.then(null, reject);\n}\n\n// States\nconst PENDING = 2,\n FULFILLED = 0, // We later abuse these as array indices\n REJECTED = 1;\n\n/**\n * @class\n * @param {(\n * resolve: (value: ArbitraryValue | PromiseLike) => void,\n * reject: (reason?: any) => void\n * ) => void} fn\n */\nfunction SyncPromise (fn) {\n const that = this;\n // Value, this will be set to either a resolved value or rejected reason\n that.v = 0;\n // State of the promise\n that.s = PENDING;\n // Callbacks c[0] is fulfillment and c[1] contains rejection callbacks\n /** @type {Callbacks|null} */\n that.c = [[], []];\n /**\n *\n * @param {ArbitraryValue} val\n * @param {0|1} state\n * @returns {void}\n */\n function transist (val, state) {\n that.v = val;\n that.s = state;\n\n // console.log('state', state);\n /** @type {Callbacks} */ (\n that.c\n )[state].forEach(function (func) { func(val); });\n // Release memory, but if no handlers have been added, as we\n // assume that we will resolve/reject (truly) synchronously\n // and thus we avoid flagging checks about whether we've\n // already resolved/rejected.\n if (/** @type {Callbacks} */(that.c)[state].length) {\n that.c = null;\n }\n }\n\n /** @type {Resolve} */\n function resolve (val) {\n if (!that.c) {\n // Already resolved (or will be resolved), do nothing.\n } else if (isPromise(val)) {\n addReject(val.then(resolve), reject);\n } else {\n transist(val, FULFILLED);\n }\n }\n\n /** @type {Reject} */\n function reject (reason) {\n if (!that.c) {\n // Already resolved (or will be resolved), do nothing.\n } else if (isPromise(reason)) {\n addReject(reason.then(reject), reject);\n } else {\n transist(reason, REJECTED);\n }\n }\n try {\n fn(resolve, reject);\n } catch (err) {\n reject(err);\n }\n}\n\n/* eslint-disable unicorn/no-thenable -- Promise API */\n/**\n * @param {((value: ArbitraryValue) => ArbitraryValue)|null|undefined} [cb]\n * @param {(reason: any) => PromiseLike} [errBack]\n * @returns {SyncPromise}\n */\nSyncPromise.prototype.then = function (cb, errBack) {\n /* eslint-enable unicorn/no-thenable -- Promise API */\n const that = this;\n return new SyncPromise(\n /** @type {ResolveReject} */\n function (resolve, reject) {\n const rej = typeof errBack === 'function' ? errBack : reject;\n\n /** @type {Settle} */\n function settle () {\n try {\n resolve(cb ? cb(that.v) : that.v);\n } catch (e) {\n rej(e);\n }\n }\n if (that.s === FULFILLED) {\n settle();\n } else if (that.s === REJECTED) {\n rej(that.v);\n } else {\n /** @type {Callbacks} */ (that.c)[FULFILLED].push(settle);\n /** @type {Callbacks} */ (that.c)[REJECTED].push(rej);\n }\n }\n );\n};\n\n/**\n * @param {(reason: any) => PromiseLike|null|undefined} cb\n * @returns {SyncPromise}\n */\nSyncPromise.prototype.catch = function (cb) {\n const that = this;\n return new SyncPromise(\n /** @type {ResolveReject} */\n function (resolve, reject) {\n /**\n * @returns {void}\n */\n function settle () {\n try {\n resolve(cb(that.v));\n } catch (e) {\n reject(e);\n }\n }\n\n if (that.s === REJECTED) {\n settle();\n } else if (that.s === FULFILLED) {\n resolve(that.v);\n } else {\n /** @type {Callbacks} */ (that.c)[REJECTED].push(settle);\n /** @type {Callbacks} */ (that.c)[FULFILLED].push(resolve);\n }\n }\n );\n};\n\n/**\n * @param {unknown[]|[]} promises\n * @returns {SyncPromise}\n */\nSyncPromise.all = function (promises) {\n return new SyncPromise(\n /** @type {ResolveReject} */\n (resolve, reject) => {\n let l = promises.length;\n /** @type {ArbitraryValue[]} */\n const newPromises = [];\n if (!l) {\n resolve(newPromises);\n return;\n }\n promises.forEach((p, i) => {\n if (isPromise(/** @type {PromiseLike} */ (p))) {\n addReject(/** @type {PromiseLike} */ (p).then(\n /** @type {OnFulfilled} */\n (res) => {\n newPromises[i] = res;\n --l || resolve(newPromises);\n }\n ), reject);\n } else {\n newPromises[i] = p;\n --l || resolve(promises);\n }\n });\n }\n );\n};\n\n/**\n * @param {unknown[]|[]} promises\n * @returns {SyncPromise}\n */\nSyncPromise.race = function (promises) {\n let resolved = false;\n return new SyncPromise(\n /** @type {ResolveReject} */\n (resolve, reject) => {\n promises.some((p, i) => {\n if (isPromise(/** @type {PromiseLike} */ (p))) {\n addReject(/** @type {PromiseLike} */ (p).then(\n /** @type {OnFulfilled} */\n (res) => {\n if (resolved) {\n return;\n }\n resolve(res);\n resolved = true;\n }\n ), reject);\n return false;\n }\n resolve(p);\n resolved = true;\n return true;\n });\n }\n );\n};\n\n/**\n * @param {ArbitraryValue} val\n * @returns {SyncPromise}\n */\nSyncPromise.resolve = function (val) {\n return new SyncPromise(\n /** @type {ResolveReject} */\n (resolve, reject) => {\n resolve(val);\n }\n );\n};\n\n/**\n * @param {ArbitraryValue} val\n * @returns {SyncPromise}\n */\nSyncPromise.reject = function (val) {\n return new SyncPromise(\n /** @type {ResolveReject} */\n (resolve, reject) => {\n reject(val);\n }\n );\n};\n\nexport default SyncPromise;\n","import CFG from './CFG.js';\nimport {encode as keyEncode, decode as keyDecode} from './Key.js';\n\n/**\n * Compares two keys.\n * @param {import('./Key.js').Key} first\n * @param {import('./Key.js').Key} second\n * @returns {0|1|-1}\n */\nfunction cmp (first, second) {\n const encodedKey1 = /** @type {string} */ (keyEncode(first));\n const encodedKey2 = /** @type {string} */ (keyEncode(second));\n const result = encodedKey1 > encodedKey2\n ? 1\n : encodedKey1 === encodedKey2 ? 0 : -1;\n\n if (CFG.DEBUG) {\n // verify that the keys encoded correctly\n let decodedKey1 = keyDecode(encodedKey1);\n let decodedKey2 = keyDecode(encodedKey2);\n if (typeof first === 'object') {\n first = JSON.stringify(first);\n decodedKey1 = JSON.stringify(decodedKey1);\n }\n if (typeof second === 'object') {\n second = JSON.stringify(second);\n decodedKey2 = JSON.stringify(decodedKey2);\n }\n\n // Encoding/decoding mismatches are usually due to a loss of\n // floating-point precision\n if (decodedKey1 !== first) {\n console.warn(\n first + ' was incorrectly encoded as ' + decodedKey1\n );\n }\n if (decodedKey2 !== second) {\n console.warn(\n second + ' was incorrectly encoded as ' + decodedKey2\n );\n }\n }\n\n return result;\n}\n\nexport default cmp;\n","import {createDOMException} from './DOMException.js';\nimport * as util from './util.js';\nimport cmp from './cmp.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView\n */\n\n/**\n * @typedef {ArrayBufferView|ArrayBuffer} BufferSource\n */\n\n/**\n * @typedef {\"number\"|\"date\"|\"string\"|\"binary\"|\"array\"} KeyType\n */\n\n/**\n * @typedef {any} Value\n */\n\n/**\n * @typedef {any} Key\n * @todo Specify possible value more precisely\n */\n\n/**\n * @typedef {KeyPath[]} KeyPathArray\n */\n/**\n * @typedef {string|KeyPathArray} KeyPath\n */\n\n/**\n* @typedef {object} KeyValueObject\n* @property {KeyType|\"NaN\"|\"null\"|\"undefined\"|\"boolean\"|\"object\"|\"symbol\"|\n* \"function\"|\"bigint\"} type If not `KeyType`, indicates invalid value\n* @property {Value} [value]\n* @property {boolean} [invalid]\n* @property {string} [message]\n* @todo Specify acceptable `value` more precisely\n*/\n\n/**\n * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive\n */\n/**\n * @typedef {ValueType[]} ValueTypeArray\n */\n/**\n * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType\n */\n\n/**\n * Encodes the keys based on their types. This is required to maintain collations\n * We leave space for future keys.\n * @type {{[key: string]: Integer|string}}\n */\nconst keyTypeToEncodedChar = {\n invalid: 100,\n number: 200,\n date: 300,\n string: 400,\n binary: 500,\n array: 600\n};\nconst keyTypes = /** @type {(KeyType|\"invalid\")[]} */ (Object.keys(keyTypeToEncodedChar));\nkeyTypes.forEach((k) => {\n keyTypeToEncodedChar[k] = String.fromCodePoint(\n /** @type {number} */ (keyTypeToEncodedChar[k])\n );\n});\n\nconst encodedCharToKeyType = keyTypes.reduce((o, k) => {\n o[keyTypeToEncodedChar[k]] = k;\n return o;\n}, /** @type {{[key: string]: KeyType|\"invalid\"}} */ ({}));\n\n/**\n * The sign values for numbers, ordered from least to greatest.\n * - \"negativeInfinity\": Sorts below all other values.\n * - \"bigNegative\": Negative values less than or equal to negative one.\n * - \"smallNegative\": Negative values between negative one and zero, noninclusive.\n * - \"smallPositive\": Positive values between zero and one, including zero but not one.\n * - \"largePositive\": Positive values greater than or equal to one.\n * - \"positiveInfinity\": Sorts above all other values.\n */\nconst signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @type {{\n * [key: string]: {\n * encode: (param: any, inArray?: boolean) => string,\n * decode: (param: string, inArray?: boolean) => any\n * }\n * }}\n */\nconst types = {\n invalid: {\n /**\n * @returns {string}\n */\n encode () {\n return keyTypeToEncodedChar.invalid + '-';\n },\n /**\n * @returns {undefined}\n */\n decode () {\n return undefined;\n }\n },\n\n // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa\n // notation.\n //\n // sign: takes a value between zero and five, inclusive. Represents infinite cases\n // and the signs of both the exponent and the fractional part of the number.\n // exponent: padded to two base-32 digits, represented by the 32's compliment in the\n // \"smallPositive\" and \"bigNegative\" cases to ensure proper lexical sorting.\n // mantissa: also called the fractional part. Normed 11-digit base-32 representation.\n // Represented by the 32's compliment in the \"smallNegative\" and \"bigNegative\"\n // cases to ensure proper lexical sorting.\n number: {\n // The encode step checks for six numeric cases and generates 14-digit encoded\n // sign-exponent-mantissa strings.\n /**\n * @param {number} key\n * @returns {string}\n */\n encode (key) {\n let key32 = key === Number.MIN_VALUE\n // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some\n // Node (and Chrome) versions with `Number.MIN_VALUE` being treated\n // as 0\n // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring\n ? '0.' + '0'.repeat(214) + '2'\n : Math.abs(key).toString(32);\n // Get the index of the decimal.\n const decimalIndex = key32.indexOf('.');\n // Remove the decimal.\n key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;\n // Get the index of the first significant digit.\n const significantDigitIndex = key32.search(/[^0]/u);\n // Truncate leading zeros.\n key32 = key32.slice(significantDigitIndex);\n let sign, exponent, mantissa;\n\n // Finite cases:\n if (Number.isFinite(\n Number(key)\n )) {\n // Negative cases:\n if (key < 0) {\n // Negative exponent case:\n if (key > -1) {\n sign = signValues.indexOf('smallNegative');\n exponent = padBase32Exponent(significantDigitIndex);\n mantissa = flipBase32(padBase32Mantissa(key32));\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigNegative');\n exponent = flipBase32(padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n ));\n mantissa = flipBase32(padBase32Mantissa(key32));\n }\n // Non-negative cases:\n // Negative exponent case:\n } else if (key < 1) {\n sign = signValues.indexOf('smallPositive');\n exponent = flipBase32(padBase32Exponent(significantDigitIndex));\n mantissa = padBase32Mantissa(key32);\n // Non-negative exponent case:\n } else {\n sign = signValues.indexOf('bigPositive');\n exponent = padBase32Exponent(\n (decimalIndex !== -1) ? decimalIndex : key32.length\n );\n mantissa = padBase32Mantissa(key32);\n }\n // Infinite cases:\n } else {\n exponent = zeros(2);\n mantissa = zeros(11);\n sign = signValues.indexOf(\n key > 0 ? 'positiveInfinity' : 'negativeInfinity'\n );\n }\n\n return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;\n },\n // The decode step must interpret the sign, reflip values encoded as the 32's complements,\n // apply signs to the exponent and mantissa, do the base-32 power operation, and return\n // the original JavaScript number values.\n /**\n * @param {string} key\n * @returns {number}\n */\n decode (key) {\n const sign = Number(key.slice(2, 3));\n let exponent = key.slice(3, 5);\n let mantissa = key.slice(5, 16);\n\n switch (signValues[sign]) {\n case 'negativeInfinity':\n return Number.NEGATIVE_INFINITY;\n case 'positiveInfinity':\n return Number.POSITIVE_INFINITY;\n case 'bigPositive':\n return pow32(mantissa, exponent);\n case 'smallPositive':\n exponent = negate(flipBase32(exponent));\n return pow32(mantissa, exponent);\n case 'smallNegative':\n exponent = negate(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n case 'bigNegative':\n exponent = flipBase32(exponent);\n mantissa = flipBase32(mantissa);\n return -pow32(mantissa, exponent);\n default:\n throw new Error('Invalid number.');\n }\n }\n },\n\n // Strings are encoded as JSON strings (with quotes and unicode characters escaped).\n //\n // If the strings are in an array, then some extra encoding is done to make sorting work correctly:\n // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly\n // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.\n // To do this, each character of the string is prepended with a dash (\"-\"), and a space is added to the end of the string.\n // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,\n // the indexes of each string's characters line up with each other.\n string: {\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n encode (key, inArray) {\n if (inArray) {\n // prepend each character with a dash, and append a space to the end\n key = key.replaceAll(/(.)/gu, '-$1') + ' ';\n }\n return keyTypeToEncodedChar.string + '-' + key;\n },\n /**\n * @param {string} key\n * @param {boolean} [inArray]\n * @returns {string}\n */\n decode (key, inArray) {\n key = key.slice(2);\n if (inArray) {\n // remove the space at the end, and the dash before each character\n key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');\n }\n return key;\n }\n },\n\n // Arrays are encoded as JSON strings.\n // An extra, value is added to each array during encoding to make\n // empty arrays sort correctly.\n array: {\n /**\n * @param {ValueTypeArray} key\n * @returns {string}\n */\n encode (key) {\n const encoded = [];\n for (const [i, item] of key.entries()) {\n const encodedItem = encode(item, true); // encode the array item\n encoded[i] = encodedItem;\n }\n encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly\n return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);\n },\n /**\n * @param {string} key\n * @returns {ValueTypeArray}\n */\n decode (key) {\n const decoded = JSON.parse(key.slice(2));\n decoded.pop(); // remove the extra item\n for (let i = 0; i < decoded.length; i++) {\n const item = decoded[i];\n const decodedItem = decode(item, true); // decode the item\n decoded[i] = decodedItem;\n }\n return decoded;\n }\n },\n\n // Dates are encoded as ISO 8601 strings, in UTC time zone.\n date: {\n /**\n * @param {Date} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.date + '-' + key.toJSON();\n },\n /**\n * @param {string} key\n * @returns {Date}\n */\n decode (key) {\n return new Date(key.slice(2));\n }\n },\n binary: {\n // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)\n /**\n * @param {BufferSource} key\n * @returns {string}\n */\n encode (key) {\n return keyTypeToEncodedChar.binary + '-' + (key.byteLength\n ? [...getCopyBytesHeldByBufferSource(key)].map(\n (b) => String(b).padStart(3, '0')\n ) // e.g., '255,005,254,000,001,033'\n : '');\n },\n /**\n * @param {string} key\n * @returns {ArrayBuffer}\n */\n decode (key) {\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const k = key.slice(2);\n const arr = k.length ? k.split(',').map((s) => Number.parseInt(s)) : [];\n const buffer = new ArrayBuffer(arr.length);\n const uint8 = new Uint8Array(buffer);\n uint8.set(arr);\n return buffer;\n }\n }\n};\n\n/**\n * Return a padded base-32 exponent value.\n * @param {number} n\n * @returns {string}\n */\nfunction padBase32Exponent (n) {\n const exp = n.toString(32);\n return (exp.length === 1) ? '0' + exp : exp;\n}\n\n/**\n * Return a padded base-32 mantissa.\n * @param {string} s\n * @returns {string}\n */\nfunction padBase32Mantissa (s) {\n return (s + zeros(11)).slice(0, 11);\n}\n\n/**\n * Flips each digit of a base-32 encoded string.\n * @param {string} encoded\n * @returns {string}\n */\nfunction flipBase32 (encoded) {\n let flipped = '';\n for (const ch of encoded) {\n flipped += (31 - Number.parseInt(ch, 32)).toString(32);\n }\n return flipped;\n}\n\n/**\n * Base-32 power function.\n * RESEARCH: This function does not precisely decode floats because it performs\n * floating point arithmetic to recover values. But can the original values be\n * recovered exactly?\n * Someone may have already figured out a good way to store JavaScript floats as\n * binary strings and convert back. Barring a better method, however, one route\n * may be to generate decimal strings that `parseFloat` decodes predictably.\n * @param {string} mantissa\n * @param {string} exponent\n * @returns {number}\n */\nfunction pow32 (mantissa, exponent) {\n const exp = Number.parseInt(exponent, 32);\n if (exp < 0) {\n return roundToPrecision(\n Number.parseInt(mantissa, 32) * (32 ** (exp - 10))\n );\n }\n if (exp < 11) {\n const whole = mantissa.slice(0, exp);\n const wholeNum = Number.parseInt(whole, 32);\n const fraction = mantissa.slice(exp);\n const fractionNum = Number.parseInt(fraction, 32) * (32 ** (exp - 11));\n return roundToPrecision(wholeNum + fractionNum);\n }\n const expansion = mantissa + zeros(exp - 11);\n return Number.parseInt(expansion, 32);\n}\n\n/**\n * @typedef {number} Float\n */\n\n/**\n * @param {Float} num\n * @param {Float} [precision]\n * @returns {Float}\n */\nfunction roundToPrecision (num, precision = 16) {\n return Number.parseFloat(num.toPrecision(precision));\n}\n\n/**\n * Returns a string of n zeros.\n * @param {number} n\n * @returns {string}\n */\nfunction zeros (n) {\n return '0'.repeat(n);\n}\n\n/**\n * Negates numeric strings.\n * @param {string} s\n * @returns {string}\n */\nfunction negate (s) {\n return '-' + s;\n}\n\n/**\n * @param {Key} key\n * @returns {KeyType|\"invalid\"}\n */\nfunction getKeyType (key) {\n if (Array.isArray(key)) { return 'array'; }\n if (util.isDate(key)) { return 'date'; }\n if (util.isBinary(key)) { return 'binary'; }\n const keyType = typeof key;\n return ['string', 'number'].includes(keyType)\n ? /** @type {\"string\"|\"number\"} */ (keyType)\n : 'invalid';\n}\n\n/**\n * Keys must be strings, numbers (besides `NaN`), Dates (if value is not\n * `NaN`), binary objects or Arrays.\n * @param {Value} input The key input\n * @param {Value[]|null|undefined} [seen] An array of already seen keys\n * @returns {KeyValueObject}\n */\nfunction convertValueToKey (input, seen) {\n return convertValueToKeyValueDecoded(input, seen, false, true);\n}\n\n/**\n* Currently not in use.\n* @param {Value} input\n* @returns {KeyValueObject}\n*/\nfunction convertValueToMultiEntryKey (input) {\n return convertValueToKeyValueDecoded(input, null, true, true);\n}\n\n/**\n *\n * @param {BufferSource} O\n * @throws {TypeError}\n * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n * @returns {Uint8Array}\n */\nfunction getCopyBytesHeldByBufferSource (O) {\n let offset = 0;\n let length = 0;\n if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot\n const arrayBuffer = O.buffer;\n if (arrayBuffer === undefined) {\n throw new TypeError(\n 'Could not copy the bytes held by a buffer source as the buffer was undefined.'\n );\n }\n offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)\n length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)\n } else {\n length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)\n }\n // const octets = new Uint8Array(input);\n // const octets = types.binary.decode(types.binary.encode(input));\n return new Uint8Array(\n // Should allow DataView\n /** @type {ArrayBuffer} */\n (('buffer' in O && O.buffer) || O),\n offset,\n length\n );\n}\n\n/**\n* Shortcut utility to avoid returning full keys from `convertValueToKey`\n* and subsequent need to process in calling code unless `fullKeys` is\n* set; may throw.\n* @param {Value} input\n* @param {Value[]|null} [seen]\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @throws {TypeError} See `getCopyBytesHeldByBufferSource`\n* @todo Document other allowable `input`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {\n seen = seen || [];\n if (seen.includes(input)) {\n return {\n type: 'array',\n invalid: true,\n message: 'An array key cannot be circular'\n };\n }\n const type = getKeyType(input);\n const ret = {type, value: input};\n switch (type) {\n case 'number': {\n if (Number.isNaN(input)) {\n // List as 'NaN' type for convenience of consumers in reporting errors\n return {type: 'NaN', invalid: true};\n }\n\n // https://github.com/w3c/IndexedDB/issues/375\n // https://github.com/w3c/IndexedDB/pull/386\n if (Object.is(input, -0)) {\n return {type, value: 0};\n }\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'string': {\n return /** @type {{type: KeyType; value: Value}} */ (ret);\n } case 'binary': { // May throw (if detached)\n // Get a copy of the bytes held by the buffer source\n // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2\n const octets = getCopyBytesHeldByBufferSource(\n /** @type {BufferSource} */ (input)\n );\n return {type: 'binary', value: octets};\n } case 'array': { // May throw (from binary)\n const arr = /** @type {Array} */ (input);\n const len = arr.length;\n seen.push(input);\n\n /** @type {(KeyValueObject|Value)[]} */\n const keys = [];\n for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated\n if (!multiEntry && !Object.hasOwn(arr, i)) {\n return {type, invalid: true, message: 'Does not have own index property'};\n }\n try {\n const entry = arr[i];\n const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry\n if (key.invalid) {\n if (multiEntry) {\n continue;\n }\n return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};\n }\n if (!multiEntry ||\n (!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||\n (fullKeys && keys.every((k) => cmp(k, key) !== 0))\n ) {\n keys.push(fullKeys ? key : key.value);\n }\n } catch (err) {\n if (!multiEntry) {\n throw err;\n }\n }\n }\n return {type, value: keys};\n } case 'date': {\n const date = /** @type {Date} */ (input);\n if (!Number.isNaN(date.getTime())) {\n return fullKeys\n ? {type, value: date.getTime()}\n : {type, value: new Date(date.getTime())};\n }\n return {type, invalid: true, message: 'Not a valid date'};\n // Falls through\n } case 'invalid': default: {\n // Other `typeof` types which are not valid keys:\n // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'\n const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors\n return {type, invalid: true, message: 'Not a valid key; type ' + type};\n }\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [fullKeys]\n * @returns {KeyValueObject}\n * @todo Document other allowable `key`?\n */\nfunction convertValueToMultiEntryKeyDecoded (key, fullKeys) {\n return convertValueToKeyValueDecoded(key, null, true, fullKeys);\n}\n\n/**\n* An internal utility.\n* @param {Value} input\n* @param {Value[]|null|undefined} [seen]\n* @throws {DOMException} `DataError`\n* @returns {KeyValueObject}\n*/\nfunction convertValueToKeyRethrowingAndIfInvalid (input, seen) {\n const key = convertValueToKey(input, seen);\n if (key.invalid) {\n throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);\n }\n return key;\n}\n\n/**\n *\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} multiEntry\n * @returns {KeyValueObject|KeyPathEvaluateValue}\n * @todo Document other possible return?\n */\nfunction extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {\n return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);\n}\n/**\n* Not currently in use.\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} multiEntry\n* @returns {KeyPathEvaluateValue}\n*/\nfunction evaluateKeyPathOnValue (value, keyPath, multiEntry) {\n return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);\n}\n\n/**\n* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)\n* or `{invalid: true}` (e.g., `NaN`).\n* @param {Value} value\n* @param {KeyPath} keyPath\n* @param {boolean} [multiEntry]\n* @param {boolean} [fullKeys]\n* @returns {KeyValueObject|KeyPathEvaluateValue}\n* @todo Document other possible return?\n*/\nfunction extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {\n const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);\n if (r.failure) {\n return r;\n }\n if (!multiEntry) {\n return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);\n }\n return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);\n}\n\n/**\n * Unused?\n * @typedef {object} KeyPathEvaluateFailure\n * @property {boolean} failure\n */\n\n/**\n * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray\n */\n\n/**\n * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue\n */\n\n/**\n * @typedef {object} KeyPathEvaluateValue\n * @property {KeyPathEvaluateValueValue} [value]\n * @property {boolean} [failure]\n */\n\n/**\n * Returns the value of an inline key based on a key path (wrapped in an\n * object with key `value`) or `{failure: true}`\n * @param {Value} value\n * @param {KeyPath} keyPath\n * @param {boolean} [multiEntry]\n * @param {boolean} [fullKeys]\n * @returns {KeyPathEvaluateValue}\n */\nfunction evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {\n if (Array.isArray(keyPath)) {\n /** @type {KeyPathEvaluateValueValueArray} */\n const result = [];\n return keyPath.some((item) => {\n const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);\n if (key.failure) {\n return true;\n }\n result.push(key.value);\n return false;\n })\n ? {failure: true}\n : {value: result};\n }\n if (keyPath === '') {\n return {value};\n }\n const identifiers = keyPath.split('.');\n return identifiers.some((idntfr) => {\n if (idntfr === 'length' && (\n typeof value === 'string' || Array.isArray(value)\n )) {\n value = value.length;\n } else if (util.isBlob(value)) {\n switch (idntfr) {\n case 'size': case 'type':\n value = /** @type {Blob} */ (value)[idntfr];\n break;\n }\n } else if (util.isFile(value)) {\n switch (idntfr) {\n case 'name': case 'lastModified':\n value = /** @type {File} */ (value)[idntfr];\n break;\n case 'lastModifiedDate':\n value = new Date(/** @type {File} */ (value).lastModified);\n break;\n }\n } else if (!util.isObj(value) || !Object.hasOwn(value, idntfr)) {\n return true;\n } else {\n value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */ (\n value\n )[idntfr];\n return value === undefined;\n }\n return false;\n })\n ? {failure: true}\n : {value};\n}\n\n/**\n * Sets the inline key value.\n * @param {{[key: string]: AnyValue}} value\n * @param {Key} key\n * @param {string} keyPath\n * @returns {void}\n */\nfunction injectKeyIntoValueUsingKeyPath (value, key, keyPath) {\n const identifiers = keyPath.split('.');\n const last = identifiers.pop();\n identifiers.forEach((identifier) => {\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n value[identifier] = {};\n }\n value = value[identifier];\n });\n value[/** @type {string} */ (last)] = key; // key is already a `keyValue` in our processing so no need to convert\n}\n\n/**\n *\n * @param {Value} value\n * @param {string} keyPath\n * @see https://github.com/w3c/IndexedDB/pull/146\n * @returns {boolean}\n */\nfunction checkKeyCouldBeInjectedIntoValue (value, keyPath) {\n const identifiers = keyPath.split('.');\n identifiers.pop();\n for (const identifier of identifiers) {\n if (!util.isObj(value)) {\n return false;\n }\n const hop = Object.hasOwn(value, identifier);\n if (!hop) {\n return true;\n }\n value = /** @type {{[key: string]: Value}} */ (value)[identifier];\n }\n return util.isObj(value);\n}\n\n/**\n *\n * @param {Key} key\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range\n * @param {boolean} [checkCached]\n * @returns {boolean}\n */\nfunction isKeyInRange (key, range, checkCached) {\n let lowerMatch = range.lower === undefined;\n let upperMatch = range.upper === undefined;\n const encodedKey = encode(key, true);\n const lower = checkCached ? range.__lowerCached : encode(range.lower, true);\n const upper = checkCached ? range.__upperCached : encode(range.upper, true);\n\n if (!lowerMatch && (\n (range.lowerOpen &&\n encodedKey !== null && lower !== null && encodedKey > lower) ||\n (!range.lowerOpen && (\n (!encodedKey && !lower) ||\n (encodedKey !== null && lower !== null && encodedKey >= lower))\n )\n )) {\n lowerMatch = true;\n }\n if (!upperMatch && (\n (range.upperOpen &&\n encodedKey !== null && upper !== null && encodedKey < upper) ||\n (!range.upperOpen && (\n (!encodedKey && !upper) ||\n (encodedKey !== null && upper !== null && encodedKey <= upper))\n )\n )) {\n upperMatch = true;\n }\n\n return lowerMatch && upperMatch;\n}\n\n/**\n * Determines whether an index entry matches a multi-entry key value.\n * @param {string} encodedEntry The entry value (already encoded)\n * @param {string} encodedKey The full index key (already encoded)\n * @returns {boolean}\n */\nfunction isMultiEntryMatch (encodedEntry, encodedKey) {\n const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];\n\n if (keyType === 'array') {\n return encodedKey.indexOf(encodedEntry) > 1;\n }\n return encodedKey === encodedEntry;\n}\n\n/**\n *\n * @param {Key} keyEntry\n * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range\n * @returns {Key[]}\n */\nfunction findMultiEntryMatches (keyEntry, range) {\n const matches = [];\n\n if (Array.isArray(keyEntry)) {\n for (let key of keyEntry) {\n if (Array.isArray(key)) {\n if (range && range.lower === range.upper) {\n continue;\n }\n if (key.length === 1) {\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n key = key[0];\n } else {\n const nested = findMultiEntryMatches(key, range);\n if (nested.length > 0) {\n matches.push(key);\n }\n continue;\n }\n }\n\n if (util.isNullish(range) || isKeyInRange(key, range, true)) {\n matches.push(key);\n }\n }\n } else if (util.isNullish(range) || isKeyInRange(keyEntry, range, true)) {\n matches.push(keyEntry);\n }\n return matches;\n}\n\n/**\n* Not currently in use but keeping for spec parity.\n* @param {Key} key\n* @throws {Error} Upon a \"bad key\"\n* @returns {ValueType}\n*/\nfunction convertKeyToValue (key) {\n const {type, value} = key;\n switch (type) {\n case 'number': case 'string': {\n return value;\n } case 'array': {\n const array = [];\n const len = value.length;\n let index = 0;\n while (index < len) {\n const entry = convertKeyToValue(value[index]);\n array[index] = entry;\n index++;\n }\n return array;\n } case 'date': {\n return new Date(value);\n } case 'binary': {\n const len = value.length;\n const buffer = new ArrayBuffer(len);\n // Set the entries in buffer's [[ArrayBufferData]] to those in `value`\n const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);\n uint8.set(value);\n return buffer;\n } case 'invalid': default:\n throw new Error('Bad key');\n }\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {string|null}\n */\nfunction encode (key, inArray) {\n // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation\n if (key === undefined) {\n return null;\n }\n // array, date, number, string, binary (should already have detected \"invalid\")\n return types[getKeyType(key)].encode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @throws {Error} Invalid number\n * @returns {undefined|ValueType}\n */\nfunction decode (key, inArray) {\n if (typeof key !== 'string') {\n return undefined;\n }\n return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);\n}\n\n/**\n *\n * @param {Key} key\n * @param {boolean} [inArray]\n * @returns {undefined|ValueType}\n */\nfunction roundTrip (key, inArray) {\n return decode(encode(key, inArray), inArray);\n}\n\nconst MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback CurrentNumberCallback\n * @param {Integer} cn The current number\n * @returns {void}\n */\n\n/**\n* @callback SQLFailureCallback\n* @param {DOMException|Error} exception\n* @returns {void}\n*/\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {CurrentNumberCallback} func\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction getCurrentNumber (tx, store, func, sqlFailCb) {\n tx.executeSql('SELECT \"currNum\" FROM __sys__ WHERE \"name\" = ?', [\n util.escapeSQLiteStatement(store.__currentName)\n ], function (tx, data) {\n if (data.rows.length !== 1) {\n func(1);\n } else {\n func(data.rows.item(0).currNum);\n }\n }, function (tx, error) {\n sqlFailCb(createDOMException(\n 'DataError',\n 'Could not get the auto increment value for key',\n error\n ));\n return false;\n });\n}\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction assignCurrentNumber (tx, store, num, successCb, failCb) {\n const sql = 'UPDATE __sys__ SET \"currNum\" = ? WHERE \"name\" = ?';\n const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n tx.executeSql(sql, sqlValues, function () {\n successCb(num);\n }, function (tx, err) {\n failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));\n return false;\n });\n}\n\n/**\n * Bump up the auto-inc counter if the key path-resolved value is valid\n * (greater than old value and >=1) OR if a manually passed in key is\n * valid (numeric and >= 1) and >= any primaryKey.\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Integer} num\n * @param {CurrentNumberCallback} successCb\n * @param {SQLFailureCallback} failCb\n * @returns {void}\n */\nfunction setCurrentNumber (tx, store, num, successCb, failCb) {\n num = num === MAX_ALLOWED_CURRENT_NUMBER\n ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner\n : num + 1;\n return assignCurrentNumber(tx, store, num, successCb, failCb);\n}\n\n/**\n * @callback KeyForStoreCallback\n * @param {\"failure\"|null} arg1\n * @param {Integer} [arg2]\n * @param {Integer} [arg3]\n * @returns {void}\n */\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {KeyForStoreCallback} cb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction generateKeyForStore (tx, store, cb, sqlFailCb) {\n getCurrentNumber(tx, store, function (key) {\n if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See )\n cb('failure');\n return;\n }\n // Increment current number by 1 (we cannot leverage SQLite's\n // autoincrement (and decrement when not needed), as decrementing\n // will be overwritten/ignored upon the next insert)\n setCurrentNumber(\n tx, store, key,\n function () {\n cb(null, key, key);\n },\n sqlFailCb\n );\n }, sqlFailCb);\n}\n\n// Fractional or numbers exceeding the max do not get changed in the result\n// per https://github.com/w3c/IndexedDB/issues/147\n// so we do not return a key\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {Key} key\n * @param {(num?: Integer) => void} successCb\n * @param {SQLFailureCallback} sqlFailCb\n * @returns {void}\n */\nfunction possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {\n // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers\n // (or numbers larger than the max) are now to have the explicit effect of\n // setting the current number (up to the max), so we do not optimize them\n // out here\n if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number\n // Auto-increment attempted with a bad key;\n // we are not to change the current number, but the steps don't call for failure\n // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1\n successCb();\n } else {\n // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher\n // to determine which to use and whether to update the current number\n getCurrentNumber(tx, store, function (cn) {\n const value = Math.floor(\n Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)\n );\n const useNewKeyForAutoInc = value >= cn;\n if (useNewKeyForAutoInc) {\n setCurrentNumber(tx, store, value, function () {\n successCb(cn); // Supply old current number in case needs to be reverted\n }, sqlFailCb);\n } else { // Not updated\n successCb();\n }\n }, sqlFailCb);\n }\n}\n\nexport {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,\n convertValueToMultiEntryKeyDecoded,\n convertValueToKey,\n convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,\n extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,\n extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,\n isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,\n assignCurrentNumber,\n generateKeyForStore, possiblyUpdateKeyGenerator};\n","import {createDOMException} from './DOMException.js';\nimport * as Key from './Key.js';\nimport * as util from './util.js';\n\nconst readonlyProperties = /** @type {const} */ (['lower', 'upper', 'lowerOpen', 'upperOpen']);\n\n/**\n * @typedef {globalThis.IDBKeyRange & {\n* __lowerCached: string|null|false,\n* __upperCached: string|null|false,\n* __lowerOpen: boolean,\n* }} IDBKeyRangeFull\n*/\n\n/**\n * The IndexedDB KeyRange object.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#dfn-key-range\n * @throws {TypeError}\n * @class\n */\nfunction IDBKeyRange () {\n this.__lowerOpen = false;\n this.__upperOpen = false;\n throw new TypeError('Illegal constructor');\n}\nconst IDBKeyRangeAlias = IDBKeyRange;\n\n/**\n * @param {import('./Key.js').Key|null} lower\n * @param {import('./Key.js').Key|null} upper\n * @param {boolean} lowerOpen\n * @param {boolean} upperOpen\n * @returns {import('./IDBKeyRange.js').IDBKeyRangeFull}\n */\nIDBKeyRange.__createInstance = function (lower, upper, lowerOpen, upperOpen) {\n /**\n * @class\n */\n function IDBKeyRange () {\n this[Symbol.toStringTag] = 'IDBKeyRange';\n if (lower === undefined && upper === undefined) {\n throw createDOMException('DataError', 'Both arguments to the key range method cannot be undefined');\n }\n let lowerConverted, upperConverted;\n if (lower !== undefined) {\n lowerConverted = Key.roundTrip(lower); // Todo: does this make the \"conversions\" redundant\n Key.convertValueToKeyRethrowingAndIfInvalid(lower);\n }\n if (upper !== undefined) {\n upperConverted = Key.roundTrip(upper); // Todo: does this make the \"conversions\" redundant\n Key.convertValueToKeyRethrowingAndIfInvalid(upper);\n }\n if (lower !== undefined && upper !== undefined && lower !== upper) {\n if (\n /** @type {string} */ (Key.encode(lower)) >\n /** @type {string} */ (Key.encode(upper))\n ) {\n throw createDOMException('DataError', '`lower` must not be greater than `upper` argument in `bound()` call.');\n }\n }\n\n this.__lower = lowerConverted;\n this.__upper = upperConverted;\n this.__lowerOpen = Boolean(lowerOpen);\n this.__upperOpen = Boolean(upperOpen);\n }\n IDBKeyRange.prototype = IDBKeyRangeAlias.prototype;\n\n // @ts-expect-error Properties added by `defineProperty/ies`\n return new IDBKeyRange();\n};\n\n/**\n * @param {import('./Key.js').Key} key\n * @this {IDBKeyRangeFull}\n * @returns {boolean}\n */\nIDBKeyRange.prototype.includes = function (key) {\n // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation\n if (!util.isObj(this) || typeof this.__lowerOpen !== 'boolean') {\n throw new TypeError('Illegal invocation');\n }\n if (!arguments.length) {\n throw new TypeError('IDBKeyRange.includes requires a key argument');\n }\n Key.convertValueToKeyRethrowingAndIfInvalid(key);\n return Key.isKeyInRange(key, this);\n};\n\n/**\n * @param {import('./Key.js').Value} value\n * @returns {import('./IDBKeyRange.js').IDBKeyRangeFull}\n */\nIDBKeyRange.only = function (value) {\n if (!arguments.length) {\n throw new TypeError('IDBKeyRange.only requires a value argument');\n }\n return IDBKeyRange.__createInstance(value, value, false, false);\n};\n\n/**\n * @param {import('./Key.js').Value} value\n * @returns {globalThis.IDBKeyRange}\n */\nIDBKeyRange.lowerBound = function (value /* , open */) {\n if (!arguments.length) {\n throw new TypeError('IDBKeyRange.lowerBound requires a value argument');\n }\n // eslint-disable-next-line prefer-rest-params -- API\n return IDBKeyRange.__createInstance(value, undefined, arguments[1], true);\n};\n\n/**\n * @param {import('./Key.js').Value} value\n * @returns {globalThis.IDBKeyRange}\n */\nIDBKeyRange.upperBound = function (value /* , open */) {\n if (!arguments.length) {\n throw new TypeError('IDBKeyRange.upperBound requires a value argument');\n }\n // eslint-disable-next-line prefer-rest-params -- API\n return IDBKeyRange.__createInstance(undefined, value, true, arguments[1]);\n};\n\n/**\n * @param {import('./Key.js').Value} lower\n * @param {import('./Key.js').Value} upper\n * @returns {globalThis.IDBKeyRange}\n */\nIDBKeyRange.bound = function (lower, upper /* , lowerOpen, upperOpen */) {\n if (arguments.length <= 1) {\n throw new TypeError('IDBKeyRange.bound requires lower and upper arguments');\n }\n // eslint-disable-next-line prefer-rest-params -- API\n return IDBKeyRange.__createInstance(lower, upper, arguments[2], arguments[3]);\n};\nIDBKeyRange.prototype[Symbol.toStringTag] = 'IDBKeyRangePrototype';\n\nreadonlyProperties.forEach((prop) => {\n Object.defineProperty(IDBKeyRange.prototype, '__' + prop, {\n enumerable: false,\n configurable: false,\n writable: true\n });\n // Ensure for proper interface testing that \"get \" is the function name\n const o = {\n /**\n * @returns {import('./Key.js').Key|null|boolean}\n */\n get [prop] () {\n // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation\n if (!util.isObj(this) || typeof this.__lowerOpen !== 'boolean') {\n throw new TypeError('Illegal invocation');\n }\n return this['__' + prop];\n }\n };\n const desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, prop)\n );\n // desc.enumerable = true; // Default\n // desc.configurable = true; // Default\n Object.defineProperty(IDBKeyRange.prototype, prop, desc);\n});\n\nObject.defineProperty(IDBKeyRange, Symbol.hasInstance, {\n value:\n /**\n * @param {object} obj\n * @returns {boolean}\n */\n (obj) => util.isObj(obj) && 'upper' in obj && 'lowerOpen' in obj &&\n typeof obj.lowerOpen === 'boolean'\n});\n\nObject.defineProperty(IDBKeyRange, 'prototype', {\n writable: false\n});\n\n/**\n * @param {IDBKeyRangeFull|undefined} range\n * @param {string} quotedKeyColumnName\n * @param {string[]} sql\n * @param {string[]} sqlValues\n * @param {boolean} [addAnd]\n * @param {boolean} [checkCached]\n * @returns {void}\n */\nfunction setSQLForKeyRange (\n range, quotedKeyColumnName, sql, sqlValues, addAnd, checkCached\n) {\n if (range && (range.lower !== undefined || range.upper !== undefined)) {\n if (addAnd) { sql.push('AND'); }\n let encodedLowerKey, encodedUpperKey;\n const hasLower = range.lower !== undefined;\n const hasUpper = range.upper !== undefined;\n if (hasLower) {\n encodedLowerKey = checkCached ? range.__lowerCached : Key.encode(range.lower);\n }\n if (hasUpper) {\n encodedUpperKey = checkCached ? range.__upperCached : Key.encode(range.upper);\n }\n if (hasLower) {\n sqlValues.push(util.escapeSQLiteStatement(/** @type {string} */ (encodedLowerKey)));\n if (hasUpper && encodedLowerKey === encodedUpperKey && !range.lowerOpen && !range.upperOpen) {\n sql.push(quotedKeyColumnName, '=', '?');\n return;\n }\n sql.push(quotedKeyColumnName, (range.lowerOpen ? '>' : '>='), '?');\n }\n if (hasLower && hasUpper) { sql.push('AND'); }\n if (hasUpper) {\n sql.push(quotedKeyColumnName, (range.upperOpen ? '<' : '<='), '?');\n sqlValues.push(util.escapeSQLiteStatement(/** @type {string} */ (encodedUpperKey)));\n }\n }\n}\n\n/**\n * @param {import('./Key.js').Value} value\n * @param {boolean} [nullDisallowed]\n * @throws {DOMException}\n * @returns {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined}\n */\nfunction convertValueToKeyRange (value, nullDisallowed) {\n if (util.instanceOf(value, IDBKeyRange)) {\n // We still need to validate IDBKeyRange-like objects (the above check is based on loose duck-typing)\n if (value.toString() !== '[object IDBKeyRange]') {\n return IDBKeyRange.__createInstance(value.lower, value.upper, value.lowerOpen, value.upperOpen);\n }\n return value;\n }\n if (util.isNullish(value)) {\n if (nullDisallowed) {\n throw createDOMException('DataError', 'No key or range was specified');\n }\n return undefined; // Represents unbounded\n }\n Key.convertValueToKeyRethrowingAndIfInvalid(value);\n return IDBKeyRange.only(value);\n}\n\nexport {setSQLForKeyRange, IDBKeyRange, convertValueToKeyRange, IDBKeyRange as default};\n","/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {{\n * _items: string[],\n * _length: Integer,\n * [key: number]: string,\n * addIndexes: () => void,\n * sortList: () => string[],\n * push: (item: string) => void,\n * clone: () => DOMStringListFull,\n * contains: (str: string) => boolean,\n * indexOf: (str: string) => Integer,\n * splice: (index: Integer, howmany: Integer, ...args: any) => void\n * length: Integer\n * }} DOMStringListFull\n */\n\nlet cleanInterface = false;\n\nconst testObject = {test: true};\n// Test whether Object.defineProperty really works.\nif (Object.defineProperty) {\n try {\n Object.defineProperty(testObject, 'test', {enumerable: false});\n if (testObject.test) {\n cleanInterface = true;\n }\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n // Object.defineProperty does not work as intended.\n }\n}\n\n/**\n * Shim the DOMStringList object.\n * @throws {TypeError}\n * @class\n */\nconst DOMStringList = function () {\n /** @type {string[]} */\n this._items = [];\n /** @type {Integer} */\n this._length = 0;\n throw new TypeError('Illegal constructor');\n};\n\n// @ts-expect-error It's ok\nDOMStringList.prototype = {\n constructor: DOMStringList,\n // Interface.\n\n /**\n * @param {string} str\n * @returns {boolean}\n */\n contains (str) {\n if (!arguments.length) {\n throw new TypeError('DOMStringList.contains must be supplied a value');\n }\n return this._items.includes(str);\n },\n\n /**\n * @param {number} key\n * @returns {string|null}\n */\n item (key) {\n if (!arguments.length) {\n throw new TypeError('DOMStringList.item must be supplied a value');\n }\n if (key < 0 || key >= this.length || !Number.isInteger(key)) {\n return null;\n }\n return this._items[key];\n },\n\n // Helpers. Should only be used internally.\n /**\n * @returns {DOMStringListFull}\n */\n clone () {\n const stringList = DOMStringList.__createInstance();\n stringList._items = this._items.slice();\n stringList._length = this.length;\n stringList.addIndexes();\n return stringList;\n },\n /**\n * @this {DOMStringListFull}\n * @returns {void}\n */\n addIndexes () {\n for (let i = 0; i < this._items.length; i++) {\n this[i] = this._items[i];\n }\n },\n /**\n * @this {DOMStringListFull}\n * @returns {string[]}\n */\n sortList () {\n // http://w3c.github.io/IndexedDB/#sorted-list\n // https://tc39.github.io/ecma262/#sec-abstract-relational-comparison\n this._items.sort();\n this.addIndexes();\n return this._items;\n },\n /**\n * @param {(value: string, i: Integer, arr: string[]) => void} cb\n * @param {object} thisArg\n * @returns {void}\n */\n forEach (cb, thisArg) {\n // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-method-this-argument -- Convenient\n this._items.forEach(cb, thisArg);\n },\n /**\n * @param {(value: string, i: Integer, arr: string[]) => any[]} cb\n * @param {object} thisArg\n * @returns {any[]}\n */\n map (cb, thisArg) {\n // eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-method-this-argument -- Convenient\n return this._items.map(cb, thisArg);\n },\n /**\n * @param {string} str\n * @returns {Integer}\n */\n indexOf (str) {\n return this._items.indexOf(str);\n },\n /**\n * @param {string} item\n * @this {DOMStringListFull}\n * @returns {void}\n */\n push (item) {\n this._items.push(item);\n this._length++;\n this.sortList();\n },\n /**\n * @typedef {any} AnyArgs\n */\n /**\n * @param {[index: Integer, howmany: Integer, ...args: any]} args\n * @this {DOMStringListFull}\n * @returns {void}\n */\n splice (...args /* index, howmany, item1, ..., itemX */) {\n this._items.splice(...args);\n this._length = this._items.length;\n for (const i in this) {\n if (i === String(Number.parseInt(i))) {\n delete this[i];\n }\n }\n this.sortList();\n },\n [Symbol.toStringTag]: 'DOMStringListPrototype',\n // At least because `DOMStringList`, as a [list](https://infra.spec.whatwg.org/#list)\n // can be converted to a sequence per https://infra.spec.whatwg.org/#list-iterate\n // and particularly as some methods, e.g., `IDBDatabase.transaction`\n // expect such sequence (or DOMString), we need an iterator (some of\n // the Mocha tests rely on these)\n *[Symbol.iterator] () {\n let i = 0;\n while (i < this._items.length) {\n yield this._items[i++];\n }\n }\n};\n\n/**\n * @typedef {any} AnyValue\n */\nObject.defineProperty(DOMStringList, Symbol.hasInstance, {\n /**\n * @param {AnyValue} obj\n * @returns {boolean}\n */\n value (obj) {\n return Object.prototype.toString.call(obj) === 'DOMStringListPrototype';\n }\n});\nconst DOMStringListAlias = DOMStringList;\nObject.defineProperty(DOMStringList, '__createInstance', {\n /**\n * @returns {DOMStringListFull}\n */\n value () {\n /**\n * @class\n * @this {DOMStringList}\n */\n const DOMStringList = function DOMStringList () {\n this.toString = function () {\n return '[object DOMStringList]';\n };\n // Internal functions on the prototype have been made non-enumerable below.\n Object.defineProperty(this, 'length', {\n enumerable: true,\n get () {\n return this._length;\n }\n });\n this._items = /** @type {string[]} */ ([]);\n this._length = 0;\n };\n DOMStringList.prototype = DOMStringListAlias.prototype;\n return /** @type {DOMStringListFull} */ (new DOMStringList());\n }\n});\n\nif (cleanInterface) {\n Object.defineProperty(DOMStringList, 'prototype', {\n writable: false\n });\n\n const nonenumerableReadonly = ['addIndexes', 'sortList', 'forEach', 'map', 'indexOf', 'push', 'splice', 'constructor', '__createInstance'];\n nonenumerableReadonly.forEach((nonenumerableReadonly) => {\n Object.defineProperty(DOMStringList.prototype, nonenumerableReadonly, {\n enumerable: false\n });\n });\n\n // Illegal invocations\n // @ts-expect-error No return value\n Object.defineProperty(DOMStringList.prototype, 'length', {\n configurable: true,\n enumerable: true,\n get () {\n throw new TypeError('Illegal invocation');\n }\n });\n\n const nonenumerableWritable = ['_items', '_length'];\n nonenumerableWritable.forEach((nonenumerableWritable) => {\n Object.defineProperty(DOMStringList.prototype, nonenumerableWritable, {\n enumerable: false,\n writable: true\n });\n });\n}\n\nexport default DOMStringList;\n","import {EventTargetFactory} from 'eventtargeter';\nimport SyncPromise from 'sync-promise-expanded';\nimport {createEvent} from './Event.js';\nimport {logError, findError, webSQLErrback, createDOMException} from './DOMException.js';\nimport {IDBRequest} from './IDBRequest.js';\nimport * as util from './util.js';\nimport IDBObjectStore from './IDBObjectStore.js';\nimport CFG from './CFG.js';\n\nlet uniqueID = 0;\nconst listeners = ['onabort', 'oncomplete', 'onerror'];\nconst readonlyProperties = ['objectStoreNames', 'mode', 'db', 'error'];\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {{\n * op: SQLCallback,\n * args: ObjectArray,\n * req: import('./IDBRequest.js').IDBRequestFull|null\n * }} RequestInfo\n */\n\n/**\n * @typedef {EventTarget & {\n * mode: \"readonly\"|\"readwrite\"|\"versionchange\",\n * db: import('./IDBDatabase.js').IDBDatabaseFull,\n * on__abort: () => void,\n * on__complete: () => void,\n * on__beforecomplete: (ev: Event & {\n * complete: () => void\n * }) => void,\n * on__preabort: () => void,\n * __abortTransaction: (err: Error|DOMException|null) => void,\n * __executeRequests: () => void,\n * __tx: SQLTransaction,\n * __id: Integer,\n * __active: boolean,\n * __running: boolean,\n * __errored: boolean,\n * __requests: RequestInfo[],\n * __db: import('./IDBDatabase.js').IDBDatabaseFull,\n * __mode: string,\n * __error: null|DOMException|Error,\n * __objectStoreNames: import('./DOMStringList.js').DOMStringListFull,\n * __storeHandles: {\n * [key: string]: import('./IDBObjectStore.js').IDBObjectStoreFull\n * },\n * __requestsFinished: boolean,\n * __transFinishedCb: (err: boolean, cb: ((bool?: boolean) => void)) => void,\n * __transactionEndCallback: () => void,\n * __transactionFinished: boolean,\n * __completed: boolean,\n * __internal: boolean,\n * __abortFinished: boolean,\n * __createRequest: (\n * source: import('./IDBDatabase.js').IDBDatabaseFull|\n * import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull|\n * import('./IDBCursor.js').IDBCursorFull\n * ) => import('./IDBRequest.js').IDBRequestFull,\n * __pushToQueue: (\n * request: import('./IDBRequest.js').IDBRequestFull|null,\n * callback: SQLCallback,\n * args?: ObjectArray\n * ) => void,\n * __assertActive: () => void,\n * __addNonRequestToTransactionQueue: (\n * callback: SQLCallback,\n * args?: ObjectArray\n * ) => void\n * __addToTransactionQueue: (\n * callback: SQLCallback,\n * args: ObjectArray|undefined,\n * source: import('./IDBDatabase.js').IDBDatabaseFull|\n * import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull|\n * import('./IDBCursor.js').IDBCursorFull\n * ) => import('./IDBRequest.js').IDBRequestFull\n * __assertWritable: () => void,\n * }} IDBTransactionFull\n */\n\n/**\n * The IndexedDB Transaction.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBTransaction\n * @class\n */\nfunction IDBTransaction () {\n throw new TypeError('Illegal constructor');\n}\nconst IDBTransactionAlias = IDBTransaction;\n/**\n * @param {import('./IDBDatabase.js').IDBDatabaseFull} db\n * @param {import('./DOMStringList.js').DOMStringListFull} storeNames\n * @param {string} mode\n * @returns {IDBTransactionFull}\n */\nIDBTransaction.__createInstance = function (db, storeNames, mode) {\n /**\n * @class\n * @this {IDBTransactionFull}\n */\n function IDBTransaction () {\n const me = this;\n // @ts-expect-error It's ok\n me[Symbol.toStringTag] = 'IDBTransaction';\n util.defineReadonlyProperties(me, readonlyProperties);\n me.__id = ++uniqueID; // for debugging simultaneous transactions\n me.__active = true;\n me.__running = false;\n me.__errored = false;\n me.__requests = [];\n me.__objectStoreNames = storeNames;\n me.__mode = mode;\n me.__db = db;\n me.__error = null;\n // @ts-expect-error Part of `ShimEventTarget`\n me.__setOptions({\n legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB\n });\n\n readonlyProperties.forEach((readonlyProp) => {\n Object.defineProperty(this, readonlyProp, {\n configurable: true\n });\n });\n util.defineListenerProperties(this, listeners);\n me.__storeHandles = {};\n\n // Kick off the transaction as soon as all synchronous code is done\n setTimeout(() => { me.__executeRequests(); }, 0);\n }\n IDBTransaction.prototype = IDBTransactionAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBTransaction();\n};\n\n// @ts-expect-error It's ok\nIDBTransaction.prototype = EventTargetFactory.createInstance({\n defaultSync: true,\n // Ensure EventTarget preserves our properties\n extraProperties: ['complete']\n});\n\n/**\n *\n * @param {boolean} err\n * @param {(bool: boolean) => void} cb\n * @returns {void}\n */\nIDBTransaction.prototype.__transFinishedCb = function (err, cb) {\n cb(Boolean(err));\n};\n/**\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__executeRequests = function () {\n const me = this;\n if (me.__running) {\n if (CFG.DEBUG) { console.log('Looks like the request set is already running', me.mode); }\n return;\n }\n\n me.__running = true;\n\n me.db.__db[me.mode === 'readonly' ? 'readTransaction' : 'transaction']( // `readTransaction` is optimized, at least in `node-websql`\n function executeRequests (tx) {\n me.__tx = tx;\n /** @type {RequestInfo} */\n let q,\n i = -1;\n\n /**\n * @typedef {any} IDBRequestResult\n */\n\n /**\n * @param {IDBRequestResult} [result]\n * @param {import('./IDBRequest.js').IDBRequestFull} [req]\n * @returns {void}\n */\n function success (result, req) {\n if (me.__errored || me.__requestsFinished) {\n // We've already called \"onerror\", \"onabort\", or thrown within the transaction, so don't do it again.\n return;\n }\n if (req) {\n q.req = req; // Need to do this in case of cursors\n }\n if (!q.req) { // TS guard\n return;\n }\n if (q.req.__done) { // Avoid continuing with aborted requests\n return;\n }\n q.req.__done = true;\n q.req.__result = result;\n q.req.__error = null;\n\n me.__active = true;\n const e = createEvent('success');\n q.req.dispatchEvent(e);\n // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87\n if (e.__legacyOutputDidListenersThrowError) {\n logError('Error', 'An error occurred in a success handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec\n // me.__active = false;\n me.__abortTransaction(createDOMException('AbortError', 'A request was aborted (in user handler after success).'));\n return;\n }\n executeNextRequest();\n }\n\n /**\n * @param {[tx: SQLTransaction|DOMException|Error|SQLError, err?: SQLError]} args\n * @returns {void}\n */\n function error (...args /* tx, err */) {\n if (me.__errored || me.__requestsFinished) {\n // We've already called \"onerror\", \"onabort\", or thrown within\n // the transaction, so don't do it again.\n return;\n }\n if (q.req && q.req.__done) { // Avoid continuing with aborted requests\n return;\n }\n const err = /** @type {Error|DOMException} */ (findError(args));\n if (!q.req) {\n me.__abortTransaction(err);\n return;\n }\n\n // Fire an error event for the current IDBRequest\n q.req.__done = true;\n q.req.__error = err;\n q.req.__result = undefined; // Must be undefined if an error per `result` getter\n q.req.addLateEventListener('error', function (e) {\n if (e.cancelable && e.defaultPrevented && !e.__legacyOutputDidListenersThrowError) {\n executeNextRequest();\n }\n });\n q.req.addDefaultEventListener('error', function () {\n if (!q.req) { // TS guard\n return;\n }\n me.__abortTransaction(q.req.__error);\n });\n\n me.__active = true;\n const e = createEvent('error', err, {bubbles: true, cancelable: true});\n q.req.dispatchEvent(e);\n // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87\n if (e.__legacyOutputDidListenersThrowError) {\n logError('Error', 'An error occurred in an error handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec\n e.preventDefault(); // Prevent 'error' default as steps indicate we should abort with `AbortError` even without cancellation\n me.__abortTransaction(createDOMException('AbortError', 'A request was aborted (in user handler after error).'));\n }\n }\n\n /**\n * @returns {void}\n */\n function executeNextRequest () {\n if (me.__errored || me.__requestsFinished) {\n // We've already called \"onerror\", \"onabort\", or thrown within the transaction, so don't do it again.\n return;\n }\n i++;\n if (i >= me.__requests.length) {\n // All requests in the transaction are done\n me.__requests = [];\n if (me.__active) {\n requestsFinished();\n }\n } else {\n try {\n q = me.__requests[i];\n if (!q.req) {\n q.op(tx, q.args, executeNextRequest, error);\n return;\n }\n if (q.req.__done) { // Avoid continuing with aborted requests\n return;\n }\n q.op(tx, q.args, success, error, executeNextRequest);\n } catch (e) {\n error(/** @type {Error} */ (e));\n }\n }\n }\n\n executeNextRequest();\n },\n function webSQLError (webSQLErr) {\n // @ts-expect-error It's ok\n if (webSQLErr === true) { // Not a genuine SQL error\n return;\n }\n const err = webSQLErrback(/** @type {SQLError} */ (webSQLErr));\n me.__abortTransaction(err);\n },\n function () {\n // For Node, we don't need to try running here as we can keep\n // the transaction running long enough to rollback (in the\n // next (non-standard) callback for this transaction call)\n if (me.__transFinishedCb !== IDBTransaction.prototype.__transFinishedCb) { // Node\n return;\n }\n if (!me.__transactionEndCallback && !me.__requestsFinished) {\n me.__transactionFinished = true;\n return;\n }\n if (me.__transactionEndCallback && !me.__completed) {\n me.__transFinishedCb(me.__errored, me.__transactionEndCallback);\n }\n },\n function (currentTask, err, done, rollback, commit) {\n if (currentTask.readOnly || err) {\n return true;\n }\n me.__transFinishedCb = function (err, cb) {\n if (err) {\n rollback(err, cb);\n } else {\n commit(cb);\n }\n };\n if (me.__transactionEndCallback && !me.__completed) {\n me.__transFinishedCb(me.__errored, me.__transactionEndCallback);\n }\n return false;\n }\n );\n\n /**\n * @returns {void}\n */\n function requestsFinished () {\n me.__active = false;\n me.__requestsFinished = true;\n\n /**\n * @throws {Error}\n * @returns {void}\n */\n function complete () {\n me.__completed = true;\n if (CFG.DEBUG) { console.log('Transaction completed'); }\n const evt = createEvent('complete');\n try {\n me.__internal = true;\n me.dispatchEvent(evt);\n me.__internal = false;\n me.dispatchEvent(createEvent('__complete'));\n } catch (e) {\n me.__internal = false;\n // An error occurred in the \"oncomplete\" handler.\n // It's too late to call \"onerror\" or \"onabort\". Throw a global error instead.\n // (this may seem odd/bad, but it's how all native IndexedDB implementations work)\n me.__errored = true;\n throw e;\n } finally {\n me.__storeHandles = {};\n }\n }\n if (me.mode === 'readwrite') {\n if (me.__transactionFinished) {\n complete();\n return;\n }\n me.__transactionEndCallback = complete;\n return;\n }\n if (me.mode === 'readonly') {\n complete();\n return;\n }\n const ev = /** @type {Event & {complete: () => void}} */ (\n createEvent('__beforecomplete')\n );\n ev.complete = complete;\n me.dispatchEvent(ev);\n }\n};\n\n/**\n * Creates a new IDBRequest for the transaction.\n * NOTE: The transaction is not queued until you call {@link IDBTransaction#__pushToQueue}.\n * @param {import('./IDBDatabase.js').IDBDatabaseFull} source\n * @this {IDBTransactionFull}\n * @returns {IDBRequest}\n */\nIDBTransaction.prototype.__createRequest = function (source) {\n const me = this;\n const request = IDBRequest.__createInstance();\n request.__source = source !== undefined ? source : me.db;\n request.__transaction = me;\n return request;\n};\n\n/**\n * @typedef {(\n * tx: SQLTransaction,\n * args: ObjectArray,\n * success: (result?: any, req?: import('./IDBRequest.js').IDBRequestFull) => void,\n * error: (tx: SQLTransaction|Error|DOMException|SQLError, err?: SQLError) => void,\n * executeNextRequest?: () => void\n * ) => void} SQLCallback\n */\n\n/**\n * Adds a callback function to the transaction queue.\n * @param {SQLCallback} callback\n * @param {ObjectArray} args\n * @param {import('./IDBDatabase.js').IDBDatabaseFull|\n * import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull} source\n * @this {IDBTransactionFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBTransaction.prototype.__addToTransactionQueue = function (callback, args, source) {\n const request = this.__createRequest(source);\n this.__pushToQueue(request, callback, args);\n return request;\n};\n\n/**\n * Adds a callback function to the transaction queue without generating a\n * request.\n * @param {SQLCallback} callback\n * @param {ObjectArray} args\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__addNonRequestToTransactionQueue = function (callback, args) {\n this.__pushToQueue(null, callback, args);\n};\n\n/**\n * Adds an IDBRequest to the transaction queue.\n * @param {import('./IDBRequest.js').IDBRequestFull|null} request\n * @param {SQLCallback} callback\n * @param {ObjectArray} args\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__pushToQueue = function (request, callback, args) {\n this.__assertActive();\n this.__requests.push({\n op: callback,\n args,\n req: request\n });\n};\n\n/**\n * @throws {DOMException}\n * @returns {void}\n */\nIDBTransaction.prototype.__assertActive = function () {\n if (!this.__active) {\n throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished');\n }\n};\n\n/**\n * @throws {DOMException}\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__assertWritable = function () {\n if (this.mode === 'readonly') {\n throw createDOMException('ReadOnlyError', 'The transaction is read only');\n }\n};\n\n/**\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__assertVersionChange = function () {\n IDBTransaction.__assertVersionChange(this);\n};\n\n/**\n * Returns the specified object store.\n * @param {string} objectStoreName\n * @this {IDBTransactionFull}\n * @returns {IDBObjectStore}\n */\nIDBTransaction.prototype.objectStore = function (objectStoreName) {\n const me = this;\n if (!(me instanceof IDBTransaction)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No object store name was specified');\n }\n IDBTransaction.__assertNotFinished(me);\n if (me.__objectStoreNames.indexOf(objectStoreName) === -1) { // eslint-disable-line unicorn/prefer-includes -- Not supported\n throw createDOMException('NotFoundError', objectStoreName + ' is not participating in this transaction');\n }\n const store = me.db.__objectStores[objectStoreName];\n if (!store) {\n throw createDOMException('NotFoundError', objectStoreName + ' does not exist in ' + me.db.name);\n }\n\n if (!me.__storeHandles[objectStoreName] ||\n // These latter conditions are to allow store\n // recreation to create new clone object\n me.__storeHandles[objectStoreName].__pendingDelete ||\n me.__storeHandles[objectStoreName].__deleted) {\n me.__storeHandles[objectStoreName] = IDBObjectStore.__clone(store, me);\n }\n return me.__storeHandles[objectStoreName];\n};\n\n/**\n *\n * @param {Error|DOMException|null} err\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.__abortTransaction = function (err) {\n const me = this;\n logError('Error', 'An error occurred in a transaction', err);\n if (me.__errored) {\n // We've already called \"onerror\", \"onabort\", or thrown, so don't do it again.\n return;\n }\n me.__errored = true;\n\n if (me.mode === 'versionchange') { // Steps for aborting an upgrade transaction\n me.db.__version = me.db.__oldVersion;\n me.db.__objectStoreNames = me.db.__oldObjectStoreNames;\n me.__objectStoreNames = me.db.__oldObjectStoreNames;\n Object.values(me.db.__objectStores).concat(\n Object.values(me.__storeHandles)\n ).forEach(function (store) {\n // Store was already created so we restore to name before the rename\n if ('__pendingName' in store &&\n me.db.__oldObjectStoreNames.indexOf(store.__pendingName) > -1 // eslint-disable-line unicorn/prefer-includes -- Not supported\n ) {\n store.__name = store.__originalName;\n }\n store.__indexNames = store.__oldIndexNames;\n delete store.__pendingDelete;\n Object.values(store.__indexes).concat(\n Object.values(store.__indexHandles)\n ).forEach(function (index) {\n // Index was already created so we restore to name before the rename\n if ('__pendingName' in index &&\n store.__oldIndexNames.indexOf(index.__pendingName) > -1 // eslint-disable-line unicorn/prefer-includes -- Not supported\n ) {\n index.__name = index.__originalName;\n }\n delete index.__pendingDelete;\n });\n });\n }\n me.__active = false; // Setting here and in requestsFinished for https://github.com/w3c/IndexedDB/issues/87\n\n if (err !== null) {\n me.__error = err;\n }\n\n if (me.__requestsFinished) {\n // The transaction has already completed, so we can't call \"onerror\" or \"onabort\".\n // So throw the error instead.\n setTimeout(() => {\n throw err;\n }, 0);\n }\n\n /**\n * @param {SQLTransaction|null} [tx]\n * @param {SQLResultSet|SQLError|{code: 0}} [errOrResult]\n * @returns {void}\n */\n function abort (tx, errOrResult) {\n if (!tx) {\n if (CFG.DEBUG) { console.log('Rollback not possible due to missing transaction', me); }\n } else if (errOrResult && 'code' in errOrResult && typeof errOrResult.code === 'number') {\n if (CFG.DEBUG) { console.log('Rollback erred; feature is probably not supported as per WebSQL', me); }\n } else if (CFG.DEBUG) { console.log('Rollback succeeded', me); }\n\n me.dispatchEvent(createEvent('__preabort'));\n me.__requests.filter(function (q, i, arr) { // eslint-disable-line promise/no-promise-in-callback -- Sync promise\n return q.req && !q.req.__done && [i, -1].includes(\n arr.map((q) => q.req).lastIndexOf(q.req)\n );\n }).reduce(function (promises, q) {\n // We reduce to a chain of promises to be queued in order, so we cannot\n // use `Promise.all`, and I'm unsure whether `setTimeout` currently\n // behaves first-in-first-out with the same timeout so we could\n // just use a `forEach`.\n return promises.then(function () {\n if (!q.req) { // TS guard\n throw new Error('Missing request');\n }\n q.req.__done = true;\n q.req.__result = undefined;\n q.req.__error = createDOMException('AbortError', 'A request was aborted (an unfinished request).');\n const reqEvt = createEvent('error', q.req.__error, {bubbles: true, cancelable: true});\n return new SyncPromise(\n /** @type {() => void} */\n (resolve) => {\n setTimeout(() => {\n if (!q.req) { // TS guard\n throw new Error('Missing request');\n }\n q.req.dispatchEvent(reqEvt); // No need to catch errors\n resolve();\n });\n }\n );\n });\n }, SyncPromise.resolve(undefined)).then(function () { // Also works when there are no pending requests\n const evt = createEvent('abort', err, {bubbles: true, cancelable: false});\n setTimeout(() => {\n me.__abortFinished = true;\n me.dispatchEvent(evt);\n me.__storeHandles = {};\n me.dispatchEvent(createEvent('__abort'));\n });\n return undefined;\n }).catch((err) => {\n console.log('Abort error');\n throw err;\n });\n }\n\n me.__transFinishedCb(true, function (rollback) {\n if (rollback && me.__tx) { // Not supported in standard SQL (and WebSQL errors should\n // rollback automatically), but for Node.js, etc., we give chance for\n // manual aborts which would otherwise not work.\n if (me.mode === 'readwrite') {\n if (me.__transactionFinished) {\n abort();\n return;\n }\n me.__transactionEndCallback = abort;\n return;\n }\n try {\n me.__tx.executeSql(\n 'ROLLBACK',\n [],\n abort,\n /** @type {SQLStatementErrorCallback} */ (abort)\n ); // Not working in some circumstances, even in Node\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n // Browser errs when transaction has ended and since it most likely already erred here,\n // we call to abort\n abort();\n }\n } else {\n abort(null, {code: 0});\n }\n });\n};\n\n/**\n * @this {IDBTransactionFull}\n * @returns {void}\n */\nIDBTransaction.prototype.abort = function () {\n const me = this;\n if (!(me instanceof IDBTransaction)) {\n throw new TypeError('Illegal invocation');\n }\n if (CFG.DEBUG) { console.log('The transaction was aborted', me); }\n IDBTransaction.__assertNotFinished(me);\n me.__abortTransaction(null);\n};\n\nIDBTransaction.prototype[Symbol.toStringTag] = 'IDBTransactionPrototype';\n\n/**\n *\n * @param {IDBTransactionFull|undefined} tx\n * @returns {void}\n */\nIDBTransaction.__assertVersionChange = function (tx) {\n if (!tx || tx.mode !== 'versionchange') {\n throw createDOMException('InvalidStateError', 'Not a version transaction');\n }\n};\n/**\n *\n * @param {IDBTransactionFull} tx\n * @throws {DOMException}\n * @returns {void}\n */\nIDBTransaction.__assertNotVersionChange = function (tx) {\n if (tx && tx.mode === 'versionchange') {\n throw createDOMException('InvalidStateError', 'Cannot be called during a version transaction');\n }\n};\n\n/**\n *\n * @param {IDBTransactionFull|undefined} tx\n * @throws {DOMException}\n * @returns {void}\n */\nIDBTransaction.__assertNotFinished = function (tx) {\n if (!tx || tx.__completed || tx.__abortFinished || tx.__errored) {\n throw createDOMException('InvalidStateError', 'Transaction finished by commit or abort');\n }\n};\n\n// object store methods behave differently: see https://github.com/w3c/IndexedDB/issues/192\n/**\n *\n * @param {IDBTransactionFull} tx\n * @returns {void}\n */\nIDBTransaction.__assertNotFinishedObjectStoreMethod = function (tx) {\n try {\n IDBTransaction.__assertNotFinished(tx);\n } catch (err) {\n if (tx && !tx.__completed && !tx.__abortFinished) {\n throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished');\n }\n throw err;\n }\n};\n\n/**\n *\n * @param {IDBTransactionFull|undefined} tx\n * @throws {DOMException}\n * @returns {void}\n */\nIDBTransaction.__assertActive = function (tx) {\n if (!tx || !tx.__active) {\n throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished');\n }\n};\n\n/**\n* Used by our `EventTarget.prototype` library to implement bubbling/capturing.\n * @this {IDBTransactionFull}\n* @returns {import('./IDBDatabase.js').IDBDatabaseFull}\n*/\nIDBTransaction.prototype.__getParent = function () {\n return this.db;\n};\n\nutil.defineOuterInterface(IDBTransaction.prototype, listeners);\nutil.defineReadonlyOuterInterface(IDBTransaction.prototype, readonlyProperties);\n\nObject.defineProperty(IDBTransaction.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBTransaction\n});\n\nObject.defineProperty(IDBTransaction, 'prototype', {\n writable: false\n});\n\nexport default IDBTransaction;\n","function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _objectSpread2(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(\"\"===t)return r;if(!e||\"object\"!==_typeof(e))throw new TypeError(\"Unexpected non-object type\");var n=t.indexOf(\".\");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function getJSONType(e){return null===e?\"null\":Array.isArray(e)?\"array\":_typeof(e)}function _await(e,t,r){return e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e}var n=Object.keys,a=Object.hasOwn,o=Array.isArray,i=[\"type\",\"replaced\",\"iterateIn\",\"iterateUnsetNumeric\",\"addLength\"];function _async(e){return function(){for(var t=[],r=0;ro?-1:at.keypath?1:0}var c=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return _createClass(Typeson,[{key:\"stringify\",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var a=this.encapsulate(e,null,n);return o(a)?JSON.stringify(a[0],t,r):a.then((function(e){return JSON.stringify(e,t,r)}))}},{key:\"stringifySync\",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:\"stringifyAsync\",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:\"parse\",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:\"parseSync\",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:\"parseAsync\",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:\"specialTypeNames\",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:\"rootTypeName\",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:\"encapsulate\",value:function encapsulate(t,r,c){var s=this,u=_objectSpread2(_objectSpread2({sync:!0},this.options),c),l=u.sync,f={},y=[],p=[],d=[],v=!(\"cyclic\"in u)||u.cyclic,m=u.encapsulateObserver,b=function finish(e){var t=Object.values(f);if(u.iterateNone)return t.length?t[0]:getJSONType(e);if(t.length){if(u.returnTypeNames)return function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}(e)||function _iterableToArray(e){if(\"undefined\"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e[\"@@iterator\"])return Array.from(e)}(e)||_unsupportedIterableToArray(e)||function _nonIterableSpread(){throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}()}(new Set(t));e&&isPlainObject(e)&&!a(e,\"$types\")?e.$types=f:e={$:e,$types:{$:f}}}else isObject(e)&&a(e,\"$types\")&&(e={$:e,$types:!0});return!u.returnTypeNames&&e},h=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var a=!1,o=[],i=_slicedToArray(r.splice(0,1),1),c=_slicedToArray(i[0],7),s=c[0],u=c[2],l=c[3],f=c[4],y=c[5],p=c[6],d=O(s,n,u,l,o,!0,p),v=hasConstructorOf(d,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(s&&v)return _await(d.p,(function(e){f[y]=e;var r=h(t,o);return a=!0,r}))}),(function(e){return a?e:(s?f[y]=d:t=v?d.p:d,h(t,o))}))})))),(function(){return t}))}))})),g=function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=i.map((function(t){var r=e[t];return delete e[t],r}));r(),i.forEach((function(t,r){e[t]=n[r]}))},O=function _encapsulate(t,r,i,c,l,d,v){var b,h={},O=_typeof(r),_=m?function(n){var a,o=null!==(a=null!=v?v:c.type)&&void 0!==a?a:getJSONType(r);m(Object.assign(null!=n?n:h,{keypath:t,value:r,cyclic:i,stateObj:c,promisesData:l,resolvingTypesonPromise:d,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:o}))}:null;if([\"string\",\"boolean\",\"number\",\"undefined\"].includes(O))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY||0===r?(b=c.replaced?r:w(t,r,c,l,!1,d,_))!==r&&(h={replaced:b}):b=r,_&&_(),b;if(null===r)return _&&_(),r;if(i&&!c.iterateIn&&!c.iterateUnsetNumeric&&r&&\"object\"===_typeof(r)){var A=y.indexOf(r);if(!(A<0))return f[t]=\"#\",_&&_({cyclicKeypath:p[A]}),\"#\"+p[A];!0===i&&(y.push(r),p.push(t))}var S,j,T=isPlainObject(r),I=o(r),N=(T||I)&&(!s.plainObjectReplacers.length||c.replaced)||c.iterateIn?r:w(t,r,c,l,T||I,null,_);if(N!==r?(b=N,h={replaced:N}):\"\"===t&&hasConstructorOf(r,e)?(l.push([t,r,i,c,void 0,void 0,c.type]),b=r):I&&\"object\"!==c.iterateIn||\"array\"===c.iterateIn?(S=new Array(r.length),h={clone:S}):([\"function\",\"symbol\"].includes(_typeof(r))||\"toJSON\"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!T&&\"object\"!==c.iterateIn?b=r:(S={},c.addLength&&(S.length=r.length),h={clone:S}),_&&_(),u.iterateNone)return null!==(j=S)&&void 0!==j?j:b;if(!S)return b;if(c.iterateIn){var P=function _loop(n){var o={ownKeys:a(r,n)};g(c,o,(function(){var a=t+(t?\".\":\"\")+escapeKeyPathComponent(n),o=_encapsulate(a,r[n],Boolean(i),c,l,d);hasConstructorOf(o,e)?l.push([a,o,Boolean(i),c,S,n,c.type]):void 0!==o&&(S[n]=o)}))};for(var x in r)P(x);_&&_({endIterateIn:!0,end:!0})}else n(r).forEach((function(n){var a=t+(t?\".\":\"\")+escapeKeyPathComponent(n);g(c,{ownKeys:!0},(function(){var t=_encapsulate(a,r[n],Boolean(i),c,l,d);hasConstructorOf(t,e)?l.push([a,t,Boolean(i),c,S,n,c.type]):void 0!==t&&(S[n]=t)}))})),_&&_({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var E=r.length,C=function _loop2(n){if(!(n in r)){var a=\"\".concat(t).concat(t?\".\":\"\").concat(n);g(c,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(i),c,l,d);hasConstructorOf(t,e)?l.push([a,t,Boolean(i),c,S,n,c.type]):void 0!==t&&(S[n]=t)}))}},B=0;B>2],o+=l[(3&n[i])<<4|n[i+1]>>4],o+=l[(15&n[i+1])<<2|n[i+2]>>6],o+=l[63&n[i+2]];return a%3==2?o=o.slice(0,-1)+\"=\":a%3==1&&(o=o.slice(0,-2)+\"==\"),o},d=function decode(e,t){var r=e.length;if(r%4)throw new Error(\"Bad base64 length: not divisible by four\");var n,a,o,i,c=.75*e.length,s=0;\"=\"===e[e.length-1]&&(c--,\"=\"===e[e.length-2]&&c--);for(var u=new ArrayBuffer(c,t),l=new Uint8Array(u),y=0;y>4,l[s++]=(15&a)<<4|o>>2,l[s++]=(3&o)<<6|63&i;return u};const v={arraybuffer:{test:e=>\"ArrayBuffer\"===toStringTag(e),replace(e,t){t.buffers||(t.buffers=[]);const r=t.buffers.indexOf(e);return r>-1?{index:r}:(t.buffers.push(e),{s:p(e),maxByteLength:e.maxByteLength})},revive(e,t){if(t.buffers||(t.buffers=[]),Object.hasOwn(e,\"index\"))return t.buffers[e.index];const r=d(e.s,{maxByteLength:e.maxByteLength});return t.buffers.push(r),r}}},m={bigintObject:{test:e=>\"object\"==typeof e&&hasConstructorOf(e,BigInt),replace:String,revive:e=>new Object(BigInt(e))}},b={bigint:{test:e=>\"bigint\"==typeof e,replace:String,revive:e=>BigInt(e)}};function arraybuffer2string(e){return new Uint8Array(e).reduce(((e,t)=>e+String.fromCodePoint(t)),\"\")}function string2arraybuffer(e){const t=new Uint8Array(e.length);for(let r=0;r\"Blob\"===toStringTag(e),replace(e){const t=new XMLHttpRequest;if(t.overrideMimeType(\"text/plain; charset=x-user-defined\"),t.open(\"GET\",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error(\"Bad Blob access: \"+t.status);return{type:e.type,stringContents:t.responseText}},revive(e){const{type:t,stringContents:r}=e;return new Blob([string2arraybuffer(r)],{type:t})},replaceAsync:t=>new e(((e,r)=>{const n=new FileReader;n.addEventListener(\"load\",(()=>{e({type:t.type,stringContents:arraybuffer2string(n.result)})})),n.addEventListener(\"error\",(()=>{r(n.error)})),n.readAsArrayBuffer(t)}))}};function generateUUID(){let e=Date.now();return\"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replaceAll(/[xy]/gu,(function(t){const r=Math.trunc((e+16*Math.random())%16);return e=Math.floor(e/16),(\"x\"===t?r:3&r|8).toString(16)}))}const g={},O={cloneable:{test:e=>e&&\"object\"==typeof e&&\"function\"==typeof e[Symbol.for(\"cloneEncapsulate\")],replace(e){const t=e[Symbol.for(\"cloneEncapsulate\")](),r=generateUUID();return g[r]=e,{uuid:r,encapsulated:t}},revive(e){const{uuid:t,encapsulated:r}=e;return g[t][Symbol.for(\"cloneRevive\")](r)}}},w={cryptokey:{test:e=>\"CryptoKey\"===toStringTag(e)&&e.extractable,replaceAsync:t=>new e((async(e,r)=>{let n;try{n=await crypto.subtle.exportKey(\"jwk\",t)}catch(e){return void r(e)}e({jwk:n,algorithm:t.algorithm,usages:t.usages})})),revive(e){const{jwk:t,algorithm:r,usages:n}=e;return crypto.subtle.importKey(\"jwk\",t,r,!0,n)}}},_={dataview:{test:e=>\"DataView\"===toStringTag(e),replace({buffer:e,byteOffset:t,byteLength:r},n){n.buffers||(n.buffers=[]);const a=n.buffers.indexOf(e);return a>-1?{index:a,byteOffset:t,byteLength:r}:(n.buffers.push(e),{encoded:p(e),maxByteLength:e.maxByteLength,byteOffset:t,byteLength:r})},revive(e,t){t.buffers||(t.buffers=[]);const{byteOffset:r,byteLength:n,encoded:a,index:o,maxByteLength:i}=e;let c;return\"index\"in e?c=t.buffers[o]:(c=d(a,void 0===i?i:{maxByteLength:i}),t.buffers.push(c)),new DataView(c,r,n)}}},A={date:{test:e=>\"Date\"===toStringTag(e),replace(e){const t=e.getTime();return Number.isNaN(t)?\"NaN\":t},revive:e=>\"NaN\"===e?new Date(Number.NaN):new Date(e)}},S={domexception:{test:e=>\"DOMException\"===toStringTag(e),replace:e=>({name:e.name,message:e.message}),revive:({message:e,name:t})=>new DOMException(e,t)}},j={};function create$5(e){j[e.name.toLowerCase()]={test:t=>toStringTag(t)===e.name,replace:e=>e.is2D?{a:e.a,b:e.b,c:e.c,d:e.d,e:e.e,f:e.f}:{m11:e.m11,m12:e.m12,m13:e.m13,m14:e.m14,m21:e.m21,m22:e.m22,m23:e.m23,m24:e.m24,m31:e.m31,m32:e.m32,m33:e.m33,m34:e.m34,m41:e.m41,m42:e.m42,m43:e.m43,m44:e.m44},revive:t=>Object.hasOwn(t,\"a\")?new e([t.a,t.b,t.c,t.d,t.e,t.f]):new e([t.m11,t.m12,t.m13,t.m14,t.m21,t.m22,t.m23,t.m24,t.m31,t.m32,t.m33,t.m34,t.m41,t.m42,t.m43,t.m44])}}\"undefined\"!=typeof DOMMatrix&&create$5(DOMMatrix),\"undefined\"!=typeof DOMMatrixReadOnly&&create$5(DOMMatrixReadOnly);const T={};function create$4(e){T[e.name.toLowerCase()]={test:t=>toStringTag(t)===e.name,replace:e=>({x:e.x,y:e.y,z:e.z,w:e.w}),revive:({x:t,y:r,z:n,w:a})=>new e(t,r,n,a)}}\"undefined\"!=typeof DOMPoint&&create$4(DOMPoint),\"undefined\"!=typeof DOMPointReadOnly&&create$4(DOMPointReadOnly);const I={domquad:{test:e=>\"DOMQuad\"===toStringTag(e),replace:e=>({p1:e.p1,p2:e.p2,p3:e.p3,p4:e.p4}),revive:({p1:e,p2:t,p3:r,p4:n})=>new DOMQuad(e,t,r,n)}},N={};function create$3(e){N[e.name.toLowerCase()]={test:t=>toStringTag(t)===e.name,replace:e=>({x:e.x,y:e.y,width:e.width,height:e.height}),revive:({x:t,y:r,width:n,height:a})=>new e(t,r,n,a)}}\"undefined\"!=typeof DOMRect&&create$3(DOMRect),\"undefined\"!=typeof DOMRectReadOnly&&create$3(DOMRectReadOnly);const P={error:{test:e=>\"Error\"===toStringTag(e),replace:({name:e,message:t,cause:r,stack:n,fileName:a,lineNumber:o,columnNumber:i})=>({name:e,message:t,cause:r,stack:n,fileName:a,lineNumber:o,columnNumber:i}),revive(e){const t=new Error(e.message);return t.name=e.name,t.cause=e.cause,t.stack=e.stack,t.fileName=e.fileName,t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}}},x={};function create$2(e){x[e.name.toLowerCase()]={test:t=>hasConstructorOf(t,e),replace:({name:e,message:t,cause:r,stack:n,fileName:a,lineNumber:o,columnNumber:i,errors:c})=>({name:e,message:t,cause:r,stack:n,fileName:a,lineNumber:o,columnNumber:i,errors:c}),revive(t){const r=\"undefined\"!=typeof AggregateError&&e===AggregateError?new e(t.errors,t.message):new e(t.message);return r.name=t.name,r.cause=t.cause,r.stack=t.stack,r.fileName=t.fileName,r.lineNumber=t.lineNumber,r.columnNumber=t.columnNumber,r}}}[TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError].forEach((e=>create$2(e))),\"undefined\"!=typeof AggregateError&&create$2(AggregateError),\"function\"==typeof InternalError&&create$2(InternalError);const E={file:{test:e=>\"File\"===toStringTag(e),replace(e){const t=new XMLHttpRequest;if(t.overrideMimeType(\"text/plain; charset=x-user-defined\"),t.open(\"GET\",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error(\"Bad File access: \"+t.status);return{type:e.type,stringContents:t.responseText,name:e.name,lastModified:e.lastModified}},revive:({name:e,type:t,stringContents:r,lastModified:n})=>new File([string2arraybuffer(r)],e,{type:t,lastModified:n}),replaceAsync:t=>new e((function(e,r){const n=new FileReader;n.addEventListener(\"load\",(function(){e({type:t.type,stringContents:arraybuffer2string(n.result),name:t.name,lastModified:t.lastModified})})),n.addEventListener(\"error\",(function(){r(n.error)})),n.readAsArrayBuffer(t)}))}},C={file:E.file,filelist:{test:e=>\"FileList\"===toStringTag(e),replace(e){const t=[];for(let r=0;r\"ImageBitmap\"===toStringTag(e)||e&&e.dataset&&\"ImageBitmap\"===e.dataset.toStringTag,replace(e){const t=document.createElement(\"canvas\");return t.getContext(\"2d\").drawImage(e,0,0),{width:e.width,height:e.height,dataURL:t.toDataURL()}},revive(e){const t=\"undefined\"==typeof OffscreenCanvas?document.createElement(\"canvas\"):new OffscreenCanvas(e.width,e.height),r=t.getContext(\"2d\"),n=document.createElement(\"img\");return n.addEventListener(\"load\",(function(){r.drawImage(n,0,0)})),n.src=e.dataURL,\"undefined\"==typeof OffscreenCanvas?t:t.transferToImageBitmap()},reviveAsync(t){const r=document.createElement(\"canvas\"),n=r.getContext(\"2d\"),a=document.createElement(\"img\");return a.addEventListener(\"load\",(function(){n.drawImage(a,0,0)})),a.src=t.dataURL,new e((async(e,t)=>{try{e(await createImageBitmap(r))}catch(e){t(e)}}))}}},k={imagedata:{test:e=>\"ImageData\"===toStringTag(e),replace:e=>({array:[...e.data],width:e.width,height:e.height}),revive:e=>new ImageData(new Uint8ClampedArray(e.array),e.width,e.height)}},U={infinity:{test:e=>e===Number.POSITIVE_INFINITY,replace:()=>\"Infinity\",revive:()=>Number.POSITIVE_INFINITY}},M={test:e=>hasConstructorOf(e,Intl.Collator),replace:e=>e.resolvedOptions(),revive:e=>new Intl.Collator(e.locale,e)},L={IntlCollator:M,IntlDateTimeFormat:{test:e=>hasConstructorOf(e,Intl.DateTimeFormat),replace:e=>e.resolvedOptions(),revive:e=>new Intl.DateTimeFormat(e.locale,e)},IntlNumberFormat:{test:e=>hasConstructorOf(e,Intl.NumberFormat),replace:e=>e.resolvedOptions(),revive:e=>new Intl.NumberFormat(e.locale,e)}},D={map:{test:e=>\"Map\"===toStringTag(e),replace:e=>[...e.entries()],revive:e=>new Map(e)}},K={nan:{test:e=>Number.isNaN(e),replace:()=>\"NaN\",revive:()=>Number.NaN}},F={negativeInfinity:{test:e=>e===Number.NEGATIVE_INFINITY,replace:()=>\"-Infinity\",revive:()=>Number.NEGATIVE_INFINITY}},$={negativeZero:{test:e=>Object.is(e,-0),replace:()=>0,revive:()=>-0}},J={nonbuiltinIgnore:{test:e=>e&&\"object\"==typeof e&&!Array.isArray(e)&&![\"Object\",\"Boolean\",\"Number\",\"String\",\"Error\",\"RegExp\",\"Math\",\"Date\",\"Map\",\"Set\",\"JSON\",\"ArrayBuffer\",\"SharedArrayBuffer\",\"DataView\",\"Int8Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"Int16Array\",\"Uint16Array\",\"Int32Array\",\"Uint32Array\",\"Float32Array\",\"Float64Array\",\"Promise\",\"String Iterator\",\"Array Iterator\",\"Map Iterator\",\"Set Iterator\",\"WeakMap\",\"WeakSet\",\"Atomics\",\"Module\"].includes(toStringTag(e)),replace(){}}},V={StringObject:{test:e=>\"String\"===toStringTag(e)&&\"object\"==typeof e,replace:String,revive:e=>new String(e)},BooleanObject:{test:e=>\"Boolean\"===toStringTag(e)&&\"object\"==typeof e,replace:e=>e.valueOf(),revive:e=>new Boolean(e)},NumberObject:{test:e=>\"Number\"===toStringTag(e)&&\"object\"==typeof e,replace:Number,revive:e=>new Number(e)}},q={promise:{test:e=>\"Promise\"===toStringTag(e),replaceAsync:t=>new e((async e=>{try{e({value:await t})}catch(t){e({error:t})}})),revive:e=>e.error?Promise.reject(e.error):Promise.resolve(e.value)}},Y={regexp:{test:e=>\"RegExp\"===toStringTag(e),replace:e=>({source:e.source,flags:(e.global?\"g\":\"\")+(e.ignoreCase?\"i\":\"\")+(e.multiline?\"m\":\"\")+(e.sticky?\"y\":\"\")+(e.unicode?\"u\":\"\")}),revive:({source:e,flags:t})=>new RegExp(e,t)}},W={},G={resurrectable:{test:e=>e&&!Array.isArray(e)&&[\"object\",\"function\",\"symbol\"].includes(typeof e),replace(e){const t=generateUUID();return W[t]=e,t},revive:e=>W[e]}},H={set:{test:e=>\"Set\"===toStringTag(e),replace:e=>[...e.values()],revive:e=>new Set(e)}},z={symbol:{test:e=>\"symbol\"==typeof e,replace:e=>({global:void 0!==Symbol.keyFor(e),sym:String(e).slice(7,-1)}),revive:e=>e.global?Symbol.for(e.sym):Symbol(e.sym)}},Q={};\"function\"==typeof Int8Array&&[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...\"function\"==typeof BigInt64Array?[BigInt64Array,BigUint64Array]:[]].forEach((e=>function create$1(e){const t=e.name;Q[t.toLowerCase()]={test:e=>toStringTag(e)===t,replace:e=>(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e:e.slice(0)).buffer,revive:t=>\"ArrayBuffer\"===toStringTag(t)?new e(t):t}}(e)));const X={};\"function\"==typeof Int8Array&&[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...\"function\"==typeof BigInt64Array?[BigInt64Array,BigUint64Array]:[]].forEach((e=>function create(e){const t=e.name;X[t.toLowerCase()]={test:e=>toStringTag(e)===t,replace({buffer:e,byteOffset:t,length:r},n){n.buffers||(n.buffers=[]);const a=n.buffers.indexOf(e);return a>-1?{index:a,byteOffset:t,length:r}:(n.buffers.push(e),{maxByteLength:e.maxByteLength,encoded:p(e),byteOffset:t,length:r})},revive(t,r){r.buffers||(r.buffers=[]);const{byteOffset:n,length:a,encoded:o,index:i,maxByteLength:c}=t;let s;return\"index\"in t?s=r.buffers[i]:(s=d(o,void 0===c?void 0:{maxByteLength:c}),r.buffers.push(s)),new e(s,n,a)}}}(e)));const Z={undef:{test:(e,t)=>void 0===e&&(t.ownKeys||!(\"ownKeys\"in t)),replace:()=>0,revive:()=>new s}},ee={userObject:{test:e=>isUserObject(e),replace:e=>({...e}),revive:e=>e}},te=[{arrayNonindexKeys:{testPlainObjects:!0,test:(e,t)=>!!Array.isArray(e)&&(Object.keys(e).some((e=>String(Number.parseInt(e))!==e))&&(t.iterateIn=\"object\",t.addLength=!0),!0),replace:(e,t)=>(t.iterateUnsetNumeric=!0,e),revive(e){if(Array.isArray(e))return e;const t=[];return Object.entries(e).forEach((([e,r])=>{t[e]=r})),t}}},{sparseUndefined:{test:(e,t)=>void 0===e&&!1===t.ownKeys,replace:()=>0,revive(){}}}],re=[K,U,F,$],ne=[Z,te,V,re,A,P,x,Y].concat(\"function\"==typeof Map?D:[],\"function\"==typeof Set?H:[],\"function\"==typeof ArrayBuffer?v:[],\"function\"==typeof Uint8Array?X:[],\"function\"==typeof DataView?_:[],\"undefined\"!=typeof Intl?L:[],\"undefined\"!=typeof BigInt?[b,m]:[]),ae=[P,x],oe=[ne,{arraybuffer:null},Q],ie=[{sparseArrays:{testPlainObjects:!0,test:e=>Array.isArray(e),replace:(e,t)=>(t.iterateUnsetNumeric=!0,e)}},{sparseUndefined:{test:(e,t)=>void 0===e&&!1===t.ownKeys,replace:()=>0,revive(){}}}],ce=[ee,Z,te,V,re,A,Y,k,B,E,C,h,P,x].concat(\"function\"==typeof Map?D:[],\"function\"==typeof Set?H:[],\"function\"==typeof ArrayBuffer?v:[],\"function\"==typeof Uint8Array?X:[],\"function\"==typeof DataView?_:[],\"undefined\"!=typeof crypto?w:[],\"undefined\"!=typeof BigInt?[b,m]:[],\"undefined\"!=typeof DOMException?S:[],\"undefined\"!=typeof DOMRect?N:[],\"undefined\"!=typeof DOMPoint?T:[],\"undefined\"!=typeof DOMQuad?I:[],\"undefined\"!=typeof DOMMatrix?j:[]),se=ce.concat({checkDataCloneException:{test(e){const t={}.toString.call(e).slice(8,-1);if([\"symbol\",\"function\"].includes(typeof e)||[\"Arguments\",\"Module\",\"Promise\",\"WeakMap\",\"WeakSet\",\"Event\",\"MessageChannel\"].includes(t)||e&&\"object\"==typeof e&&\"number\"==typeof e.nodeType&&\"function\"==typeof e.insertBefore)throw new DOMException(\"The object cannot be cloned.\",\"DataCloneError\");return!1}}}),ue=[ie,Z],le=[ne];export{u as JSON_TYPES,c as Typeson,e as TypesonPromise,s as Undefined,te as arrayNonindexKeys,v as arraybuffer,b as bigint,m as bigintObject,h as blob,ne as builtin,O as cloneable,w as cryptokey,_ as dataview,A as date,S as domexception,j as dommatrix,T as dompoint,I as domquad,N as domrect,P as error,x as errors,escapeKeyPathComponent,E as file,C as filelist,getByKeyPath,getJSONType,hasConstructorOf,B as imagebitmap,k as imagedata,U as infinity,L as intlTypes,isObject,isPlainObject,isThenable,isUserObject,D as map,K as nan,F as negativeInfinity,$ as negativeZero,J as nonbuiltinIgnore,ae as postmessage,V as primitiveObjects,q as promise,Y as regexp,G as resurrectable,H as set,setAtKeyPath,oe as socketio,ie as sparseUndefined,re as specialNumbers,ce as structuredCloning,se as structuredCloningThrowing,z as symbol,toStringTag,X as typedArrays,Q as typedArraysSocketio,Z as undef,ue as undefPreset,unescapeKeyPathComponent,le as universal,ee as userObject};\n//# sourceMappingURL=index.min.js.map\n","import {\n Typeson, hasConstructorOf, structuredCloningThrowing\n} from 'typeson-registry';\n\nimport {createDOMException, ShimDOMException} from './DOMException.js';\n\n// See: http://stackoverflow.com/questions/42170826/categories-for-rejection-by-the-structured-cloning-algorithm\n\nlet typeson = new Typeson().register(structuredCloningThrowing);\n\n/**\n * @param {(preset: import('typeson-registry').Preset) =>\n * import('typeson-registry').Preset} func\n * @returns {void}\n */\nfunction register (func) {\n typeson = new Typeson().register(func(structuredCloningThrowing));\n}\n\n/**\n * We are keeping the callback approach for now in case we wish to reexpose\n * `Blob`, `File`, `FileList` asynchronously (though in such a case, we\n * should probably refactor as a Promise).\n * @param {AnyValue} obj\n * @param {(str: string) => void} [func]\n * @throws {Error}\n * @returns {string}\n */\nfunction encode (obj, func) {\n let ret;\n try {\n ret = typeson.stringifySync(obj);\n } catch (err) {\n // SCA in typeson-registry using `DOMException` which is not defined (e.g., in Node)\n if (hasConstructorOf(err, ReferenceError) ||\n // SCA in typeson-registry threw a cloning error and we are in a\n // supporting environment (e.g., the browser) where `ShimDOMException` is\n // an alias for `DOMException`; if typeson-registry ever uses our shim\n // to throw, we can use this condition alone.\n hasConstructorOf(err, ShimDOMException)) {\n throw createDOMException('DataCloneError', 'The object cannot be cloned.');\n }\n // We should rethrow non-cloning exceptions like from\n // throwing getters (as in the W3C test, key-conversion-exceptions.htm)\n throw err;\n }\n if (func) {\n func(ret);\n }\n return ret;\n}\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @param {string} obj\n * @returns {AnyValue}\n */\nfunction decode (obj) {\n return typeson.parse(obj);\n}\n\n/**\n * @param {AnyValue} val\n * @returns {AnyValue}\n */\nfunction clone (val) {\n // We don't return the intermediate `encode` as we'll need to reencode\n // the clone as it may differ\n return decode(encode(val));\n}\n\nexport {encode, decode, clone, register};\n","import SyncPromise from 'sync-promise-expanded';\nimport {createDOMException} from './DOMException.js';\nimport {IDBCursor, IDBCursorWithValue} from './IDBCursor.js';\nimport * as util from './util.js';\nimport * as Key from './Key.js';\nimport {setSQLForKeyRange, IDBKeyRange, convertValueToKeyRange} from './IDBKeyRange.js';\nimport IDBTransaction from './IDBTransaction.js';\nimport * as Sca from './Sca.js';\nimport CFG from './CFG.js';\nimport IDBObjectStore from './IDBObjectStore.js';\n\nconst readonlyProperties = ['objectStore', 'keyPath', 'multiEntry', 'unique'];\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {{\n * columnName: string,\n * keyPath: import('./Key.js').KeyPath,\n * optionalParams: {\n * unique: boolean,\n * multiEntry: boolean\n * }\n * deleted?: boolean,\n * __deleted?: boolean,\n * cursors?: import('./IDBCursor.js').IDBCursorWithValueFull[],\n * }} IDBIndexProperties\n */\n\n/**\n * IDB Index.\n * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex\n * @class\n */\nfunction IDBIndex () {\n throw new TypeError('Illegal constructor');\n}\nconst IDBIndexAlias = IDBIndex;\n\n/**\n * @typedef {IDBIndex & {\n * name: string,\n * keyPath: import('./Key.js').KeyPath,\n * multiEntry: boolean,\n * unique: boolean,\n * objectStore: import('./IDBObjectStore.js').IDBObjectStoreFull,\n * __pendingCreate?: boolean,\n * __deleted?: boolean,\n * __originalName: string,\n * __currentName: string,\n * __pendingName?: string,\n * __pendingDelete?: boolean,\n * __name: string,\n * __multiEntry: boolean,\n * __unique: boolean,\n * __objectStore: import('./IDBObjectStore.js').IDBObjectStoreFull,\n * __keyPath: import('./Key.js').KeyPath,\n * __recreated?: boolean\n * }} IDBIndexFull\n */\n\n/**\n *\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {IDBIndexProperties} indexProperties\n * @returns {IDBIndexFull}\n */\nIDBIndex.__createInstance = function (store, indexProperties) {\n /**\n * @class\n * @this {IDBIndexFull}\n */\n function IDBIndex () {\n const me = this;\n // @ts-expect-error It's ok\n me[Symbol.toStringTag] = 'IDBIndex';\n util.defineReadonlyProperties(me, readonlyProperties);\n me.__objectStore = store;\n me.__name = me.__originalName = indexProperties.columnName;\n me.__keyPath = Array.isArray(indexProperties.keyPath) ? indexProperties.keyPath.slice() : indexProperties.keyPath;\n const {optionalParams} = indexProperties;\n me.__multiEntry = Boolean(optionalParams && optionalParams.multiEntry);\n me.__unique = Boolean(optionalParams && optionalParams.unique);\n me.__deleted = Boolean(indexProperties.__deleted);\n me.__objectStore.__cursors = indexProperties.cursors || [];\n Object.defineProperty(me, '__currentName', {\n /**\n * @this {IDBIndexFull}\n * @returns {string}\n */\n get () {\n return '__pendingName' in me\n ? /** @type {string} */ (me.__pendingName)\n : me.name;\n }\n });\n Object.defineProperty(me, 'name', {\n enumerable: false,\n configurable: false,\n /**\n * @this {IDBIndexFull}\n * @returns {string}\n */\n get () {\n return this.__name;\n },\n /**\n * @param {string} newName\n * @this {IDBIndexFull}\n * @returns {void}\n */\n set (newName) {\n const me = this;\n newName = util.convertToDOMString(newName);\n const oldName = me.name;\n IDBTransaction.__assertVersionChange(me.objectStore.transaction);\n IDBTransaction.__assertActive(me.objectStore.transaction);\n IDBIndexAlias.__invalidStateIfDeleted(me);\n IDBObjectStore.__invalidStateIfDeleted(me);\n if (newName === oldName) {\n return;\n }\n\n if (me.objectStore.__indexes[newName] && !me.objectStore.__indexes[newName].__deleted &&\n !me.objectStore.__indexes[newName].__pendingDelete) {\n throw createDOMException('ConstraintError', 'Index \"' + newName + '\" already exists on ' + me.objectStore.__currentName);\n }\n\n me.__name = newName;\n\n const {objectStore} = me;\n delete objectStore.__indexes[oldName];\n objectStore.__indexes[newName] = me;\n objectStore.indexNames.splice(objectStore.indexNames.indexOf(oldName), 1, newName);\n\n const storeHandle = /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n objectStore.transaction\n ).__storeHandles[objectStore.name];\n const oldIndexHandle = storeHandle.__indexHandles[oldName];\n oldIndexHandle.__name = newName; // Fix old references\n storeHandle.__indexHandles[newName] = oldIndexHandle; // Ensure new reference accessible\n me.__pendingName = oldName;\n\n const colInfoToPreserveArr = [\n ['key', 'BLOB ' + (objectStore.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY')],\n ['value', 'BLOB']\n ].concat(\n // @ts-expect-error Has numeric indexes instead of iterator\n [...objectStore.indexNames]\n .filter((indexName) => indexName !== newName)\n .map((indexName) => [util.escapeIndexNameForSQL(indexName), 'BLOB'])\n );\n\n me.__renameIndex(\n objectStore, oldName, newName, colInfoToPreserveArr,\n function (tx, success) {\n IDBIndexAlias.__updateIndexList(store, tx, function (store) {\n delete storeHandle.__pendingName;\n success(store);\n });\n }\n );\n }\n });\n }\n IDBIndex.prototype = IDBIndexAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBIndex();\n};\n\n/**\n *\n * @param {IDBIndexFull} index\n * @param {string} [msg]\n * @throws {DOMException}\n * @returns {void}\n */\nIDBIndex.__invalidStateIfDeleted = function (index, msg) {\n if (index.__deleted || index.__pendingDelete || (\n index.__pendingCreate && index.objectStore.transaction && index.objectStore.transaction.__errored\n )) {\n throw createDOMException('InvalidStateError', msg || 'This index has been deleted');\n }\n};\n\n/**\n * Clones an IDBIndex instance for a different IDBObjectStore instance.\n * @param {IDBIndexFull} index\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @returns {IDBIndexFull}\n */\nIDBIndex.__clone = function (index, store) {\n const idx = IDBIndex.__createInstance(store, {\n columnName: index.name,\n keyPath: index.keyPath,\n optionalParams: {\n multiEntry: index.multiEntry,\n unique: index.unique\n }\n });\n /** @type {const} */ ([\n '__pendingCreate', '__pendingDelete', '__deleted',\n '__originalName', '__recreated'\n ]).forEach((p) => {\n // @ts-expect-error Why is this type \"never\"?\n idx[p] = index[p];\n });\n return idx;\n};\n\n/**\n * Creates a new index on an object store.\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {IDBIndexFull} index\n * @returns {void}\n */\nIDBIndex.__createIndex = function (store, index) {\n const indexName = index.name;\n const storeName = store.__currentName;\n const idx = store.__indexes[indexName];\n\n index.__pendingCreate = true;\n\n // Add the index to the IDBObjectStore\n store.indexNames.push(indexName);\n store.__indexes[indexName] = index; // We add to indexes as needs to be available, e.g., if there is a subsequent deleteIndex call\n\n let indexHandle = store.__indexHandles[indexName];\n if (!indexHandle ||\n index.__pendingDelete ||\n index.__deleted ||\n indexHandle.__pendingDelete ||\n indexHandle.__deleted\n ) {\n indexHandle = store.__indexHandles[indexName] = IDBIndex.__clone(index, store);\n }\n\n // Create the index in WebSQL\n const {transaction} = store;\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n transaction\n ).__addNonRequestToTransactionQueue(function createIndex (tx, args, success, failure) {\n const columnExists = idx && (idx.__deleted || idx.__recreated); // This check must occur here rather than earlier as properties may not have been set yet otherwise\n\n /** @type {{[key: string]: boolean}} */\n let indexValues = {};\n\n /**\n * @param {SQLTransaction} tx\n * @param {SQLError} err\n * @returns {void}\n */\n function error (tx, err) {\n failure(createDOMException('UnknownError', 'Could not create index \"' + indexName + '\"' + err.code + '::' + err.message, err));\n }\n\n /**\n * @param {SQLTransaction} tx\n * @returns {void}\n */\n function applyIndex (tx) {\n // Update the object store's index list\n IDBIndex.__updateIndexList(store, tx, function () {\n // Add index entries for all existing records\n tx.executeSql('SELECT \"key\", \"value\" FROM ' + util.escapeStoreNameForSQL(storeName), [], function (tx, data) {\n if (CFG.DEBUG) { console.log('Adding existing ' + storeName + ' records to the ' + indexName + ' index'); }\n addIndexEntry(0);\n\n /**\n * @param {Integer} i\n * @returns {void}\n */\n function addIndexEntry (i) {\n if (i < data.rows.length) {\n try {\n const value = Sca.decode(util.unescapeSQLiteResponse(data.rows.item(i).value));\n const indexKey = Key.extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Todo: Do we need this stricter error checking?\n if (\n ('invalid' in indexKey && indexKey.invalid) ||\n ('failure' in indexKey && indexKey.failure)\n ) { // Todo: Do we need invalid checks and should we instead treat these as being duplicates?\n throw new Error('Go to catch; ignore bad indexKey');\n }\n const indexKeyStr = /** @type {string} */ (\n Key.encode(indexKey.value, index.multiEntry)\n );\n if (index.unique) {\n if (indexValues[indexKeyStr]) {\n indexValues = {};\n failure(createDOMException(\n 'ConstraintError',\n 'Duplicate values already exist within the store'\n ));\n return;\n }\n indexValues[indexKeyStr] = true;\n }\n\n tx.executeSql(\n 'UPDATE ' + util.escapeStoreNameForSQL(storeName) + ' SET ' +\n util.escapeIndexNameForSQL(indexName) + ' = ? WHERE \"key\" = ?',\n [util.escapeSQLiteStatement(indexKeyStr), data.rows.item(i).key],\n function () {\n addIndexEntry(i + 1);\n },\n /** @type {SQLStatementErrorCallback} */ (error)\n );\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n // Not a valid value to insert into index, so just continue\n addIndexEntry(i + 1);\n }\n } else {\n delete index.__pendingCreate;\n delete indexHandle.__pendingCreate;\n if (index.__deleted) {\n delete index.__deleted;\n delete indexHandle.__deleted;\n index.__recreated = true;\n indexHandle.__recreated = true;\n }\n indexValues = {};\n success(store);\n }\n }\n }, /** @type {SQLStatementErrorCallback} */ (error));\n }, /** @type {SQLStatementErrorCallback} */ (error));\n }\n\n const escapedStoreNameSQL = util.escapeStoreNameForSQL(storeName);\n const escapedIndexNameSQL = util.escapeIndexNameForSQL(index.name);\n\n /**\n * @param {SQLTransaction} tx\n * @returns {void}\n */\n function addIndexSQL (tx) {\n if (!CFG.useSQLiteIndexes) {\n applyIndex(tx);\n return;\n }\n tx.executeSql(\n 'CREATE INDEX IF NOT EXISTS \"' +\n // The escaped index name must be unique among indexes in the whole database;\n // so we prefix with store name; as prefixed, will also not conflict with\n // index on `key`\n // Avoid quotes and separate with special escape sequence\n escapedStoreNameSQL.slice(1, -1) + '^5' + escapedIndexNameSQL.slice(1, -1) +\n '\" ON ' + escapedStoreNameSQL + '(' + escapedIndexNameSQL + ')',\n [],\n applyIndex,\n /** @type {SQLStatementErrorCallback} */ (error)\n );\n }\n\n if (columnExists) {\n // For a previously existing index, just update the index entries in the existing column;\n // no need to add SQLite index to it either as should already exist\n applyIndex(tx);\n } else {\n // For a new index, add a new column to the object store, then apply the index\n const sql = ['ALTER TABLE', escapedStoreNameSQL, 'ADD', escapedIndexNameSQL, 'BLOB'].join(' ');\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(\n sql, [], addIndexSQL, /** @type {SQLStatementErrorCallback} */ (error)\n );\n }\n });\n};\n\n/**\n * Deletes an index from an object store.\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {IDBIndexFull} index\n * @returns {void}\n */\nIDBIndex.__deleteIndex = function (store, index) {\n // Remove the index from the IDBObjectStore\n index.__pendingDelete = true;\n const indexHandle = store.__indexHandles[index.name];\n if (indexHandle) {\n indexHandle.__pendingDelete = true;\n }\n\n store.indexNames.splice(store.indexNames.indexOf(index.name), 1);\n\n // Remove the index in WebSQL\n const {transaction} = store;\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n transaction\n ).__addNonRequestToTransactionQueue(function deleteIndex (tx, args, success, failure) {\n /**\n * @param {SQLTransaction} tx\n * @param {SQLError} err\n * @returns {void}\n */\n function error (tx, err) {\n failure(createDOMException('UnknownError', 'Could not delete index \"' + index.name + '\"', err));\n }\n\n /**\n * @returns {void}\n */\n function finishDeleteIndex () {\n // Update the object store's index list\n IDBIndex.__updateIndexList(store, tx, function (store) {\n delete index.__pendingDelete;\n delete index.__recreated;\n index.__deleted = true;\n if (indexHandle) {\n indexHandle.__deleted = true;\n delete indexHandle.__pendingDelete;\n }\n success(store);\n }, /** @type {SQLStatementErrorCallback} */ (error));\n }\n\n if (!CFG.useSQLiteIndexes) {\n finishDeleteIndex();\n return;\n }\n tx.executeSql(\n 'DROP INDEX IF EXISTS ' +\n util.sqlQuote(\n util.escapeStoreNameForSQL(store.name).slice(1, -1) + '^5' +\n util.escapeIndexNameForSQL(index.name).slice(1, -1)\n ),\n [],\n finishDeleteIndex,\n /** @type {SQLStatementErrorCallback} */ (error)\n );\n });\n};\n\n/**\n * @typedef {{[key: string]: IDBIndexProperties}} IndexList\n */\n\n/**\n * Updates index list for the given object store.\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {SQLTransaction} tx\n * @param {(store: IDBObjectStore) => void} success\n * @param {(\n * tx: SQLTransaction,\n * err: SQLError\n * ) => boolean} [failure]\n * @returns {void}\n */\nIDBIndex.__updateIndexList = function (store, tx, success, failure) {\n /** @type {IndexList} **/\n const indexList = {};\n // eslint-disable-next-line sonarjs/prefer-for-of -- Implement iterability?\n for (let i = 0; i < store.indexNames.length; i++) {\n const idx = store.__indexes[store.indexNames[i]];\n indexList[idx.name] = {\n columnName: idx.name,\n keyPath: idx.keyPath,\n optionalParams: {\n unique: idx.unique,\n multiEntry: idx.multiEntry\n },\n deleted: Boolean(idx.__deleted)\n };\n }\n\n if (CFG.DEBUG) { console.log('Updating the index list for ' + store.__currentName, indexList); }\n tx.executeSql('UPDATE __sys__ SET \"indexList\" = ? WHERE \"name\" = ?', [JSON.stringify(indexList), util.escapeSQLiteStatement(store.__currentName)], function () {\n success(store);\n }, /** @type {SQLStatementErrorCallback} */ (failure));\n};\n\n/**\n * @typedef {any|IDBKeyRange} Query\n */\n\n/**\n * Retrieves index data for the given key.\n * @param {Query} range\n * @param {\"value\"|\"key\"|\"count\"} opType\n * @param {boolean} nullDisallowed\n * @param {number} [count]\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.__fetchIndexData = function (range, opType, nullDisallowed, count) {\n const me = this;\n if (count !== undefined) {\n count = util.enforceRange(count, 'unsigned long');\n }\n\n IDBIndex.__invalidStateIfDeleted(me);\n IDBObjectStore.__invalidStateIfDeleted(me.objectStore);\n if (me.objectStore.__deleted) {\n throw createDOMException('InvalidStateError', \"This index's object store has been deleted\");\n }\n IDBTransaction.__assertActive(me.objectStore.transaction);\n\n if (nullDisallowed && util.isNullish(range)) {\n throw createDOMException('DataError', 'No key or range was specified');\n }\n\n const fetchArgs = buildFetchIndexDataSQL(nullDisallowed, me, range, opType, false);\n return /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.objectStore.transaction\n ).__addToTransactionQueue(function (...args) {\n executeFetchIndexData(\n count,\n ...fetchArgs,\n // @ts-expect-error It's ok\n ...args\n );\n }, undefined, me);\n};\n\n/**\n * Opens a cursor over the given key range.\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.openCursor = function (/* query, direction */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, direction] = arguments;\n const cursor = IDBCursorWithValue.__createInstance(query, direction, me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'value');\n me.__objectStore.__cursors.push(cursor);\n return cursor.__request;\n};\n\n/**\n * Opens a cursor over the given key range. The cursor only includes key values, not data.\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.openKeyCursor = function (/* query, direction */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, direction] = arguments;\n const cursor = IDBCursor.__createInstance(query, direction, me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'key');\n me.__objectStore.__cursors.push(cursor);\n return cursor.__request;\n};\n\n/**\n *\n * @param {Query} query\n * @throws {TypeError}\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.get = function (query) {\n if (!arguments.length) { // Per https://heycam.github.io/webidl/\n throw new TypeError('A parameter was missing for `IDBIndex.get`.');\n }\n return this.__fetchIndexData(query, 'value', true);\n};\n\n/**\n *\n * @param {Query} query\n * @throws {TypeError}\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.getKey = function (query) {\n if (!arguments.length) { // Per https://heycam.github.io/webidl/\n throw new TypeError('A parameter was missing for `IDBIndex.getKey`.');\n }\n return this.__fetchIndexData(query, 'key', true);\n};\n\n/**\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.getAll = function (/* query, count */) {\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, count] = arguments;\n return this.__fetchIndexData(query, 'value', false, count);\n};\n\n/**\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.getAllKeys = function (/* query, count */) {\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, count] = arguments;\n return this.__fetchIndexData(query, 'key', false, count);\n};\n\n/**\n * @this {IDBIndexFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBIndex.prototype.count = function (/* query */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const query = arguments[0];\n // With the exception of needing to check whether the index has been\n // deleted, we could, for greater spec parity (if not accuracy),\n // just call:\n // `return me.__objectStore.count(query);`\n\n if (util.instanceOf(query, IDBKeyRange)) { // Todo: Do we need this block?\n // We don't need to add to cursors array since has the count parameter which won't cache\n return IDBCursorWithValue.__createInstance(query, 'next', me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'value', true).__request;\n }\n return me.__fetchIndexData(query, 'count', false);\n};\n\n/**\n *\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {string} oldName\n * @param {string} newName\n * @param {string[][]} colInfoToPreserveArr\n * @param {null|((\n * tx: SQLTransaction,\n * success: ((store: IDBObjectStore) => void)\n * ) => void)} cb\n * @this {IDBIndexFull}\n * @returns {void}\n */\nIDBIndex.prototype.__renameIndex = function (store, oldName, newName, colInfoToPreserveArr = [], cb = null) {\n const newNameType = 'BLOB';\n const storeName = store.__currentName;\n const escapedStoreNameSQL = util.escapeStoreNameForSQL(storeName);\n const escapedNewIndexNameSQL = util.escapeIndexNameForSQL(newName);\n const escapedTmpStoreNameSQL = util.sqlQuote('tmp_' + util.escapeStoreNameForSQL(storeName).slice(1, -1));\n const colNamesToPreserve = colInfoToPreserveArr.map((colInfo) => colInfo[0]);\n const colInfoToPreserve = colInfoToPreserveArr.map((colInfo) => colInfo.join(' '));\n const listColInfoToPreserve = (colInfoToPreserve.length ? (colInfoToPreserve.join(', ') + ', ') : '');\n const listColsToPreserve = (colNamesToPreserve.length ? (colNamesToPreserve.join(', ') + ', ') : '');\n\n // We could adapt the approach at http://stackoverflow.com/a/8430746/271577\n // to make the approach reusable without passing column names, but it is a bit fragile\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n store.transaction\n ).__addNonRequestToTransactionQueue(function renameIndex (tx, args, success, error) {\n /**\n * @param {SQLTransaction} tx\n * @param {SQLError} err\n * @returns {void}\n */\n function sqlError (tx, err) {\n error(err);\n }\n /**\n * @returns {void}\n */\n function finish () {\n if (cb) {\n cb(tx, success);\n return;\n }\n success();\n }\n // See https://www.sqlite.org/lang_altertable.html#otheralter\n // We don't query for indexes as we already have the info\n // This approach has the advantage of auto-deleting indexes via the DROP TABLE\n const sql = 'CREATE TABLE ' + escapedTmpStoreNameSQL +\n '(' + listColInfoToPreserve + escapedNewIndexNameSQL + ' ' + newNameType + ')';\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function () {\n const sql = 'INSERT INTO ' + escapedTmpStoreNameSQL + '(' +\n listColsToPreserve + escapedNewIndexNameSQL +\n ') SELECT ' + listColsToPreserve + util.escapeIndexNameForSQL(oldName) + ' FROM ' + escapedStoreNameSQL;\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function () {\n const sql = 'DROP TABLE ' + escapedStoreNameSQL;\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function () {\n const sql = 'ALTER TABLE ' + escapedTmpStoreNameSQL + ' RENAME TO ' + escapedStoreNameSQL;\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function (tx) {\n if (!CFG.useSQLiteIndexes) {\n finish();\n return;\n }\n const indexCreations = colNamesToPreserve\n .slice(2) // Doing `key` separately and no need for index on `value`\n .map((escapedIndexNameSQL) => new SyncPromise(function (resolve, reject) {\n const escapedIndexToRecreate = util.sqlQuote(\n escapedStoreNameSQL.slice(1, -1) + '^5' + escapedIndexNameSQL.slice(1, -1)\n );\n // const sql = 'DROP INDEX IF EXISTS ' + escapedIndexToRecreate;\n // if (CFG.DEBUG) { console.log(sql); }\n // tx.executeSql(sql, [], function () {\n const sql = 'CREATE INDEX ' +\n escapedIndexToRecreate + ' ON ' + escapedStoreNameSQL + '(' + escapedIndexNameSQL + ')';\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(\n sql,\n [],\n resolve,\n /** @type {SQLStatementErrorCallback} */\n (function (tx, err) {\n reject(err);\n })\n );\n // }, function (tx, err) {\n // reject(err);\n // });\n }));\n indexCreations.push(\n new SyncPromise(function (resolve, reject) {\n const escapedIndexToRecreate = util.sqlQuote('sk_' + escapedStoreNameSQL.slice(1, -1));\n // Chrome erring here if not dropped first; Node does not\n const sql = 'DROP INDEX IF EXISTS ' + escapedIndexToRecreate;\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(\n sql, [], function () {\n const sql = 'CREATE INDEX ' + escapedIndexToRecreate +\n ' ON ' + escapedStoreNameSQL + '(\"key\")';\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(\n sql, [], resolve,\n /** @type {SQLStatementErrorCallback} */\n (function (tx, err) {\n reject(err);\n })\n );\n },\n /** @type {SQLStatementErrorCallback} */\n (function (tx, err) {\n reject(err);\n })\n );\n })\n );\n SyncPromise.all(indexCreations).then(\n finish,\n /** @type {(reason: any) => PromiseLike} */\n (error)\n ).catch((err) => {\n console.log('Index rename error');\n throw err;\n });\n }, /** @type {SQLStatementErrorCallback} */ (sqlError));\n }, /** @type {SQLStatementErrorCallback} */ (sqlError));\n }, /** @type {SQLStatementErrorCallback} */ (sqlError));\n }, /** @type {SQLStatementErrorCallback} */ (sqlError));\n });\n};\n\n/**\n * @typedef {any} AnyValue\n */\n\nObject.defineProperty(IDBIndex, Symbol.hasInstance, {\n /**\n * @param {AnyValue} obj\n * @returns {boolean}\n */\n value: (obj) => util.isObj(obj) &&\n 'openCursor' in obj &&\n typeof obj.openCursor === 'function' &&\n 'multiEntry' in obj &&\n typeof obj.multiEntry === 'boolean'\n});\n\nutil.defineReadonlyOuterInterface(IDBIndex.prototype, readonlyProperties);\nutil.defineOuterInterface(IDBIndex.prototype, ['name']);\n\nIDBIndex.prototype[Symbol.toStringTag] = 'IDBIndexPrototype';\n\nObject.defineProperty(IDBIndex, 'prototype', {\n writable: false\n});\n\n/**\n * @param {number|null} count\n * @param {boolean} unboundedDisallowed\n * @param {IDBIndexFull} index\n * @param {boolean} hasKey\n * @param {import('./Key.js').Value|import('./Key.js').Key} range\n * @param {\"value\"|\"key\"|\"count\"} opType\n * @param {boolean} multiChecks\n * @param {string[]} sql\n * @param {string[]} sqlValues\n * @param {SQLTransaction} tx\n * @param {null|undefined} args\n * @param {(result: number|undefined|[]|AnyValue|AnyValue[]) => void} success\n * @param {(tx: SQLTransaction, err: SQLError) => void} error\n * @returns {void}\n */\nfunction executeFetchIndexData (\n count, unboundedDisallowed, index, hasKey, range, opType,\n multiChecks, sql, sqlValues, tx, args, success, error\n) {\n if (unboundedDisallowed) {\n count = 1;\n }\n if (count) {\n sql.push('LIMIT', String(count));\n }\n const isCount = opType === 'count';\n if (CFG.DEBUG) { console.log('Trying to fetch data for Index', sql.join(' '), sqlValues); }\n tx.executeSql(sql.join(' '), sqlValues, function (tx, data) {\n const records = [];\n let recordCount = 0;\n const decode = isCount\n ? () => { /* */ }\n : (opType === 'key'\n // eslint-disable-next-line @stylistic/operator-linebreak -- JSDoc\n ?\n /**\n * @param {{\n * key: string\n * }} record\n * @returns {import('./Key.js').ValueType|undefined}\n */\n (record) => {\n // Key.convertValueToKey(record.key); // Already validated before storage\n return Key.decode(util.unescapeSQLiteResponse(record.key));\n }\n // eslint-disable-next-line @stylistic/operator-linebreak -- JSDoc\n :\n /**\n * @param {{\n * value: string\n * }} record\n * @returns {AnyValue}\n */\n (record) => { // when opType is value\n return Sca.decode(util.unescapeSQLiteResponse(record.value));\n });\n if (index.multiEntry) {\n const escapedIndexNameForKeyCol = util.escapeIndexNameForSQLKeyColumn(index.name);\n const encodedKey = Key.encode(range, index.multiEntry);\n for (let i = 0; i < data.rows.length; i++) {\n const row = data.rows.item(i);\n const rowKey = /** @type {import('./Key.js').ValueTypeArray} */ (\n Key.decode(row[escapedIndexNameForKeyCol])\n );\n let record;\n if (hasKey && (\n (multiChecks && range.some(\n /**\n * @param {string} check\n * @returns {boolean}\n */\n (check) => rowKey.includes(check)\n )) || // More precise than our SQL\n Key.isMultiEntryMatch(\n /** @type {string} */\n (encodedKey),\n row[escapedIndexNameForKeyCol]\n )\n )) {\n recordCount++;\n record = row;\n } else if (!hasKey && !multiChecks) {\n if (rowKey !== undefined) {\n recordCount += (Array.isArray(rowKey) ? rowKey.length : 1);\n record = row;\n }\n }\n if (record) {\n records.push(decode(record));\n if (unboundedDisallowed) {\n break;\n }\n }\n }\n } else {\n for (let i = 0; i < data.rows.length; i++) {\n const record = data.rows.item(i);\n if (record) {\n records.push(decode(record));\n }\n }\n recordCount = records.length;\n }\n if (isCount) {\n success(recordCount);\n } else if (recordCount === 0) {\n success(unboundedDisallowed ? undefined : []);\n } else {\n success(unboundedDisallowed ? records[0] : records);\n }\n }, /** @type {SQLStatementErrorCallback} */ (error));\n}\n\n/**\n * @param {boolean} nullDisallowed\n * @param {IDBIndexFull} index\n * @param {import('./Key.js').Value|import('./Key.js').Key} range\n * @param {\"value\"|\"key\"|\"count\"} opType\n * @param {boolean} multiChecks\n * @returns {[\n * nullDisallowed: boolean,\n * index: IDBIndexFull,\n * hasRange: boolean,\n * range: import('./Key.js').Value|import('./Key.js').Key,\n * opType: \"value\"|\"key\"|\"count\",\n * multiChecks: boolean,\n * sql: string[],\n * sqlValues: string[]\n * ]}\n */\nfunction buildFetchIndexDataSQL (\n nullDisallowed, index, range, opType, multiChecks\n) {\n const hasRange = nullDisallowed || !util.isNullish(range);\n const col = opType === 'count' ? 'key' : opType; // It doesn't matter which column we use for 'count' as long as it is valid\n const sql = [\n 'SELECT', util.sqlQuote(col) + (\n index.multiEntry ? ', ' + util.escapeIndexNameForSQL(index.name) : ''\n ),\n 'FROM', util.escapeStoreNameForSQL(index.objectStore.__currentName),\n 'WHERE', util.escapeIndexNameForSQL(index.name), 'NOT NULL'\n ];\n\n /** @type {string[]} */\n const sqlValues = [];\n if (hasRange) {\n if (multiChecks) {\n sql.push('AND (');\n /** @type {import('./Key.js').KeyPathArray} */ (\n range\n ).forEach((innerKey, i) => {\n if (i > 0) { sql.push('OR'); }\n sql.push(util.escapeIndexNameForSQL(index.name), \"LIKE ? ESCAPE '^' \");\n sqlValues.push('%' + util.sqlLIKEEscape(\n /** @type {string} */ (Key.encode(innerKey, index.multiEntry))\n ) + '%');\n });\n sql.push(')');\n } else if (index.multiEntry) {\n sql.push('AND', util.escapeIndexNameForSQL(index.name), \"LIKE ? ESCAPE '^'\");\n sqlValues.push('%' + util.sqlLIKEEscape(\n /** @type {string} */ (Key.encode(range, index.multiEntry))\n ) + '%');\n } else {\n const convertedRange = convertValueToKeyRange(range, nullDisallowed);\n setSQLForKeyRange(convertedRange, util.escapeIndexNameForSQL(index.name), sql, sqlValues, true, false);\n }\n }\n return [nullDisallowed, index, hasRange, range, opType, multiChecks, sql, sqlValues];\n}\n\nexport {buildFetchIndexDataSQL, executeFetchIndexData, IDBIndex, IDBIndex as default};\n","import SyncPromise from 'sync-promise-expanded';\nimport {createDOMException} from './DOMException.js';\nimport {IDBCursor, IDBCursorWithValue} from './IDBCursor.js';\nimport {setSQLForKeyRange, convertValueToKeyRange} from './IDBKeyRange.js';\nimport DOMStringList from './DOMStringList.js';\nimport * as util from './util.js';\nimport * as Key from './Key.js';\nimport {executeFetchIndexData, buildFetchIndexDataSQL, IDBIndex} from './IDBIndex.js';\nimport IDBTransaction from './IDBTransaction.js';\nimport * as Sca from './Sca.js';\nimport CFG from './CFG.js';\n\nconst readonlyProperties = ['keyPath', 'indexNames', 'transaction', 'autoIncrement'];\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * IndexedDB Object Store.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBObjectStore\n * @class\n */\nfunction IDBObjectStore () {\n throw new TypeError('Illegal constructor');\n}\nconst IDBObjectStoreAlias = IDBObjectStore;\n\n/**\n * @typedef {IDBObjectStore & {\n * name: string,\n * keyPath: import('./Key.js').KeyPath,\n * transaction?: import('./IDBTransaction.js').IDBTransactionFull,\n * indexNames: import('./DOMStringList.js').DOMStringListFull,\n * autoIncrement: boolean,\n * __autoIncrement: boolean,\n * __indexes: {[key: string]: import('./IDBIndex.js').IDBIndexFull},\n * __indexHandles: {[key: string]: import('./IDBIndex.js').IDBIndexFull},\n * __indexNames: import('./DOMStringList.js').DOMStringListFull,\n * __oldIndexNames: import('./DOMStringList.js').DOMStringListFull,\n * __transaction?: import('./IDBTransaction.js').IDBTransactionFull,\n * __name: string,\n * __keyPath: import('./Key.js').KeyPath,\n * __originalName: string,\n * __currentName: string,\n * __pendingName?: string,\n * __pendingDelete?: boolean,\n * __pendingCreate?: boolean,\n * __deleted?: boolean,\n * __cursors: (\n * import('./IDBCursor.js').IDBCursorFull|\n * import('./IDBCursor.js').IDBCursorWithValueFull\n * )[],\n * __idbdb: import('./IDBDatabase.js').IDBDatabaseFull,\n * }} IDBObjectStoreFull\n */\n\n/**\n *\n * @param {import('./IDBDatabase.js').IDBObjectStoreProperties} storeProperties\n * @param {import('./IDBTransaction.js').IDBTransactionFull} [transaction]\n * @returns {IDBObjectStoreFull}\n */\nIDBObjectStore.__createInstance = function (storeProperties, transaction) {\n /**\n * @class\n * @this {IDBObjectStoreFull}\n */\n function IDBObjectStore () {\n const me = this;\n // @ts-expect-error It's ok\n me[Symbol.toStringTag] = 'IDBObjectStore';\n util.defineReadonlyProperties(this, readonlyProperties);\n me.__name = me.__originalName = storeProperties.name;\n me.__keyPath = Array.isArray(storeProperties.keyPath) ? storeProperties.keyPath.slice() : storeProperties.keyPath;\n me.__transaction = transaction;\n me.__idbdb = storeProperties.idbdb;\n me.__cursors = storeProperties.cursors || [];\n\n // autoInc is numeric (0/1) on WinPhone\n me.__autoIncrement = Boolean(storeProperties.autoInc);\n\n me.__indexes = {};\n me.__indexHandles = {};\n me.__indexNames = DOMStringList.__createInstance();\n const {indexList} = storeProperties;\n for (const indexName in indexList) {\n if (Object.hasOwn(indexList, indexName)) {\n const index = IDBIndex.__createInstance(me, indexList[indexName]);\n me.__indexes[index.name] = index;\n if (!index.__deleted) {\n me.indexNames.push(index.name);\n }\n }\n }\n me.__oldIndexNames = me.indexNames.clone();\n Object.defineProperty(this, '__currentName', {\n get () {\n return '__pendingName' in this ? this.__pendingName : this.name;\n }\n });\n Object.defineProperty(this, 'name', {\n enumerable: false,\n configurable: false,\n /**\n * @this {IDBObjectStoreFull}\n * @returns {string}\n */\n get () {\n return this.__name;\n },\n /**\n * @param {string} name\n * @this {IDBObjectStoreFull}\n * @returns {void}\n */\n set (name) {\n const me = this;\n name = util.convertToDOMString(name);\n const oldName = me.name;\n IDBObjectStoreAlias.__invalidStateIfDeleted(me);\n IDBTransaction.__assertVersionChange(me.transaction);\n IDBTransaction.__assertActive(me.transaction);\n if (oldName === name) {\n return;\n }\n if (me.__idbdb.__objectStores[name] && !me.__idbdb.__objectStores[name].__pendingDelete) {\n throw createDOMException('ConstraintError', 'Object store \"' + name + '\" already exists in ' + me.__idbdb.name);\n }\n\n me.__name = name;\n\n const oldStore = me.__idbdb.__objectStores[oldName];\n oldStore.__name = name; // Fix old references\n me.__idbdb.__objectStores[name] = oldStore; // Ensure new reference accessible\n delete me.__idbdb.__objectStores[oldName]; // Ensure won't be found\n\n me.__idbdb.objectStoreNames.splice(me.__idbdb.objectStoreNames.indexOf(oldName), 1, name);\n\n const oldHandle = /** @type {IDBObjectStoreFull} */ (\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__storeHandles[oldName]\n );\n oldHandle.__name = name; // Fix old references\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__storeHandles[name] = oldHandle; // Ensure new reference accessible\n\n me.__pendingName = oldName;\n\n const sql = 'UPDATE __sys__ SET \"name\" = ? WHERE \"name\" = ?';\n const sqlValues = [util.escapeSQLiteStatement(name), util.escapeSQLiteStatement(oldName)];\n if (CFG.DEBUG) { console.log(sql, sqlValues); }\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__addNonRequestToTransactionQueue(function objectStoreClear (tx, args, success, error) {\n tx.executeSql(sql, sqlValues, function (tx) {\n // This SQL preserves indexes per https://www.sqlite.org/lang_altertable.html\n const sql = 'ALTER TABLE ' + util.escapeStoreNameForSQL(oldName) + ' RENAME TO ' + util.escapeStoreNameForSQL(name);\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function () {\n delete me.__pendingName;\n success();\n });\n }, function (tx, err) {\n error(err);\n return false;\n });\n });\n }\n });\n }\n IDBObjectStore.prototype = IDBObjectStoreAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBObjectStore();\n};\n\n/**\n * Clones an IDBObjectStore instance for a different IDBTransaction instance.\n * @param {IDBObjectStoreFull} store\n * @param {import('./IDBTransaction.js').IDBTransactionFull} transaction\n * @returns {IDBObjectStoreFull}\n */\nIDBObjectStore.__clone = function (store, transaction) {\n const newStore = IDBObjectStore.__createInstance({\n name: store.__currentName,\n keyPath: Array.isArray(store.keyPath) ? store.keyPath.slice() : store.keyPath,\n autoInc: store.autoIncrement,\n indexList: {},\n idbdb: store.__idbdb,\n cursors: store.__cursors\n }, transaction);\n\n /** @type {const} */ ([\n '__indexes', '__indexNames', '__oldIndexNames',\n '__deleted', '__pendingDelete', '__pendingCreate', '__originalName'\n ]).forEach((p) => {\n // @ts-expect-error It's ok\n newStore[p] = store[p];\n });\n return newStore;\n};\n\n/**\n *\n * @param {IDBObjectStoreFull|import('./IDBIndex.js').IDBIndexFull} store\n * @param {string} [msg]\n * @throws {DOMException}\n * @returns {void}\n */\nIDBObjectStore.__invalidStateIfDeleted = function (store, msg) {\n if (\n store.__deleted || store.__pendingDelete || (store.__pendingCreate && (\n 'transaction' in store && store.transaction && store.transaction.__errored\n ))\n ) {\n throw createDOMException('InvalidStateError', msg || 'This store has been deleted');\n }\n};\n\n/**\n * Creates a new object store in the database.\n * @param {import('./IDBDatabase.js').IDBDatabaseFull} db\n * @param {IDBObjectStoreFull} store\n * @returns {IDBObjectStore}\n */\nIDBObjectStore.__createObjectStore = function (db, store) {\n // Add the object store to the IDBDatabase\n const storeName = store.__currentName;\n store.__pendingCreate = true;\n db.__objectStores[storeName] = store;\n db.objectStoreNames.push(storeName);\n\n // Add the object store to WebSQL\n const transaction =/** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n db.__versionTransaction\n );\n\n const storeHandles = transaction.__storeHandles;\n if (!storeHandles[storeName] ||\n // These latter conditions are to allow store\n // recreation to create new clone object\n storeHandles[storeName].__pendingDelete ||\n storeHandles[storeName].__deleted) {\n storeHandles[storeName] = IDBObjectStore.__clone(store, transaction);\n }\n\n transaction.__addNonRequestToTransactionQueue(function createObjectStore (tx, args, success, failure) {\n /**\n * @param {SQLTransaction} tx\n * @param {SQLError} [err]\n * @returns {boolean}\n */\n function error (tx, err) {\n if (CFG.DEBUG) { console.log(err); }\n failure(createDOMException('UnknownError', 'Could not create object store \"' + storeName + '\"', err));\n return false;\n }\n\n const escapedStoreNameSQL = util.escapeStoreNameForSQL(storeName);\n // key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE\n const sql = ['CREATE TABLE', escapedStoreNameSQL, '(key BLOB', store.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY', ', value BLOB)'].join(' ');\n if (CFG.DEBUG) { console.log(sql); }\n tx.executeSql(sql, [], function (tx) {\n /**\n * @returns {void}\n */\n function insertStoreInfo () {\n const encodedKeyPath = JSON.stringify(store.keyPath);\n tx.executeSql('INSERT INTO __sys__ VALUES (?,?,?,?,?)', [\n util.escapeSQLiteStatement(storeName),\n encodedKeyPath,\n // For why converting here, see comment and following\n // discussion at:\n // https://github.com/axemclion/IndexedDBShim/issues/313#issuecomment-590086778\n Number(store.autoIncrement),\n '{}',\n 1\n ], function () {\n delete store.__pendingCreate;\n delete store.__deleted;\n success(store);\n }, error);\n }\n if (!CFG.useSQLiteIndexes) {\n insertStoreInfo();\n return;\n }\n tx.executeSql('CREATE INDEX IF NOT EXISTS ' + (\n util.sqlQuote('sk_' + escapedStoreNameSQL.slice(1, -1))\n ) + ' ON ' + escapedStoreNameSQL + '(\"key\")', [], insertStoreInfo, error);\n }, error);\n });\n return storeHandles[storeName];\n};\n\n/**\n * Deletes an object store from the database.\n * @param {import('./IDBDatabase.js').IDBDatabaseFull} db\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @returns {void}\n */\nIDBObjectStore.__deleteObjectStore = function (db, store) {\n // Remove the object store from the IDBDatabase\n store.__pendingDelete = true;\n // We don't delete the other index holders in case need reversion\n store.__indexNames = DOMStringList.__createInstance();\n\n db.objectStoreNames.splice(db.objectStoreNames.indexOf(store.__currentName), 1);\n\n const storeHandle = db.__versionTransaction.__storeHandles[store.__currentName];\n if (storeHandle) {\n storeHandle.__indexNames = DOMStringList.__createInstance();\n storeHandle.__pendingDelete = true;\n }\n\n // Remove the object store from WebSQL\n const transaction = /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n db.__versionTransaction\n );\n transaction.__addNonRequestToTransactionQueue(function deleteObjectStore (tx, args, success, failure) {\n /**\n * @param {SQLTransaction} tx\n * @param {SQLError} [err]\n * @returns {boolean}\n */\n function error (tx, err) {\n if (CFG.DEBUG) { console.log(err); }\n failure(createDOMException('UnknownError', 'Could not delete ObjectStore', err));\n return false;\n }\n\n tx.executeSql('SELECT \"name\" FROM __sys__ WHERE \"name\" = ?', [util.escapeSQLiteStatement(store.__currentName)], function (tx, data) {\n if (data.rows.length > 0) {\n tx.executeSql('DROP TABLE ' + util.escapeStoreNameForSQL(store.__currentName), [], function () {\n tx.executeSql('DELETE FROM __sys__ WHERE \"name\" = ?', [util.escapeSQLiteStatement(store.__currentName)], function () {\n delete store.__pendingDelete;\n store.__deleted = true;\n if (storeHandle) {\n delete storeHandle.__pendingDelete;\n storeHandle.__deleted = true;\n }\n success();\n }, error);\n }, error);\n }\n });\n });\n};\n\n/**\n * @typedef {[import('./Key.js').Key, import('./Key.js').Value]} KeyValueArray\n */\n\n// Todo: Although we may end up needing to do cloning genuinely asynchronously (for Blobs and FileLists),\n// and we'll want to ensure the queue starts up synchronously, we nevertheless do the cloning\n// before entering the queue and its callback since the encoding we do is preceded by validation\n// which we must do synchronously anyways. If we reimplement Blobs and FileLists asynchronously,\n// we can detect these types (though validating synchronously as possible) and once entering the\n// queue callback, ensure they load before triggering success or failure (perhaps by returning and\n// a `SyncPromise` from the `Sca.clone` operation and later detecting and ensuring it is resolved\n// before continuing).\n/**\n * Determines whether the given inline or out-of-line key is valid,\n * according to the object store's schema.\n * @param {import('./Key.js').Value} value Used for inline keys\n * @param {import('./Key.js').Key} key Used for out-of-line keys\n * @param {boolean} cursorUpdate\n * @throws {DOMException}\n * @this {IDBObjectStoreFull}\n * @returns {KeyValueArray}\n */\nIDBObjectStore.prototype.__validateKeyAndValueAndCloneValue = function (value, key, cursorUpdate) {\n const me = this;\n if (me.keyPath !== null) {\n if (key !== undefined) {\n throw createDOMException('DataError', 'The object store uses in-line keys and the key parameter was provided');\n }\n // Todo Binary: Avoid blobs loading async to ensure cloning (and errors therein)\n // occurs sync; then can make cloning and this method without callbacks (except where ok\n // to be async)\n const clonedValue = Sca.clone(value);\n key = Key.extractKeyValueDecodedFromValueUsingKeyPath(clonedValue, me.keyPath); // May throw so \"rethrow\"\n if (key.invalid) {\n throw createDOMException('DataError', 'KeyPath was specified, but key was invalid.');\n }\n if (key.failure) {\n if (!cursorUpdate) {\n if (!me.autoIncrement) {\n throw createDOMException('DataError', 'Could not evaluate a key from keyPath and there is no key generator');\n }\n // Todo: Could the keyPath not be an array?\n if (!Key.checkKeyCouldBeInjectedIntoValue(clonedValue, /** @type {string} */ (me.keyPath))) {\n throw createDOMException('DataError', 'A key could not be injected into a value');\n }\n // A key will be generated\n return [undefined, clonedValue];\n }\n throw createDOMException('DataError', 'Could not evaluate a key from keyPath');\n }\n // An `IDBCursor.update` call will also throw if not equal to the cursor’s effective key\n return [key.value, clonedValue];\n }\n if (key === undefined) {\n if (!me.autoIncrement) {\n throw createDOMException('DataError', 'The object store uses out-of-line keys and has no key generator and the key parameter was not provided.');\n }\n // A key will be generated\n key = undefined;\n } else {\n Key.convertValueToKeyRethrowingAndIfInvalid(key);\n }\n const clonedValue = Sca.clone(value);\n return [key, clonedValue];\n};\n\n/**\n * From the store properties and object, extracts the value for the key in\n * the object store\n * If the table has auto increment, get the current number (unless it has\n * a keyPath leading to a valid but non-numeric or < 1 key).\n * @param {SQLTransaction} tx\n * @param {import('./Key.js').Value} value\n * @param {import('./Key.js').Key} key\n * @param {(key: import('./Key.js').Key, cn?: Integer) => void} success\n * @param {import('./Key.js').SQLFailureCallback} failCb\n * @this {IDBObjectStoreFull}\n * @returns {void}\n */\nIDBObjectStore.prototype.__deriveKey = function (tx, value, key, success, failCb) {\n const me = this;\n\n // Only run if cloning is needed\n /**\n * @param {Integer} [oldCn]\n * @returns {void}\n */\n function keyCloneThenSuccess (oldCn) { // We want to return the original key, so we don't need to accept an argument here\n Sca.encode(key, function (key) {\n key = Sca.decode(key);\n success(key, oldCn);\n });\n }\n\n if (me.autoIncrement) {\n // If auto-increment and no valid primaryKey found on the keyPath, get and set the new value, and use\n if (key === undefined) {\n Key.generateKeyForStore(tx, me, function (failure, key, oldCn) {\n if (failure) {\n failCb(createDOMException('ConstraintError', 'The key generator\\'s current number has reached the maximum safe integer limit'));\n return;\n }\n if (me.keyPath !== null) {\n // Should not throw now as checked earlier\n // Todo: Could this not be an array here?\n Key.injectKeyIntoValueUsingKeyPath(\n value, key, /** @type {string} */ (me.keyPath)\n );\n }\n success(key, oldCn);\n }, failCb);\n } else {\n Key.possiblyUpdateKeyGenerator(tx, me, key, keyCloneThenSuccess, failCb);\n }\n // Not auto-increment\n } else {\n keyCloneThenSuccess();\n }\n};\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {string} encoded\n * @param {import('./Key.js').Value} value\n * @param {import('./Key.js').Key|Integer} clonedKeyOrCurrentNumber\n * @param {Integer|undefined} oldCn\n * @param {(\n * clonedKeyOrCurrentNumber: import('./Key.js').Key|Integer\n * ) => void} success\n * @param {(err: Error|DOMException) => void} error\n * @this {IDBObjectStoreFull}\n * @returns {SyncPromise}\n */\nIDBObjectStore.prototype.__insertData = function (tx, encoded, value, clonedKeyOrCurrentNumber, oldCn, success, error) {\n const me = this;\n // The `ConstraintError` to occur for `add` upon a duplicate will occur naturally in attempting an insert\n // We process the index information first as it will stored in the same table as the store\n /** @type {{[key: string]: string}} */\n const paramMap = {};\n const indexPromises = Object.keys(\n // We do not iterate `indexNames` as those can be modified synchronously (e.g.,\n // `deleteIndex` could, by its synchronous removal from `indexNames`, prevent\n // iteration here of an index though per IndexedDB test\n // `idbobjectstore_createIndex4-deleteIndex-event_order.js`, `createIndex`\n // should be allowed to first fail even in such a case).\n me.__indexes\n ).map((indexName) => {\n // While this may sometimes resolve sync and sometimes async, the\n // idea is to avoid, where possible, unnecessary delays (and\n // consuming code ought to only see a difference in the browser\n // where we can't control the transaction timeout anyways).\n return new SyncPromise((resolve, reject) => {\n const index = me.__indexes[indexName];\n if (\n // `createIndex` was called synchronously after the current insertion was added to\n // the transaction queue so although it was added to `__indexes`, it is not yet\n // ready to be checked here for the insertion as it will be when running the\n // `createIndex` operation (e.g., if two items with the same key were added and\n // *then* a unique index was created, it should not continue to err and abort\n // yet, as we're still handling the insertions which must be processed (e.g., to\n // add duplicates which then cause a unique index to fail))\n index.__pendingCreate ||\n // If already deleted (and not just slated for deletion (by `__pendingDelete`\n // after this add), we avoid checks\n index.__deleted\n ) {\n resolve(undefined);\n return;\n }\n /**\n * @type {import('./Key.js').KeyValueObject|\n * import('./Key.js').KeyPathEvaluateValue}\n */\n let indexKey;\n try {\n indexKey = Key.extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Add as necessary to this and skip past this index if exceptions here)\n if (\n ('invalid' in indexKey && indexKey.invalid) ||\n ('failure' in indexKey && indexKey.failure)\n ) {\n throw new Error('Go to catch');\n }\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n resolve(undefined);\n return;\n }\n indexKey = indexKey.value;\n /**\n * @param {import('./IDBIndex.js').IDBIndexFull} index\n * @returns {void}\n */\n function setIndexInfo (index) {\n if (indexKey === undefined) {\n return;\n }\n paramMap[index.__currentName] = /** @type {string} */ (\n Key.encode(indexKey, index.multiEntry)\n );\n }\n if (index.unique) {\n const multiCheck = index.multiEntry && Array.isArray(indexKey);\n const fetchArgs = buildFetchIndexDataSQL(true, index, indexKey, 'key', multiCheck);\n executeFetchIndexData(null, ...fetchArgs, tx, null, function success (key) {\n if (key === undefined) {\n setIndexInfo(index);\n resolve(undefined);\n return;\n }\n reject(createDOMException(\n 'ConstraintError',\n 'Index already contains a record equal to ' +\n (multiCheck ? 'one of the subkeys of' : '') +\n '`indexKey`'\n ));\n }, reject);\n } else {\n setIndexInfo(index);\n resolve(undefined);\n }\n });\n });\n return SyncPromise.all(indexPromises).then(() => {\n const sqlStart = ['INSERT INTO', util.escapeStoreNameForSQL(me.__currentName), '('];\n const sqlEnd = [' VALUES ('];\n const insertSqlValues = [];\n if (clonedKeyOrCurrentNumber !== undefined) {\n // Key.convertValueToKey(primaryKey); // Already run\n sqlStart.push(util.sqlQuote('key'), ',');\n sqlEnd.push('?,');\n insertSqlValues.push(\n util.escapeSQLiteStatement(\n /** @type {string} */ (Key.encode(clonedKeyOrCurrentNumber))\n )\n );\n }\n Object.entries(paramMap).forEach(([key, stmt]) => {\n sqlStart.push(util.escapeIndexNameForSQL(key) + ',');\n sqlEnd.push('?,');\n insertSqlValues.push(util.escapeSQLiteStatement(stmt));\n });\n // removing the trailing comma\n sqlStart.push(util.sqlQuote('value') + ' )');\n sqlEnd.push('?)');\n insertSqlValues.push(util.escapeSQLiteStatement(encoded));\n\n const insertSql = sqlStart.join(' ') + sqlEnd.join(' ');\n if (CFG.DEBUG) { console.log('SQL for adding', insertSql, insertSqlValues); }\n\n tx.executeSql(insertSql, insertSqlValues, function () {\n success(clonedKeyOrCurrentNumber);\n }, function (tx, err) {\n // Should occur for `add` operation\n error(createDOMException(\n 'ConstraintError', /** @type {string} */ (err.message), err\n ));\n return false;\n });\n return undefined;\n // eslint-disable-next-line sonarjs/no-invariant-returns -- Convenient\n }).catch(function (err) {\n /**\n * @returns {void}\n */\n function fail () {\n // Todo: Add a different error object here if `assignCurrentNumber`\n // fails in reverting?\n error(err);\n }\n if (typeof oldCn === 'number') {\n Key.assignCurrentNumber(tx, me, oldCn, fail, fail);\n return null;\n }\n fail();\n return null;\n });\n};\n\n/**\n *\n * @param {import('./Key.js').Value} value\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.add = function (value /* , key */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const key = arguments[1];\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No value was specified');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__assertWritable();\n\n const request = /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__createRequest(me);\n const [ky, clonedValue] = me.__validateKeyAndValueAndCloneValue(value, key, false);\n IDBObjectStore.__storingRecordObjectStore(request, me, true, clonedValue, true, ky);\n return request;\n};\n\n/**\n *\n * @param {import('./Key.js').Value} value\n * @throws {TypeError}\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.put = function (value /* , key */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const key = arguments[1];\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No value was specified');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__assertWritable();\n\n const request = /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__createRequest(me);\n const [ky, clonedValue] = me.__validateKeyAndValueAndCloneValue(value, key, false);\n IDBObjectStore.__storingRecordObjectStore(request, me, true, clonedValue, false, ky);\n return request;\n};\n\n/**\n *\n * @param {SQLTransaction} tx\n * @param {import('./Key.js').Key} key\n * @param {(tx: SQLTransaction) => void} cb\n * @param {(err: SQLError) => void} error\n * @this {IDBObjectStoreFull}\n * @returns {void}\n */\nIDBObjectStore.prototype.__overwrite = function (tx, key, cb, error) {\n const me = this;\n // First try to delete if the record exists\n // Key.convertValueToKey(key); // Already run\n const sql = 'DELETE FROM ' + util.escapeStoreNameForSQL(me.__currentName) + ' WHERE \"key\" = ?';\n const encodedKey = /** @type {string} */ (Key.encode(key));\n tx.executeSql(sql, [util.escapeSQLiteStatement(encodedKey)], function (tx, data) {\n if (CFG.DEBUG) { console.log('Did the row with the', key, 'exist?', data.rowsAffected); }\n cb(tx);\n }, function (tx, err) {\n error(err);\n return false;\n });\n};\n\n/**\n *\n * @param {import('./IDBRequest.js').IDBRequestFull} request\n * @param {IDBObjectStoreFull} store\n * @param {boolean} invalidateCache\n * @param {import('./Key.js').Value} value\n * @param {boolean} noOverwrite\n * @returns {void}\n */\nIDBObjectStore.__storingRecordObjectStore = function (request, store, invalidateCache, value, noOverwrite /* , key */) {\n // eslint-disable-next-line prefer-rest-params -- API\n const key = arguments[5];\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n store.transaction\n ).__pushToQueue(request, function (tx, args, success, error) {\n store.__deriveKey(tx, value, key, function (clonedKeyOrCurrentNumber, oldCn) {\n Sca.encode(value, function (encoded) {\n /**\n * @param {SQLTransaction} tx\n * @returns {void}\n */\n function insert (tx) {\n store.__insertData(tx, encoded, value, clonedKeyOrCurrentNumber, oldCn, function (...args) {\n if (invalidateCache) {\n store.__cursors.forEach((cursor) => {\n cursor.__invalidateCache();\n });\n }\n success(...args);\n }, error);\n }\n if (!noOverwrite) {\n store.__overwrite(tx, clonedKeyOrCurrentNumber, insert, error);\n return;\n }\n insert(tx);\n });\n }, error);\n });\n};\n\n/**\n *\n * @param {import('./Key.js').Value} query\n * @param {boolean} [getKey]\n * @param {boolean} [getAll]\n * @param {Integer} [count]\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.__get = function (query, getKey, getAll, count) {\n const me = this;\n if (count !== undefined) {\n count = util.enforceRange(count, 'unsigned long');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n\n const range = convertValueToKeyRange(query, !getAll);\n\n const col = getKey ? 'key' : 'value';\n const sql = ['SELECT', util.sqlQuote(col), 'FROM', util.escapeStoreNameForSQL(me.__currentName)];\n /** @type {string[]} */\n const sqlValues = [];\n if (range !== undefined) {\n sql.push('WHERE');\n setSQLForKeyRange(range, util.sqlQuote('key'), sql, sqlValues);\n }\n if (!getAll) {\n count = 1;\n }\n if (count) {\n if (!Number.isFinite(count)) {\n throw new TypeError('The count parameter must be a finite number');\n }\n sql.push('LIMIT', String(count));\n }\n const sqlStr = sql.join(' ');\n return /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__addToTransactionQueue(function objectStoreGet (tx, args, success, error) {\n if (CFG.DEBUG) { console.log('Fetching', me.__currentName, sqlValues); }\n tx.executeSql(sqlStr, sqlValues, function (tx, data) {\n if (CFG.DEBUG) { console.log('Fetched data', data); }\n let ret;\n try {\n // Opera can't deal with the try-catch here.\n if (data.rows.length === 0) {\n if (getAll) {\n success([]);\n } else {\n success();\n }\n return;\n }\n ret = [];\n if (getKey) {\n for (let i = 0; i < data.rows.length; i++) {\n // Key.convertValueToKey(data.rows.item(i).key); // Already validated before storage\n ret.push(\n Key.decode(util.unescapeSQLiteResponse(data.rows.item(i).key), false)\n );\n }\n } else {\n for (let i = 0; i < data.rows.length; i++) {\n ret.push(\n Sca.decode(util.unescapeSQLiteResponse(data.rows.item(i).value))\n );\n }\n }\n if (!getAll) {\n ret = ret[0];\n }\n } catch (e) {\n // If no result is returned, or error occurs when parsing JSON\n if (CFG.DEBUG) { console.log(e); }\n }\n success(ret);\n }, function (tx, err) {\n error(err);\n return false;\n });\n }, undefined, me);\n};\n\n/**\n *\n * @param {import('./Key.js').Value} query\n * @throws {TypeError}\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.get = function (query) {\n if (!arguments.length) {\n throw new TypeError('A parameter was missing for `IDBObjectStore.get`.');\n }\n return this.__get(query);\n};\n\n/**\n *\n * @param {import('./Key.js').Value} query\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.getKey = function (query) {\n if (!arguments.length) {\n throw new TypeError('A parameter was missing for `IDBObjectStore.getKey`.');\n }\n return this.__get(query, true);\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.getAll = function (/* query, count */) {\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, count] = arguments;\n return this.__get(query, false, true, count);\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.getAllKeys = function (/* query, count */) {\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, count] = arguments;\n return this.__get(query, true, true, count);\n};\n\n/**\n *\n * @param {import('./Key.js').Value} query\n * @throws {TypeError}\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.delete = function (query) {\n const me = this;\n if (!(this instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n if (!arguments.length) {\n throw new TypeError('A parameter was missing for `IDBObjectStore.delete`.');\n }\n\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__assertWritable();\n\n const range = convertValueToKeyRange(query, true);\n\n const sqlArr = ['DELETE FROM', util.escapeStoreNameForSQL(me.__currentName), 'WHERE'];\n /** @type {string[]} */\n const sqlValues = [];\n setSQLForKeyRange(range, util.sqlQuote('key'), sqlArr, sqlValues);\n const sql = sqlArr.join(' ');\n\n return /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__addToTransactionQueue(function objectStoreDelete (tx, args, success, error) {\n if (CFG.DEBUG) { console.log('Deleting', me.__currentName, sqlValues); }\n tx.executeSql(sql, sqlValues, function (tx, data) {\n if (CFG.DEBUG) { console.log('Deleted from database', data.rowsAffected); }\n me.__cursors.forEach((cursor) => {\n cursor.__invalidateCache(); // Delete\n });\n success();\n }, function (tx, err) {\n error(err);\n return false;\n });\n }, undefined, me);\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.clear = function () {\n const me = this;\n if (!(this instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__assertWritable();\n\n return /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.transaction\n ).__addToTransactionQueue(function objectStoreClear (tx, args, success, error) {\n tx.executeSql('DELETE FROM ' + util.escapeStoreNameForSQL(me.__currentName), [], function (tx, data) {\n if (CFG.DEBUG) { console.log('Cleared all records from database', data.rowsAffected); }\n me.__cursors.forEach((cursor) => {\n cursor.__invalidateCache(); // Clear\n });\n success();\n }, function (tx, err) {\n error(err);\n return false;\n });\n }, undefined, me);\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.count = function (/* query */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const query = arguments[0];\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n\n // We don't need to add to cursors array since has the count parameter which won't cache\n return IDBCursorWithValue.__createInstance(query, 'next', me, me, 'key', 'value', true).__request;\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.openCursor = function (/* query, direction */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, direction] = arguments;\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n const cursor = IDBCursorWithValue.__createInstance(query, direction, me, me, 'key', 'value');\n me.__cursors.push(cursor);\n return cursor.__request;\n};\n\n/**\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBRequest.js').IDBRequestFull}\n */\nIDBObjectStore.prototype.openKeyCursor = function (/* query, direction */) {\n const me = this;\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n // eslint-disable-next-line prefer-rest-params -- API\n const [query, direction] = arguments;\n const cursor = IDBCursor.__createInstance(query, direction, me, me, 'key', 'key');\n me.__cursors.push(cursor);\n return cursor.__request;\n};\n\n/**\n *\n * @param {string} indexName\n * @this {IDBObjectStoreFull}\n * @returns {import('./IDBIndex.js').IDBIndexFull}\n */\nIDBObjectStore.prototype.index = function (indexName) {\n const me = this;\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No index name was specified');\n }\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertNotFinished(me.transaction);\n const index = me.__indexes[indexName];\n if (!index || index.__deleted) {\n throw createDOMException('NotFoundError', 'Index \"' + indexName + '\" does not exist on ' + me.__currentName);\n }\n\n if (!me.__indexHandles[indexName] ||\n me.__indexes[indexName].__pendingDelete ||\n me.__indexes[indexName].__deleted\n ) {\n me.__indexHandles[indexName] = IDBIndex.__clone(index, me);\n }\n return me.__indexHandles[indexName];\n};\n\n/**\n * Creates a new index on the object store.\n * @param {string} indexName\n * @param {string|string[]} keyPath\n * @this {IDBObjectStoreFull}\n * @returns {IDBIndex}\n */\nIDBObjectStore.prototype.createIndex = function (indexName, keyPath /* , optionalParameters */) {\n const me = this;\n // eslint-disable-next-line prefer-rest-params -- API\n let optionalParameters = arguments[2];\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n indexName = String(indexName); // W3C test within IDBObjectStore.js seems to accept string conversion\n if (arguments.length === 0) {\n throw new TypeError('No index name was specified');\n }\n if (arguments.length === 1) {\n throw new TypeError('No key path was specified');\n }\n IDBTransaction.__assertVersionChange(me.transaction);\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n if (me.__indexes[indexName] && !me.__indexes[indexName].__deleted && !me.__indexes[indexName].__pendingDelete) {\n throw createDOMException('ConstraintError', 'Index \"' + indexName + '\" already exists on ' + me.__currentName);\n }\n\n keyPath = util.convertToSequenceDOMString(keyPath);\n if (!util.isValidKeyPath(keyPath)) {\n throw createDOMException('SyntaxError', 'A valid keyPath must be supplied');\n }\n if (Array.isArray(keyPath) && optionalParameters && optionalParameters.multiEntry) {\n throw createDOMException('InvalidAccessError', 'The keyPath argument was an array and the multiEntry option is true.');\n }\n\n optionalParameters = optionalParameters || {};\n /** @type {import('./IDBIndex.js').IDBIndexProperties} */\n const indexProperties = {\n columnName: indexName,\n keyPath,\n optionalParams: {\n unique: Boolean(optionalParameters.unique),\n multiEntry: Boolean(optionalParameters.multiEntry)\n }\n };\n const index = IDBIndex.__createInstance(me, indexProperties);\n IDBIndex.__createIndex(me, index);\n return index;\n};\n\n/**\n *\n * @param {string} name\n * @this {IDBObjectStoreFull}\n * @returns {void}\n */\nIDBObjectStore.prototype.deleteIndex = function (name) {\n const me = this;\n if (!(me instanceof IDBObjectStore)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No index name was specified');\n }\n IDBTransaction.__assertVersionChange(me.transaction);\n IDBObjectStore.__invalidStateIfDeleted(me);\n IDBTransaction.__assertActive(me.transaction);\n const index = me.__indexes[name];\n if (!index) {\n throw createDOMException('NotFoundError', 'Index \"' + name + '\" does not exist on ' + me.__currentName);\n }\n\n IDBIndex.__deleteIndex(me, index);\n};\n\nutil.defineReadonlyOuterInterface(IDBObjectStore.prototype, readonlyProperties);\nutil.defineOuterInterface(IDBObjectStore.prototype, ['name']);\n\nIDBObjectStore.prototype[Symbol.toStringTag] = 'IDBObjectStorePrototype';\n\nObject.defineProperty(IDBObjectStore, 'prototype', {\n writable: false\n});\n\nexport default IDBObjectStore;\n","import {EventTargetFactory} from 'eventtargeter';\nimport {createDOMException} from './DOMException.js';\nimport {createEvent} from './Event.js';\nimport * as util from './util.js';\nimport DOMStringList from './DOMStringList.js';\nimport IDBObjectStore from './IDBObjectStore.js';\nimport IDBTransaction from './IDBTransaction.js';\n\nconst listeners = ['onabort', 'onclose', 'onerror', 'onversionchange'];\nconst readonlyProperties = ['name', 'version', 'objectStoreNames'];\n\n/**\n * @typedef {{\n * name: string,\n * keyPath: import('./Key.js').KeyPath,\n * autoInc: boolean,\n * indexList: {[key: string]: import('./IDBIndex.js').IDBIndexProperties},\n * idbdb: IDBDatabaseFull,\n * cursors?: (import('./IDBCursor.js').IDBCursorFull|\n * import('./IDBCursor.js').IDBCursorWithValueFull)[],\n * }} IDBObjectStoreProperties\n */\n\n/**\n * IDB Database Object.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#database-interface\n * @class\n */\nfunction IDBDatabase () {\n this.__versionTransaction = null;\n this.__objectStores = null;\n /** @type {import('./IDBTransaction.js').IDBTransactionFull[]} */\n this.__transactions = [];\n throw new TypeError('Illegal constructor');\n}\nconst IDBDatabaseAlias = IDBDatabase;\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {IDBDatabase & EventTarget & {\n * createObjectStore: (storeName: string) => IDBObjectStore,\n * deleteObjectStore: (storeName: string) => void,\n * close: () => void,\n * transaction: (storeNames: string|string[], mode: string) => IDBTransaction,\n * throwIfUpgradeTransactionNull: () => void,\n * objectStoreNames: import('./DOMStringList.js').DOMStringListFull,\n * name: string,\n * __forceClose: (msg: string) => void,\n * __db: import('websql-configurable/lib/websql/WebSQLDatabase.js').default,\n * __oldVersion: Integer,\n * __version: Integer,\n * __name: string,\n * __upgradeTransaction: null|import('./IDBTransaction.js').IDBTransactionFull,\n * __versionTransaction: import('./IDBTransaction.js').IDBTransactionFull,\n * __transactions: import('./IDBTransaction.js').IDBTransactionFull[],\n * __objectStores: {[key: string]: IDBObjectStore},\n * __objectStoreNames: import('./DOMStringList.js').DOMStringListFull,\n * __oldObjectStoreNames: import('./DOMStringList.js').DOMStringListFull,\n * __unblocking: {\n * check: () => void\n * }\n * }} IDBDatabaseFull\n */\n\n/**\n * @param {import('websql-configurable').default} db\n * @param {string} name\n * @param {Integer} oldVersion\n * @param {Integer} version\n * @param {SQLResultSet} storeProperties\n * @returns {IDBDatabaseFull}\n */\nIDBDatabase.__createInstance = function (db, name, oldVersion, version, storeProperties) {\n /**\n * @class\n * @this {IDBDatabaseFull}\n */\n function IDBDatabase () {\n // @ts-expect-error It's ok\n this[Symbol.toStringTag] = 'IDBDatabase';\n util.defineReadonlyProperties(this, readonlyProperties);\n this.__db = db;\n this.__closePending = false;\n this.__oldVersion = oldVersion;\n this.__version = version;\n this.__name = name;\n this.__upgradeTransaction = null;\n util.defineListenerProperties(this, listeners);\n // @ts-expect-error Part of `ShimEventTarget`\n this.__setOptions({\n legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB\n });\n\n /** @type {import('./IDBTransaction.js').IDBTransactionFull[]} */\n this.__transactions = [];\n\n /** @type {{[key: string]: IDBObjectStore}} */\n this.__objectStores = {};\n this.__objectStoreNames = DOMStringList.__createInstance();\n\n /**\n * @type {IDBObjectStoreProperties}\n */\n const itemCopy = {};\n for (let i = 0; i < storeProperties.rows.length; i++) {\n const item = storeProperties.rows.item(i);\n // Safari implements `item` getter return object's properties\n // as readonly, so we copy all its properties (except our\n // custom `currNum` which we don't need) onto a new object\n itemCopy.name = item.name;\n itemCopy.keyPath = JSON.parse(item.keyPath);\n // Though `autoInc` is coming from the database as a NUMERIC\n // type (how SQLite stores BOOLEAN set in CREATE TABLE),\n // and should thus be parsed into a number here (0 or 1),\n // `IDBObjectStore.__createInstance` will convert to a boolean\n // when setting the store's `autoIncrement`.\n /** @type {const} */ (['autoInc', 'indexList']).forEach((prop) => {\n itemCopy[prop] = JSON.parse(item[prop]);\n });\n\n itemCopy.idbdb = this;\n const store = IDBObjectStore.__createInstance(itemCopy);\n this.__objectStores[store.name] = store;\n this.objectStoreNames.push(store.name);\n }\n this.__oldObjectStoreNames = this.objectStoreNames.clone();\n }\n IDBDatabase.prototype = IDBDatabaseAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBDatabase();\n};\n\n// @ts-expect-error It's ok\nIDBDatabase.prototype = EventTargetFactory.createInstance();\nIDBDatabase.prototype[Symbol.toStringTag] = 'IDBDatabasePrototype';\n\n/**\n * Creates a new object store.\n * @param {string} storeName\n * @this {IDBDatabaseFull}\n * @returns {IDBObjectStore}\n */\nIDBDatabase.prototype.createObjectStore = function (storeName /* , createOptions */) {\n // eslint-disable-next-line prefer-rest-params -- API\n let createOptions = arguments[1];\n storeName = String(storeName); // W3C test within IDBObjectStore.js seems to accept string conversion\n if (!(this instanceof IDBDatabase)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No object store name was specified');\n }\n IDBTransaction.__assertVersionChange(this.__versionTransaction); // this.__versionTransaction may not exist if called mistakenly by user in onsuccess\n this.throwIfUpgradeTransactionNull();\n IDBTransaction.__assertActive(this.__versionTransaction);\n\n createOptions = {...createOptions};\n let {keyPath} = createOptions;\n keyPath = keyPath === undefined ? null : util.convertToSequenceDOMString(keyPath);\n if (keyPath !== null && !util.isValidKeyPath(keyPath)) {\n throw createDOMException('SyntaxError', 'The keyPath argument contains an invalid key path.');\n }\n\n if (this.__objectStores[storeName] && !this.__objectStores[storeName].__pendingDelete) {\n throw createDOMException('ConstraintError', 'Object store \"' + storeName + '\" already exists in ' + this.name);\n }\n\n const autoInc = createOptions.autoIncrement;\n if (autoInc && (keyPath === '' || Array.isArray(keyPath))) {\n throw createDOMException('InvalidAccessError', 'With autoIncrement set, the keyPath argument must not be an array or empty string.');\n }\n\n /** @type {IDBObjectStoreProperties} */\n const storeProperties = {\n name: storeName,\n keyPath,\n autoInc,\n indexList: {},\n idbdb: this\n };\n const store = IDBObjectStore.__createInstance(storeProperties, this.__versionTransaction);\n return IDBObjectStore.__createObjectStore(this, store);\n};\n\n/**\n * Deletes an object store.\n * @param {string} storeName\n * @throws {TypeError|DOMException}\n * @this {IDBDatabaseFull}\n * @returns {void}\n */\nIDBDatabase.prototype.deleteObjectStore = function (storeName) {\n if (!(this instanceof IDBDatabase)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('No object store name was specified');\n }\n IDBTransaction.__assertVersionChange(this.__versionTransaction);\n this.throwIfUpgradeTransactionNull();\n IDBTransaction.__assertActive(this.__versionTransaction);\n\n const store = this.__objectStores[storeName];\n if (!store) {\n throw createDOMException('NotFoundError', 'Object store \"' + storeName + '\" does not exist in ' + this.name);\n }\n\n IDBObjectStore.__deleteObjectStore(this, store);\n};\n\n/**\n * @throws {TypeError}\n * @this {IDBDatabaseFull}\n * @returns {void}\n */\nIDBDatabase.prototype.close = function () {\n if (!(this instanceof IDBDatabase)) {\n throw new TypeError('Illegal invocation');\n }\n this.__closePending = true;\n if (this.__unblocking) {\n this.__unblocking.check();\n }\n this.__transactions = [];\n};\n\n/**\n * Starts a new transaction.\n * @param {string|string[]} storeNames\n * @this {IDBDatabaseFull}\n * @returns {import('./IDBTransaction.js').IDBTransactionFull}\n */\nIDBDatabase.prototype.transaction = function (storeNames /* , mode */) {\n if (arguments.length === 0) {\n throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`');\n }\n // eslint-disable-next-line prefer-rest-params -- API\n let mode = arguments[1];\n storeNames = util.isIterable(storeNames)\n // Creating new array also ensures sequence is passed by value: https://heycam.github.io/webidl/#idl-sequence\n ? [...new Set( // to be unique\n util.convertToSequenceDOMString(storeNames) // iterables have `ToString` applied (and we convert to array for convenience)\n )].sort() // must be sorted\n : [util.convertToDOMString(storeNames)];\n\n /* (function () {\n throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`');\n }())); */\n\n // Since SQLite (at least node-websql and definitely WebSQL) requires\n // locking of the whole database, to allow simultaneous readwrite\n // operations on transactions without overlapping stores, we'd probably\n // need to save the stores in separate databases (we could also consider\n // prioritizing readonly but not starving readwrite).\n // Even for readonly transactions, due to [issue 17](https://github.com/nolanlawson/node-websql/issues/17),\n // we're not currently actually running the SQL requests in parallel.\n mode = mode || 'readonly';\n\n IDBTransaction.__assertNotVersionChange(this.__versionTransaction);\n if (this.__closePending) {\n throw createDOMException('InvalidStateError', 'An attempt was made to start a new transaction on a database connection that is not open');\n }\n\n const objectStoreNames = DOMStringList.__createInstance();\n storeNames.forEach((storeName) => {\n if (!this.objectStoreNames.contains(storeName)) {\n throw createDOMException('NotFoundError', 'The \"' + storeName + '\" object store does not exist');\n }\n objectStoreNames.push(storeName);\n });\n\n if (storeNames.length === 0) {\n throw createDOMException('InvalidAccessError', 'No valid object store names were specified');\n }\n\n if (mode !== 'readonly' && mode !== 'readwrite') {\n throw new TypeError('Invalid transaction mode: ' + mode);\n }\n\n // Do not set transaction state to \"inactive\" yet (will be set after\n // timeout on creating transaction instance):\n // https://github.com/w3c/IndexedDB/issues/87\n const trans = IDBTransaction.__createInstance(this, objectStoreNames, mode);\n this.__transactions.push(trans);\n return trans;\n};\n\n/**\n * @see https://github.com/w3c/IndexedDB/issues/192\n * @throws {DOMException}\n * @this {IDBDatabaseFull}\n * @returns {void}\n */\nIDBDatabase.prototype.throwIfUpgradeTransactionNull = function () {\n if (this.__upgradeTransaction === null) {\n throw createDOMException('InvalidStateError', 'No upgrade transaction associated with database.');\n }\n};\n\n// Todo __forceClose: Add tests for `__forceClose`\n/**\n *\n * @param {string} msg\n * @this {IDBDatabaseFull}\n * @returns {void}\n */\nIDBDatabase.prototype.__forceClose = function (msg) {\n const me = this;\n me.close();\n let ct = 0;\n me.__transactions.forEach(function (trans) {\n // eslint-disable-next-line camelcase -- Clear API\n trans.on__abort = function () {\n ct++;\n if (ct === me.__transactions.length) {\n // Todo __forceClose: unblock any pending `upgradeneeded` or `deleteDatabase` calls\n const evt = createEvent('close');\n setTimeout(() => {\n me.dispatchEvent(evt);\n });\n }\n };\n trans.__abortTransaction(createDOMException(\n 'AbortError',\n 'The connection was force-closed: ' + (msg || '')\n ));\n });\n me.__transactions = [];\n};\n\nutil.defineOuterInterface(IDBDatabase.prototype, listeners);\nutil.defineReadonlyOuterInterface(IDBDatabase.prototype, readonlyProperties);\n\nObject.defineProperty(IDBDatabase.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBDatabase\n});\n\nObject.defineProperty(IDBDatabase, 'prototype', {\n writable: false\n});\n\nexport default IDBDatabase;\n","/* eslint-disable sonarjs/no-invariant-returns -- Convenient here */\n// eslint-disable-next-line no-restricted-imports -- Can be polyfilled\nimport path from 'path';\nimport SyncPromise from 'sync-promise-expanded';\n\nimport {createEvent} from './Event.js';\nimport IDBVersionChangeEvent from './IDBVersionChangeEvent.js';\nimport {logError, webSQLErrback, createDOMException} from './DOMException.js';\nimport {IDBOpenDBRequest} from './IDBRequest.js';\nimport cmp from './cmp.js';\nimport * as util from './util.js';\nimport * as Key from './Key.js';\nimport IDBTransaction from './IDBTransaction.js';\nimport IDBDatabase from './IDBDatabase.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @callback DatabaseDeleted\n * @returns {void}\n */\n\n/** @type {import('./CFG.js').FSApi} */\nlet fs;\n\n/**\n * @param {import('./CFG.js').FSApi} _fs\n * @returns {void}\n */\nconst setFS = (_fs) => {\n fs = _fs;\n};\n\n/**\n * @returns {string}\n */\nconst getOrigin = () => {\n // eslint-disable-next-line no-undef -- If browser/polyfilled\n return (typeof location !== 'object' || !location) ? 'null' : location.origin;\n};\nconst hasNullOrigin = () => CFG.checkOrigin !== false && (getOrigin() === 'null');\n\n// Todo: This really should be process and tab-independent so the\n// origin could vary; in the browser, this might be through a\n// `SharedWorker`\n\n/**\n * @type {{\n * [key: string]: {\n * [key: string]: {\n * req: import('./IDBRequest.js').IDBOpenDBRequestFull,\n * cb: (req: import('./IDBRequest.js').IDBRequestFull) => void,\n * }[]\n * }\n * }}\n */\nconst connectionQueue = {};\n\n/**\n * @param {string} name\n * @param {string} origin\n * @returns {void}\n */\nfunction processNextInConnectionQueue (name, origin = getOrigin()) {\n const queueItems = connectionQueue[origin][name];\n if (!queueItems[0]) { // Nothing left to process\n return;\n }\n const {req, cb} = queueItems[0]; // Keep in queue to prevent continuation\n\n /**\n * @returns {void}\n */\n function removeFromQueue () {\n queueItems.shift();\n processNextInConnectionQueue(name, origin);\n }\n req.addEventListener('success', removeFromQueue);\n req.addEventListener('error', removeFromQueue);\n req.addEventListener('blocked', removeFromQueue);\n cb(req);\n}\n\n/* eslint-disable default-param-last -- Keep cb at end */\n/**\n * @param {import('./IDBRequest.js').IDBOpenDBRequestFull} req\n * @param {string} name\n * @param {string} origin\n * @param {(req: import('./IDBRequest.js').IDBOpenDBRequestFull) => void} cb\n * @returns {void}\n */\nfunction addRequestToConnectionQueue (req, name, origin = getOrigin(), cb) {\n /* eslint-enable default-param-last -- Keep cb at end */\n if (!connectionQueue[origin][name]) {\n connectionQueue[origin][name] = [];\n }\n connectionQueue[origin][name].push({req, cb});\n\n if (connectionQueue[origin][name].length === 1) { // If there are no items in the queue, we have to start it\n processNextInConnectionQueue(name, origin);\n }\n}\n\n/**\n * @param {import('./IDBDatabase.js').IDBDatabaseFull[]} openConnections\n * @param {import('./IDBRequest.js').IDBRequestFull} req\n * @param {Integer} oldVersion\n * @param {Integer|null} newVersion\n * @returns {SyncPromise}\n */\nfunction triggerAnyVersionChangeAndBlockedEvents (openConnections, req, oldVersion, newVersion) {\n // Todo: For Node (and in browser using service workers if available?) the\n // connections ought to involve those in any process; should also\n // auto-close if unloading\n\n /**\n * @param {IDBDatabase} connection\n * @returns {boolean|undefined}\n */\n const connectionIsClosed = (connection) => connection.__closePending;\n const connectionsClosed = () => openConnections.every((conn) => {\n return connectionIsClosed(conn);\n });\n return openConnections.reduce(function (promises, entry) {\n if (connectionIsClosed(entry)) {\n return promises;\n }\n return promises.then(function () {\n if (connectionIsClosed(entry)) {\n // Prior onversionchange must have caused this connection to be closed\n return undefined;\n }\n const e = /** @type {Event & IDBVersionChangeEvent} */ (\n new IDBVersionChangeEvent('versionchange', {oldVersion, newVersion})\n );\n return new SyncPromise(function (resolve) {\n setTimeout(() => {\n entry.dispatchEvent(e); // No need to catch errors\n resolve(undefined);\n });\n });\n });\n }, SyncPromise.resolve(undefined)).then(function () {\n if (connectionsClosed()) {\n return undefined;\n }\n return new SyncPromise(function (resolve) {\n const unblocking = {\n check () {\n if (connectionsClosed()) {\n resolve(undefined);\n }\n }\n };\n const e = /** @type {Event & IDBVersionChangeEvent} */ (\n new IDBVersionChangeEvent('blocked', {oldVersion, newVersion})\n );\n setTimeout(() => {\n req.dispatchEvent(e); // No need to catch errors\n if (!connectionsClosed()) {\n openConnections.forEach((connection) => {\n if (!connectionIsClosed(connection)) {\n connection.__unblocking = unblocking;\n }\n });\n } else {\n resolve(undefined);\n }\n });\n });\n });\n}\n\n/**\n * @typedef {import('websql-configurable/lib/websql/WebSQLDatabase.js').default & {\n * _db: {\n * _db: {\n * close: (errBack: (err: Error) => void) => void\n * }\n * }\n * }} DatabaseFull\n */\n\n/**\n * @type {{\n * [key: string]: {\n * [key: string]: DatabaseFull\n * }\n * }}\n */\nconst websqlDBCache = {};\n\n/** @type {import('websql-configurable/lib/websql/WebSQLDatabase.js').default} */\nlet sysdb;\nlet nameCounter = 0;\n\n/**\n * @param {string} name\n * @returns {Integer}\n */\nfunction getLatestCachedWebSQLVersion (name) {\n return Object.keys(websqlDBCache[name]).map(Number).reduce(\n (prev, curr) => {\n return curr > prev ? curr : prev;\n }, 0\n );\n}\n\n/**\n * @param {string} name\n * @returns {DatabaseFull}\n */\nfunction getLatestCachedWebSQLDB (name) {\n return websqlDBCache[name] && websqlDBCache[name][\n getLatestCachedWebSQLVersion(name)\n ];\n}\n\n/**\n * @param {OpenDatabase} __openDatabase\n * @param {string} name\n * @param {string} escapedDatabaseName\n * @param {DatabaseDeleted} databaseDeleted\n * @param {(tx: SQLTransaction|Error|SQLError, err?: SQLError) => boolean} dbError\n * @returns {void}\n */\nfunction cleanupDatabaseResources (__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError) {\n const useMemoryDatabase = typeof CFG.memoryDatabase === 'string';\n if (useMemoryDatabase) {\n const latestSQLiteDBCached = websqlDBCache[name] ? getLatestCachedWebSQLDB(name) : null;\n if (!latestSQLiteDBCached) {\n console.warn('Could not find a memory database instance to delete.');\n databaseDeleted();\n return;\n }\n const sqliteDB = latestSQLiteDBCached._db && latestSQLiteDBCached._db._db;\n if (!sqliteDB || !sqliteDB.close) {\n console.error('The `openDatabase` implementation does not have the expected `._db._db.close` method for closing the database');\n return;\n }\n sqliteDB.close(\n /**\n * @param {Error} err\n * @returns {void}\n */\n (err) => {\n if (err) {\n console.warn('Error closing (destroying) memory database');\n return;\n }\n databaseDeleted();\n }\n );\n return;\n }\n if (fs && CFG.deleteDatabaseFiles !== false) {\n fs.unlink(path.join(CFG.databaseBasePath || '', escapedDatabaseName), (err) => {\n if (err && err.code !== 'ENOENT') { // Ignore if file is already deleted\n dbError({\n code: 0,\n message: 'Error removing database file: ' + escapedDatabaseName + ' ' + err\n });\n return;\n }\n databaseDeleted();\n });\n return;\n }\n\n const sqliteDB = __openDatabase(\n path.join(CFG.databaseBasePath || '', escapedDatabaseName),\n '1',\n name,\n CFG.DEFAULT_DB_SIZE\n );\n sqliteDB.transaction(function (tx) {\n tx.executeSql('SELECT \"name\" FROM __sys__', [], function (tx, data) {\n const tables = data.rows;\n (function deleteTables (i) {\n if (i >= tables.length) {\n // If all tables are deleted, delete the housekeeping tables\n tx.executeSql('DROP TABLE IF EXISTS __sys__', [], function () {\n databaseDeleted();\n }, dbError);\n } else {\n // Delete all tables in this database, maintained in the sys table\n tx.executeSql('DROP TABLE ' + util.escapeStoreNameForSQL(\n util.unescapeSQLiteResponse( // Avoid double-escaping\n tables.item(i).name\n )\n ), [], function () {\n deleteTables(i + 1);\n }, function () {\n deleteTables(i + 1);\n return false;\n });\n }\n }(0));\n }, function () {\n // __sys__ table does not exist, but that does not mean delete did not happen\n databaseDeleted();\n return false;\n });\n });\n}\n\n/**\n * @callback CreateSysDBSuccessCallback\n * @returns {void}\n */\n\n/**\n * Creates the sysDB to keep track of version numbers for databases.\n * @param {OpenDatabase} __openDatabase\n * @param {CreateSysDBSuccessCallback} success\n * @param {(tx: SQLTransaction|SQLError|Error, err?: SQLError) => void} failure\n * @returns {void}\n */\nfunction createSysDB (__openDatabase, success, failure) {\n /**\n *\n * @param {boolean|SQLTransaction|SQLError} tx\n * @param {SQLError} [err]\n * @returns {void}\n */\n function sysDbCreateError (tx, err) {\n const er = webSQLErrback(/** @type {SQLError} */ (err) || tx);\n if (CFG.DEBUG) { console.log('Error in sysdb transaction - when creating dbVersions', err); }\n failure(er);\n }\n\n if (sysdb) {\n success();\n } else {\n sysdb = __openDatabase(\n typeof CFG.memoryDatabase === 'string'\n ? CFG.memoryDatabase\n : path.join(\n (typeof CFG.sysDatabaseBasePath === 'string'\n ? CFG.sysDatabaseBasePath\n : (CFG.databaseBasePath || '')),\n '__sysdb__' + (CFG.addSQLiteExtension !== false ? '.sqlite' : '')\n ),\n '1',\n 'System Database',\n CFG.DEFAULT_DB_SIZE\n );\n sysdb.transaction(function (systx) {\n systx.executeSql('CREATE TABLE IF NOT EXISTS dbVersions (name BLOB, version INT);', [], function (systx) {\n if (!CFG.useSQLiteIndexes) {\n success();\n return;\n }\n systx.executeSql(\n 'CREATE INDEX IF NOT EXISTS dbvname ON dbVersions(name)',\n [],\n success,\n /** @type {SQLStatementErrorCallback} */ (sysDbCreateError)\n );\n }, /** @type {SQLStatementErrorCallback} */ (sysDbCreateError));\n }, sysDbCreateError);\n }\n}\n\n/**\n * IDBFactory Class.\n * @see https://w3c.github.io/IndexedDB/#idl-def-IDBFactory\n * @class\n */\nfunction IDBFactory () {\n throw new TypeError('Illegal constructor');\n}\n\n/**\n * @typedef {(\n * name: string, version: string, displayName: string, estimatedSize: number\n * ) => import('websql-configurable/lib/websql/WebSQLDatabase.js').default} OpenDatabase\n */\n\n/**\n * @typedef {globalThis.IDBFactory & {\n * __openDatabase: OpenDatabase,\n * __connections: {\n * [key: string]: import('./IDBDatabase.js').IDBDatabaseFull[]\n * }\n* }} IDBFactoryFull\n */\n\nconst IDBFactoryAlias = IDBFactory;\n/**\n * @returns {IDBFactoryFull}\n */\nIDBFactory.__createInstance = function () {\n /**\n * @class\n */\n function IDBFactory () {\n this[Symbol.toStringTag] = 'IDBFactory';\n this.__connections = {};\n }\n IDBFactory.prototype = IDBFactoryAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBFactory();\n};\n\n/**\n * The IndexedDB Method to create a new database and return the DB.\n * @param {string} name\n * @this {IDBFactoryFull}\n * @throws {TypeError} Illegal invocation or no arguments (for database name)\n * @returns {IDBOpenDBRequest}\n */\nIDBFactory.prototype.open = function (name /* , version */) {\n const me = this;\n if (!(me instanceof IDBFactory)) {\n throw new TypeError('Illegal invocation');\n }\n // eslint-disable-next-line prefer-rest-params -- API\n let version = arguments[1];\n\n if (arguments.length === 0) {\n throw new TypeError('Database name is required');\n }\n if (version !== undefined) {\n version = util.enforceRange(version, 'unsigned long long');\n if (version === 0) {\n throw new TypeError('Version cannot be 0');\n }\n }\n if (hasNullOrigin()) {\n throw createDOMException('SecurityError', 'Cannot open an IndexedDB database from an opaque origin.');\n }\n\n const req = IDBOpenDBRequest.__createInstance();\n let calledDbCreateError = false;\n\n if (CFG.autoName && name === '') {\n name = 'autoNamedDatabase_' + nameCounter++;\n }\n name = String(name); // cast to a string\n const sqlSafeName = util.escapeSQLiteStatement(name);\n\n const useMemoryDatabase = typeof CFG.memoryDatabase === 'string';\n const useDatabaseCache = CFG.cacheDatabaseInstances !== false || useMemoryDatabase;\n\n /** @type {string} */\n let escapedDatabaseName;\n // eslint-disable-next-line no-useless-catch -- Possible refactoring\n try {\n escapedDatabaseName = util.escapeDatabaseNameForSQLAndFiles(name);\n // eslint-disable-next-line sonarjs/no-useless-catch -- Possible refactoring\n } catch (err) {\n throw err; // new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.');\n }\n\n /**\n *\n * @param {SQLTransaction|Error|SQLError} tx\n * @param {SQLError} [err]\n * @returns {boolean}\n */\n function dbCreateError (tx, err) {\n if (calledDbCreateError) {\n return false;\n }\n const er = err ? webSQLErrback(err) : /** @type {Error} */ (tx);\n calledDbCreateError = true;\n // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86\n const evt = createEvent('error', er, {bubbles: true, cancelable: true});\n req.__done = true;\n req.__error = er;\n req.__result = undefined; // Must be undefined if an error per `result` getter\n req.dispatchEvent(evt);\n return false;\n }\n\n /**\n *\n * @param {SQLTransaction} tx\n * @param {DatabaseFull} db\n * @param {Integer} oldVersion\n * @returns {void}\n */\n function setupDatabase (tx, db, oldVersion) {\n tx.executeSql('SELECT \"name\", \"keyPath\", \"autoInc\", \"indexList\" FROM __sys__', [], function (tx, data) {\n /**\n * @returns {void}\n */\n function finishRequest () {\n req.__result = connection;\n req.__done = true;\n }\n const connection = IDBDatabase.__createInstance(db, name, oldVersion, version, data);\n if (!me.__connections[name]) {\n me.__connections[name] = [];\n }\n me.__connections[name].push(connection);\n\n if (oldVersion < version) {\n const openConnections = me.__connections[name].slice(0, -1);\n triggerAnyVersionChangeAndBlockedEvents(openConnections, req, oldVersion, version).then(function () {\n // DB Upgrade in progress\n /**\n *\n * @param {SQLTransaction} systx\n * @param {boolean|SQLError|DOMException|Error} err\n * @param {(tx?: SQLTransaction|SQLError, err?: SQLError|SQLResultSet) => boolean} cb\n * @returns {void}\n */\n let sysdbFinishedCb = function (systx, err, cb) {\n if (err) {\n try {\n systx.executeSql('ROLLBACK', [], cb, cb);\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n // Browser may fail with expired transaction above so\n // no choice but to manually revert\n sysdb.transaction(function (systx) {\n /**\n *\n * @param {string} msg\n * @throws {Error}\n * @returns {never}\n */\n function reportError (msg) {\n throw new Error('Unable to roll back upgrade transaction!' + (msg || ''));\n }\n\n // Attempt to revert\n if (oldVersion === 0) {\n systx.executeSql(\n 'DELETE FROM dbVersions WHERE \"name\" = ?',\n [sqlSafeName],\n function () {\n // @ts-expect-error Force to work\n cb(reportError); // eslint-disable-line promise/no-callback-in-promise -- Convenient\n },\n // @ts-expect-error Force to work\n reportError\n );\n } else {\n systx.executeSql(\n 'UPDATE dbVersions SET \"version\" = ? WHERE \"name\" = ?',\n [\n oldVersion, sqlSafeName\n ],\n cb,\n // @ts-expect-error Force to work\n reportError\n );\n }\n });\n }\n return;\n }\n // In browser, should auto-commit\n cb(); // eslint-disable-line promise/no-callback-in-promise -- Convenient\n };\n\n sysdb.transaction(function (systx) {\n /**\n * @returns {void}\n */\n function versionSet () {\n const e = /** @type {import('eventtargeter').EventWithProps & Event & IDBVersionChangeEvent} */ (\n new IDBVersionChangeEvent('upgradeneeded', {oldVersion, newVersion: version})\n );\n req.__result = connection;\n connection.__upgradeTransaction = req.__transaction = req.__result.__versionTransaction = IDBTransaction.__createInstance(req.__result, req.__result.objectStoreNames, 'versionchange');\n req.__done = true;\n\n req.transaction.__addNonRequestToTransactionQueue(function onupgradeneeded (tx, args, finished /* , error */) {\n req.dispatchEvent(e);\n\n if (e.__legacyOutputDidListenersThrowError) {\n logError('Error', 'An error occurred in an upgradeneeded handler attached to request chain', /** @type {Error} */ (e.__legacyOutputDidListenersThrowError)); // We do nothing else with this error as per spec\n req.transaction.__abortTransaction(createDOMException('AbortError', 'A request was aborted.'));\n return;\n }\n finished();\n });\n\n // eslint-disable-next-line camelcase -- Clear API\n req.transaction.on__beforecomplete = function (ev) {\n connection.__upgradeTransaction = null;\n /** @type {import('./IDBDatabase.js').IDBDatabaseFull} */ (\n req.__result\n ).__versionTransaction = null;\n sysdbFinishedCb(systx, false, function () {\n req.transaction.__transFinishedCb(false, function () {\n ev.complete();\n req.__transaction = null;\n });\n return false;\n });\n };\n\n // eslint-disable-next-line camelcase -- Clear API\n req.transaction.on__preabort = function () {\n connection.__upgradeTransaction = null;\n // We ensure any cache is deleted before any request error events fire and try to reopen\n if (useDatabaseCache) {\n if (name in websqlDBCache) {\n delete websqlDBCache[name][version];\n }\n }\n };\n\n // eslint-disable-next-line camelcase -- Clear API\n req.transaction.on__abort = function () {\n req.__transaction = null;\n // `readyState` and `result` will be reset anyways by `dbCreateError` but we follow spec.\n req.__result = undefined;\n req.__done = false;\n\n connection.close();\n setTimeout(() => {\n const err = createDOMException('AbortError', 'The upgrade transaction was aborted.');\n sysdbFinishedCb(systx, err, function (reportError) {\n if (oldVersion === 0) {\n cleanupDatabaseResources(\n me.__openDatabase,\n name,\n escapedDatabaseName,\n dbCreateError.bind(null, err),\n // @ts-expect-error It's ok\n reportError || dbCreateError\n );\n return false;\n }\n dbCreateError(err);\n return false;\n });\n });\n };\n\n // eslint-disable-next-line camelcase -- Clear API\n req.transaction.on__complete = function () {\n const pos = connection.__transactions.indexOf(req.transaction);\n if (pos > -1) {\n connection.__transactions.splice(pos, 1);\n }\n\n if (/** @type {import('./IDBDatabase.js').IDBDatabaseFull} */ (\n req.__result\n ).__closePending) {\n req.__transaction = null;\n const err = createDOMException('AbortError', 'The connection has been closed.');\n dbCreateError(err);\n return;\n }\n // Since this is running directly after `IDBTransaction.complete`,\n // there should be a new task. However, while increasing the\n // timeout 1ms in `IDBTransaction.__executeRequests` can allow\n // `IDBOpenDBRequest.onsuccess` to trigger faster than a new\n // transaction as required by \"transaction-create_in_versionchange\" in\n // w3c/Transaction.js (though still on a timeout separate from this\n // preceding `IDBTransaction.oncomplete`), this causes a race condition\n // somehow with old transactions (e.g., for the Mocha test,\n // in `IDBObjectStore.deleteIndex`, \"should delete an index that was\n // created in a previous transaction\").\n // setTimeout(() => {\n\n finishRequest();\n\n req.__transaction = null;\n const e = createEvent('success');\n req.dispatchEvent(e);\n // });\n };\n }\n\n if (oldVersion === 0) {\n systx.executeSql('INSERT INTO dbVersions VALUES (?,?)', [sqlSafeName, version], versionSet, dbCreateError);\n } else {\n systx.executeSql('UPDATE dbVersions SET \"version\" = ? WHERE \"name\" = ?', [version, sqlSafeName], versionSet, dbCreateError);\n }\n }, dbCreateError, undefined, function (currentTask, err, done, rollback, commit) {\n if (currentTask.readOnly || err) {\n return true;\n }\n sysdbFinishedCb = function (systx, err, cb) {\n if (err) {\n rollback(err, cb);\n } else {\n commit(cb);\n }\n };\n return false;\n });\n return undefined;\n }).catch((err) => {\n console.log('Error within `triggerAnyVersionChangeAndBlockedEvents`');\n throw err;\n });\n } else {\n finishRequest();\n\n const e = createEvent('success');\n req.dispatchEvent(e);\n }\n }, dbCreateError);\n }\n\n /**\n *\n * @param {Integer} oldVersion\n * @returns {void}\n */\n function openDB (oldVersion) {\n /** @type {DatabaseFull} */\n let db;\n if ((useMemoryDatabase || useDatabaseCache) && name in websqlDBCache && websqlDBCache[name][version]) {\n db = websqlDBCache[name][version];\n } else {\n db = me.__openDatabase(\n useMemoryDatabase ? CFG.memoryDatabase : path.join(CFG.databaseBasePath || '', escapedDatabaseName),\n '1',\n name,\n CFG.DEFAULT_DB_SIZE\n );\n if (useDatabaseCache) {\n if (!(name in websqlDBCache)) {\n websqlDBCache[name] = {};\n }\n websqlDBCache[name][version] = db;\n }\n }\n\n if (version === undefined) {\n version = oldVersion || 1;\n }\n if (oldVersion > version) {\n const err = createDOMException('VersionError', 'An attempt was made to open a database using a lower version than the existing version.', version);\n if (useDatabaseCache) {\n setTimeout(() => {\n dbCreateError(err);\n });\n } else {\n dbCreateError(err);\n }\n return;\n }\n\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE IF NOT EXISTS __sys__ (name BLOB, keyPath BLOB, autoInc BOOLEAN, indexList BLOB, currNum INTEGER)', [], function () {\n /**\n * @returns {void}\n */\n function setup () {\n setupDatabase(tx, db, oldVersion);\n }\n if (!CFG.createIndexes) {\n setup();\n return;\n }\n tx.executeSql('CREATE INDEX IF NOT EXISTS sysname ON __sys__(name)', [], setup, dbCreateError);\n }, /** @type {SQLStatementErrorCallback} */ (dbCreateError));\n }, dbCreateError);\n }\n\n addRequestToConnectionQueue(req, name, /* origin */ undefined, function () {\n let latestCachedVersion;\n if (useDatabaseCache) {\n if (!(name in websqlDBCache)) {\n websqlDBCache[name] = {};\n }\n latestCachedVersion = getLatestCachedWebSQLVersion(name);\n }\n if (latestCachedVersion) {\n openDB(latestCachedVersion);\n } else {\n createSysDB(me.__openDatabase, function () {\n sysdb.readTransaction(function (sysReadTx) {\n sysReadTx.executeSql('SELECT \"version\" FROM dbVersions WHERE \"name\" = ?', [sqlSafeName], function (sysReadTx, data) {\n if (data.rows.length === 0) {\n // Database with this name does not exist\n openDB(0);\n } else {\n openDB(data.rows.item(0).version);\n }\n }, dbCreateError);\n }, dbCreateError);\n }, dbCreateError);\n }\n });\n\n return req;\n};\n\n/**\n * Deletes a database.\n * @param {string} name\n * @this {IDBFactoryFull}\n * @returns {IDBOpenDBRequest}\n */\nIDBFactory.prototype.deleteDatabase = function (name) {\n const me = this;\n if (!(me instanceof IDBFactory)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length === 0) {\n throw new TypeError('Database name is required');\n }\n if (hasNullOrigin()) {\n throw createDOMException('SecurityError', 'Cannot delete an IndexedDB database from an opaque origin.');\n }\n\n name = String(name); // cast to a string\n const sqlSafeName = util.escapeSQLiteStatement(name);\n\n /** @type {string} */\n let escapedDatabaseName;\n // eslint-disable-next-line no-useless-catch -- Possible refactoring\n try {\n escapedDatabaseName = util.escapeDatabaseNameForSQLAndFiles(name);\n // eslint-disable-next-line sonarjs/no-useless-catch -- Possible refactoring\n } catch (err) {\n throw err; // throw new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.');\n }\n\n const useMemoryDatabase = typeof CFG.memoryDatabase === 'string';\n const useDatabaseCache = CFG.cacheDatabaseInstances !== false || useMemoryDatabase;\n\n const req = IDBOpenDBRequest.__createInstance();\n let calledDBError = false;\n let version = 0;\n\n /**\n *\n * @param {boolean} err\n * @param {(erred?: boolean) => void} cb\n * @returns {void}\n */\n let sysdbFinishedCbDelete = function (err, cb) {\n cb(err);\n };\n\n // Although the spec has no specific conditions where an error\n // may occur in `deleteDatabase`, it does provide for\n // `UnknownError` as we may require upon a SQL deletion error\n /**\n *\n * @param {SQLTransaction|SQLError|Error} tx\n * @param {SQLError|boolean} [err]\n * @returns {boolean}\n */\n function dbError (tx, err) {\n if (calledDBError || err === true) {\n return false;\n }\n const er = webSQLErrback(/** @type {SQLError} */ (err || tx));\n sysdbFinishedCbDelete(true, function () {\n req.__done = true;\n req.__error = er;\n req.__result = undefined; // Must be undefined if an error per `result` getter\n // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86\n const e = createEvent('error', er, {bubbles: true, cancelable: true});\n req.dispatchEvent(e);\n calledDBError = true;\n });\n return false;\n }\n\n addRequestToConnectionQueue(req, name, /* origin */ undefined, function (req) {\n createSysDB(me.__openDatabase, function () {\n // function callback (cb) { cb(); }\n // callback(function () {\n\n /**\n * @returns {void}\n */\n function completeDatabaseDelete () {\n req.__result = undefined;\n req.__done = true;\n const e = /** @type {Event & IDBVersionChangeEvent} */ (\n new IDBVersionChangeEvent('success', {oldVersion: version, newVersion: null})\n );\n req.dispatchEvent(e);\n }\n\n /** @type {DatabaseDeleted} */\n function databaseDeleted () {\n sysdbFinishedCbDelete(false, function () {\n if (useDatabaseCache && name in websqlDBCache) {\n delete websqlDBCache[name]; // New calls will treat as though never existed\n }\n delete me.__connections[name];\n\n completeDatabaseDelete();\n });\n }\n sysdb.readTransaction(function (sysReadTx) {\n sysReadTx.executeSql('SELECT \"version\" FROM dbVersions WHERE \"name\" = ?', [sqlSafeName], function (sysReadTx, data) {\n if (data.rows.length === 0) {\n completeDatabaseDelete();\n return undefined;\n }\n ({version} = data.rows.item(0));\n\n const openConnections = me.__connections[name] || [];\n triggerAnyVersionChangeAndBlockedEvents(openConnections, req, version, null).then(function () { // eslint-disable-line promise/catch-or-return -- Sync promise\n // Since we need two databases which can't be in a single transaction, we\n // do this deleting from `dbVersions` first since the `__sys__` deleting\n // only impacts file memory whereas this one is critical for avoiding it\n // being found via `open` or `databases`; however, we will\n // avoid committing anyways until all deletions are made and rollback the\n // `dbVersions` change if they fail\n sysdb.transaction(function (systx) {\n systx.executeSql('DELETE FROM dbVersions WHERE \"name\" = ? ', [sqlSafeName], function () {\n // Todo: We should also check whether `dbVersions` is empty and if so, delete upon\n // `deleteDatabaseFiles` config. We also ought to do this when aborting (see\n // above code with `DELETE FROM dbVersions`)\n cleanupDatabaseResources(me.__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError);\n }, dbError);\n }, dbError, undefined, function (currentTask, err, done, rollback, commit) {\n if (currentTask.readOnly || err) {\n return true;\n }\n sysdbFinishedCbDelete = function (err, cb) {\n if (err) {\n rollback(err, cb);\n } else {\n commit(cb);\n }\n };\n return false;\n });\n return undefined;\n // @ts-expect-error It's ok\n }, dbError);\n return undefined;\n }, dbError);\n });\n }, dbError);\n });\n\n return req;\n};\n\n/**\n *\n * @param {import('./Key.js').Key} key1\n * @param {import('./Key.js').Key} key2\n * @throws {TypeError}\n * @returns {number}\n */\nIDBFactory.prototype.cmp = function (key1, key2) {\n if (!(this instanceof IDBFactory)) {\n throw new TypeError('Illegal invocation');\n }\n if (arguments.length < 2) {\n throw new TypeError('You must provide two keys to be compared');\n }\n // We use encoding facilities already built for proper sorting;\n // the following \"conversions\" are for validation only\n Key.convertValueToKeyRethrowingAndIfInvalid(key1);\n Key.convertValueToKeyRethrowingAndIfInvalid(key2);\n return cmp(key1, key2);\n};\n\n/**\n* May return outdated information if a database has since been deleted.\n* @see https://github.com/w3c/IndexedDB/pull/240/files\n* @this {IDBFactoryFull}\n* @returns {Promise<{\n* name: string,\n* version: Integer\n* }[]>}\n*/\nIDBFactory.prototype.databases = function () {\n const me = this;\n let calledDbCreateError = false;\n return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new -- Own polyfill\n if (!(me instanceof IDBFactory)) {\n throw new TypeError('Illegal invocation');\n }\n if (hasNullOrigin()) {\n throw createDOMException('SecurityError', 'Cannot get IndexedDB database names from an opaque origin.');\n }\n /**\n *\n * @param {true|SQLTransaction|SQLError|DOMException|Error} tx\n * @param {SQLError|DOMException|Error} [err]\n * @returns {boolean}\n */\n function dbGetDatabaseNamesError (tx, err) {\n if (calledDbCreateError) {\n return false;\n }\n const er = err ? webSQLErrback(/** @type {SQLError} */ (err)) : tx;\n calledDbCreateError = true;\n reject(er);\n return false;\n }\n createSysDB(me.__openDatabase, function () {\n sysdb.readTransaction(function (sysReadTx) {\n sysReadTx.executeSql('SELECT \"name\", \"version\" FROM dbVersions', [], function (sysReadTx, data) {\n const dbNames = [];\n for (let i = 0; i < data.rows.length; i++) {\n const {name, version} = data.rows.item(i);\n dbNames.push({\n name: util.unescapeSQLiteResponse(name),\n version\n });\n }\n resolve(dbNames);\n }, dbGetDatabaseNamesError);\n }, dbGetDatabaseNamesError);\n }, dbGetDatabaseNamesError);\n });\n};\n\n/**\n* @todo forceClose: Test\n* This is provided to facilitate unit-testing of the\n* closing of a database connection with a forced flag:\n* \n* @param {string} dbName\n* @param {Integer} connIdx\n* @param {string} msg\n* @throws {TypeError}\n* @this {IDBFactoryFull}\n* @returns {void}\n*/\nIDBFactory.prototype.__forceClose = function (dbName, connIdx, msg) {\n const me = this;\n /**\n *\n * @param {import('./IDBDatabase.js').IDBDatabaseFull} conn\n * @returns {void}\n */\n function forceClose (conn) {\n conn.__forceClose(msg);\n }\n if (util.isNullish(dbName)) {\n (Object.values(me.__connections)).forEach((connections) => {\n connections.forEach((connection) => {\n forceClose(connection);\n });\n });\n } else if (!me.__connections[dbName]) {\n console.log('No database connections with that name to force close');\n } else if (util.isNullish(connIdx)) {\n me.__connections[dbName].forEach((conn) => {\n forceClose(conn);\n });\n } else if (!Number.isInteger(connIdx) || connIdx < 0 || connIdx > me.__connections[dbName].length - 1) {\n throw new TypeError(\n 'If providing an argument, __forceClose must be called with a ' +\n 'numeric index to indicate a specific connection to close'\n );\n } else {\n forceClose(me.__connections[dbName][connIdx]);\n }\n};\n\n/**\n *\n * @param {string} [origin]\n * @returns {void}\n */\nIDBFactory.prototype.__setConnectionQueueOrigin = function (origin = getOrigin()) {\n connectionQueue[origin] = {};\n};\n\nIDBFactory.prototype[Symbol.toStringTag] = 'IDBFactoryPrototype';\n\nObject.defineProperty(IDBFactory, 'prototype', {\n writable: false\n});\n\nconst shimIndexedDB = IDBFactory.__createInstance();\nexport {IDBFactory, cmp, shimIndexedDB, setFS};\n","import {IDBRequest} from './IDBRequest.js';\nimport IDBObjectStore from './IDBObjectStore.js';\nimport {createDOMException} from './DOMException.js';\nimport {setSQLForKeyRange, convertValueToKeyRange} from './IDBKeyRange.js';\nimport {cmp} from './IDBFactory.js';\nimport * as util from './util.js';\nimport IDBTransaction from './IDBTransaction.js';\nimport * as Key from './Key.js';\nimport * as Sca from './Sca.js';\nimport IDBIndex from './IDBIndex.js';\nimport CFG from './CFG.js';\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {IDBCursor & {\n * primaryKey: import('./Key.js').Key,\n * key: import('./Key.js').Key,\n * direction: string,\n * source: import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull,\n * __request: import('./IDBRequest.js').IDBRequestFull,\n * __advanceCount: Integer|undefined,\n * __indexSource: boolean,\n * __key: import('./Key.js').Key,\n * __primaryKey: import('./Key.js').Key,\n * __value: import('./Key.js').Value,\n * __store: import('./IDBObjectStore.js').IDBObjectStoreFull,\n * __range: import('./IDBKeyRange.js').IDBKeyRangeFull|undefined,\n * __keyColumnName: string,\n * __valueColumnName: string,\n * __keyOnly: boolean,\n * __valueDecoder: {\n * decode: (str: string) => any,\n * },\n * __count: boolean,\n * __prefetchedIndex: Integer,\n * __prefetchedData: null|SQLResultSetRowList|{\n * data: RowItemNonNull[],\n * length: Integer,\n * item: (index: Integer) => RowItemNonNull\n * },\n * __multiEntryIndex: boolean,\n * __unique: boolean,\n * __sqlDirection: \"DESC\"|\"ASC\",\n * __matchedKeys: {[key: string]: true},\n * __invalidateCache: () => void\n * }} IDBCursorFull\n */\n\n/**\n * @typedef {IDBCursorFull & {\n * __request: import('./IDBRequest.js').IDBRequestFull,\n * }} IDBCursorWithValueFull\n */\n\n/**\n * @class\n */\nfunction IDBCursor () {\n throw new TypeError('Illegal constructor');\n}\nconst IDBCursorAlias = IDBCursor;\n\n/* eslint-disable func-name-matching -- API */\n/**\n * The IndexedDB Cursor Object.\n * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursor\n * @param {IDBKeyRange} query\n * @param {string} direction\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store\n * @param {import('./IDBObjectStore.js').IDBObjectStoreFull|\n * import('./IDBIndex.js').IDBIndexFull} source\n * @param {string} keyColumnName\n * @param {string} valueColumnName\n * @param {boolean} count\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.__super = function IDBCursor (query, direction, store, source, keyColumnName, valueColumnName, count) {\n /* eslint-enable func-name-matching -- API */\n // @ts-expect-error Should be ok\n this[Symbol.toStringTag] = 'IDBCursor';\n util.defineReadonlyProperties(this, ['key', 'primaryKey', 'request']);\n IDBObjectStore.__invalidStateIfDeleted(store);\n this.__indexSource = util.instanceOf(source, IDBIndex);\n if (this.__indexSource) {\n IDBIndex.__invalidStateIfDeleted(\n /** @type {import('./IDBIndex.js').IDBIndexFull} */ (source)\n );\n }\n IDBTransaction.__assertActive(store.transaction);\n const range = convertValueToKeyRange(query);\n if (direction !== undefined && !(['next', 'prev', 'nextunique', 'prevunique'].includes(direction))) {\n throw new TypeError(direction + 'is not a valid cursor direction');\n }\n\n Object.defineProperties(this, {\n // Babel is not respecting default writable false here, so make explicit\n source: {writable: false, value: source},\n direction: {writable: false, value: direction || 'next'}\n });\n this.__key = undefined;\n this.__primaryKey = undefined;\n\n this.__store = store;\n this.__range = range;\n this.__request = IDBRequest.__createInstance();\n this.__request.__source = source;\n this.__request.__transaction = this.__store.transaction;\n this.__keyColumnName = keyColumnName;\n this.__valueColumnName = valueColumnName;\n this.__keyOnly = valueColumnName === 'key';\n this.__valueDecoder = this.__keyOnly ? Key : Sca;\n this.__count = count;\n this.__prefetchedIndex = -1;\n this.__multiEntryIndex = this.__indexSource\n ? 'multiEntry' in source && source.multiEntry\n : false;\n this.__unique = this.direction.includes('unique');\n this.__sqlDirection = ['prev', 'prevunique'].includes(this.direction) ? 'DESC' : 'ASC';\n\n if (range !== undefined) {\n // Encode the key range and cache the encoded values, so we don't have to re-encode them over and over\n range.__lowerCached = range.lower !== undefined && Key.encode(range.lower, this.__multiEntryIndex);\n range.__upperCached = range.upper !== undefined && Key.encode(range.upper, this.__multiEntryIndex);\n }\n this.__gotValue = true;\n this.continue();\n};\n\n/**\n *\n * @param {...any} args\n * @returns {IDBCursorFull}\n */\nIDBCursor.__createInstance = function (...args) {\n const IDBCursor = IDBCursorAlias.__super;\n IDBCursor.prototype = IDBCursorAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBCursor(...args);\n};\n\n/**\n *\n * @param {...any} args\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__find = function (...args /* key, tx, success, error, recordsToLoad */) {\n if (this.__multiEntryIndex) {\n const [key, primaryKey, tx, success, error] = args;\n this.__findMultiEntry(key, primaryKey, tx, success, error);\n } else {\n const [key, primaryKey, tx, success, error, recordsToLoad] = args;\n this.__findBasic(key, primaryKey, tx, success, error, recordsToLoad);\n }\n};\n\n/**\n * @typedef {(\n * k: import('./Key.js').Key,\n * val: import('./Key.js').Value,\n * primKey: import('./Key.js').Key\n * ) => void} KeySuccess\n */\n\n/**\n * @typedef {(tx: SQLTransaction|Error|DOMException|SQLError, err?: SQLError) => void} FindError\n */\n\n/**\n *\n * @param {undefined|import('./Key.js').Key} key\n * @param {undefined|import('./Key.js').Key} primaryKey\n * @param {SQLTransaction} tx\n * @param {KeySuccess} success\n * @param {FindError} error\n * @param {Integer|undefined} recordsToLoad\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__findBasic = function (key, primaryKey, tx, success, error, recordsToLoad) {\n const continueCall = recordsToLoad !== undefined;\n recordsToLoad = recordsToLoad || 1;\n\n const me = this;\n const quotedKeyColumnName = util.sqlQuote(me.__keyColumnName);\n const quotedKey = util.sqlQuote('key');\n const sql = ['SELECT * FROM', util.escapeStoreNameForSQL(me.__store.__currentName)];\n\n /** @type {string[]} */\n const sqlValues = [];\n sql.push('WHERE', quotedKeyColumnName, 'NOT NULL');\n setSQLForKeyRange(me.__range, quotedKeyColumnName, sql, sqlValues, true, true);\n\n // Determine the ORDER BY direction based on the cursor.\n const direction = me.__sqlDirection;\n const op = direction === 'ASC' ? '>' : '<';\n\n if (primaryKey !== undefined) {\n sql.push('AND', quotedKey, op + '= ?');\n // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey`\n sqlValues.push(/** @type {string} */ (Key.encode(primaryKey)));\n }\n if (key !== undefined) {\n sql.push('AND', quotedKeyColumnName, op + '= ?');\n // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey`\n sqlValues.push(/** @type {string} */ (Key.encode(key)));\n } else if (continueCall && me.__key !== undefined) {\n sql.push('AND', quotedKeyColumnName, op + ' ?');\n // Key.convertValueToKey(me.__key); // Already checked when stored\n sqlValues.push(/** @type {string} */ (Key.encode(me.__key)));\n }\n\n if (!me.__count) {\n // 1. Sort by key\n sql.push('ORDER BY', quotedKeyColumnName, direction);\n\n if (me.__keyColumnName !== 'key') { // Avoid adding 'key' twice\n if (!me.__unique) {\n // 2. Sort by primaryKey (if defined and not unique)\n // 3. Sort by position (if defined)\n sql.push(',', quotedKey, direction);\n } else if (me.direction === 'prevunique') {\n // Sort by first record with key matching\n sql.push(',', quotedKey, 'ASC');\n }\n }\n\n if (!me.__unique && me.__indexSource) {\n // 4. Sort by object store position (if defined and not unique)\n sql.push(',', util.sqlQuote(me.__valueColumnName), direction);\n }\n sql.push('LIMIT', String(recordsToLoad));\n }\n const sqlStr = sql.join(' ');\n if (CFG.DEBUG) { console.log(sqlStr, sqlValues); }\n\n tx.executeSql(sqlStr, sqlValues, function (tx, data) {\n if (me.__count) {\n success(undefined, data.rows.length, undefined);\n } else if (data.rows.length > 1) {\n me.__prefetchedIndex = 0;\n me.__prefetchedData = data.rows;\n if (CFG.DEBUG) { console.log('Preloaded ' + me.__prefetchedData.length + ' records for cursor'); }\n me.__decode(data.rows.item(0), success);\n } else if (data.rows.length === 1) {\n me.__decode(data.rows.item(0), success);\n } else {\n if (CFG.DEBUG) { console.log('Reached end of cursors'); }\n success(undefined, undefined, undefined);\n }\n }, function (tx, err) {\n if (CFG.DEBUG) { console.log('Could not execute Cursor.continue', sqlStr, sqlValues); }\n error(err);\n return false;\n });\n};\n\nconst leftBracketRegex = /\\[/gu;\n\n/**\n *\n * @param {undefined|import('./Key.js').Key} key\n * @param {undefined|import('./Key.js').Key} primaryKey\n * @param {SQLTransaction} tx\n * @param {KeySuccess} success\n * @param {FindError} error\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__findMultiEntry = function (key, primaryKey, tx, success, error) {\n const me = this;\n\n if (me.__prefetchedData && me.__prefetchedData.length === me.__prefetchedIndex) {\n if (CFG.DEBUG) { console.log('Reached end of multiEntry cursor'); }\n success(undefined, undefined, undefined);\n return;\n }\n\n const quotedKeyColumnName = util.sqlQuote(me.__keyColumnName);\n const sql = ['SELECT * FROM', util.escapeStoreNameForSQL(me.__store.__currentName)];\n /** @type {string[]} */\n const sqlValues = [];\n sql.push('WHERE', quotedKeyColumnName, 'NOT NULL');\n if (me.__range && (me.__range.lower !== undefined && Array.isArray(me.__range.upper))) {\n if (me.__range.upper.indexOf(me.__range.lower) === 0) {\n sql.push('AND', quotedKeyColumnName, \"LIKE ? ESCAPE '^'\");\n sqlValues.push(\n '%' + util.sqlLIKEEscape(\n /** @type {string} */ (me.__range.__lowerCached).slice(0, -1)\n ) + '%'\n );\n }\n }\n\n // Determine the ORDER BY direction based on the cursor.\n const direction = me.__sqlDirection;\n const op = direction === 'ASC' ? '>' : '<';\n const quotedKey = util.sqlQuote('key');\n\n if (primaryKey !== undefined) {\n sql.push('AND', quotedKey, op + '= ?');\n // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey`\n sqlValues.push(/** @type {string} */ (Key.encode(primaryKey)));\n }\n if (key !== undefined) {\n sql.push('AND', quotedKeyColumnName, op + '= ?');\n // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey`\n sqlValues.push(/** @type {string} */ (Key.encode(key)));\n } else if (me.__key !== undefined) {\n sql.push('AND', quotedKeyColumnName, op + ' ?');\n // Key.convertValueToKey(me.__key); // Already checked when entered\n sqlValues.push(/** @type {string} */ (Key.encode(me.__key)));\n }\n\n if (!me.__count) {\n // 1. Sort by key\n sql.push('ORDER BY', quotedKeyColumnName, direction);\n\n // 2. Sort by primaryKey (if defined and not unique)\n if (!me.__unique && me.__keyColumnName !== 'key') { // Avoid adding 'key' twice\n sql.push(',', util.sqlQuote('key'), direction);\n }\n\n // 3. Sort by position (if defined)\n\n if (!me.__unique && me.__indexSource) {\n // 4. Sort by object store position (if defined and not unique)\n sql.push(',', util.sqlQuote(me.__valueColumnName), direction);\n }\n }\n const sqlStr = sql.join(' ');\n if (CFG.DEBUG) { console.log(sqlStr, sqlValues); }\n\n tx.executeSql(sqlStr, sqlValues, function (tx, data) {\n if (data.rows.length > 0) {\n if (me.__count) { // Avoid caching and other processing below\n let ct = 0;\n for (let i = 0; i < data.rows.length; i++) {\n const rowItem = data.rows.item(i);\n const rowKey = Key.decode(rowItem[me.__keyColumnName], true);\n const matches = Key.findMultiEntryMatches(rowKey, me.__range);\n ct += matches.length;\n }\n success(undefined, ct, undefined);\n return;\n }\n const rows = [];\n for (let i = 0; i < data.rows.length; i++) {\n const rowItem = data.rows.item(i);\n const rowKey = Key.decode(rowItem[me.__keyColumnName], true);\n const matches = Key.findMultiEntryMatches(rowKey, me.__range);\n\n for (const matchingKey of matches) {\n /**\n * @type {RowItemNonNull}\n */\n const clone = {\n matchingKey: /** @type {string} */ (\n Key.encode(matchingKey, true)\n ),\n key: rowItem.key\n };\n clone[me.__keyColumnName] = rowItem[me.__keyColumnName];\n clone[me.__valueColumnName] = rowItem[me.__valueColumnName];\n rows.push(clone);\n }\n }\n const reverse = me.direction.indexOf('prev') === 0;\n rows.sort(function (a, b) {\n if (a.matchingKey.replaceAll(leftBracketRegex, 'z') < b.matchingKey.replaceAll(leftBracketRegex, 'z')) {\n return reverse ? 1 : -1;\n }\n if (a.matchingKey.replaceAll(leftBracketRegex, 'z') > b.matchingKey.replaceAll(leftBracketRegex, 'z')) {\n return reverse ? -1 : 1;\n }\n if (a.key < b.key) {\n return me.direction === 'prev' ? 1 : -1;\n }\n if (a.key > b.key) {\n return me.direction === 'prev' ? -1 : 1;\n }\n return 0;\n });\n\n if (rows.length > 1) {\n me.__prefetchedIndex = 0;\n me.__prefetchedData = {\n data: rows,\n length: rows.length,\n /**\n * @param {Integer} index\n * @returns {RowItemNonNull}\n */\n item (index) {\n return this.data[index];\n }\n };\n if (CFG.DEBUG) { console.log('Preloaded ' + me.__prefetchedData.length + ' records for multiEntry cursor'); }\n me.__decode(rows[0], success);\n } else if (rows.length === 1) {\n if (CFG.DEBUG) { console.log('Reached end of multiEntry cursor'); }\n me.__decode(rows[0], success);\n } else {\n if (CFG.DEBUG) { console.log('Reached end of multiEntry cursor'); }\n success(undefined, undefined, undefined);\n }\n } else {\n if (CFG.DEBUG) { console.log('Reached end of multiEntry cursor'); }\n success(undefined, undefined, undefined);\n }\n }, function (tx, err) {\n if (CFG.DEBUG) { console.log('Could not execute Cursor.continue', sqlStr, sqlValues); }\n error(err);\n return false;\n });\n};\n\n/**\n * @typedef {any} StructuredCloneValue\n */\n\n/**\n * @typedef {any} IndexedDBKey\n */\n\n/**\n* @callback SuccessArg\n* @param {StructuredCloneValue} value\n* @param {import('./IDBRequest.js').IDBRequestFull} req\n* @returns {void}\n*/\n\n/**\n* @callback SuccessCallback\n* @param {IndexedDBKey} key\n* @param {StructuredCloneValue} value\n* @param {IndexedDBKey} primaryKey\n* @returns {void}\n*/\n\n/**\n * Creates an \"onsuccess\" callback.\n * @param {SuccessArg} success\n * @this {IDBCursorFull}\n * @returns {SuccessCallback}\n */\nIDBCursor.prototype.__onsuccess = function (success) {\n const me = this;\n return function (key, value, primaryKey) {\n if (me.__count) {\n success(value, me.__request);\n } else {\n if (key !== undefined) {\n me.__gotValue = true;\n }\n me.__key = key === undefined ? null : key;\n me.__primaryKey = primaryKey === undefined ? null : primaryKey;\n me.__value = value === undefined ? null : value;\n const result = key === undefined ? null : me;\n success(result, me.__request);\n }\n };\n};\n\n/**\n * @typedef {{\n* matchingKey: string,\n* key: string,\n* [k: string]: string\n* }} RowItemNonNull\n*/\n\n/**\n *\n * @param {RowItemNonNull} rowItem\n * @param {(\n * key: import('./Key.js').Key,\n * val: import('./Key.js').Value,\n * primaryKey: import('./Key.js').Key,\n * encKey?: string\n * ) => void} callback\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__decode = function (rowItem, callback) {\n const me = this;\n if (me.__multiEntryIndex && me.__unique) {\n if (!me.__matchedKeys) {\n me.__matchedKeys = {};\n }\n if (me.__matchedKeys[rowItem.matchingKey]) {\n callback(undefined, undefined, undefined);\n return;\n }\n me.__matchedKeys[rowItem.matchingKey] = true;\n }\n const encKey = util.unescapeSQLiteResponse(\n me.__multiEntryIndex\n ? rowItem.matchingKey\n : rowItem[me.__keyColumnName]\n );\n const encVal = util.unescapeSQLiteResponse(rowItem[me.__valueColumnName]);\n const encPrimaryKey = util.unescapeSQLiteResponse(rowItem.key);\n\n const key = Key.decode(\n encKey,\n me.__multiEntryIndex\n );\n const val = me.__valueDecoder.decode(encVal);\n const primaryKey = Key.decode(encPrimaryKey);\n callback(key, val, primaryKey, encKey /* , encVal, encPrimaryKey */);\n};\n\n/**\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__sourceOrEffectiveObjStoreDeleted = function () {\n IDBObjectStore.__invalidStateIfDeleted(this.__store, \"The cursor's effective object store has been deleted\");\n if (this.__indexSource) {\n IDBIndex.__invalidStateIfDeleted(\n /** @type {import('./IDBIndex.js').IDBIndexFull} */ (this.source),\n \"The cursor's index source has been deleted\"\n );\n }\n};\n\n/**\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__invalidateCache = function () {\n // @ts-expect-error Why is this not being found?\n this.__prefetchedData = null;\n};\n\n/**\n *\n * @param {import('./Key.js').Key} [key]\n * @param {boolean} [advanceContinue]\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__continue = function (key, advanceContinue) {\n const me = this;\n const advanceState = me.__advanceCount !== undefined;\n IDBTransaction.__assertActive(me.__store.transaction);\n me.__sourceOrEffectiveObjStoreDeleted();\n if (!me.__gotValue && !advanceContinue) {\n throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.');\n }\n if (key !== undefined) {\n Key.convertValueToKeyRethrowingAndIfInvalid(key);\n const cmpResult = cmp(key, me.key);\n if (cmpResult === 0 ||\n (me.direction.includes('next') && cmpResult === -1) ||\n (me.direction.includes('prev') && cmpResult === 1)\n ) {\n throw createDOMException('DataError', 'Cannot ' + (advanceState ? 'advance' : 'continue') + ' the cursor in an unexpected direction');\n }\n }\n this.__continueFinish(key, undefined, advanceState);\n};\n\n/**\n *\n * @param {import('./Key.js').Key} key\n * @param {import('./Key.js').Key} primaryKey\n * @param {boolean} advanceState\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.__continueFinish = function (key, primaryKey, advanceState) {\n const me = this;\n const recordsToPreloadOnContinue = me.__advanceCount || CFG.cursorPreloadPackSize || 100;\n me.__gotValue = false;\n me.__request.__done = false;\n\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.__store.transaction\n ).__pushToQueue(me.__request, function cursorContinue (tx, args, success, error, executeNextRequest) {\n /**\n * @param {import('./Key.js').Key} k\n * @param {import('./Key.js').Value} val\n * @param {import('./Key.js').Key} primKey\n * @returns {void}\n */\n function triggerSuccess (k, val, primKey) {\n if (advanceState) {\n if (me.__advanceCount && me.__advanceCount >= 2 && k !== undefined) {\n me.__advanceCount--;\n me.__key = k;\n me.__continue(undefined, true);\n /** @type {() => void} */ (\n executeNextRequest\n )(); // We don't call success yet but do need to advance the transaction queue\n return;\n }\n me.__advanceCount = undefined;\n }\n me.__onsuccess(success)(k, val, primKey);\n }\n if (me.__prefetchedData) {\n // We have pre-loaded data for the cursor\n me.__prefetchedIndex++;\n if (me.__prefetchedIndex < me.__prefetchedData.length) {\n me.__decode(me.__prefetchedData.item(me.__prefetchedIndex), function (k, val, primKey, encKey) {\n /**\n * @returns {void}\n */\n function checkKey () {\n const cmpResult = Number(key === undefined) || cmp(k, key);\n if (cmpResult > 0 || (\n cmpResult === 0 && (\n me.__unique || primaryKey === undefined || cmp(primKey, primaryKey) >= 0\n )\n )) {\n triggerSuccess(k, val, primKey);\n return;\n }\n cursorContinue(tx, args, success, error);\n }\n if (me.__unique && !me.__multiEntryIndex &&\n encKey === Key.encode(me.key, me.__multiEntryIndex)) {\n cursorContinue(tx, args, success, error);\n return;\n }\n checkKey();\n });\n return;\n }\n }\n\n // No (or not enough) pre-fetched data, do query\n me.__find(\n key, primaryKey, tx, triggerSuccess,\n /** @type {FindError} */\n function (...args) {\n me.__advanceCount = undefined;\n const [t, err] = args;\n error(t, err);\n }, recordsToPreloadOnContinue\n );\n });\n};\n\n/**\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.continue = function (/* key */) {\n // eslint-disable-next-line prefer-rest-params -- API\n this.__continue(arguments[0]);\n};\n\n/**\n *\n * @param {import('./Key.js').Key} key\n * @param {import('./Key.js').Key} primaryKey\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.continuePrimaryKey = function (key, primaryKey) {\n const me = this;\n IDBTransaction.__assertActive(me.__store.transaction);\n me.__sourceOrEffectiveObjStoreDeleted();\n if (!me.__indexSource) {\n throw createDOMException('InvalidAccessError', '`continuePrimaryKey` may only be called on an index source.');\n }\n if (!['next', 'prev'].includes(me.direction)) {\n throw createDOMException('InvalidAccessError', '`continuePrimaryKey` may not be called with unique cursors.');\n }\n if (!me.__gotValue) {\n throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.');\n }\n Key.convertValueToKeyRethrowingAndIfInvalid(key);\n Key.convertValueToKeyRethrowingAndIfInvalid(primaryKey);\n\n const cmpResult = cmp(key, me.key);\n if (\n (me.direction === 'next' && cmpResult === -1) ||\n (me.direction === 'prev' && cmpResult === 1)\n ) {\n throw createDOMException('DataError', 'Cannot continue the cursor in an unexpected direction');\n }\n\n /**\n * @returns {void}\n */\n function noErrors () {\n me.__continueFinish(key, primaryKey, false);\n }\n if (cmpResult === 0) {\n Sca.encode(primaryKey, function (encPrimaryKey) {\n Sca.encode(me.primaryKey, function (encObjectStorePos) {\n if (encPrimaryKey === encObjectStorePos ||\n (me.direction === 'next' && encPrimaryKey < encObjectStorePos) ||\n (me.direction === 'prev' && encPrimaryKey > encObjectStorePos)\n ) {\n throw createDOMException('DataError', 'Cannot continue the cursor in an unexpected direction');\n }\n noErrors();\n });\n });\n } else {\n noErrors();\n }\n};\n\n/**\n *\n * @param {Integer} count\n * @this {IDBCursorFull}\n * @returns {void}\n */\nIDBCursor.prototype.advance = function (count) {\n const me = this;\n count = util.enforceRange(count, 'unsigned long');\n if (count === 0) {\n throw new TypeError('Calling advance() with count argument 0');\n }\n if (me.__gotValue) { // Only set the count if not running in error (otherwise will override earlier good advance calls)\n me.__advanceCount = count;\n }\n me.__continue();\n};\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n *\n * @param {AnyValue} valueToUpdate\n * @this {IDBCursorFull}\n * @returns {IDBRequest}\n */\nIDBCursor.prototype.update = function (valueToUpdate) {\n const me = this;\n if (!arguments.length) {\n throw new TypeError('A value must be passed to update()');\n }\n IDBTransaction.__assertActive(me.__store.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.__store.transaction\n ).__assertWritable();\n me.__sourceOrEffectiveObjStoreDeleted();\n if (!me.__gotValue) {\n throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.');\n }\n if (me.__keyOnly) {\n throw createDOMException('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.');\n }\n const request = /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.__store.transaction\n ).__createRequest(me);\n const key = me.primaryKey;\n\n /**\n * @param {import('./Key.js').Value} clonedValue\n * @returns {void}\n */\n function addToQueue (clonedValue) {\n // We set the `invalidateCache` argument to `false` since the old value shouldn't be accessed\n IDBObjectStore.__storingRecordObjectStore(request, me.__store, false, clonedValue, false, key);\n }\n if (me.__store.keyPath !== null) {\n const [evaluatedKey, clonedValue] = me.__store.__validateKeyAndValueAndCloneValue(valueToUpdate, undefined, true);\n if (cmp(me.primaryKey, evaluatedKey) !== 0) {\n throw createDOMException('DataError', 'The key of the supplied value to `update` is not equal to the cursor\\'s effective key');\n }\n addToQueue(clonedValue);\n } else {\n const clonedValue = Sca.clone(valueToUpdate);\n addToQueue(clonedValue);\n }\n return request;\n};\n\n/**\n * @this {IDBCursorFull}\n * @returns {IDBRequest}\n */\nIDBCursor.prototype.delete = function () {\n const me = this;\n IDBTransaction.__assertActive(me.__store.transaction);\n /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n me.__store.transaction\n ).__assertWritable();\n me.__sourceOrEffectiveObjStoreDeleted();\n if (!me.__gotValue) {\n throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.');\n }\n if (me.__keyOnly) {\n throw createDOMException('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.');\n }\n return /** @type {import('./IDBTransaction.js').IDBTransactionFull} */ (\n this.__store.transaction\n ).__addToTransactionQueue(function cursorDelete (tx, args, success, error) {\n me.__find(\n undefined, undefined, tx,\n /** @type {KeySuccess} */\n function (key, value, primaryKey) {\n const sql = 'DELETE FROM ' + util.escapeStoreNameForSQL(me.__store.__currentName) + ' WHERE \"key\" = ?';\n if (CFG.DEBUG) { console.log(sql, key, primaryKey); }\n // Key.convertValueToKey(primaryKey); // Already checked when entered\n tx.executeSql(sql, [util.escapeSQLiteStatement(\n /** @type {string} */ (Key.encode(primaryKey))\n )], function (tx, data) {\n if (data.rowsAffected === 1) {\n // We don't invalidate the cache (as we don't access it anymore\n // and it will set the index off)\n success(undefined);\n } else {\n // @ts-expect-error Apparently ok\n error('No rows with key found' + key);\n }\n }, function (tx, data) {\n error(data);\n return false;\n });\n }, error\n );\n }, undefined, me);\n};\n\nIDBCursor.prototype[Symbol.toStringTag] = 'IDBCursorPrototype';\n\nutil.defineReadonlyOuterInterface(\n IDBCursor.prototype,\n ['source', 'direction', 'key', 'primaryKey', 'request']\n);\nObject.defineProperty(IDBCursor, 'prototype', {\n writable: false\n});\n\n/**\n * @class\n */\nfunction IDBCursorWithValue () {\n throw new TypeError('Illegal constructor');\n}\n\n// @ts-expect-error It's ok\nIDBCursorWithValue.prototype = Object.create(IDBCursor.prototype);\nObject.defineProperty(IDBCursorWithValue.prototype, 'constructor', {\n enumerable: false,\n writable: true,\n configurable: true,\n value: IDBCursorWithValue\n});\n\nconst IDBCursorWithValueAlias = IDBCursorWithValue;\n/**\n *\n * @param {...any} args\n * @returns {IDBCursorWithValueFull}\n */\nIDBCursorWithValue.__createInstance = function (...args) {\n /**\n * @class\n * @this {IDBCursorWithValueFull}\n */\n function IDBCursorWithValue () {\n const [query, direction, store, source, keyColumnName, valueColumnName, count] = args;\n IDBCursor.__super.call(this, query, direction, store, source, keyColumnName, valueColumnName, count);\n // @ts-expect-error It's ok\n this[Symbol.toStringTag] = 'IDBCursorWithValue';\n util.defineReadonlyProperties(this, 'value');\n }\n IDBCursorWithValue.prototype = IDBCursorWithValueAlias.prototype;\n\n // @ts-expect-error It's ok\n return new IDBCursorWithValue();\n};\n\nutil.defineReadonlyOuterInterface(IDBCursorWithValue.prototype, ['value']);\n\nIDBCursorWithValue.prototype[Symbol.toStringTag] = 'IDBCursorWithValuePrototype';\n\nObject.defineProperty(IDBCursorWithValue, 'prototype', {\n writable: false\n});\n\nexport {IDBCursor, IDBCursorWithValue};\n","import {setPrototypeOfCustomEvent} from 'eventtargeter';\nimport shimIDBVersionChangeEvent from './IDBVersionChangeEvent.js';\nimport {IDBCursor as shimIDBCursor, IDBCursorWithValue as shimIDBCursorWithValue} from './IDBCursor.js';\nimport {IDBRequest as shimIDBRequest, IDBOpenDBRequest as shimIDBOpenDBRequest} from './IDBRequest.js';\nimport {createDOMException, ShimDOMException} from './DOMException.js';\nimport {shimIndexedDB, IDBFactory, setFS} from './IDBFactory.js';\nimport DOMStringList from './DOMStringList.js';\nimport {ShimEvent, ShimCustomEvent, ShimEventTarget} from './Event.js';\nimport {register} from './Sca.js';\nimport shimIDBKeyRange from './IDBKeyRange.js';\nimport shimIDBObjectStore from './IDBObjectStore.js';\nimport shimIDBIndex from './IDBIndex.js';\nimport shimIDBTransaction from './IDBTransaction.js';\nimport shimIDBDatabase from './IDBDatabase.js';\nimport CFG from './CFG.js';\nimport {isNullish} from './util.js';\n\n/**\n * @typedef {any} AnyValue\n */\n\n/**\n * @callback SetConfig\n * @param {import('./CFG.js').KeyofConfigValues|\n * Partial} prop\n * @param {AnyValue} [val]\n * @throws {Error}\n * @returns {void}\n */\n\n/** @type {SetConfig} */\nfunction setConfig (prop, val) {\n if (prop && typeof prop === 'object') {\n Object.entries(prop).forEach(([p, val]) => {\n setConfig(\n /** @type {import('./CFG.js').KeyofConfigValues} */\n (p),\n val\n );\n });\n return;\n }\n if (!(prop in CFG)) {\n throw new Error(prop + ' is not a valid configuration property');\n }\n // @ts-expect-error Should not be `never` here!\n CFG[prop] = val;\n if (prop === 'registerSCA' && typeof val === 'function') {\n register(\n /**\n * @type {(\n * preset: import('typeson').Preset\n * ) => import('typeson').Preset}\n */ (\n val\n )\n );\n }\n}\n\n/**\n * @typedef {(\n * prop: import('./CFG.js').KeyofConfigValues\n * ) => import('./CFG.js').ConfigValue} GetConfig\n */\n\n/**\n * @typedef {(cfg: {\n * UnicodeIDStart: string,\n * UnicodeIDContinue: string\n * }) => void} SetUnicodeIdentifiers\n */\n\n/**\n * @typedef {(IDBFactory|object) & {\n * __useShim: () => void,\n * __debug: (val: boolean) => void,\n * __setConfig: SetConfig,\n * __getConfig: GetConfig,\n * __setUnicodeIdentifiers: SetUnicodeIdentifiers,\n * __setConnectionQueueOrigin: (origin?: string) => void\n * }} ShimIndexedDB\n */\n\n/**\n * @typedef {number} Integer\n */\n\n/**\n * @typedef {(typeof globalThis|object) & {\n * indexedDB?: Partial,\n * IDBFactory: typeof IDBFactory,\n * IDBOpenDBRequest: typeof IDBOpenDBRequest,\n * IDBRequest: typeof IDBRequest,\n * IDBCursorWithValue: typeof IDBCursorWithValue,\n * IDBCursor: typeof IDBCursor,\n * IDBDatabase: typeof IDBDatabase,\n * IDBTransaction: typeof IDBTransaction,\n * IDBKeyRange: typeof IDBKeyRange,\n * shimIndexedDB?: ShimIndexedDB\n * }} ShimmedObject\n */\n\n/**\n *\n * @param {ShimmedObject} [idb]\n * @param {import('./CFG.js').ConfigValues} [initialConfig]\n * @returns {ShimmedObject}\n */\nfunction setGlobalVars (idb, initialConfig) {\n if (initialConfig) {\n setConfig(initialConfig);\n }\n const IDB = idb || globalThis || {};\n /**\n * @typedef {any} AnyClass\n */\n /**\n * @typedef {any} AnyValue\n */\n /**\n * @typedef {Function} AnyFunction\n */\n /**\n * @param {string} name\n * @param {AnyClass} value\n * @param {PropertyDescriptor & {\n * shimNS?: object\n * }|undefined} [propDesc]\n * @returns {void}\n */\n function shim (name, value, propDesc) {\n if (!propDesc || !Object.defineProperty) {\n try {\n // Try setting the property. This will fail if the property is read-only.\n // @ts-expect-error It's ok\n IDB[name] = value;\n } catch (e) {\n console.log(e);\n }\n }\n if (\n // @ts-expect-error It's ok\n IDB[name] !== value &&\n Object.defineProperty\n ) {\n // Setting a read-only property failed, so try re-defining the property\n try {\n let desc = propDesc || {};\n if (!('get' in desc)) {\n if (!('value' in desc)) {\n desc.value = value;\n }\n if (!('writable' in desc)) {\n desc.writable = true;\n }\n } else {\n const o = {\n /**\n * @returns {AnyValue}\n */\n get [name] () {\n return /** @type {AnyFunction} */ (\n /** @type {PropertyDescriptor} */ (\n propDesc\n ).get\n ).call(this);\n }\n };\n desc = /** @type {PropertyDescriptor} */ (\n Object.getOwnPropertyDescriptor(o, name)\n );\n }\n Object.defineProperty(IDB, name, desc);\n // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup\n } catch (err) {\n // With `indexedDB`, PhantomJS fails here and below but\n // not above, while Chrome is reverse (and Firefox doesn't\n // get here since no WebSQL to use for shimming)\n }\n }\n\n // @ts-expect-error It's ok\n if (IDB[name] !== value) {\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('Unable to shim ' + name);\n }\n }\n }\n if (CFG.win.openDatabase !== undefined) {\n shim('shimIndexedDB', shimIndexedDB, {\n enumerable: false,\n configurable: true\n });\n }\n if ('shimIndexedDB' in IDB && IDB.shimIndexedDB) {\n IDB.shimIndexedDB.__useShim = function () {\n /**\n *\n * @param {\"Shim\"|\"\"} [prefix]\n * @returns {void}\n */\n function setNonIDBGlobals (prefix = '') {\n shim(prefix + 'DOMException', ShimDOMException);\n shim(prefix + 'DOMStringList', DOMStringList, {\n enumerable: false,\n configurable: true,\n writable: true,\n value: DOMStringList\n });\n shim(prefix + 'Event', ShimEvent, {\n configurable: true,\n writable: true,\n value: ShimEvent,\n enumerable: false\n });\n shim(prefix + 'CustomEvent', ShimCustomEvent, {\n configurable: true,\n writable: true,\n value: ShimCustomEvent,\n enumerable: false\n });\n shim(prefix + 'EventTarget', ShimEventTarget, {\n configurable: true,\n writable: true,\n value: ShimEventTarget,\n enumerable: false\n });\n }\n const shimIDBFactory = IDBFactory;\n if (CFG.win.openDatabase !== undefined) {\n shimIndexedDB.__openDatabase = CFG.win.openDatabase.bind(CFG.win); // We cache here in case the function is overwritten later as by the IndexedDB support promises tests\n // Polyfill ALL of IndexedDB, using WebSQL\n shim('indexedDB', shimIndexedDB, {\n enumerable: true,\n configurable: true,\n get () {\n if (this !== IDB && !isNullish(this) && !this.shimNS) { // Latter is hack for test environment\n throw new TypeError('Illegal invocation');\n }\n return shimIndexedDB;\n }\n });\n /** @type {[string, any][]} */\n ([\n ['IDBFactory', shimIDBFactory],\n ['IDBDatabase', shimIDBDatabase],\n ['IDBObjectStore', shimIDBObjectStore],\n ['IDBIndex', shimIDBIndex],\n ['IDBTransaction', shimIDBTransaction],\n ['IDBCursor', shimIDBCursor],\n ['IDBCursorWithValue', shimIDBCursorWithValue],\n ['IDBKeyRange', shimIDBKeyRange],\n ['IDBRequest', shimIDBRequest],\n ['IDBOpenDBRequest', shimIDBOpenDBRequest],\n ['IDBVersionChangeEvent', shimIDBVersionChangeEvent]\n ]).forEach(([prop, obj]) => {\n shim(prop, obj, {\n enumerable: false,\n configurable: true\n });\n });\n // For Node environments\n if (CFG.fs) {\n setFS(CFG.fs);\n }\n if (CFG.fullIDLSupport) {\n // Slow per MDN so off by default! Though apparently needed for WebIDL: http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements\n\n Object.setPrototypeOf(IDB.IDBOpenDBRequest, IDB.IDBRequest);\n Object.setPrototypeOf(IDB.IDBCursorWithValue, IDB.IDBCursor);\n\n Object.setPrototypeOf(shimIDBDatabase, ShimEventTarget);\n Object.setPrototypeOf(shimIDBRequest, ShimEventTarget);\n Object.setPrototypeOf(shimIDBTransaction, ShimEventTarget);\n Object.setPrototypeOf(shimIDBVersionChangeEvent, ShimEvent);\n Object.setPrototypeOf(ShimDOMException, Error);\n Object.setPrototypeOf(ShimDOMException.prototype, Error.prototype);\n setPrototypeOfCustomEvent();\n }\n if (IDB.indexedDB && !IDB.indexedDB.toString().includes('[native code]')) {\n if (CFG.addNonIDBGlobals) {\n // As `DOMStringList` exists per IDL (and Chrome) in the global\n // thread (but not in workers), we prefix the name to avoid\n // shadowing or conflicts\n setNonIDBGlobals('Shim');\n }\n if (CFG.replaceNonIDBGlobals) {\n setNonIDBGlobals();\n }\n }\n /* istanbul ignore next -- TS guard */\n if (!IDB.shimIndexedDB) {\n return;\n }\n IDB.shimIndexedDB.__setConnectionQueueOrigin();\n }\n };\n\n IDB.shimIndexedDB.__debug = function (val) {\n CFG.DEBUG = val;\n };\n IDB.shimIndexedDB.__setConfig = setConfig;\n\n /** @type {GetConfig} */\n IDB.shimIndexedDB.__getConfig = function (prop) {\n if (!(prop in CFG)) {\n throw new Error(prop + ' is not a valid configuration property');\n }\n return CFG[prop];\n };\n\n /** @type {SetUnicodeIdentifiers} */\n IDB.shimIndexedDB.__setUnicodeIdentifiers = function ({\n UnicodeIDStart, UnicodeIDContinue\n }) {\n setConfig({UnicodeIDStart, UnicodeIDContinue});\n };\n } else {\n // We no-op the harmless set-up properties and methods with a warning; the `IDBFactory` methods,\n // however (including our non-standard methods), are not stubbed as they ought\n // to fail earlier rather than potentially having side effects.\n IDB.shimIndexedDB = /** @type {ShimIndexedDB} */ ({});\n /** @type {const} */ ([\n '__useShim', '__debug', '__setConfig',\n '__getConfig', '__setUnicodeIdentifiers'\n ]).forEach((prop) => {\n /** @type {ShimIndexedDB} */ (IDB.shimIndexedDB)[prop] = /** @type {() => any} */ function () {\n console.warn('This browser does not have WebSQL to shim.');\n };\n });\n }\n\n // Workaround to prevent an error in Firefox\n if (!('indexedDB' in IDB) && typeof window !== 'undefined') { // 2nd condition avoids problems in Node\n IDB.indexedDB = /** @type {IDBFactory} */ (IDB.indexedDB ||\n ('webkitIndexedDB' in IDB && IDB.webkitIndexedDB) ||\n ('mozIndexedDB' in IDB && IDB.mozIndexedDB) ||\n ('oIndexedDB' in IDB && IDB.oIndexedDB) ||\n ('msIndexedDB' in IDB && IDB.msIndexedDB));\n }\n\n // Detect browsers with known IndexedDB issues (e.g. Android pre-4.4)\n let poorIndexedDbSupport = false;\n if (\n typeof navigator !== 'undefined' &&\n // Not apparently defined in React Native\n navigator.userAgent &&\n ( // Ignore Node or other environments\n (\n // Bad non-Chrome Android support\n (/Android (?:2|3|4\\.[0-3])/u).test(navigator.userAgent) &&\n !navigator.userAgent.includes('Chrome')\n ) ||\n (\n // Bad non-Safari iOS9 support (see )\n (!navigator.userAgent.includes('Safari') || navigator.userAgent.includes('Chrome')) && // Exclude genuine Safari: http://stackoverflow.com/a/7768006/271577\n // Detect iOS: http://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885#9039885\n // and detect version 9: http://stackoverflow.com/a/26363560/271577\n (/(iPad|iPhone|iPod).* os 9_/ui).test(navigator.userAgent) &&\n (typeof window !== 'undefined' &&\n // eslint-disable-next-line no-undef -- Extra check\n !('MSStream' in window)) // But avoid IE11\n )\n )\n ) {\n poorIndexedDbSupport = true;\n }\n if (!CFG.DEFAULT_DB_SIZE) {\n CFG.DEFAULT_DB_SIZE = (\n ( // Safari currently requires larger size: (We don't need a larger size for Node as node-websql doesn't use this info)\n // https://github.com/axemclion/IndexedDBShim/issues/41\n // https://github.com/axemclion/IndexedDBShim/issues/115\n typeof navigator !== 'undefined' &&\n // React Native\n navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n )\n ? 25\n : 4\n ) * 1024 * 1024;\n }\n if (!CFG.avoidAutoShim &&\n (!IDB.indexedDB || poorIndexedDbSupport) &&\n CFG.win.openDatabase !== undefined\n ) {\n IDB.shimIndexedDB.__useShim();\n } else {\n IDB.IDBDatabase = IDB.IDBDatabase ||\n ('webkitIDBDatabase' in IDB && IDB.webkitIDBDatabase);\n IDB.IDBTransaction = IDB.IDBTransaction ||\n ('webkitIDBTransaction' in IDB && IDB.webkitIDBTransaction) || {};\n IDB.IDBCursor = IDB.IDBCursor ||\n ('webkitIDBCursor' in IDB && IDB.webkitIDBCursor);\n IDB.IDBKeyRange = IDB.IDBKeyRange ||\n ('webkitIDBKeyRange' in IDB && IDB.webkitIDBKeyRange);\n }\n return /** @type {ShimmedObject} */ (IDB);\n}\n\n// Expose for ease in simulating such exceptions during testing\nexport {createDOMException};\n\nexport default setGlobalVars;\n","'use strict';\nexports.test = function () {\n // Don't get fooled by e.g. browserify environments.\n return (typeof process !== 'undefined') && !process.browser;\n};\n\nexports.install = function (func) {\n return function () {\n process.nextTick(func);\n };\n};\n","'use strict';\nexports.test = function () {\n return typeof global.queueMicrotask === 'function';\n};\n\nexports.install = function (func) {\n return function () {\n global.queueMicrotask(func);\n };\n};\n","'use strict';\n//based off rsvp https://github.com/tildeio/rsvp.js\n//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE\n//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js\n\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nexports.test = function () {\n return Mutation;\n};\n\nexports.install = function (handle) {\n var called = 0;\n var observer = new Mutation(handle);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n return function () {\n element.data = (called = ++called % 2);\n };\n};","'use strict';\n\nexports.test = function () {\n if (global.setImmediate) {\n // we can only get here in IE10\n // which doesn't handel postMessage well\n return false;\n }\n return typeof global.MessageChannel !== 'undefined';\n};\n\nexports.install = function (func) {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = func;\n return function () {\n channel.port2.postMessage(0);\n };\n};","'use strict';\n\nexports.test = function () {\n return 'document' in global && 'onreadystatechange' in global.document.createElement('script');\n};\n\nexports.install = function (handle) {\n return function () {\n\n // Create a