indexeddbshim 16.1.0 → 17.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +3 -3
  2. package/badges/licenses-badge-dev.svg +1 -1
  3. package/badges/licenses-badge.svg +1 -1
  4. package/dist/CFG.d.ts.map +1 -1
  5. package/dist/DOMException.d.ts.map +1 -1
  6. package/dist/DOMStringList.d.ts.map +1 -1
  7. package/dist/IDBCursor.d.ts +3 -1
  8. package/dist/IDBCursor.d.ts.map +1 -1
  9. package/dist/IDBDatabase.d.ts +2 -1
  10. package/dist/IDBDatabase.d.ts.map +1 -1
  11. package/dist/IDBFactory.d.ts +2 -1
  12. package/dist/IDBFactory.d.ts.map +1 -1
  13. package/dist/IDBIndex.d.ts +2 -1
  14. package/dist/IDBIndex.d.ts.map +1 -1
  15. package/dist/IDBKeyRange.d.ts +1 -1
  16. package/dist/IDBKeyRange.d.ts.map +1 -1
  17. package/dist/IDBObjectStore.d.ts +2 -1
  18. package/dist/IDBObjectStore.d.ts.map +1 -1
  19. package/dist/IDBRequest.d.ts +5 -3
  20. package/dist/IDBRequest.d.ts.map +1 -1
  21. package/dist/IDBTransaction.d.ts +2 -1
  22. package/dist/IDBTransaction.d.ts.map +1 -1
  23. package/dist/Key.d.ts.map +1 -1
  24. package/dist/Sca.d.ts.map +1 -1
  25. package/dist/UnicodeIdentifiers.d.ts.map +1 -1
  26. package/dist/browser-noninvasive.d.ts.map +1 -1
  27. package/dist/indexeddbshim-Key.js +1844 -1669
  28. package/dist/indexeddbshim-Key.js.map +1 -1
  29. package/dist/indexeddbshim-Key.min.js +2 -2
  30. package/dist/indexeddbshim-Key.min.js.map +1 -1
  31. package/dist/indexeddbshim-UnicodeIdentifiers-node.cjs +972 -1076
  32. package/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map +1 -1
  33. package/dist/indexeddbshim-UnicodeIdentifiers.js +2704 -2034
  34. package/dist/indexeddbshim-UnicodeIdentifiers.js.map +1 -1
  35. package/dist/indexeddbshim-UnicodeIdentifiers.min.js +9 -2
  36. package/dist/indexeddbshim-UnicodeIdentifiers.min.js.map +1 -1
  37. package/dist/indexeddbshim-node.cjs +972 -1076
  38. package/dist/indexeddbshim-node.cjs.map +1 -1
  39. package/dist/indexeddbshim-noninvasive.js +2703 -2033
  40. package/dist/indexeddbshim-noninvasive.js.map +1 -1
  41. package/dist/indexeddbshim-noninvasive.min.js +9 -2
  42. package/dist/indexeddbshim-noninvasive.min.js.map +1 -1
  43. package/dist/indexeddbshim.js +2676 -2014
  44. package/dist/indexeddbshim.js.map +1 -1
  45. package/dist/indexeddbshim.min.js +9 -2
  46. package/dist/indexeddbshim.min.js.map +1 -1
  47. package/dist/node-UnicodeIdentifiers.d.ts +2 -2
  48. package/dist/node-UnicodeIdentifiers.d.ts.map +1 -1
  49. package/dist/node.d.ts +2 -2
  50. package/dist/node.d.ts.map +1 -1
  51. package/dist/util.d.ts.map +1 -1
  52. package/package.json +111 -103
  53. package/src/CFG.js +2 -3
  54. package/src/DOMException.js +11 -9
  55. package/src/DOMStringList.js +8 -3
  56. package/src/Event.js +2 -0
  57. package/src/IDBCursor.js +16 -9
  58. package/src/IDBDatabase.js +9 -6
  59. package/src/IDBFactory.js +21 -14
  60. package/src/IDBIndex.js +82 -77
  61. package/src/IDBKeyRange.js +42 -35
  62. package/src/IDBObjectStore.js +83 -77
  63. package/src/IDBRequest.js +28 -15
  64. package/src/IDBTransaction.js +8 -4
  65. package/src/IDBVersionChangeEvent.js +2 -0
  66. package/src/Key.js +18 -12
  67. package/src/Sca.js +2 -1
  68. package/src/UnicodeIdentifiers.js +2 -2
  69. package/src/browser-UnicodeIdentifiers.js +0 -1
  70. package/src/browser-noninvasive.js +0 -1
  71. package/src/browser.js +0 -1
  72. package/src/node-UnicodeIdentifiers.js +1 -1
  73. package/src/node.js +1 -1
  74. package/src/setGlobalVars.js +13 -13
  75. package/src/util.js +13 -12
