@ngx-pwa/local-storage 22.0.0 → 22.0.1

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.
@@ -1,1386 +1,665 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken, makeEnvironmentProviders, NgModule, inject, Service, assertInInjectionContext, PLATFORM_ID, Injectable } from '@angular/core';
3
- import { of, throwError, Observable, asyncScheduler, from, ReplaySubject, fromEvent, race } from 'rxjs';
4
- import { observeOn, mergeMap, map, first, takeWhile, tap, catchError } from 'rxjs/operators';
5
- import { isPlatformBrowser } from '@angular/common';
6
-
7
- /**
8
- * Exception message when `indexedDB` is not working
9
- */
1
+ import * as i0 from "@angular/core";
2
+ import { Injectable, InjectionToken, NgModule, PLATFORM_ID, Service, assertInInjectionContext, inject, makeEnvironmentProviders } from "@angular/core";
3
+ import { Observable, ReplaySubject, asyncScheduler, from, fromEvent, of, race, throwError } from "rxjs";
4
+ import { catchError, first, map, mergeMap, observeOn, takeWhile, tap } from "rxjs/operators";
5
+ import { isPlatformBrowser } from "@angular/common";
10
6
  const IDB_BROKEN_ERROR = "indexedDB is not working";
11
- /**
12
- * Exception raised when `indexedDB` is not working
13
- */
14
- class IDBBrokenError extends Error {
15
- message = IDB_BROKEN_ERROR;
16
- }
17
- /**
18
- * Exception message when a value cannot be serialized for `localStorage`
19
- */
7
+ var IDBBrokenError = class extends Error {
8
+ message = IDB_BROKEN_ERROR;
9
+ };
20
10
  const SERIALIZATION_ERROR = `The storage is currently localStorage,
21
11
  where data must be serialized, and the provided data can't be serialized.`;
22
- /**
23
- * Exception throwned when a value cannot be serialized for `localStorage`
24
- */
25
- class SerializationError extends Error {
26
- message = SERIALIZATION_ERROR;
27
- }
28
-
29
- /**
30
- * Token to provide a prefix to `localStorage` keys.
31
- */
12
+ var SerializationError = class extends Error {
13
+ message = SERIALIZATION_ERROR;
14
+ };
32
15
  const LS_PREFIX = new InjectionToken("localStoragePrefix", {
33
- providedIn: "root",
34
- factory: () => ""
16
+ providedIn: "root",
17
+ factory: () => ""
35
18
  });
36
- /**
37
- * Default name used for `indexedDB` database.
38
- */
39
19
  const DEFAULT_IDB_DB_NAME = "ngStorage";
40
- /**
41
- * Token to provide `indexedDB` database name.
42
- */
43
20
  const IDB_DB_NAME = new InjectionToken("localStorageIDBDBName", {
44
- providedIn: "root",
45
- factory: () => DEFAULT_IDB_DB_NAME
21
+ providedIn: "root",
22
+ factory: () => DEFAULT_IDB_DB_NAME
46
23
  });
47
- /**
48
- * Default version used for `indexedDB` database.
49
- */
50
- const DEFAULT_IDB_DB_VERSION = 1;
51
- /**
52
- * Token to provide `indexedDB` database version.
53
- * Must be an unsigned **integer**.
54
- */
55
24
  const IDB_DB_VERSION = new InjectionToken("localStorageIDBDBVersion", {
56
- providedIn: "root",
57
- factory: () => DEFAULT_IDB_DB_VERSION
25
+ providedIn: "root",
26
+ factory: () => 1
58
27
  });
59
- /**
60
- * Default name used for `indexedDB` object store.
61
- */
62
28
  const DEFAULT_IDB_STORE_NAME = "localStorage";
63
- /**
64
- * Token to provide `indexedDB` store name.
65
- * For backward compatibility, the default can't be set now, `IndexedDBDatabase` will do it at runtime.
66
- */
67
29
  const IDB_STORE_NAME = new InjectionToken("localStorageIDBStoreName", {
68
- providedIn: "root",
69
- factory: () => DEFAULT_IDB_STORE_NAME
30
+ providedIn: "root",
31
+ factory: () => DEFAULT_IDB_STORE_NAME
70
32
  });
71
- /**
72
- * Default value for interoperability with native `indexedDB` and other storage libs,
73
- * by changing how values are stored in `indexedDB` database.
74
- */
75
- const DEFAULT_IDB_NO_WRAP = true;
76
- /**
77
- * Token to allow interoperability with native `indexedDB` and other storage libs,
78
- * by changing how values are stored in `indexedDB` database.
79
- * Defaults to `true`. Change to `false` for backward compatiblity in existing applications.
80
- * **DO NOT CHANGE THIS BEHAVIOR ONCE IN PRODUCTION**, as it would break with existing data.
81
- */
82
33
  const IDB_NO_WRAP = new InjectionToken("localStorageIDBWrap", {
83
- providedIn: "root",
84
- factory: () => DEFAULT_IDB_NO_WRAP
34
+ providedIn: "root",
35
+ factory: () => true
85
36
  });
86
-
87
- /**
88
- * Allows to add a prefix before `localStorage` keys.
89
- *
90
- * *Use only* for interoperability with other APIs or to avoid collision for multiple applications on the same subdomain.
91
- *
92
- * **WARNING: do not change this option in an application already deployed in production, as previously stored data would be lost.**
93
- *
94
- * @example
95
- * export const appConfig: ApplicationConfig = {
96
- * providers: [provideLocalStoragePrefix('custom_')]
97
- * };
98
- */
99
37
  function provideLocalStoragePrefix(prefix) {
100
- return makeEnvironmentProviders([{ provide: LS_PREFIX, useValue: prefix }]);
38
+ return makeEnvironmentProviders([{
39
+ provide: LS_PREFIX,
40
+ useValue: prefix
41
+ }]);
101
42
  }
102
- /**
103
- * Allows to change the name used for `indexedDB` database.
104
- *
105
- * *Use only* for interoperability with other APIs or to avoid collision for multiple applications on the same subdomain.
106
- *
107
- * **WARNING: do not change this option in an application already deployed in production, as previously stored data would be lost.**
108
- *
109
- * @example
110
- * export const appConfig: ApplicationConfig = {
111
- * providers: [provideIndexedDBDataBaseName('custom')]
112
- * };
113
- */
114
43
  function provideIndexedDBDataBaseName(name) {
115
- return makeEnvironmentProviders([{ provide: IDB_DB_NAME, useValue: name }]);
44
+ return makeEnvironmentProviders([{
45
+ provide: IDB_DB_NAME,
46
+ useValue: name
47
+ }]);
116
48
  }
117
- /**
118
- * Allows to change the database version used for `indexedDB` database.
119
- * Must be an unsigned **integer**.
120
- *
121
- * **Use with caution as the creation of the store depends on the version.**
122
- *
123
- * *Use only* for interoperability with other APIs or to avoid collision for multiple applications on the same subdomain.
124
- *
125
- * **WARNING: do not change this option in an applicattion already deployed in production, as previously stored data would be lost.**
126
- *
127
- * @example
128
- * export const appConfig: ApplicationConfig = {
129
- * providers: [provideIndexedDBDataBaseVersion(2)]
130
- * };
131
- */
132
49
  function provideIndexedDBDataBaseVersion(version) {
133
- return makeEnvironmentProviders([{ provide: IDB_DB_VERSION, useValue: version }]);
50
+ return makeEnvironmentProviders([{
51
+ provide: IDB_DB_VERSION,
52
+ useValue: version
53
+ }]);
134
54
  }
135
- /**
136
- * Allows to change the name used for `indexedDB` object store.
137
- *
138
- * *Use only* for interoperability with other APIs.
139
- *
140
- * **WARNING: do not change this option in an application already deployed in production, as previously stored data would be lost.**
141
- *
142
- * @example
143
- * export const appConfig: ApplicationConfig = {
144
- * providers: [provideIndexedDBStoreName('custom')]
145
- * };
146
- */
147
55
  function provideIndexedDBStoreName(name) {
148
- return makeEnvironmentProviders([{ provide: IDB_STORE_NAME, useValue: name }]);
149
- }
150
-
151
- /**
152
- * This module is only here for backward compatibility, **do not add it by yourself**
153
- *
154
- * @ignore
155
- */
156
- class StorageModule {
157
- /**
158
- * Only useful to provide options, otherwise it does nothing.
159
- *
160
- * **Must be used at initialization, ie. in `AppModule`, and must not be loaded again in another module.**
161
- */
162
- static forRoot(config) {
163
- return {
164
- ngModule: StorageModule,
165
- providers: [
166
- // eslint-disable-next-line @typescript-eslint/no-deprecated
167
- config.LSPrefix !== undefined ? { provide: LS_PREFIX, useValue: config.LSPrefix } : [],
168
- // eslint-disable-next-line @typescript-eslint/no-deprecated
169
- config.IDBDBName !== undefined ? { provide: IDB_DB_NAME, useValue: config.IDBDBName } : [],
170
- // eslint-disable-next-line @typescript-eslint/no-deprecated
171
- config.IDBStoreName !== undefined ? { provide: IDB_STORE_NAME, useValue: config.IDBStoreName } : [],
172
- // eslint-disable-next-line @typescript-eslint/no-deprecated
173
- config.IDBDBVersion !== undefined ? { provide: IDB_DB_VERSION, useValue: config.IDBDBVersion } : [],
174
- (config.IDBNoWrap === false) ? { provide: IDB_NO_WRAP, useValue: config.IDBNoWrap } : [],
175
- ],
176
- };
177
- }
178
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
179
- static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "22.0.0", ngImport: i0, type: StorageModule });
180
- static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageModule });
56
+ return makeEnvironmentProviders([{
57
+ provide: IDB_STORE_NAME,
58
+ useValue: name
59
+ }]);
181
60
  }
