@ngx-pwa/local-storage 12.1.0 → 13.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +6 -18
  2. package/{esm2015/lib/databases/exceptions.js → esm2020/lib/databases/exceptions.mjs} +1 -1
  3. package/esm2020/lib/databases/indexeddb-database.mjs +326 -0
  4. package/{esm2015/lib/databases/local-database.js → esm2020/lib/databases/local-database.mjs} +7 -7
  5. package/{esm2015/lib/databases/localstorage-database.js → esm2020/lib/databases/localstorage-database.mjs} +3 -3
  6. package/{esm2015/lib/databases/memory-database.js → esm2020/lib/databases/memory-database.mjs} +3 -3
  7. package/{esm2015/lib/storage.module.js → esm2020/lib/storage.module.mjs} +4 -4
  8. package/{esm2015/lib/storages/exceptions.js → esm2020/lib/storages/exceptions.mjs} +1 -1
  9. package/esm2020/lib/storages/local-storage.service.mjs +83 -0
  10. package/{esm2015/lib/storages/storage-map.service.js → esm2020/lib/storages/storage-map.service.mjs} +5 -5
  11. package/{esm2015/lib/tokens.js → esm2020/lib/tokens.mjs} +0 -0
  12. package/{esm2015/lib/validation/json-schema.js → esm2020/lib/validation/json-schema.mjs} +0 -0
  13. package/esm2020/lib/validation/json-validator.mjs +243 -0
  14. package/{esm2015/ngx-pwa-local-storage.js → esm2020/ngx-pwa-local-storage.mjs} +0 -0
  15. package/{esm2015/public-api.js → esm2020/public-api.mjs} +0 -0
  16. package/fesm2015/ngx-pwa-local-storage.mjs +1389 -0
  17. package/fesm2015/ngx-pwa-local-storage.mjs.map +1 -0
  18. package/{fesm2015/ngx-pwa-local-storage.js → fesm2020/ngx-pwa-local-storage.mjs} +40 -38
  19. package/fesm2020/ngx-pwa-local-storage.mjs.map +1 -0
  20. package/package.json +25 -12
  21. package/schematics/migration.json +5 -0
  22. package/schematics/ng-add/index.js +14 -3
  23. package/schematics/ng-add/index.js.map +1 -1
  24. package/schematics/ng-add/schema.json +1 -1
  25. package/schematics/ng-update/index.d.ts +1 -0
  26. package/schematics/ng-update/index.js +18 -5
  27. package/schematics/ng-update/index.js.map +1 -1
  28. package/schematics/utility/config.d.ts +1 -1
  29. package/schematics/utility/config.js +11 -11
  30. package/schematics/utility/config.js.map +1 -1
  31. package/schematics/utility/module.js +3 -3
  32. package/schematics/utility/module.js.map +1 -1
  33. package/bundles/ngx-pwa-local-storage.umd.js +0 -1846
  34. package/bundles/ngx-pwa-local-storage.umd.js.map +0 -1
  35. package/esm2015/lib/databases/indexeddb-database.js +0 -327
  36. package/esm2015/lib/storages/local-storage.service.js +0 -80
  37. package/esm2015/lib/validation/json-validator.js +0 -242
  38. package/fesm2015/ngx-pwa-local-storage.js.map +0 -1