@@ -1,1235 +1,1384 @@
1
- /*! indexeddbshim - v16.1.0 - 9/1/2025 */
1
+ /*! indexeddbshim - v17.0.0 - 7/28/2026 */
2
2
 
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
5
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IDBKeyUtils = {}));
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
5
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IDBKeyUtils = {}));
7
7
  })(this, (function (exports) { 'use strict';
8
8
 
9
- /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
10
- /**
11
- * @typedef {T[keyof T]} ValueOf<T>
12
- * @template T
13
- */
14
- /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
15
-
16
- /**
17
- * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi
18
- */
19
-
20
- /**
21
- * @typedef {{
22
- * DEBUG: boolean,
23
- * cacheDatabaseInstances: boolean,
24
- * autoName: boolean,
25
- * fullIDLSupport: boolean,
26
- * checkOrigin: boolean,
27
- * cursorPreloadPackSize: number,
28
- * UnicodeIDStart: string,
29
- * UnicodeIDContinue: string,
30
- * registerSCA: (
31
- * preset: import('typeson').Preset
32
- * ) => import('typeson').Preset,
33
- * avoidAutoShim: boolean,
34
- * win: {
35
- * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default
36
- * },
37
- * DEFAULT_DB_SIZE: number,
38
- * useSQLiteIndexes: boolean,
39
- * fs: FSApi,
40
- * addNonIDBGlobals: boolean,
41
- * replaceNonIDBGlobals: boolean,
42
- * escapeDatabaseName: (name: string) => string,
43
- * unescapeDatabaseName: (name: string) => string,
44
- * databaseCharacterEscapeList: string|false,
45
- * databaseNameLengthLimit: number|false,
46
- * escapeNFDForDatabaseNames: boolean,
47
- * addSQLiteExtension: boolean,
48
- * memoryDatabase: string,
49
- * deleteDatabaseFiles: boolean,
50
- * databaseBasePath: string,
51
- * sysDatabaseBasePath: string,
52
- * sqlBusyTimeout: number,
53
- * sqlTrace: () => void,
54
- * sqlProfile: () => void,
55
- * createIndexes: boolean
56
- * }} ConfigValues
57
- */
58
-
59
- /**
60
- * @typedef {ValueOf<ConfigValues>} ConfigValue
61
- */
62
-
63
- /** @type {{[key: string]: ConfigValue}} */
64
- const map = {};
65
- const CFG = /** @type {ConfigValues} */{};
66
-
67
- /**
68
- * @typedef {keyof ConfigValues} KeyofConfigValues
69
- */
70
-
71
- /**
72
- * @typedef {KeyofConfigValues[]} Config
73
- */
74
-
75
- /** @type {Config} */
76
- [
77
- // Boolean for verbose reporting
78
- 'DEBUG',
79
- // Effectively defaults to false (ignored unless `true`)
80
-
81
- // Boolean (effectively defaults to true) on whether to cache WebSQL
82
- // `openDatabase` instances
83
- 'cacheDatabaseInstances',
84
- // Boolean on whether to auto-name databases (based on an
85
- // auto-increment) when the empty string is supplied; useful with
86
- // `memoryDatabase`; defaults to `false` which means the empty string
87
- // will be used as the (valid) database name
88
- 'autoName',
89
- // Determines whether the slow-performing `Object.setPrototypeOf`
90
- // calls required for full WebIDL compliance will be used. Probably
91
- // only needed for testing or environments where full introspection
92
- // on class relationships is required; see
93
- // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements
94
- 'fullIDLSupport',
95
- // Effectively defaults to false (ignored unless `true`)
96
-
97
- // Boolean on whether to perform origin checks in `IDBFactory` methods
98
- // Effectively defaults to `true` (must be set to `false` to cancel checks)
99
- 'checkOrigin',
100
- // Used by `IDBCursor` continue methods for number of records to cache;
101
- // Defaults to 100
102
- 'cursorPreloadPackSize',
103
- // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);
104
- // or just use the Unicode builds which invoke this method
105
- // automatically using the large, fully spec-compliant, regular
106
- // expression strings of `src/UnicodeIdentifiers.js`)
107
- // In the non-Unicode builds, defaults to /[$A-Z_a-z]/
108
- 'UnicodeIDStart',
109
- // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/
110
- 'UnicodeIDContinue',
111
- // Used by SCA.js for optional restructuring of typeson-registry
112
- // Structured Cloning Algorithm; should only be needed for ensuring data
113
- // created in 3.* versions of IndexedDBShim continue to work; see the
114
- // library `typeson-registry-sca-reverter` to get a function to do this
115
- 'registerSCA',
116
- // BROWSER-SPECIFIC CONFIG
117
- 'avoidAutoShim',
118
- // Where WebSQL is detected but where `indexedDB` is
119
- // missing or poor support is known (non-Chrome Android or
120
- // non-Safari iOS9), the shim will be auto-applied without
121
- // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing
122
- // the shim for such cases.
123
-
124
- // -----------SQL CONFIG----------
125
- // Object (`window` in the browser) on which there may be an
126
- // `openDatabase` method (if any) for WebSQL. (The browser
127
- // throws if attempting to call `openDatabase` without the window
128
- // so this is why the config doesn't just allow the function.)
129
- // Defaults to `window` or `self` in browser builds or
130
- // a singleton object with the `openDatabase` method set to
131
- // the "websql" package in Node.
132
- 'win',
133
- // For internal `openDatabase` calls made by `IDBFactory` methods;
134
- // per the WebSQL spec, "User agents are expected to use the display name
135
- // and the estimated database size to optimize the user experience.
136
- // For example, a user agent could use the estimated size to suggest an
137
- // initial quota to the user. This allows a site that is aware that it
138
- // will try to use hundreds of megabytes to declare this upfront, instead
139
- // of the user agent prompting the user for permission to increase the
140
- // quota every five megabytes."
141
- // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari
142
- 'DEFAULT_DB_SIZE',
143
- // Whether to create indexes on SQLite tables (and also whether to try
144
- // dropping)
145
- // Effectively defaults to `false` (ignored unless `true`)
146
- 'useSQLiteIndexes',
147
- // NODE-IMPINGING SETTINGS (created for sake of limitations in Node
148
- // or desktop file system implementation but applied by default in
149
- // browser for parity)
150
-
151
- // File system module with `unlink` to remove deleted database files
152
- 'fs',
153
- // Used when setting global shims to determine whether to try to add
154
- // other globals shimmed by the library (`ShimDOMException`,
155
- // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)
156
- // Effectively defaults to `false` (ignored unless `true`)
157
- 'addNonIDBGlobals',
158
- // Used when setting global shims to determine whether to try to overwrite
159
- // other globals shimmed by the library (`DOMException`, `DOMStringList`,
160
- // `Event`, `CustomEvent`, `EventTarget`)
161
- // Effectively defaults to `false` (ignored unless `true`)
162
- 'replaceNonIDBGlobals',
163
- // Overcoming limitations with node-sqlite3/storing database name on
164
- // file systems
165
- // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
166
- // Defaults to prefixing database with `D_`, escaping
167
- // `databaseCharacterEscapeList`, escaping NUL, and
168
- // escaping upper case letters, as well as enforcing
169
- // `databaseNameLengthLimit`
170
- 'escapeDatabaseName',
171
- // Not used internally; usable as a convenience method
172
- 'unescapeDatabaseName',
173
- // Defaults to global regex representing the following
174
- // (characters nevertheless commonly reserved in modern,
175
- // Unicode-supporting systems): 0x00-0x1F 0x7F " * / : < > ? \ |
176
- 'databaseCharacterEscapeList',
177
- // Defaults to 254 (shortest typical modern file length limit)
178
- 'databaseNameLengthLimit',
179
- // Boolean defaulting to true on whether to escape NFD-escaping
180
- // characters to avoid clashes on MacOS which performs NFD on files
181
- 'escapeNFDForDatabaseNames',
182
- // Boolean on whether to add the `.sqlite` extension to file names;
183
- // defaults to `true`
184
- 'addSQLiteExtension',
185
- // Various types of in-memory databases that can auto-delete
186
- ['memoryDatabase',
187
- /**
188
- * @param {string} val
189
- * @throws {TypeError}
190
- * @returns {void}
191
- */
192
- val => {
193
- if (!/^(?::memory:|file::memory:(\?[^#]*)?(#.*)?)?$/u.test(/** @type {string} */val)) {
194
- throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a ' + '"file::memory:[?queryString][#hash] URL".');
195
- }
196
- }],
197
- // NODE-SPECIFIC CONFIG
198
- // Boolean on whether to delete the database file itself after
199
- // `deleteDatabase`; defaults to `true` as the database will be empty
200
- 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath',
201
- // NODE-SPECIFIC WEBSQL CONFIG
202
- 'sqlBusyTimeout',
203
- // Defaults to 1000
204
- 'sqlTrace',
205
- // Callback not used by default
206
- 'sqlProfile',
207
- // Callback not used by default
208
-
209
- 'createIndexes'].forEach(prop => {
210
- /** @type {(val: any) => void} */
211
- let validator;
212
- if (Array.isArray(prop)) {
213
- [prop, validator] = prop;
9
+ function _arrayLikeToArray(r, a) {
10
+ (null == a || a > r.length) && (a = r.length);
11
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
12
+ return n;
13
+ }
14
+ function _arrayWithHoles(r) {
15
+ if (Array.isArray(r)) return r;
16
+ }
17
+ function _arrayWithoutHoles(r) {
18
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
19
+ }
20
+ function _createForOfIteratorHelper(r, e) {
21
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
22
+ if (!t) {
23
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
24
+ t && (r = t);
25
+ var n = 0,
26
+ F = function () {};
27
+ return {
28
+ s: F,
29
+ n: function () {
30
+ return n >= r.length ? {
31
+ done: true
32
+ } : {
33
+ done: false,
34
+ value: r[n++]
35
+ };
36
+ },
37
+ e: function (r) {
38
+ throw r;
39
+ },
40
+ f: F
41
+ };
214
42
  }
215
- Object.defineProperty(CFG, prop, {
216
- get() {
217
- return map[prop];
218
- },
219
- set(val) {
220
- if (validator) {
221
- validator(val);
222
- }
223
- map[prop] = val;
224
- }
225
- });
226
- });
227
-
228
- /**
229
- * Creates a native DOMException, for browsers that support it.
230
- * @param {string} name
231
- * @param {string} message
232
- * @returns {DOMException}
233
- */
234
- function createNativeDOMException(name, message) {
235
- // @ts-expect-error It's ok
236
- return new DOMException.prototype.constructor(message, name || 'DOMException');
43
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
237
44
  }
238
-
239
- // From web-platform-tests testharness.js name_code_map (though not in new spec)
240
-
241
- /**
242
- * @typedef {"IndexSizeError"|"HierarchyRequestError"|"WrongDocumentError"|
243
- * "InvalidCharacterError"|"NoModificationAllowedError"|"NotFoundError"|
244
- * "NotSupportedError"|"InUseAttributeError"|"InvalidStateError"|
245
- * "SyntaxError"|"InvalidModificationError"|"NamespaceError"|
246
- * "InvalidAccessError"|"TypeMismatchError"|"SecurityError"|
247
- * "NetworkError"|"AbortError"|"URLMismatchError"|"QuotaExceededError"|
248
- * "TimeoutError"|"InvalidNodeTypeError"|"DataCloneError"|"EncodingError"|
249
- * "NotReadableError"|"UnknownError"|"ConstraintError"|"DataError"|
250
- * "TransactionInactiveError"|"ReadOnlyError"|"VersionError"|
251
- * "OperationError"|"NotAllowedError"} Code
252
- */
253
-
254
- const codes = {
255
- IndexSizeError: 1,
256
- HierarchyRequestError: 3,
257
- WrongDocumentError: 4,
258
- InvalidCharacterError: 5,
259
- NoModificationAllowedError: 7,
260
- NotFoundError: 8,
261
- NotSupportedError: 9,
262
- InUseAttributeError: 10,
263
- InvalidStateError: 11,
264
- SyntaxError: 12,
265
- InvalidModificationError: 13,
266
- NamespaceError: 14,
267
- InvalidAccessError: 15,
268
- TypeMismatchError: 17,
269
- SecurityError: 18,
270
- NetworkError: 19,
271
- AbortError: 20,
272
- URLMismatchError: 21,
273
- QuotaExceededError: 22,
274
- TimeoutError: 23,
275
- InvalidNodeTypeError: 24,
276
- DataCloneError: 25,
277
- EncodingError: 0,
278
- NotReadableError: 0,
279
- UnknownError: 0,
280
- ConstraintError: 0,
281
- DataError: 0,
282
- TransactionInactiveError: 0,
283
- ReadOnlyError: 0,
284
- VersionError: 0,
285
- OperationError: 0,
286
- NotAllowedError: 0
287
- };
288
-
289
- /**
290
- * @typedef {"INDEX_SIZE_ERR"|"DOMSTRING_SIZE_ERR"|"HIERARCHY_REQUEST_ERR"|
291
- * "WRONG_DOCUMENT_ERR"|"INVALID_CHARACTER_ERR"|"NO_DATA_ALLOWED_ERR"|
292
- * "NO_MODIFICATION_ALLOWED_ERR"|"NOT_FOUND_ERR"|"NOT_SUPPORTED_ERR"|
293
- * "INUSE_ATTRIBUTE_ERR"|"INVALID_STATE_ERR"|"SYNTAX_ERR"|
294
- * "INVALID_MODIFICATION_ERR"|"NAMESPACE_ERR"|"INVALID_ACCESS_ERR"|
295
- * "VALIDATION_ERR"|"TYPE_MISMATCH_ERR"|"SECURITY_ERR"|"NETWORK_ERR"|
296
- * "ABORT_ERR"|"URL_MISMATCH_ERR"|"QUOTA_EXCEEDED_ERR"|"TIMEOUT_ERR"|
297
- * "INVALID_NODE_TYPE_ERR"|"DATA_CLONE_ERR"} LegacyCode
298
- */
299
-
300
- const legacyCodes = {
301
- INDEX_SIZE_ERR: 1,
302
- DOMSTRING_SIZE_ERR: 2,
303
- HIERARCHY_REQUEST_ERR: 3,
304
- WRONG_DOCUMENT_ERR: 4,
305
- INVALID_CHARACTER_ERR: 5,
306
- NO_DATA_ALLOWED_ERR: 6,
307
- NO_MODIFICATION_ALLOWED_ERR: 7,
308
- NOT_FOUND_ERR: 8,
309
- NOT_SUPPORTED_ERR: 9,
310
- INUSE_ATTRIBUTE_ERR: 10,
311
- INVALID_STATE_ERR: 11,
312
- SYNTAX_ERR: 12,
313
- INVALID_MODIFICATION_ERR: 13,
314
- NAMESPACE_ERR: 14,
315
- INVALID_ACCESS_ERR: 15,
316
- VALIDATION_ERR: 16,
317
- TYPE_MISMATCH_ERR: 17,
318
- SECURITY_ERR: 18,
319
- NETWORK_ERR: 19,
320
- ABORT_ERR: 20,
321
- URL_MISMATCH_ERR: 21,
322
- QUOTA_EXCEEDED_ERR: 22,
323
- TIMEOUT_ERR: 23,
324
- INVALID_NODE_TYPE_ERR: 24,
325
- DATA_CLONE_ERR: 25
45
+ var o,
46
+ a = true,
47
+ u = false;
48
+ return {
49
+ s: function () {
50
+ t = t.call(r);
51
+ },
52
+ n: function () {
53
+ var r = t.next();
54
+ return a = r.done, r;
55
+ },
56
+ e: function (r) {
57
+ u = true, o = r;
58
+ },
59
+ f: function () {
60
+ try {
61
+ a || null == t.return || t.return();
62
+ } finally {
63
+ if (u) throw o;
64
+ }
65
+ }
326
66
  };
327
-
328
- /**
329
- *
330
- * @returns {typeof DOMException}
331
- */
332
- function createNonNativeDOMExceptionClass() {
333
- /**
334
- * @param {string|undefined} message
335
- * @param {Code|LegacyCode} name
336
- * @returns {void}
337
- */
338
- function DOMException(message, name) {
339
- // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message
340
- this[Symbol.toStringTag] = 'DOMException';
341
- this._code = name in codes ? codes[(/** @type {Code} */name)] : legacyCodes[(/** @type {LegacyCode} */name)] || 0;
342
- this._name = name || 'Error';
343
- // We avoid `String()` in this next line as it converts Symbols
344
- this._message = message === undefined ? '' : '' + message; // eslint-disable-line no-implicit-coercion -- Don't convert symbols
345
- Object.defineProperty(this, 'code', {
346
- configurable: true,
347
- enumerable: true,
348
- writable: true,
349
- value: this._code
350
- });
351
- if (name !== undefined) {
352
- Object.defineProperty(this, 'name', {
353
- configurable: true,
354
- enumerable: true,
355
- writable: true,
356
- value: this._name
357
- });
67
+ }
68
+ function _iterableToArray(r) {
69
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
70
+ }
71
+ function _iterableToArrayLimit(r, l) {
72
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
73
+ if (null != t) {
74
+ var e,
75
+ n,
76
+ i,
77
+ u,
78
+ a = [],
79
+ f = true,
80
+ o = false;
81
+ try {
82
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
83
+ } catch (r) {
84
+ o = true, n = r;
85
+ } finally {
86
+ try {
87
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
88
+ } finally {
89
+ if (o) throw n;
358
90
  }
359
- if (message !== undefined) {
360
- Object.defineProperty(this, 'message', {
361
- configurable: true,
362
- enumerable: false,
363
- writable: true,
364
- value: this._message
365
- });
91
+ }
92
+ return a;
93
+ }
94
+ }
95
+ function _nonIterableRest() {
96
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
97
+ }
98
+ function _nonIterableSpread() {
99
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
100
+ }
101
+ function _slicedToArray(r, e) {
102
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
103
+ }
104
+ function _toConsumableArray(r) {
105
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
106
+ }
107
+ function _typeof(o) {
108
+ "@babel/helpers - typeof";
109
+
110
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
111
+ return typeof o;
112
+ } : function (o) {
113
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
114
+ }, _typeof(o);
115
+ }
116
+ function _unsupportedIterableToArray(r, a) {
117
+ if (r) {
118
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
119
+ var t = {}.toString.call(r).slice(8, -1);
120
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * @typedef {T[keyof T]} ValueOf<T>
126
+ * @template T
127
+ */
128
+
129
+ /**
130
+ * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi
131
+ */
132
+
133
+ /**
134
+ * @typedef {{
135
+ * DEBUG: boolean,
136
+ * cacheDatabaseInstances: boolean,
137
+ * autoName: boolean,
138
+ * fullIDLSupport: boolean,
139
+ * checkOrigin: boolean,
140
+ * cursorPreloadPackSize: number,
141
+ * UnicodeIDStart: string,
142
+ * UnicodeIDContinue: string,
143
+ * registerSCA: (
144
+ * preset: import('typeson').Preset
145
+ * ) => import('typeson').Preset,
146
+ * avoidAutoShim: boolean,
147
+ * win: {
148
+ * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default
149
+ * },
150
+ * DEFAULT_DB_SIZE: number,
151
+ * useSQLiteIndexes: boolean,
152
+ * fs: FSApi,
153
+ * addNonIDBGlobals: boolean,
154
+ * replaceNonIDBGlobals: boolean,
155
+ * escapeDatabaseName: (name: string) => string,
156
+ * unescapeDatabaseName: (name: string) => string,
157
+ * databaseCharacterEscapeList: string|false,
158
+ * databaseNameLengthLimit: number|false,
159
+ * escapeNFDForDatabaseNames: boolean,
160
+ * addSQLiteExtension: boolean,
161
+ * memoryDatabase: string,
162
+ * deleteDatabaseFiles: boolean,
163
+ * databaseBasePath: string,
164
+ * sysDatabaseBasePath: string,
165
+ * sqlBusyTimeout: number,
166
+ * sqlTrace: () => void,
167
+ * sqlProfile: () => void,
168
+ * createIndexes: boolean
169
+ * }} ConfigValues
170
+ */
171
+
172
+ /**
173
+ * @typedef {ValueOf<ConfigValues>} ConfigValue
174
+ */
175
+
176
+ /** @type {{[key: string]: ConfigValue}} */
177
+ var map = {};
178
+ var CFG = /** @type {ConfigValues} */{};
179
+
180
+ /**
181
+ * @typedef {keyof ConfigValues} KeyofConfigValues
182
+ */
183
+
184
+ /**
185
+ * @typedef {KeyofConfigValues[]} Config
186
+ */
187
+
188
+ /** @type {Config} */
189
+ // eslint-disable-next-line unicorn/no-top-level-side-effects -- Would be good
190
+ [
191
+ // Boolean for verbose reporting
192
+ 'DEBUG',
193
+ // Effectively defaults to false (ignored unless `true`)
194
+
195
+ // Boolean (effectively defaults to true) on whether to cache WebSQL
196
+ // `openDatabase` instances
197
+ 'cacheDatabaseInstances',
198
+ // Boolean on whether to auto-name databases (based on an
199
+ // auto-increment) when the empty string is supplied; useful with
200
+ // `memoryDatabase`; defaults to `false` which means the empty string
201
+ // will be used as the (valid) database name
202
+ 'autoName',
203
+ // Determines whether the slow-performing `Object.setPrototypeOf`
204
+ // calls required for full WebIDL compliance will be used. Probably
205
+ // only needed for testing or environments where full introspection
206
+ // on class relationships is required; see
207
+ // https://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements
208
+ 'fullIDLSupport',
209
+ // Effectively defaults to false (ignored unless `true`)
210
+
211
+ // Boolean on whether to perform origin checks in `IDBFactory` methods
212
+ // Effectively defaults to `true` (must be set to `false` to cancel checks)
213
+ 'checkOrigin',
214
+ // Used by `IDBCursor` continue methods for number of records to cache;
215
+ // Defaults to 100
216
+ 'cursorPreloadPackSize',
217
+ // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);
218
+ // or just use the Unicode builds which invoke this method
219
+ // automatically using the large, fully spec-compliant, regular
220
+ // expression strings of `src/UnicodeIdentifiers.js`)
221
+ // In the non-Unicode builds, defaults to /[$A-Z_a-z]/
222
+ 'UnicodeIDStart',
223
+ // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/
224
+ 'UnicodeIDContinue',
225
+ // Used by SCA.js for optional restructuring of typeson-registry
226
+ // Structured Cloning Algorithm; should only be needed for ensuring data
227
+ // created in 3.* versions of IndexedDBShim continue to work; see the
228
+ // library `typeson-registry-sca-reverter` to get a function to do this
229
+ 'registerSCA',
230
+ // BROWSER-SPECIFIC CONFIG
231
+ 'avoidAutoShim',
232
+ // Where WebSQL is detected but where `indexedDB` is
233
+ // missing or poor support is known (non-Chrome Android or
234
+ // non-Safari iOS9), the shim will be auto-applied without
235
+ // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing
236
+ // the shim for such cases.
237
+
238
+ // -----------SQL CONFIG----------
239
+ // Object (`window` in the browser) on which there may be an
240
+ // `openDatabase` method (if any) for WebSQL. (The browser
241
+ // throws if attempting to call `openDatabase` without the window
242
+ // so this is why the config doesn't just allow the function.)
243
+ // Defaults to `window` or `self` in browser builds or
244
+ // a singleton object with the `openDatabase` method set to
245
+ // the "websql" package in Node.
246
+ 'win',
247
+ // For internal `openDatabase` calls made by `IDBFactory` methods;
248
+ // per the WebSQL spec, "User agents are expected to use the display name
249
+ // and the estimated database size to optimize the user experience.
250
+ // For example, a user agent could use the estimated size to suggest an
251
+ // initial quota to the user. This allows a site that is aware that it
252
+ // will try to use hundreds of megabytes to declare this upfront, instead
253
+ // of the user agent prompting the user for permission to increase the
254
+ // quota every five megabytes."
255
+ // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari
256
+ 'DEFAULT_DB_SIZE',
257
+ // Whether to create indexes on SQLite tables (and also whether to try
258
+ // dropping)
259
+ // Effectively defaults to `false` (ignored unless `true`)
260
+ 'useSQLiteIndexes',
261
+ // NODE-IMPINGING SETTINGS (created for sake of limitations in Node
262
+ // or desktop file system implementation but applied by default in
263
+ // browser for parity)
264
+
265
+ // File system module with `unlink` to remove deleted database files
266
+ 'fs',
267
+ // Used when setting global shims to determine whether to try to add
268
+ // other globals shimmed by the library (`ShimDOMException`,
269
+ // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)
270
+ // Effectively defaults to `false` (ignored unless `true`)
271
+ 'addNonIDBGlobals',
272
+ // Used when setting global shims to determine whether to try to overwrite
273
+ // other globals shimmed by the library (`DOMException`, `DOMStringList`,
274
+ // `Event`, `CustomEvent`, `EventTarget`)
275
+ // Effectively defaults to `false` (ignored unless `true`)
276
+ 'replaceNonIDBGlobals',
277
+ // Overcoming limitations with node-sqlite3/storing database name on
278
+ // file systems
279
+ // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
280
+ // Defaults to prefixing database with `D_`, escaping
281
+ // `databaseCharacterEscapeList`, escaping NUL, and
282
+ // escaping upper case letters, as well as enforcing
283
+ // `databaseNameLengthLimit`
284
+ 'escapeDatabaseName',
285
+ // Not used internally; usable as a convenience method
286
+ 'unescapeDatabaseName',
287
+ // Defaults to global regex representing the following
288
+ // (characters nevertheless commonly reserved in modern,
289
+ // Unicode-supporting systems): 0x00-0x1F 0x7F " * / : < > ? \ |
290
+ 'databaseCharacterEscapeList',
291
+ // Defaults to 254 (shortest typical modern file length limit)
292
+ 'databaseNameLengthLimit',
293
+ // Boolean defaulting to true on whether to escape NFD-escaping
294
+ // characters to avoid clashes on MacOS which performs NFD on files
295
+ 'escapeNFDForDatabaseNames',
296
+ // Boolean on whether to add the `.sqlite` extension to file names;
297
+ // defaults to `true`
298
+ 'addSQLiteExtension',
299
+ // Various types of in-memory databases that can auto-delete
300
+ ['memoryDatabase',
301
+ /**
302
+ * @param {string} val
303
+ * @throws {TypeError}
304
+ * @returns {void}
305
+ */
306
+ function (val) {
307
+ 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(/** @type {string} */val)) {
308
+ throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a ' + '"file::memory:[?queryString][#hash] URL".');
309
+ }
310
+ }],
311
+ // NODE-SPECIFIC CONFIG
312
+ // Boolean on whether to delete the database file itself after
313
+ // `deleteDatabase`; defaults to `true` as the database will be empty
314
+ 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath',
315
+ // NODE-SPECIFIC WEBSQL CONFIG
316
+ 'sqlBusyTimeout',
317
+ // Defaults to 1000
318
+ 'sqlTrace',
319
+ // Callback not used by default
320
+ 'sqlProfile',
321
+ // Callback not used by default
322
+
323
+ 'createIndexes'].forEach(function (prop) {
324
+ /** @type {(val: any) => void} */
325
+ var validator;
326
+ if (Array.isArray(prop)) {
327
+ var _prop = prop;
328
+ var _prop2 = _slicedToArray(_prop, 2);
329
+ prop = _prop2[0];
330
+ validator = _prop2[1];
331
+ }
332
+ Object.defineProperty(CFG, prop, {
333
+ get: function get() {
334
+ return map[prop];
335
+ },
336
+ set: function set(val) {
337
+ if (validator) {
338
+ validator(val);
366
339
  }
340
+ map[prop] = val;
367
341
  }
368
-
369
- // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype
370
-
371
- // class DummyDOMException extends Error {}; // Sometimes causing problems in Node
372
- /* eslint-disable func-name-matching -- See above */
373
- /**
374
- * @class
375
- */
376
- const DummyDOMException = function DOMException() {/* */};
377
- /* eslint-enable func-name-matching -- See above */
378
- DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing
379
- /** @type {const} */
380
- ['name', 'message'].forEach(prop => {
381
- Object.defineProperty(DummyDOMException.prototype, prop, {
382
- enumerable: true,
383
- /**
384
- * @this {DOMException}
385
- * @returns {string}
386
- */
387
- get() {
388
- if (!(this instanceof DOMException ||
389
- // @ts-expect-error Just checking
390
- this instanceof DummyDOMException ||
391
- // @ts-expect-error Just checking
392
- this instanceof Error)) {
393
- throw new TypeError('Illegal invocation');
394
- }
395
- return this[prop === 'name' ? '_name' : '_message'];
396
- }
397
- });
398
- });
399
- // DOMException uses the same `toString` as `Error`
400
- Object.defineProperty(DummyDOMException.prototype, 'code', {
342
+ });
343
+ });
344
+
345
+ /**
346
+ * Creates a native DOMException, for browsers that support it.
347
+ * @param {string} name
348
+ * @param {string} message
349
+ * @returns {DOMException}
350
+ */
351
+ function createNativeDOMException(name, message) {
352
+ // @ts-expect-error It's ok
353
+ return new DOMException.prototype.constructor(message, name || 'DOMException');
354
+ }
355
+
356
+ // From web-platform-tests testharness.js name_code_map (though not in new spec)
357
+
358
+ /**
359
+ * @typedef {"IndexSizeError"|"HierarchyRequestError"|"WrongDocumentError"|
360
+ * "InvalidCharacterError"|"NoModificationAllowedError"|"NotFoundError"|
361
+ * "NotSupportedError"|"InUseAttributeError"|"InvalidStateError"|
362
+ * "SyntaxError"|"InvalidModificationError"|"NamespaceError"|
363
+ * "InvalidAccessError"|"TypeMismatchError"|"SecurityError"|
364
+ * "NetworkError"|"AbortError"|"URLMismatchError"|"QuotaExceededError"|
365
+ * "TimeoutError"|"InvalidNodeTypeError"|"DataCloneError"|"EncodingError"|
366
+ * "NotReadableError"|"UnknownError"|"ConstraintError"|"DataError"|
367
+ * "TransactionInactiveError"|"ReadOnlyError"|"VersionError"|
368
+ * "OperationError"|"NotAllowedError"} Code
369
+ */
370
+
371
+ var codes = {
372
+ IndexSizeError: 1,
373
+ HierarchyRequestError: 3,
374
+ WrongDocumentError: 4,
375
+ InvalidCharacterError: 5,
376
+ NoModificationAllowedError: 7,
377
+ NotFoundError: 8,
378
+ NotSupportedError: 9,
379
+ InUseAttributeError: 10,
380
+ InvalidStateError: 11,
381
+ SyntaxError: 12,
382
+ InvalidModificationError: 13,
383
+ NamespaceError: 14,
384
+ InvalidAccessError: 15,
385
+ TypeMismatchError: 17,
386
+ SecurityError: 18,
387
+ NetworkError: 19,
388
+ AbortError: 20,
389
+ URLMismatchError: 21,
390
+ QuotaExceededError: 22,
391
+ TimeoutError: 23,
392
+ InvalidNodeTypeError: 24,
393
+ DataCloneError: 25,
394
+ EncodingError: 0,
395
+ NotReadableError: 0,
396
+ UnknownError: 0,
397
+ ConstraintError: 0,
398
+ DataError: 0,
399
+ TransactionInactiveError: 0,
400
+ ReadOnlyError: 0,
401
+ VersionError: 0,
402
+ OperationError: 0,
403
+ NotAllowedError: 0
404
+ };
405
+
406
+ /**
407
+ * @typedef {"INDEX_SIZE_ERR"|"DOMSTRING_SIZE_ERR"|"HIERARCHY_REQUEST_ERR"|
408
+ * "WRONG_DOCUMENT_ERR"|"INVALID_CHARACTER_ERR"|"NO_DATA_ALLOWED_ERR"|
409
+ * "NO_MODIFICATION_ALLOWED_ERR"|"NOT_FOUND_ERR"|"NOT_SUPPORTED_ERR"|
410
+ * "INUSE_ATTRIBUTE_ERR"|"INVALID_STATE_ERR"|"SYNTAX_ERR"|
411
+ * "INVALID_MODIFICATION_ERR"|"NAMESPACE_ERR"|"INVALID_ACCESS_ERR"|
412
+ * "VALIDATION_ERR"|"TYPE_MISMATCH_ERR"|"SECURITY_ERR"|"NETWORK_ERR"|
413
+ * "ABORT_ERR"|"URL_MISMATCH_ERR"|"QUOTA_EXCEEDED_ERR"|"TIMEOUT_ERR"|
414
+ * "INVALID_NODE_TYPE_ERR"|"DATA_CLONE_ERR"} LegacyCode
415
+ */
416
+
417
+ var legacyCodes = {
418
+ INDEX_SIZE_ERR: 1,
419
+ DOMSTRING_SIZE_ERR: 2,
420
+ HIERARCHY_REQUEST_ERR: 3,
421
+ WRONG_DOCUMENT_ERR: 4,
422
+ INVALID_CHARACTER_ERR: 5,
423
+ NO_DATA_ALLOWED_ERR: 6,
424
+ NO_MODIFICATION_ALLOWED_ERR: 7,
425
+ NOT_FOUND_ERR: 8,
426
+ NOT_SUPPORTED_ERR: 9,
427
+ INUSE_ATTRIBUTE_ERR: 10,
428
+ INVALID_STATE_ERR: 11,
429
+ SYNTAX_ERR: 12,
430
+ INVALID_MODIFICATION_ERR: 13,
431
+ NAMESPACE_ERR: 14,
432
+ INVALID_ACCESS_ERR: 15,
433
+ VALIDATION_ERR: 16,
434
+ TYPE_MISMATCH_ERR: 17,
435
+ SECURITY_ERR: 18,
436
+ NETWORK_ERR: 19,
437
+ ABORT_ERR: 20,
438
+ URL_MISMATCH_ERR: 21,
439
+ QUOTA_EXCEEDED_ERR: 22,
440
+ TIMEOUT_ERR: 23,
441
+ INVALID_NODE_TYPE_ERR: 24,
442
+ DATA_CLONE_ERR: 25
443
+ };
444
+
445
+ /**
446
+ *
447
+ * @returns {typeof DOMException}
448
+ */
449
+ function createNonNativeDOMExceptionClass() {
450
+ /**
451
+ * @param {string|undefined} message
452
+ * @param {Code|LegacyCode} name
453
+ * @returns {void}
454
+ */
455
+ function DOMException(message, name) {
456
+ // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message
457
+ this[Symbol.toStringTag] = 'DOMException';
458
+ this._code = Object.hasOwn(codes, name) ? codes[(/** @type {Code} */name)] : legacyCodes[(/** @type {LegacyCode} */name)] || 0;
459
+ this._name = name || 'Error';
460
+ // We avoid `String()` in this next line as it converts Symbols
461
+ this._message = message === undefined ? '' : '' + message; // eslint-disable-line no-implicit-coercion -- Don't convert symbols
462
+ Object.defineProperty(this, 'code', {
401
463
  configurable: true,
402
464
  enumerable: true,
403
- get() {
404
- throw new TypeError('Illegal invocation');
405
- }
406
- });
407
- // @ts-expect-error It's ok
408
- DOMException.prototype = new DummyDOMException();
409
- DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';
410
- Object.defineProperty(DOMException, 'prototype', {
411
- writable: false
412
- });
413
- const keys = Object.keys(codes);
414
-
415
- /** @type {(keyof codes)[]} */
416
- keys.forEach(codeName => {
417
- Object.defineProperty(DOMException.prototype, codeName, {
418
- enumerable: true,
419
- configurable: false,
420
- value: codes[codeName]
421
- });
422
- Object.defineProperty(DOMException, codeName, {
423
- enumerable: true,
424
- configurable: false,
425
- value: codes[codeName]
426
- });
465
+ writable: true,
466
+ value: this._code
427
467
  });
428
- /** @type {(keyof legacyCodes)[]} */
429
- Object.keys(legacyCodes).forEach(codeName => {
430
- Object.defineProperty(DOMException.prototype, codeName, {
431
- enumerable: true,
432
- configurable: false,
433
- value: legacyCodes[codeName]
434
- });
435
- Object.defineProperty(DOMException, codeName, {
468
+ if (name !== undefined) {
469
+ Object.defineProperty(this, 'name', {
470
+ configurable: true,
436
471
  enumerable: true,
437
- configurable: false,
438
- value: legacyCodes[codeName]
472
+ writable: true,
473
+ value: this._name
439
474
  });
440
- });
441
- Object.defineProperty(DOMException.prototype, 'constructor', {
442
- writable: true,
443
- configurable: true,
444
- enumerable: false,
445
- value: DOMException
446
- });
447
-
448
- // @ts-expect-error We don't need all its properties
449
- return DOMException;
450
- }
451
- const ShimNonNativeDOMException = createNonNativeDOMExceptionClass();
452
-
453
- /**
454
- * Creates a generic Error object.
455
- * @param {string} name
456
- * @param {string} message
457
- * @returns {Error}
458
- */
459
- function createNonNativeDOMException(name, message) {
460
- return new ShimNonNativeDOMException(message, name);
461
- }
462
-
463
- /**
464
- * @typedef {{
465
- * message: string|DOMString
466
- * }} ErrorLike
467
- */
468
-
469
- /**
470
- * Logs detailed error information to the console.
471
- * @param {string} name
472
- * @param {string} message
473
- * @param {string|ErrorLike|boolean|null} [error]
474
- * @returns {void}
475
- */
476
- function logError(name, message, error) {
477
- if (CFG.DEBUG) {
478
- const msg = error && typeof error === 'object' && error.message ? error.message : (/** @type {string} */error);
479
- const method = typeof console.error === 'function' ? 'error' : 'log';
480
- console[method](name + ': ' + message + '. ' + (msg || ''));
481
- if (console.trace) {
482
- console.trace();
483
- }
484
475
  }
485
- }
486
-
487
- /**
488
- * @typedef {any} ArbitraryValue
489
- */
490
-
491
- /**
492
- * @param {ArbitraryValue} obj
493
- * @returns {boolean}
494
- */
495
- function isErrorOrDOMErrorOrDOMException(obj) {
496
- return obj && typeof obj === 'object' &&
497
- // We don't use util.isObj here as mutual dependency causing problems in Babel with browser
498
- typeof obj.name === 'string';
499
- }
500
- let test,
501
- useNativeDOMException = false;
502
-
503
- // Test whether we can use the browser's native DOMException class
504
- try {
505
- test = createNativeDOMException('test name', 'test message');
506
- if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {
507
- // Native DOMException works as expected
508
- useNativeDOMException = true;
476
+ if (message !== undefined) {
477
+ Object.defineProperty(this, 'message', {
478
+ configurable: true,
479
+ enumerable: false,
480
+ writable: true,
481
+ value: this._message
482
+ });
509
483
  }
510
- } catch (err) {}
511
- const createDOMException = useNativeDOMException
512
- // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
513
- ?
514
- /**
515
- * @param {string} name
516
- * @param {string} message
517
- * @param {ErrorLike} [error]
518
- * @returns {DOMException}
519
- */
520
- function (name, message, error) {
521
- logError(name, message, error);
522
- return createNativeDOMException(name, message);
523
484
  }
524
- // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
525
- :
526
- /**
527
- * @param {string} name
528
- * @param {string} message
529
- * @param {ErrorLike} [error]
530
- * @returns {Error}
531
- */
532
- function (name, message, error) {
533
- logError(name, message, error);
534
- return createNonNativeDOMException(name, message);
535
- };
536
485
 
537
- /* eslint-disable new-cap -- ToString is how it is defined */
538
- /* eslint-disable sonarjs/no-control-regex -- Needed */
486
+ // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype
539
487
 
488
+ // class DummyDOMException extends Error {}; // Sometimes causing problems in Node
489
+ /* eslint-disable func-name-matching -- See above */
540
490
  /**
541
- * @typedef {number} Integer
491
+ * @class
542
492
  */
543
-
544
- /**
545
- * @param {string} arg
546
- * @returns {string}
547
- */
548
- function escapeUnmatchedSurrogates(arg) {
549
- // http://stackoverflow.com/a/6701665/271577
550
- return arg.replaceAll(/([\uD800-\uDBFF])(?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])([\uDC00-\uDFFF])/gu, function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {
551
- // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577
552
- // but Chrome having problems
553
- if (unmatchedHighSurrogate) {
554
- return '^2' + unmatchedHighSurrogate.codePointAt().toString(16).padStart(4, '0');
493
+ var DummyDOMException = function DOMException() {/* */};
494
+ /* eslint-enable func-name-matching -- See above */
495
+ DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing
496
+ /** @type {const} */
497
+ ['name', 'message'].forEach(function (prop) {
498
+ Object.defineProperty(DummyDOMException.prototype, prop, {
499
+ enumerable: true,
500
+ /**
501
+ * @this {DOMException}
502
+ * @returns {string}
503
+ */
504
+ get: function get() {
505
+ if (!(this instanceof DOMException ||
506
+ // @ts-expect-error Just checking
507
+ this instanceof DummyDOMException ||
508
+ // @ts-expect-error Just checking
509
+ this instanceof Error)) {
510
+ throw new TypeError('Illegal invocation');
511
+ }
512
+ return this[prop === 'name' ? '_name' : '_message'];
555
513
  }
556
- return (precedingLow || '') + '^3' + unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');
557
514
  });
558
- }
559
-
560
- /**
561
- * The escaping of unmatched surrogates was needed by Chrome but not Node.
562
- * @param {string} arg
563
- * @returns {string}
564
- */
565
- function escapeSQLiteStatement(arg) {
566
- return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\0', '^0'));
567
- }
568
-
569
- /**
570
- *
571
- * @param {AnyValue} obj
572
- * @returns {obj is object}
573
- */
574
- function isObj(obj) {
575
- return obj !== null && typeof obj === 'object';
576
- }
577
-
578
- /**
579
- *
580
- * @param {object} obj
581
- * @returns {boolean}
582
- */
583
- function isDate(obj) {
584
- return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';
585
- }
515
+ });
516
+ // DOMException uses the same `toString` as `Error`
517
+ Object.defineProperty(DummyDOMException.prototype, 'code', {
518
+ configurable: true,
519
+ enumerable: true,
520
+ get: function get() {
521
+ throw new TypeError('Illegal invocation');
522
+ }
523
+ });
524
+ // @ts-expect-error It's ok
525
+ DOMException.prototype = new DummyDOMException();
526
+ DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';
527
+ Object.defineProperty(DOMException, 'prototype', {
528
+ writable: false
529
+ });
530
+ var keys = Object.keys(codes);
586
531
 
587
- /**
588
- *
589
- * @param {object} obj
590
- * @returns {boolean}
591
- */
592
- function isBlob(obj) {
593
- return isObj(obj) && 'size' in obj && typeof obj.size === 'number' && 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);
594
- }
532
+ /** @type {(keyof codes)[]} */
533
+ keys.forEach(function (codeName) {
534
+ Object.defineProperty(DOMException.prototype, codeName, {
535
+ enumerable: true,
536
+ configurable: false,
537
+ value: codes[codeName]
538
+ });
539
+ Object.defineProperty(DOMException, codeName, {
540
+ enumerable: true,
541
+ configurable: false,
542
+ value: codes[codeName]
543
+ });
544
+ });
545
+ /** @type {(keyof legacyCodes)[]} */
546
+ Object.keys(legacyCodes).forEach(function (codeName) {
547
+ Object.defineProperty(DOMException.prototype, codeName, {
548
+ enumerable: true,
549
+ configurable: false,
550
+ value: legacyCodes[codeName]
551
+ });
552
+ Object.defineProperty(DOMException, codeName, {
553
+ enumerable: true,
554
+ configurable: false,
555
+ value: legacyCodes[codeName]
556
+ });
557
+ });
558
+ Object.defineProperty(DOMException.prototype, 'constructor', {
559
+ writable: true,
560
+ configurable: true,
561
+ enumerable: false,
562
+ value: DOMException
563
+ });
595
564
 
596
- /**
597
- *
598
- * @param {object} obj
599
- * @returns {boolean}
600
- */
601
- function isFile(obj) {
602
- return isObj(obj) && 'name' in obj && typeof obj.name === 'string' && 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;
565
+ // @ts-expect-error We don't need all its properties
566
+ return DOMException;
567
+ }
568
+ var ShimNonNativeDOMException = createNonNativeDOMExceptionClass();
569
+
570
+ /**
571
+ * Creates a generic Error object.
572
+ * @param {string} name
573
+ * @param {string} message
574
+ * @returns {Error}
575
+ */
576
+ function createNonNativeDOMException(name, message) {
577
+ return new ShimNonNativeDOMException(message, name);
578
+ }
579
+
580
+ /**
581
+ * @typedef {{
582
+ * message: string|DOMString
583
+ * }} ErrorLike
584
+ */
585
+
586
+ /**
587
+ * Logs detailed error information to the console.
588
+ * @param {string} name
589
+ * @param {string} message
590
+ * @param {string|ErrorLike|boolean|null} [error]
591
+ * @returns {void}
592
+ */
593
+ function logError(name, message, error) {
594
+ if (!CFG.DEBUG) {
595
+ return;
603
596
  }
604
-
605
- /**
606
- *
607
- * @param {AnyValue} obj
608
- * @returns {boolean}
609
- */
610
- function isBinary(obj) {
611
- return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && ('slice' in obj && typeof obj.slice === 'function' ||
612
- // `TypedArray` (view on buffer) or `ArrayBuffer`
613
- 'getFloat64' in obj && typeof obj.getFloat64 === 'function' // `DataView` (view on buffer)
614
- );
597
+ var msg = error && _typeof(error) === 'object' && error.message ? error.message : (/** @type {string} */error);
598
+ var method = typeof console.error === 'function' ? 'error' : 'log';
599
+ console[method](name + ': ' + message + '. ' + (msg || ''));
600
+ if (console.trace) {
601
+ console.trace();
615
602
  }
616
-
617
- /**
618
- * @param {AnyValue} v
619
- * @returns {v is null|undefined}
620
- */
621
- function isNullish(v) {
622
- return v === null || v === undefined;
603
+ }
604
+
605
+ /**
606
+ * @typedef {any} ArbitraryValue
607
+ */
608
+
609
+ /**
610
+ * @param {ArbitraryValue} obj
611
+ * @returns {boolean}
612
+ */
613
+ function isErrorOrDOMErrorOrDOMException(obj) {
614
+ return obj && _typeof(obj) === 'object' &&
615
+ // We don't use util.isObj here as mutual dependency causing problems in Babel with browser
616
+ typeof obj.name === 'string';
617
+ }
618
+ var test,
619
+ useNativeDOMException = false;
620
+
621
+ // Test whether we can use the browser's native DOMException class
622
+ try {
623
+ test = createNativeDOMException('test name', 'test message');
624
+ if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {
625
+ // Native DOMException works as expected
626
+ useNativeDOMException = true;
623
627
  }
624
-
625
- /**
626
- * Compares two keys.
627
- * @param {import('./Key.js').Key} first
628
- * @param {import('./Key.js').Key} second
629
- * @returns {0|1|-1}
630
- */
631
- function cmp(first, second) {
632
- const encodedKey1 = /** @type {string} */encode(first);
633
- const encodedKey2 = /** @type {string} */encode(second);
634
- const result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1;
635
- if (CFG.DEBUG) {
636
- // verify that the keys encoded correctly
637
- let decodedKey1 = decode(encodedKey1);
638
- let decodedKey2 = decode(encodedKey2);
639
- if (typeof first === 'object') {
640
- first = JSON.stringify(first);
641
- decodedKey1 = JSON.stringify(decodedKey1);
642
- }
643
- if (typeof second === 'object') {
644
- second = JSON.stringify(second);
645
- decodedKey2 = JSON.stringify(decodedKey2);
646
- }
647
-
648
- // Encoding/decoding mismatches are usually due to a loss of
649
- // floating-point precision
650
- if (decodedKey1 !== first) {
651
- console.warn(first + ' was incorrectly encoded as ' + decodedKey1);
652
- }
653
- if (decodedKey2 !== second) {
654
- console.warn(second + ' was incorrectly encoded as ' + decodedKey2);
655
- }
628
+ } catch (err) {}
629
+ var createDOMException = useNativeDOMException
630
+ // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
631
+ ?
632
+ /**
633
+ * @param {string} name
634
+ * @param {string} message
635
+ * @param {ErrorLike} [error]
636
+ * @returns {DOMException}
637
+ */
638
+ function (name, message, error) {
639
+ logError(name, message, error);
640
+ return createNativeDOMException(name, message);
641
+ }
642
+ // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
643
+ :
644
+ /**
645
+ * @param {string} name
646
+ * @param {string} message
647
+ * @param {ErrorLike} [error]
648
+ * @returns {Error}
649
+ */
650
+ function (name, message, error) {
651
+ logError(name, message, error);
652
+ return createNonNativeDOMException(name, message);
653
+ };
654
+
655
+ /**
656
+ * @typedef {number} Integer
657
+ */
658
+
659
+ /**
660
+ * @param {string} arg
661
+ * @returns {string}
662
+ */
663
+ function escapeUnmatchedSurrogates(arg) {
664
+ // https://stackoverflow.com/a/6701665/271577
665
+ return arg.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 (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {
666
+ // Could add a corresponding surrogate for compatibility with `node-sqlite3`: https://bugs.python.org/issue12569 and https://stackoverflow.com/a/6701665/271577
667
+ // but Chrome having problems
668
+ if (unmatchedHighSurrogate) {
669
+ return '^2' + unmatchedHighSurrogate.codePointAt().toString(16).padStart(4, '0');
656
670
  }
657
- return result;
658
- }
659
-
660
- /**
661
- * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView
662
- */
663
-
664
- /**
665
- * @typedef {ArrayBufferView|ArrayBuffer} BufferSource
666
- */
667
-
668
- /**
669
- * @typedef {"number"|"date"|"string"|"binary"|"array"} KeyType
670
- */
671
-
672
- /**
673
- * @typedef {any} Value
674
- */
675
-
676
- /**
677
- * @typedef {any} Key
678
- * @todo Specify possible value more precisely
679
- */
680
-
681
- /**
682
- * @typedef {KeyPath[]} KeyPathArray
683
- */
684
- /**
685
- * @typedef {string|KeyPathArray} KeyPath
686
- */
687
-
688
- /**
689
- * @typedef {object} KeyValueObject
690
- * @property {KeyType|"NaN"|"null"|"undefined"|"boolean"|"object"|"symbol"|
691
- * "function"|"bigint"} type If not `KeyType`, indicates invalid value
692
- * @property {Value} [value]
693
- * @property {boolean} [invalid]
694
- * @property {string} [message]
695
- * @todo Specify acceptable `value` more precisely
696
- */
697
-
698
- /**
699
- * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive
700
- */
701
- /**
702
- * @typedef {ValueType[]} ValueTypeArray
703
- */
704
- /**
705
- * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType
706
- */
707
-
708
- /**
709
- * Encodes the keys based on their types. This is required to maintain collations
710
- * We leave space for future keys.
711
- * @type {{[key: string]: Integer|string}}
712
- */
713
- const keyTypeToEncodedChar = {
714
- invalid: 100,
715
- number: 200,
716
- date: 300,
717
- string: 400,
718
- binary: 500,
719
- array: 600
720
- };
721
- const keyTypes = /** @type {(KeyType|"invalid")[]} */Object.keys(keyTypeToEncodedChar);
722
- keyTypes.forEach(k => {
723
- keyTypeToEncodedChar[k] = String.fromCodePoint(/** @type {number} */keyTypeToEncodedChar[k]);
671
+ return (precedingLow || '') + '^3' + unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');
724
672
  });
725
- const encodedCharToKeyType = keyTypes.reduce((o, k) => {
726
- o[keyTypeToEncodedChar[k]] = k;
727
- return o;
728
- }, /** @type {{[key: string]: KeyType|"invalid"}} */{});
729
-
730
- /**
731
- * The sign values for numbers, ordered from least to greatest.
732
- * - "negativeInfinity": Sorts below all other values.
733
- * - "bigNegative": Negative values less than or equal to negative one.
734
- * - "smallNegative": Negative values between negative one and zero, noninclusive.
735
- * - "smallPositive": Positive values between zero and one, including zero but not one.
736
- * - "largePositive": Positive values greater than or equal to one.
737
- * - "positiveInfinity": Sorts above all other values.
738
- */
739
- const signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];
740
-
741
- /**
742
- * @typedef {any} AnyValue
743
- */
673
+ }
674
+
675
+ /**
676
+ * The escaping of unmatched surrogates was needed by Chrome but not Node.
677
+ * @param {string} arg
678
+ * @returns {string}
679
+ */
680
+ function escapeSQLiteStatement(arg) {
681
+ return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\0', '^0'));
682
+ }
683
+
684
+ /**
685
+ *
686
+ * @param {AnyValue} obj
687
+ * @returns {obj is object}
688
+ */
689
+ function isObj(obj) {
690
+ return obj !== null && _typeof(obj) === 'object';
691
+ }
692
+
693
+ /**
694
+ *
695
+ * @param {object} obj
696
+ * @returns {boolean}
697
+ */
698
+ function isDate(obj) {
699
+ return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';
700
+ }
701
+
702
+ /**
703
+ *
704
+ * @param {object} obj
705
+ * @returns {boolean}
706
+ */
707
+ function isBlob(obj) {
708
+ return isObj(obj) && 'size' in obj && typeof obj.size === 'number' && 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);
709
+ }
710
+
711
+ /**
712
+ *
713
+ * @param {object} obj
714
+ * @returns {boolean}
715
+ */
716
+ function isFile(obj) {
717
+ return isObj(obj) && 'name' in obj && typeof obj.name === 'string' && 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;
718
+ }
719
+
720
+ /**
721
+ *
722
+ * @param {AnyValue} obj
723
+ * @returns {boolean}
724
+ */
725
+ function isBinary(obj) {
726
+ return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && ('slice' in obj && typeof obj.slice === 'function' ||
727
+ // `TypedArray` (view on buffer) or `ArrayBuffer`
728
+ 'getFloat64' in obj && typeof obj.getFloat64 === 'function' // `DataView` (view on buffer)
729
+ );
730
+ }
731
+
732
+ /**
733
+ * @param {AnyValue} v
734
+ * @returns {v is null|undefined}
735
+ */
736
+ function isNullish(v) {
737
+ return v === null || v === undefined;
738
+ }
739
+
740
+ /**
741
+ * Compares two keys.
742
+ * @param {import('./Key.js').Key} first
743
+ * @param {import('./Key.js').Key} second
744
+ * @returns {0|1|-1}
745
+ */
746
+ function cmp(first, second) {
747
+ var encodedKey1 = /** @type {string} */_encode(first);
748
+ var encodedKey2 = /** @type {string} */_encode(second);
749
+ var result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1;
750
+ if (CFG.DEBUG) {
751
+ // verify that the keys encoded correctly
752
+ var decodedKey1 = _decode(encodedKey1);
753
+ var decodedKey2 = _decode(encodedKey2);
754
+ if (_typeof(first) === 'object') {
755
+ first = JSON.stringify(first);
756
+ decodedKey1 = JSON.stringify(decodedKey1);
757
+ }
758
+ if (_typeof(second) === 'object') {
759
+ second = JSON.stringify(second);
760
+ decodedKey2 = JSON.stringify(decodedKey2);
761
+ }
744
762
 
745
- /**
746
- * @type {{
747
- * [key: string]: {
748
- * encode: (param: any, inArray?: boolean) => string,
749
- * decode: (param: string, inArray?: boolean) => any
750
- * }
751
- * }}
752
- */
753
- const types = {
754
- invalid: {
755
- /**
756
- * @returns {string}
757
- */
758
- encode() {
759
- return keyTypeToEncodedChar.invalid + '-';
760
- },
761
- /**
762
- * @returns {undefined}
763
- */
764
- decode() {
765
- return undefined;
766
- }
763
+ // Encoding/decoding mismatches are usually due to a loss of
764
+ // floating-point precision
765
+ if (decodedKey1 !== first) {
766
+ console.warn(first + ' was incorrectly encoded as ' + decodedKey1);
767
+ }
768
+ if (decodedKey2 !== second) {
769
+ console.warn(second + ' was incorrectly encoded as ' + decodedKey2);
770
+ }
771
+ }
772
+ return result;
773
+ }
774
+
775
+ /**
776
+ * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView
777
+ */
778
+
779
+ /**
780
+ * @typedef {ArrayBufferView|ArrayBuffer} BufferSource
781
+ */
782
+
783
+ /**
784
+ * @typedef {"number"|"date"|"string"|"binary"|"array"} KeyType
785
+ */
786
+
787
+ /**
788
+ * @typedef {any} Value
789
+ */
790
+
791
+ /**
792
+ * @typedef {any} Key
793
+ * @todo Specify possible value more precisely
794
+ */
795
+
796
+ /**
797
+ * @typedef {KeyPath[]} KeyPathArray
798
+ */
799
+ /**
800
+ * @typedef {string|KeyPathArray} KeyPath
801
+ */
802
+
803
+ /**
804
+ * @typedef {object} KeyValueObject
805
+ * @property {KeyType|"NaN"|"null"|"undefined"|"boolean"|"object"|"symbol"|
806
+ * "function"|"bigint"} type If not `KeyType`, indicates invalid value
807
+ * @property {Value} [value]
808
+ * @property {boolean} [invalid]
809
+ * @property {string} [message]
810
+ * @todo Specify acceptable `value` more precisely
811
+ */
812
+
813
+ /**
814
+ * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive
815
+ */
816
+ /**
817
+ * @typedef {ValueType[]} ValueTypeArray
818
+ */
819
+ /**
820
+ * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType
821
+ */
822
+
823
+ /**
824
+ * Encodes the keys based on their types. This is required to maintain collations
825
+ * We leave space for future keys.
826
+ * @type {{[key: string]: Integer|string}}
827
+ */
828
+ var keyTypeToEncodedChar = {
829
+ invalid: 100,
830
+ number: 200,
831
+ date: 300,
832
+ string: 400,
833
+ binary: 500,
834
+ array: 600
835
+ };
836
+
837
+ /* eslint-disable unicorn/no-top-level-side-effects -- Would be good */
838
+ var keyTypes = /** @type {(KeyType|"invalid")[]} */Object.keys(keyTypeToEncodedChar);
839
+ keyTypes.forEach(function (k) {
840
+ keyTypeToEncodedChar[k] = String.fromCodePoint(/** @type {number} */keyTypeToEncodedChar[k]);
841
+ });
842
+ /* eslint-enable unicorn/no-top-level-side-effects -- Would be good */
843
+
844
+ var encodedCharToKeyType = keyTypes.reduce(function (o, k) {
845
+ o[keyTypeToEncodedChar[k]] = k;
846
+ return o;
847
+ }, /** @type {{[key: string]: KeyType|"invalid"}} */{});
848
+
849
+ /**
850
+ * The sign values for numbers, ordered from least to greatest.
851
+ * - "negativeInfinity": Sorts below all other values.
852
+ * - "bigNegative": Negative values less than or equal to negative one.
853
+ * - "smallNegative": Negative values between negative one and zero, noninclusive.
854
+ * - "smallPositive": Positive values between zero and one, including zero but not one.
855
+ * - "largePositive": Positive values greater than or equal to one.
856
+ * - "positiveInfinity": Sorts above all other values.
857
+ */
858
+ var signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];
859
+
860
+ /**
861
+ * @typedef {any} AnyValue
862
+ */
863
+
864
+ /**
865
+ * @type {{
866
+ * [key: string]: {
867
+ * encode: (param: any, inArray?: boolean) => string,
868
+ * decode: (param: string, inArray?: boolean) => any
869
+ * }
870
+ * }}
871
+ */
872
+ var types = {
873
+ invalid: {
874
+ /**
875
+ * @returns {string}
876
+ */
877
+ encode: function encode() {
878
+ return keyTypeToEncodedChar.invalid + '-';
767
879
  },
768
- // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa
769
- // notation.
770
- //
771
- // sign: takes a value between zero and five, inclusive. Represents infinite cases
772
- // and the signs of both the exponent and the fractional part of the number.
773
- // exponent: padded to two base-32 digits, represented by the 32's compliment in the
774
- // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting.
775
- // mantissa: also called the fractional part. Normed 11-digit base-32 representation.
776
- // Represented by the 32's compliment in the "smallNegative" and "bigNegative"
777
- // cases to ensure proper lexical sorting.
778
- number: {
779
- // The encode step checks for six numeric cases and generates 14-digit encoded
780
- // sign-exponent-mantissa strings.
781
- /**
782
- * @param {number} key
783
- * @returns {string}
784
- */
785
- encode(key) {
786
- let key32 = key === Number.MIN_VALUE
787
- // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some
788
- // Node (and Chrome) versions with `Number.MIN_VALUE` being treated
789
- // as 0
790
- // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring
791
- ? '0.' + '0'.repeat(214) + '2' : Math.abs(key).toString(32);
792
- // Get the index of the decimal.
793
- const decimalIndex = key32.indexOf('.');
794
- // Remove the decimal.
795
- key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32;
796
- // Get the index of the first significant digit.
797
- const significantDigitIndex = key32.search(/[^0]/u);
798
- // Truncate leading zeros.
799
- key32 = key32.slice(significantDigitIndex);
800
- let sign, exponent, mantissa;
801
-
802
- // Finite cases:
803
- if (Number.isFinite(Number(key))) {
804
- // Negative cases:
805
- if (key < 0) {
806
- // Negative exponent case:
807
- if (key > -1) {
808
- sign = signValues.indexOf('smallNegative');
809
- exponent = padBase32Exponent(significantDigitIndex);
810
- mantissa = flipBase32(padBase32Mantissa(key32));
811
- // Non-negative exponent case:
812
- } else {
813
- sign = signValues.indexOf('bigNegative');
814
- exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length));
815
- mantissa = flipBase32(padBase32Mantissa(key32));
816
- }
817
- // Non-negative cases:
818
- // Negative exponent case:
819
- } else if (key < 1) {
820
- sign = signValues.indexOf('smallPositive');
821
- exponent = flipBase32(padBase32Exponent(significantDigitIndex));
822
- mantissa = padBase32Mantissa(key32);
880
+ /**
881
+ * @returns {undefined}
882
+ */
883
+ decode: function decode() {
884
+ return undefined;
885
+ }
886
+ },
887
+ // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa
888
+ // notation.
889
+ //
890
+ // sign: takes a value between zero and five, inclusive. Represents infinite cases
891
+ // and the signs of both the exponent and the fractional part of the number.
892
+ // exponent: padded to two base-32 digits, represented by the 32's compliment in the
893
+ // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting.
894
+ // mantissa: also called the fractional part. Normed 11-digit base-32 representation.
895
+ // Represented by the 32's compliment in the "smallNegative" and "bigNegative"
896
+ // cases to ensure proper lexical sorting.
897
+ number: {
898
+ // The encode step checks for six numeric cases and generates 14-digit encoded
899
+ // sign-exponent-mantissa strings.
900
+ /**
901
+ * @param {number} key
902
+ * @returns {string}
903
+ */
904
+ encode: function encode(key) {
905
+ var key32 = key === Number.MIN_VALUE
906
+ // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some
907
+ // Node (and Chrome) versions with `Number.MIN_VALUE` being treated
908
+ // as 0
909
+ // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring
910
+ ? '0.' + '0'.repeat(214) + '2' : Math.abs(key).toString(32);
911
+ // Get the index of the decimal.
912
+ var decimalIndex = key32.indexOf('.');
913
+ // Remove the decimal.
914
+ key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32;
915
+ // Get the index of the first significant digit.
916
+ var significantDigitIndex = key32.search(/(?:[\0-\/1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/);
917
+ // Truncate leading zeros.
918
+ key32 = key32.slice(significantDigitIndex);
919
+ var sign, exponent, mantissa;
920
+
921
+ // Finite cases:
922
+ if (Number.isFinite(Number(key))) {
923
+ // Negative cases:
924
+ if (key < 0) {
925
+ // Negative exponent case:
926
+ if (key > -1) {
927
+ sign = signValues.indexOf('smallNegative');
928
+ exponent = padBase32Exponent(significantDigitIndex);
823
929
  // Non-negative exponent case:
824
930
  } else {
825
- sign = signValues.indexOf('bigPositive');
826
- exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length);
827
- mantissa = padBase32Mantissa(key32);
931
+ sign = signValues.indexOf('bigNegative');
932
+ exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length));
828
933
  }
829
- // Infinite cases:
934
+ mantissa = flipBase32(padBase32Mantissa(key32));
935
+ // Non-negative cases:
936
+ // Negative exponent case:
937
+ } else if (key < 1) {
938
+ sign = signValues.indexOf('smallPositive');
939
+ exponent = flipBase32(padBase32Exponent(significantDigitIndex));
940
+ mantissa = padBase32Mantissa(key32);
941
+ // Non-negative exponent case:
830
942
  } else {
831
- exponent = zeros(2);
832
- mantissa = zeros(11);
833
- sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity');
834
- }
835
- return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;
836
- },
837
- // The decode step must interpret the sign, reflip values encoded as the 32's complements,
838
- // apply signs to the exponent and mantissa, do the base-32 power operation, and return
839
- // the original JavaScript number values.
840
- /**
841
- * @param {string} key
842
- * @returns {number}
843
- */
844
- decode(key) {
845
- const sign = Number(key.slice(2, 3));
846
- let exponent = key.slice(3, 5);
847
- let mantissa = key.slice(5, 16);
848
- switch (signValues[sign]) {
849
- case 'negativeInfinity':
850
- return Number.NEGATIVE_INFINITY;
851
- case 'positiveInfinity':
852
- return Number.POSITIVE_INFINITY;
853
- case 'bigPositive':
854
- return pow32(mantissa, exponent);
855
- case 'smallPositive':
856
- exponent = negate(flipBase32(exponent));
857
- return pow32(mantissa, exponent);
858
- case 'smallNegative':
859
- exponent = negate(exponent);
860
- mantissa = flipBase32(mantissa);
861
- return -pow32(mantissa, exponent);
862
- case 'bigNegative':
863
- exponent = flipBase32(exponent);
864
- mantissa = flipBase32(mantissa);
865
- return -pow32(mantissa, exponent);
866
- default:
867
- throw new Error('Invalid number.');
943
+ sign = signValues.indexOf('bigPositive');
944
+ exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length);
945
+ mantissa = padBase32Mantissa(key32);
868
946
  }
947
+ // Infinite cases:
948
+ } else {
949
+ exponent = zeros(2);
950
+ mantissa = zeros(11);
951
+ sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity');
869
952
  }
953
+ return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;
870
954
  },
871
- // Strings are encoded as JSON strings (with quotes and unicode characters escaped).
872
- //
873
- // If the strings are in an array, then some extra encoding is done to make sorting work correctly:
874
- // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly
875
- // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.
876
- // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string.
877
- // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,
878
- // the indexes of each string's characters line up with each other.
879
- string: {
880
- /**
881
- * @param {string} key
882
- * @param {boolean} [inArray]
883
- * @returns {string}
884
- */
885
- encode(key, inArray) {
886
- if (inArray) {
887
- // prepend each character with a dash, and append a space to the end
888
- key = key.replaceAll(/(.)/gu, '-$1') + ' ';
889
- }
890
- return keyTypeToEncodedChar.string + '-' + key;
891
- },
892
- /**
893
- * @param {string} key
894
- * @param {boolean} [inArray]
895
- * @returns {string}
896
- */
897
- decode(key, inArray) {
898
- key = key.slice(2);
899
- if (inArray) {
900
- // remove the space at the end, and the dash before each character
901
- key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');
902
- }
903
- return key;
955
+ // The decode step must interpret the sign, reflip values encoded as the 32's complements,
956
+ // apply signs to the exponent and mantissa, do the base-32 power operation, and return
957
+ // the original JavaScript number values.
958
+ /**
959
+ * @param {string} key
960
+ * @returns {number}
961
+ */
962
+ decode: function decode(key) {
963
+ var sign = Number(key.slice(2, 3));
964
+ var exponent = key.slice(3, 5);
965
+ var mantissa = key.slice(5, 16);
966
+ switch (signValues[sign]) {
967
+ case 'negativeInfinity':
968
+ return -Infinity;
969
+ case 'positiveInfinity':
970
+ return Infinity;
971
+ case 'bigPositive':
972
+ return pow32(mantissa, exponent);
973
+ case 'smallPositive':
974
+ exponent = negate(flipBase32(exponent));
975
+ return pow32(mantissa, exponent);
976
+ case 'smallNegative':
977
+ exponent = negate(exponent);
978
+ mantissa = flipBase32(mantissa);
979
+ return -pow32(mantissa, exponent);
980
+ case 'bigNegative':
981
+ exponent = flipBase32(exponent);
982
+ mantissa = flipBase32(mantissa);
983
+ return -pow32(mantissa, exponent);
984
+ default:
985
+ throw new Error('Invalid number.');
904
986
  }
905
- },
906
- // Arrays are encoded as JSON strings.
907
- // An extra, value is added to each array during encoding to make
908
- // empty arrays sort correctly.
909
- array: {
910
- /**
911
- * @param {ValueTypeArray} key
912
- * @returns {string}
913
- */
914
- encode(key) {
915
- const encoded = [];
916
- for (const [i, item] of key.entries()) {
917
- const encodedItem = encode(item, true); // encode the array item
918
- encoded[i] = encodedItem;
919
- }
920
- encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly
921
- return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);
922
- },
923
- /**
924
- * @param {string} key
925
- * @returns {ValueTypeArray}
926
- */
927
- decode(key) {
928
- const decoded = JSON.parse(key.slice(2));
929
- decoded.pop(); // remove the extra item
930
- for (let i = 0; i < decoded.length; i++) {
931
- const item = decoded[i];
932
- const decodedItem = decode(item, true); // decode the item
933
- decoded[i] = decodedItem;
934
- }
935
- return decoded;
987
+ }
988
+ },
989
+ // Strings are encoded as JSON strings (with quotes and unicode characters escaped).
990
+ //
991
+ // If the strings are in an array, then some extra encoding is done to make sorting work correctly:
992
+ // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly
993
+ // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.
994
+ // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string.
995
+ // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,
996
+ // the indexes of each string's characters line up with each other.
997
+ string: {
998
+ /**
999
+ * @param {string} key
1000
+ * @param {boolean} [inArray]
1001
+ * @returns {string}
1002
+ */
1003
+ encode: function encode(key, inArray) {
1004
+ if (inArray) {
1005
+ // prepend each character with a dash, and append a space to the end
1006
+ key = key.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') + ' ';
936
1007
  }
1008
+ return keyTypeToEncodedChar.string + '-' + key;
937
1009
  },
938
- // Dates are encoded as ISO 8601 strings, in UTC time zone.
939
- date: {
940
- /**
941
- * @param {Date} key
942
- * @returns {string}
943
- */
944
- encode(key) {
945
- return keyTypeToEncodedChar.date + '-' + key.toJSON();
946
- },
947
- /**
948
- * @param {string} key
949
- * @returns {Date}
950
- */
951
- decode(key) {
952
- return new Date(key.slice(2));
1010
+ /**
1011
+ * @param {string} key
1012
+ * @param {boolean} [inArray]
1013
+ * @returns {string}
1014
+ */
1015
+ decode: function decode(key, inArray) {
1016
+ key = key.slice(2);
1017
+ if (inArray) {
1018
+ // remove the space at the end, and the dash before each character
1019
+ key = key.slice(0, -1).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');
1020
+ }
1021
+ return key;
1022
+ }
1023
+ },
1024
+ // Arrays are encoded as JSON strings.
1025
+ // An extra, value is added to each array during encoding to make
1026
+ // empty arrays sort correctly.
1027
+ array: {
1028
+ /**
1029
+ * @param {ValueTypeArray} key
1030
+ * @returns {string}
1031
+ */
1032
+ encode: function encode(key) {
1033
+ var encoded = [];
1034
+ var _iterator = _createForOfIteratorHelper(key.entries()),
1035
+ _step;
1036
+ try {
1037
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1038
+ var _step$value = _slicedToArray(_step.value, 2),
1039
+ i = _step$value[0],
1040
+ item = _step$value[1];
1041
+ var encodedItem = _encode(item, true); // encode the array item
1042
+ encoded[i] = encodedItem;
1043
+ }
1044
+ } catch (err) {
1045
+ _iterator.e(err);
1046
+ } finally {
1047
+ _iterator.f();
953
1048
  }
1049
+ encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly
1050
+ return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);
954
1051
  },
955
- binary: {
956
- // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)
957
- /**
958
- * @param {BufferSource} key
959
- * @returns {string}
960
- */
961
- encode(key) {
962
- return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? [...getCopyBytesHeldByBufferSource(key)].map(b => String(b).padStart(3, '0')) // e.g., '255,005,254,000,001,033'
963
- : '');
964
- },
965
- /**
966
- * @param {string} key
967
- * @returns {ArrayBuffer}
968
- */
969
- decode(key) {
970
- // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
971
- const k = key.slice(2);
972
- const arr = k.length ? k.split(',').map(s => Number.parseInt(s)) : [];
973
- const buffer = new ArrayBuffer(arr.length);
974
- const uint8 = new Uint8Array(buffer);
975
- uint8.set(arr);
976
- return buffer;
1052
+ /**
1053
+ * @param {string} key
1054
+ * @returns {ValueTypeArray}
1055
+ */
1056
+ decode: function decode(key) {
1057
+ var decoded = JSON.parse(key.slice(2));
1058
+ decoded.pop(); // remove the extra item
1059
+ for (var i = 0; i < decoded.length; i++) {
1060
+ var item = decoded[i];
1061
+ var decodedItem = _decode(item, true); // decode the item
1062
+ decoded[i] = decodedItem;
977
1063
  }
1064
+ return decoded;
978
1065
  }
979
- };
980
-
981
- /**
982
- * Return a padded base-32 exponent value.
983
- * @param {number} n
984
- * @returns {string}
985
- */
986
- function padBase32Exponent(n) {
987
- const exp = n.toString(32);
988
- return exp.length === 1 ? '0' + exp : exp;
989
- }
990
-
991
- /**
992
- * Return a padded base-32 mantissa.
993
- * @param {string} s
994
- * @returns {string}
995
- */
996
- function padBase32Mantissa(s) {
997
- return (s + zeros(11)).slice(0, 11);
998
- }
999
-
1000
- /**
1001
- * Flips each digit of a base-32 encoded string.
1002
- * @param {string} encoded
1003
- * @returns {string}
1004
- */
1005
- function flipBase32(encoded) {
1006
- let flipped = '';
1007
- for (const ch of encoded) {
1008
- flipped += (31 - Number.parseInt(ch, 32)).toString(32);
1009
- }
1010
- return flipped;
1011
- }
1012
-
1013
- /**
1014
- * Base-32 power function.
1015
- * RESEARCH: This function does not precisely decode floats because it performs
1016
- * floating point arithmetic to recover values. But can the original values be
1017
- * recovered exactly?
1018
- * Someone may have already figured out a good way to store JavaScript floats as
1019
- * binary strings and convert back. Barring a better method, however, one route
1020
- * may be to generate decimal strings that `parseFloat` decodes predictably.
1021
- * @param {string} mantissa
1022
- * @param {string} exponent
1023
- * @returns {number}
1024
- */
1025
- function pow32(mantissa, exponent) {
1026
- const exp = Number.parseInt(exponent, 32);
1027
- if (exp < 0) {
1028
- return roundToPrecision(Number.parseInt(mantissa, 32) * 32 ** (exp - 10));
1066
+ },
1067
+ // Dates are encoded as ISO 8601 strings, in UTC time zone.
1068
+ date: {
1069
+ /**
1070
+ * @param {Date} key
1071
+ * @returns {string}
1072
+ */
1073
+ encode: function encode(key) {
1074
+ return keyTypeToEncodedChar.date + '-' + key.toJSON();
1075
+ },
1076
+ /**
1077
+ * @param {string} key
1078
+ * @returns {Date}
1079
+ */
1080
+ decode: function decode(key) {
1081
+ return new Date(key.slice(2));
1029
1082
  }
1030
- if (exp < 11) {
1031
- const whole = mantissa.slice(0, exp);
1032
- const wholeNum = Number.parseInt(whole, 32);
1033
- const fraction = mantissa.slice(exp);
1034
- const fractionNum = Number.parseInt(fraction, 32) * 32 ** (exp - 11);
1035
- return roundToPrecision(wholeNum + fractionNum);
1083
+ },
1084
+ binary: {
1085
+ // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)
1086
+ /**
1087
+ * @param {BufferSource} key
1088
+ * @returns {string}
1089
+ */
1090
+ encode: function encode(key) {
1091
+ return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? _toConsumableArray(getCopyBytesHeldByBufferSource(key)).map(function (b) {
1092
+ return String(b).padStart(3, '0');
1093
+ }) // e.g., '255,005,254,000,001,033'
1094
+ : '');
1095
+ },
1096
+ /**
1097
+ * @param {string} key
1098
+ * @returns {ArrayBuffer}
1099
+ */
1100
+ decode: function decode(key) {
1101
+ // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1102
+ var k = key.slice(2);
1103
+ var arr = k.length ? k.split(',').map(Number) : [];
1104
+ var buffer = new ArrayBuffer(arr.length);
1105
+ var uint8 = new Uint8Array(buffer);
1106
+ uint8.set(arr);
1107
+ return buffer;
1036
1108
  }
1037
- const expansion = mantissa + zeros(exp - 11);
1038
- return Number.parseInt(expansion, 32);
1039
1109
  }
1040
-
1041
- /**
1042
- * @typedef {number} Float
1043
- */
1044
-
1045
- /**
1046
- * @param {Float} num
1047
- * @param {Float} [precision]
1048
- * @returns {Float}
1049
- */
1050
- function roundToPrecision(num, precision = 16) {
1051
- return Number.parseFloat(num.toPrecision(precision));
1110
+ };
1111
+
1112
+ /**
1113
+ * Return a padded base-32 exponent value.
1114
+ * @param {number} n
1115
+ * @returns {string}
1116
+ */
1117
+ function padBase32Exponent(n) {
1118
+ var exp = n.toString(32);
1119
+ return exp.length === 1 ? '0' + exp : exp;
1120
+ }
1121
+
1122
+ /**
1123
+ * Return a padded base-32 mantissa.
1124
+ * @param {string} s
1125
+ * @returns {string}
1126
+ */
1127
+ function padBase32Mantissa(s) {
1128
+ return (s + zeros(11)).slice(0, 11);
1129
+ }
1130
+
1131
+ /**
1132
+ * Flips each digit of a base-32 encoded string.
1133
+ * @param {string} encoded
1134
+ * @returns {string}
1135
+ */
1136
+ function flipBase32(encoded) {
1137
+ var flipped = '';
1138
+ var _iterator2 = _createForOfIteratorHelper(encoded),
1139
+ _step2;
1140
+ try {
1141
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1142
+ var ch = _step2.value;
1143
+ flipped += (31 - Number.parseInt(ch, 32)).toString(32);
1144
+ }
1145
+ } catch (err) {
1146
+ _iterator2.e(err);
1147
+ } finally {
1148
+ _iterator2.f();
1052
1149
  }
1053
-
1054
- /**
1055
- * Returns a string of n zeros.
1056
- * @param {number} n
1057
- * @returns {string}
1058
- */
1059
- function zeros(n) {
1060
- return '0'.repeat(n);
1150
+ return flipped;
1151
+ }
1152
+
1153
+ /**
1154
+ * Base-32 power function.
1155
+ * RESEARCH: This function does not precisely decode floats because it performs
1156
+ * floating point arithmetic to recover values. But can the original values be
1157
+ * recovered exactly?
1158
+ * Someone may have already figured out a good way to store JavaScript floats as
1159
+ * binary strings and convert back. Barring a better method, however, one route
1160
+ * may be to generate decimal strings that `parseFloat` decodes predictably.
1161
+ * @param {string} mantissa
1162
+ * @param {string} exponent
1163
+ * @returns {number}
1164
+ */
1165
+ function pow32(mantissa, exponent) {
1166
+ var exp = Number.parseInt(exponent, 32);
1167
+ if (exp < 0) {
1168
+ return roundToPrecision(Number.parseInt(mantissa, 32) * Math.pow(32, exp - 10));
1061
1169
  }
1062
-
1063
- /**
1064
- * Negates numeric strings.
1065
- * @param {string} s
1066
- * @returns {string}
1067
- */
1068
- function negate(s) {
1069
- return '-' + s;
1170
+ if (exp < 11) {
1171
+ var whole = mantissa.slice(0, exp);
1172
+ var wholeNum = Number.parseInt(whole, 32);
1173
+ var fraction = mantissa.slice(exp);
1174
+ var fractionNum = Number.parseInt(fraction, 32) * Math.pow(32, exp - 11);
1175
+ return roundToPrecision(wholeNum + fractionNum);
1070
1176
  }
1071
-
1072
- /**
1073
- * @param {Key} key
1074
- * @returns {KeyType|"invalid"}
1075
- */
1076
- function getKeyType(key) {
1077
- if (Array.isArray(key)) {
1078
- return 'array';
1079
- }
1080
- if (isDate(key)) {
1081
- return 'date';
1082
- }
1083
- if (isBinary(key)) {
1084
- return 'binary';
1085
- }
1086
- const keyType = typeof key;
1087
- return ['string', 'number'].includes(keyType) ? (/** @type {"string"|"number"} */keyType) : 'invalid';
1177
+ var expansion = mantissa + zeros(exp - 11);
1178
+ return Number.parseInt(expansion, 32);
1179
+ }
1180
+
1181
+ /**
1182
+ * @typedef {number} Float
1183
+ */
1184
+
1185
+ /**
1186
+ * @param {Float} num
1187
+ * @param {Float} [precision]
1188
+ * @returns {Float}
1189
+ */
1190
+ function roundToPrecision(num) {
1191
+ var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;
1192
+ return Number(num.toPrecision(precision));
1193
+ }
1194
+
1195
+ /**
1196
+ * Returns a string of n zeros.
1197
+ * @param {number} n
1198
+ * @returns {string}
1199
+ */
1200
+ function zeros(n) {
1201
+ return '0'.repeat(n);
1202
+ }
1203
+
1204
+ /**
1205
+ * Negates numeric strings.
1206
+ * @param {string} s
1207
+ * @returns {string}
1208
+ */
1209
+ function negate(s) {
1210
+ return '-' + s;
1211
+ }
1212
+
1213
+ /**
1214
+ * @param {Key} key
1215
+ * @returns {KeyType|"invalid"}
1216
+ */
1217
+ function getKeyType(key) {
1218
+ if (Array.isArray(key)) {
1219
+ return 'array';
1088
1220
  }
1089
-
1090
- /**
1091
- * Keys must be strings, numbers (besides `NaN`), Dates (if value is not
1092
- * `NaN`), binary objects or Arrays.
1093
- * @param {Value} input The key input
1094
- * @param {Value[]|null|undefined} [seen] An array of already seen keys
1095
- * @returns {KeyValueObject}
1096
- */
1097
- function convertValueToKey(input, seen) {
1098
- return convertValueToKeyValueDecoded(input, seen, false, true);
1221
+ if (isDate(key)) {
1222
+ return 'date';
1099
1223
  }
1100
-
1101
- /**
1102
- * Currently not in use.
1103
- * @param {Value} input
1104
- * @returns {KeyValueObject}
1105
- */
1106
- function convertValueToMultiEntryKey(input) {
1107
- return convertValueToKeyValueDecoded(input, null, true, true);
1224
+ if (isBinary(key)) {
1225
+ return 'binary';
1108
1226
  }
1109
-
1110
- /**
1111
- *
1112
- * @param {BufferSource} O
1113
- * @throws {TypeError}
1114
- * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1115
- * @returns {Uint8Array}
1116
- */
1117
- function getCopyBytesHeldByBufferSource(O) {
1118
- let offset = 0;
1119
- let length = 0;
1120
- if (ArrayBuffer.isView(O)) {
1121
- // Has [[ViewedArrayBuffer]] internal slot
1122
- const arrayBuffer = O.buffer;
1123
- if (arrayBuffer === undefined) {
1124
- throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
1125
- }
1126
- offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
1127
- length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)
1128
- } else {
1129
- length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)
1227
+ var keyType = _typeof(key);
1228
+ return ['string', 'number'].includes(keyType) ? (/** @type {"string"|"number"} */keyType) : 'invalid';
1229
+ }
1230
+
1231
+ /**
1232
+ * Keys must be strings, numbers (besides `NaN`), Dates (if value is not
1233
+ * `NaN`), binary objects or Arrays.
1234
+ * @param {Value} input The key input
1235
+ * @param {Value[]|null|undefined} [seen] An array of already seen keys
1236
+ * @returns {KeyValueObject}
1237
+ */
1238
+ function convertValueToKey(input, seen) {
1239
+ return convertValueToKeyValueDecoded(input, seen, false, true);
1240
+ }
1241
+
1242
+ /**
1243
+ * Currently not in use.
1244
+ * @param {Value} input
1245
+ * @returns {KeyValueObject}
1246
+ */
1247
+ function convertValueToMultiEntryKey(input) {
1248
+ return convertValueToKeyValueDecoded(input, null, true, true);
1249
+ }
1250
+
1251
+ /**
1252
+ *
1253
+ * @param {BufferSource} O
1254
+ * @throws {TypeError}
1255
+ * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1256
+ * @returns {Uint8Array}
1257
+ */
1258
+ function getCopyBytesHeldByBufferSource(O) {
1259
+ var offset = 0;
1260
+ var length;
1261
+ if (ArrayBuffer.isView(O)) {
1262
+ // Has [[ViewedArrayBuffer]] internal slot
1263
+ var arrayBuffer = O.buffer;
1264
+ if (arrayBuffer === undefined) {
1265
+ throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
1130
1266
  }
1131
- // const octets = new Uint8Array(input);
1132
- // const octets = types.binary.decode(types.binary.encode(input));
1133
- return new Uint8Array(
1134
- // Should allow DataView
1135
- /** @type {ArrayBuffer} */
1136
- 'buffer' in O && O.buffer || O, offset, length);
1267
+ offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
1268
+ length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)
1269
+ } else {
1270
+ length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)
1137
1271
  }
1138
-
1139
- /**
1140
- * Shortcut utility to avoid returning full keys from `convertValueToKey`
1141
- * and subsequent need to process in calling code unless `fullKeys` is
1142
- * set; may throw.
1143
- * @param {Value} input
1144
- * @param {Value[]|null} [seen]
1145
- * @param {boolean} [multiEntry]
1146
- * @param {boolean} [fullKeys]
1147
- * @throws {TypeError} See `getCopyBytesHeldByBufferSource`
1148
- * @todo Document other allowable `input`
1149
- * @returns {KeyValueObject}
1150
- */
1151
- function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) {
1152
- seen = seen || [];
1153
- if (seen.includes(input)) {
1154
- return {
1155
- type: 'array',
1156
- invalid: true,
1157
- message: 'An array key cannot be circular'
1158
- };
1159
- }
1160
- const type = getKeyType(input);
1161
- const ret = {
1162
- type,
1163
- value: input
1272
+ // const octets = new Uint8Array(input);
1273
+ // const octets = types.binary.decode(types.binary.encode(input));
1274
+ return new Uint8Array(
1275
+ // Should allow DataView
1276
+ /** @type {ArrayBuffer} */
1277
+ 'buffer' in O && O.buffer || O, offset, length);
1278
+ }
1279
+
1280
+ /**
1281
+ * Shortcut utility to avoid returning full keys from `convertValueToKey`
1282
+ * and subsequent need to process in calling code unless `fullKeys` is
1283
+ * set; may throw.
1284
+ * @param {Value} input
1285
+ * @param {Value[]|null} [seen]
1286
+ * @param {boolean} [multiEntry]
1287
+ * @param {boolean} [fullKeys]
1288
+ * @throws {TypeError} See `getCopyBytesHeldByBufferSource`
1289
+ * @todo Document other allowable `input`
1290
+ * @returns {KeyValueObject}
1291
+ */
1292
+ function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) {
1293
+ seen || (seen = []);
1294
+ if (seen.includes(input)) {
1295
+ return {
1296
+ type: 'array',
1297
+ invalid: true,
1298
+ message: 'An array key cannot be circular'
1164
1299
  };
1165
- switch (type) {
1166
- case 'number':
1167
- {
1168
- if (Number.isNaN(input)) {
1169
- // List as 'NaN' type for convenience of consumers in reporting errors
1170
- return {
1171
- type: 'NaN',
1172
- invalid: true
1173
- };
1174
- }
1175
-
1176
- // https://github.com/w3c/IndexedDB/issues/375
1177
- // https://github.com/w3c/IndexedDB/pull/386
1178
- if (Object.is(input, -0)) {
1179
- return {
1180
- type,
1181
- value: 0
1182
- };
1183
- }
1184
- return /** @type {{type: KeyType; value: Value}} */ret;
1185
- }
1186
- case 'string':
1187
- {
1188
- return /** @type {{type: KeyType; value: Value}} */ret;
1300
+ }
1301
+ var type = getKeyType(input);
1302
+ var ret = {
1303
+ type: type,
1304
+ value: input
1305
+ };
1306
+ switch (type) {
1307
+ case 'number':
1308
+ {
1309
+ if (Number.isNaN(input)) {
1310
+ // List as 'NaN' type for convenience of consumers in reporting errors
1311
+ return {
1312
+ type: 'NaN',
1313
+ invalid: true
1314
+ };
1189
1315
  }
1190
- case 'binary':
1191
- {
1192
- // May throw (if detached)
1193
- // Get a copy of the bytes held by the buffer source
1194
- // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1195
- const octets = getCopyBytesHeldByBufferSource(/** @type {BufferSource} */input);
1316
+
1317
+ // https://github.com/w3c/IndexedDB/issues/375
1318
+ // https://github.com/w3c/IndexedDB/pull/386
1319
+ if (Object.is(input, -0)) {
1196
1320
  return {
1197
- type: 'binary',
1198
- value: octets
1321
+ type: type,
1322
+ value: 0
1199
1323
  };
1200
1324
  }
1201
- case 'array':
1202
- {
1203
- // May throw (from binary)
1204
- const arr = /** @type {Array<any>} */input;
1205
- const len = arr.length;
1206
- seen.push(input);
1207
-
1208
- /** @type {(KeyValueObject|Value)[]} */
1209
- const keys = [];
1210
- for (let i = 0; i < len; i++) {
1325
+ return /** @type {{type: KeyType; value: Value}} */ret;
1326
+ }
1327
+ case 'string':
1328
+ {
1329
+ return /** @type {{type: KeyType; value: Value}} */ret;
1330
+ }
1331
+ case 'binary':
1332
+ {
1333
+ // May throw (if detached)
1334
+ // Get a copy of the bytes held by the buffer source
1335
+ // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1336
+ var octets = getCopyBytesHeldByBufferSource(/** @type {BufferSource} */input);
1337
+ return {
1338
+ type: 'binary',
1339
+ value: octets
1340
+ };
1341
+ }
1342
+ case 'array':
1343
+ {
1344
+ // May throw (from binary)
1345
+ var arr = /** @type {Array<any>} */input;
1346
+ var len = arr.length;
1347
+ seen.push(input);
1348
+
1349
+ /** @type {(KeyValueObject|Value)[]} */
1350
+ var keys = [];
1351
+ var _loop = function _loop() {
1211
1352
  // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated
1212
1353
  if (!multiEntry && !Object.hasOwn(arr, i)) {
1213
1354
  return {
1214
- type,
1215
- invalid: true,
1216
- message: 'Does not have own index property'
1355
+ v: {
1356
+ type: type,
1357
+ invalid: true,
1358
+ message: 'Does not have own index property'
1359
+ }
1217
1360
  };
1218
1361
  }
1219
1362
  try {
1220
- const entry = arr[i];
1221
- const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry
1363
+ var entry = arr[i];
1364
+ var key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry
1222
1365
  if (key.invalid) {
1223
1366
  if (multiEntry) {
1224
- continue;
1367
+ return 0; // continue
1225
1368
  }
1226
1369
  return {
1227
- type,
1228
- invalid: true,
1229
- message: 'Bad array entry value-to-key conversion'
1370
+ v: {
1371
+ type: type,
1372
+ invalid: true,
1373
+ message: 'Bad array entry value-to-key conversion'
1374
+ }
1230
1375
  };
1231
1376
  }
1232
- if (!multiEntry || !fullKeys && keys.every(k => cmp(k, key.value) !== 0) || fullKeys && keys.every(k => cmp(k, key) !== 0)) {
1377
+ if (!multiEntry || !fullKeys && keys.every(function (k) {
1378
+ return cmp(k, key.value) !== 0;
1379
+ }) || fullKeys && keys.every(function (k) {
1380
+ return cmp(k, key) !== 0;
1381
+ })) {
1233
1382
  keys.push(fullKeys ? key : key.value);
1234
1383
  }
1235
1384
  } catch (err) {
@@ -1237,299 +1386,317 @@
1237
1386
  throw err;
1238
1387
  }
1239
1388
  }
1240
- }
1241
- return {
1242
- type,
1243
- value: keys
1244
- };
1245
- }
1246
- case 'date':
1247
- {
1248
- const date = /** @type {Date} */input;
1249
- if (!Number.isNaN(date.getTime())) {
1250
- return fullKeys ? {
1251
- type,
1252
- value: date.getTime()
1253
- } : {
1254
- type,
1255
- value: new Date(date)
1256
- };
1257
- }
1258
- return {
1259
- type,
1260
- invalid: true,
1261
- message: 'Not a valid date'
1262
- };
1263
- // Falls through
1389
+ },
1390
+ _ret;
1391
+ for (var i = 0; i < len; i++) {
1392
+ _ret = _loop();
1393
+ if (_ret === 0) continue;
1394
+ if (_ret) return _ret.v;
1264
1395
  }
1265
- case 'invalid':
1266
- default:
1267
- {
1268
- // Other `typeof` types which are not valid keys:
1269
- // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'
1270
- const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors
1271
- return {
1272
- type,
1273
- invalid: true,
1274
- message: 'Not a valid key; type ' + type
1396
+ return {
1397
+ type: type,
1398
+ value: keys
1399
+ };
1400
+ }
1401
+ case 'date':
1402
+ {
1403
+ var date = /** @type {Date} */input;
1404
+ if (!Number.isNaN(date.getTime())) {
1405
+ return fullKeys ? {
1406
+ type: type,
1407
+ value: date.getTime()
1408
+ } : {
1409
+ type: type,
1410
+ value: new Date(date)
1275
1411
  };
1276
1412
  }
1277
- }
1278
- }
1279
-
1280
- /**
1281
- *
1282
- * @param {Key} key
1283
- * @param {boolean} [fullKeys]
1284
- * @returns {KeyValueObject}
1285
- * @todo Document other allowable `key`?
1286
- */
1287
- function convertValueToMultiEntryKeyDecoded(key, fullKeys) {
1288
- return convertValueToKeyValueDecoded(key, null, true, fullKeys);
1289
- }
1290
-
1291
- /**
1292
- * An internal utility.
1293
- * @param {Value} input
1294
- * @param {Value[]|null|undefined} [seen]
1295
- * @throws {DOMException} `DataError`
1296
- * @returns {KeyValueObject}
1297
- */
1298
- function convertValueToKeyRethrowingAndIfInvalid(input, seen) {
1299
- const key = convertValueToKey(input, seen);
1300
- if (key.invalid) {
1301
- throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);
1302
- }
1303
- return key;
1413
+ return {
1414
+ type: type,
1415
+ invalid: true,
1416
+ message: 'Not a valid date'
1417
+ };
1418
+ // Falls through
1419
+ }
1420
+ case 'invalid':
1421
+ default:
1422
+ {
1423
+ // Other `typeof` types which are not valid keys:
1424
+ // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'
1425
+ var _type = input === null ? 'null' : _typeof(input); // Convert `null` for convenience of consumers in reporting errors
1426
+ return {
1427
+ type: _type,
1428
+ invalid: true,
1429
+ message: 'Not a valid key; type ' + _type
1430
+ };
1431
+ }
1304
1432
  }
1305
-
1306
- /**
1307
- *
1308
- * @param {Value} value
1309
- * @param {KeyPath} keyPath
1310
- * @param {boolean} multiEntry
1311
- * @returns {KeyValueObject|KeyPathEvaluateValue}
1312
- * @todo Document other possible return?
1313
- */
1314
- function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) {
1315
- return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);
1433
+ }
1434
+
1435
+ /**
1436
+ *
1437
+ * @param {Key} key
1438
+ * @param {boolean} [fullKeys]
1439
+ * @returns {KeyValueObject}
1440
+ * @todo Document other allowable `key`?
1441
+ */
1442
+ function convertValueToMultiEntryKeyDecoded(key, fullKeys) {
1443
+ return convertValueToKeyValueDecoded(key, null, true, fullKeys);
1444
+ }
1445
+
1446
+ /**
1447
+ * An internal utility.
1448
+ * @param {Value} input
1449
+ * @param {Value[]|null|undefined} [seen]
1450
+ * @throws {DOMException} `DataError`
1451
+ * @returns {KeyValueObject}
1452
+ */
1453
+ function convertValueToKeyRethrowingAndIfInvalid(input, seen) {
1454
+ var key = convertValueToKey(input, seen);
1455
+ if (key.invalid) {
1456
+ throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);
1316
1457
  }
1317
- /**
1318
- * Not currently in use.
1319
- * @param {Value} value
1320
- * @param {KeyPath} keyPath
1321
- * @param {boolean} multiEntry
1322
- * @returns {KeyPathEvaluateValue}
1323
- */
1324
- function evaluateKeyPathOnValue(value, keyPath, multiEntry) {
1325
- return evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1458
+ return key;
1459
+ }
1460
+
1461
+ /**
1462
+ *
1463
+ * @param {Value} value
1464
+ * @param {KeyPath} keyPath
1465
+ * @param {boolean} multiEntry
1466
+ * @returns {KeyValueObject|KeyPathEvaluateValue}
1467
+ * @todo Document other possible return?
1468
+ */
1469
+ function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) {
1470
+ return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);
1471
+ }
1472
+ /**
1473
+ * Not currently in use.
1474
+ * @param {Value} value
1475
+ * @param {KeyPath} keyPath
1476
+ * @param {boolean} multiEntry
1477
+ * @returns {KeyPathEvaluateValue}
1478
+ */
1479
+ function evaluateKeyPathOnValue(value, keyPath, multiEntry) {
1480
+ return evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1481
+ }
1482
+
1483
+ /**
1484
+ * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)
1485
+ * or `{invalid: true}` (e.g., `NaN`).
1486
+ * @param {Value} value
1487
+ * @param {KeyPath} keyPath
1488
+ * @param {boolean} [multiEntry]
1489
+ * @param {boolean} [fullKeys]
1490
+ * @returns {KeyValueObject|KeyPathEvaluateValue}
1491
+ * @todo Document other possible return?
1492
+ */
1493
+ function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) {
1494
+ var r = evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1495
+ if (r.failure) {
1496
+ return r;
1326
1497
  }
1327
-
1328
- /**
1329
- * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)
1330
- * or `{invalid: true}` (e.g., `NaN`).
1331
- * @param {Value} value
1332
- * @param {KeyPath} keyPath
1333
- * @param {boolean} [multiEntry]
1334
- * @param {boolean} [fullKeys]
1335
- * @returns {KeyValueObject|KeyPathEvaluateValue}
1336
- * @todo Document other possible return?
1337
- */
1338
- function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) {
1339
- const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1340
- if (r.failure) {
1341
- return r;
1342
- }
1343
- if (!multiEntry) {
1344
- return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);
1345
- }
1346
- return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);
1498
+ if (!multiEntry) {
1499
+ return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);
1347
1500
  }
1348
-
1349
- /**
1350
- * Unused?
1351
- * @typedef {object} KeyPathEvaluateFailure
1352
- * @property {boolean} failure
1353
- */
1354
-
1355
- /**
1356
- * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray
1357
- */
1358
-
1359
- /**
1360
- * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue
1361
- */
1362
-
1363
- /**
1364
- * @typedef {object} KeyPathEvaluateValue
1365
- * @property {KeyPathEvaluateValueValue} [value]
1366
- * @property {boolean} [failure]
1367
- */
1368
-
1369
- /**
1370
- * Returns the value of an inline key based on a key path (wrapped in an
1371
- * object with key `value`) or `{failure: true}`
1372
- * @param {Value} value
1373
- * @param {KeyPath} keyPath
1374
- * @param {boolean} [multiEntry]
1375
- * @param {boolean} [fullKeys]
1376
- * @returns {KeyPathEvaluateValue}
1377
- */
1378
- function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) {
1379
- if (Array.isArray(keyPath)) {
1380
- /** @type {KeyPathEvaluateValueValueArray} */
1381
- const result = [];
1382
- return keyPath.some(item => {
1383
- const key = evaluateKeyPathOnValueToDecodedValue(value, item);
1384
- if (key.failure) {
1385
- return true;
1386
- }
1387
- result.push(key.value);
1388
- return false;
1389
- }) ? {
1390
- failure: true
1391
- } : {
1392
- value: result
1393
- };
1394
- }
1395
- if (keyPath === '') {
1396
- return {
1397
- value
1398
- };
1399
- }
1400
- const identifiers = keyPath.split('.');
1401
- return identifiers.some(idntfr => {
1402
- if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) {
1403
- value = value.length;
1404
- } else if (isBlob(value)) {
1405
- switch (idntfr) {
1406
- case 'size':
1407
- case 'type':
1408
- value = /** @type {Blob} */value[idntfr];
1409
- break;
1410
- }
1411
- } else if (isFile(value)) {
1412
- switch (idntfr) {
1413
- case 'name':
1414
- case 'lastModified':
1415
- value = /** @type {File} */value[idntfr];
1416
- break;
1417
- case 'lastModifiedDate':
1418
- value = new Date(/** @type {File} */value.lastModified);
1419
- break;
1420
- }
1421
- } else if (!isObj(value) || !Object.hasOwn(value, idntfr)) {
1501
+ return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);
1502
+ }
1503
+
1504
+ /**
1505
+ * Unused?
1506
+ * @typedef {object} KeyPathEvaluateFailure
1507
+ * @property {boolean} failure
1508
+ */
1509
+
1510
+ /**
1511
+ * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray
1512
+ */
1513
+
1514
+ /**
1515
+ * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue
1516
+ */
1517
+
1518
+ /**
1519
+ * @typedef {object} KeyPathEvaluateValue
1520
+ * @property {KeyPathEvaluateValueValue} [value]
1521
+ * @property {boolean} [failure]
1522
+ */
1523
+
1524
+ /**
1525
+ * Returns the value of an inline key based on a key path (wrapped in an
1526
+ * object with key `value`) or `{failure: true}`
1527
+ * @param {Value} value
1528
+ * @param {KeyPath} keyPath
1529
+ * @param {boolean} [multiEntry]
1530
+ * @param {boolean} [fullKeys]
1531
+ * @returns {KeyPathEvaluateValue}
1532
+ */
1533
+ function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) {
1534
+ if (Array.isArray(keyPath)) {
1535
+ /** @type {KeyPathEvaluateValueValueArray} */
1536
+ var result = [];
1537
+ return keyPath.some(function (item) {
1538
+ var key = evaluateKeyPathOnValueToDecodedValue(value, item);
1539
+ if (key.failure) {
1422
1540
  return true;
1423
- } else {
1424
- value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */value[idntfr];
1425
- return value === undefined;
1426
1541
  }
1542
+ result.push(key.value);
1427
1543
  return false;
1428
1544
  }) ? {
1429
1545
  failure: true
1430
1546
  } : {
1431
- value
1547
+ value: result
1432
1548
  };
1433
1549
  }
1434
-
1435
- /**
1436
- * Sets the inline key value.
1437
- * @param {{[key: string]: AnyValue}} value
1438
- * @param {Key} key
1439
- * @param {string} keyPath
1440
- * @returns {void}
1441
- */
1442
- function injectKeyIntoValueUsingKeyPath(value, key, keyPath) {
1443
- const identifiers = keyPath.split('.');
1444
- const last = identifiers.pop();
1445
- identifiers.forEach(identifier => {
1446
- const hop = Object.hasOwn(value, identifier);
1447
- if (!hop) {
1448
- value[identifier] = {};
1449
- }
1450
- value = value[identifier];
1451
- });
1452
- value[(/** @type {string} */last)] = key; // key is already a `keyValue` in our processing so no need to convert
1550
+ if (keyPath === '') {
1551
+ return {
1552
+ value: value
1553
+ };
1453
1554
  }
1454
-
1455
- /**
1456
- *
1457
- * @param {Value} value
1458
- * @param {string} keyPath
1459
- * @see https://github.com/w3c/IndexedDB/pull/146
1460
- * @returns {boolean}
1461
- */
1462
- function checkKeyCouldBeInjectedIntoValue(value, keyPath) {
1463
- const identifiers = keyPath.split('.');
1464
- identifiers.pop();
1465
- for (const identifier of identifiers) {
1555
+ var identifiers = keyPath.split('.');
1556
+ return identifiers.some(function (idntfr) {
1557
+ if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) {
1558
+ value = value.length;
1559
+ } else if (isBlob(value)) {
1560
+ switch (idntfr) {
1561
+ case 'size':
1562
+ case 'type':
1563
+ value = /** @type {Blob} */value[idntfr];
1564
+ break;
1565
+ }
1566
+ } else if (isFile(value)) {
1567
+ switch (idntfr) {
1568
+ case 'name':
1569
+ case 'lastModified':
1570
+ value = /** @type {File} */value[idntfr];
1571
+ break;
1572
+ case 'lastModifiedDate':
1573
+ value = new Date(/** @type {File} */value.lastModified);
1574
+ break;
1575
+ }
1576
+ } else if (!isObj(value) || !Object.hasOwn(value, idntfr)) {
1577
+ return true;
1578
+ } else {
1579
+ value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */value[idntfr];
1580
+ return value === undefined;
1581
+ }
1582
+ return false;
1583
+ }) ? {
1584
+ failure: true
1585
+ } : {
1586
+ value: value
1587
+ };
1588
+ }
1589
+
1590
+ /**
1591
+ * Sets the inline key value.
1592
+ * @param {{[key: string]: AnyValue}} value
1593
+ * @param {Key} key
1594
+ * @param {string} keyPath
1595
+ * @returns {void}
1596
+ */
1597
+ function injectKeyIntoValueUsingKeyPath(value, key, keyPath) {
1598
+ var identifiers = keyPath.split('.');
1599
+ var last = identifiers.pop();
1600
+ identifiers.forEach(function (identifier) {
1601
+ var hop = Object.hasOwn(value, identifier);
1602
+ if (!hop) {
1603
+ value[identifier] = {};
1604
+ }
1605
+ value = value[identifier];
1606
+ });
1607
+ value[(/** @type {string} */last)] = key; // key is already a `keyValue` in our processing so no need to convert
1608
+ }
1609
+
1610
+ /**
1611
+ *
1612
+ * @param {Value} value
1613
+ * @param {string} keyPath
1614
+ * @see https://github.com/w3c/IndexedDB/pull/146
1615
+ * @returns {boolean}
1616
+ */
1617
+ function checkKeyCouldBeInjectedIntoValue(value, keyPath) {
1618
+ var identifiers = keyPath.split('.');
1619
+ identifiers.pop();
1620
+ var _iterator3 = _createForOfIteratorHelper(identifiers),
1621
+ _step3;
1622
+ try {
1623
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1624
+ var identifier = _step3.value;
1466
1625
  if (!isObj(value)) {
1467
1626
  return false;
1468
1627
  }
1469
- const hop = Object.hasOwn(value, identifier);
1628
+ var hop = Object.hasOwn(value, identifier);
1470
1629
  if (!hop) {
1471
1630
  return true;
1472
1631
  }
1473
1632
  value = /** @type {{[key: string]: Value}} */value[identifier];
1474
1633
  }
1475
- return isObj(value);
1634
+ } catch (err) {
1635
+ _iterator3.e(err);
1636
+ } finally {
1637
+ _iterator3.f();
1476
1638
  }
1477
-
1478
- /**
1479
- *
1480
- * @param {Key} key
1481
- * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range
1482
- * @param {boolean} [checkCached]
1483
- * @returns {boolean}
1484
- */
1485
- function isKeyInRange(key, range, checkCached) {
1486
- let lowerMatch = range.lower === undefined;
1487
- let upperMatch = range.upper === undefined;
1488
- const encodedKey = encode(key, true);
1489
- const lower = checkCached ? range.__lowerCached : encode(range.lower, true);
1490
- const upper = checkCached ? range.__upperCached : encode(range.upper, true);
1491
- if (!lowerMatch && (range.lowerOpen && encodedKey !== null && lower !== null && encodedKey > lower || !range.lowerOpen && (!encodedKey && !lower || encodedKey !== null && lower !== null && encodedKey >= lower))) {
1492
- lowerMatch = true;
1493
- }
1494
- if (!upperMatch && (range.upperOpen && encodedKey !== null && upper !== null && encodedKey < upper || !range.upperOpen && (!encodedKey && !upper || encodedKey !== null && upper !== null && encodedKey <= upper))) {
1495
- upperMatch = true;
1496
- }
1497
- return lowerMatch && upperMatch;
1639
+ return isObj(value);
1640
+ }
1641
+
1642
+ /**
1643
+ *
1644
+ * @param {Key} key
1645
+ * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range
1646
+ * @param {boolean} [checkCached]
1647
+ * @returns {boolean}
1648
+ */
1649
+ function isKeyInRange(key, range, checkCached) {
1650
+ var lowerMatch = range.lower === undefined;
1651
+ var upperMatch = range.upper === undefined;
1652
+ var encodedKey = _encode(key, true);
1653
+ var lower = checkCached ? range.__lowerCached : _encode(range.lower, true);
1654
+ var upper = checkCached ? range.__upperCached : _encode(range.upper, true);
1655
+ if (!lowerMatch && (range.lowerOpen && encodedKey !== null && lower !== null && encodedKey > lower || !range.lowerOpen && (!encodedKey && !lower || encodedKey !== null && lower !== null && encodedKey >= lower))) {
1656
+ lowerMatch = true;
1498
1657
  }
1499
-
1500
- /**
1501
- * Determines whether an index entry matches a multi-entry key value.
1502
- * @param {string} encodedEntry The entry value (already encoded)
1503
- * @param {string} encodedKey The full index key (already encoded)
1504
- * @returns {boolean}
1505
- */
1506
- function isMultiEntryMatch(encodedEntry, encodedKey) {
1507
- const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];
1508
- if (keyType === 'array') {
1509
- return encodedKey.indexOf(encodedEntry) > 1;
1510
- }
1511
- return encodedKey === encodedEntry;
1658
+ if (!upperMatch && (range.upperOpen && encodedKey !== null && upper !== null && encodedKey < upper || !range.upperOpen && (!encodedKey && !upper || encodedKey !== null && upper !== null && encodedKey <= upper))) {
1659
+ upperMatch = true;
1512
1660
  }
1513
-
1514
- /**
1515
- *
1516
- * @param {Key} keyEntry
1517
- * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range
1518
- * @returns {Key[]}
1519
- */
1520
- function findMultiEntryMatches(keyEntry, range) {
1521
- const matches = [];
1522
- if (Array.isArray(keyEntry)) {
1523
- for (let key of keyEntry) {
1661
+ return lowerMatch && upperMatch;
1662
+ }
1663
+
1664
+ /**
1665
+ * Determines whether an index entry matches a multi-entry key value.
1666
+ * @param {string} encodedEntry The entry value (already encoded)
1667
+ * @param {string} encodedKey The full index key (already encoded)
1668
+ * @returns {boolean}
1669
+ */
1670
+ function isMultiEntryMatch(encodedEntry, encodedKey) {
1671
+ var keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];
1672
+ if (keyType === 'array') {
1673
+ return encodedKey.indexOf(encodedEntry) > 1;
1674
+ }
1675
+ return encodedKey === encodedEntry;
1676
+ }
1677
+
1678
+ /**
1679
+ *
1680
+ * @param {Key} keyEntry
1681
+ * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range
1682
+ * @returns {Key[]}
1683
+ */
1684
+ function findMultiEntryMatches(keyEntry, range) {
1685
+ var matches = [];
1686
+ if (Array.isArray(keyEntry)) {
1687
+ var _iterator4 = _createForOfIteratorHelper(keyEntry),
1688
+ _step4;
1689
+ try {
1690
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1691
+ var key = _step4.value;
1524
1692
  if (Array.isArray(key)) {
1525
1693
  if (range && range.lower === range.upper) {
1526
1694
  continue;
1527
1695
  }
1528
1696
  if (key.length === 1) {
1529
- // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
1530
1697
  key = key[0];
1531
1698
  } else {
1532
- const nested = findMultiEntryMatches(key, range);
1699
+ var nested = findMultiEntryMatches(key, range);
1533
1700
  if (nested.length > 0) {
1534
1701
  matches.push(key);
1535
1702
  }
@@ -1540,270 +1707,278 @@
1540
1707
  matches.push(key);
1541
1708
  }
1542
1709
  }
1543
- } else if (isNullish(range) || isKeyInRange(keyEntry, range, true)) {
1544
- matches.push(keyEntry);
1710
+ } catch (err) {
1711
+ _iterator4.e(err);
1712
+ } finally {
1713
+ _iterator4.f();
1545
1714
  }
1546
- return matches;
1715
+ } else if (isNullish(range) || isKeyInRange(keyEntry, range, true)) {
1716
+ matches.push(keyEntry);
1547
1717
  }
1548
-
1549
- /**
1550
- * Not currently in use but keeping for spec parity.
1551
- * @param {Key} key
1552
- * @throws {Error} Upon a "bad key"
1553
- * @returns {ValueType}
1554
- */
1555
- function convertKeyToValue(key) {
1556
- const {
1557
- type,
1558
- value
1559
- } = key;
1560
- switch (type) {
1561
- case 'number':
1562
- case 'string':
1563
- {
1564
- return value;
1565
- }
1566
- case 'array':
1567
- {
1568
- const array = [];
1569
- const len = value.length;
1570
- let index = 0;
1571
- while (index < len) {
1572
- const entry = convertKeyToValue(value[index]);
1573
- array[index] = entry;
1574
- index++;
1575
- }
1576
- return array;
1577
- }
1578
- case 'date':
1579
- {
1580
- return new Date(value);
1581
- }
1582
- case 'binary':
1583
- {
1584
- const len = value.length;
1585
- const buffer = new ArrayBuffer(len);
1586
- // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1587
- const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);
1588
- uint8.set(value);
1589
- return buffer;
1718
+ return matches;
1719
+ }
1720
+
1721
+ /**
1722
+ * Not currently in use but keeping for spec parity.
1723
+ * @param {Key} key
1724
+ * @throws {Error} Upon a "bad key"
1725
+ * @returns {ValueType}
1726
+ */
1727
+ function convertKeyToValue(key) {
1728
+ var type = key.type,
1729
+ value = key.value;
1730
+ switch (type) {
1731
+ case 'number':
1732
+ case 'string':
1733
+ {
1734
+ return value;
1735
+ }
1736
+ case 'array':
1737
+ {
1738
+ var array = [];
1739
+ var len = value.length;
1740
+ var index = 0;
1741
+ while (index < len) {
1742
+ var entry = convertKeyToValue(value[index]);
1743
+ array[index] = entry;
1744
+ index++;
1590
1745
  }
1591
- case 'invalid':
1592
- default:
1593
- throw new Error('Bad key');
1594
- }
1595
- }
1596
-
1597
- /**
1598
- *
1599
- * @param {Key} key
1600
- * @param {boolean} [inArray]
1601
- * @returns {string|null}
1602
- */
1603
- function encode(key, inArray) {
1604
- // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation
1605
- if (key === undefined) {
1606
- return null;
1607
- }
1608
- // array, date, number, string, binary (should already have detected "invalid")
1609
- return types[getKeyType(key)].encode(key, inArray);
1610
- }
1611
-
1612
- /**
1613
- *
1614
- * @param {Key} key
1615
- * @param {boolean} [inArray]
1616
- * @throws {Error} Invalid number
1617
- * @returns {undefined|ValueType}
1618
- */
1619
- function decode(key, inArray) {
1620
- if (typeof key !== 'string') {
1621
- return undefined;
1622
- }
1623
- return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);
1746
+ return array;
1747
+ }
1748
+ case 'date':
1749
+ {
1750
+ return new Date(value);
1751
+ }
1752
+ case 'binary':
1753
+ {
1754
+ var _len = value.length;
1755
+ var buffer = new ArrayBuffer(_len);
1756
+ // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1757
+ var uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);
1758
+ uint8.set(value);
1759
+ return buffer;
1760
+ }
1761
+ case 'invalid':
1762
+ default:
1763
+ throw new Error('Bad key');
1624
1764
  }
1625
-
1626
- /**
1627
- *
1628
- * @param {Key} key
1629
- * @param {boolean} [inArray]
1630
- * @returns {undefined|ValueType}
1631
- */
1632
- function roundTrip(key, inArray) {
1633
- return decode(encode(key, inArray), inArray);
1765
+ }
1766
+
1767
+ /**
1768
+ *
1769
+ * @param {Key} key
1770
+ * @param {boolean} [inArray]
1771
+ * @returns {string|null}
1772
+ */
1773
+ function _encode(key, inArray) {
1774
+ // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation
1775
+ if (key === undefined) {
1776
+ return null;
1634
1777
  }
1635
- const MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)
1636
-
1637
- /**
1638
- * @typedef {number} Integer
1639
- */
1640
-
1641
- /**
1642
- * @callback CurrentNumberCallback
1643
- * @param {Integer} cn The current number
1644
- * @returns {void}
1645
- */
1646
-
1647
- /**
1648
- * @callback SQLFailureCallback
1649
- * @param {DOMException|Error} exception
1650
- * @returns {void}
1651
- */
1652
-
1653
- /**
1654
- *
1655
- * @param {SQLTransaction} tx
1656
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1657
- * @param {CurrentNumberCallback} func
1658
- * @param {SQLFailureCallback} sqlFailCb
1659
- * @returns {void}
1660
- */
1661
- function getCurrentNumber(tx, store, func, sqlFailCb) {
1662
- tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) {
1663
- if (data.rows.length !== 1) {
1664
- func(1);
1665
- } else {
1666
- func(data.rows.item(0).currNum);
1667
- }
1668
- }, function (tx, error) {
1669
- sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error));
1670
- return false;
1671
- });
1778
+ // array, date, number, string, binary (should already have detected "invalid")
1779
+ return types[getKeyType(key)].encode(key, inArray);
1780
+ }
1781
+
1782
+ /**
1783
+ *
1784
+ * @param {Key} key
1785
+ * @param {boolean} [inArray]
1786
+ * @throws {Error} Invalid number
1787
+ * @returns {undefined|ValueType}
1788
+ */
1789
+ function _decode(key, inArray) {
1790
+ if (typeof key !== 'string') {
1791
+ return undefined;
1672
1792
  }
1673
-
1674
- /**
1675
- *
1676
- * @param {SQLTransaction} tx
1677
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1678
- * @param {Integer} num
1679
- * @param {CurrentNumberCallback} successCb
1680
- * @param {SQLFailureCallback} failCb
1681
- * @returns {void}
1682
- */
1683
- function assignCurrentNumber(tx, store, num, successCb, failCb) {
1684
- const sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?';
1685
- const sqlValues = [num, escapeSQLiteStatement(store.__currentName)];
1686
- if (CFG.DEBUG) {
1687
- console.log(sql, sqlValues);
1793
+ return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);
1794
+ }
1795
+
1796
+ /**
1797
+ *
1798
+ * @param {Key} key
1799
+ * @param {boolean} [inArray]
1800
+ * @returns {undefined|ValueType}
1801
+ */
1802
+ function roundTrip(key, inArray) {
1803
+ return _decode(_encode(key, inArray), inArray);
1804
+ }
1805
+ var MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)
1806
+
1807
+ /**
1808
+ * @typedef {number} Integer
1809
+ */
1810
+
1811
+ /**
1812
+ * @callback CurrentNumberCallback
1813
+ * @param {Integer} cn The current number
1814
+ * @returns {void}
1815
+ */
1816
+
1817
+ /**
1818
+ * @callback SQLFailureCallback
1819
+ * @param {DOMException|Error} exception
1820
+ * @returns {void}
1821
+ */
1822
+
1823
+ /**
1824
+ *
1825
+ * @param {SQLTransaction} tx
1826
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1827
+ * @param {CurrentNumberCallback} func
1828
+ * @param {SQLFailureCallback} sqlFailCb
1829
+ * @returns {void}
1830
+ */
1831
+ function getCurrentNumber(tx, store, func, sqlFailCb) {
1832
+ tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) {
1833
+ if (data.rows.length !== 1) {
1834
+ func(1);
1835
+ } else {
1836
+ func(data.rows.item(0).currNum);
1688
1837
  }
1689
- tx.executeSql(sql, sqlValues, function () {
1690
- successCb(num);
1691
- }, function (tx, err) {
1692
- failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));
1693
- return false;
1694
- });
1695
- }
1696
-
1697
- /**
1698
- * Bump up the auto-inc counter if the key path-resolved value is valid
1699
- * (greater than old value and >=1) OR if a manually passed in key is
1700
- * valid (numeric and >= 1) and >= any primaryKey.
1701
- * @param {SQLTransaction} tx
1702
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1703
- * @param {Integer} num
1704
- * @param {CurrentNumberCallback} successCb
1705
- * @param {SQLFailureCallback} failCb
1706
- * @returns {void}
1707
- */
1708
- function setCurrentNumber(tx, store, num, successCb, failCb) {
1709
- num = num === MAX_ALLOWED_CURRENT_NUMBER ? 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
1710
- : num + 1;
1711
- return assignCurrentNumber(tx, store, num, successCb, failCb);
1838
+ }, function (tx, error) {
1839
+ sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error));
1840
+ return false;
1841
+ });
1842
+ }
1843
+
1844
+ /**
1845
+ *
1846
+ * @param {SQLTransaction} tx
1847
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1848
+ * @param {Integer} num
1849
+ * @param {CurrentNumberCallback} successCb
1850
+ * @param {SQLFailureCallback} failCb
1851
+ * @returns {void}
1852
+ */
1853
+ function assignCurrentNumber(tx, store, num, successCb, failCb) {
1854
+ var sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?';
1855
+ var sqlValues = [num, escapeSQLiteStatement(store.__currentName)];
1856
+ if (CFG.DEBUG) {
1857
+ console.log(sql, sqlValues);
1712
1858
  }
1713
-
1714
- /**
1715
- * @callback KeyForStoreCallback
1716
- * @param {"failure"|null} arg1
1717
- * @param {Integer} [arg2]
1718
- * @param {Integer} [arg3]
1719
- * @returns {void}
1720
- */
1721
-
1722
- /**
1723
- *
1724
- * @param {SQLTransaction} tx
1725
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1726
- * @param {KeyForStoreCallback} cb
1727
- * @param {SQLFailureCallback} sqlFailCb
1728
- * @returns {void}
1729
- */
1730
- function generateKeyForStore(tx, store, cb, sqlFailCb) {
1731
- getCurrentNumber(tx, store, function (key) {
1732
- if (key > MAX_ALLOWED_CURRENT_NUMBER) {
1733
- // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>)
1734
- cb('failure');
1735
- return;
1859
+ tx.executeSql(sql, sqlValues, function () {
1860
+ successCb(num);
1861
+ }, function (tx, err) {
1862
+ failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));
1863
+ return false;
1864
+ });
1865
+ }
1866
+
1867
+ /**
1868
+ * Bump up the auto-inc counter if the key path-resolved value is valid
1869
+ * (greater than old value and >=1) OR if a manually passed in key is
1870
+ * valid (numeric and >= 1) and >= any primaryKey.
1871
+ * @param {SQLTransaction} tx
1872
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1873
+ * @param {Integer} num
1874
+ * @param {CurrentNumberCallback} successCb
1875
+ * @param {SQLFailureCallback} failCb
1876
+ * @returns {void}
1877
+ */
1878
+ function setCurrentNumber(tx, store, num, successCb, failCb) {
1879
+ num = 1 + (num === MAX_ALLOWED_CURRENT_NUMBER
1880
+ // Since incrementing by one will have no effect in JavaScript on this
1881
+ // unsafe max, we represent the max as a number incremented by two.
1882
+ // The getting of the current number is never returned to the user and
1883
+ // is only used in safe comparisons, so it is safe for us to represent
1884
+ // it in this manner
1885
+ ? num + 1 : num);
1886
+ return assignCurrentNumber(tx, store, num, successCb, failCb);
1887
+ }
1888
+
1889
+ /**
1890
+ * @callback KeyForStoreCallback
1891
+ * @param {"failure"|null} arg1
1892
+ * @param {Integer} [arg2]
1893
+ * @param {Integer} [arg3]
1894
+ * @returns {void}
1895
+ */
1896
+
1897
+ /**
1898
+ *
1899
+ * @param {SQLTransaction} tx
1900
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1901
+ * @param {KeyForStoreCallback} cb
1902
+ * @param {SQLFailureCallback} sqlFailCb
1903
+ * @returns {void}
1904
+ */
1905
+ function generateKeyForStore(tx, store, cb, sqlFailCb) {
1906
+ getCurrentNumber(tx, store, function (key) {
1907
+ if (key > MAX_ALLOWED_CURRENT_NUMBER) {
1908
+ // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>)
1909
+ cb('failure');
1910
+ return;
1911
+ }
1912
+ // Increment current number by 1 (we cannot leverage SQLite's
1913
+ // autoincrement (and decrement when not needed), as decrementing
1914
+ // will be overwritten/ignored upon the next insert)
1915
+ setCurrentNumber(tx, store, key, function () {
1916
+ cb(null, key, key);
1917
+ }, sqlFailCb);
1918
+ }, sqlFailCb);
1919
+ }
1920
+
1921
+ // Fractional or numbers exceeding the max do not get changed in the result
1922
+ // per https://github.com/w3c/IndexedDB/issues/147
1923
+ // so we do not return a key
1924
+ /**
1925
+ *
1926
+ * @param {SQLTransaction} tx
1927
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1928
+ * @param {Key} key
1929
+ * @param {(num?: Integer) => void} successCb
1930
+ * @param {SQLFailureCallback} sqlFailCb
1931
+ * @returns {void}
1932
+ */
1933
+ function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) {
1934
+ // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers
1935
+ // (or numbers larger than the max) are now to have the explicit effect of
1936
+ // setting the current number (up to the max), so we do not optimize them
1937
+ // out here
1938
+ if (typeof key !== 'number' || key < 1) {
1939
+ // Optimize with no need to get the current number
1940
+ // Auto-increment attempted with a bad key;
1941
+ // we are not to change the current number, but the steps don't call for failure
1942
+ // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1
1943
+ successCb();
1944
+ } else {
1945
+ // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher
1946
+ // to determine which to use and whether to update the current number
1947
+ getCurrentNumber(tx, store, function (cn) {
1948
+ var value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER));
1949
+ var useNewKeyForAutoInc = value >= cn;
1950
+ if (useNewKeyForAutoInc) {
1951
+ setCurrentNumber(tx, store, value, function () {
1952
+ successCb(cn); // Supply old current number in case needs to be reverted
1953
+ }, sqlFailCb);
1954
+ } else {
1955
+ // Not updated
1956
+ successCb();
1736
1957
  }
1737
- // Increment current number by 1 (we cannot leverage SQLite's
1738
- // autoincrement (and decrement when not needed), as decrementing
1739
- // will be overwritten/ignored upon the next insert)
1740
- setCurrentNumber(tx, store, key, function () {
1741
- cb(null, key, key);
1742
- }, sqlFailCb);
1743
1958
  }, sqlFailCb);
1744
1959
  }
1745
-
1746
- // Fractional or numbers exceeding the max do not get changed in the result
1747
- // per https://github.com/w3c/IndexedDB/issues/147
1748
- // so we do not return a key
1749
- /**
1750
- *
1751
- * @param {SQLTransaction} tx
1752
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1753
- * @param {Key} key
1754
- * @param {(num?: Integer) => void} successCb
1755
- * @param {SQLFailureCallback} sqlFailCb
1756
- * @returns {void}
1757
- */
1758
- function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) {
1759
- // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers
1760
- // (or numbers larger than the max) are now to have the explicit effect of
1761
- // setting the current number (up to the max), so we do not optimize them
1762
- // out here
1763
- if (typeof key !== 'number' || key < 1) {
1764
- // Optimize with no need to get the current number
1765
- // Auto-increment attempted with a bad key;
1766
- // we are not to change the current number, but the steps don't call for failure
1767
- // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1
1768
- successCb();
1769
- } else {
1770
- // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher
1771
- // to determine which to use and whether to update the current number
1772
- getCurrentNumber(tx, store, function (cn) {
1773
- const value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER));
1774
- const useNewKeyForAutoInc = value >= cn;
1775
- if (useNewKeyForAutoInc) {
1776
- setCurrentNumber(tx, store, value, function () {
1777
- successCb(cn); // Supply old current number in case needs to be reverted
1778
- }, sqlFailCb);
1779
- } else {
1780
- // Not updated
1781
- successCb();
1782
- }
1783
- }, sqlFailCb);
1784
- }
1785
- }
1786
-
1787
- exports.assignCurrentNumber = assignCurrentNumber;
1788
- exports.checkKeyCouldBeInjectedIntoValue = checkKeyCouldBeInjectedIntoValue;
1789
- exports.convertKeyToValue = convertKeyToValue;
1790
- exports.convertValueToKey = convertValueToKey;
1791
- exports.convertValueToKeyRethrowingAndIfInvalid = convertValueToKeyRethrowingAndIfInvalid;
1792
- exports.convertValueToKeyValueDecoded = convertValueToKeyValueDecoded;
1793
- exports.convertValueToMultiEntryKey = convertValueToMultiEntryKey;
1794
- exports.convertValueToMultiEntryKeyDecoded = convertValueToMultiEntryKeyDecoded;
1795
- exports.decode = decode;
1796
- exports.encode = encode;
1797
- exports.evaluateKeyPathOnValue = evaluateKeyPathOnValue;
1798
- exports.extractKeyFromValueUsingKeyPath = extractKeyFromValueUsingKeyPath;
1799
- exports.extractKeyValueDecodedFromValueUsingKeyPath = extractKeyValueDecodedFromValueUsingKeyPath;
1800
- exports.findMultiEntryMatches = findMultiEntryMatches;
1801
- exports.generateKeyForStore = generateKeyForStore;
1802
- exports.injectKeyIntoValueUsingKeyPath = injectKeyIntoValueUsingKeyPath;
1803
- exports.isKeyInRange = isKeyInRange;
1804
- exports.isMultiEntryMatch = isMultiEntryMatch;
1805
- exports.possiblyUpdateKeyGenerator = possiblyUpdateKeyGenerator;
1806
- exports.roundTrip = roundTrip;
1960
+ }
1961
+
1962
+ exports.assignCurrentNumber = assignCurrentNumber;
1963
+ exports.checkKeyCouldBeInjectedIntoValue = checkKeyCouldBeInjectedIntoValue;
1964
+ exports.convertKeyToValue = convertKeyToValue;
1965
+ exports.convertValueToKey = convertValueToKey;
1966
+ exports.convertValueToKeyRethrowingAndIfInvalid = convertValueToKeyRethrowingAndIfInvalid;
1967
+ exports.convertValueToKeyValueDecoded = convertValueToKeyValueDecoded;
1968
+ exports.convertValueToMultiEntryKey = convertValueToMultiEntryKey;
1969
+ exports.convertValueToMultiEntryKeyDecoded = convertValueToMultiEntryKeyDecoded;
1970
+ exports.decode = _decode;
1971
+ exports.encode = _encode;
1972
+ exports.evaluateKeyPathOnValue = evaluateKeyPathOnValue;
1973
+ exports.extractKeyFromValueUsingKeyPath = extractKeyFromValueUsingKeyPath;
1974
+ exports.extractKeyValueDecodedFromValueUsingKeyPath = extractKeyValueDecodedFromValueUsingKeyPath;
1975
+ exports.findMultiEntryMatches = findMultiEntryMatches;
1976
+ exports.generateKeyForStore = generateKeyForStore;
1977
+ exports.injectKeyIntoValueUsingKeyPath = injectKeyIntoValueUsingKeyPath;
1978
+ exports.isKeyInRange = isKeyInRange;
1979
+ exports.isMultiEntryMatch = isMultiEntryMatch;
1980
+ exports.possiblyUpdateKeyGenerator = possiblyUpdateKeyGenerator;
1981
+ exports.roundTrip = roundTrip;
1807
1982
 
1808
1983
  }));
1809
1984
  //# sourceMappingURL=indexeddbshim-Key.js.map