182
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageModule, decorators: [{
183
- type: NgModule
184
- }] });
185
-
186
- /**
187
- * Exception message when a value is not valid against the JSON schema
188
- */
61
+ var StorageModule = class StorageModule {
62
+ static forRoot(config) {
63
+ return {
64
+ ngModule: StorageModule,
65
+ providers: [
66
+ config.LSPrefix !== void 0 ? {
67
+ provide: LS_PREFIX,
68
+ useValue: config.LSPrefix
69
+ } : [],
70
+ config.IDBDBName !== void 0 ? {
71
+ provide: IDB_DB_NAME,
72
+ useValue: config.IDBDBName
73
+ } : [],
74
+ config.IDBStoreName !== void 0 ? {
75
+ provide: IDB_STORE_NAME,
76
+ useValue: config.IDBStoreName
77
+ } : [],
78
+ config.IDBDBVersion !== void 0 ? {
79
+ provide: IDB_DB_VERSION,
80
+ useValue: config.IDBDBVersion
81
+ } : [],
82
+ config.IDBNoWrap === false ? {
83
+ provide: IDB_NO_WRAP,
84
+ useValue: config.IDBNoWrap
85
+ } : []
86
+ ]
87
+ };
88
+ }
89
+ static ɵfac = i0.ɵɵngDeclareFactory({
90
+ minVersion: "12.0.0",
91
+ version: "22.2.3",
92
+ ngImport: i0,
93
+ type: StorageModule,
94
+ deps: [],
95
+ target: i0.ɵɵFactoryTarget.NgModule
96
+ });
97
+ static ɵmod = i0.ɵɵngDeclareNgModule({
98
+ minVersion: "14.0.0",
99
+ version: "22.2.3",
100
+ ngImport: i0,
101
+ type: StorageModule
102
+ });
103
+ static ɵinj = i0.ɵɵngDeclareInjector({
104
+ minVersion: "12.0.0",
105
+ version: "22.2.3",
106
+ ngImport: i0,
107
+ type: StorageModule
108
+ });
109
+ };
110
+ i0.ɵɵngDeclareClassMetadata({
111
+ minVersion: "12.0.0",
112
+ version: "22.2.3",
113
+ ngImport: i0,
114
+ type: StorageModule,
115
+ decorators: [{ type: NgModule }]
116
+ });
189
117
  const VALIDATION_ERROR = `Data stored is not valid against the provided JSON schema.
190
118
  Check your JSON schema, otherwise it means data has been corrupted.`;
