tsdf 18.3.1 → 18.5.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.
- package/dist/async-storage.d.ts +1 -1
- package/dist/async-storage.js +1 -1
- package/dist/{asyncStorageAdapter-D_Ltk0xg.d.ts → asyncStorageAdapter-C7J64ZKi.d.ts} +1 -1
- package/dist/{asyncStorageAdapter-NrI38v4g.js → asyncStorageAdapter-D6IVBzPg.js} +1 -1
- package/dist/{asyncStorageAdapters-Daewq7dv.js → asyncStorageAdapters-CBMshtkY.js} +2 -2
- package/dist/indexed-db-storage.d.ts +1 -1
- package/dist/indexed-db-storage.js +1 -1
- package/dist/indexedDbPersistentStorage-x6dVEqkJ.js +1156 -0
- package/dist/main.d.ts +133 -20
- package/dist/main.js +1589 -372
- package/dist/opfs-storage.d.ts +1 -1
- package/dist/opfs-storage.js +1 -1
- package/dist/{opfsPersistentStorage-HRMP5gzd.d.ts → opfsPersistentStorage-CEhiNR8Q.d.ts} +1 -1
- package/dist/{opfsPersistentStorage-amwSWm_p.js → opfsPersistentStorage-CwmY3O1r.js} +1 -1
- package/dist/{types-DeZ9VDOe.d.ts → types-Bp7_Ra7_.d.ts} +625 -45
- package/docs/collection-store.md +9 -7
- package/docs/hooks.md +116 -3
- package/docs/list-query-store.md +3 -0
- package/docs/offline.md +457 -4
- package/docs/partial-resources.md +4 -0
- package/docs/persistent-storage.md +30 -0
- package/docs/shared-types.md +4 -0
- package/docs/store-manager.md +22 -3
- package/package.json +1 -1
- package/dist/indexedDbPersistentStorage-JJdUGGI8.js +0 -966
|
@@ -0,0 +1,1156 @@
|
|
|
1
|
+
import { $ as matchesConditionalRemove, J as compareMetadata, Q as getPersistedNamespaceId, X as getNamespaceId, Y as encodePersistedAsyncNamespaceKind, Z as getPayloadRecordKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as emitTSDFDebugLog, et as normalizeStaticPolicy, i as createAsyncStorageAdapter, j as serializeJsonForStorage, nt as parsePersistedAsyncNamespaceKind, rt as serializeProtectedRef, tt as parseAsyncStorageRecordKey, x as getTSDFDebugTimingMs } from "./asyncStorageAdapter-D6IVBzPg.js";
|
|
2
|
+
import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
|
|
3
|
+
import { isObject } from "@ls-stack/utils/typeGuards";
|
|
4
|
+
import { asPossiblyUndefined } from "@ls-stack/utils/typingFnUtils";
|
|
5
|
+
//#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
|
|
6
|
+
const DEFAULT_INDEXED_DB_NAME = "tsdf-persistent-storage-compact-alpha-reset";
|
|
7
|
+
const INDEXED_DB_VERSION = 1;
|
|
8
|
+
const INDEXED_DB_ENTRY_STORE = "entries";
|
|
9
|
+
const INDEXED_DB_NAMESPACE_POLICY_STORE = "namespacePolicies";
|
|
10
|
+
/** No longer used; still created so the database schema stays the same. */
|
|
11
|
+
const INDEXED_DB_META_STORE = "meta";
|
|
12
|
+
/**
|
|
13
|
+
* How often a pending open request or transaction is checked for progress.
|
|
14
|
+
* It is given up after two consecutive checks without a single IndexedDB
|
|
15
|
+
* event, i.e. after 30s to 45s without progress. Progress is what is
|
|
16
|
+
* measured, not total duration, so a large batch on a slow device is never
|
|
17
|
+
* cut short.
|
|
18
|
+
*/
|
|
19
|
+
const INDEXED_DB_STALL_CHECK_INTERVAL_MS = 15e3;
|
|
20
|
+
/**
|
|
21
|
+
* Errors that say the connection (not the data or the quota) failed: the
|
|
22
|
+
* connection was closed or is closing (`InvalidStateError`), the browser's
|
|
23
|
+
* storage process went away (`UnknownError`, e.g. WebKit's "Connection to
|
|
24
|
+
* Indexed Database server lost"), a transaction was aborted under the
|
|
25
|
+
* operation (`AbortError`), or the operation stalled (`TimeoutError`).
|
|
26
|
+
*/
|
|
27
|
+
const INDEXED_DB_CONNECTION_ERROR_NAMES = new Set([
|
|
28
|
+
"AbortError",
|
|
29
|
+
"InvalidStateError",
|
|
30
|
+
"TimeoutError",
|
|
31
|
+
"UnknownError"
|
|
32
|
+
]);
|
|
33
|
+
function isIndexedDbConnectionError(error) {
|
|
34
|
+
return typeof error === "object" && error !== null && "name" in error && typeof error.name === "string" && INDEXED_DB_CONNECTION_ERROR_NAMES.has(error.name);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* IndexedDB events delivered so far to this page, per database. While a
|
|
38
|
+
* database's count keeps growing the browser's storage backend is answering
|
|
39
|
+
* for it, so an operation that is merely queued behind a long-running one is
|
|
40
|
+
* not mistaken for a stalled one. Operations only queue behind work on the
|
|
41
|
+
* same database, so other databases' events say nothing about it.
|
|
42
|
+
*/
|
|
43
|
+
const indexedDbProgressByDatabase = /* @__PURE__ */ new Map();
|
|
44
|
+
/**
|
|
45
|
+
* Times the page was hidden or shown since the first stall watch started, so
|
|
46
|
+
* a check can tell its interval included hidden time even when the page was
|
|
47
|
+
* visible both when the interval started and when it ended.
|
|
48
|
+
*/
|
|
49
|
+
let pageVisibilityChanges = 0;
|
|
50
|
+
let isTrackingPageVisibility = false;
|
|
51
|
+
function trackPageVisibility() {
|
|
52
|
+
if (isTrackingPageVisibility) return;
|
|
53
|
+
isTrackingPageVisibility = true;
|
|
54
|
+
asPossiblyUndefined(globalThis.document)?.addEventListener("visibilitychange", () => {
|
|
55
|
+
pageVisibilityChanges += 1;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
function isPageHidden() {
|
|
59
|
+
return asPossiblyUndefined(globalThis.document)?.visibilityState === "hidden";
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Gives up on an open request or transaction when IndexedDB stopped
|
|
63
|
+
* answering: some browsers leave operations pending forever, without any
|
|
64
|
+
* event, after a tab was backgrounded.
|
|
65
|
+
*/
|
|
66
|
+
var IndexedDbStallWatch = class {
|
|
67
|
+
/** Reject the promises still waiting on the watched operation. */
|
|
68
|
+
rejecters = [];
|
|
69
|
+
#transaction;
|
|
70
|
+
#progress;
|
|
71
|
+
#checkedEventCount;
|
|
72
|
+
#checkedAt = Date.now();
|
|
73
|
+
#checkedVisibilityChanges;
|
|
74
|
+
#stalledChecks = 0;
|
|
75
|
+
#timer;
|
|
76
|
+
constructor(databaseName, transaction) {
|
|
77
|
+
trackPageVisibility();
|
|
78
|
+
this.#checkedVisibilityChanges = pageVisibilityChanges;
|
|
79
|
+
let progress = indexedDbProgressByDatabase.get(databaseName);
|
|
80
|
+
if (progress === void 0) {
|
|
81
|
+
progress = { events: 0 };
|
|
82
|
+
indexedDbProgressByDatabase.set(databaseName, progress);
|
|
83
|
+
}
|
|
84
|
+
this.#progress = progress;
|
|
85
|
+
this.#checkedEventCount = progress.events;
|
|
86
|
+
this.#transaction = transaction;
|
|
87
|
+
this.#timer = setTimeout(this.#check, INDEXED_DB_STALL_CHECK_INTERVAL_MS);
|
|
88
|
+
transaction?.addEventListener("complete", this.stop);
|
|
89
|
+
transaction?.addEventListener("abort", this.stop);
|
|
90
|
+
}
|
|
91
|
+
/** Records an IndexedDB event of the watched database. */
|
|
92
|
+
progressed = () => {
|
|
93
|
+
this.#progress.events += 1;
|
|
94
|
+
};
|
|
95
|
+
stop = () => {
|
|
96
|
+
clearTimeout(this.#timer);
|
|
97
|
+
};
|
|
98
|
+
#check = () => {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
if (this.#progress.events !== this.#checkedEventCount || now - this.#checkedAt > INDEXED_DB_STALL_CHECK_INTERVAL_MS * 1.5 || pageVisibilityChanges !== this.#checkedVisibilityChanges || isPageHidden()) this.#stalledChecks = 0;
|
|
101
|
+
else this.#stalledChecks += 1;
|
|
102
|
+
this.#checkedEventCount = this.#progress.events;
|
|
103
|
+
this.#checkedAt = now;
|
|
104
|
+
this.#checkedVisibilityChanges = pageVisibilityChanges;
|
|
105
|
+
if (this.#stalledChecks < 2) {
|
|
106
|
+
this.#timer = setTimeout(this.#check, INDEXED_DB_STALL_CHECK_INTERVAL_MS);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
this.#transaction?.abort();
|
|
111
|
+
} catch {}
|
|
112
|
+
const error = /* @__PURE__ */ new Error("IndexedDB operation made no progress; treating the connection as lost.");
|
|
113
|
+
error.name = "TimeoutError";
|
|
114
|
+
for (const reject of this.rejecters) reject(error);
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
function createScopePrimaryKey(scope) {
|
|
118
|
+
return [
|
|
119
|
+
scope.sessionKey,
|
|
120
|
+
scope.storeName,
|
|
121
|
+
encodePersistedAsyncNamespaceKind(scope.kind)
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
function createEntryPrimaryKey(scope, key) {
|
|
125
|
+
return [createScopeId(scope.sessionKey, scope.storeName, scope.kind), key];
|
|
126
|
+
}
|
|
127
|
+
function createScopeKeyRange(scope) {
|
|
128
|
+
return IDBKeyRange.bound(createEntryPrimaryKey(scope, ""), createEntryPrimaryKey(scope, ""));
|
|
129
|
+
}
|
|
130
|
+
function createScopeLastAccessRange(scope) {
|
|
131
|
+
const scopeId = createScopeId(scope.sessionKey, scope.storeName, scope.kind);
|
|
132
|
+
return IDBKeyRange.bound([scopeId, Number.MIN_SAFE_INTEGER], [scopeId, Number.MAX_SAFE_INTEGER]);
|
|
133
|
+
}
|
|
134
|
+
function createScopeGroupRange(scope, group) {
|
|
135
|
+
return IDBKeyRange.only([createScopeId(scope.sessionKey, scope.storeName, scope.kind), group]);
|
|
136
|
+
}
|
|
137
|
+
function createScopeOfflineProtectedRange(scope) {
|
|
138
|
+
return IDBKeyRange.only([createScopeId(scope.sessionKey, scope.storeName, scope.kind), 1]);
|
|
139
|
+
}
|
|
140
|
+
function createScopePolicyKey(scope) {
|
|
141
|
+
return createScopePrimaryKey(scope);
|
|
142
|
+
}
|
|
143
|
+
function createScopeId(sessionKey, storeName, kind) {
|
|
144
|
+
return getPersistedNamespaceId({
|
|
145
|
+
sessionKey,
|
|
146
|
+
storeName,
|
|
147
|
+
kind
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
function getScopeFromPrimaryKey(key) {
|
|
151
|
+
if (!Array.isArray(key) || key.length < 3) return null;
|
|
152
|
+
const [sessionKey, storeName, rawKind] = key;
|
|
153
|
+
if (typeof sessionKey !== "string" || typeof storeName !== "string") return null;
|
|
154
|
+
const kind = typeof rawKind === "string" ? parsePersistedAsyncNamespaceKind(rawKind) : null;
|
|
155
|
+
if (kind === null) return null;
|
|
156
|
+
return {
|
|
157
|
+
kind,
|
|
158
|
+
sessionKey,
|
|
159
|
+
storeName
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function getEntryKeyFromPrimaryKey(key) {
|
|
163
|
+
if (!Array.isArray(key) || key.length < 2) return null;
|
|
164
|
+
return typeof key[1] === "string" ? key[1] : null;
|
|
165
|
+
}
|
|
166
|
+
function splitCustomMetadata(customMetadata) {
|
|
167
|
+
if (customMetadata === void 0) return {};
|
|
168
|
+
const { g, o, p, ...rest } = customMetadata;
|
|
169
|
+
return {
|
|
170
|
+
...typeof g === "string" ? { group: g } : {},
|
|
171
|
+
...o === true ? { offlineProtected: true } : {},
|
|
172
|
+
..."p" in customMetadata ? { payload: p } : {},
|
|
173
|
+
...Object.keys(rest).length > 0 ? { extraMetadata: rest } : {}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function mergeCustomMetadata(fields) {
|
|
177
|
+
const result = {
|
|
178
|
+
...fields.extraMetadata ?? {},
|
|
179
|
+
...fields.group !== void 0 ? { g: fields.group } : {},
|
|
180
|
+
...fields.offlineProtected === true ? { o: true } : {},
|
|
181
|
+
...fields.payload !== void 0 ? { p: fields.payload } : {}
|
|
182
|
+
};
|
|
183
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
184
|
+
}
|
|
185
|
+
function getCustomMetadataFromEntryRecord(record) {
|
|
186
|
+
return mergeCustomMetadata({
|
|
187
|
+
extraMetadata: record.m,
|
|
188
|
+
group: record.g,
|
|
189
|
+
offlineProtected: record.o === 1 ? true : void 0,
|
|
190
|
+
payload: record.p
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
function toMetadataRecord(record) {
|
|
194
|
+
const customMetadata = getCustomMetadataFromEntryRecord(record);
|
|
195
|
+
return {
|
|
196
|
+
lastAccessAt: record.a,
|
|
197
|
+
...typeof record.z === "number" ? { sizeBytes: record.z } : {},
|
|
198
|
+
version: record.v ?? 1,
|
|
199
|
+
...customMetadata ? { customMetadata } : {}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function toPublicMetadata(key, record) {
|
|
203
|
+
return {
|
|
204
|
+
customMetadata: getCustomMetadataFromEntryRecord(record) ?? {},
|
|
205
|
+
key,
|
|
206
|
+
lastAccessAt: record.a,
|
|
207
|
+
payloadRef: getPayloadRecordKey(key),
|
|
208
|
+
...typeof record.z === "number" ? { sizeBytes: record.z } : {},
|
|
209
|
+
version: record.v ?? 1,
|
|
210
|
+
writtenAt: record.a
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const INDEXED_DB_ENTRY_RECORD_KEYS = new Set([
|
|
214
|
+
"a",
|
|
215
|
+
"d",
|
|
216
|
+
"g",
|
|
217
|
+
"i",
|
|
218
|
+
"m",
|
|
219
|
+
"o",
|
|
220
|
+
"p",
|
|
221
|
+
"v",
|
|
222
|
+
"z"
|
|
223
|
+
]);
|
|
224
|
+
const INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS = new Set(["p", "s"]);
|
|
225
|
+
function toRecordValue(value) {
|
|
226
|
+
return __LEGIT_CAST__(value);
|
|
227
|
+
}
|
|
228
|
+
function toEntryRecordValue(value) {
|
|
229
|
+
return __LEGIT_CAST__(value);
|
|
230
|
+
}
|
|
231
|
+
function toNamespacePolicyRecordValue(value) {
|
|
232
|
+
return __LEGIT_CAST__(value);
|
|
233
|
+
}
|
|
234
|
+
function parseIndexedDbPersistedStaticPolicy(value) {
|
|
235
|
+
if (value === null || value === void 0) return null;
|
|
236
|
+
if (!isObject(value)) return void 0;
|
|
237
|
+
const record = toRecordValue(value);
|
|
238
|
+
if (Object.keys(record).some((key) => key !== "b" && key !== "k")) return;
|
|
239
|
+
const rawMaxBytes = record.b;
|
|
240
|
+
if (rawMaxBytes !== void 0 && (typeof rawMaxBytes !== "number" || !Number.isInteger(rawMaxBytes) || rawMaxBytes < 0)) return;
|
|
241
|
+
const validatedPinnedKeys = record.k === void 0 ? void 0 : validateStringArray(record.k);
|
|
242
|
+
if (validatedPinnedKeys === null) return void 0;
|
|
243
|
+
return normalizeStaticPolicy({
|
|
244
|
+
...typeof record.b === "number" ? { maxBytes: record.b } : {},
|
|
245
|
+
...validatedPinnedKeys !== void 0 ? { pinnedKeys: validatedPinnedKeys } : {}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function serializeIndexedDbPersistedStaticPolicy(policy) {
|
|
249
|
+
const normalizedPolicy = normalizeStaticPolicy(policy);
|
|
250
|
+
if (normalizedPolicy === null) return null;
|
|
251
|
+
return {
|
|
252
|
+
...normalizedPolicy.maxBytes !== void 0 ? { b: normalizedPolicy.maxBytes } : {},
|
|
253
|
+
...normalizedPolicy.pinnedKeys !== void 0 && normalizedPolicy.pinnedKeys.length > 0 ? { k: normalizedPolicy.pinnedKeys } : {}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function validateStringArray(value) {
|
|
257
|
+
if (!Array.isArray(value)) return null;
|
|
258
|
+
const result = [];
|
|
259
|
+
for (const entry of value) {
|
|
260
|
+
if (typeof entry !== "string") return null;
|
|
261
|
+
result.push(entry);
|
|
262
|
+
}
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
function isValidEntryRecord(record) {
|
|
266
|
+
if (!isObject(record)) return false;
|
|
267
|
+
const recordValue = toRecordValue(record);
|
|
268
|
+
if (Object.keys(recordValue).some((key) => !INDEXED_DB_ENTRY_RECORD_KEYS.has(key))) return false;
|
|
269
|
+
return typeof recordValue.i === "string" && typeof recordValue.a === "number" && "d" in recordValue && (recordValue.v === void 0 || typeof recordValue.v === "number") && (recordValue.z === void 0 || typeof recordValue.z === "number") && (recordValue.m === void 0 || isObject(recordValue.m)) && (recordValue.g === void 0 || typeof recordValue.g === "string") && (recordValue.o === void 0 || recordValue.o === 1);
|
|
270
|
+
}
|
|
271
|
+
function isValidNamespacePolicyRecord(record) {
|
|
272
|
+
if (!isObject(record)) return false;
|
|
273
|
+
const recordValue = toRecordValue(record);
|
|
274
|
+
if (Object.keys(recordValue).some((key) => !INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS.has(key))) return false;
|
|
275
|
+
if (typeof recordValue.s !== "string" || !("p" in recordValue)) return false;
|
|
276
|
+
return recordValue.p === null || parseIndexedDbPersistedStaticPolicy(recordValue.p) !== void 0;
|
|
277
|
+
}
|
|
278
|
+
function getStaticPolicyFromScopeRecord(record) {
|
|
279
|
+
if (record === void 0) return null;
|
|
280
|
+
return parseIndexedDbPersistedStaticPolicy(record.p) ?? null;
|
|
281
|
+
}
|
|
282
|
+
function compactEntryValue(scope, value) {
|
|
283
|
+
return { d: value };
|
|
284
|
+
}
|
|
285
|
+
function estimateIndexedDbManagedEntrySizeBytes(args) {
|
|
286
|
+
return estimateManagedAsyncStorageEntrySizeBytes(args.serializedValue ?? serializeJsonForStorage(args.value).rawValue, args.lastAccessAt, args.version, args.customMetadata);
|
|
287
|
+
}
|
|
288
|
+
function expandEntryValue(scope, record) {
|
|
289
|
+
return record.d;
|
|
290
|
+
}
|
|
291
|
+
function openRequestAsPromise(watch, request) {
|
|
292
|
+
return new Promise((resolve, reject) => {
|
|
293
|
+
watch.rejecters.push(reject);
|
|
294
|
+
request.onsuccess = () => {
|
|
295
|
+
watch.progressed();
|
|
296
|
+
resolve(__LEGIT_CAST__(request.result));
|
|
297
|
+
};
|
|
298
|
+
request.onerror = () => reject(getRequestError(request) ?? /* @__PURE__ */ new Error("IndexedDB request failed."));
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* A request still pending when its transaction aborts fails with a generic
|
|
303
|
+
* `AbortError`; the transaction's error is then the real cause (a quota or
|
|
304
|
+
* constraint error from another request), which must not be mistaken for a
|
|
305
|
+
* lost connection.
|
|
306
|
+
*/
|
|
307
|
+
function getRequestError(request) {
|
|
308
|
+
const error = request.error;
|
|
309
|
+
if (error?.name === "AbortError") return request.transaction?.error ?? error;
|
|
310
|
+
return error;
|
|
311
|
+
}
|
|
312
|
+
function transactionDone(transaction, watch) {
|
|
313
|
+
return new Promise((resolve, reject) => {
|
|
314
|
+
watch.rejecters.push(reject);
|
|
315
|
+
transaction.oncomplete = () => {
|
|
316
|
+
watch.progressed();
|
|
317
|
+
resolve();
|
|
318
|
+
};
|
|
319
|
+
transaction.onerror = (event) => reject(transaction.error ?? (event.target instanceof IDBRequest ? event.target.error : null) ?? /* @__PURE__ */ new Error("IndexedDB transaction failed."));
|
|
320
|
+
transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB transaction aborted."));
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
async function iterateCursor(watch, request, callback) {
|
|
324
|
+
await new Promise((resolve, reject) => {
|
|
325
|
+
watch.rejecters.push(reject);
|
|
326
|
+
request.onerror = () => reject(getRequestError(request) ?? /* @__PURE__ */ new Error("IndexedDB cursor request failed."));
|
|
327
|
+
request.onsuccess = async () => {
|
|
328
|
+
watch.progressed();
|
|
329
|
+
const cursor = request.result;
|
|
330
|
+
if (cursor === null) {
|
|
331
|
+
resolve();
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
await callback(cursor);
|
|
336
|
+
cursor.continue();
|
|
337
|
+
} catch (error) {
|
|
338
|
+
reject(error instanceof Error ? error : /* @__PURE__ */ new Error("IndexedDB cursor callback failed."));
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
function deleteDatabase(databaseName) {
|
|
344
|
+
return new Promise((resolve, reject) => {
|
|
345
|
+
const request = indexedDB.deleteDatabase(databaseName);
|
|
346
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB deleteDatabase failed."));
|
|
347
|
+
request.onblocked = () => resolve();
|
|
348
|
+
request.onsuccess = () => resolve();
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
var IndexedDbAsyncStorageDriver = class {
|
|
352
|
+
debugLogger;
|
|
353
|
+
__tsdfManagedStorage = {
|
|
354
|
+
applyManagedCommit: this.applyManagedCommit.bind(this),
|
|
355
|
+
clearManagedNamespace: this.clearManagedNamespace.bind(this),
|
|
356
|
+
listManagedKeys: this.listManagedKeys.bind(this),
|
|
357
|
+
listManagedMetadata: this.listManagedMetadata.bind(this),
|
|
358
|
+
persistNamespaceIndexState: this.persistNamespaceIndexState.bind(this),
|
|
359
|
+
readProtectedStorageKeys: this.readProtectedStorageKeys.bind(this),
|
|
360
|
+
readManagedEntries: this.readManagedEntries.bind(this),
|
|
361
|
+
readNamespaceIndexState: this.readNamespaceIndexState.bind(this),
|
|
362
|
+
syncSessionProtectedKeys: this.syncSessionProtectedKeys.bind(this)
|
|
363
|
+
};
|
|
364
|
+
#database = null;
|
|
365
|
+
#databasePromise = null;
|
|
366
|
+
#instrumentation;
|
|
367
|
+
databaseName;
|
|
368
|
+
storageId;
|
|
369
|
+
constructor(databaseName = DEFAULT_INDEXED_DB_NAME, instrumentation = void 0) {
|
|
370
|
+
this.databaseName = databaseName;
|
|
371
|
+
this.storageId = `indexedDb:${databaseName}`;
|
|
372
|
+
this.#instrumentation = instrumentation;
|
|
373
|
+
}
|
|
374
|
+
async get(scope, key) {
|
|
375
|
+
const parsedKey = parseAsyncStorageRecordKey(key);
|
|
376
|
+
if (parsedKey.recordKind === "payload") {
|
|
377
|
+
const entry = await this.#getEntry(scope, parsedKey.userKey);
|
|
378
|
+
return entry === null ? null : expandEntryValue(scope, entry);
|
|
379
|
+
}
|
|
380
|
+
if (parsedKey.rawKey !== "_i") return null;
|
|
381
|
+
const state = await this.readNamespaceIndexState(scope);
|
|
382
|
+
if (!state.exists || !state.valid || state.entries === null) return null;
|
|
383
|
+
return {
|
|
384
|
+
e: Object.fromEntries([...state.entries.entries()].map(([entryKey, metadata]) => [entryKey, {
|
|
385
|
+
a: metadata.lastAccessAt,
|
|
386
|
+
...metadata.version !== 1 ? { v: metadata.version } : {},
|
|
387
|
+
...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
|
|
388
|
+
...metadata.customMetadata ?? {}
|
|
389
|
+
}])),
|
|
390
|
+
...state.staticPolicy !== null ? { s: state.staticPolicy } : {}
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
async set(scope, key, value) {
|
|
394
|
+
await this.setMany(scope, [{
|
|
395
|
+
key,
|
|
396
|
+
value
|
|
397
|
+
}]);
|
|
398
|
+
}
|
|
399
|
+
async remove(scope, key) {
|
|
400
|
+
await this.removeMany(scope, [key]);
|
|
401
|
+
}
|
|
402
|
+
async getMany(scope, keys) {
|
|
403
|
+
return Promise.all(keys.map((key) => this.get(scope, key)));
|
|
404
|
+
}
|
|
405
|
+
async setMany(scope, entries) {
|
|
406
|
+
for (const entry of entries) {
|
|
407
|
+
const parsedKey = parseAsyncStorageRecordKey(entry.key);
|
|
408
|
+
if (parsedKey.recordKind === "payload") {
|
|
409
|
+
const existing = await this.#getEntry(scope, parsedKey.userKey);
|
|
410
|
+
const lastAccessAt = existing?.a ?? Date.now();
|
|
411
|
+
await this.#putEntryRecord(scope, {
|
|
412
|
+
customMetadata: existing === null ? void 0 : getCustomMetadataFromEntryRecord(existing),
|
|
413
|
+
key: parsedKey.userKey,
|
|
414
|
+
lastAccessAt,
|
|
415
|
+
value: entry.value,
|
|
416
|
+
version: existing?.v ?? 1
|
|
417
|
+
});
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
if (parsedKey.rawKey === "_i") {
|
|
421
|
+
const state = this.#parsePersistedIndexState(entry.value);
|
|
422
|
+
if (state !== null) await this.persistNamespaceIndexState(scope, state);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async removeMany(scope, keys) {
|
|
427
|
+
return this.#withConnection(async (database) => {
|
|
428
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
429
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
430
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
431
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
432
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
433
|
+
let removedAnyEntry = false;
|
|
434
|
+
let removedScope = false;
|
|
435
|
+
for (const key of keys) {
|
|
436
|
+
const parsedKey = parseAsyncStorageRecordKey(key);
|
|
437
|
+
if (parsedKey.recordKind === "payload") {
|
|
438
|
+
entryStore.delete(createEntryPrimaryKey(scope, parsedKey.userKey)).onsuccess = watch.progressed;
|
|
439
|
+
removedAnyEntry = true;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (parsedKey.rawKey === "_i") {
|
|
443
|
+
policyStore.delete(createScopePolicyKey(scope));
|
|
444
|
+
removedScope = true;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (removedAnyEntry && !removedScope) {
|
|
448
|
+
const countRequest = entryStore.count(createScopeKeyRange(scope));
|
|
449
|
+
countRequest.onsuccess = () => {
|
|
450
|
+
watch.progressed();
|
|
451
|
+
if (countRequest.result === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
await transactionDone(transaction, watch);
|
|
455
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-records", startTime, {
|
|
456
|
+
keyCount: keys.length,
|
|
457
|
+
objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE]
|
|
458
|
+
});
|
|
459
|
+
this.#instrumentation?.onRemoveMany?.(scope, keys);
|
|
460
|
+
this.#instrumentation?.record({
|
|
461
|
+
keys: [...keys].sort((left, right) => left.localeCompare(right)),
|
|
462
|
+
scope,
|
|
463
|
+
time: Date.now(),
|
|
464
|
+
type: "removeManagedRecords"
|
|
465
|
+
});
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
async listKeys(scope) {
|
|
469
|
+
const state = await this.readNamespaceIndexState(scope);
|
|
470
|
+
if (!state.exists || state.entries === null) return [];
|
|
471
|
+
const keys = [...state.entries.keys()].map((key) => getPayloadRecordKey(key));
|
|
472
|
+
keys.push("_i");
|
|
473
|
+
return keys.sort((left, right) => left.localeCompare(right));
|
|
474
|
+
}
|
|
475
|
+
async clear(scope) {
|
|
476
|
+
await this.clearManagedNamespace(scope);
|
|
477
|
+
}
|
|
478
|
+
async listScopes(sessionKey) {
|
|
479
|
+
return (await this.listScopesWithKnownRecordKeys(sessionKey)).map(({ scope }) => scope);
|
|
480
|
+
}
|
|
481
|
+
async listScopesWithKnownRecordKeys(sessionKey) {
|
|
482
|
+
return this.#withConnection(async (database) => {
|
|
483
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
484
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
485
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
486
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
487
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
488
|
+
const discoveredScopes = [];
|
|
489
|
+
await iterateCursor(watch, sessionKey === void 0 ? policyStore.openKeyCursor() : policyStore.index("bySession").openKeyCursor(IDBKeyRange.only(sessionKey)), async (cursor) => {
|
|
490
|
+
const scope = getScopeFromPrimaryKey(cursor.primaryKey);
|
|
491
|
+
if (scope === null) return;
|
|
492
|
+
const keys = new Set(["_i"]);
|
|
493
|
+
await iterateCursor(watch, entryStore.openKeyCursor(createScopeKeyRange(scope)), (entryCursor) => {
|
|
494
|
+
const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
|
|
495
|
+
if (entryKey === null) return;
|
|
496
|
+
keys.add(getPayloadRecordKey(entryKey));
|
|
497
|
+
});
|
|
498
|
+
discoveredScopes.push({
|
|
499
|
+
knownRecordKeys: [...keys].sort((left, right) => left.localeCompare(right)),
|
|
500
|
+
scope
|
|
501
|
+
});
|
|
502
|
+
});
|
|
503
|
+
await transactionDone(transaction, watch);
|
|
504
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(void 0, "list-scopes", startTime, {
|
|
505
|
+
count: discoveredScopes.length,
|
|
506
|
+
objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
|
|
507
|
+
...sessionKey !== void 0 ? { sessionKey } : {}
|
|
508
|
+
});
|
|
509
|
+
discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
|
|
510
|
+
this.#instrumentation?.record({
|
|
511
|
+
scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
|
|
512
|
+
...sessionKey !== void 0 ? { sessionKey } : {},
|
|
513
|
+
time: Date.now(),
|
|
514
|
+
type: "listScopesWithKnownRecordKeys"
|
|
515
|
+
});
|
|
516
|
+
return discoveredScopes;
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
async readManagedEntries(scope, keys) {
|
|
520
|
+
return this.#withConnection(async (database) => {
|
|
521
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
522
|
+
const transaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
523
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
524
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
525
|
+
const uniqueKeys = [...new Set(keys)];
|
|
526
|
+
const result = /* @__PURE__ */ new Map();
|
|
527
|
+
await Promise.all(uniqueKeys.map(async (key) => {
|
|
528
|
+
const record = await openRequestAsPromise(watch, store.get(createEntryPrimaryKey(scope, key)));
|
|
529
|
+
if (!isValidEntryRecord(record)) {
|
|
530
|
+
result.set(key, null);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
const entryRecord = toEntryRecordValue(record);
|
|
534
|
+
result.set(key, {
|
|
535
|
+
metadata: toPublicMetadata(key, entryRecord),
|
|
536
|
+
value: __LEGIT_CAST__(expandEntryValue(scope, entryRecord))
|
|
537
|
+
});
|
|
538
|
+
}));
|
|
539
|
+
await transactionDone(transaction, watch);
|
|
540
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "read-records", startTime, {
|
|
541
|
+
hitCount: [...result.values()].filter((value) => value !== null).length,
|
|
542
|
+
keyCount: uniqueKeys.length,
|
|
543
|
+
objectStores: [INDEXED_DB_ENTRY_STORE]
|
|
544
|
+
});
|
|
545
|
+
this.#instrumentation?.record({
|
|
546
|
+
keys: uniqueKeys,
|
|
547
|
+
resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
|
|
548
|
+
scope,
|
|
549
|
+
time: Date.now(),
|
|
550
|
+
type: "readManagedEntries"
|
|
551
|
+
});
|
|
552
|
+
return result;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
async listManagedMetadata(scope, args = {}) {
|
|
556
|
+
return this.#withConnection(async (database) => {
|
|
557
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
558
|
+
const order = args.order ?? "key";
|
|
559
|
+
const transaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
560
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
561
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
562
|
+
const entries = [];
|
|
563
|
+
let usedIndex = "key";
|
|
564
|
+
if (args.filter?.key === "g" && typeof args.filter.equals === "string" && order === "key") {
|
|
565
|
+
usedIndex = "group";
|
|
566
|
+
await iterateCursor(watch, store.index("byScopeGroup").openCursor(createScopeGroupRange(scope, args.filter.equals)), (cursor) => {
|
|
567
|
+
const record = cursor.value;
|
|
568
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
569
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
570
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
571
|
+
});
|
|
572
|
+
} else if (order === "lru-asc" || order === "lru-desc") {
|
|
573
|
+
usedIndex = "lru";
|
|
574
|
+
await iterateCursor(watch, store.index("byScopeLastAccessAt").openCursor(createScopeLastAccessRange(scope), order === "lru-desc" ? "prev" : "next"), (cursor) => {
|
|
575
|
+
const record = cursor.value;
|
|
576
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
577
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
578
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
579
|
+
});
|
|
580
|
+
} else await iterateCursor(watch, store.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
581
|
+
const record = cursor.value;
|
|
582
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
583
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
584
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
585
|
+
});
|
|
586
|
+
await transactionDone(transaction, watch);
|
|
587
|
+
const filter = args.filter;
|
|
588
|
+
const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
|
|
589
|
+
if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
|
|
590
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-record-metadata", startTime, {
|
|
591
|
+
count: filteredEntries.length,
|
|
592
|
+
objectStores: [INDEXED_DB_ENTRY_STORE],
|
|
593
|
+
order,
|
|
594
|
+
usedIndex
|
|
595
|
+
});
|
|
596
|
+
this.#instrumentation?.record({
|
|
597
|
+
order,
|
|
598
|
+
resultKeys: filteredEntries.map((entry) => entry.key),
|
|
599
|
+
scope,
|
|
600
|
+
time: Date.now(),
|
|
601
|
+
type: "listManagedMetadata",
|
|
602
|
+
usedIndex
|
|
603
|
+
});
|
|
604
|
+
return filteredEntries;
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
async listManagedKeys(scope) {
|
|
608
|
+
return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
|
|
609
|
+
}
|
|
610
|
+
async clearManagedNamespace(scope) {
|
|
611
|
+
return this.#withConnection(async (database) => {
|
|
612
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
613
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
614
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
615
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
616
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
617
|
+
entryStore.delete(createScopeKeyRange(scope));
|
|
618
|
+
policyStore.delete(createScopePolicyKey(scope));
|
|
619
|
+
await transactionDone(transaction, watch);
|
|
620
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "clear-records", startTime, { objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE] });
|
|
621
|
+
this.#instrumentation?.onClearManagedNamespace?.(scope);
|
|
622
|
+
this.#instrumentation?.record({
|
|
623
|
+
scope,
|
|
624
|
+
time: Date.now(),
|
|
625
|
+
type: "clearManagedNamespace"
|
|
626
|
+
});
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
async applyManagedCommit(scope, args, helpers) {
|
|
630
|
+
return this.#withConnection(async (database) => {
|
|
631
|
+
const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
|
|
632
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
633
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
634
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
635
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
636
|
+
const upserts = args.upserts ?? [];
|
|
637
|
+
const removes = [...new Set(args.removes ?? [])];
|
|
638
|
+
const conditionalRemoves = args.conditionalRemoves ?? [];
|
|
639
|
+
const touches = args.touches ?? [];
|
|
640
|
+
const scopeId = createScopeId(scope.sessionKey, scope.storeName, scope.kind);
|
|
641
|
+
const uniqueKeys = [...new Set([
|
|
642
|
+
...removes,
|
|
643
|
+
...conditionalRemoves.map((remove) => remove.key),
|
|
644
|
+
...touches.map((touch) => touch.key),
|
|
645
|
+
...upserts.map((upsert) => upsert.key)
|
|
646
|
+
])];
|
|
647
|
+
const existingEntries = /* @__PURE__ */ new Map();
|
|
648
|
+
const now = Date.now();
|
|
649
|
+
const touchTimestamps = new Map(touches.map((touch) => [touch.key, touch.lastAccessAt ?? now]));
|
|
650
|
+
const rawScopeRecord = await openRequestAsPromise(watch, policyStore.get(createScopePolicyKey(scope)));
|
|
651
|
+
const existingStaticPolicy = isValidNamespacePolicyRecord(rawScopeRecord) ? getStaticPolicyFromScopeRecord(toNamespacePolicyRecordValue(rawScopeRecord)) : null;
|
|
652
|
+
await Promise.all(uniqueKeys.map(async (key) => {
|
|
653
|
+
const record = await openRequestAsPromise(watch, entryStore.get(createEntryPrimaryKey(scope, key)));
|
|
654
|
+
if (isValidEntryRecord(record)) existingEntries.set(key, toEntryRecordValue(record));
|
|
655
|
+
}));
|
|
656
|
+
const staleConditionalRemoveKeys = /* @__PURE__ */ new Set();
|
|
657
|
+
for (const remove of conditionalRemoves) {
|
|
658
|
+
const existing = existingEntries.get(remove.key);
|
|
659
|
+
if (existing === void 0) continue;
|
|
660
|
+
if (matchesConditionalRemove(remove, existing.a, existing.z, existing.v ?? 1, existing.o === 1)) removes.push(remove.key);
|
|
661
|
+
else staleConditionalRemoveKeys.add(remove.key);
|
|
662
|
+
}
|
|
663
|
+
for (const key of removes) entryStore.delete(createEntryPrimaryKey(scope, key)).onsuccess = watch.progressed;
|
|
664
|
+
const upsertKeySet = new Set(upserts.map((upsert) => upsert.key));
|
|
665
|
+
for (const upsert of upserts) {
|
|
666
|
+
const existing = existingEntries.get(upsert.key);
|
|
667
|
+
const customMetadata = helpers.mergeOfflineProtectionMetadata(upsert.key, upsert.metadata, existing === void 0 ? void 0 : getCustomMetadataFromEntryRecord(existing));
|
|
668
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(customMetadata);
|
|
669
|
+
const nextLastAccessAt = touchTimestamps.get(upsert.key) ?? existing?.a ?? now;
|
|
670
|
+
const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
|
|
671
|
+
customMetadata,
|
|
672
|
+
lastAccessAt: nextLastAccessAt,
|
|
673
|
+
serializedValue: upsert.serializedValue,
|
|
674
|
+
value: upsert.value,
|
|
675
|
+
version: upsert.version
|
|
676
|
+
}) : void 0;
|
|
677
|
+
const compactValue = compactEntryValue(scope, upsert.value);
|
|
678
|
+
await openRequestAsPromise(watch, entryStore.put({
|
|
679
|
+
a: nextLastAccessAt,
|
|
680
|
+
...compactValue,
|
|
681
|
+
...group !== void 0 ? { g: group } : {},
|
|
682
|
+
i: scopeId,
|
|
683
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
684
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
685
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
686
|
+
...upsert.version !== 1 ? { v: upsert.version } : {},
|
|
687
|
+
...sizeBytes !== void 0 ? { z: sizeBytes } : {}
|
|
688
|
+
}, createEntryPrimaryKey(scope, upsert.key)));
|
|
689
|
+
}
|
|
690
|
+
for (const touch of touches) {
|
|
691
|
+
if (upsertKeySet.has(touch.key)) continue;
|
|
692
|
+
const existing = existingEntries.get(touch.key);
|
|
693
|
+
if (existing === void 0) continue;
|
|
694
|
+
const nextLastAccessAt = touch.lastAccessAt ?? now;
|
|
695
|
+
if (existing.a === nextLastAccessAt) continue;
|
|
696
|
+
await openRequestAsPromise(watch, entryStore.put({
|
|
697
|
+
...existing,
|
|
698
|
+
a: nextLastAccessAt
|
|
699
|
+
}, createEntryPrimaryKey(scope, touch.key)));
|
|
700
|
+
}
|
|
701
|
+
const normalizedStaticPolicy = "staticPolicy" in args ? normalizeStaticPolicy(args.staticPolicy) : void 0;
|
|
702
|
+
if (await openRequestAsPromise(watch, entryStore.count(createScopeKeyRange(scope))) === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
703
|
+
else await openRequestAsPromise(watch, policyStore.put({
|
|
704
|
+
p: serializeIndexedDbPersistedStaticPolicy(normalizedStaticPolicy === void 0 ? existingStaticPolicy : normalizedStaticPolicy),
|
|
705
|
+
s: scope.sessionKey
|
|
706
|
+
}, createScopePolicyKey(scope)));
|
|
707
|
+
await transactionDone(transaction, watch);
|
|
708
|
+
if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-records", startTime, {
|
|
709
|
+
objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
|
|
710
|
+
removes: removes.length,
|
|
711
|
+
touches: touches.length,
|
|
712
|
+
upserts: upserts.length
|
|
713
|
+
});
|
|
714
|
+
this.#instrumentation?.onApplyManagedCommit?.(scope, args);
|
|
715
|
+
this.#instrumentation?.record({
|
|
716
|
+
removes,
|
|
717
|
+
scope,
|
|
718
|
+
staticPolicyChanged: "staticPolicy" in args,
|
|
719
|
+
time: Date.now(),
|
|
720
|
+
touches: touches.map((touch) => touch.key).sort((left, right) => left.localeCompare(right)),
|
|
721
|
+
type: "applyManagedCommit",
|
|
722
|
+
upserts: upserts.map((upsert) => upsert.key).sort((left, right) => left.localeCompare(right))
|
|
723
|
+
});
|
|
724
|
+
return staleConditionalRemoveKeys;
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
async readNamespaceIndexState(scope, knownRecordKeys_) {
|
|
728
|
+
return this.#withConnection(async (database) => {
|
|
729
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
730
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
731
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
732
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
733
|
+
const entries = /* @__PURE__ */ new Map();
|
|
734
|
+
let invalidEntryCount = 0;
|
|
735
|
+
const [rawPolicy] = await Promise.all([openRequestAsPromise(watch, policyStore.get(createScopePolicyKey(scope))), iterateCursor(watch, entryStore.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
736
|
+
const record = cursor.value;
|
|
737
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
738
|
+
if (!isValidEntryRecord(record)) {
|
|
739
|
+
invalidEntryCount += 1;
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (entryKey === null) {
|
|
743
|
+
invalidEntryCount += 1;
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
entries.set(entryKey, toMetadataRecord(toEntryRecordValue(record)));
|
|
747
|
+
})]);
|
|
748
|
+
await transactionDone(transaction, watch);
|
|
749
|
+
if (invalidEntryCount > 0) {
|
|
750
|
+
const result = {
|
|
751
|
+
entries: null,
|
|
752
|
+
exists: entries.size > 0 || rawPolicy !== void 0,
|
|
753
|
+
staticPolicy: null,
|
|
754
|
+
valid: false
|
|
755
|
+
};
|
|
756
|
+
this.#instrumentation?.record({
|
|
757
|
+
exists: result.exists,
|
|
758
|
+
keyCount: entries.size,
|
|
759
|
+
scope,
|
|
760
|
+
time: Date.now(),
|
|
761
|
+
type: "readManagedIndexState",
|
|
762
|
+
valid: result.valid
|
|
763
|
+
});
|
|
764
|
+
return result;
|
|
765
|
+
}
|
|
766
|
+
if (rawPolicy !== void 0 && !isValidNamespacePolicyRecord(rawPolicy)) {
|
|
767
|
+
const result = {
|
|
768
|
+
entries: null,
|
|
769
|
+
exists: true,
|
|
770
|
+
staticPolicy: null,
|
|
771
|
+
valid: false
|
|
772
|
+
};
|
|
773
|
+
this.#instrumentation?.record({
|
|
774
|
+
exists: result.exists,
|
|
775
|
+
keyCount: entries.size,
|
|
776
|
+
scope,
|
|
777
|
+
time: Date.now(),
|
|
778
|
+
type: "readManagedIndexState",
|
|
779
|
+
valid: result.valid
|
|
780
|
+
});
|
|
781
|
+
return result;
|
|
782
|
+
}
|
|
783
|
+
const exists = rawPolicy !== void 0 || entries.size > 0;
|
|
784
|
+
if (rawPolicy === void 0 && entries.size > 0 || rawPolicy !== void 0 && entries.size === 0) {
|
|
785
|
+
const result = {
|
|
786
|
+
entries: null,
|
|
787
|
+
exists,
|
|
788
|
+
staticPolicy: null,
|
|
789
|
+
valid: false
|
|
790
|
+
};
|
|
791
|
+
this.#instrumentation?.record({
|
|
792
|
+
exists: result.exists,
|
|
793
|
+
keyCount: entries.size,
|
|
794
|
+
scope,
|
|
795
|
+
time: Date.now(),
|
|
796
|
+
type: "readManagedIndexState",
|
|
797
|
+
valid: result.valid
|
|
798
|
+
});
|
|
799
|
+
return result;
|
|
800
|
+
}
|
|
801
|
+
const result = {
|
|
802
|
+
entries,
|
|
803
|
+
exists: rawPolicy !== void 0,
|
|
804
|
+
staticPolicy: getStaticPolicyFromScopeRecord(rawPolicy === void 0 ? void 0 : toNamespacePolicyRecordValue(rawPolicy)),
|
|
805
|
+
valid: true
|
|
806
|
+
};
|
|
807
|
+
this.#instrumentation?.record({
|
|
808
|
+
exists: result.exists,
|
|
809
|
+
keyCount: result.entries.size,
|
|
810
|
+
scope,
|
|
811
|
+
time: Date.now(),
|
|
812
|
+
type: "readManagedIndexState",
|
|
813
|
+
valid: result.valid
|
|
814
|
+
});
|
|
815
|
+
return result;
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
async persistNamespaceIndexState(scope, state) {
|
|
819
|
+
return this.#withConnection(async (database) => {
|
|
820
|
+
const existingEntries = /* @__PURE__ */ new Map();
|
|
821
|
+
const readTransaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
822
|
+
const readWatch = new IndexedDbStallWatch(database.name, readTransaction);
|
|
823
|
+
const readStore = readTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
824
|
+
const desiredKeys = [...state.entries.keys()];
|
|
825
|
+
await Promise.all(desiredKeys.map(async (key) => {
|
|
826
|
+
const existing = await openRequestAsPromise(readWatch, readStore.get(createEntryPrimaryKey(scope, key)));
|
|
827
|
+
if (isValidEntryRecord(existing)) existingEntries.set(key, toEntryRecordValue(existing));
|
|
828
|
+
}));
|
|
829
|
+
await transactionDone(readTransaction, readWatch);
|
|
830
|
+
const writeTransaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
831
|
+
const writeWatch = new IndexedDbStallWatch(database.name, writeTransaction);
|
|
832
|
+
const entryStore = writeTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
833
|
+
const policyStore = writeTransaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
834
|
+
for (const [key, metadata] of state.entries.entries()) {
|
|
835
|
+
const existing = existingEntries.get(key);
|
|
836
|
+
if (existing === void 0) continue;
|
|
837
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(metadata.customMetadata);
|
|
838
|
+
entryStore.put({
|
|
839
|
+
...existing,
|
|
840
|
+
a: metadata.lastAccessAt,
|
|
841
|
+
...group !== void 0 ? { g: group } : {},
|
|
842
|
+
...group === void 0 ? { g: void 0 } : {},
|
|
843
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
844
|
+
...extraMetadata === void 0 ? { m: void 0 } : {},
|
|
845
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
846
|
+
...offlineProtected !== true ? { o: void 0 } : {},
|
|
847
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
848
|
+
...payload === void 0 ? { p: void 0 } : {},
|
|
849
|
+
...metadata.version !== 1 ? { v: metadata.version } : {},
|
|
850
|
+
...metadata.version === 1 ? { v: void 0 } : {},
|
|
851
|
+
...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
|
|
852
|
+
...metadata.sizeBytes === void 0 ? { z: void 0 } : {}
|
|
853
|
+
}, createEntryPrimaryKey(scope, key)).onsuccess = writeWatch.progressed;
|
|
854
|
+
}
|
|
855
|
+
if (state.entries.size === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
856
|
+
else policyStore.put({
|
|
857
|
+
p: serializeIndexedDbPersistedStaticPolicy(state.staticPolicy),
|
|
858
|
+
s: scope.sessionKey
|
|
859
|
+
}, createScopePolicyKey(scope));
|
|
860
|
+
await transactionDone(writeTransaction, writeWatch);
|
|
861
|
+
this.#instrumentation?.onPersistNamespaceIndexState?.(scope, state);
|
|
862
|
+
this.#instrumentation?.record({
|
|
863
|
+
keyCount: state.entries.size,
|
|
864
|
+
scope,
|
|
865
|
+
staticPolicy: state.staticPolicy,
|
|
866
|
+
time: Date.now(),
|
|
867
|
+
type: "persistManagedIndexState"
|
|
868
|
+
});
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
async readProtectedStorageKeys(sessionKey) {
|
|
872
|
+
return this.#withConnection(async (database) => {
|
|
873
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
874
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
875
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
876
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
877
|
+
const values = [];
|
|
878
|
+
await iterateCursor(watch, policyStore.index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
|
|
879
|
+
const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
|
|
880
|
+
if (scope === null) return;
|
|
881
|
+
await iterateCursor(watch, entryStore.index("byScopeOfflineProtected").openCursor(createScopeOfflineProtectedRange(scope)), (entryCursor) => {
|
|
882
|
+
const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
|
|
883
|
+
const record = entryCursor.value;
|
|
884
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
885
|
+
values.push(serializeProtectedRef({
|
|
886
|
+
...scope,
|
|
887
|
+
key: entryKey
|
|
888
|
+
}));
|
|
889
|
+
});
|
|
890
|
+
});
|
|
891
|
+
await transactionDone(transaction, watch);
|
|
892
|
+
this.#instrumentation?.record({
|
|
893
|
+
sessionKey,
|
|
894
|
+
time: Date.now(),
|
|
895
|
+
type: "readProtectedStorageKeys",
|
|
896
|
+
values: [...values].sort((left, right) => left.localeCompare(right))
|
|
897
|
+
});
|
|
898
|
+
return values;
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
async syncSessionProtectedKeys(sessionKey, protectedKeys) {
|
|
902
|
+
return this.#withConnection(async (database) => {
|
|
903
|
+
const nextProtectedKeys = new Set(protectedKeys);
|
|
904
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
905
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
906
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
907
|
+
await iterateCursor(watch, transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
|
|
908
|
+
const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
|
|
909
|
+
if (scope === null) return;
|
|
910
|
+
await iterateCursor(watch, store.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
911
|
+
const record = cursor.value;
|
|
912
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
913
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
914
|
+
const entryRecord = toEntryRecordValue(record);
|
|
915
|
+
const ref = serializeProtectedRef({
|
|
916
|
+
...scope,
|
|
917
|
+
key: entryKey
|
|
918
|
+
});
|
|
919
|
+
const shouldProtect = nextProtectedKeys.has(ref);
|
|
920
|
+
if (entryRecord.o === 1 === shouldProtect) return;
|
|
921
|
+
const nextRecord = {
|
|
922
|
+
...entryRecord,
|
|
923
|
+
...shouldProtect ? { o: 1 } : { o: void 0 }
|
|
924
|
+
};
|
|
925
|
+
cursor.update(nextRecord);
|
|
926
|
+
});
|
|
927
|
+
});
|
|
928
|
+
await transactionDone(transaction, watch);
|
|
929
|
+
this.#instrumentation?.record({
|
|
930
|
+
sessionKey,
|
|
931
|
+
time: Date.now(),
|
|
932
|
+
type: "syncSessionProtectedKeys",
|
|
933
|
+
values: [...nextProtectedKeys].sort((left, right) => left.localeCompare(right))
|
|
934
|
+
});
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
async __resetForTests() {
|
|
938
|
+
if (this.#database !== null) this.#dropDatabase(this.#database);
|
|
939
|
+
await deleteDatabase(this.databaseName);
|
|
940
|
+
this.#instrumentation?.reset();
|
|
941
|
+
}
|
|
942
|
+
async __inspectStructureForTests() {
|
|
943
|
+
const database = await this.#getDatabase();
|
|
944
|
+
const stores = [];
|
|
945
|
+
for (const storeName of [...database.objectStoreNames].sort((left, right) => left.localeCompare(right))) {
|
|
946
|
+
const transaction = database.transaction(storeName, "readonly");
|
|
947
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
948
|
+
const store = transaction.objectStore(storeName);
|
|
949
|
+
const indexes = [...store.indexNames].sort((left, right) => left.localeCompare(right)).map((indexName) => {
|
|
950
|
+
const index = store.index(indexName);
|
|
951
|
+
return {
|
|
952
|
+
keyPath: index.keyPath,
|
|
953
|
+
multiEntry: index.multiEntry,
|
|
954
|
+
name: index.name,
|
|
955
|
+
unique: index.unique
|
|
956
|
+
};
|
|
957
|
+
});
|
|
958
|
+
const [keys, values] = await Promise.all([openRequestAsPromise(watch, store.getAllKeys()), openRequestAsPromise(watch, store.getAll())]);
|
|
959
|
+
await transactionDone(transaction, watch);
|
|
960
|
+
stores.push({
|
|
961
|
+
autoIncrement: store.autoIncrement,
|
|
962
|
+
indexes,
|
|
963
|
+
keyPath: store.keyPath,
|
|
964
|
+
name: storeName,
|
|
965
|
+
rows: keys.map((key, index) => ({
|
|
966
|
+
key,
|
|
967
|
+
value: values[index]
|
|
968
|
+
}))
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return {
|
|
972
|
+
stores,
|
|
973
|
+
version: database.version
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
async #getEntry(scope, key) {
|
|
977
|
+
return this.#withConnection(async (database) => {
|
|
978
|
+
const transaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
979
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
980
|
+
const record = await openRequestAsPromise(watch, transaction.objectStore(INDEXED_DB_ENTRY_STORE).get(createEntryPrimaryKey(scope, key)));
|
|
981
|
+
await transactionDone(transaction, watch);
|
|
982
|
+
return isValidEntryRecord(record) ? toEntryRecordValue(record) : null;
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
async #putEntryRecord(scope, args) {
|
|
986
|
+
return this.#withConnection(async (database) => {
|
|
987
|
+
const transaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
988
|
+
const watch = new IndexedDbStallWatch(database.name, transaction);
|
|
989
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
990
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
991
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(args.customMetadata);
|
|
992
|
+
const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
|
|
993
|
+
customMetadata: args.customMetadata,
|
|
994
|
+
lastAccessAt: args.lastAccessAt,
|
|
995
|
+
value: args.value,
|
|
996
|
+
version: args.version
|
|
997
|
+
}) : void 0;
|
|
998
|
+
const compactValue = compactEntryValue(scope, args.value);
|
|
999
|
+
entryStore.put({
|
|
1000
|
+
a: args.lastAccessAt,
|
|
1001
|
+
...compactValue,
|
|
1002
|
+
...group !== void 0 ? { g: group } : {},
|
|
1003
|
+
i: createScopeId(scope.sessionKey, scope.storeName, scope.kind),
|
|
1004
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
1005
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
1006
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
1007
|
+
...args.version !== 1 ? { v: args.version } : {},
|
|
1008
|
+
...sizeBytes !== void 0 ? { z: sizeBytes } : {}
|
|
1009
|
+
}, createEntryPrimaryKey(scope, args.key));
|
|
1010
|
+
const policyRequest = policyStore.get(createScopePolicyKey(scope));
|
|
1011
|
+
policyRequest.onsuccess = () => {
|
|
1012
|
+
watch.progressed();
|
|
1013
|
+
const existingScopeRecord = policyRequest.result;
|
|
1014
|
+
policyStore.put({
|
|
1015
|
+
p: serializeIndexedDbPersistedStaticPolicy(getStaticPolicyFromScopeRecord(isValidNamespacePolicyRecord(existingScopeRecord) ? toNamespacePolicyRecordValue(existingScopeRecord) : void 0)),
|
|
1016
|
+
s: scope.sessionKey
|
|
1017
|
+
}, createScopePolicyKey(scope));
|
|
1018
|
+
};
|
|
1019
|
+
await transactionDone(transaction, watch);
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
#parsePersistedIndexState(value) {
|
|
1023
|
+
if (!isObject(value)) return null;
|
|
1024
|
+
const recordValue = toRecordValue(value);
|
|
1025
|
+
const rawEntries = recordValue.e;
|
|
1026
|
+
if (!isObject(rawEntries)) return null;
|
|
1027
|
+
const rawEntriesRecord = toRecordValue(rawEntries);
|
|
1028
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1029
|
+
for (const [key, rawMetadata] of Object.entries(rawEntriesRecord)) {
|
|
1030
|
+
if (!isObject(rawMetadata)) return null;
|
|
1031
|
+
const rawMetadataRecord = toRecordValue(rawMetadata);
|
|
1032
|
+
if (typeof rawMetadataRecord.a !== "number") return null;
|
|
1033
|
+
const customMetadata = Object.fromEntries(Object.entries(rawMetadataRecord).filter(([metadataKey]) => metadataKey !== "a" && metadataKey !== "v" && metadataKey !== "z"));
|
|
1034
|
+
entries.set(key, {
|
|
1035
|
+
...Object.keys(customMetadata).length > 0 ? { customMetadata } : {},
|
|
1036
|
+
lastAccessAt: rawMetadataRecord.a,
|
|
1037
|
+
...typeof rawMetadataRecord.z === "number" ? { sizeBytes: rawMetadataRecord.z } : {},
|
|
1038
|
+
version: typeof rawMetadataRecord.v === "number" ? rawMetadataRecord.v : 1
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
const staticPolicy = parseIndexedDbPersistedStaticPolicy(recordValue.s);
|
|
1042
|
+
if (staticPolicy === void 0) return null;
|
|
1043
|
+
return {
|
|
1044
|
+
entries,
|
|
1045
|
+
staticPolicy
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
async #getDatabase() {
|
|
1049
|
+
if (this.#databasePromise !== null) return this.#databasePromise;
|
|
1050
|
+
const opening = new Promise((resolve, reject) => {
|
|
1051
|
+
const request = indexedDB.open(this.databaseName, INDEXED_DB_VERSION);
|
|
1052
|
+
const watch = new IndexedDbStallWatch(this.databaseName, null);
|
|
1053
|
+
watch.rejecters.push(reject);
|
|
1054
|
+
request.onupgradeneeded = () => {
|
|
1055
|
+
watch.progressed();
|
|
1056
|
+
const database = request.result;
|
|
1057
|
+
if (database.objectStoreNames.contains(INDEXED_DB_ENTRY_STORE)) database.deleteObjectStore(INDEXED_DB_ENTRY_STORE);
|
|
1058
|
+
if (database.objectStoreNames.contains(INDEXED_DB_NAMESPACE_POLICY_STORE)) database.deleteObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
1059
|
+
const entryStore = database.createObjectStore(INDEXED_DB_ENTRY_STORE);
|
|
1060
|
+
entryStore.createIndex("byScopeLastAccessAt", ["i", "a"], { unique: false });
|
|
1061
|
+
entryStore.createIndex("byScopeGroup", ["i", "g"], { unique: false });
|
|
1062
|
+
entryStore.createIndex("byScopeOfflineProtected", ["i", "o"], { unique: false });
|
|
1063
|
+
database.createObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).createIndex("bySession", "s", { unique: false });
|
|
1064
|
+
if (!database.objectStoreNames.contains(INDEXED_DB_META_STORE)) database.createObjectStore(INDEXED_DB_META_STORE, { keyPath: "k" });
|
|
1065
|
+
};
|
|
1066
|
+
request.onerror = () => {
|
|
1067
|
+
watch.stop();
|
|
1068
|
+
reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB open failed."));
|
|
1069
|
+
};
|
|
1070
|
+
request.onsuccess = () => {
|
|
1071
|
+
watch.stop();
|
|
1072
|
+
const database = request.result;
|
|
1073
|
+
if (this.#databasePromise !== opening) {
|
|
1074
|
+
database.close();
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
database.onclose = () => this.#dropDatabase(database);
|
|
1078
|
+
database.onversionchange = () => this.#dropDatabase(database);
|
|
1079
|
+
this.#database = database;
|
|
1080
|
+
resolve(database);
|
|
1081
|
+
};
|
|
1082
|
+
});
|
|
1083
|
+
this.#databasePromise = opening;
|
|
1084
|
+
opening.catch(() => {
|
|
1085
|
+
if (this.#databasePromise === opening) this.#databasePromise = null;
|
|
1086
|
+
});
|
|
1087
|
+
return opening;
|
|
1088
|
+
}
|
|
1089
|
+
#dropDatabase(database) {
|
|
1090
|
+
if (this.#database === database) {
|
|
1091
|
+
this.#database = null;
|
|
1092
|
+
this.#databasePromise = null;
|
|
1093
|
+
}
|
|
1094
|
+
database.close();
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Runs an operation and, when the connection fails under it, runs it once
|
|
1098
|
+
* more on a new connection.
|
|
1099
|
+
*
|
|
1100
|
+
* Every operation of this driver is safe to repeat: each one is a single
|
|
1101
|
+
* atomic transaction (or a sequence of them) that reads what it needs inside
|
|
1102
|
+
* the transaction and writes whole values, deletes, or flags derived from
|
|
1103
|
+
* its arguments, so applying it after an attempt that did or did not commit
|
|
1104
|
+
* leaves the same data. Quota, data and version errors are not connection
|
|
1105
|
+
* errors and are never retried.
|
|
1106
|
+
*/
|
|
1107
|
+
async #withConnection(run, isRetry = false) {
|
|
1108
|
+
let database;
|
|
1109
|
+
try {
|
|
1110
|
+
database = await this.#getDatabase();
|
|
1111
|
+
return await run(database);
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
if (!isIndexedDbConnectionError(error)) throw error;
|
|
1114
|
+
if (database !== void 0) this.#dropDatabase(database);
|
|
1115
|
+
if (isRetry) throw error;
|
|
1116
|
+
return this.#withConnection(run, true);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
#logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
|
|
1120
|
+
if (!import.meta.env.DEV) return;
|
|
1121
|
+
if (startTime === null) return;
|
|
1122
|
+
if (!this.debugLogger) return;
|
|
1123
|
+
const status = typeof details.status === "string" ? details.status : "success";
|
|
1124
|
+
emitTSDFDebugLog(this.debugLogger, {
|
|
1125
|
+
area: "persistent-storage",
|
|
1126
|
+
level: "log",
|
|
1127
|
+
message: `persistent storage adapter ${adapterOperation} ${status}`,
|
|
1128
|
+
operation: "adapter-operation",
|
|
1129
|
+
details: {
|
|
1130
|
+
adapter: "async",
|
|
1131
|
+
adapterName: "indexeddb",
|
|
1132
|
+
adapterOperation,
|
|
1133
|
+
databaseName: this.databaseName,
|
|
1134
|
+
durationMs: getTSDFDebugTimingMs() - startTime,
|
|
1135
|
+
status,
|
|
1136
|
+
...scope !== void 0 ? {
|
|
1137
|
+
namespaceKind: scope.kind,
|
|
1138
|
+
sessionKey: scope.sessionKey,
|
|
1139
|
+
storeName: scope.storeName
|
|
1140
|
+
} : {},
|
|
1141
|
+
...details
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
function createIndexedDbPersistentStorage$1(options = {}) {
|
|
1147
|
+
return createAsyncStorageAdapter(new IndexedDbAsyncStorageDriver(options.databaseName));
|
|
1148
|
+
}
|
|
1149
|
+
//#endregion
|
|
1150
|
+
//#region src/persistentStorage/indexedDbPersistentStorage.ts
|
|
1151
|
+
const indexedDbPersistentStorage = /* @__PURE__ */ createIndexedDbPersistentStorage$1();
|
|
1152
|
+
function createIndexedDbPersistentStorage(options = {}) {
|
|
1153
|
+
return createIndexedDbPersistentStorage$1(options);
|
|
1154
|
+
}
|
|
1155
|
+
//#endregion
|
|
1156
|
+
export { indexedDbPersistentStorage as n, createIndexedDbPersistentStorage as t };
|