@@ -1,1846 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('rxjs'), require('rxjs/operators')) :
3
- typeof define === 'function' && define.amd ? define('@ngx-pwa/local-storage', ['exports', '@angular/core', '@angular/common', 'rxjs', 'rxjs/operators'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global['ngx-pwa'] = global['ngx-pwa'] || {}, global['ngx-pwa']['local-storage'] = {}), global.ng.core, global.ng.common, global.rxjs, global.rxjs.operators));
5
- }(this, (function (exports, i0, common, rxjs, operators) { 'use strict';
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () {
17
- return e[k];
18
- }
19
- });
20
- }
21
- });
22
- }
23
- n['default'] = e;
24
- return Object.freeze(n);
25
- }
26
-
27
- var i0__namespace = /*#__PURE__*/_interopNamespace(i0);
28
-
29
- /*! *****************************************************************************
30
- Copyright (c) Microsoft Corporation.
31
-
32
- Permission to use, copy, modify, and/or distribute this software for any
33
- purpose with or without fee is hereby granted.
34
-
35
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
36
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
37
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
38
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
39
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
40
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
41
- PERFORMANCE OF THIS SOFTWARE.
42
- ***************************************************************************** */
43
- /* global Reflect, Promise */
44
- var extendStatics = function (d, b) {
45
- extendStatics = Object.setPrototypeOf ||
46
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
47
- function (d, b) { for (var p in b)
48
- if (Object.prototype.hasOwnProperty.call(b, p))
49
- d[p] = b[p]; };
50
- return extendStatics(d, b);
51
- };
52
- function __extends(d, b) {
53
- if (typeof b !== "function" && b !== null)
54
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
55
- extendStatics(d, b);
56
- function __() { this.constructor = d; }
57
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
58
- }
59
- var __assign = function () {
60
- __assign = Object.assign || function __assign(t) {
61
- for (var s, i = 1, n = arguments.length; i < n; i++) {
62
- s = arguments[i];
63
- for (var p in s)
64
- if (Object.prototype.hasOwnProperty.call(s, p))
65
- t[p] = s[p];
66
- }
67
- return t;
68
- };
69
- return __assign.apply(this, arguments);
70
- };
71
- function __rest(s, e) {
72
- var t = {};
73
- for (var p in s)
74
- if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
75
- t[p] = s[p];
76
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
77
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
78
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
79
- t[p[i]] = s[p[i]];
80
- }
81
- return t;
82
- }
83
- function __decorate(decorators, target, key, desc) {
84
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
85
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
86
- r = Reflect.decorate(decorators, target, key, desc);
87
- else
88
- for (var i = decorators.length - 1; i >= 0; i--)
89
- if (d = decorators[i])
90
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
91
- return c > 3 && r && Object.defineProperty(target, key, r), r;
92
- }
93
- function __param(paramIndex, decorator) {
94
- return function (target, key) { decorator(target, key, paramIndex); };
95
- }
96
- function __metadata(metadataKey, metadataValue) {
97
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
98
- return Reflect.metadata(metadataKey, metadataValue);
99
- }
100
- function __awaiter(thisArg, _arguments, P, generator) {
101
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
102
- return new (P || (P = Promise))(function (resolve, reject) {
103
- function fulfilled(value) { try {
104
- step(generator.next(value));
105
- }
106
- catch (e) {
107
- reject(e);
108
- } }
109
- function rejected(value) { try {
110
- step(generator["throw"](value));
111
- }
112
- catch (e) {
113
- reject(e);
114
- } }
115
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
116
- step((generator = generator.apply(thisArg, _arguments || [])).next());
117
- });
118
- }
119
- function __generator(thisArg, body) {
120
- var _ = { label: 0, sent: function () { if (t[0] & 1)
121
- throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
122
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
123
- function verb(n) { return function (v) { return step([n, v]); }; }
124
- function step(op) {
125
- if (f)
126
- throw new TypeError("Generator is already executing.");
127
- while (_)
128
- try {
129
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
130
- return t;
131
- if (y = 0, t)
132
- op = [op[0] & 2, t.value];
133
- switch (op[0]) {
134
- case 0:
135
- case 1:
136
- t = op;
137
- break;
138
- case 4:
139
- _.label++;
140
- return { value: op[1], done: false };
141
- case 5:
142
- _.label++;
143
- y = op[1];
144
- op = [0];
145
- continue;
146
- case 7:
147
- op = _.ops.pop();
148
- _.trys.pop();
149
- continue;
150
- default:
151
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
152
- _ = 0;
153
- continue;
154
- }
155
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
156
- _.label = op[1];
157
- break;
158
- }
159
- if (op[0] === 6 && _.label < t[1]) {
160
- _.label = t[1];
161
- t = op;
162
- break;
163
- }
164
- if (t && _.label < t[2]) {
165
- _.label = t[2];
166
- _.ops.push(op);
167
- break;
168
- }
169
- if (t[2])
170
- _.ops.pop();
171
- _.trys.pop();
172
- continue;
173
- }
174
- op = body.call(thisArg, _);
175
- }
176
- catch (e) {
177
- op = [6, e];
178
- y = 0;
179
- }
180
- finally {
181
- f = t = 0;
182
- }
183
- if (op[0] & 5)
184
- throw op[1];
185
- return { value: op[0] ? op[1] : void 0, done: true };
186
- }
187
- }
188
- var __createBinding = Object.create ? (function (o, m, k, k2) {
189
- if (k2 === undefined)
190
- k2 = k;
191
- Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
192
- }) : (function (o, m, k, k2) {
193
- if (k2 === undefined)
194
- k2 = k;
195
- o[k2] = m[k];
196
- });
197
- function __exportStar(m, o) {
198
- for (var p in m)
199
- if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
200
- __createBinding(o, m, p);
201
- }
202
- function __values(o) {
203
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
204
- if (m)
205
- return m.call(o);
206
- if (o && typeof o.length === "number")
207
- return {
208
- next: function () {
209
- if (o && i >= o.length)
210
- o = void 0;
211
- return { value: o && o[i++], done: !o };
212
- }
213
- };
214
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
215
- }
216
- function __read(o, n) {
217
- var m = typeof Symbol === "function" && o[Symbol.iterator];
218
- if (!m)
219
- return o;
220
- var i = m.call(o), r, ar = [], e;
221
- try {
222
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
223
- ar.push(r.value);
224
- }
225
- catch (error) {
226
- e = { error: error };
227
- }
228
- finally {
229
- try {
230
- if (r && !r.done && (m = i["return"]))
231
- m.call(i);
232
- }
233
- finally {
234
- if (e)
235
- throw e.error;
236
- }
237
- }
238
- return ar;
239
- }
240
- /** @deprecated */
241
- function __spread() {
242
- for (var ar = [], i = 0; i < arguments.length; i++)
243
- ar = ar.concat(__read(arguments[i]));
244
- return ar;
245
- }
246
- /** @deprecated */
247
- function __spreadArrays() {
248
- for (var s = 0, i = 0, il = arguments.length; i < il; i++)
249
- s += arguments[i].length;
250
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
251
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
252
- r[k] = a[j];
253
- return r;
254
- }
255
- function __spreadArray(to, from) {
256
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
257
- to[j] = from[i];
258
- return to;
259
- }
260
- function __await(v) {
261
- return this instanceof __await ? (this.v = v, this) : new __await(v);
262
- }
263
- function __asyncGenerator(thisArg, _arguments, generator) {
264
- if (!Symbol.asyncIterator)
265
- throw new TypeError("Symbol.asyncIterator is not defined.");
266
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
267
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
268
- function verb(n) { if (g[n])
269
- i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
270
- function resume(n, v) { try {
271
- step(g[n](v));
272
- }
273
- catch (e) {
274
- settle(q[0][3], e);
275
- } }
276
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
277
- function fulfill(value) { resume("next", value); }
278
- function reject(value) { resume("throw", value); }
279
- function settle(f, v) { if (f(v), q.shift(), q.length)
280
- resume(q[0][0], q[0][1]); }
281
- }
282
- function __asyncDelegator(o) {
283
- var i, p;
284
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
285
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
286
- }
287
- function __asyncValues(o) {
288
- if (!Symbol.asyncIterator)
289
- throw new TypeError("Symbol.asyncIterator is not defined.");
290
- var m = o[Symbol.asyncIterator], i;
291
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
292
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
293
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
294
- }
295
- function __makeTemplateObject(cooked, raw) {
296
- if (Object.defineProperty) {
297
- Object.defineProperty(cooked, "raw", { value: raw });
298
- }
299
- else {
300
- cooked.raw = raw;
301
- }
302
- return cooked;
303
- }
304
- ;
305
- var __setModuleDefault = Object.create ? (function (o, v) {
306
- Object.defineProperty(o, "default", { enumerable: true, value: v });
307
- }) : function (o, v) {
308
- o["default"] = v;
309
- };
310
- function __importStar(mod) {
311
- if (mod && mod.__esModule)
312
- return mod;
313
- var result = {};
314
- if (mod != null)
315
- for (var k in mod)
316
- if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
317
- __createBinding(result, mod, k);
318
- __setModuleDefault(result, mod);
319
- return result;
320
- }
321
- function __importDefault(mod) {
322
- return (mod && mod.__esModule) ? mod : { default: mod };
323
- }
324
- function __classPrivateFieldGet(receiver, state, kind, f) {
325
- if (kind === "a" && !f)
326
- throw new TypeError("Private accessor was defined without a getter");
327
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
328
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
329
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
330
- }
331
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
332
- if (kind === "m")
333
- throw new TypeError("Private method is not writable");
334
- if (kind === "a" && !f)
335
- throw new TypeError("Private accessor was defined without a setter");
336
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
337
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
338
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
339
- }
340
-
341
- var JSONValidator = /** @class */ (function () {
342
- function JSONValidator() {
343
- }
344
- /**
345
- * Validate a JSON data against a Jsubset of the JSON Schema standard.
346
- * Types are enforced to validate everything: each schema must
347
- * @param data JSON data to validate
348
- * @param schema Subset of JSON Schema. Must have a `type`.
349
- * @returns If data is valid: `true`, if it is invalid: `false`
350
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/VALIDATION.md}
351
- */
352
- JSONValidator.prototype.validate = function (data, schema) {
353
- switch (schema.type) {
354
- case 'string':
355
- return this.validateString(data, schema);
356
- case 'number':
357
- case 'integer':
358
- return this.validateNumber(data, schema);
359
- case 'boolean':
360
- return this.validateBoolean(data, schema);
361
- case 'array':
362
- return this.validateArray(data, schema);
363
- case 'object':
364
- return this.validateObject(data, schema);
365
- }
366
- };
367
- /**
368
- * Validate a string
369
- * @param data Data to validate
370
- * @param schema Schema describing the string
371
- * @returns If data is valid: `true`, if it is invalid: `false`
372
- */
373
- JSONValidator.prototype.validateString = function (data, schema) {
374
- if (typeof data !== 'string') {
375
- return false;
376
- }
377
- if (!this.validateConst(data, schema)) {
378
- return false;
379
- }
380
- if (!this.validateEnum(data, schema)) {
381
- return false;
382
- }
383
- if ((schema.maxLength !== undefined) && (data.length > schema.maxLength)) {
384
- return false;
385
- }
386
- if ((schema.minLength !== undefined) && (data.length < schema.minLength)) {
387
- return false;
388
- }
389
- if (schema.pattern) {
390
- var regularExpression = null;
391
- try {
392
- regularExpression = new RegExp(schema.pattern);
393
- }
394
- catch (_a) {
395
- // Nothing to do
396
- }
397
- if (regularExpression && !regularExpression.test(data)) {
398
- return false;
399
- }
400
- }
401
- return true;
402
- };
403
- /**
404
- * Validate a number or an integer
405
- * @param data Data to validate
406
- * @param schema Schema describing the number or integer
407
- * @returns If data is valid: `true`, if it is invalid: `false`
408
- */
409
- JSONValidator.prototype.validateNumber = function (data, schema) {
410
- if (typeof data !== 'number') {
411
- return false;
412
- }
413
- if ((schema.type === 'integer') && !Number.isInteger(data)) {
414
- return false;
415
- }
416
- if (!this.validateConst(data, schema)) {
417
- return false;
418
- }
419
- if (!this.validateEnum(data, schema)) {
420
- return false;
421
- }
422
- /* Test is done this way to not divide by 0 */
423
- if (schema.multipleOf && !Number.isInteger(data / schema.multipleOf)) {
424
- return false;
425
- }
426
- if ((schema.maximum !== undefined) && (data > schema.maximum)) {
427
- return false;
428
- }
429
- if ((schema.exclusiveMaximum !== undefined) && (data >= schema.exclusiveMaximum)) {
430
- return false;
431
- }
432
- if ((schema.minimum !== undefined) && (data < schema.minimum)) {
433
- return false;
434
- }
435
- if ((schema.exclusiveMinimum !== undefined) && (data <= schema.exclusiveMinimum)) {
436
- return false;
437
- }
438
- return true;
439
- };
440
- /**
441
- * Validate a boolean
442
- * @param data Data to validate
443
- * @param schema Schema describing the boolean
444
- * @returns If data is valid: `true`, if it is invalid: `false`
445
- */
446
- JSONValidator.prototype.validateBoolean = function (data, schema) {
447
- if (typeof data !== 'boolean') {
448
- return false;
449
- }
450
- if (!this.validateConst(data, schema)) {
451
- return false;
452
- }
453
- return true;
454
- };
455
- /**
456
- * Validate an array
457
- * @param data Data to validate
458
- * @param schema Schema describing the array
459
- * @returns If data is valid: `true`, if it is invalid: `false`
460
- */
461
- JSONValidator.prototype.validateArray = function (data, schema) {
462
- var e_1, _b;
463
- if (!Array.isArray(data)) {
464
- return false;
465
- }
466
- if ((schema.maxItems !== undefined) && (data.length > schema.maxItems)) {
467
- return false;
468
- }
469
- if ((schema.minItems !== undefined) && (data.length < schema.minItems)) {
470
- return false;
471
- }
472
- if (schema.uniqueItems) {
473
- /* Create a set to eliminate values with multiple occurences */
474
- var dataSet = new Set(data);
475
- if (data.length !== dataSet.size) {
476
- return false;
477
- }
478
- }
479
- /* Specific test for tuples */
480
- if (Array.isArray(schema.items)) {
481
- return this.validateTuple(data, schema.items);
482
- }
483
- try {
484
- /* Validate all the values in array */
485
- for (var data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
486
- var value = data_1_1.value;
487
- // TODO: remove when TypeScript 4.1 is available
488
- // (currently the narrowed type from `Array.isArray()` is lost on readonly arrays)
489
- if (!this.validate(value, schema.items)) {
490
- return false;
491
- }
492
- }
493
- }
494
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
495
- finally {
496
- try {
497
- if (data_1_1 && !data_1_1.done && (_b = data_1.return)) _b.call(data_1);
498
- }
499
- finally { if (e_1) throw e_1.error; }
500
- }
501
- return true;
502
- };
503
- /**
504
- * Validate a tuple (array with fixed length and multiple types)
505
- * @param data Data to validate
506
- * @param schemas Schemas describing the tuple
507
- * @returns If data is valid: `true`, if it is invalid: `false`
508
- */
509
- JSONValidator.prototype.validateTuple = function (data, schemas) {
510
- /* Tuples have a fixed length */
511
- if (data.length !== schemas.length) {
512
- return false;
513
- }
514
- for (var i = 0; i < schemas.length; i += 1) {
515
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
516
- if (!this.validate(data[i], schemas[i])) {
517
- return false;
518
- }
519
- }
520
- return true;
521
- };
522
- /**
523
- * Validate an object
524
- * @param data Data to validate
525
- * @param schema JSON schema describing the object
526
- * @returns If data is valid: `true`, if it is invalid: `false`
527
- */
528
- JSONValidator.prototype.validateObject = function (data, schema) {
529
- var e_2, _b;
530
- /* Check the type and if not `null` as `null` also have the type `object` in old browsers */
531
- if ((typeof data !== 'object') || (data === null)) {
532
- return false;
533
- }
534
- /* Check if the object doesn't have more properties than expected
535
- * Equivalent of `additionalProperties: false`
536
- */
537
- if (Object.keys(schema.properties).length < Object.keys(data).length) {
538
- return false;
539
- }
540
- /* Validate required properties */
541
- if (schema.required) {
542
- try {
543
- for (var _c = __values(schema.required), _d = _c.next(); !_d.done; _d = _c.next()) {
544
- var requiredProp = _d.value;
545
- if (!Object.prototype.hasOwnProperty.call(data, requiredProp)) {
546
- return false;
547
- }
548
- }
549
- }
550
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
551
- finally {
552
- try {
553
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
554
- }
555
- finally { if (e_2) throw e_2.error; }
556
- }
557
- }
558
- /* Recursively validate all properties */
559
- for (var property in schema.properties) {
560
- /* Filter to keep only real properties (no internal JS stuff) and check if the data has the property too */
561
- if (Object.prototype.hasOwnProperty.call(schema.properties, property) && Object.prototype.hasOwnProperty.call(data, property)) {
562
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
563
- if (!this.validate(data[property], schema.properties[property])) {
564
- return false;
565
- }
566
- }
567
- }
568
- return true;
569
- };
570
- /**
571
- * Validate a constant
572
- * @param data Data ta validate
573
- * @param schema JSON schema describing the constant
574
- * @returns If data is valid: `true`, if it is invalid: `false`
575
- */
576
- JSONValidator.prototype.validateConst = function (data, schema) {
577
- if (!schema.const) {
578
- return true;
579
- }
580
- return (data === schema.const);
581
- };
582
- /**
583
- * Validate an enum
584
- * @param data Data ta validate
585
- * @param schema JSON schema describing the enum
586
- * @returns If data is valid: `true`, if it is invalid: `false`
587
- */
588
- JSONValidator.prototype.validateEnum = function (data, schema) {
589
- if (!schema.enum) {
590
- return true;
591
- }
592
- /* Cast as the data can be of multiple types, and so TypeScript is lost */
593
- return (schema.enum.includes(data));
594
- };
595
- return JSONValidator;
596
- }());
597
- JSONValidator.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: JSONValidator, deps: [], target: i0__namespace.ɵɵFactoryTarget.Injectable });
598
- JSONValidator.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: JSONValidator, providedIn: 'root' });
599
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: JSONValidator, decorators: [{
600
- type: i0.Injectable,
601
- args: [{
602
- providedIn: 'root'
603
- }]
604
- }] });
605
-
606
- /**
607
- * Token to provide a prefix to `localStorage` keys.
608
- */
609
- var LS_PREFIX = new i0.InjectionToken('localStoragePrefix', {
610
- providedIn: 'root',
611
- factory: function () { return ''; }
612
- });
613
- /**
614
- * Default name used for `indexedDB` database.
615
- */
616
- var DEFAULT_IDB_DB_NAME = 'ngStorage';
617
- /**
618
- * Token to provide `indexedDB` database name.
619
- */
620
- var IDB_DB_NAME = new i0.InjectionToken('localStorageIDBDBName', {
621
- providedIn: 'root',
622
- factory: function () { return DEFAULT_IDB_DB_NAME; }
623
- });
624
- /**
625
- * Default version used for `indexedDB` database.
626
- */
627
- var DEFAULT_IDB_DB_VERSION = 1;
628
- /**
629
- * Token to provide `indexedDB` database version.
630
- * Must be an unsigned **integer**.
631
- */
632
- var IDB_DB_VERSION = new i0.InjectionToken('localStorageIDBDBVersion', {
633
- providedIn: 'root',
634
- factory: function () { return DEFAULT_IDB_DB_VERSION; }
635
- });
636
- /**
637
- * Default name used for `indexedDB` object store.
638
- */
639
- var DEFAULT_IDB_STORE_NAME = 'localStorage';
640
- /**
641
- * Token to provide `indexedDB` store name.
642
- * For backward compatibility, the default can't be set now, `IndexedDBDatabase` will do it at runtime.
643
- */
644
- var IDB_STORE_NAME = new i0.InjectionToken('localStorageIDBStoreName', {
645
- providedIn: 'root',
646
- factory: function () { return DEFAULT_IDB_STORE_NAME; }
647
- });
648
- /**
649
- * Default value for interoperability with native `indexedDB` and other storage libs,
650
- * by changing how values are stored in `indexedDB` database.
651
- */
652
- var DEFAULT_IDB_NO_WRAP = true;
653
- /**
654
- * Token to allow interoperability with native `indexedDB` and other storage libs,
655
- * by changing how values are stored in `indexedDB` database.
656
- * Defaults to `true`. Change to `false` for backward compatiblity in existing applications.
657
- * **DO NOT CHANGE THIS BEHAVIOR ONCE IN PRODUCTION**, as it would break with existing data.
658
- */
659
- var IDB_NO_WRAP = new i0.InjectionToken('localStorageIDBWrap', {
660
- providedIn: 'root',
661
- factory: function () { return DEFAULT_IDB_NO_WRAP; }
662
- });
663
-
664
- /**
665
- * Exception message when `indexedDB` is not working
666
- */
667
- var IDB_BROKEN_ERROR = 'indexedDB is not working';
668
- /**
669
- * Exception raised when `indexedDB` is not working
670
- */
671
- var IDBBrokenError = /** @class */ (function (_super) {
672
- __extends(IDBBrokenError, _super);
673
- function IDBBrokenError() {
674
- var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
675
- _this.message = IDB_BROKEN_ERROR;
676
- return _this;
677
- }
678
- return IDBBrokenError;
679
- }(Error));
680
- /**
681
- * Exception message when a value can't be serialized for `localStorage`
682
- */
683
- var SERIALIZATION_ERROR = "The storage is currently localStorage,\nwhere data must be serialized, and the provided data can't be serialized.";
684
- /**
685
- * Exception raised when a value can't be serialized for `localStorage`
686
- */
687
- var SerializationError = /** @class */ (function (_super) {
688
- __extends(SerializationError, _super);
689
- function SerializationError() {
690
- var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
691
- _this.message = SERIALIZATION_ERROR;
692
- return _this;
693
- }
694
- return SerializationError;
695
- }(Error));
696
-
697
- var IndexedDBDatabase = /** @class */ (function () {
698
- /**
699
- * Constructor params are provided by Angular (but can also be passed manually in tests)
700
- * @param dbName `indexedDB` database name
701
- * @param storeName `indexedDB` store name
702
- * @param dbVersion `indexedDB` database version
703
- * @param noWrap Flag to not wrap `indexedDB` values for interoperability or to wrap for backward compatibility
704
- */
705
- function IndexedDBDatabase(dbName, storeName, dbVersion, noWrap) {
706
- if (dbName === void 0) { dbName = DEFAULT_IDB_DB_NAME; }
707
- if (storeName === void 0) { storeName = DEFAULT_IDB_STORE_NAME; }
708
- if (dbVersion === void 0) { dbVersion = DEFAULT_IDB_DB_VERSION; }
709
- if (noWrap === void 0) { noWrap = DEFAULT_IDB_NO_WRAP; }
710
- /**
711
- * `indexedDB` database connection, wrapped in a RxJS `ReplaySubject` to be able to access the connection
712
- * even after the connection success event happened
713
- */
714
- this.database = new rxjs.ReplaySubject(1);
715
- /**
716
- * Index used when wrapping value. *For backward compatibility only.*
717
- */
718
- this.wrapIndex = 'value';
719
- this.dbName = dbName;
720
- this.storeName = storeName;
721
- this.dbVersion = dbVersion;
722
- this.noWrap = noWrap;
723
- /* Connect to `indexedDB`, with prefix if provided by the user */
724
- this.connect();
725
- }
726
- Object.defineProperty(IndexedDBDatabase.prototype, "backingStore", {
727
- /**
728
- * Information about `indexedDB` connection. *Only useful for interoperability.*
729
- * @returns `indexedDB` database name, store name and database version
730
- */
731
- get: function () {
732
- return {
733
- database: this.dbName,
734
- store: this.storeName,
735
- version: this.dbVersion,
736
- };
737
- },
738
- enumerable: false,
739
- configurable: true
740
- });
741
- Object.defineProperty(IndexedDBDatabase.prototype, "size", {
742
- /**
743
- * Number of items in our `indexedDB` database and object store
744
- */
745
- get: function () {
746
- /* Open a transaction in read-only mode */
747
- return this.transaction('readonly').pipe(operators.mergeMap(function (transactionData) {
748
- var store = transactionData.store, events = transactionData.events;
749
- /* Request to know the number of items */
750
- var request = store.count();
751
- /* Return the result */
752
- return events.pipe(operators.map(function () { return request.result; }));
753
- }),
754
- /* The observable will complete after the first value */
755
- operators.first());
756
- },
757
- enumerable: false,
758
- configurable: true
759
- });
760
- /**
761
- * Gets an item value in our `indexedDB` store
762
- * @param key The item's key
763
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in an RxJS `Observable`
764
- */
765
- IndexedDBDatabase.prototype.get = function (key) {
766
- var _this = this;
767
- /* Open a transaction in read-only mode */
768
- return this.transaction('readonly').pipe(operators.mergeMap(function (transactionData) {
769
- var store = transactionData.store, events = transactionData.events;
770
- /* Request the value with the key provided by the user */
771
- var request = store.get(key);
772
- /* Listen events and return the result */
773
- return events.pipe(operators.map(function () {
774
- if ((request.result !== undefined) && (request.result !== null)) {
775
- /* Prior to v8, the value was wrapped in an `{ value: ...}` object */
776
- if (!_this.noWrap && (typeof request.result === 'object') && (_this.wrapIndex in request.result) &&
777
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
778
- (request.result[_this.wrapIndex] !== undefined) && (request.result[_this.wrapIndex] !== null)) {
779
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
780
- return request.result[_this.wrapIndex];
781
- }
782
- else {
783
- /* Cast to the wanted type */
784
- return request.result;
785
- }
786
- }
787
- /* Return `undefined` if the value is empty */
788
- return undefined;
789
- }));
790
- }),
791
- /* The observable will complete after the first value */
792
- operators.first());
793
- };
794
- /**
795
- * Sets an item in our `indexedDB` store
796
- * @param key The item's key
797
- * @param data The item's value
798
- * @returns An RxJS `Observable` to wait the end of the operation
799
- */
800
- IndexedDBDatabase.prototype.set = function (key, data) {
801
- var _this = this;
802
- /* Storing `undefined` in `indexedDb` can cause issues in some browsers so removing item instead */
803
- if (data === undefined) {
804
- return this.delete(key);
805
- }
806
- /* Open a transaction in write mode */
807
- return this.transaction('readwrite').pipe(operators.mergeMap(function (transactionData) {
808
- var _b;
809
- var store = transactionData.store, events = transactionData.events;
810
- /* Prior to v8, data was wrapped in a `{ value: ... }` object */
811
- var dataToStore = _this.noWrap ? data : (_b = {}, _b[_this.wrapIndex] = data, _b);
812
- /* Add if the item is not existing yet, or update otherwise */
813
- store.put(dataToStore, key);
814
- /* Listen to events and return `undefined` as no value is expected */
815
- return events.pipe(operators.mapTo(undefined));
816
- }),
817
- /* The observable will complete after the first value */
818
- operators.first());
819
- };
820
- /**
821
- * Deletes an item in our `indexedDB` store
822
- * @param key The item's key
823
- * @returns An RxJS `Observable` to wait the end of the operation
824
- */
825
- IndexedDBDatabase.prototype.delete = function (key) {
826
- /* Open a transaction in write mode */
827
- return this.transaction('readwrite').pipe(operators.mergeMap(function (transactionData) {
828
- var store = transactionData.store, events = transactionData.events;
829
- /* Delete the item in store */
830
- store.delete(key);
831
- /* Listen to events and return `undefined` as no data is expected here */
832
- return events.pipe(operators.mapTo(undefined));
833
- }),
834
- /* The observable will complete after the first value */
835
- operators.first());
836
- };
837
- /**
838
- * Deletes all items from our `indexedDB` objet store
839
- * @returns An RxJS `Observable` to wait the end of the operation
840
- */
841
- IndexedDBDatabase.prototype.clear = function () {
842
- /* Open a transaction in write mode */
843
- return this.transaction('readwrite').pipe(operators.mergeMap(function (transactionData) {
844
- var store = transactionData.store, events = transactionData.events;
845
- /* Delete all items in object store */
846
- store.clear();
847
- /* Listen to events and return `undefined` as no data is expected here */
848
- return events.pipe(operators.mapTo(undefined));
849
- }),
850
- /* The observable will complete */
851
- operators.first());
852
- };
853
- /**
854
- * Get all the keys in our `indexedDB` store
855
- * @returns An RxJS `Observable` iterating on each key
856
- */
857
- IndexedDBDatabase.prototype.keys = function () {
858
- var _this = this;
859
- /* Open a transaction in read-only mode */
860
- return this.transaction('readonly').pipe(
861
- /* `first()` is used as the final operator in other methods to complete the `Observable`
862
- * (as it all starts from a `ReplaySubject` which never ends),
863
- * but as this method is iterating over multiple values, `first()` **must** be used here */
864
- operators.first(), operators.mergeMap(function (transactionData) {
865
- var store = transactionData.store;
866
- /* Open a cursor on the store
867
- * `.openKeyCursor()` is better for performance, but only available in indexedDB v2 (missing in IE)
868
- * Avoid issues like https://github.com/cyrilletuzi/angular-async-local-storage/issues/69 */
869
- var request = ('openKeyCursor' in store) ? store.openKeyCursor() : store.openCursor();
870
- /* Listen to success event */
871
- var success$ = rxjs.fromEvent(request, 'success').pipe(
872
- /* Stop the `Observable` when the cursor is `null` */
873
- operators.takeWhile(function () { return (request.result !== null); }),
874
- /* This lib only allows string keys, but user could have added other types of keys from outside
875
- * It's OK to cast as the cursor as been tested in the previous operator */
876
- operators.map(function () { return request.result.key.toString(); }),
877
- /* Iterate on the cursor */
878
- operators.tap(function () { request.result.continue(); }));
879
- /* Listen to error event and if so, throw an error */
880
- var error$ = _this.listenError(request);
881
- /* Choose the first event to occur */
882
- return rxjs.race([success$, error$]);
883
- }));
884
- };
885
- /**
886
- * Check if a key exists in our `indexedDB` store
887
- * @returns An RxJS `Observable` telling if the key exists or not
888
- */
889
- IndexedDBDatabase.prototype.has = function (key) {
890
- /* Open a transaction in read-only mode */
891
- return this.transaction('readonly').pipe(operators.mergeMap(function (transactionData) {
892
- var store = transactionData.store, events = transactionData.events;
893
- /* Check if the key exists in the store
894
- * `getKey()` is better but only available in `indexedDB` v2 (Chrome >= 58, missing in IE/Edge Legacy).
895
- * In older browsers, the value is checked instead, but it could lead to an exception
896
- * if `undefined` was stored outside of this lib (e.g. directly with the native `indexedDB` API).
897
- * Fixes https://github.com/cyrilletuzi/angular-async-local-storage/issues/69
898
- */
899
- var request = ('getKey' in store) ? store.getKey(key) : store.get(key);
900
- /* Listen to events and return `true` or `false` */
901
- return events.pipe(operators.map(function () { return (request.result !== undefined) ? true : false; }));
902
- }),
903
- /* The observable will complete */
904
- operators.first());
905
- };
906
- /**
907
- * Connects to `indexedDB` and creates the object store on first time
908
- */
909
- IndexedDBDatabase.prototype.connect = function () {
910
- var _this = this;
911
- var request;
912
- /* Connect to `indexedDB`
913
- * Will fail in Safari cross-origin iframes
914
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42} */
915
- try {
916
- /* Do NOT explicit `window` here, as `indexedDB` could be used from a web worker too */
917
- request = indexedDB.open(this.dbName, this.dbVersion);
918
- }
919
- catch (_a) {
920
- this.database.error(new IDBBrokenError());
921
- return;
922
- }
923
- /* Create store on first connection */
924
- this.createStore(request);
925
- /* Listen to success and error events */
926
- var success$ = rxjs.fromEvent(request, 'success');
927
- var error$ = this.listenError(request);
928
- /* Choose the first to occur */
929
- rxjs.race([success$, error$])
930
- /* The observable will complete */
931
- .pipe(operators.first())
932
- .subscribe({
933
- next: function () {
934
- /* Register the database connection in the `ReplaySubject` for further access */
935
- _this.database.next(request.result);
936
- },
937
- error: function () {
938
- /* Firefox private mode issue: fallback storage if IndexedDb connection is failing
939
- * @see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=781982}
940
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/26} */
941
- _this.database.error(new IDBBrokenError());
942
- },
943
- });
944
- };
945
- /**
946
- * Create store on first use of `indexedDB`
947
- * @param request `indexedDB` database opening request
948
- */
949
- IndexedDBDatabase.prototype.createStore = function (request) {
950
- var _this = this;
951
- /* Listen to the event fired on first connection */
952
- rxjs.fromEvent(request, 'upgradeneeded')
953
- /* The observable will complete */
954
- .pipe(operators.first())
955
- .subscribe({
956
- next: function () {
957
- /* Check if the store already exists, to avoid error */
958
- if (!request.result.objectStoreNames.contains(_this.storeName)) {
959
- /* Create the object store */
960
- request.result.createObjectStore(_this.storeName);
961
- }
962
- }
963
- });
964
- };
965
- /**
966
- * Open an `indexedDB` transaction and get our store
967
- * @param mode `readonly` or `readwrite`
968
- * @returns An `indexedDB` transaction store and events, wrapped in an RxJS `Observable`
969
- */
970
- IndexedDBDatabase.prototype.transaction = function (mode) {
971
- var _this = this;
972
- /* From the `indexedDB` connection, open a transaction and get the store */
973
- return this.database
974
- .pipe(operators.mergeMap(function (database) {
975
- var transaction;
976
- try {
977
- transaction = database.transaction([_this.storeName], mode);
978
- }
979
- catch (error) {
980
- /* The store could have been deleted from outside */
981
- return rxjs.throwError(error);
982
- }
983
- /* Get the store from the transaction */
984
- var store = transaction.objectStore(_this.storeName);
985
- /* Listen transaction `complete` and `error` events */
986
- var events = _this.listenTransactionEvents(transaction);
987
- return rxjs.of({ store: store, events: events });
988
- }));
989
- };
990
- /**
991
- * Listen errors on a transaction or request, and throw if trigerred
992
- * @param transactionOrRequest `indexedDb` transaction or request to listen
993
- * @returns An `Observable` listening to errors
994
- */
995
- IndexedDBDatabase.prototype.listenError = function (transactionOrRequest) {
996
- return rxjs.fromEvent(transactionOrRequest, 'error').pipe(
997
- /* Throw on error to be able to catch errors in RxJS way.
998
- * Here `event.target` must be used, as `transactionOrRequest.error` will be `null`
999
- * if we are on the request and the error is only triggered later by the transaction */
1000
- operators.mergeMap(function (event) { return rxjs.throwError(event.target.error); }));
1001
- };
1002
- /**
1003
- * Listen transaction `complete` and `error` events
1004
- * @param transaction Transaction to listen
1005
- * @returns An `Observable` listening to transaction `complete` and `error` events
1006
- */
1007
- IndexedDBDatabase.prototype.listenTransactionEvents = function (transaction) {
1008
- /* Listen to the `complete` event */
1009
- var complete$ = rxjs.fromEvent(transaction, 'complete');
1010
- /* Listen to the `error` event */
1011
- var error$ = this.listenError(transaction);
1012
- /* Choose the first event to occur */
1013
- return rxjs.race([complete$, error$]);
1014
- };
1015
- return IndexedDBDatabase;
1016
- }());
1017
- IndexedDBDatabase.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: IndexedDBDatabase, deps: [{ token: IDB_DB_NAME }, { token: IDB_STORE_NAME }, { token: IDB_DB_VERSION }, { token: IDB_NO_WRAP }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1018
- IndexedDBDatabase.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: IndexedDBDatabase, providedIn: 'root' });
1019
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: IndexedDBDatabase, decorators: [{
1020
- type: i0.Injectable,
1021
- args: [{
1022
- providedIn: 'root'
1023
- }]
1024
- }], ctorParameters: function () {
1025
- return [{ type: undefined, decorators: [{
1026
- type: i0.Inject,
1027
- args: [IDB_DB_NAME]
1028
- }] }, { type: undefined, decorators: [{
1029
- type: i0.Inject,
1030
- args: [IDB_STORE_NAME]
1031
- }] }, { type: undefined, decorators: [{
1032
- type: i0.Inject,
1033
- args: [IDB_DB_VERSION]
1034
- }] }, { type: undefined, decorators: [{
1035
- type: i0.Inject,
1036
- args: [IDB_NO_WRAP]
1037
- }] }];
1038
- } });
1039
-
1040
- var LocalStorageDatabase = /** @class */ (function () {
1041
- /**
1042
- * Constructor params are provided by Angular (but can also be passed manually in tests)
1043
- * @param prefix Prefix option to avoid collision for multiple apps on the same subdomain or for interoperability
1044
- */
1045
- function LocalStorageDatabase(prefix) {
1046
- if (prefix === void 0) { prefix = ''; }
1047
- /* Prefix if asked, or no prefix otherwise */
1048
- this.prefix = prefix || '';
1049
- }
1050
- Object.defineProperty(LocalStorageDatabase.prototype, "size", {
1051
- /**
1052
- * Number of items in `localStorage`
1053
- */
1054
- get: function () {
1055
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1056
- return rxjs.of(localStorage.length);
1057
- },
1058
- enumerable: false,
1059
- configurable: true
1060
- });
1061
- /**
1062
- * Gets an item value in `localStorage`
1063
- * @param key The item's key
1064
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
1065
- */
1066
- LocalStorageDatabase.prototype.get = function (key) {
1067
- /* Get raw data */
1068
- var unparsedData = localStorage.getItem(this.prefixKey(key));
1069
- var parsedData;
1070
- /* No need to parse if data is `null` or `undefined` */
1071
- if ((unparsedData !== undefined) && (unparsedData !== null)) {
1072
- /* Try to parse */
1073
- try {
1074
- parsedData = JSON.parse(unparsedData);
1075
- }
1076
- catch (error) {
1077
- return rxjs.throwError(error);
1078
- }
1079
- }
1080
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1081
- return rxjs.of(parsedData);
1082
- };
1083
- /**
1084
- * Store an item in `localStorage`
1085
- * @param key The item's key
1086
- * @param data The item's value
1087
- * @returns A RxJS `Observable` to wait the end of the operation
1088
- */
1089
- LocalStorageDatabase.prototype.set = function (key, data) {
1090
- var serializedData = null;
1091
- /* Check if data can be serialized */
1092
- var dataPrototype = Object.getPrototypeOf(data);
1093
- if ((typeof data === 'object') && (data !== null) && !Array.isArray(data) &&
1094
- !((dataPrototype === Object.prototype) || (dataPrototype === null))) {
1095
- return rxjs.throwError(new SerializationError());
1096
- }
1097
- /* Try to stringify (can fail on circular references) */
1098
- try {
1099
- serializedData = JSON.stringify(data);
1100
- }
1101
- catch (error) {
1102
- return rxjs.throwError(error);
1103
- }
1104
- /* Can fail if storage quota is exceeded */
1105
- try {
1106
- localStorage.setItem(this.prefixKey(key), serializedData);
1107
- }
1108
- catch (error) {
1109
- return rxjs.throwError(error);
1110
- }
1111
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1112
- return rxjs.of(undefined);
1113
- };
1114
- /**
1115
- * Deletes an item in `localStorage`
1116
- * @param key The item's key
1117
- * @returns A RxJS `Observable` to wait the end of the operation
1118
- */
1119
- LocalStorageDatabase.prototype.delete = function (key) {
1120
- localStorage.removeItem(this.prefixKey(key));
1121
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1122
- return rxjs.of(undefined);
1123
- };
1124
- /**
1125
- * Deletes all items in `localStorage`
1126
- * @returns A RxJS `Observable` to wait the end of the operation
1127
- */
1128
- LocalStorageDatabase.prototype.clear = function () {
1129
- localStorage.clear();
1130
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1131
- return rxjs.of(undefined);
1132
- };
1133
- /**
1134
- * Get all keys in `localStorage`
1135
- * Note the order of the keys may be inconsistent in Firefox
1136
- * @returns A RxJS `Observable` iterating on keys
1137
- */
1138
- LocalStorageDatabase.prototype.keys = function () {
1139
- var _this = this;
1140
- /* Create an `Observable` from keys */
1141
- return new rxjs.Observable(function (subscriber) {
1142
- /* Iteretate over all the indexes */
1143
- for (var index = 0; index < localStorage.length; index += 1) {
1144
- /* Cast as we are sure in this case the key is not `null` */
1145
- subscriber.next(_this.getUnprefixedKey(index));
1146
- }
1147
- subscriber.complete();
1148
- }).pipe(
1149
- /* Required to work like other databases which are asynchronous */
1150
- operators.observeOn(rxjs.asyncScheduler));
1151
- };
1152
- /**
1153
- * Check if a key exists in `localStorage`
1154
- * @param key The item's key
1155
- * @returns A RxJS `Observable` telling if the key exists or not
1156
- */
1157
- LocalStorageDatabase.prototype.has = function (key) {
1158
- /* Itérate over all indexes in storage */
1159
- for (var index = 0; index < localStorage.length; index += 1) {
1160
- if (key === this.getUnprefixedKey(index)) {
1161
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1162
- return rxjs.of(true);
1163
- }
1164
- }
1165
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1166
- return rxjs.of(false);
1167
- };
1168
- /**
1169
- * Get an unprefixed key
1170
- * @param index Index of the key
1171
- * @returns The unprefixed key name if exists, `null` otherwise
1172
- */
1173
- LocalStorageDatabase.prototype.getUnprefixedKey = function (index) {
1174
- /* Get the key in storage: may have a prefix */
1175
- var prefixedKey = localStorage.key(index);
1176
- if (prefixedKey !== null) {
1177
- /* If no prefix, the key is already good, otherwrite strip the prefix */
1178
- return !this.prefix ? prefixedKey : prefixedKey.substr(this.prefix.length);
1179
- }
1180
- return null;
1181
- };
1182
- /**
1183
- * Add the prefix to a key
1184
- * @param key The key name
1185
- * @returns The prefixed key name
1186
- */
1187
- LocalStorageDatabase.prototype.prefixKey = function (key) {
1188
- return "" + this.prefix + key;
1189
- };
1190
- return LocalStorageDatabase;
1191
- }());
1192
- LocalStorageDatabase.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorageDatabase, deps: [{ token: LS_PREFIX }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1193
- LocalStorageDatabase.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorageDatabase, providedIn: 'root' });
1194
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorageDatabase, decorators: [{
1195
- type: i0.Injectable,
1196
- args: [{
1197
- providedIn: 'root'
1198
- }]
1199
- }], ctorParameters: function () {
1200
- return [{ type: undefined, decorators: [{
1201
- type: i0.Inject,
1202
- args: [LS_PREFIX]
1203
- }] }];
1204
- } });
1205
-
1206
- var MemoryDatabase = /** @class */ (function () {
1207
- function MemoryDatabase() {
1208
- /**
1209
- * Memory storage
1210
- */
1211
- this.memoryStorage = new Map();
1212
- }
1213
- Object.defineProperty(MemoryDatabase.prototype, "size", {
1214
- /**
1215
- * Number of items in memory
1216
- */
1217
- get: function () {
1218
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1219
- return rxjs.of(this.memoryStorage.size);
1220
- },
1221
- enumerable: false,
1222
- configurable: true
1223
- });
1224
- /**
1225
- * Gets an item value in memory
1226
- * @param key The item's key
1227
- * @returns The item's value if the key exists, `undefined` otherwise, wrapped in a RxJS `Observable`
1228
- */
1229
- MemoryDatabase.prototype.get = function (key) {
1230
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1231
- return rxjs.of(this.memoryStorage.get(key));
1232
- };
1233
- /**
1234
- * Sets an item in memory
1235
- * @param key The item's key
1236
- * @param data The item's value
1237
- * @returns A RxJS `Observable` to wait the end of the operation
1238
- */
1239
- MemoryDatabase.prototype.set = function (key, data) {
1240
- this.memoryStorage.set(key, data);
1241
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1242
- return rxjs.of(undefined);
1243
- };
1244
- /**
1245
- * Deletes an item in memory
1246
- * @param key The item's key
1247
- * @returns A RxJS `Observable` to wait the end of the operation
1248
- */
1249
- MemoryDatabase.prototype.delete = function (key) {
1250
- this.memoryStorage.delete(key);
1251
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1252
- return rxjs.of(undefined);
1253
- };
1254
- /**
1255
- * Deletes all items in memory
1256
- * @returns A RxJS `Observable` to wait the end of the operation
1257
- */
1258
- MemoryDatabase.prototype.clear = function () {
1259
- this.memoryStorage.clear();
1260
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1261
- return rxjs.of(undefined);
1262
- };
1263
- /**
1264
- * Get all keys in memory
1265
- * @returns A RxJS `Observable` iterating on keys
1266
- */
1267
- MemoryDatabase.prototype.keys = function () {
1268
- /* Create an `Observable` from keys */
1269
- return rxjs.from(this.memoryStorage.keys());
1270
- };
1271
- /**
1272
- * Check if a key exists in memory
1273
- * @param key Key name
1274
- * @returns a RxJS `Observable` telling if the key exists or not
1275
- */
1276
- MemoryDatabase.prototype.has = function (key) {
1277
- /* Wrap in a RxJS `Observable` to be consistent with other storages */
1278
- return rxjs.of(this.memoryStorage.has(key));
1279
- };
1280
- return MemoryDatabase;
1281
- }());
1282
- MemoryDatabase.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: MemoryDatabase, deps: [], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1283
- MemoryDatabase.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: MemoryDatabase, providedIn: 'root' });
1284
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: MemoryDatabase, decorators: [{
1285
- type: i0.Injectable,
1286
- args: [{
1287
- providedIn: 'root'
1288
- }]
1289
- }] });
1290
-
1291
- /**
1292
- * Factory to create a storage according to browser support
1293
- * @param platformId Context about the platform (`browser`, `server`...)
1294
- * @param LSPrefix Prefix for `localStorage` keys to avoid collision for multiple apps on the same subdomain
1295
- * @param IDBDBName `indexedDB` database name
1296
- * @param IDBstoreName `indexedDB` storeName name
1297
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/BROWSERS_SUPPORT.md}
1298
- */
1299
- function localDatabaseFactory(platformId, LSPrefix, IDBDBName, IDBStoreName, IDBDBVersion, IDBNoWrap) {
1300
- /* When storage is fully disabled in browser (via the "Block all cookies" option),
1301
- * just trying to check `indexedDB` or `localStorage` variables causes a security exception.
1302
- * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
1303
- */
1304
- try {
1305
- // Do not explicit `window` here, as the global object is not the same in web workers
1306
- if (common.isPlatformBrowser(platformId) && (indexedDB !== undefined) && (indexedDB !== null) && ('open' in indexedDB)) {
1307
- /* Check:
1308
- * - if we are in a browser context (issue: server-side rendering)
1309
- * - it could exist but be `undefined` or `null` (issue: IE private mode)
1310
- * - it could exists but not having a working API
1311
- * Will be the case for:
1312
- * - All other browsers in normal mode
1313
- * - Chromium / Safari private mode, but in this case, data will be swiped when the user leaves the app */
1314
- return new IndexedDBDatabase(IDBDBName, IDBStoreName, IDBDBVersion, IDBNoWrap);
1315
- }
1316
- else if (common.isPlatformBrowser(platformId)
1317
- && (localStorage !== undefined) && (localStorage !== null) && ('getItem' in localStorage)) {
1318
- /* Check:
1319
- * - if we are in a browser context (issue: server-side rendering)
1320
- * - if `localStorage` exists (to be sure)
1321
- * - it could exists but not having a working API
1322
- * Will be the case for:
1323
- * - Safari cross-origin iframes, detected later in `IndexedDBDatabase.connect()`
1324
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/issues/42}
1325
- * - IE / Firefox private mode, but in this case, data will be swiped when the user leaves the app
1326
- * For Firefox, can only be detected later in `IndexedDBDatabase.connect()`
1327
- * @see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=781982}
1328
- */
1329
- return new LocalStorageDatabase(LSPrefix);
1330
- }
1331
- }
1332
- catch (_a) {
1333
- // Nothing to do
1334
- }
1335
- /* Will be the case for:
1336
- * - In browsers if storage has been fully disabled (via the "Block all cookies" option)
1337
- * - Server-side rendering
1338
- * - All other non-browser context
1339
- */
1340
- return new MemoryDatabase();
1341
- }
1342
- var LocalDatabase = /** @class */ (function () {
1343
- function LocalDatabase() {
1344
- }
1345
- return LocalDatabase;
1346
- }());
1347
- LocalDatabase.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalDatabase, deps: [], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1348
- LocalDatabase.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalDatabase, providedIn: 'root', useFactory: localDatabaseFactory, deps: [{ token: i0.PLATFORM_ID }, { token: LS_PREFIX }, { token: IDB_DB_NAME }, { token: IDB_STORE_NAME }, { token: IDB_DB_VERSION }, { token: IDB_NO_WRAP }] });
1349
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalDatabase, decorators: [{
1350
- type: i0.Injectable,
1351
- args: [{
1352
- providedIn: 'root',
1353
- useFactory: localDatabaseFactory,
1354
- deps: [
1355
- i0.PLATFORM_ID,
1356
- LS_PREFIX,
1357
- IDB_DB_NAME,
1358
- IDB_STORE_NAME,
1359
- IDB_DB_VERSION,
1360
- IDB_NO_WRAP,
1361
- ]
1362
- }]
1363
- }] });
1364
-
1365
- /**
1366
- * Exception message when a value is not valid against the JSON schema
1367
- */
1368
- var VALIDATION_ERROR = "Data stored is not valid against the provided JSON schema.\nCheck your JSON schema, otherwise it means data has been corrupted.";
1369
- /**
1370
- * Exception raised when a value is not valid against the JSON schema
1371
- */
1372
- var ValidationError = /** @class */ (function (_super) {
1373
- __extends(ValidationError, _super);
1374
- function ValidationError() {
1375
- var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
1376
- _this.message = VALIDATION_ERROR;
1377
- return _this;
1378
- }
1379
- return ValidationError;
1380
- }(Error));
1381
-
1382
- var StorageMap = /** @class */ (function () {
1383
- /**
1384
- * Constructor params are provided by Angular (but can also be passed manually in tests)
1385
- * @param database Storage to use
1386
- * @param jsonValidator Validator service
1387
- * @param LSPrefix Prefix for `localStorage` keys to avoid collision for multiple apps on the same subdomain or for interoperability
1388
- */
1389
- function StorageMap(database, jsonValidator, LSPrefix) {
1390
- if (jsonValidator === void 0) { jsonValidator = new JSONValidator(); }
1391
- if (LSPrefix === void 0) { LSPrefix = ''; }
1392
- this.database = database;
1393
- this.jsonValidator = jsonValidator;
1394
- this.LSPrefix = LSPrefix;
1395
- this.notifiers = new Map();
1396
- }
1397
- Object.defineProperty(StorageMap.prototype, "size", {
1398
- /**
1399
- * **Number of items** in storage, wrapped in an `Observable`.
1400
- *
1401
- * @example
1402
- * this.storageMap.size.subscribe((size) => {
1403
- * console.log(size);
1404
- * });
1405
- */
1406
- get: function () {
1407
- var _this = this;
1408
- return this.database.size
1409
- /* Catch if `indexedDb` is broken */
1410
- .pipe(this.catchIDBBroken(function () { return _this.database.size; }));
1411
- },
1412
- enumerable: false,
1413
- configurable: true
1414
- });
1415
- Object.defineProperty(StorageMap.prototype, "backingEngine", {
1416
- /**
1417
- * Tells you which storage engine is used. *Only useful for interoperability.*
1418
- * Note that due to some browsers issues in some special contexts
1419
- * (Firefox private mode and Safari cross-origin iframes),
1420
- * **this information may be wrong at initialization,**
1421
- * as the storage could fallback from `indexedDB` to `localStorage`
1422
- * only after a first read or write operation.
1423
- * @returns Storage engine used
1424
- *
1425
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1426
- *
1427
- * @example
1428
- * if (this.storageMap.backingEngine === 'indexedDB') {}
1429
- */
1430
- get: function () {
1431
- if (this.database instanceof IndexedDBDatabase) {
1432
- return 'indexedDB';
1433
- }
1434
- else if (this.database instanceof LocalStorageDatabase) {
1435
- return 'localStorage';
1436
- }
1437
- else if (this.database instanceof MemoryDatabase) {
1438
- return 'memory';
1439
- }
1440
- else {
1441
- return 'unknown';
1442
- }
1443
- },
1444
- enumerable: false,
1445
- configurable: true
1446
- });
1447
- Object.defineProperty(StorageMap.prototype, "backingStore", {
1448
- /**
1449
- * Info about `indexedDB` database. *Only useful for interoperability.*
1450
- * @returns `indexedDB` database name, store name and database version.
1451
- * **Values will be empty if the storage is not `indexedDB`,**
1452
- * **so it should be used after an engine check**.
1453
- *
1454
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1455
- *
1456
- * @example
1457
- * if (this.storageMap.backingEngine === 'indexedDB') {
1458
- * const { database, store, version } = this.storageMap.backingStore;
1459
- * }
1460
- */
1461
- get: function () {
1462
- return (this.database instanceof IndexedDBDatabase) ?
1463
- this.database.backingStore :
1464
- { database: '', store: '', version: 0 };
1465
- },
1466
- enumerable: false,
1467
- configurable: true
1468
- });
1469
- Object.defineProperty(StorageMap.prototype, "fallbackBackingStore", {
1470
- /**
1471
- * Info about `localStorage` fallback storage. *Only useful for interoperability.*
1472
- * @returns `localStorage` prefix.
1473
- * **Values will be empty if the storage is not `localStorage`,**
1474
- * **so it should be used after an engine check**.
1475
- *
1476
- * @see {@link https://github.com/cyrilletuzi/angular-async-local-storage/blob/main/docs/INTEROPERABILITY.md}
1477
- *
1478
- * @example
1479
- * if (this.storageMap.backingEngine === 'localStorage') {
1480
- * const { prefix } = this.storageMap.fallbackBackingStore;
1481
- * }
1482
- */
1483
- get: function () {
1484
- return (this.database instanceof LocalStorageDatabase) ?
1485
- { prefix: this.database.prefix } :
1486
- { prefix: '' };
1487
- },
1488
- enumerable: false,
1489
- configurable: true
1490
- });
1491
- StorageMap.prototype.get = function (key, schema) {
1492
- var _this = this;
1493
- /* Get the data in storage */
1494
- return this.database.get(key).pipe(
1495
- /* Check if `indexedDb` is broken */
1496
- this.catchIDBBroken(function () { return _this.database.get(key); }), operators.mergeMap(function (data) {
1497
- /* No need to validate if the data is empty */
1498
- if ((data === undefined) || (data === null)) {
1499
- return rxjs.of(undefined);
1500
- }
1501
- else if (schema) {
1502
- /* Validate data against a JSON schema if provided */
1503
- if (!_this.jsonValidator.validate(data, schema)) {
1504
- return rxjs.throwError(new ValidationError());
1505
- }
1506
- /* Data have been checked, so it's OK to cast */
1507
- return rxjs.of(data);
1508
- }
1509
- /* Cast to unknown as the data wasn't checked */
1510
- return rxjs.of(data);
1511
- }));
1512
- };
1513
- /**
1514
- * Set an item in storage.
1515
- * Note that setting `null` or `undefined` will remove the item to avoid some browsers issues.
1516
- * @param key The item's key
1517
- * @param data The item's value
1518
- * @param schema Optional JSON schema to validate the data
1519
- * @returns A RxJS `Observable` to wait the end of the operation
1520
- *
1521
- * @example
1522
- * this.storageMap.set('key', 'value').subscribe(() => {});
1523
- */
1524
- StorageMap.prototype.set = function (key, data, schema) {
1525
- var _this = this;
1526
- /* Storing `undefined` or `null` is useless and can cause issues in `indexedDb` in some browsers,
1527
- * so removing item instead for all storages to have a consistent API */
1528
- if ((data === undefined) || (data === null)) {
1529
- return this.delete(key);
1530
- }
1531
- /* Validate data against a JSON schema if provided */
1532
- if (schema && !this.jsonValidator.validate(data, schema)) {
1533
- return rxjs.throwError(new ValidationError());
1534
- }
1535
- return this.database.set(key, data).pipe(
1536
- /* Catch if `indexedDb` is broken */
1537
- this.catchIDBBroken(function () { return _this.database.set(key, data); }),
1538
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1539
- operators.tap(function () { _this.notify(key, data); }));
1540
- };
1541
- /**
1542
- * Delete an item in storage
1543
- * @param key The item's key
1544
- * @returns A RxJS `Observable` to wait the end of the operation
1545
- *
1546
- * @example
1547
- * this.storageMap.delete('key').subscribe(() => {});
1548
- */
1549
- StorageMap.prototype.delete = function (key) {
1550
- var _this = this;
1551
- return this.database.delete(key).pipe(
1552
- /* Catch if `indexedDb` is broken */
1553
- this.catchIDBBroken(function () { return _this.database.delete(key); }),
1554
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1555
- operators.tap(function () { _this.notify(key, undefined); }));
1556
- };
1557
- /**
1558
- * Delete all items in storage
1559
- * @returns A RxJS `Observable` to wait the end of the operation
1560
- *
1561
- * @example
1562
- * this.storageMap.clear().subscribe(() => {});
1563
- */
1564
- StorageMap.prototype.clear = function () {
1565
- var _this = this;
1566
- return this.database.clear().pipe(
1567
- /* Catch if `indexedDb` is broken */
1568
- this.catchIDBBroken(function () { return _this.database.clear(); }),
1569
- /* Notify watchers (must be last because it should only happen if the operation succeeds) */
1570
- operators.tap(function () {
1571
- var e_1, _b;
1572
- try {
1573
- for (var _c = __values(_this.notifiers.keys()), _d = _c.next(); !_d.done; _d = _c.next()) {
1574
- var key = _d.value;
1575
- _this.notify(key, undefined);
1576
- }
1577
- }
1578
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1579
- finally {
1580
- try {
1581
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1582
- }
1583
- finally { if (e_1) throw e_1.error; }
1584
- }
1585
- }));
1586
- };
1587
- /**
1588
- * Get all keys stored in storage. Note **this is an *iterating* `Observable`**:
1589
- * * if there is no key, the `next` callback will not be invoked,
1590
- * * if you need to wait the whole operation to end, be sure to act in the `complete` callback,
1591
- * as this `Observable` can emit several values and so will invoke the `next` callback several times.
1592
- * @returns A list of the keys wrapped in a RxJS `Observable`
1593
- *
1594
- * @example
1595
- * this.storageMap.keys().subscribe({
1596
- * next: (key) => { console.log(key); },
1597
- * complete: () => { console.log('Done'); },
1598
- * });
1599
- */
1600
- StorageMap.prototype.keys = function () {
1601
- var _this = this;
1602
- return this.database.keys()
1603
- /* Catch if `indexedDb` is broken */
1604
- .pipe(this.catchIDBBroken(function () { return _this.database.keys(); }));
1605
- };
1606
- /**
1607
- * Tells if a key exists in storage
1608
- * @returns A RxJS `Observable` telling if the key exists
1609
- *
1610
- * @example
1611
- * this.storageMap.has('key').subscribe((hasKey) => {
1612
- * if (hasKey) {}
1613
- * });
1614
- */
1615
- StorageMap.prototype.has = function (key) {
1616
- var _this = this;
1617
- return this.database.has(key)
1618
- /* Catch if `indexedDb` is broken */
1619
- .pipe(this.catchIDBBroken(function () { return _this.database.has(key); }));
1620
- };
1621
- StorageMap.prototype.watch = function (key, schema) {
1622
- /* Check if there is already a notifier */
1623
- if (!this.notifiers.has(key)) {
1624
- this.notifiers.set(key, new rxjs.ReplaySubject(1));
1625
- }
1626
- /* Non-null assertion is required because TypeScript doesn't narrow `.has()` yet */
1627
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1628
- var notifier = this.notifiers.get(key);
1629
- /* Get the current item value */
1630
- (schema ? this.get(key, schema) : this.get(key)).subscribe({
1631
- next: function (result) { return notifier.next(result); },
1632
- error: function (error) { return notifier.error(error); },
1633
- });
1634
- /* Only the public API of the `Observable` should be returned */
1635
- return (schema ?
1636
- notifier.asObservable() :
1637
- notifier.asObservable());
1638
- };
1639
- /**
1640
- * Notify when a value changes
1641
- * @param key The item's key
1642
- * @param data The new value
1643
- */
1644
- StorageMap.prototype.notify = function (key, value) {
1645
- var notifier = this.notifiers.get(key);
1646
- if (notifier) {
1647
- notifier.next(value);
1648
- }
1649
- };
1650
- /**
1651
- * RxJS operator to catch if `indexedDB` is broken
1652
- * @param operationCallback Callback with the operation to redo
1653
- */
1654
- StorageMap.prototype.catchIDBBroken = function (operationCallback) {
1655
- var _this = this;
1656
- return operators.catchError(function (error) {
1657
- /* Check if `indexedDB` is broken based on error message (the specific error class seems to be lost in the process) */
1658
- if ((error !== undefined) && (error !== null)
1659
- && (typeof error === 'object') && ('message' in error)
1660
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1661
- && (error.message === IDB_BROKEN_ERROR)) {
1662
- /* When storage is fully disabled in browser (via the "Block all cookies" option),
1663
- * just trying to check `localStorage` variable causes a security exception.
1664
- * Prevents https://github.com/cyrilletuzi/angular-async-local-storage/issues/118
1665
- */
1666
- try {
1667
- if ('getItem' in localStorage) {
1668
- /* Fallback to `localStorage` if available */
1669
- _this.database = new LocalStorageDatabase(_this.LSPrefix);
1670
- }
1671
- else {
1672
- /* Fallback to memory storage otherwise */
1673
- _this.database = new MemoryDatabase();
1674
- }
1675
- }
1676
- catch (_a) {
1677
- /* Fallback to memory storage otherwise */
1678
- _this.database = new MemoryDatabase();
1679
- }
1680
- /* Redo the operation */
1681
- return operationCallback();
1682
- }
1683
- else {
1684
- /* Otherwise, rethrow the error */
1685
- return rxjs.throwError(error);
1686
- }
1687
- });
1688
- };
1689
- return StorageMap;
1690
- }());
1691
- StorageMap.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageMap, deps: [{ token: LocalDatabase }, { token: JSONValidator }, { token: LS_PREFIX }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1692
- StorageMap.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageMap, providedIn: 'root' });
1693
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageMap, decorators: [{
1694
- type: i0.Injectable,
1695
- args: [{
1696
- providedIn: 'root'
1697
- }]
1698
- }], ctorParameters: function () {
1699
- return [{ type: LocalDatabase }, { type: JSONValidator }, { type: undefined, decorators: [{
1700
- type: i0.Inject,
1701
- args: [LS_PREFIX]
1702
- }] }];
1703
- } });
1704
-
1705
- var LocalStorage = /** @class */ (function () {
1706
- /* Use the `StorageMap` service to avoid code duplication */
1707
- function LocalStorage(storageMap) {
1708
- this.storageMap = storageMap;
1709
- }
1710
- Object.defineProperty(LocalStorage.prototype, "length", {
1711
- /**
1712
- * Number of items in storage wrapped in an `Observable`
1713
- *
1714
- * @example
1715
- * this.localStorage.length.subscribe((length) => {
1716
- * console.log(length);
1717
- * });
1718
- */
1719
- get: function () {
1720
- return this.storageMap.size;
1721
- },
1722
- enumerable: false,
1723
- configurable: true
1724
- });
1725
- LocalStorage.prototype.getItem = function (key, schema) {
1726
- if (schema) {
1727
- /* Backward compatibility with version <= 7 */
1728
- schema = ('schema' in schema) ? schema.schema : schema;
1729
- }
1730
- return (schema ? this.storageMap.get(key, schema) : this.storageMap.get(key)).pipe(
1731
- /* Transform `undefined` into `null` to align with `localStorage` API */
1732
- operators.map(function (value) { return (value !== undefined) ? value : null; }));
1733
- };
1734
- /**
1735
- * Set an item in storage.
1736
- * Note that setting `null` or `undefined` will remove the item to avoid some browsers issues.
1737
- * @param key The item's key
1738
- * @param data The item's value
1739
- * @param schema Optional JSON schema to validate the data
1740
- * @returns A RxJS `Observable` to wait the end of the operation
1741
- *
1742
- * @example
1743
- * this.localStorage.set('key', 'value').subscribe(() => {});
1744
- */
1745
- LocalStorage.prototype.setItem = function (key, data, schema) {
1746
- return this.storageMap.set(key, data, schema).pipe(
1747
- /* Transform `undefined` into `true` for backward compatibility with v7 */
1748
- operators.mapTo(true));
1749
- };
1750
- /**
1751
- * Delete an item in storage
1752
- * @param key The item's key
1753
- * @returns A RxJS `Observable` to wait the end of the operation
1754
- *
1755
- * @example
1756
- * this.localStorage.delete('key').subscribe(() => {});
1757
- */
1758
- LocalStorage.prototype.removeItem = function (key) {
1759
- return this.storageMap.delete(key).pipe(
1760
- /* Transform `undefined` into `true` for backward compatibility with v7 */
1761
- operators.mapTo(true));
1762
- };
1763
- /**
1764
- * Delete all items in storage
1765
- * @returns A RxJS `Observable` to wait the end of the operation
1766
- *
1767
- * @example
1768
- * this.localStorage.clear().subscribe(() => {});
1769
- */
1770
- LocalStorage.prototype.clear = function () {
1771
- return this.storageMap.clear().pipe(
1772
- /* Transform `undefined` into `true` for backward compatibility with v7 */
1773
- operators.mapTo(true));
1774
- };
1775
- return LocalStorage;
1776
- }());
1777
- LocalStorage.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorage, deps: [{ token: StorageMap }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
1778
- LocalStorage.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorage, providedIn: 'root' });
1779
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: LocalStorage, decorators: [{
1780
- type: i0.Injectable,
1781
- args: [{
1782
- providedIn: 'root'
1783
- }]
1784
- }], ctorParameters: function () { return [{ type: StorageMap }]; } });
1785
-
1786
- /**
1787
- * This module does not contain anything, it's only useful to provide options via `.forRoot()`.
1788
- */
1789
- var StorageModule = /** @class */ (function () {
1790
- function StorageModule() {
1791
- }
1792
- /**
1793
- * Only useful to provide options, otherwise it does nothing.
1794
- * **Must be used at initialization, ie. in `AppModule`, and must not be loaded again in another module.**
1795
- *
1796
- * @example
1797
- * NgModule({
1798
- * imports: [StorageModule.forRoot({
1799
- * LSPrefix: 'custom_',
1800
- * })]
1801
- * })
1802
- * export class AppModule
1803
- */
1804
- StorageModule.forRoot = function (config) {
1805
- return {
1806
- ngModule: StorageModule,
1807
- providers: [
1808
- config.LSPrefix ? { provide: LS_PREFIX, useValue: config.LSPrefix } : [],
1809
- config.IDBDBName ? { provide: IDB_DB_NAME, useValue: config.IDBDBName } : [],
1810
- config.IDBStoreName ? { provide: IDB_STORE_NAME, useValue: config.IDBStoreName } : [],
1811
- config.IDBDBVersion ? { provide: IDB_DB_VERSION, useValue: config.IDBDBVersion } : [],
1812
- (config.IDBNoWrap === false) ? { provide: IDB_NO_WRAP, useValue: config.IDBNoWrap } : [],
1813
- ],
1814
- };
1815
- };
1816
- return StorageModule;
1817
- }());
1818
- StorageModule.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageModule, deps: [], target: i0__namespace.ɵɵFactoryTarget.NgModule });
1819
- StorageModule.ɵmod = i0__namespace.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageModule });
1820
- StorageModule.ɵinj = i0__namespace.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageModule });
1821
- i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.0", ngImport: i0__namespace, type: StorageModule, decorators: [{
1822
- type: i0.NgModule
1823
- }] });
1824
-
1825
- /*
1826
- * Public API Surface of local-storage
1827
- */
1828
-
1829
- /**
1830
- * Generated bundle index. Do not edit.
1831
- */
1832
-
1833
- exports.JSONValidator = JSONValidator;
1834
- exports.LocalDatabase = LocalDatabase;
1835
- exports.LocalStorage = LocalStorage;
1836
- exports.SERIALIZATION_ERROR = SERIALIZATION_ERROR;
1837
- exports.SerializationError = SerializationError;
1838
- exports.StorageMap = StorageMap;
1839
- exports.StorageModule = StorageModule;
1840
- exports.VALIDATION_ERROR = VALIDATION_ERROR;
1841
- exports.ValidationError = ValidationError;
1842
-
1843
- Object.defineProperty(exports, '__esModule', { value: true });
1844
-
1845
- })));
1846
- //# sourceMappingURL=ngx-pwa-local-storage.umd.js.map