fake-indexeddb 6.2.2 → 6.2.4

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 (38) hide show
  1. package/README.md +23 -15
  2. package/auto/index.js +1 -1
  3. package/auto/index.mjs +1 -1
  4. package/build/cjs/FDBCursor.js +2 -1
  5. package/build/cjs/FDBDatabase.js +45 -20
  6. package/build/cjs/FDBFactory.js +285 -137
  7. package/build/cjs/FDBIndex.js +13 -9
  8. package/build/cjs/FDBObjectStore.js +26 -22
  9. package/build/cjs/FDBTransaction.js +51 -11
  10. package/build/cjs/lib/Database.js +25 -12
  11. package/build/cjs/lib/FakeEventTarget.js +17 -5
  12. package/build/cjs/lib/ObjectStore.js +60 -20
  13. package/build/cjs/lib/cloneValueForInsertion.js +30 -0
  14. package/build/cjs/lib/extractGetAllOptions.js +2 -2
  15. package/build/cjs/lib/intersection.js +18 -0
  16. package/build/cjs/lib/isPotentiallyValidKeyRange.js +13 -20
  17. package/build/cjs/lib/scheduling.js +4 -4
  18. package/build/cjs/lib/validateRequiredArguments.js +13 -0
  19. package/build/cjs/lib/valueToKey.js +8 -53
  20. package/build/cjs/lib/valueToKeyWithoutThrowing.js +102 -0
  21. package/build/esm/FDBCursor.js +2 -1
  22. package/build/esm/FDBDatabase.js +45 -20
  23. package/build/esm/FDBFactory.js +285 -137
  24. package/build/esm/FDBIndex.js +13 -9
  25. package/build/esm/FDBObjectStore.js +26 -22
  26. package/build/esm/FDBTransaction.js +51 -11
  27. package/build/esm/lib/Database.js +25 -12
  28. package/build/esm/lib/FakeEventTarget.js +17 -5
  29. package/build/esm/lib/ObjectStore.js +60 -20
  30. package/build/esm/lib/cloneValueForInsertion.js +24 -0
  31. package/build/esm/lib/extractGetAllOptions.js +2 -2
  32. package/build/esm/lib/intersection.js +12 -0
  33. package/build/esm/lib/isPotentiallyValidKeyRange.js +12 -20
  34. package/build/esm/lib/scheduling.js +4 -4
  35. package/build/esm/lib/validateRequiredArguments.js +7 -0
  36. package/build/esm/lib/valueToKey.js +7 -52
  37. package/build/esm/lib/valueToKeyWithoutThrowing.js +95 -0
  38. package/package.json +4 -2
@@ -18,11 +18,14 @@ class FDBTransaction extends _FakeEventTarget.default {
18
18
  _started = false;
19
19
  _rollbackLog = [];
20
20
  _objectStoresCache = new Map();
21
+ _openRequest = null;
21
22
  error = null;
22
23
  onabort = null;
23
24
  oncomplete = null;
24
25
  onerror = null;
25
26
  _requests = [];
27
+ _createdIndexes = new Set();
28
+ _createdObjectStores = new Set();
26
29
  constructor(storeNames, mode, durability, db) {
27
30
  super();
28
31
  this._scope = new Set(storeNames);
@@ -32,7 +35,7 @@ class FDBTransaction extends _FakeEventTarget.default {
32
35
  this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this._scope).sort());
33
36
  }
34
37
 