191
- /**
192
- * Exception throwned when a value is not valid against the JSON schema
193
- */
194
- class ValidationError extends Error {
195
- message = VALIDATION_ERROR;
196
- }
197
-
198
- class LocalStorageDatabase {
199
- /**
200
- * Optional user prefix to avoid collision for multiple apps on the same subdomain
201
- */
202
- prefix;
203
- constructor() {
204
- /* Prefix if asked, or no prefix otherwise */
205
- this.prefix = inject(LS_PREFIX);
206
- }
207
- /**
208
- * Number of items in `localStorage`
209
- */
210
- get size() {
211
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
212
- return of(localStorage.length);
213
- }
214
- /**
215
- * Gets an item value in `localStorage`
216
- * @param key The item's key
217
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
218
- */
219
- get(key) {
220
- /* Get raw data */
221
- const unparsedData = localStorage.getItem(this.prefixKey(key));
222
- /* No need to parse if data is `null` or `undefined` */
223
- if (unparsedData !== null) {
224
- /* Try to parse */
225
- try {
226
- const parsedData = JSON.parse(unparsedData);
227
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
228
- return of(parsedData);
229
- }
230
- catch (error) {
231
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
232
- return throwError(() => error);
233
- }
234
- }
235
- return of(undefined);
236
- }
237
- /**
238
- * Store an item in `localStorage`
239
- * @param key The item's key
240
- * @param data The item's value
241
- * @returns A RxJS `Observable` to wait the end of the operation
242
- */
243
- set(key, data) {
244
- // eslint-disable-next-line no-useless-assignment
245
- let serializedData = null;
246
- /* Check if data can be serialized */
247
- const dataPrototype = Object.getPrototypeOf(data);
248
- if ((typeof data === "object") && !Array.isArray(data) &&
249
- !((dataPrototype === Object.prototype) || (dataPrototype === null))) {
250
- return throwError(() => new SerializationError());
251
- }
252
- /* Try to stringify (can fail on circular references) */
253
- try {
254
- serializedData = JSON.stringify(data);
255
- if (serializedData === undefined) {
256
- throw new Error();
257
- }
258
- }
259
- catch (error) {
260
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
261
- return throwError(() => error);
262
- }
263
- /* Can fail if storage quota is exceeded */
264
- try {
265
- localStorage.setItem(this.prefixKey(key), serializedData);
266
- }
267
- catch (error) {
268
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
269
- return throwError(() => error);
270
- }
271
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
272
- return of(undefined);
273
- }
274
- /**
275
- * Deletes an item in `localStorage`
276
- * @param key The item's key
277
- * @returns A RxJS `Observable` to wait the end of the operation
278
- */
279
- delete(key) {
280
- localStorage.removeItem(this.prefixKey(key));
281
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
282
- return of(undefined);
283
- }
284
- /**
285
- * Deletes all items in `localStorage`
286
- * @returns A RxJS `Observable` to wait the end of the operation
287
- */
288
- clear() {
289
- localStorage.clear();
290
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
291
- return of(undefined);
292
- }
293
- /**
294
- * Get all keys in `localStorage`
295
- * Note the order of the keys may be inconsistent in Firefox
296
- * @returns A RxJS `Observable` iterating on keys
297
- */
298
- keys() {
299
- /* Create an `Observable` from keys */
300
- return new Observable((subscriber) => {
301
- /* Iteretate over all the indexes */
302
- for (let index = 0; index < localStorage.length; index += 1) {
303
- /* Cast as we are sure in this case the key is not `null` */
304
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Ensured by the logic
305
- subscriber.next(this.getUnprefixedKey(index));
306
- }
307
- subscriber.complete();
308
- }).pipe(
309
- /* Required to work like other databases which are asynchronous */
310
- observeOn(asyncScheduler));
311
- }
312
- /**
313
- * Check if a key exists in `localStorage`
314
- * @param key The item's key
315
- * @returns A RxJS `Observable` telling if the key exists or not
316
- */
317
- has(key) {
318
- /* Itérate over all indexes in storage */
319
- for (let index = 0; index < localStorage.length; index += 1) {
320
- if (key === this.getUnprefixedKey(index)) {
321
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
322
- return of(true);
323
- }
324
- }
325
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
326
- return of(false);
327
- }
328
- /**
329
- * Get an unprefixed key
330
- * @param index Index of the key
331
- * @returns The unprefixed key name if exists, `null` otherwise
332
- */
333
- getUnprefixedKey(index) {
334
- /* Get the key in storage: may have a prefix */
335
- const prefixedKey = localStorage.key(index);
336
- if (prefixedKey !== null) {
337
- /* If no prefix, the key is already good, otherwrite strip the prefix */
338
- return this.prefix === "" ? prefixedKey : prefixedKey.substring(this.prefix.length);
339
- }
340
- return null;
341
- }
342
- /**
343
- * Add the prefix to a key
344
- * @param key The key name
345
- * @returns The prefixed key name
346
- */
347
- prefixKey(key) {
348
- return `${this.prefix}${key}`;
349
- }
350
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: LocalStorageDatabase, deps: [], target: i0.ɵɵFactoryTarget.Service });
351
- static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.0", ngImport: i0, type: LocalStorageDatabase });
352
- }
353
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: LocalStorageDatabase, decorators: [{
354
- type: Service
355
- }], ctorParameters: () => [] });
356
-
357
- class MemoryDatabase {
358
- /**
359
- * Memory storage
360
- */
361
- memoryStorage = new Map();
362
- /**
363
- * Number of items in memory
364
- */
365
- get size() {
366
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
367
- return of(this.memoryStorage.size);
368
- }
369
- /**
370
- * Gets an item value in memory
371
- * @param key The item's key
372
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
373
- */
374
- get(key) {
375
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
376
- return of(this.memoryStorage.get(key));
377
- }
378
- /**
379
- * Sets an item in memory
380
- * @param key The item's key
381
- * @param data The item's value
382
- * @returns A RxJS `Observable` to wait the end of the operation
383
- */
384
- set(key, data) {
385
- this.memoryStorage.set(key, data);
386
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
387
- return of(undefined);
388
- }
389
- /**
390
- * Deletes an item in memory
391
- * @param key The item's key
392
- * @returns A RxJS `Observable` to wait the end of the operation
393
- */
394
- delete(key) {
395
- this.memoryStorage.delete(key);
396
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
397
- return of(undefined);
398
- }
399
- /**
400
- * Deletes all items in memory
401
- * @returns A RxJS `Observable` to wait the end of the operation
402
- */
403
- clear() {
404
- this.memoryStorage.clear();
405
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
406
- return of(undefined);
407
- }
408
- /**
409
- * Get all keys in memory
410
- * @returns A RxJS `Observable` iterating on keys
411
- */
412
- keys() {
413
- /* Create an `Observable` from keys */
414
- return from(this.memoryStorage.keys());
415
- }
416
- /**
417
- * Check if a key exists in memory
418
- * @param key Key name
419
- * @returns a RxJS `Observable` telling if the key exists or not
420
- */
421
- has(key) {
422
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
423
- return of(this.memoryStorage.has(key));
424
- }
425
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: MemoryDatabase, deps: [], target: i0.ɵɵFactoryTarget.Service });
426
- static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.0", ngImport: i0, type: MemoryDatabase });
427
- }
428
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: MemoryDatabase, decorators: [{
429
- type: Service
430
- }] });
431
-
432
- /**
433
- * Factory to create a storage according to browser support
434
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/BROWSERS_SUPPORT.md}
435
- */
119
+ var ValidationError = class extends Error {
120
+ message = VALIDATION_ERROR;
121
+ };
122
+ var LocalStorageDatabase = class LocalStorageDatabase {
123
+ prefix;
124
+ constructor() {
125
+ this.prefix = inject(LS_PREFIX);
126
+ }
127
+ get size() {
128
+ return of(localStorage.length);
129
+ }
130
+ get(key) {
131
+ const unparsedData = localStorage.getItem(this.prefixKey(key));
132
+ if (unparsedData !== null) try {
133
+ const parsedData = JSON.parse(unparsedData);
134
+ return of(parsedData);
135
+ } catch (error) {
136
+ return throwError(() => error);
137
+ }
138
+ return of(void 0);
139
+ }
140
+ set(key, data) {
141
+ let serializedData = null;
142
+ const dataPrototype = Object.getPrototypeOf(data);
143
+ if (typeof data === "object" && !Array.isArray(data) && !(dataPrototype === Object.prototype || dataPrototype === null)) return throwError(() => new SerializationError());
144
+ try {
145
+ serializedData = JSON.stringify(data);
146
+ if (serializedData === void 0) throw new Error();
147
+ } catch (error) {
148
+ return throwError(() => error);
149
+ }
150
+ try {
151
+ localStorage.setItem(this.prefixKey(key), serializedData);
152
+ } catch (error) {
153
+ return throwError(() => error);
154
+ }
155
+ return of(void 0);
156
+ }
157
+ delete(key) {
158
+ localStorage.removeItem(this.prefixKey(key));
159
+ return of(void 0);
160
+ }
161
+ clear() {
162
+ localStorage.clear();
163
+ return of(void 0);
164
+ }
165
+ keys() {
166
+ return new Observable((subscriber) => {
167
+ for (let index = 0; index < localStorage.length; index += 1) subscriber.next(this.getUnprefixedKey(index));
168
+ subscriber.complete();
169
+ }).pipe(observeOn(asyncScheduler));
170
+ }
171
+ has(key) {
172
+ for (let index = 0; index < localStorage.length; index += 1) if (key === this.getUnprefixedKey(index)) return of(true);
173
+ return of(false);
174
+ }
175
+ getUnprefixedKey(index) {
176
+ const prefixedKey = localStorage.key(index);
177
+ if (prefixedKey !== null) return this.prefix === "" ? prefixedKey : prefixedKey.substring(this.prefix.length);
178
+ return null;
179
+ }
180
+ prefixKey(key) {
181
+ return `${this.prefix}${key}`;
182
+ }
183
+ static ɵfac = i0.ɵɵngDeclareFactory({
184
+ minVersion: "12.0.0",
185
+ version: "22.2.3",
186
+ ngImport: i0,
187
+ type: LocalStorageDatabase,
188
+ deps: [],
189
+ target: i0.ɵɵFactoryTarget.Service
190
+ });
191
+ static ɵprov = i0.ɵɵngDeclareService({
192
+ minVersion: "22.0.0",
193
+ version: "22.2.3",
194
+ ngImport: i0,
195
+ type: LocalStorageDatabase
196
+ });
197
+ };
198
+ i0.ɵɵngDeclareClassMetadata({
199
+ minVersion: "12.0.0",
200
+ version: "22.2.3",
201
+ ngImport: i0,
202
+ type: LocalStorageDatabase,
203
+ decorators: [{ type: Service }],
204
+ ctorParameters: () => []
205
+ });
206
+ var MemoryDatabase = class MemoryDatabase {
207
+ memoryStorage = /* @__PURE__ */ new Map();
208
+ get size() {
209
+ return of(this.memoryStorage.size);
210
+ }
211
+ get(key) {
212
+ return of(this.memoryStorage.get(key));
213
+ }
214
+ set(key, data) {
215
+ this.memoryStorage.set(key, data);
216
+ return of(void 0);
217
+ }
218
+ delete(key) {
219
+ this.memoryStorage.delete(key);
220
+ return of(void 0);
221
+ }
222
+ clear() {
223
+ this.memoryStorage.clear();
224
+ return of(void 0);
225
+ }
226
+ keys() {
227
+ return from(this.memoryStorage.keys());
228
+ }
229
+ has(key) {
230
+ return of(this.memoryStorage.has(key));
231
+ }
232
+ static ɵfac = i0.ɵɵngDeclareFactory({
233
+ minVersion: "12.0.0",
234
+ version: "22.2.3",
235
+ ngImport: i0,
236
+ type: MemoryDatabase,
237
+ deps: [],
238
+ target: i0.ɵɵFactoryTarget.Service
239
+ });
240
+ static ɵprov = i0.ɵɵngDeclareService({
241
+ minVersion: "22.0.0",
242
+ version: "22.2.3",
243
+ ngImport: i0,
244
+ type: MemoryDatabase
245
+ });
246
+ };
247
+ i0.ɵɵngDeclareClassMetadata({
248
+ minVersion: "12.0.0",
249
+ version: "22.2.3",
250
+ ngImport: i0,
251
+ type: MemoryDatabase,
252
+ decorators: [{ type: Service }]
253
+ });
436
254
  function localDatabaseFactory() {
437
- assertInInjectionContext(localDatabaseFactory);
438
- const platformId = inject(PLATFORM_ID);
439
- /* When storage is fully disabled in browser (via the "Block all cookies" option),
440
- * just trying to check `indexedDB` or `localStorage` variables causes a security exception.
441
- * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
442
- */
443
- try {
444
- // Do not explicit `window` here, as the global object is not the same in web workers
445
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- They can be undefined in some browsers scenarios
446
- if (isPlatformBrowser(platformId) && (indexedDB !== undefined) && (indexedDB !== null) && ("open" in indexedDB)) {
447
- /* Check:
448
- * - if we are in a browser context (issue: server-side rendering)
449
- * - it could exist but be `undefined` or `null`
450
- * - it could exists but not having a working API
451
- * Will be the case for:
452
- * - All other browsers in normal mode
453
- * - Chromium / Safari / Firefox private mode, but in this case, data will be swiped when the user leaves the app */
454
- return new IndexedDBDatabase();
455
- }
456
- else if (isPlatformBrowser(platformId)
457
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- They can be undefined in some browsers scenarios
458
- && (localStorage !== undefined) && (localStorage !== null) && ("getItem" in localStorage)) {
459
- /* Check:
460
- * - if we are in a browser context (issue: server-side rendering)
461
- * - if `localStorage` exists (to be sure)
462
- * - it could exists but not having a working API
463
- * Will be the case for:
464
- * - Safari cross-origin iframes, detected later in `IndexedDBDatabase.connect()`
465
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42}
466
- */
467
- return new LocalStorageDatabase();
468
- }
469
- }
470
- catch { }
471
- /* Will be the case for:
472
- * - In browsers if storage has been fully disabled (via the "Block all cookies" option)
473
- * - Server-side rendering
474
- * - All other non-browser context
475
- */
476
- return new MemoryDatabase();
477
- }
478
- class LocalDatabase {
479
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: LocalDatabase, deps: [], target: i0.ɵɵFactoryTarget.Service });
480
- static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.0", ngImport: i0, type: LocalDatabase, factory: localDatabaseFactory });
481
- }
482
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: LocalDatabase, decorators: [{
483
- type: Service,
484
- args: [{
485
- factory: localDatabaseFactory,
486
- }]
487
- }] });
488
-
489
- class IndexedDBDatabase {
490
- /**
491
- * `indexedDB` database name
492
- */
493
- dbName;
494
- /**
495
- * `indexedDB` object store name
496
- */
497
- storeName;
498
- /**
499
- * `indexedDB` database version. Must be an unsigned **integer**
500
- */
501
- dbVersion;
502
- /**
503
- * `indexedDB` database connection, wrapped in a RxJS `ReplaySubject` to be able to access the connection
504
- * even after the connection success event happened
505
- */
506
- database = new ReplaySubject(1);
507
- /**
508
- * Flag to not wrap `indexedDB` values for interoperability or to wrap for backward compatibility.
509
- */
510
- noWrap;
511
- /**
512
- * Index used when wrapping value. *For backward compatibility only.*
513
- */
514
- wrapIndex = "value";
515
- constructor() {
516
- this.dbName = inject(IDB_DB_NAME);
517
- this.storeName = inject(IDB_STORE_NAME);
518
- this.dbVersion = inject(IDB_DB_VERSION);
519
- this.noWrap = inject(IDB_NO_WRAP);
520
- /* Connect to `indexedDB`, with prefix if provided by the user */
521
- this.connect();
522
- }
523
- /**
524
- * Information about `indexedDB` connection. *Only useful for interoperability.*
525
- * @returns `indexedDB` database name, store name and database version
526
- */
527
- get backingStore() {
528
- return {
529
- database: this.dbName,
530
- store: this.storeName,
531
- version: this.dbVersion,
532
- };
533
- }
534
- /**
535
- * Number of items in our `indexedDB` database and object store
536
- */
537
- get size() {
538
- /* Open a transaction in read-only mode */
539
- return this.transaction("readonly").pipe(mergeMap((transactionData) => {
540
- const { store, events } = transactionData;
541
- /* Request to know the number of items */
542
- const request = store.count();
543
- /* Return the result */
544
- return events.pipe(map(() => request.result));
545
- }),
546
- /* The observable will complete after the first value */
547
- first());
548
- }
549
- /**
550
- * Gets an item value in our `indexedDB` store
551
- * @param key The item's key
552
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in an RxJS `Observable`
553
- */
554
- get(key) {
555
- /* Open a transaction in read-only mode */
556
- return this.transaction("readonly").pipe(mergeMap((transactionData) => {
557
- const { store, events } = transactionData;
558
- /* Request the value with the key provided by the user */
559
- const request = store.get(key);
560
- /* Listen events and return the result */
561
- return events.pipe(map(() => {
562
- if ((request.result !== undefined) && (request.result !== null)) {
563
- /* Prior to v8, the value was wrapped in an `{ value: ...}` object */
564
- if (!this.noWrap && (typeof request.result === "object") && (this.wrapIndex in request.result) &&
565
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Required by indexedDb behavior
566
- (request.result[this.wrapIndex] !== undefined) && (request.result[this.wrapIndex] !== null)) {
567
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Required by indexedDb behavior
568
- return request.result[this.wrapIndex];
569
- }
570
- else {
571
- /* Cast to the wanted type */
572
- return request.result;
573
- }
574
- }
575
- /* Return `undefined` if the value is empty */
576
- return undefined;
577
- }));
578
- }),
579
- /* The observable will complete after the first value */
580
- first());
581
- }
582
- /**
583
- * Sets an item in our `indexedDB` store
584
- * @param key The item's key
585
- * @param data The item's value
586
- * @returns An RxJS `Observable` to wait the end of the operation
587
- */
588
- set(key, data) {
589
- /* Storing `undefined` in `indexedDb` can cause issues in some browsers so removing item instead */
590
- if (data === undefined) {
591
- return this.delete(key);
592
- }
593
- /* Open a transaction in write mode */
594
- return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
595
- const { store, events } = transactionData;
596
- /* Prior to v8, data was wrapped in a `{ value: ... }` object */
597
- const dataToStore = this.noWrap ? data : { [this.wrapIndex]: data };
598
- /* Add if the item is not existing yet, or update otherwise */
599
- store.put(dataToStore, key);
600
- /* Listen to events and return `undefined` as no value is expected */
601
- return events.pipe(map(() => undefined));
602
- }),
603
- /* The observable will complete after the first value */
604
- first());
605
- }
606
- /**
607
- * Deletes an item in our `indexedDB` store
608
- * @param key The item's key
609
- * @returns An RxJS `Observable` to wait the end of the operation
610
- */
611
- delete(key) {
612
- /* Open a transaction in write mode */
613
- return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
614
- const { store, events } = transactionData;
615
- /* Delete the item in store */
616
- store.delete(key);
617
- /* Listen to events and return `undefined` as no data is expected here */
618
- return events.pipe(map(() => undefined));
619
- }),
620
- /* The observable will complete after the first value */
621
- first());
622
- }
623
- /**
624
- * Deletes all items from our `indexedDB` objet store
625
- * @returns An RxJS `Observable` to wait the end of the operation
626
- */
627
- clear() {
628
- /* Open a transaction in write mode */
629
- return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
630
- const { store, events } = transactionData;
631
- /* Delete all items in object store */
632
- store.clear();
633
- /* Listen to events and return `undefined` as no data is expected here */
634
- return events.pipe(map(() => undefined));
635
- }),
636
- /* The observable will complete */
637
- first());
638
- }
639
- /**
640
- * Get all the keys in our `indexedDB` store
641
- * @returns An RxJS `Observable` iterating on each key
642
- */
643
- keys() {
644
- /* Open a transaction in read-only mode */
645
- return this.transaction("readonly").pipe(
646
- /* `first()` is used as the final operator in other methods to complete the `Observable`
647
- * (as it all starts from a `ReplaySubject` which never ends),
648
- * but as this method is iterating over multiple values, `first()` **must** be used here */
649
- first(), mergeMap((transactionData) => {
650
- const { store } = transactionData;
651
- /* Open a cursor on the store
652
- * Avoid issues like https://github.com/cyrilletuzi/angular-async-local-storage/issues/69 */
653
- const request = store.openKeyCursor();
654
- /* Listen to success event */
655
- const success$ = fromEvent(request, "success").pipe(
656
- /* Stop the `Observable` when the cursor is `null` */
657
- // // eslint-disable-next-line rxjs/no-ignored-takewhile-value -- Required by indexedDb behavior, getting the result from the event does not always work
658
- takeWhile(() => (request.result !== null)),
659
- /* This lib only allows string keys, but user could have added other types of keys from outside
660
- * It's OK to cast as the cursor as been tested in the previous operator */
661
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-base-to-string -- Required by indexedDb behavior, and strings are enforced by the lib
662
- map(() => request.result.key.toString()),
663
- /* Iterate on the cursor */
664
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Required by indexedDb behavior
665
- tap(() => { request.result.continue(); }));
666
- /* Listen to error event and if so, throw an error */
667
- const error$ = this.listenError(request);
668
- /* Choose the first event to occur */
669
- return race([success$, error$]);
670
- }));
671
- }
672
- /**
673
- * Check if a key exists in our `indexedDB` store
674
- * @returns An RxJS `Observable` telling if the key exists or not
675
- */
676
- has(key) {
677
- /* Open a transaction in read-only mode */
678
- return this.transaction("readonly").pipe(mergeMap((transactionData) => {
679
- const { store, events } = transactionData;
680
- /* Check if the key exists in the store
681
- * Fixes https://github.com/cyrilletuzi/angular-async-local-storage/issues/69
682
- */
683
- const request = store.getKey(key);
684
- /* Listen to events and return `true` or `false` */
685
- return events.pipe(map(() => (request.result !== undefined) ? true : false));
686
- }),
687
- /* The observable will complete */
688
- first());
689
- }
690
- /**
691
- * Connects to `indexedDB` and creates the object store on first time
692
- */
693
- connect() {
694
- let request;
695
- /* Connect to `indexedDB`
696
- * Will fail in Safari cross-origin iframes
697
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42} */
698
- try {
699
- /* Do NOT explicit `window` here, as `indexedDB` could be used from a web worker too */
700
- request = indexedDB.open(this.dbName, this.dbVersion);
701
- }
702
- catch {
703
- this.database.error(new IDBBrokenError());
704
- return;
705
- }
706
- /* Create store on first connection */
707
- this.createStore(request);
708
- /* Listen to success and error events */
709
- const success$ = fromEvent(request, "success");
710
- const error$ = this.listenError(request);
711
- /* Choose the first to occur */
712
- race([success$, error$])
713
- /* The observable will complete */
714
- .pipe(first())
715
- .subscribe({
716
- next: () => {
717
- /* Register the database connection in the `ReplaySubject` for further access */
718
- this.database.next(request.result);
719
- },
720
- error: () => {
721
- /* Keeping this error management for safety, but it should not happen anymore.
722
- * It was for Firefox private mode issue in Firefox versions < 115
723
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/26} */
724
- this.database.error(new IDBBrokenError());
725
- },
726
- });
727
- }
728
- /**
729
- * Create store on first use of `indexedDB`
730
- * @param request `indexedDB` database opening request
731
- */
732
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
733
- createStore(request) {
734
- /* Listen to the event fired on first connection */
735
- fromEvent(request, "upgradeneeded")
736
- /* The observable will complete */
737
- .pipe(first())
738
- .subscribe({
739
- next: () => {
740
- /* Check if the store already exists, to avoid error */
741
- if (!request.result.objectStoreNames.contains(this.storeName)) {
742
- /* Create the object store */
743
- request.result.createObjectStore(this.storeName);
744
- }
745
- }
746
- });
747
- }
748
- /**
749
- * Open an `indexedDB` transaction and get our store
750
- * @param mode `readonly` or `readwrite`
751
- * @returns An `indexedDB` transaction store and events, wrapped in an RxJS `Observable`
752
- */
753
- transaction(mode) {
754
- /* From the `indexedDB` connection, open a transaction and get the store */
755
- return this.database
756
- .pipe(mergeMap((database) => {
757
- let transaction;
758
- try {
759
- transaction = database.transaction([this.storeName], mode);
760
- }
761
- catch (error) {
762
- /* The store could have been deleted from outside */
763
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
764
- return throwError(() => error);
765
- }
766
- /* Get the store from the transaction */
767
- const store = transaction.objectStore(this.storeName);
768
- /* Listen transaction `complete` and `error` events */
769
- const events = this.listenTransactionEvents(transaction);
770
- return of({ store, events });
771
- }));
772
- }
773
- /**
774
- * Listen errors on a transaction or request, and throw if trigerred
775
- * @param transactionOrRequest `indexedDb` transaction or request to listen
776
- * @returns An `Observable` listening to errors
777
- */
778
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
779
- listenError(transactionOrRequest) {
780
- return fromEvent(transactionOrRequest, "error").pipe(
781
- /* Throw on error to be able to catch errors in RxJS way.
782
- * Here `event.target` must be used, as `transactionOrRequest.error` will be `null`
783
- * if we are on the request and the error is only triggered later by the transaction */
784
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
785
- mergeMap((event) => throwError(() => event.target?.error)));
786
- }
787
- /**
788
- * Listen transaction `complete` and `error` events
789
- * @param transaction Transaction to listen
790
- * @returns An `Observable` listening to transaction `complete` and `error` events
791
- */
792
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
793
- listenTransactionEvents(transaction) {
794
- /* Listen to the `complete` event */
795
- const complete$ = fromEvent(transaction, "complete");
796
- /* Listen to the `error` event */
797
- const error$ = this.listenError(transaction);
798
- /* Choose the first event to occur */
799
- return race([complete$, error$]);
800
- }
801
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: IndexedDBDatabase, deps: [], target: i0.ɵɵFactoryTarget.Service });
802
- static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.0", ngImport: i0, type: IndexedDBDatabase });
803
- }
804
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: IndexedDBDatabase, decorators: [{
805
- type: Service
806
- }], ctorParameters: () => [] });
807
-
808
- class JSONValidator {
809
- /**
810
- * Validate a JSON data against a Jsubset of the JSON Schema standard.
811
- * Types are enforced to validate everything: each schema must
812
- * @param data JSON data to validate
813
- * @param schema Subset of JSON Schema. Must have a `type`.
814
- * @returns If data is valid: `true`, if it is invalid: `false`
815
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/VALIDATION.md}
816
- */
817
- validate(data, schema) {
818
- switch (schema.type) {
819
- case "string":
820
- return this.validateString(data, schema);
821
- case "number":
822
- case "integer":
823
- return this.validateNumber(data, schema);
824
- case "boolean":
825
- return this.validateBoolean(data, schema);
826
- case "array":
827
- return this.validateArray(data, schema);
828
- case "object":
829
- return this.validateObject(data, schema);
830
- }
831
- }
832
- /**
833
- * Validate a string
834
- * @param data Data to validate
835
- * @param schema Schema describing the string
836
- * @returns If data is valid: `true`, if it is invalid: `false`
837
- */
838
- validateString(data, schema) {
839
- if (typeof data !== "string") {
840
- return false;
841
- }
842
- if (!this.validateConst(data, schema)) {
843
- return false;
844
- }
845
- if (!this.validateEnum(data, schema)) {
846
- return false;
847
- }
848
- if ((schema.maxLength !== undefined) && (data.length > schema.maxLength)) {
849
- return false;
850
- }
851
- if ((schema.minLength !== undefined) && (data.length < schema.minLength)) {
852
- return false;
853
- }
854
- if (schema.pattern !== undefined) {
855
- try {
856
- const regularExpression = new RegExp(schema.pattern);
857
- if (!regularExpression.test(data)) {
858
- return false;
859
- }
860
- }
861
- catch { }
862
- }
863
- return true;
864
- }
865
- /**
866
- * Validate a number or an integer
867
- * @param data Data to validate
868
- * @param schema Schema describing the number or integer
869
- * @returns If data is valid: `true`, if it is invalid: `false`
870
- */
871
- validateNumber(data, schema) {
872
- if (typeof data !== "number") {
873
- return false;
874
- }
875
- if ((schema.type === "integer") && !Number.isInteger(data)) {
876
- return false;
877
- }
878
- if (!this.validateConst(data, schema)) {
879
- return false;
880
- }
881
- if (!this.validateEnum(data, schema)) {
882
- return false;
883
- }
884
- /* Test is done this way to not divide by 0 */
885
- if (schema.multipleOf !== undefined && schema.multipleOf !== 0 && Number.isFinite(schema.multipleOf) && !Number.isInteger(data / schema.multipleOf)) {
886
- return false;
887
- }
888
- if ((schema.maximum !== undefined) && (data > schema.maximum)) {
889
- return false;
890
- }
891
- if ((schema.exclusiveMaximum !== undefined) && (data >= schema.exclusiveMaximum)) {
892
- return false;
893
- }
894
- if ((schema.minimum !== undefined) && (data < schema.minimum)) {
895
- return false;
896
- }
897
- if ((schema.exclusiveMinimum !== undefined) && (data <= schema.exclusiveMinimum)) {
898
- return false;
899
- }
900
- return true;
901
- }
902
- /**
903
- * Validate a boolean
904
- * @param data Data to validate
905
- * @param schema Schema describing the boolean
906
- * @returns If data is valid: `true`, if it is invalid: `false`
907
- */
908
- validateBoolean(data, schema) {
909
- if (typeof data !== "boolean") {
910
- return false;
911
- }
912
- if (!this.validateConst(data, schema)) {
913
- return false;
914
- }
915
- return true;
916
- }
917
- /**
918
- * Validate an array
919
- * @param data Data to validate
920
- * @param schema Schema describing the array
921
- * @returns If data is valid: `true`, if it is invalid: `false`
922
- */
923
- validateArray(data, schema) {
924
- if (!Array.isArray(data)) {
925
- return false;
926
- }
927
- if ((schema.maxItems !== undefined) && (data.length > schema.maxItems)) {
928
- return false;
929
- }
930
- if ((schema.minItems !== undefined) && (data.length < schema.minItems)) {
931
- return false;
932
- }
933
- if (schema.uniqueItems === true) {
934
- /* Create a set to eliminate values with multiple occurences */
935
- const dataSet = new Set(data);
936
- if (data.length !== dataSet.size) {
937
- return false;
938
- }
939
- }
940
- /* Specific test for tuples */
941
- if (Array.isArray(schema.items) || schema.items === undefined) {
942
- // TODO: cast should not be needed here
943
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
944
- return this.validateTuple(data, schema.items);
945
- }
946
- /* Validate all the values in array */
947
- for (const value of data) {
948
- // TODO: remove when TypeScript 4.1 is available
949
- // (currently the narrowed type from `Array.isArray()` is lost on readonly arrays)
950
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
951
- if (!this.validate(value, schema.items)) {
952
- return false;
953
- }
954
- }
955
- return true;
956
- }
957
- /**
958
- * Validate a tuple (array with fixed length and multiple types)
959
- * @param data Data to validate
960
- * @param schemas Schemas describing the tuple
961
- * @returns If data is valid: `true`, if it is invalid: `false`
962
- */
963
- validateTuple(data, schemas) {
964
- const lengthToCheck = schemas ? schemas.length : 0;
965
- /* Tuples have a fixed length */
966
- if (data.length !== lengthToCheck) {
967
- return false;
968
- }
969
- if (schemas) {
970
- for (const [index, schema] of schemas.entries()) {
971
- if (!this.validate(data[index], schema)) {
972
- return false;
973
- }
974
- }
975
- }
976
- return true;
977
- }
978
- /**
979
- * Validate an object
980
- * @param data Data to validate
981
- * @param schema JSON schema describing the object
982
- * @returns If data is valid: `true`, if it is invalid: `false`
983
- */
984
- validateObject(data, schema) {
985
- /* Check the type and if not `null` as `null` also have the type `object` in old browsers */
986
- if ((typeof data !== "object") || (data === null)) {
987
- return false;
988
- }
989
- /* Check if the object doesn't have more properties than expected
990
- * Equivalent of `additionalProperties: false`
991
- */
992
- if (Object.keys(schema.properties).length < Object.keys(data).length) {
993
- return false;
994
- }
995
- /* Validate required properties */
996
- if (schema.required) {
997
- for (const requiredProp of schema.required) {
998
- if (!Object.hasOwn(data, requiredProp)) {
999
- return false;
1000
- }
1001
- }
1002
- }
1003
- /* Recursively validate all properties */
1004
- for (const property in schema.properties) {
1005
- /* Filter to keep only real properties (no internal JS stuff) and check if the data has the property too */
1006
- if (Object.hasOwn(schema.properties, property) && Object.hasOwn(data, property)) {
1007
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-unsafe-type-assertion -- Ensured by the logic
1008
- if (!this.validate(data[property], schema.properties[property])) {
1009
- return false;
1010
- }
1011
- }
1012
- }
1013
- return true;
1014
- }
1015
- /**
1016
- * Validate a constant
1017
- * @param data Data ta validate
1018
- * @param schema JSON schema describing the constant
1019
- * @returns If data is valid: `true`, if it is invalid: `false`
1020
- */
1021
- validateConst(data, schema) {
1022
- if (schema.const === undefined) {
1023
- return true;
1024
- }
1025
- return (data === schema.const);
1026
- }
1027
- /**
1028
- * Validate an enum
1029
- * @param data Data ta validate
1030
- * @param schema JSON schema describing the enum
1031
- * @returns If data is valid: `true`, if it is invalid: `false`
1032
- */
1033
- validateEnum(data, schema) {
1034
- if (!schema.enum) {
1035
- return true;
1036
- }
1037
- /* Cast as the data can be of multiple types, and so TypeScript is lost */
1038
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
1039
- return (schema.enum.includes(data));
1040
- }
1041
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: JSONValidator, deps: [], target: i0.ɵɵFactoryTarget.Service });
1042
- static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.0", ngImport: i0, type: JSONValidator });
1043
- }
1044
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: JSONValidator, decorators: [{
1045
- type: Service
1046
- }] });
1047
-
1048
- class StorageMap {
1049
- #database;
1050
- #jsonValidator;
1051
- #notifiers = new Map();
1052
- /**
1053
- * Constructor params are provided by Angular (but can also be passed manually in tests)
1054
- * @param database Storage to use
1055
- */
1056
- constructor(
1057
- // eslint-disable-next-line @angular-eslint/prefer-inject, @typescript-eslint/prefer-readonly-parameter-types -- Used in tests for inject, wanted as writeable for readonly
1058
- database) {
1059
- this.#database = database;
1060
- this.#jsonValidator = new JSONValidator();
1061
- }
1062
- /**
1063
- * **Number of items** in storage, wrapped in an Observable.
1064
- *
1065
- * Note you do *not* need to unsubscribe (it is a self-completing Observable).
1066
- *
1067
- * @example
1068
- * this.storageMap.size.subscribe((size) => {
1069
- * console.log(size);
1070
- * });
1071
- */
1072
- get size() {
1073
- return this.#database.size
1074
- /* Catch if `indexedDb` is broken */
1075
- .pipe(this.#catchIDBBroken(() => this.#database.size));
1076
- }
1077
- /**
1078
- * Tells you which storage engine is used.
1079
- *
1080
- * *Only useful for interoperability.*
1081
- *
1082
- * Note that due to some browsers issues in some special contexts
1083
- * (like Safari cross-origin iframes),
1084
- * **this information may be wrong at initialization,**
1085
- * as the storage could fallback from `indexedDB` to `localStorage`
1086
- * only after a first read or write operation.
1087
- * @returns Storage engine used
1088
- *
1089
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1090
- *
1091
- * @example
1092
- * if (this.storageMap.backingEngine === 'indexedDB') {}
1093
- */
1094
- get backingEngine() {
1095
- if (this.#database instanceof IndexedDBDatabase) {
1096
- return "indexedDB";
1097
- }
1098
- else if (this.#database instanceof LocalStorageDatabase) {
1099
- return "localStorage";
1100
- }
1101
- else if (this.#database instanceof MemoryDatabase) {
1102
- return "memory";
1103
- }
1104
- else {
1105
- return "unknown";
1106
- }
1107
- }
1108
- /**
1109
- * Information about `indexedDB` database.
1110
- *
1111
- * *Only useful for interoperability.*
1112
- *
1113
- * @returns `indexedDB` database name, store name and database version.
1114
- * **Values will be empty if the storage is not `indexedDB`, so it should be used after an engine check**.
1115
- *
1116
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1117
- *
1118
- * @example
1119
- * if (this.storageMap.backingEngine === 'indexedDB') {
1120
- * const { database, store, version } = this.storageMap.backingStore;
1121
- * }
1122
- */
1123
- get backingStore() {
1124
- return (this.#database instanceof IndexedDBDatabase) ?
1125
- this.#database.backingStore :
1126
- { database: "", store: "", version: 0 };
1127
- }
1128
- /**
1129
- * Information about `localStorage` fallback storage.
1130
- *
1131
- * *Only useful for interoperability.*
1132
- *
1133
- * @returns `localStorage` prefix.
1134
- * **Values will be empty if the storage is not `localStorage`, so it should be used after an engine check**.
1135
- *
1136
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1137
- *
1138
- * @example
1139
- * if (this.storageMap.backingEngine === 'localStorage') {
1140
- * const { prefix } = this.storageMap.fallbackBackingStore;
1141
- * }
1142
- */
1143
- get fallbackBackingStore() {
1144
- return (this.#database instanceof LocalStorageDatabase) ?
1145
- { prefix: this.#database.prefix } :
1146
- { prefix: "" };
1147
- }
1148
- get(key, schema) {
1149
- /* Get the data in storage */
1150
- return this.#database.get(key).pipe(
1151
- /* Check if `indexedDb` is broken */
1152
- this.#catchIDBBroken(() => this.#database.get(key)), mergeMap((data) => {
1153
- /* No need to validate if the data is empty */
1154
- if ((data === undefined) || (data === null)) {
1155
- return of(undefined);
1156
- }
1157
- else if (schema) {
1158
- /* Validate data against a JSON schema if provided */
1159
- if (!this.#jsonValidator.validate(data, schema)) {
1160
- return throwError(() => new ValidationError());
1161
- }
1162
- /* Data have been checked, so it's OK to cast */
1163
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
1164
- return of(data);
1165
- }
1166
- /* Cast to unknown as the data wasn't checked */
1167
- return of(data);
1168
- }));
1169
- }
1170
- /**
1171
- * Store an item in storage.
1172
- *
1173
- * Note that:
1174
- * * you *do* need to subscribe, even if you do not have something specific to do after writing in storage, otherwise nothing happens (because it is how RxJS Observables work),
1175
- * * but you do *not* need to unsubscribe (it is a self-completing Observable),
1176
- * * setting `null` or `undefined` will remove the item to avoid some browsers issues,
1177
- * * you should stick to serializable JSON data, meaning primitive types, arrays and literal objects. Date, Map, Set, Blob and other special structures can cause issues in some scenarios.
1178
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/SERIALIZATION.md}
1179
- *
1180
- * @param key The item's key
1181
- * @param data The item's value
1182
- * @param schema Optional JSON schema to validate the data
1183
- * @returns A RxJS Observable to wait the end of the operation
1184
- *
1185
- * @example
1186
- * this.storageMap.set('key', 'value').subscribe(() => {});
1187
- */
1188
- set(key, data, schema) {
1189
- /* Storing `undefined` or `null` is useless and can cause issues in `indexedDb` in some browsers,
1190
- * so removing item instead for all storages to have a consistent API */
1191
- if ((data === undefined) || (data === null)) {
1192
- return this.delete(key);
1193
- }
1194
- /* Validate data against a JSON schema if provided */
1195
- if (schema && !this.#jsonValidator.validate(data, schema)) {
1196
- return throwError(() => new ValidationError());
1197
- }
1198
- return this.#database.set(key, data).pipe(
1199
- /* Catch if `indexedDb` is broken */
1200
- this.#catchIDBBroken(() => this.#database.set(key, data)),
1201
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1202
- tap(() => { this.#notify(key, data); }));
1203
- }
1204
- /**
1205
- * Delete an item in storage.
1206
- *
1207
- * Note that:
1208
- * * you *do* need to subscribe, even if you do not have something specific to do after deleting, otherwise nothing happens (because it is how RxJS Observables work),
1209
- * * but you do *not* need to unsubscribe (it is a self-completing Observable).
1210
- *
1211
- * @param key The item's key
1212
- * @returns A RxJS Observable to wait the end of the operation
1213
- *
1214
- * @example
1215
- * this.storageMap.delete('key').subscribe(() => {});
1216
- */
1217
- delete(key) {
1218
- return this.#database.delete(key).pipe(
1219
- /* Catch if `indexedDb` is broken */
1220
- this.#catchIDBBroken(() => this.#database.delete(key)),
1221
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1222
- tap(() => { this.#notify(key, undefined); }));
1223
- }
1224
- /**
1225
- * Delete all items in storage.
1226
- *
1227
- * Note that:
1228
- * * you *do* need to subscribe, even if you do not have something specific to do after clearing, otherwise nothing happens (because it is how RxJS Observables work),
1229
- * * but you do *not* need to unsubscribe (it is a self-completing Observable).
1230
- *
1231
- * @returns A RxJS Observable to wait the end of the operation
1232
- *
1233
- * @example
1234
- * this.storageMap.clear().subscribe(() => {});
1235
- */
1236
- clear() {
1237
- return this.#database.clear().pipe(
1238
- /* Catch if `indexedDb` is broken */
1239
- this.#catchIDBBroken(() => this.#database.clear()),
1240
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1241
- tap(() => {
1242
- for (const key of this.#notifiers.keys()) {
1243
- this.#notify(key, undefined);
1244
- }
1245
- }));
1246
- }
1247
- /**
1248
- * Get all keys stored in storage.
1249
- *
1250
- * Note **this is an *iterating* Observable**:
1251
- * * if there is no key, the `next` callback will not be invoked,
1252
- * * if you need to wait the whole operation to end, be sure to act in the `complete` callback,
1253
- * as this Observable can emit several values and so will invoke the `next` callback several times,
1254
- * * you do *not* need to unsubscribe (it is a self-completing Observable).
1255
- *
1256
- * @returns A list of the keys wrapped in a RxJS Observable
1257
- *
1258
- * @example
1259
- * this.storageMap.keys().subscribe({
1260
- * next: (key) => { console.log(key); },
1261
- * complete: () => { console.log('Done'); },
1262
- * });
1263
- */
1264
- keys() {
1265
- return this.#database.keys()
1266
- /* Catch if `indexedDb` is broken */
1267
- .pipe(this.#catchIDBBroken(() => this.#database.keys()));
1268
- }
1269
- /**
1270
- * Tells if a key exists in storage.
1271
- *
1272
- * Note you do *not* need to unsubscribe (it is a self-completing Observable).
1273
- *
1274
- * @returns A RxJS Observable telling if the key exists
1275
- *
1276
- * @example
1277
- * this.storageMap.has('key').subscribe((hasKey) => {
1278
- * if (hasKey) {}
1279
- * });
1280
- */
1281
- has(key) {
1282
- return this.#database.has(key)
1283
- /* Catch if `indexedDb` is broken */
1284
- .pipe(this.#catchIDBBroken(() => this.#database.has(key)));
1285
- }
1286
- watch(key, schema) {
1287
- /* Check if there is already a notifier */
1288
- if (!this.#notifiers.has(key)) {
1289
- this.#notifiers.set(key, new ReplaySubject(1));
1290
- }
1291
- /* Non-null assertion is required because TypeScript doesn't narrow `.has()` yet */
1292
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Ensured by the logic
1293
- const notifier = this.#notifiers.get(key);
1294
- /* Get the current item value */
1295
- (schema ? this.get(key, schema) : this.get(key)).subscribe({
1296
- next: (result) => {
1297
- notifier.next(result);
1298
- },
1299
- error: (error) => {
1300
- notifier.error(error);
1301
- },
1302
- });
1303
- /* Only the public API of the Observable should be returned */
1304
- return notifier.asObservable();
1305
- }
1306
- /**
1307
- * Notify when a value changes
1308
- * @param key The item's key
1309
- * @param data The new value
1310
- */
1311
- #notify(key, value) {
1312
- const notifier = this.#notifiers.get(key);
1313
- if (notifier) {
1314
- notifier.next(value);
1315
- }
1316
- }
1317
- /**
1318
- * RxJS operator to catch if `indexedDB` is broken
1319
- * @param operationCallback Callback with the operation to redo
1320
- */
1321
- #catchIDBBroken(operationCallback) {
1322
- return catchError((error) => {
1323
- /* Check if `indexedDB` is broken based on error message (the specific error class seems to be lost in the process) */
1324
- if ((error !== undefined) && (error !== null)
1325
- && (typeof error === "object") && ("message" in error)
1326
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Required because TypeScript narrowing is not working here
1327
- && (error.message === IDB_BROKEN_ERROR)) {
1328
- /* When storage is fully disabled in browser (via the "Block all cookies" option),
1329
- * just trying to check `localStorage` variable causes a security exception.
1330
- * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
1331
- */
1332
- try {
1333
- if ("getItem" in localStorage) {
1334
- /* Fallback to `localStorage` if available */
1335
- this.#database = new LocalStorageDatabase();
1336
- }
1337
- else {
1338
- /* Fallback to memory storage otherwise */
1339
- this.#database = new MemoryDatabase();
1340
- }
1341
- }
1342
- catch {
1343
- /* Fallback to memory storage otherwise */
1344
- this.#database = new MemoryDatabase();
1345
- }
1346
- /* Redo the operation */
1347
- return operationCallback();
1348
- }
1349
- else {
1350
- /* Otherwise, rethrow the error */
1351
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
1352
- return throwError(() => error);
1353
- }
1354
- });
1355
- }
1356
- /**
1357
- * THIS METHOD IS FOR INTERNAL PURPOSE ONLY AND MUST NOT BE USED,
1358
- * IT CAN BE REMOVED AT ANY TIME AND MESSING WITH IT CAN CAUSE ISSUES
1359
- * @private
1360
- * @ignore
1361
- */
1362
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- Silence the not used error, it is used in tests
1363
- // @ts-ignore
1364
- ɵinternalGetDatabase() {
1365
- return this.#database;
1366
- }
1367
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageMap, deps: [{ token: LocalDatabase }], target: i0.ɵɵFactoryTarget.Injectable });
1368
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageMap, providedIn: "root" });
255
+ assertInInjectionContext(localDatabaseFactory);
256
+ const platformId = inject(PLATFORM_ID);
257
+ try {
258
+ if (isPlatformBrowser(platformId) && indexedDB !== void 0 && indexedDB !== null && "open" in indexedDB) return new IndexedDBDatabase();
259
+ else if (isPlatformBrowser(platformId) && localStorage !== void 0 && localStorage !== null && "getItem" in localStorage) return new LocalStorageDatabase();
260
+ } catch {}
261
+ return new MemoryDatabase();
1369
262
  }
