@telperion/reactive-storage 1.1.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.
Files changed (57) hide show
  1. package/.build-manifest.json +96 -0
  2. package/README.md +172 -1
  3. package/fesm/reactive-storage.mjs +620 -0
  4. package/fesm/reactive-storage.mjs.map +1 -0
  5. package/index.cjs +17 -7
  6. package/index.cjs.map +1 -0
  7. package/index.d.cts +6 -0
  8. package/index.d.ts +6 -4
  9. package/index.js +5 -5
  10. package/index.js.map +1 -1
  11. package/json-parse.cjs +18 -0
  12. package/json-parse.cjs.map +1 -0
  13. package/json-parse.d.cts +8 -0
  14. package/json-parse.d.ts +8 -0
  15. package/json-parse.js +16 -0
  16. package/json-parse.js.map +1 -0
  17. package/package.json +91 -25
  18. package/reactive-cookie-storage.cjs +217 -0
  19. package/reactive-cookie-storage.cjs.map +1 -0
  20. package/reactive-cookie-storage.d.cts +77 -0
  21. package/reactive-cookie-storage.d.ts +77 -0
  22. package/reactive-cookie-storage.js +215 -0
  23. package/reactive-cookie-storage.js.map +1 -0
  24. package/reactive-storage.cjs +127 -74
  25. package/reactive-storage.cjs.map +1 -0
  26. package/reactive-storage.d.cts +144 -0
  27. package/reactive-storage.d.ts +87 -27
  28. package/reactive-storage.js +84 -31
  29. package/reactive-storage.js.map +1 -1
  30. package/reactive-web-local-storage.cjs +31 -8
  31. package/reactive-web-local-storage.cjs.map +1 -0
  32. package/reactive-web-local-storage.d.cts +38 -0
  33. package/reactive-web-local-storage.d.ts +31 -5
  34. package/reactive-web-local-storage.js +28 -5
  35. package/reactive-web-local-storage.js.map +1 -1
  36. package/reactive-web-session-storage.cjs +24 -8
  37. package/reactive-web-session-storage.cjs.map +1 -0
  38. package/reactive-web-session-storage.d.cts +31 -0
  39. package/reactive-web-session-storage.d.ts +24 -5
  40. package/reactive-web-session-storage.js +21 -5
  41. package/reactive-web-session-storage.js.map +1 -1
  42. package/reactive-web-storage.cjs +41 -29
  43. package/reactive-web-storage.cjs.map +1 -0
  44. package/reactive-web-storage.d.cts +47 -0
  45. package/reactive-web-storage.d.ts +28 -11
  46. package/reactive-web-storage.js +32 -20
  47. package/reactive-web-storage.js.map +1 -1
  48. package/regex-parser.cjs +4 -3
  49. package/regex-parser.cjs.map +1 -0
  50. package/regex-parser.d.cts +13 -0
  51. package/regex-parser.d.ts +3 -1
  52. package/regex-parser.js +2 -1
  53. package/regex-parser.js.map +1 -1
  54. package/async-iterator.polyfill.cjs +0 -87
  55. package/async-iterator.polyfill.d.ts +0 -2
  56. package/async-iterator.polyfill.js +0 -86
  57. package/async-iterator.polyfill.js.map +0 -1