35
- // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-aborting-a-transaction
38
+ // https://w3c.github.io/IndexedDB/#abort-transaction
36
39
  _abort(errName) {
37
40
  for (const f of this._rollbackLog.reverse()) {
38
41
  f();
@@ -49,24 +52,61 @@ class FDBTransaction extends _FakeEventTarget.default {
49
52
  if (request.readyState !== "done") {
50
53
  request.readyState = "done"; // This will cancel execution of this request's operation
51
54
  if (request.source) {
52
- request.result = undefined;
53
- request.error = new _errors.AbortError();
54
- const event = new _FakeEvent.default("error", {
55
- bubbles: true,
56
- cancelable: true
55
+ // https://w3c.github.io/IndexedDB/#ref-for-list-iterate%E2%91%A2
56
+ // For each request of transaction’s request list, abort the steps to asynchronously
57
+ // execute a request for request, set request’s processed flag to true, and queue a
58
+ // database task to run these steps:
59
+ (0, _scheduling.queueTask)(() => {
60
+ // Set request’s result to undefined.
61
+ request.result = undefined;
62
+ // Set request’s error to a newly created "AbortError" DOMException.
63
+ request.error = new _errors.AbortError();
64
+
65
+ // Fire an event named error at request with its bubbles and cancelable attributes initialized
66
+ // to true.
67
+ const event = new _FakeEvent.default("error", {
68
+ bubbles: true,
69
+ cancelable: true
70
+ });
71
+ event.eventPath = [this.db, this];
72
+ try {
73
+ request.dispatchEvent(event);
74
+ } catch (_err) {
75
+ if (this._state === "active") {
76
+ this._abort("AbortError");
77
+ }
78
+ }
57
79
  });
58
- event.eventPath = [this.db, this];
59
- request.dispatchEvent(event);
60
80
  }
61
81
  }
62
82
  }
83
+
84
+ // Queue a database task to run these steps:
63
85
  (0, _scheduling.queueTask)(() => {
86
+ // If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s
87
+ // upgrade transaction to null.
88
+ // (i.e. remove it from the list of `db.connections`)
89
+ const isUpgradeTransaction = this.mode === "versionchange";
90
+ if (isUpgradeTransaction) {
91
+ this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter(connection => !connection._rawDatabase.transactions.includes(this));
92
+ }
93
+ // Fire an event named abort at transaction with its bubbles attribute initialized to true.
64
94
  const event = new _FakeEvent.default("abort", {
65
95
  bubbles: true,
66
96
  cancelable: false
67
97
  });
68
98
  event.eventPath = [this.db];
69
99
  this.dispatchEvent(event);
100
+
101
+ // If transaction is an upgrade transaction, then:
102
+ if (isUpgradeTransaction) {
103
+ // Let request be the open request associated with transaction.
104
+ const request = this._openRequest;
105
+ // Set request’s transaction to null.
106
+ request.transaction = null;
107
+ // Set request’s result to undefined.
108
+ request.result = undefined;
109
+ }
70
110
  });
71
111
  this._state = "finished";
72
112
  }
@@ -178,11 +218,11 @@ class FDBTransaction extends _FakeEventTarget.default {
178
218
  try {
179
219
  event.eventPath = [this.db, this];
180
220
  request.dispatchEvent(event);
181
- } catch (err) {
182
- if (this._state !== "committing") {
221
+ } catch (_err) {
222
+ if (this._state === "active") {
183
223
  this._abort("AbortError");
224
+ defaultAction = undefined; // do not abort again
184
225
  }
185
- throw err;
186
226
  }
187
227
 
188
228
  // Default action of event
@@ -5,9 +5,9 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _scheduling = require("./scheduling.js");
8
+ var _intersection = require("./intersection.js");
8
9
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-database
9
10
  class Database {
10
- deletePending = false;
11
11
  transactions = [];
12
12
  rawObjectStores = new Map();
13
13
  connections = [];
@@ -18,18 +18,31 @@ class Database {
18
18
  }
19
19
  processTransactions() {
20
20
  (0, _scheduling.queueTask)(() => {
21
- const anyRunning = this.transactions.some(transaction => {
22
- return transaction._started && transaction._state !== "finished";
23
- });
24
- if (!anyRunning) {
25
- const next = this.transactions.find(transaction => {
26
- return !transaction._started && transaction._state !== "finished";
27
- });
28
- if (next) {
29
- next.addEventListener("complete", this.processTransactions);
30
- next.addEventListener("abort", this.processTransactions);
31
- next._start();
21
+ const running = this.transactions.filter(transaction => transaction._started && transaction._state !== "finished");
22
+ const waiting = this.transactions.filter(transaction => !transaction._started && transaction._state !== "finished");
23
+
24
+ // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a
25
+ // preceding waiting one. This allows non-overlapping transactions to run in parallel.
26
+ // The exception is readonly transactions, which are allowed to run in parallel with other readonly
27
+ // transactions, even with overlapping scopes, since no data is being modified.
28
+ const next = waiting.find((transaction, i) => {
29
+ const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && (0, _intersection.intersection)(other._scope, transaction._scope).size > 0);
30
+ if (anyRunning) {
31
+ return false;
32
32
  }
33
+
34
+ // If any _preceding_ waiting transactions are blocked, then that's also blocking.
35
+ // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c]
36
+ // until [a] is complete, even though [a] and [b,c] share no overlap.
37
+ // Note that readonly transactions do not have to be handled as a special case here,
38
+ // because if any transactions with overlapping scopes are blocked, then we can assume they are
39
+ const anyWaiting = waiting.slice(0, i).some(other => (0, _intersection.intersection)(other._scope, transaction._scope).size > 0);
40
+ return !anyWaiting;
41
+ });
42
+ if (next) {
43
+ next.addEventListener("complete", this.processTransactions);
44
+ next.addEventListener("abort", this.processTransactions);
45
+ next._start();
33
46
  }
34
47
  });
35
48
  }
@@ -12,6 +12,15 @@ const stopped = (event, listener) => {
12
12
  // http://www.w3.org/TR/dom/#concept-event-listener-invoke
13
13
  const invokeEventListeners = (event, obj) => {
14
14
  event.currentTarget = obj;
15
+ const errors = [];
16
+ const invoke = callback => {
17
+ try {
18
+ // @ts-expect-error EventCallback's types are not quite right here
19
+ callback.call(event.currentTarget, event);
20
+ } catch (err) {
21
+ errors.push(err);
22
+ }
23
+ };
15
24
 
16
25
  // The callback might cause obj.listeners to mutate as we traverse it.
17
26
  // Take a copy of the array so that nothing sneaks in and we don't lose
@@ -20,9 +29,7 @@ const invokeEventListeners = (event, obj) => {
20
29
  if (event.type !== listener.type || stopped(event, listener)) {
21
30
  continue;
22
31
  }
23
-
24
- // @ts-ignore
25
- listener.callback.call(event.currentTarget, event);
32
+ invoke(listener.callback);
26
33
  }
27
34
  const typeToProp = {
28
35
  abort: "onabort",
@@ -46,10 +53,15 @@ const invokeEventListeners = (event, obj) => {
46
53
  type: event.type
47
54
  };
48
55
  if (!stopped(event, listener)) {
49
- // @ts-ignore
50
- listener.callback.call(event.currentTarget, event);
56
+ invoke(listener.callback);
51
57
  }
52
58
  }
59
+
60
+ // we want to execute all listeners before deciding if we want to throw, because there could be an error thrown by
61
+ // the first listener, but the second should still be invoked
62
+ if (errors.length) {
63
+ throw new AggregateError(errors);
64
+ }
53
65
  };
54
66
  class FakeEventTarget {
55
67
  listeners = [];
@@ -89,14 +89,22 @@ class ObjectStore {
89
89
  newRecord.key = key;
90
90
  }
91
91
  }
92
+ const rollbackLogForThisOperation = [];
92
93
  if (this.keyGenerator !== null && newRecord.key === undefined) {
94
+ let rolledBack = false;
95
+ const keyGeneratorBefore = this.keyGenerator.num;
96
+ const rollbackKeyGenerator = () => {
97
+ if (rolledBack) {
98
+ return;
99
+ }
100
+ rolledBack = true;
101
+ if (this.keyGenerator) {
102
+ this.keyGenerator.num = keyGeneratorBefore;
103
+ }
104
+ };
105
+ rollbackLogForThisOperation.push(rollbackKeyGenerator);
93
106
  if (rollbackLog) {
94
- const keyGeneratorBefore = this.keyGenerator.num;
95
- rollbackLog.push(() => {
96
- if (this.keyGenerator) {
97
- this.keyGenerator.num = keyGeneratorBefore;
98
- }
99
- });
107
+ rollbackLog.push(rollbackKeyGenerator);
100
108
  }
101
109
  newRecord.key = this.keyGenerator.next();
102
110
 
@@ -119,28 +127,50 @@ class ObjectStore {
119
127
  identifier = remainingKeyPath.slice(0, i);
120
128
  remainingKeyPath = remainingKeyPath.slice(i + 1);
121
129
  if (!Object.hasOwn(object, identifier)) {
122
- object[identifier] = {};
130
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
131
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
132
+ Object.defineProperty(object, identifier, {
133
+ configurable: true,
134
+ enumerable: true,
135
+ writable: true,
136
+ value: {}
137
+ });
123
138
  }
124
139
  object = object[identifier];
125
140
  }
126
141
  }
127
142
  identifier = remainingKeyPath;
128
- object[identifier] = newRecord.key;
143
+
144
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
145
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
146
+ Object.defineProperty(object, identifier, {
147
+ configurable: true,
148
+ enumerable: true,
149
+ writable: true,
150
+ value: newRecord.key
151
+ });
129
152
  }
130
153
  } else if (this.keyGenerator !== null && typeof newRecord.key === "number") {
131
154
  this.keyGenerator.setIfLarger(newRecord.key);
132
155
  }
133
156
  const existingRecord = this.records.put(newRecord, noOverwrite);
157
+ let rolledBack = false;
158
+ const rollbackStoreRecord = () => {
159
+ if (rolledBack) {
160
+ return;
161
+ }
162
+ rolledBack = true;
163
+ if (existingRecord) {
164
+ // overwrite on rollback
165
+ this.storeRecord(existingRecord, false);
166
+ } else {
167
+ // delete on rollback
168
+ this.deleteRecord(newRecord.key);
169
+ }
170
+ };
171
+ rollbackLogForThisOperation.push(rollbackStoreRecord);
134
172
  if (rollbackLog) {
135
- rollbackLog.push(() => {
136
- if (existingRecord) {
137
- // overwrite on rollback
138
- this.storeRecord(existingRecord, false);
139
- } else {
140
- // delete on rollback
141
- this.deleteRecord(newRecord.key);
142
- }
143
- });
173
+ rollbackLog.push(rollbackStoreRecord);
144
174
  }
145
175
 
146
176
  // Delete existing indexes
@@ -151,10 +181,20 @@ class ObjectStore {
151
181
  }
152
182
 
153
183
  // Update indexes
154
- for (const rawIndex of this.rawIndexes.values()) {
155
- if (rawIndex.initialized) {
156
- rawIndex.storeRecord(newRecord);
184
+ try {
185
+ for (const rawIndex of this.rawIndexes.values()) {
186
+ if (rawIndex.initialized) {
187
+ rawIndex.storeRecord(newRecord);
188
+ }
189
+ }
190
+ } catch (err) {
191
+ // If this request fails here and preventDefault is used to stop the transaction from aborting, we need to roll back the addition of this record to the store, otherwise it will be present in subsequent requests on this transaction. Same for key generator.
192
+ if (err.name === "ConstraintError") {
193
+ for (const rollback of rollbackLogForThisOperation) {
194
+ rollback();
195
+ }
157
196
  }
197
+ throw err;
158
198
  }
159
199
  return newRecord.key;
160
200
  }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cloneValueForInsertion = cloneValueForInsertion;
7
+ // https://w3c.github.io/IndexedDB/#clone-value
8
+ // Note that we only need to call this during insertions because the spec does not expect any cloning during retrieval,
9
+ // only `StructuredDeserialize()` (e.g. see [1]). This is also only required for values, not keys, since keys do not
10
+ // require cloning during insertion (e.g. see [2]).
11
+ // [1]: https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store
12
+ // [2]: https://w3c.github.io/IndexedDB/#add-or-put
13
+ function cloneValueForInsertion(value, transaction) {
14
+ // Assert: transaction’s state is active.
15
+ if (transaction._state !== "active") {
16
+ throw new Error("Assert: transaction state is active");
17
+ }
18
+
19
+ // Set transaction’s state to inactive.
20
+ transaction._state = "inactive";
21
+ try {
22
+ // Let serialized be StructuredSerializeForStorage(value).
23
+ // Let clone be ? StructuredDeserialize(serialized, targetRealm).
24
+ // Return clone.
25
+ return structuredClone(value);
26
+ } finally {
27
+ // Set transaction’s state to active.
28
+ transaction._state = "active";
29
+ }
30
+ }
@@ -11,8 +11,8 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
11
11
  const extractGetAllOptions = (queryOrOptions, count, numArguments) => {
12
12
  let query;
13
13
  let direction;
14
- if ((0, _isPotentiallyValidKeyRange.default)(queryOrOptions)) {
15
- // queryOrOptions is FDBKeyRange | Key
14
+ if (queryOrOptions === undefined || queryOrOptions === null || (0, _isPotentiallyValidKeyRange.default)(queryOrOptions)) {
15
+ // queryOrOptions is FDBKeyRange | Key | null | undefined
16
16
  query = queryOrOptions;
17
17
  if (numArguments > 1 && count !== undefined) {
18
18
  count = (0, _enforceRange.default)(count, "unsigned long");
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.intersection = intersection;
7
+ /**
8
+ * Minimal polyfill of `Set.prototype.intersection`, available in Node 22+.
9
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection
10
+ * @param set1
11
+ * @param set2
12
+ */
13
+ function intersection(set1, set2) {
14
+ if ("intersection" in set1) {
15
+ return set1.intersection(set2);
16
+ }
17
+ return new Set([...set1].filter(item => set2.has(item)));
18
+ }
@@ -5,29 +5,22 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js"));
8
- var _isSharedArrayBuffer = _interopRequireDefault(require("./isSharedArrayBuffer.js"));
8
+ var _valueToKeyWithoutThrowing = _interopRequireWildcard(require("./valueToKeyWithoutThrowing.js"));
9
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
9
10
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
10
11
  // https://www.w3.org/TR/IndexedDB/#is-a-potentially-valid-key-range
11
12
  const isPotentiallyValidKeyRange = value => {
12
- // Many of these conditions recapitulate the same conditions in `valueToKeyRange.ts`
13
- return (
14
- // FDBKeyRange
15
- value instanceof _FDBKeyRange.default ||
16
- // null/undefined - nullDisallowedFlag=false is assumed here
17
- value === null || value === undefined ||
18
- // Number
19
- typeof value === "number" ||
20
- // Date
21
- Object.prototype.toString.call(value) === "[object Date]" ||
22
- // string
23
- typeof value === "string" ||
24
- // buffer source type
25
- // note: we are explicitly _not_ checking for detachedness here, to match Chromium's behavior
26
- // see: https://github.com/w3c/IndexedDB/issues/465
27
- value instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(value) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(value) ||
28
- // array exotic type
29
- Array.isArray(value)
30
- );
13
+ // If value is a key range, return true.
14
+ if (value instanceof _FDBKeyRange.default) {
15
+ return true;
16
+ }
17
+
18
+ // Let key be the result of converting a value to a key with value.
19
+ const key = (0, _valueToKeyWithoutThrowing.default)(value);
20
+
21
+ // If key is "invalid type" return false.
22
+ // Else return true.
23
+ return key !== _valueToKeyWithoutThrowing.INVALID_TYPE;
31
24
  };
32
25
  var _default = exports.default = isPotentiallyValidKeyRange;
33
26
  module.exports = exports.default;
@@ -25,10 +25,10 @@ function getSetImmediateFromJsdom() {
25
25
 
26
26
  // waiting on this PR for typescript types: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1249
27
27
 
28
- // 'user-blocking' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping
29
- const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn, {
30
- priority: "user-blocking"
31
- }));
28
+ // 'postTask' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping.
29
+ // Using the default priority of 'user-visible' to avoid blocking input while still running fairly quickly.
30
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities
31
+ const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn));
32
32
 
33
33
  // fallback for environments that don't support any of the above
34
34
  const doSetTimeout = fn => setTimeout(fn, 0);
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.validateRequiredArguments = validateRequiredArguments;
7
+ // WebIDL requires passing the right number of non-optional arguments, e.g. IDBFactory.open() must have at least 1 arg
8
+ function validateRequiredArguments(numArguments, expectedNumArguments, methodName) {
9
+ if (numArguments < expectedNumArguments) {
10
+ // imitate Firefox's error message
11
+ throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} ` + `required, but only ${arguments.length} passed`);
12
+ }
13
+ }
@@ -5,63 +5,18 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _errors = require("./errors.js");
8
- var _isSharedArrayBuffer = _interopRequireDefault(require("./isSharedArrayBuffer.js"));
9
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
8
+ var _valueToKeyWithoutThrowing = _interopRequireWildcard(require("./valueToKeyWithoutThrowing.js"));
9
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
10
10
  // https://w3c.github.io/IndexedDB/#convert-value-to-key
11
+ // Plus throwing a DataError for invalid value/invalid key, which is commonly done
12
+ // in lots of IndexedDB operations
11
13
  const valueToKey = (input, seen) => {
12
- if (typeof input === "number") {
13
- if (isNaN(input)) {
14
- throw new _errors.DataError();
15
- }
16
- return input;
17
- } else if (Object.prototype.toString.call(input) === "[object Date]") {
18
- const ms = input.valueOf();
19
- if (isNaN(ms)) {
20
- throw new _errors.DataError();
21
- }
22
- return new Date(ms);
23
- } else if (typeof input === "string") {
24
- return input;
25
- } else if (
26
- // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type
27
- (input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input)) &&
28
- // We can't consistently test detachedness, so instead we check if byteLength === 0
29
- // This isn't foolproof, but there's no perfect way to detect if Uint8Arrays or
30
- // SharedArrayBuffers are detached
31
- !("detached" in input ? input.detached : input.byteLength === 0)) {
32
- let arrayBuffer;
33
- let offset = 0;
34
- let length = 0;
35
- if (input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input)) {
36
- arrayBuffer = input;
37
- length = input.byteLength;
38
- } else {
39
- arrayBuffer = input.buffer;
40
- offset = input.byteOffset;
41
- length = input.byteLength;
42
- }
43
- return arrayBuffer.slice(offset, offset + length);
44
- } else if (Array.isArray(input)) {
45
- if (seen === undefined) {
46
- seen = new Set();
47
- } else if (seen.has(input)) {
48
- throw new _errors.DataError();
49
- }
50
- seen.add(input);
51
- const keys = [];
52
- for (let i = 0; i < input.length; i++) {
53
- const hop = Object.hasOwn(input, i);
54
- if (!hop) {
55
- throw new _errors.DataError();
56
- }
57
- const entry = input[i];
58
- const key = valueToKey(entry, seen);
59
- keys.push(key);
60
- }
61
- return keys;
62
- } else {
14
+ const result = (0, _valueToKeyWithoutThrowing.default)(input, seen);
15
+ if (result === _valueToKeyWithoutThrowing.INVALID_VALUE || result === _valueToKeyWithoutThrowing.INVALID_TYPE) {
16
+ // If key is "invalid value" or "invalid type", throw a "DataError" DOMException
63
17
  throw new _errors.DataError();
64
18
  }
19
+ return result;
65
20
  };
66
21
  var _default = exports.default = valueToKey;
67
22
  module.exports = exports.default;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.INVALID_VALUE = exports.INVALID_TYPE = void 0;
7
+ var _isSharedArrayBuffer = _interopRequireDefault(require("./isSharedArrayBuffer.js"));
8
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
9
+ const INVALID_TYPE = exports.INVALID_TYPE = Symbol("INVALID_TYPE");
10
+ const INVALID_VALUE = exports.INVALID_VALUE = Symbol("INVALID_VALUE");
11
+
12
+ // https://w3c.github.io/IndexedDB/#convert-value-to-key
13
+ // The "without exceptions" version is because we typically want to throw exceptions (DataError) but not for
14
+ // the "is potentially valid key range" routine.
15
+ const valueToKeyWithoutThrowing = (input, seen) => {
16
+ if (typeof input === "number") {
17
+ if (isNaN(input)) {
18
+ // If input is NaN then return "invalid value".
19
+ return INVALID_VALUE;
20
+ }
21
+ return input;
22
+ } else if (Object.prototype.toString.call(input) === "[object Date]") {
23
+ const ms = input.valueOf();
24
+ if (isNaN(ms)) {
25
+ // If ms is NaN then return "invalid value".
26
+ return INVALID_VALUE;
27
+ }
28
+ return new Date(ms);
29
+ } else if (typeof input === "string") {
30
+ return input;
31
+ } else if (
32
+ // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type
33
+ input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input)) {
34
+ // We can't consistently test detachedness, so instead we check if byteLength === 0
35
+ // This isn't foolproof, but there's no perfect way to detect if Uint8Arrays or
36
+ // SharedArrayBuffers are detached
37
+ if ("detached" in input ? input.detached : input.byteLength === 0) {
38
+ // If input is detached then return "invalid value".
39
+ return INVALID_VALUE;
40
+ }
41
+ let arrayBuffer;
42
+ let offset = 0;
43
+ let length = 0;
44
+ if (input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input)) {
45
+ arrayBuffer = input;
46
+ length = input.byteLength;
47
+ } else {
48
+ arrayBuffer = input.buffer;
49
+ offset = input.byteOffset;
50
+ length = input.byteLength;
51
+ }
52
+ return arrayBuffer.slice(offset, offset + length);
53
+ } else if (Array.isArray(input)) {
54
+ if (seen === undefined) {
55
+ seen = new Set();
56
+ } else if (seen.has(input)) {
57
+ // If seen contains input, then return "invalid value".
58
+ return INVALID_VALUE;
59
+ }
60
+ seen.add(input);
61
+
62
+ // This algorithm is tricky to account for `bindings-inject-keys-bypass.any.js`. We _should_ return early when
63
+ // encountering an invalid key/type, but we also need to avoid triggering `Object.prototype['10']` if it's been
64
+ // overridden. One simple way to do this (and which doesn't rely on sparse arrays or other exotic solutions that
65
+ // could cause de-opts) is to use `Array.from()` with a mapper function, which does not trigger the prototype
66
+ // setter [1]. It does prevent an early return, but we can at least short-circuit inside the mapper function
67
+ // (which isn't strictly necessary to pass the WPTs, but is closer to the spec).
68
+ // [1]: See https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from, specifically
69
+ // the chain CreateDataPropertyOrThrow -> CreateDataProperty -> DefineOwnProperty which defines
70
+ // the array element as an "own" property.
71
+ let hasInvalid = false;
72
+ const keys = Array.from({
73
+ length: input.length
74
+ }, (_, i) => {
75
+ if (hasInvalid) {
76
+ return;
77
+ }
78
+ const hop = Object.hasOwn(input, i);
79
+ if (!hop) {
80
+ // If hop is false, return "invalid value".
81
+ hasInvalid = true;
82
+ return;
83
+ }
84
+ const entry = input[i];
85
+ const key = valueToKeyWithoutThrowing(entry, seen);
86
+ // If key is "invalid value" or "invalid type" abort these steps and return "invalid value".
87
+ if (key === INVALID_VALUE || key === INVALID_TYPE) {
88
+ hasInvalid = true;
89
+ return;
90
+ }
91
+ return key;
92
+ });
93
+ if (hasInvalid) {
94
+ return INVALID_VALUE;
95
+ }
96
+ return keys;
97
+ } else {
98
+ // Otherwise: Return "invalid type".
99
+ return INVALID_TYPE;
100
+ }
101
+ };
102
+ var _default = exports.default = valueToKeyWithoutThrowing;
@@ -4,6 +4,7 @@ import cmp from "./lib/cmp.js";
4
4
  import { DataError, InvalidAccessError, InvalidStateError, ReadOnlyError, TransactionInactiveError } from "./lib/errors.js";
5
5
  import extractKey from "./lib/extractKey.js";
6
6
  import valueToKey from "./lib/valueToKey.js";
7
+ import { cloneValueForInsertion } from "./lib/cloneValueForInsertion.js";
7
8
  const getEffectiveObjectStore = cursor => {
8
9
  if (cursor.source instanceof FDBObjectStore) {
9
10
  return cursor.source;
@@ -298,7 +299,7 @@ class FDBCursor {
298
299
  if (!this._gotValue || !Object.hasOwn(this, "value")) {
299
300
  throw new InvalidStateError();
300
301
  }
301
- const clone = structuredClone(value);
302
+ const clone = cloneValueForInsertion(value, transaction);
302
303
  if (effectiveObjectStore.keyPath !== null) {
303
304
  let tempKey;
304
305
  try {