@telperion/reactive-storage 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.build-manifest.json +96 -0
- package/fesm/reactive-storage.mjs +620 -0
- package/fesm/reactive-storage.mjs.map +1 -0
- package/index.cjs +17 -8
- package/index.cjs.map +1 -0
- package/index.d.cts +6 -0
- package/index.d.ts +6 -5
- package/index.js +5 -6
- package/index.js.map +1 -1
- package/json-parse.cjs +5 -3
- package/json-parse.cjs.map +1 -0
- package/json-parse.d.cts +8 -0
- package/json-parse.d.ts +3 -1
- package/json-parse.js +2 -1
- package/json-parse.js.map +1 -1
- package/package.json +70 -31
- package/reactive-cookie-storage.cjs +49 -44
- package/reactive-cookie-storage.cjs.map +1 -0
- package/reactive-cookie-storage.d.cts +77 -0
- package/reactive-cookie-storage.d.ts +48 -40
- package/reactive-cookie-storage.js +40 -35
- package/reactive-cookie-storage.js.map +1 -1
- package/reactive-storage.cjs +127 -74
- package/reactive-storage.cjs.map +1 -0
- package/reactive-storage.d.cts +144 -0
- package/reactive-storage.d.ts +87 -27
- package/reactive-storage.js +84 -31
- package/reactive-storage.js.map +1 -1
- package/reactive-web-local-storage.cjs +31 -8
- package/reactive-web-local-storage.cjs.map +1 -0
- package/reactive-web-local-storage.d.cts +38 -0
- package/reactive-web-local-storage.d.ts +31 -5
- package/reactive-web-local-storage.js +28 -5
- package/reactive-web-local-storage.js.map +1 -1
- package/reactive-web-session-storage.cjs +24 -8
- package/reactive-web-session-storage.cjs.map +1 -0
- package/reactive-web-session-storage.d.cts +31 -0
- package/reactive-web-session-storage.d.ts +24 -5
- package/reactive-web-session-storage.js +21 -5
- package/reactive-web-session-storage.js.map +1 -1
- package/reactive-web-storage.cjs +39 -23
- package/reactive-web-storage.cjs.map +1 -0
- package/reactive-web-storage.d.cts +47 -0
- package/reactive-web-storage.d.ts +28 -10
- package/reactive-web-storage.js +29 -13
- package/reactive-web-storage.js.map +1 -1
- package/regex-parser.cjs +4 -3
- package/regex-parser.cjs.map +1 -0
- package/regex-parser.d.cts +13 -0
- package/regex-parser.d.ts +3 -1
- package/regex-parser.js +2 -1
- package/regex-parser.js.map +1 -1
- package/async-iterator.polyfill.cjs +0 -87
- package/async-iterator.polyfill.d.ts +0 -2
- package/async-iterator.polyfill.js +0 -86
- package/async-iterator.polyfill.js.map +0 -1
|
@@ -1,44 +1,43 @@
|
|
|
1
|
-
var _a;
|
|
2
1
|
import { Subject } from 'rxjs';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { jsonParse } from './json-parse';
|
|
2
|
+
import { makeAsyncIterator } from '@telperion/rx-utils/to-async-iteratable';
|
|
3
|
+
import { ReactiveStorage } from './reactive-storage.js';
|
|
4
|
+
import { jsonParse } from './json-parse.js';
|
|
5
|
+
|
|
6
|
+
var _a;
|
|
6
7
|
/**
|
|
7
|
-
* Reactive
|
|
8
|
-
*
|
|
8
|
+
* Reactive storage on `document.cookie`: for small values the server should see too, or that must expire.
|
|
9
|
+
*
|
|
10
|
+
* Each store is one cookie named `<appName>_<storeName>` (characters other than letters, digits,
|
|
11
|
+
* `_` and `-` become `_`), holding the store as URI-encoded JSON. Every cookie is written with
|
|
12
|
+
* the attributes given in `options`.
|
|
9
13
|
*
|
|
10
|
-
*
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
13
|
-
* -
|
|
14
|
+
* - A cookie is limited to 4000 bytes; a larger write is rejected with an error.
|
|
15
|
+
* - Browsers have no change event for cookies, so only writes made through this instance are observed.
|
|
16
|
+
* Pass the same `linker` to several instances to have each one notified of the others' writes.
|
|
17
|
+
* - `httpOnly` cookies set by the server cannot be read or written from JavaScript.
|
|
14
18
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
19
|
+
* Example usage:
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { ReactiveCookieStorage } from '@telperion/reactive-storage/reactive-cookie-storage';
|
|
17
22
|
*
|
|
18
|
-
*
|
|
23
|
+
* const storage = new ReactiveCookieStorage('my-app', { path: '/', maxAge: 60 * 60 * 24, sameSite: 'strict' });
|
|
19
24
|
*
|
|
20
|
-
*
|
|
21
|
-
* ```
|
|
22
|
-
* // Single instance
|
|
23
|
-
* const storage = new ReactiveCookieStorage('my-app', {
|
|
24
|
-
* path: '/',
|
|
25
|
-
* maxAge: 86400,
|
|
26
|
-
* secure: true,
|
|
27
|
-
* sameSite: 'strict'
|
|
28
|
-
* });
|
|
25
|
+
* await storage.set('consent', 'analytics', true); // cookie my-app_consent, valid for a day
|
|
26
|
+
* ```
|
|
29
27
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* const
|
|
33
|
-
* const
|
|
34
|
-
*
|
|
28
|
+
* Linked instances:
|
|
29
|
+
* ```ts
|
|
30
|
+
* const linker = Symbol('cookies');
|
|
31
|
+
* const header = new ReactiveCookieStorage('my-app', { path: '/' }, linker);
|
|
32
|
+
* const settings = new ReactiveCookieStorage('my-app', { path: '/' }, linker);
|
|
35
33
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');
|
|
34
|
+
* header.get('prefs', 'theme').subscribe(console.log);
|
|
35
|
+
* await settings.set('prefs', 'theme', 'dark'); // header logs "dark"
|
|
39
36
|
* ```
|
|
37
|
+
*
|
|
38
|
+
* @template S - Store name type: a union of string literals restricts the store names you can use
|
|
40
39
|
*/
|
|
41
|
-
|
|
40
|
+
class ReactiveCookieStorage extends ReactiveStorage {
|
|
42
41
|
appName;
|
|
43
42
|
options;
|
|
44
43
|
static #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit
|
|
@@ -52,6 +51,11 @@ export class ReactiveCookieStorage extends ReactiveStorage {
|
|
|
52
51
|
}
|
|
53
52
|
#changes$ = new Subject();
|
|
54
53
|
#linker;
|
|
54
|
+
/**
|
|
55
|
+
* @param appName - Prefix of this app's cookie names: each store is saved as `<appName>_<storeName>`. Defaults to `'app'`
|
|
56
|
+
* @param options - Attributes written with every cookie
|
|
57
|
+
* @param linker - Any truthy value, e.g. a symbol: instances created with the same linker are notified of each other's writes
|
|
58
|
+
*/
|
|
55
59
|
constructor(appName = 'app', options = {}, linker) {
|
|
56
60
|
super();
|
|
57
61
|
this.appName = appName;
|
|
@@ -66,9 +70,8 @@ export class ReactiveCookieStorage extends ReactiveStorage {
|
|
|
66
70
|
}
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
* Call this when you're done using the storage to prevent memory leaks.
|
|
73
|
+
* Releases the instance: unlinks it from its linker group and stops its change stream.
|
|
74
|
+
* Call it when the storage is no longer used, so linked instances do not keep it alive.
|
|
72
75
|
*/
|
|
73
76
|
destroy() {
|
|
74
77
|
// Unregister from linker group
|
|
@@ -87,8 +90,9 @@ export class ReactiveCookieStorage extends ReactiveStorage {
|
|
|
87
90
|
const cookies = this.#getAppCookies();
|
|
88
91
|
return Object.fromEntries(Object.entries(cookies).map(([storeName, value]) => [storeName, _a.#parse(value)]));
|
|
89
92
|
}
|
|
93
|
+
// Prefer an Observable's own async iterator (rxjs 8, or `@telperion/rx-utils/static/async-iterator`)
|
|
90
94
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
91
|
-
[ReactiveStorage.Props.CHANGES] = this.#changes$[Symbol.asyncIterator] ??
|
|
95
|
+
[ReactiveStorage.Props.CHANGES] = this.#changes$[Symbol.asyncIterator]?.() ?? makeAsyncIterator(this.#changes$);
|
|
92
96
|
async [ReactiveStorage.Props.SET](storeName, value) {
|
|
93
97
|
const serialized = JSON.stringify(value);
|
|
94
98
|
const cookieName = this.#getCookieName(storeName);
|
|
@@ -207,4 +211,5 @@ export class ReactiveCookieStorage extends ReactiveStorage {
|
|
|
207
211
|
}
|
|
208
212
|
_a = ReactiveCookieStorage;
|
|
209
213
|
|
|
214
|
+
export { ReactiveCookieStorage };
|
|
210
215
|
//# sourceMappingURL=react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C,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;gBACtB,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC","file":"reactive-cookie-storage.js","sourcesContent":["import { Subject } from 'rxjs';\r\n\r\nimport { ReactiveStorage, ReactiveStorageChangeEvent } from './reactive-storage';\r\nimport { toAsyncIterator } from './async-iterator.polyfill';\r\nimport { jsonParse } from './json-parse';\r\n\r\n/**\r\n * Options for configuring cookie behavior in ReactiveCookieStorage.\r\n */\r\nexport interface ReactiveCookieStorageOptions {\r\n /** URL path where the cookie is valid. Default: '/' */\r\n path?: string;\r\n /** Domain where the cookie is valid. Default: current domain */\r\n domain?: string;\r\n /** Cookie lifetime in seconds. Default: undefined (session cookie) */\r\n maxAge?: number;\r\n /** Absolute expiration date. Default: undefined */\r\n expires?: Date;\r\n /** HTTPS only flag. Default: false */\r\n secure?: boolean;\r\n /** CSRF protection level. Default: 'lax' */\r\n sameSite?: 'strict' | 'lax' | 'none';\r\n}\r\n\r\n/**\r\n * Reactive wrapper for browser cookies.\r\n * Provides RxJS-based reactive API for cookie storage with automatic change detection.\r\n *\r\n * **Important Limitations:**\r\n * - Cookies have a ~4KB size limit per cookie\r\n * - No native change events - use linker to sync multiple instances\r\n * - Cannot access httpOnly cookies set by the server\r\n *\r\n * **Cross-Instance Synchronization:**\r\n * Link multiple instances using any shared value (symbol, string, object, etc.) to automatically sync changes between them.\r\n *\r\n * @template S - Storage store name type\r\n *\r\n * @example\r\n * ```typescript\r\n * // Single instance\r\n * const storage = new ReactiveCookieStorage('my-app', {\r\n * path: '/',\r\n * maxAge: 86400,\r\n * secure: true,\r\n * sameSite: 'strict'\r\n * });\r\n *\r\n * // Multiple linked instances using a symbol\r\n * const linker = Symbol('cookie-sync');\r\n * const storageOne = new ReactiveCookieStorage('my-app', { secure: true }, linker);\r\n * const storageTwo = new ReactiveCookieStorage('my-app', { secure: false }, linker);\r\n * // Changes in storageOne will notify storageTwo and vice versa\r\n *\r\n * // Or use any other value type\r\n * const storageA = new ReactiveCookieStorage('my-app', { secure: true }, 'my-linker');\r\n * const storageB = new ReactiveCookieStorage('my-app', { secure: false }, 'my-linker');\r\n * ```\r\n */\r\nexport class ReactiveCookieStorage<S extends string = string> extends ReactiveStorage<S> {\r\n static readonly #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit\r\n static readonly #LINKERS = new Map<any, Set<ReactiveCookieStorage<any>>>();\r\n\r\n /**\r\n * Safely parse JSON with error handling.\r\n * Returns undefined if parsing fails.\r\n */\r\n static #parse(value: string): any {\r\n return jsonParse(value);\r\n }\r\n\r\n readonly #changes$ = new Subject<ReactiveStorageChangeEvent<S>>();\r\n readonly #linker?: any;\r\n\r\n constructor(\r\n public readonly appName: string = 'app',\r\n private readonly options: ReactiveCookieStorageOptions = {},\r\n linker?: any\r\n ) {\r\n super();\r\n\r\n // Register to linker group if provided\r\n if (linker) {\r\n this.#linker = linker;\r\n if (!ReactiveCookieStorage.#LINKERS.has(linker)) {\r\n ReactiveCookieStorage.#LINKERS.set(linker, new Set());\r\n }\r\n ReactiveCookieStorage.#LINKERS.get(linker)!.add(this);\r\n }\r\n }\r\n\r\n /**\r\n * Destroy the storage instance and cleanup resources.\r\n * Unregisters from linker group and completes the changes subject.\r\n * Call this when you're done using the storage to prevent memory leaks.\r\n */\r\n destroy(): void {\r\n // Unregister from linker group\r\n if (this.#linker) {\r\n const linkedInstances = ReactiveCookieStorage.#LINKERS.get(this.#linker);\r\n if (linkedInstances) {\r\n linkedInstances.delete(this);\r\n if (linkedInstances.size === 0) {\r\n ReactiveCookieStorage.#LINKERS.delete(this.#linker);\r\n }\r\n }\r\n }\r\n\r\n this.#changes$.complete();\r\n }\r\n\r\n protected async [ReactiveStorage.Props.GET_ALL](): Promise<any> {\r\n const cookies = this.#getAppCookies();\r\n\r\n return Object.fromEntries(\r\n Object.entries(cookies).map(([storeName, value]) => [storeName, ReactiveCookieStorage.#parse(value)])\r\n );\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n protected [ReactiveStorage.Props.CHANGES] = (this.#changes$ as any)[Symbol.asyncIterator] ?? toAsyncIterator(this.#changes$);\r\n\r\n protected async [ReactiveStorage.Props.SET](storeName: S, value: unknown): Promise<void> {\r\n const serialized = JSON.stringify(value);\r\n const cookieName = this.#getCookieName(storeName);\r\n\r\n // Validate size before setting\r\n const cookieString = `${cookieName}=${encodeURIComponent(serialized)}`;\r\n this.#validateSize(cookieString);\r\n\r\n this.#setCookie(cookieName, serialized); // Uses instance options\r\n\r\n const event = { storeName, value };\r\n this.#changes$.next(event);\r\n this.#notifyLinkedInstances(event);\r\n }\r\n\r\n protected async [ReactiveStorage.Props.REMOVE](storeName: S): Promise<void> {\r\n const cookieName = this.#getCookieName(storeName);\r\n\r\n // Delete cookie by setting max-age to 0\r\n this.#setCookie(cookieName, '', { maxAge: 0 });\r\n\r\n const event = { storeName, value: undefined };\r\n this.#changes$.next(event);\r\n this.#notifyLinkedInstances(event);\r\n }\r\n\r\n /**\r\n * Convert store name to cookie name by prefixing with app name.\r\n * Sanitizes to only allow alphanumeric, underscore, and hyphen.\r\n */\r\n #getCookieName(storeName: S): string {\r\n return `${this.appName}_${storeName}`.replace(/[^a-zA-Z0-9_-]/g, '_');\r\n }\r\n\r\n /**\r\n * Parse document.cookie string into key-value object.\r\n * Handles decoding of cookie values.\r\n */\r\n #parseCookies(): Record<string, string> {\r\n if (!document.cookie) {\r\n return {};\r\n }\r\n\r\n return Object.fromEntries(\r\n document.cookie\r\n .split('; ')\r\n .filter(Boolean)\r\n .map((cookie) => {\r\n const separatorIndex = cookie.indexOf('=');\r\n if (separatorIndex === -1) {\r\n return [cookie, ''];\r\n }\r\n const name = cookie.slice(0, separatorIndex);\r\n const value = cookie.slice(separatorIndex + 1);\r\n try {\r\n return [name, decodeURIComponent(value)];\r\n } catch {\r\n return [name, value]; // Return raw value if decode fails\r\n }\r\n })\r\n );\r\n }\r\n\r\n /**\r\n * Get all cookies that belong to this app (matching appName prefix).\r\n * Returns object with storeName -> encoded value.\r\n */\r\n #getAppCookies(): Record<string, string> {\r\n const allCookies = this.#parseCookies();\r\n const prefix = `${this.appName}_`;\r\n const appCookies: Record<string, string> = {};\r\n\r\n for (const [cookieName, value] of Object.entries(allCookies)) {\r\n if (cookieName.startsWith(prefix)) {\r\n const storeName = cookieName.slice(prefix.length);\r\n appCookies[storeName] = value;\r\n }\r\n }\r\n\r\n return appCookies;\r\n }\r\n\r\n /**\r\n * Build and set a cookie with the instance's configured options.\r\n * Pass options parameter to override specific settings (e.g., maxAge: 0 to delete).\r\n */\r\n #setCookie(name: string, value: string, overrides: Partial<ReactiveCookieStorageOptions> = {}): void {\r\n const opts = { ...this.options, ...overrides };\r\n let cookie = `${name}=${encodeURIComponent(value)}`;\r\n\r\n if (opts.path !== undefined) cookie += `; path=${opts.path}`;\r\n if (opts.domain) cookie += `; domain=${opts.domain}`;\r\n if (opts.maxAge !== undefined) cookie += `; max-age=${opts.maxAge}`;\r\n if (opts.expires) cookie += `; expires=${opts.expires.toUTCString()}`;\r\n if (opts.secure) cookie += '; secure';\r\n if (opts.sameSite) cookie += `; samesite=${opts.sameSite}`;\r\n\r\n document.cookie = cookie;\r\n }\r\n\r\n /**\r\n * Validate that a cookie string doesn't exceed size limits.\r\n * Throws an error if the cookie is too large.\r\n */\r\n #validateSize(cookieString: string): void {\r\n if (cookieString.length > ReactiveCookieStorage.#MAX_COOKIE_SIZE) {\r\n throw new Error(\r\n `Cookie size (${cookieString.length} bytes) exceeds ${ReactiveCookieStorage.#MAX_COOKIE_SIZE} byte limit. ` +\r\n `Consider using localStorage for larger data or splitting across multiple stores.`\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Notify all other linked storage instances about a change.\r\n * This instance will not be notified (to prevent infinite loops).\r\n */\r\n #notifyLinkedInstances(event: ReactiveStorageChangeEvent<S>): void {\r\n if (!this.#linker) return;\r\n\r\n const linkedInstances = ReactiveCookieStorage.#LINKERS.get(this.#linker);\r\n if (!linkedInstances) return;\r\n\r\n for (const instance of linkedInstances) {\r\n if (instance !== this) {\r\n instance.#changes$.next(event);\r\n }\r\n }\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"reactive-cookie-storage.js","sources":["../../../libs/reactive-storage/src/reactive-cookie-storage.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCG;AACG,MAAO,qBAAiD,SAAQ,eAAkB,CAAA;AAqBpE,IAAA,OAAA;AACC,IAAA,OAAA;AArBnB,IAAA,OAAgB,gBAAgB,GAAG,IAAI,CAAC;AACxC,IAAA,OAAgB,QAAQ,GAAG,IAAI,GAAG,EAAwC;AAE1E;;;AAGG;IACH,OAAO,MAAM,CAAC,KAAa,EAAA;AACzB,QAAA,OAAO,SAAS,CAAC,KAAK,CAAC;IACzB;AAES,IAAA,SAAS,GAAG,IAAI,OAAO,EAAiC;AACxD,IAAA,OAAO;AAEhB;;;;AAIG;AACH,IAAA,WAAA,CACkB,UAAkB,KAAK,EACtB,OAAA,GAAwC,EAAE,EAC3D,MAAY,EAAA;AAEZ,QAAA,KAAK,EAAE;QAJS,IAAA,CAAA,OAAO,GAAP,OAAO;QACN,IAAA,CAAA,OAAO,GAAP,OAAO;;QAMxB,IAAI,MAAM,EAAE;AACV,YAAA,IAAI,CAAC,OAAO,GAAG,MAAM;YACrB,IAAI,CAAC,EAAqB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;gBAC/C,EAAqB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,EAAE,CAAC;YACvD;AACA,YAAA,EAAqB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAE,CAAC,GAAG,CAAC,IAAI,CAAC;QACvD;IACF;AAEA;;;AAGG;IACH,OAAO,GAAA;;AAEL,QAAA,IAAI,IAAI,C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,54 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var tslib = require('tslib');
|
|
4
|
+
var rxjs = require('rxjs');
|
|
5
|
+
var compact = require('@telperion/js-utils/array/compact');
|
|
6
|
+
var remove = require('@telperion/js-utils/array/remove');
|
|
7
|
+
var deepFreeze = require('@telperion/js-utils/object/deep-freeze');
|
|
8
|
+
var shareLast = require('@telperion/rx-utils/operators/share-last');
|
|
9
|
+
var fifoPromise = require('@telperion/ts-utils/fifo-promise');
|
|
10
|
+
|
|
2
11
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
3
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.ReactiveStorage = void 0;
|
|
5
|
-
const tslib_1 = require("tslib");
|
|
6
|
-
const rxjs_1 = require("rxjs");
|
|
7
|
-
const compact_1 = require("@thalesrc/js-utils/array/compact");
|
|
8
|
-
const remove_1 = require("@thalesrc/js-utils/array/remove");
|
|
9
|
-
const deep_freeze_1 = require("@thalesrc/js-utils/object/deep-freeze");
|
|
10
|
-
const share_last_1 = require("@thalesrc/rx-utils/operators/share-last");
|
|
11
|
-
const fifo_promise_1 = require("@thalesrc/ts-utils/fifo-promise");
|
|
12
12
|
const GET_ALL = Symbol('Reactive Storage Get All');
|
|
13
13
|
const CHANGES = Symbol('Reactive Storage Changes');
|
|
14
14
|
const SET = Symbol('Reactive Storage Set');
|
|
15
15
|
const REMOVE = Symbol('Reactive Storage Remove');
|
|
16
16
|
/**
|
|
17
|
-
* Abstract base class
|
|
18
|
-
* Provides RxJS-based reactive API for storage with support for nested property access.
|
|
19
|
-
* All write operations are queued using FIFO promises to ensure consistency.
|
|
17
|
+
* Abstract base class of every reactive storage: the shared `get`/`set`/`patch`/`delete`/`push`/`drop` API.
|
|
20
18
|
*
|
|
21
|
-
*
|
|
19
|
+
* Data is organised in named **stores**: one JSON value per store name (one localStorage key, one cookie).
|
|
20
|
+
* Read and write inside a store with a dot-separated **key path** (`'profile.name'`); an empty key
|
|
21
|
+
* means the whole store.
|
|
22
|
+
*
|
|
23
|
+
* - `get()` returns an Observable that emits the current value right away and again whenever it changes.
|
|
24
|
+
* Repeats of the same value (`===`) are skipped, so a primitive at a path emits only when it changes.
|
|
25
|
+
* - Emitted values are deep-frozen: copy them before changing them.
|
|
26
|
+
* - Writes return a Promise that resolves once subscribers have been notified. Writes from every
|
|
27
|
+
* storage instance run one at a time, first in first out; one that takes longer than a second
|
|
28
|
+
* is rejected with a `TimeoutError`.
|
|
29
|
+
* - Only writes made through the same instance (or, for cookies, linked instances) are observed.
|
|
30
|
+
*
|
|
31
|
+
* Example usage:
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { ReactiveWebLocalStorage } from '@telperion/reactive-storage/reactive-web-local-storage';
|
|
34
|
+
*
|
|
35
|
+
* const storage = new ReactiveWebLocalStorage<'user' | 'settings'>('my-app');
|
|
36
|
+
*
|
|
37
|
+
* storage.get<string>('user', 'profile.name').subscribe((name) => console.log(name));
|
|
38
|
+
* // undefined
|
|
39
|
+
*
|
|
40
|
+
* await storage.set('user', 'profile.name', 'Ada');
|
|
41
|
+
* // Ada
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* @template S - Store name type: a union of string literals restricts the store names you can use
|
|
22
45
|
*/
|
|
23
46
|
class ReactiveStorage {
|
|
24
47
|
static FifoGroup = Symbol();
|
|
25
48
|
static extractData(data, prop = null) {
|
|
26
49
|
if (!prop)
|
|
27
50
|
return data;
|
|
28
|
-
const fragments =
|
|
51
|
+
const fragments = compact.compact(prop.split('.'));
|
|
29
52
|
let value = data;
|
|
30
53
|
do {
|
|
31
54
|
try {
|
|
@@ -41,16 +64,16 @@ class ReactiveStorage {
|
|
|
41
64
|
static Props = { GET_ALL, CHANGES, SET, REMOVE };
|
|
42
65
|
#_stream$ = null;
|
|
43
66
|
#initializeStream() {
|
|
44
|
-
this.#_stream$ =
|
|
67
|
+
this.#_stream$ = rxjs.from(this[GET_ALL]()).pipe(rxjs.switchMap(data => {
|
|
45
68
|
data ??= {};
|
|
46
|
-
return
|
|
69
|
+
return rxjs.from(this[CHANGES]).pipe(rxjs.map(({ storeName, value }) => {
|
|
47
70
|
if (value === undefined)
|
|
48
71
|
delete data[storeName];
|
|
49
72
|
else
|
|
50
73
|
data[storeName] = value;
|
|
51
|
-
return
|
|
52
|
-
}),
|
|
53
|
-
}),
|
|
74
|
+
return deepFreeze.deepFreeze({ ...data });
|
|
75
|
+
}), rxjs.startWith(deepFreeze.deepFreeze({ ...data })));
|
|
76
|
+
}), shareLast.shareLast());
|
|
54
77
|
}
|
|
55
78
|
get #stream$() {
|
|
56
79
|
if (!this.#_stream$)
|
|
@@ -58,21 +81,28 @@ class ReactiveStorage {
|
|
|
58
81
|
return this.#_stream$;
|
|
59
82
|
}
|
|
60
83
|
/**
|
|
61
|
-
*
|
|
62
|
-
* Supports dot notation for nested property access (e.g., 'user.settings.theme').
|
|
84
|
+
* Observable of a store, or of one value inside it, that emits the current value and then every change.
|
|
63
85
|
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
86
|
+
* The value is `undefined` while the store or path does not exist. Emitted values are deep-frozen.
|
|
87
|
+
*
|
|
88
|
+
* Example usage:
|
|
89
|
+
* ```ts
|
|
90
|
+
* storage.get('user').subscribe((user) => console.log(user)); // whole store
|
|
91
|
+
* storage.get<string>('user', 'profile.name').subscribe(console.log); // one value
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @template T - Type of the value at `key`
|
|
95
|
+
* @param storeName - Store to read
|
|
96
|
+
* @param key - Dot-separated path inside the store; empty (default) for the whole store
|
|
97
|
+
* @returns Observable of the value, which never completes
|
|
68
98
|
*/
|
|
69
99
|
get(storeName, key = '') {
|
|
70
|
-
return this.#stream$.pipe(
|
|
100
|
+
return this.#stream$.pipe(rxjs.map(allData => ReactiveStorage.extractData(allData, `${storeName}.${key}`)), rxjs.distinctUntilChanged());
|
|
71
101
|
}
|
|
72
102
|
async #set(storeName, key, value) {
|
|
73
|
-
const store = await
|
|
74
|
-
const storeChangeEvent =
|
|
75
|
-
const paths =
|
|
103
|
+
const store = await rxjs.firstValueFrom(this.get(storeName));
|
|
104
|
+
const storeChangeEvent = rxjs.lastValueFrom(this.get(storeName).pipe(rxjs.take(2)));
|
|
105
|
+
const paths = compact.compact(key.split('.'));
|
|
76
106
|
if (!paths.length) {
|
|
77
107
|
if (value === undefined) {
|
|
78
108
|
await this[REMOVE](storeName);
|
|
@@ -104,12 +134,21 @@ class ReactiveStorage {
|
|
|
104
134
|
return;
|
|
105
135
|
}
|
|
106
136
|
/**
|
|
107
|
-
*
|
|
108
|
-
* Pass undefined as value to remove the property.
|
|
137
|
+
* Writes a value at a path, replacing what was there and creating missing parent objects.
|
|
109
138
|
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
139
|
+
* The value is stored as JSON, so it must be JSON-serializable. Passing `undefined` removes
|
|
140
|
+
* the property (or, with an empty key, the whole store).
|
|
141
|
+
*
|
|
142
|
+
* Example usage:
|
|
143
|
+
* ```ts
|
|
144
|
+
* await storage.set('user', '', { name: 'Ada' }); // whole store
|
|
145
|
+
* await storage.set('user', 'profile.theme', 'dark'); // { name: 'Ada', profile: { theme: 'dark' } }
|
|
146
|
+
* ```
|
|
147
|
+
*
|
|
148
|
+
* @param storeName - Store to write
|
|
149
|
+
* @param key - Dot-separated path inside the store; empty for the whole store
|
|
150
|
+
* @param value - New value; `undefined` removes it
|
|
151
|
+
* @returns Resolves once subscribers have received the new value
|
|
113
152
|
*/
|
|
114
153
|
async set(storeName, key, value) {
|
|
115
154
|
return await this.#set(storeName, key, value);
|
|
@@ -123,28 +162,40 @@ class ReactiveStorage {
|
|
|
123
162
|
* @param value - Partial object to merge with existing value
|
|
124
163
|
*/
|
|
125
164
|
async patch(storeName, key, value) {
|
|
126
|
-
const existing = await
|
|
127
|
-
await this.#set(storeName, key, Object.assign({}, existing,
|
|
165
|
+
const existing = await rxjs.firstValueFrom(this.get(storeName, key));
|
|
166
|
+
await this.#set(storeName, key, Object.assign({}, existing, compact.compact(value)));
|
|
128
167
|
}
|
|
129
168
|
/**
|
|
130
|
-
*
|
|
169
|
+
* Removes a value at a path, or the whole store. Same as `set(storeName, key, undefined)`.
|
|
131
170
|
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
171
|
+
* Example usage:
|
|
172
|
+
* ```ts
|
|
173
|
+
* await storage.delete('user', 'profile.theme'); // one property
|
|
174
|
+
* await storage.delete('user'); // the whole store
|
|
175
|
+
* ```
|
|
176
|
+
*
|
|
177
|
+
* @param storeName - Store to change
|
|
178
|
+
* @param key - Dot-separated path inside the store; empty (default) removes the whole store
|
|
179
|
+
* @returns Resolves once subscribers have been notified
|
|
134
180
|
*/
|
|
135
181
|
async delete(storeName, key = '') {
|
|
136
182
|
return await this.#set(storeName, key, undefined);
|
|
137
183
|
}
|
|
138
184
|
/**
|
|
139
|
-
*
|
|
140
|
-
* Creates array if it doesn't exist.
|
|
185
|
+
* Appends values to the array at a path, creating the array when there is none.
|
|
141
186
|
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
187
|
+
* Example usage:
|
|
188
|
+
* ```ts
|
|
189
|
+
* await storage.push('todos', 'items', 'Buy milk', 'Walk the dog');
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @param storeName - Store to change
|
|
193
|
+
* @param key - Dot-separated path of the array inside the store
|
|
194
|
+
* @param values - Values to append
|
|
195
|
+
* @returns Resolves once subscribers have been notified
|
|
145
196
|
*/
|
|
146
197
|
async push(storeName, key, ...values) {
|
|
147
|
-
const existing = await
|
|
198
|
+
const existing = await rxjs.firstValueFrom(this.get(storeName, key)) ?? [];
|
|
148
199
|
await this.#set(storeName, key, [...existing, ...values]);
|
|
149
200
|
}
|
|
150
201
|
/**
|
|
@@ -155,38 +206,40 @@ class ReactiveStorage {
|
|
|
155
206
|
* @param value - Value to remove from the array
|
|
156
207
|
*/
|
|
157
208
|
async drop(storeName, key, value) {
|
|
158
|
-
const existing = await
|
|
159
|
-
await this.#set(storeName, key,
|
|
209
|
+
const existing = await rxjs.firstValueFrom(this.get(storeName, key));
|
|
210
|
+
await this.#set(storeName, key, remove.remove(existing, value));
|
|
160
211
|
}
|
|
161
212
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
tslib_1.__metadata("design:returntype", Promise)
|
|
213
|
+
tslib.__decorate([
|
|
214
|
+
fifoPromise.FifoPromise({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
|
|
215
|
+
tslib.__metadata("design:type", Function),
|
|
216
|
+
tslib.__metadata("design:paramtypes", [String, String, Object]),
|
|
217
|
+
tslib.__metadata("design:returntype", Promise)
|
|
168
218
|
], ReactiveStorage.prototype, "set", null);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
219
|
+
tslib.__decorate([
|
|
220
|
+
fifoPromise.FifoPromise({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
|
|
221
|
+
tslib.__metadata("design:type", Function),
|
|
222
|
+
tslib.__metadata("design:paramtypes", [String, String, Object]),
|
|
223
|
+
tslib.__metadata("design:returntype", Promise)
|
|
174
224
|
], ReactiveStorage.prototype, "patch", null);
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
225
|
+
tslib.__decorate([
|
|
226
|
+
fifoPromise.FifoPromise({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
|
|
227
|
+
tslib.__metadata("design:type", Function),
|
|
228
|
+
tslib.__metadata("design:paramtypes", [String, Object]),
|
|
229
|
+
tslib.__metadata("design:returntype", Promise)
|
|
180
230
|
], ReactiveStorage.prototype, "delete", null);
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
231
|
+
tslib.__decorate([
|
|
232
|
+
fifoPromise.FifoPromise({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
|
|
233
|
+
tslib.__metadata("design:type", Function),
|
|
234
|
+
tslib.__metadata("design:paramtypes", [String, String, Object]),
|
|
235
|
+
tslib.__metadata("design:returntype", Promise)
|
|
186
236
|
], ReactiveStorage.prototype, "push", null);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
237
|
+
tslib.__decorate([
|
|
238
|
+
fifoPromise.FifoPromise({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
|
|
239
|
+
tslib.__metadata("design:type", Function),
|
|
240
|
+
tslib.__metadata("design:paramtypes", [String, String, Object]),
|
|
241
|
+
tslib.__metadata("design:returntype", Promise)
|
|
192
242
|
], ReactiveStorage.prototype, "drop", null);
|
|
243
|
+
|
|
244
|
+
exports.ReactiveStorage = ReactiveStorage;
|
|
245
|
+
//# sourceMappingURL=reactive-storage.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reactive-storage.cjs","sources":["../../../libs/reactive-storage/src/reactive-storage.ts"],"sourcesContent":[null],"names":["compact","from","switchMap","map","deepFreeze","startWith","shareLast","distinctUntilChanged","firstValueFrom","lastValueFrom","take","remove","__decorate","FifoPromise"],"mappings":";;;;;;;;;;AAAA;AASA,MAAM,OAAO,GAAG,MAAM,CAAC,0BAA0B,CAAC;AAClD,MAAM,OAAO,GAAG,MAAM,CAAC,0BAA0B,CAAC;AAClD,MAAM,GAAG,GAAG,MAAM,CAAC,sBAAsB,CAAC;AAC1C,MAAM,MAAM,GAAG,MAAM,CAAC,yBAAyB,CAAC;AAahD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BG;MACmB,eAAe,CAAA;AAC3B,IAAA,OAAO,SAAS,GAAG,MAAM,EAAE;AAC3B,IAAA,OAAO,WAAW,CAAU,IAAS,EAAE,OAAe,IAAK,EAAA;AACjE,QAAA,IAAI,CAAC,IAAI;A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,EAAA,QAAA,EAAA,IAAA,CAAA;AAgBKD,gBAAA,CAAA;AADL,IAAAC,uBAAW,CAAC,EAAE,KAAK,EAAE,eAAe,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;;;;AAKhE,CAAA,EAAA,eAAA,CAAA,SAAA,EAAA,MAAA,EAAA,IAAA,CAAA;AAUKD,gBAAA,CAAA;AADL,IAAAC,uBAAW,CAAC,EAAE,KAAK,EAAE,eAAe,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;;;;AAKhE,CAAA,EAAA,eAAA,CAAA,SAAA,EAAA,MAAA,EAAA,IAAA,CAAA;;;;"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
|
|
3
|
+
declare const GET_ALL: unique symbol;
|
|
4
|
+
declare const CHANGES: unique symbol;
|
|
5
|
+
declare const SET: unique symbol;
|
|
6
|
+
declare const REMOVE: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* A change to one store, as a storage implementation reports it to {@link ReactiveStorage}.
|
|
9
|
+
* `value` is the store's new content, or `undefined` when the store was removed.
|
|
10
|
+
*
|
|
11
|
+
* @template S - Store name type
|
|
12
|
+
*/
|
|
13
|
+
interface ReactiveStorageChangeEvent<S = string> {
|
|
14
|
+
storeName: S;
|
|
15
|
+
value: any;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Abstract base class of every reactive storage: the shared `get`/`set`/`patch`/`delete`/`push`/`drop` API.
|
|
19
|
+
*
|
|
20
|
+
* Data is organised in named **stores**: one JSON value per store name (one localStorage key, one cookie).
|
|
21
|
+
* Read and write inside a store with a dot-separated **key path** (`'profile.name'`); an empty key
|
|
22
|
+
* means the whole store.
|
|
23
|
+
*
|
|
24
|
+
* - `get()` returns an Observable that emits the current value right away and again whenever it changes.
|
|
25
|
+
* Repeats of the same value (`===`) are skipped, so a primitive at a path emits only when it changes.
|
|
26
|
+
* - Emitted values are deep-frozen: copy them before changing them.
|
|
27
|
+
* - Writes return a Promise that resolves once subscribers have been notified. Writes from every
|
|
28
|
+
* storage instance run one at a time, first in first out; one that takes longer than a second
|
|
29
|
+
* is rejected with a `TimeoutError`.
|
|
30
|
+
* - Only writes made through the same instance (or, for cookies, linked instances) are observed.
|
|
31
|
+
*
|
|
32
|
+
* Example usage:
|
|
33
|
+
* ```ts
|
|
34
|
+
* import { ReactiveWebLocalStorage } from '@telperion/reactive-storage/reactive-web-local-storage';
|
|
35
|
+
*
|
|
36
|
+
* const storage = new ReactiveWebLocalStorage<'user' | 'settings'>('my-app');
|
|
37
|
+
*
|
|
38
|
+
* storage.get<string>('user', 'profile.name').subscribe((name) => console.log(name));
|
|
39
|
+
* // undefined
|
|
40
|
+
*
|
|
41
|
+
* await storage.set('user', 'profile.name', 'Ada');
|
|
42
|
+
* // Ada
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* @template S - Store name type: a union of string literals restricts the store names you can use
|
|
46
|
+
*/
|
|
47
|
+
declare abstract class ReactiveStorage<S extends string = string> {
|
|
48
|
+
#private;
|
|
49
|
+
private static FifoGroup;
|
|
50
|
+
private static extractData;
|
|
51
|
+
static Props: {
|
|
52
|
+
readonly GET_ALL: typeof GET_ALL;
|
|
53
|
+
readonly CHANGES: typeof CHANGES;
|
|
54
|
+
readonly SET: typeof SET;
|
|
55
|
+
readonly REMOVE: typeof REMOVE;
|
|
56
|
+
};
|
|
57
|
+
protected abstract [GET_ALL](): Promise<any>;
|
|
58
|
+
protected abstract [CHANGES]: AsyncGenerator<ReactiveStorageChangeEvent<S>>;
|
|
59
|
+
protected abstract [SET](store: S, value: any): Promise<void>;
|
|
60
|
+
protected abstract [REMOVE](store: S): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Observable of a store, or of one value inside it, that emits the current value and then every change.
|
|
63
|
+
*
|
|
64
|
+
* The value is `undefined` while the store or path does not exist. Emitted values are deep-frozen.
|
|
65
|
+
*
|
|
66
|
+
* Example usage:
|
|
67
|
+
* ```ts
|
|
68
|
+
* storage.get('user').subscribe((user) => console.log(user)); // whole store
|
|
69
|
+
* storage.get<string>('user', 'profile.name').subscribe(console.log); // one value
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @template T - Type of the value at `key`
|
|
73
|
+
* @param storeName - Store to read
|
|
74
|
+
* @param key - Dot-separated path inside the store; empty (default) for the whole store
|
|
75
|
+
* @returns Observable of the value, which never completes
|
|
76
|
+
*/
|
|
77
|
+
get<T = Record<string, any>>(storeName: S, key?: string): Observable<T>;
|
|
78
|
+
/**
|
|
79
|
+
* Writes a value at a path, replacing what was there and creating missing parent objects.
|
|
80
|
+
*
|
|
81
|
+
* The value is stored as JSON, so it must be JSON-serializable. Passing `undefined` removes
|
|
82
|
+
* the property (or, with an empty key, the whole store).
|
|
83
|
+
*
|
|
84
|
+
* Example usage:
|
|
85
|
+
* ```ts
|
|
86
|
+
* await storage.set('user', '', { name: 'Ada' }); // whole store
|
|
87
|
+
* await storage.set('user', 'profile.theme', 'dark'); // { name: 'Ada', profile: { theme: 'dark' } }
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @param storeName - Store to write
|
|
91
|
+
* @param key - Dot-separated path inside the store; empty for the whole store
|
|
92
|
+
* @param value - New value; `undefined` removes it
|
|
93
|
+
* @returns Resolves once subscribers have received the new value
|
|
94
|
+
*/
|
|
95
|
+
set(storeName: S, key: string, value: any): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Merge a partial object into existing value.
|
|
98
|
+
* Only works with object values.
|
|
99
|
+
*
|
|
100
|
+
* @param storeName - Name of the storage store
|
|
101
|
+
* @param key - Property path using dot notation
|
|
102
|
+
* @param value - Partial object to merge with existing value
|
|
103
|
+
*/
|
|
104
|
+
patch(storeName: S, key: string, value: any): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Removes a value at a path, or the whole store. Same as `set(storeName, key, undefined)`.
|
|
107
|
+
*
|
|
108
|
+
* Example usage:
|
|
109
|
+
* ```ts
|
|
110
|
+
* await storage.delete('user', 'profile.theme'); // one property
|
|
111
|
+
* await storage.delete('user'); // the whole store
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* @param storeName - Store to change
|
|
115
|
+
* @param key - Dot-separated path inside the store; empty (default) removes the whole store
|
|
116
|
+
* @returns Resolves once subscribers have been notified
|
|
117
|
+
*/
|
|
118
|
+
delete(storeName: S, key?: string): Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* Appends values to the array at a path, creating the array when there is none.
|
|
121
|
+
*
|
|
122
|
+
* Example usage:
|
|
123
|
+
* ```ts
|
|
124
|
+
* await storage.push('todos', 'items', 'Buy milk', 'Walk the dog');
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* @param storeName - Store to change
|
|
128
|
+
* @param key - Dot-separated path of the array inside the store
|
|
129
|
+
* @param values - Values to append
|
|
130
|
+
* @returns Resolves once subscribers have been notified
|
|
131
|
+
*/
|
|
132
|
+
push(storeName: S, key: string, ...values: any[]): Promise<void>;
|
|
133
|
+
/**
|
|
134
|
+
* Remove a specific value from an array in storage.
|
|
135
|
+
*
|
|
136
|
+
* @param storeName - Name of the storage store
|
|
137
|
+
* @param key - Path to array property using dot notation
|
|
138
|
+
* @param value - Value to remove from the array
|
|
139
|
+
*/
|
|
140
|
+
drop(storeName: S, key: string, value: any): Promise<void>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export { ReactiveStorage };
|
|
144
|
+
export type { ReactiveStorageChangeEvent };
|