@@ -0,0 +1,215 @@
1
+ import { Subject } from 'rxjs';
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;
7
+ /**
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`.
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.
18
+ *
19
+ * Example usage:
20
+ * ```ts
21
+ * import { ReactiveCookieStorage } from '@telperion/reactive-storage/reactive-cookie-storage';
22
+ *
23
+ * const storage = new ReactiveCookieStorage('my-app', { path: '/', maxAge: 60 * 60 * 24, sameSite: 'strict' });
24
+ *
25
+ * await storage.set('consent', 'analytics', true); // cookie my-app_consent, valid for a day
26
+ * ```
27
+ *
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);
33
+ *
34
+ * header.get('prefs', 'theme').subscribe(console.log);
35
+ * await settings.set('prefs', 'theme', 'dark'); // header logs "dark"
36
+ * ```
37
+ *
38
+ * @template S - Store name type: a union of string literals restricts the store names you can use
39
+ */
40
+ class ReactiveCookieStorage extends ReactiveStorage {
41
+ appName;
42
+ options;
43
+ static #MAX_COOKIE_SIZE = 4000; // Conservative 4KB limit
44
+ static #LINKERS = new Map();
45
+ /**
46
+ * Safely parse JSON with error handling.
47
+ * Returns undefined if parsing fails.
48
+ */
49
+ static #parse(value) {
50
+ return jsonParse(value);
51
+ }
52
+ #changes$ = new Subject();
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
+ */
59
+ constructor(appName = 'app', options = {}, linker) {
60
+ super();
61
+ this.appName = appName;
62
+ this.options = options;
63
+ // Register to linker group if provided
64
+ if (linker) {
65
+ this.#linker = linker;
66
+ if (!_a.#LINKERS.has(linker)) {
67
+ _a.#LINKERS.set(linker, new Set());
68
+ }
69
+ _a.#LINKERS.get(linker).add(this);
70
+ }
71
+ }
72
+ /**
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.
75
+ */
76
+ destroy() {
77
+ // Unregister from linker group
78
+ if (this.#linker) {
79
+ const linkedInstances = _a.#LINKERS.get(this.#linker);
80
+ if (linkedInstances) {
81
+ linkedInstances.delete(this);
82
+ if (linkedInstances.size === 0) {
83
+ _a.#LINKERS.delete(this.#linker);
84
+ }
85
+ }
86
+ }
87
+ this.#changes$.complete();
88
+ }
89
+ async [ReactiveStorage.Props.GET_ALL]() {
90
+ const cookies = this.#getAppCookies();
91
+ return Object.fromEntries(Object.entries(cookies).map(([storeName, value]) => [storeName, _a.#parse(value)]));
92
+ }
93
+ // Prefer an Observable's own async iterator (rxjs 8, or `@telperion/rx-utils/static/async-iterator`)
94
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
95
+ [ReactiveStorage.Props.CHANGES] = this.#changes$[Symbol.asyncIterator]?.() ?? makeAsyncIterator(this.#changes$);
96
+ async [ReactiveStorage.Props.SET](storeName, value) {
97
+ const serialized = JSON.stringify(value);
98
+ const cookieName = this.#getCookieName(storeName);
99
+ // Validate size before setting
100
+ const cookieString = `${cookieName}=${encodeURIComponent(serialized)}`;
101
+ this.#validateSize(cookieString);
102
+ this.#setCookie(cookieName, serialized); // Uses instance options
103
+ const event = { storeName, value };
104
+ this.#changes$.next(event);
105
+ this.#notifyLinkedInstances(event);
106
+ }
107
+ async [ReactiveStorage.Props.REMOVE](storeName) {
108
+ const cookieName = this.#getCookieName(storeName);
109
+ // Delete cookie by setting max-age to 0
110
+ this.#setCookie(cookieName, '', { maxAge: 0 });
111
+ const event = { storeName, value: undefined };
112
+ this.#changes$.next(event);
113
+ this.#notifyLinkedInstances(event);
114
+ }
115
+ /**
116
+ * Convert store name to cookie name by prefixing with app name.
117
+ * Sanitizes to only allow alphanumeric, underscore, and hyphen.
118
+ */
119
+ #getCookieName(storeName) {
120
+ return `${this.appName}_${storeName}`.replace(/[^a-zA-Z0-9_-]/g, '_');
121
+ }
122
+ /**
123
+ * Parse document.cookie string into key-value object.
124
+ * Handles decoding of cookie values.
125
+ */
126
+ #parseCookies() {
127
+ if (!document.cookie) {
128
+ return {};
129
+ }
130
+ return Object.fromEntries(document.cookie
131
+ .split('; ')
132
+ .filter(Boolean)
133
+ .map((cookie) => {
134
+ const separatorIndex = cookie.indexOf('=');
135
+ if (separatorIndex === -1) {
136
+ return [cookie, ''];
137
+ }
138
+ const name = cookie.slice(0, separatorIndex);
139
+ const value = cookie.slice(separatorIndex + 1);
140
+ try {
141
+ return [name, decodeURIComponent(value)];
142
+ }
143
+ catch {
144
+ return [name, value]; // Return raw value if decode fails
145
+ }
146
+ }));
147
+ }
148
+ /**
149
+ * Get all cookies that belong to this app (matching appName prefix).
150
+ * Returns object with storeName -> encoded value.
151
+ */
152
+ #getAppCookies() {
153
+ const allCookies = this.#parseCookies();
154
+ const prefix = `${this.appName}_`;
155
+ const appCookies = {};
156
+ for (const [cookieName, value] of Object.entries(allCookies)) {
157
+ if (cookieName.startsWith(prefix)) {
158
+ const storeName = cookieName.slice(prefix.length);
159
+ appCookies[storeName] = value;
160
+ }
161
+ }
162
+ return appCookies;
163
+ }
164
+ /**
165
+ * Build and set a cookie with the instance's configured options.
166
+ * Pass options parameter to override specific settings (e.g., maxAge: 0 to delete).
167
+ */
168
+ #setCookie(name, value, overrides = {}) {
169
+ const opts = { ...this.options, ...overrides };
170
+ let cookie = `${name}=${encodeURIComponent(value)}`;
171
+ if (opts.path !== undefined)
172
+ cookie += `; path=${opts.path}`;
173
+ if (opts.domain)
174
+ cookie += `; domain=${opts.domain}`;
175
+ if (opts.maxAge !== undefined)
176
+ cookie += `; max-age=${opts.maxAge}`;
177
+ if (opts.expires)
178
+ cookie += `; expires=${opts.expires.toUTCString()}`;
179
+ if (opts.secure)
180
+ cookie += '; secure';
181
+ if (opts.sameSite)
182
+ cookie += `; samesite=${opts.sameSite}`;
183
+ document.cookie = cookie;
184
+ }
185
+ /**
186
+ * Validate that a cookie string doesn't exceed size limits.
187
+ * Throws an error if the cookie is too large.
188
+ */
189
+ #validateSize(cookieString) {
190
+ if (cookieString.length > _a.#MAX_COOKIE_SIZE) {
191
+ throw new Error(`Cookie size (${cookieString.length} bytes) exceeds ${_a.#MAX_COOKIE_SIZE} byte limit. ` +
192
+ `Consider using localStorage for larger data or splitting across multiple stores.`);
193
+ }
194
+ }
195
+ /**
196
+ * Notify all other linked storage instances about a change.
197
+ * This instance will not be notified (to prevent infinite loops).
198
+ */
199
+ #notifyLinkedInstances(event) {
200
+ if (!this.#linker)
201
+ return;
202
+ const linkedInstances = _a.#LINKERS.get(this.#linker);
203
+ if (!linkedInstances)
204
+ return;
205
+ for (const instance of linkedInstances) {
206
+ if (instance !== this) {
207
+ instance.#changes$.next(event);
208
+ }
209
+ }
210
+ }
211
+ }
212
+ _a = ReactiveCookieStorage;
213
+
214
+ export { ReactiveCookieStorage };
215
+ //# sourceMappingURL=reactive-cookie-storage.js.map
@@ -0,0 +1 @@
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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AAC,KAAK,CAAC;YAChC;QACF;IACF;;;;;;"}
@@ -1,31 +1,54 @@
1
- "use strict";
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 for reactive storage implementations.
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
- * @template S - Storage store name type (defaults to string)
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 = (0, compact_1.compact)(prop.split('.'));
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$ = (0, rxjs_1.from)(this[GET_ALL]()).pipe((0, rxjs_1.switchMap)(data => {
67
+ this.#_stream$ = rxjs.from(this[GET_ALL]()).pipe(rxjs.switchMap(data => {
45
68
  data ??= {};
46
- return (0, rxjs_1.from)(this[CHANGES]).pipe((0, rxjs_1.map)(({ storeName, value }) => {
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 (0, deep_freeze_1.deepFreeze)({ ...data });
52
- }), (0, rxjs_1.startWith)((0, deep_freeze_1.deepFreeze)({ ...data })));
53
- }), (0, share_last_1.shareLast)());
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
- * Get an observable that emits the current value and all future changes.
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
- * @template T - Expected return type
65
- * @param storeName - Name of the storage store
66
- * @param key - Property path using dot notation (empty string for entire store)
67
- * @returns Observable that emits current value and all updates
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((0, rxjs_1.map)(allData => ReactiveStorage.extractData(allData, `${storeName}.${key}`)), (0, rxjs_1.distinctUntilChanged)());
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 (0, rxjs_1.firstValueFrom)(this.get(storeName));
74
- const storeChangeEvent = (0, rxjs_1.lastValueFrom)(this.get(storeName).pipe((0, rxjs_1.take)(2)));
75
- const paths = (0, compact_1.compact)(key.split('.'));
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
- * Set a value in storage. Overwrites existing value.
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
- * @param storeName - Name of the storage store
111
- * @param key - Property path using dot notation
112
- * @param value - Value to set (undefined removes the value)
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 (0, rxjs_1.firstValueFrom)(this.get(storeName, key));
127
- await this.#set(storeName, key, Object.assign({}, existing, (0, compact_1.compact)(value)));
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
- * Delete a value from storage.
169
+ * Removes a value at a path, or the whole store. Same as `set(storeName, key, undefined)`.
131
170
  *