1370
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: StorageMap, decorators: [{
1371
- type: Injectable,
1372
- args: [{
1373
- providedIn: "root"
1374
- }]
1375
- }], ctorParameters: () => [{ type: LocalDatabase }] });
1376
-
1377
- /*
1378
- * Public API Surface of local-storage
1379
- */
1380
-
1381
- /**
1382
- * Generated bundle index. Do not edit.
1383
- */
1384
-
263
+ var LocalDatabase = class LocalDatabase {
264
+ static ɵfac = i0.ɵɵngDeclareFactory({
265
+ minVersion: "12.0.0",
266
+ version: "22.2.3",
267
+ ngImport: i0,
268
+ type: LocalDatabase,
269
+ deps: [],
270
+ target: i0.ɵɵFactoryTarget.Service
271
+ });
272
+ static ɵprov = i0.ɵɵngDeclareService({
273
+ minVersion: "22.0.0",
274
+ version: "22.2.3",
275
+ ngImport: i0,
276
+ type: LocalDatabase,
277
+ factory: localDatabaseFactory
278
+ });
279
+ };
280
+ i0.ɵɵngDeclareClassMetadata({
281
+ minVersion: "12.0.0",
282
+ version: "22.2.3",
283
+ ngImport: i0,
284
+ type: LocalDatabase,
285
+ decorators: [{
286
+ type: Service,
287
+ args: [{ factory: localDatabaseFactory }]
288
+ }]
289
+ });
290
+ var IndexedDBDatabase = class IndexedDBDatabase {
291
+ dbName;
292
+ storeName;
293
+ dbVersion;
294
+ database = new ReplaySubject(1);
295
+ noWrap;
296
+ wrapIndex = "value";
297
+ constructor() {
298
+ this.dbName = inject(IDB_DB_NAME);
299
+ this.storeName = inject(IDB_STORE_NAME);
300
+ this.dbVersion = inject(IDB_DB_VERSION);
301
+ this.noWrap = inject(IDB_NO_WRAP);
302
+ this.connect();
303
+ }
304
+ get backingStore() {
305
+ return {
306
+ database: this.dbName,
307
+ store: this.storeName,
308
+ version: this.dbVersion
309
+ };
310
+ }
311
+ get size() {
312
+ return this.transaction("readonly").pipe(mergeMap((transactionData) => {
313
+ const { store, events } = transactionData;
314
+ const request = store.count();
315
+ return events.pipe(map(() => request.result));
316
+ }), first());
317
+ }
318
+ get(key) {
319
+ return this.transaction("readonly").pipe(mergeMap((transactionData) => {
320
+ const { store, events } = transactionData;
321
+ const request = store.get(key);
322
+ return events.pipe(map(() => {
323
+ if (request.result !== void 0 && request.result !== null) {
324
+ if (!this.noWrap && typeof request.result === "object" && this.wrapIndex in request.result && request.result[this.wrapIndex] !== void 0 && request.result[this.wrapIndex] !== null) return request.result[this.wrapIndex];
325
+ else return request.result;
326
+ }
327
+ }));
328
+ }), first());
329
+ }
330
+ set(key, data) {
331
+ if (data === void 0) return this.delete(key);
332
+ return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
333
+ const { store, events } = transactionData;
334
+ const dataToStore = this.noWrap ? data : { [this.wrapIndex]: data };
335
+ store.put(dataToStore, key);
336
+ return events.pipe(map(() => void 0));
337
+ }), first());
338
+ }
339
+ delete(key) {
340
+ return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
341
+ const { store, events } = transactionData;
342
+ store.delete(key);
343
+ return events.pipe(map(() => void 0));
344
+ }), first());
345
+ }
346
+ clear() {
347
+ return this.transaction("readwrite").pipe(mergeMap((transactionData) => {
348
+ const { store, events } = transactionData;
349
+ store.clear();
350
+ return events.pipe(map(() => void 0));
351
+ }), first());
352
+ }
353
+ keys() {
354
+ return this.transaction("readonly").pipe(first(), mergeMap((transactionData) => {
355
+ const { store } = transactionData;
356
+ const request = store.openKeyCursor();
357
+ const success$ = fromEvent(request, "success").pipe(takeWhile(() => request.result !== null), map(() => request.result.key.toString()), tap(() => {
358
+ request.result.continue();
359
+ }));
360
+ const error$ = this.listenError(request);
361
+ return race([success$, error$]);
362
+ }));
363
+ }
364
+ has(key) {
365
+ return this.transaction("readonly").pipe(mergeMap((transactionData) => {
366
+ const { store, events } = transactionData;
367
+ const request = store.getKey(key);
368
+ return events.pipe(map(() => request.result !== void 0 ? true : false));
369
+ }), first());
370
+ }
371
+ connect() {
372
+ let request;
373
+ try {
374
+ request = indexedDB.open(this.dbName, this.dbVersion);
375
+ } catch {
376
+ this.database.error(new IDBBrokenError());
377
+ return;
378
+ }
379
+ this.createStore(request);
380
+ const success$ = fromEvent(request, "success");
381
+ const error$ = this.listenError(request);
382
+ race([success$, error$]).pipe(first()).subscribe({
383
+ next: () => {
384
+ this.database.next(request.result);
385
+ },
386
+ error: () => {
387
+ this.database.error(new IDBBrokenError());
388
+ }
389
+ });
390
+ }
391
+ createStore(request) {
392
+ fromEvent(request, "upgradeneeded").pipe(first()).subscribe({ next: () => {
393
+ if (!request.result.objectStoreNames.contains(this.storeName)) request.result.createObjectStore(this.storeName);
394
+ } });
395
+ }
396
+ transaction(mode) {
397
+ return this.database.pipe(mergeMap((database) => {
398
+ let transaction;
399
+ try {
400
+ transaction = database.transaction([this.storeName], mode);
401
+ } catch (error) {
402
+ return throwError(() => error);
403
+ }
404
+ const store = transaction.objectStore(this.storeName);
405
+ const events = this.listenTransactionEvents(transaction);
406
+ return of({
407
+ store,
408
+ events
409
+ });
410
+ }));
411
+ }
412
+ listenError(transactionOrRequest) {
413
+ return fromEvent(transactionOrRequest, "error").pipe(mergeMap((event) => throwError(() => event.target?.error)));
414
+ }
415
+ listenTransactionEvents(transaction) {
416
+ const complete$ = fromEvent(transaction, "complete");
417
+ const error$ = this.listenError(transaction);
418
+ return race([complete$, error$]);
419
+ }
420
+ static ɵfac = i0.ɵɵngDeclareFactory({
421
+ minVersion: "12.0.0",
422
+ version: "22.2.3",
423
+ ngImport: i0,
424
+ type: IndexedDBDatabase,
425
+ deps: [],
426
+ target: i0.ɵɵFactoryTarget.Service
427
+ });
428
+ static ɵprov = i0.ɵɵngDeclareService({
429
+ minVersion: "22.0.0",
430
+ version: "22.2.3",
431
+ ngImport: i0,
432
+ type: IndexedDBDatabase
433
+ });
434
+ };
435
+ i0.ɵɵngDeclareClassMetadata({
436
+ minVersion: "12.0.0",
437
+ version: "22.2.3",
438
+ ngImport: i0,
439
+ type: IndexedDBDatabase,
440
+ decorators: [{ type: Service }],
441
+ ctorParameters: () => []
442
+ });
443
+ var JSONValidator = class JSONValidator {
444
+ validate(data, schema) {
445
+ switch (schema.type) {
446
+ case "string": return this.validateString(data, schema);
447
+ case "number":
448
+ case "integer": return this.validateNumber(data, schema);
449
+ case "boolean": return this.validateBoolean(data, schema);
450
+ case "array": return this.validateArray(data, schema);
451
+ case "object": return this.validateObject(data, schema);
452
+ }
453
+ }
454
+ validateString(data, schema) {
455
+ if (typeof data !== "string") return false;
456
+ if (!this.validateConst(data, schema)) return false;
457
+ if (!this.validateEnum(data, schema)) return false;
458
+ if (schema.maxLength !== void 0 && data.length > schema.maxLength) return false;
459
+ if (schema.minLength !== void 0 && data.length < schema.minLength) return false;
460
+ if (schema.pattern !== void 0) try {
461
+ if (!new RegExp(schema.pattern).test(data)) return false;
462
+ } catch {}
463
+ return true;
464
+ }
465
+ validateNumber(data, schema) {
466
+ if (typeof data !== "number") return false;
467
+ if (schema.type === "integer" && !Number.isInteger(data)) return false;
468
+ if (!this.validateConst(data, schema)) return false;
469
+ if (!this.validateEnum(data, schema)) return false;
470
+ if (schema.multipleOf !== void 0 && schema.multipleOf !== 0 && Number.isFinite(schema.multipleOf) && !Number.isInteger(data / schema.multipleOf)) return false;
471
+ if (schema.maximum !== void 0 && data > schema.maximum) return false;
472
+ if (schema.exclusiveMaximum !== void 0 && data >= schema.exclusiveMaximum) return false;
473
+ if (schema.minimum !== void 0 && data < schema.minimum) return false;
474
+ if (schema.exclusiveMinimum !== void 0 && data <= schema.exclusiveMinimum) return false;
475
+ return true;
476
+ }
477
+ validateBoolean(data, schema) {
478
+ if (typeof data !== "boolean") return false;
479
+ if (!this.validateConst(data, schema)) return false;
480
+ return true;
481
+ }
482
+ validateArray(data, schema) {
483
+ if (!Array.isArray(data)) return false;
484
+ if (schema.maxItems !== void 0 && data.length > schema.maxItems) return false;
485
+ if (schema.minItems !== void 0 && data.length < schema.minItems) return false;
486
+ if (schema.uniqueItems === true) {
487
+ const dataSet = new Set(data);
488
+ if (data.length !== dataSet.size) return false;
489
+ }
490
+ if (Array.isArray(schema.items) || schema.items === void 0) return this.validateTuple(data, schema.items);
491
+ for (const value of data) if (!this.validate(value, schema.items)) return false;
492
+ return true;
493
+ }
494
+ validateTuple(data, schemas) {
495
+ const lengthToCheck = schemas ? schemas.length : 0;
496
+ if (data.length !== lengthToCheck) return false;
497
+ if (schemas) {
498
+ for (const [index, schema] of schemas.entries()) if (!this.validate(data[index], schema)) return false;
499
+ }
500
+ return true;
501
+ }
502
+ validateObject(data, schema) {
503
+ if (typeof data !== "object" || data === null) return false;
504
+ if (Object.keys(schema.properties).length < Object.keys(data).length) return false;
505
+ if (schema.required) {
506
+ for (const requiredProp of schema.required) if (!Object.hasOwn(data, requiredProp)) return false;
507
+ }
508
+ for (const property in schema.properties) if (Object.hasOwn(schema.properties, property) && Object.hasOwn(data, property)) {
509
+ if (!this.validate(data[property], schema.properties[property])) return false;
510
+ }
511
+ return true;
512
+ }
513
+ validateConst(data, schema) {
514
+ if (schema.const === void 0) return true;
515
+ return data === schema.const;
516
+ }
517
+ validateEnum(data, schema) {
518
+ if (!schema.enum) return true;
519
+ return schema.enum.includes(data);
520
+ }
521
+ static ɵfac = i0.ɵɵngDeclareFactory({
522
+ minVersion: "12.0.0",
523
+ version: "22.2.3",
524
+ ngImport: i0,
525
+ type: JSONValidator,
526
+ deps: [],
527
+ target: i0.ɵɵFactoryTarget.Service
528
+ });
529
+ static ɵprov = i0.ɵɵngDeclareService({
530
+ minVersion: "22.0.0",
531
+ version: "22.2.3",
532
+ ngImport: i0,
533
+ type: JSONValidator
534
+ });
535
+ };
536
+ i0.ɵɵngDeclareClassMetadata({
537
+ minVersion: "12.0.0",
538
+ version: "22.2.3",
539
+ ngImport: i0,
540
+ type: JSONValidator,
541
+ decorators: [{ type: Service }]
542
+ });
543
+ var StorageMap = class StorageMap {
544
+ #database;
545
+ #jsonValidator;
546
+ #notifiers = /* @__PURE__ */ new Map();
547
+ constructor(database) {
548
+ this.#database = database;
549
+ this.#jsonValidator = new JSONValidator();
550
+ }
551
+ get size() {
552
+ return this.#database.size.pipe(this.#catchIDBBroken(() => this.#database.size));
553
+ }
554
+ get backingEngine() {
555
+ if (this.#database instanceof IndexedDBDatabase) return "indexedDB";
556
+ else if (this.#database instanceof LocalStorageDatabase) return "localStorage";
557
+ else if (this.#database instanceof MemoryDatabase) return "memory";
558
+ else return "unknown";
559
+ }
560
+ get backingStore() {
561
+ return this.#database instanceof IndexedDBDatabase ? this.#database.backingStore : {
562
+ database: "",
563
+ store: "",
564
+ version: 0
565
+ };
566
+ }
567
+ get fallbackBackingStore() {
568
+ return this.#database instanceof LocalStorageDatabase ? { prefix: this.#database.prefix } : { prefix: "" };
569
+ }
570
+ get(key, schema) {
571
+ return this.#database.get(key).pipe(this.#catchIDBBroken(() => this.#database.get(key)), mergeMap((data) => {
572
+ if (data === void 0 || data === null) return of(void 0);
573
+ else if (schema) {
574
+ if (!this.#jsonValidator.validate(data, schema)) return throwError(() => new ValidationError());
575
+ return of(data);
576
+ }
577
+ return of(data);
578
+ }));
579
+ }
580
+ set(key, data, schema) {
581
+ if (data === void 0 || data === null) return this.delete(key);
582
+ if (schema && !this.#jsonValidator.validate(data, schema)) return throwError(() => new ValidationError());
583
+ return this.#database.set(key, data).pipe(this.#catchIDBBroken(() => this.#database.set(key, data)), tap(() => {
584
+ this.#notify(key, data);
585
+ }));
586
+ }
587
+ delete(key) {
588
+ return this.#database.delete(key).pipe(this.#catchIDBBroken(() => this.#database.delete(key)), tap(() => {
589
+ this.#notify(key, void 0);
590
+ }));
591
+ }
592
+ clear() {
593
+ return this.#database.clear().pipe(this.#catchIDBBroken(() => this.#database.clear()), tap(() => {
594
+ for (const key of this.#notifiers.keys()) this.#notify(key, void 0);
595
+ }));
596
+ }
597
+ keys() {
598
+ return this.#database.keys().pipe(this.#catchIDBBroken(() => this.#database.keys()));
599
+ }
600
+ has(key) {
601
+ return this.#database.has(key).pipe(this.#catchIDBBroken(() => this.#database.has(key)));
602
+ }
603
+ watch(key, schema) {
604
+ if (!this.#notifiers.has(key)) this.#notifiers.set(key, new ReplaySubject(1));
605
+ const notifier = this.#notifiers.get(key);
606
+ (schema ? this.get(key, schema) : this.get(key)).subscribe({
607
+ next: (result) => {
608
+ notifier.next(result);
609
+ },
610
+ error: (error) => {
611
+ notifier.error(error);
612
+ }
613
+ });
614
+ return notifier.asObservable();
615
+ }
616
+ #notify(key, value) {
617
+ const notifier = this.#notifiers.get(key);
618
+ if (notifier) notifier.next(value);
619
+ }
620
+ #catchIDBBroken(operationCallback) {
621
+ return catchError((error) => {
622
+ if (error !== void 0 && error !== null && typeof error === "object" && "message" in error && error.message === "indexedDB is not working") {
623
+ try {
624
+ if ("getItem" in localStorage) this.#database = new LocalStorageDatabase();
625
+ else this.#database = new MemoryDatabase();
626
+ } catch {
627
+ this.#database = new MemoryDatabase();
628
+ }
629
+ return operationCallback();
630
+ } else return throwError(() => error);
631
+ });
632
+ }
633
+ ɵinternalGetDatabase() {
634
+ return this.#database;
635
+ }
636
+ static ɵfac = i0.ɵɵngDeclareFactory({
637
+ minVersion: "12.0.0",
638
+ version: "22.2.3",
639
+ ngImport: i0,
640
+ type: StorageMap,
641
+ deps: [{ token: LocalDatabase }],
642
+ target: i0.ɵɵFactoryTarget.Injectable
643
+ });
644
+ static ɵprov = i0.ɵɵngDeclareInjectable({
645
+ minVersion: "12.0.0",
646
+ version: "22.2.3",
647
+ ngImport: i0,
648
+ type: StorageMap,
649
+ providedIn: "root"
650
+ });
651
+ };
652
+ i0.ɵɵngDeclareClassMetadata({
653
+ minVersion: "12.0.0",
654
+ version: "22.2.3",
655
+ ngImport: i0,
656
+ type: StorageMap,
657
+ decorators: [{
658
+ type: Injectable,
659
+ args: [{ providedIn: "root" }]
660
+ }],
661
+ ctorParameters: () => [{ type: LocalDatabase }]
662
+ });
1385
663
  export { SERIALIZATION_ERROR, SerializationError, StorageMap, StorageModule, VALIDATION_ERROR, ValidationError, provideIndexedDBDataBaseName, provideIndexedDBDataBaseVersion, provideIndexedDBStoreName, provideLocalStoragePrefix };
1386
- //# sourceMappingURL=ngx-pwa-local-storage.mjs.map
664
+
665
+ //# sourceMappingURL=ngx-pwa-local-storage.mjs.map