132
- * @param storeName - Name of the storage store
133
- * @param key - Property path using dot notation (empty string deletes entire store)
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
- * Add items to an array in storage.
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
- * @param storeName - Name of the storage store
143
- * @param key - Path to array property using dot notation
144
- * @param values - Values to push into the array
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 (0, rxjs_1.firstValueFrom)(this.get(storeName, key)) ?? [];
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 (0, rxjs_1.firstValueFrom)(this.get(storeName, key));
159
- await this.#set(storeName, key, (0, remove_1.remove)(existing, value));
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
- exports.ReactiveStorage = ReactiveStorage;
163
- tslib_1.__decorate([
164
- (0, fifo_promise_1.FifoPromise)({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
165
- tslib_1.__metadata("design:type", Function),
166
- tslib_1.__metadata("design:paramtypes", [String, String, Object]),
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
- tslib_1.__decorate([
170
- (0, fifo_promise_1.FifoPromise)({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
171
- tslib_1.__metadata("design:type", Function),
172
- tslib_1.__metadata("design:paramtypes", [String, String, Object]),
173
- tslib_1.__metadata("design:returntype", Promise)
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
- tslib_1.__decorate([
176
- (0, fifo_promise_1.FifoPromise)({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
177
- tslib_1.__metadata("design:type", Function),
178
- tslib_1.__metadata("design:paramtypes", [String, Object]),
179
- tslib_1.__metadata("design:returntype", Promise)
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
- tslib_1.__decorate([
182
- (0, fifo_promise_1.FifoPromise)({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
183
- tslib_1.__metadata("design:type", Function),
184
- tslib_1.__metadata("design:paramtypes", [String, String, Object]),
185
- tslib_1.__metadata("design:returntype", Promise)
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
- tslib_1.__decorate([
188
- (0, fifo_promise_1.FifoPromise)({ group: ReactiveStorage.FifoGroup, timeout: 1000 }),
189
- tslib_1.__metadata("design:type", Function),
190
- tslib_1.__metadata("design:paramtypes", [String, String, Object]),
191
- tslib_1.__metadata("design:returntype", Promise)
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;AAAE,YAAA,OAAO,IAAI;QAEtB,MAAM,SAAS,GAAGA,eAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC1C,IAAI,KAAK,GAAG,IAAI;AAEhB,QAAA,GAAG;AACD,YAAA,IAAI;gBACF,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YAC7B;AAAE,YAAA,MAAM;AACN,gBAAA,OAAO,SAAU;YACnB;YAEA,SA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C,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 };