@superutils/store 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,331 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Store: () => Store,
24
+ Store_OnErrorType: () => Store_OnErrorType,
25
+ createObjectStore: () => createObjectStore,
26
+ createStore: () => createStore,
27
+ default: () => index_default,
28
+ forceUpdateCache$: () => forceUpdateCache$,
29
+ objToMap: () => import_core4.objToMap
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/createObjectStore.ts
34
+ var import_core3 = require("@superutils/core");
35
+
36
+ // src/createStore.ts
37
+ var import_core2 = require("@superutils/core");
38
+
39
+ // src/Store.ts
40
+ var import_core = require("@superutils/core");
41
+ var import_rxjs = require("rxjs");
42
+
43
+ // src/types/types.ts
44
+ var Store_OnErrorType = /* @__PURE__ */ ((Store_OnErrorType2) => {
45
+ Store_OnErrorType2["onChange"] = "onChange";
46
+ Store_OnErrorType2["parse"] = "parse";
47
+ Store_OnErrorType2["parse_json"] = "parse-json";
48
+ Store_OnErrorType2["stringify"] = "stringify";
49
+ Store_OnErrorType2["stringify_json"] = "stringify-json";
50
+ Store_OnErrorType2["write"] = "write";
51
+ return Store_OnErrorType2;
52
+ })(Store_OnErrorType || {});
53
+
54
+ // src/Store.ts
55
+ var forceUpdateCache$ = new import_rxjs.Subject();
56
+ var _Store = class _Store {
57
+ constructor(name, options) {
58
+ this.initialized = false;
59
+ this.subscriptions = {
60
+ subject: void 0,
61
+ forceUpdateCache: void 0
62
+ };
63
+ this.type = "map";
64
+ this.clear = () => this.setAll(/* @__PURE__ */ new Map(), true);
65
+ this.delete = (keys) => {
66
+ if (!(0, import_core.isArr)(keys)) keys = [keys];
67
+ const data = this.getAll();
68
+ for (const k of keys) data.delete(k);
69
+ this.setAll(data, true);
70
+ return this;
71
+ };
72
+ this.filter = (...args) => (0, import_core.filter)(this.getAll(), ...args);
73
+ this.find = (predicateOrOptions) => (0, import_core.find)(this.getAll(), predicateOrOptions);
74
+ this.get = (key) => this.getAll().get(key);
75
+ this.getAll = (forceRead = false) => {
76
+ const wasInitialized = this.initialized;
77
+ if (!wasInitialized) this.init();
78
+ const readFromStorage = this.cacheDisabled || this.storage && forceRead;
79
+ if (readFromStorage) {
80
+ const data = this.read();
81
+ const shouldTrigger = forceRead || !wasInitialized && !!data.size;
82
+ shouldTrigger && this.subject$.next(data);
83
+ return data;
84
+ }
85
+ return this.subject$.value;
86
+ };
87
+ this.handleForceUpdateCache = (name) => {
88
+ const isTarget = !this.name ? false : (0, import_core.isArr)(name) ? name.includes(this.name) : (0, import_core.isStr)(name) ? name === this.name : name === true;
89
+ if (!isTarget) return;
90
+ const newData = this.read();
91
+ this.subject$.next(newData);
92
+ };
93
+ this.handleSubjectChange = (data) => {
94
+ var _a;
95
+ if (!(0, import_core.isMap)(data)) return this.subject$.next(/* @__PURE__ */ new Map());
96
+ this.write(data);
97
+ (0, import_core.fallbackIfFails)(
98
+ (_a = this.onChange) == null ? void 0 : _a.bind(this),
99
+ [data],
100
+ this.triggerOnErrorCb("onChange" /* onChange */)
101
+ );
102
+ };
103
+ this.has = (key) => this.getAll().has(key);
104
+ this.init = (initialValue, checkStorage = true) => {
105
+ var _a;
106
+ if (this.initialized) return false;
107
+ this.initialized = true;
108
+ if (checkStorage && this.name && !this.storage)
109
+ throw new Error(_Store.messages.invalidOptionsStorage);
110
+ let isEmpty = !!this.cacheDisabled;
111
+ let firstValue = initialValue;
112
+ if (!!(initialValue == null ? void 0 : initialValue.size) || !this.cacheDisabled) {
113
+ const dataStr = this.name ? (_a = this.storage) == null ? void 0 : _a.getItem(this.name) : null;
114
+ const existingValue = this.read(dataStr != null ? dataStr : null);
115
+ if ((0, import_core.isDefined)(dataStr)) firstValue = existingValue;
116
+ isEmpty = this.cacheDisabled || existingValue.size === 0;
117
+ }
118
+ (firstValue == null ? void 0 : firstValue.size) && this.subject$.next(firstValue);
119
+ this.unsubscribe();
120
+ if (!this.cacheDisabled) {
121
+ this.subscriptions.forceUpdateCache = forceUpdateCache$.subscribe(
122
+ this.handleForceUpdateCache
123
+ );
124
+ }
125
+ this.subscriptions.subject = this.subject$.pipe((0, import_rxjs.skip)(isEmpty ? 0 : 1)).subscribe(
126
+ !this.cacheDisabled && this.delay > 0 ? (0, import_core.deferred)(this.handleSubjectChange, this.delay, {
127
+ thisArg: this,
128
+ ...this.delayOptions
129
+ }) : this.handleSubjectChange
130
+ );
131
+ return true;
132
+ };
133
+ this.keys = () => (0, import_core.getKeys)(this.getAll());
134
+ this.map = (callback) => this.toArray().map(
135
+ ([key, value], index, entries) => callback(value, key, entries, index)
136
+ );
137
+ this.read = (dataStr = ((_b) => (_b = this.name && ((_a) => (_a = this.storage) == null ? void 0 : _a.getItem(this.name))()) != null ? _b : null)()) => {
138
+ var _a2;
139
+ const data = (0, import_core.fallbackIfFails)(
140
+ this.parse,
141
+ [dataStr],
142
+ this.triggerOnErrorCb("parse" /* parse */, void 0)
143
+ );
144
+ if ((0, import_core.isMap)(data) || !(0, import_core.isStr)(dataStr))
145
+ return (_a2 = (0, import_core.isFn)(this.parse) ? data : this.subject$.value) != null ? _a2 : /* @__PURE__ */ new Map();
146
+ return new Map(
147
+ (0, import_core.fallbackIfFails)(
148
+ () => {
149
+ const entries = JSON.parse(dataStr);
150
+ if (!(0, import_core.isArr2D)(entries))
151
+ throw new Error(_Store.messages.invalidJsonEntries);
152
+ return entries;
153
+ },
154
+ [],
155
+ this.triggerOnErrorCb("parse-json" /* parse_json */)
156
+ )
157
+ );
158
+ };
159
+ this.search = (...args) => (0, import_core.search)(this.getAll(), ...args);
160
+ this.set = (key, value) => {
161
+ const data = this.getAll();
162
+ data.set(key, (0, import_core.isFn)(value) ? value(data.get(key)) : value);
163
+ return this.setAll(data, true);
164
+ };
165
+ this.setAll = (data, replace = false) => {
166
+ if (!(0, import_core.isMap)(data)) return this;
167
+ data = replace ? data : (0, import_core.mapJoin)(this.getAll(), data);
168
+ this.subject$.next(new Map(data));
169
+ return this;
170
+ };
171
+ this.sort = (...args) => {
172
+ var _a;
173
+ const result = (0, import_core.sort)(
174
+ this.getAll(),
175
+ args[0],
176
+ args[1]
177
+ );
178
+ ((_a = args[1]) == null ? void 0 : _a.save) && this.setAll(result, true);
179
+ return result;
180
+ };
181
+ this.toArray = () => (0, import_core.getEntries)(this.getAll());
182
+ this.toJSON = (replacer, spacing = this.spaces, data = this.getAll()) => {
183
+ const str = (0, import_core.fallbackIfFails)(
184
+ this.stringify,
185
+ [data],
186
+ this.triggerOnErrorCb("stringify" /* stringify */, "")
187
+ // if fails return empty string
188
+ );
189
+ if ((0, import_core.isStr)(str)) return str;
190
+ return (0, import_core.fallbackIfFails)(
191
+ () => JSON.stringify(
192
+ Array.from(data),
193
+ replacer,
194
+ spacing
195
+ ),
196
+ [],
197
+ this.triggerOnErrorCb("stringify-json" /* stringify_json */, "")
198
+ );
199
+ };
200
+ this.toObject = (data = this.getAll()) => {
201
+ const obj = {};
202
+ if (!(0, import_core.isMap)(data)) return obj;
203
+ for (const [key, value] of data)
204
+ obj[key] = value;
205
+ return obj;
206
+ };
207
+ this.toString = (data = this.getAll()) => this.toJSON(void 0, void 0, data);
208
+ this.triggerOnErrorCb = (type, returnValue = void 0) => (err) => {
209
+ var _a;
210
+ (0, import_core.fallbackIfFails)(
211
+ (_a = this.onError) == null ? void 0 : _a.bind(this),
212
+ [err, type],
213
+ ""
214
+ );
215
+ return returnValue;
216
+ };
217
+ this.unsubscribe = () => {
218
+ var _a, _b;
219
+ (_a = this.subscriptions.forceUpdateCache) == null ? void 0 : _a.unsubscribe();
220
+ (_b = this.subscriptions.subject) == null ? void 0 : _b.unsubscribe();
221
+ this.subscriptions = {};
222
+ };
223
+ this.values = () => (0, import_core.getValues)(this.getAll());
224
+ this.write = (data) => {
225
+ var _a;
226
+ try {
227
+ !this.initialized && this.init();
228
+ data != null ? data : data = (_a = this.subject$) == null ? void 0 : _a.value;
229
+ if (!(0, import_core.isMap)(data)) return false;
230
+ const jsonStr = this.toString(data);
231
+ if (!this.name || !this.storage) return false;
232
+ this.storage.setItem(this.name, jsonStr);
233
+ return true;
234
+ } catch (err) {
235
+ this.triggerOnErrorCb("write" /* write */)(err);
236
+ return false;
237
+ }
238
+ };
239
+ const {
240
+ cacheDisabled = false,
241
+ delay,
242
+ delayOptions,
243
+ initialValue,
244
+ onError,
245
+ onChange,
246
+ parse,
247
+ spaces,
248
+ storage = (0, import_core.fallbackIfFails)(
249
+ () => globalThis.localStorage,
250
+ [],
251
+ void 0
252
+ ),
253
+ stringify
254
+ } = options != null ? options : {};
255
+ this.name = `${name != null ? name : ""}`.trim() || null;
256
+ if (this.name && !storage && !(options == null ? void 0 : options.checkStorageOnInit))
257
+ throw new Error(_Store.messages.invalidOptionsStorage);
258
+ this.cacheDisabled = !!storage && cacheDisabled;
259
+ this.delay = delay === 0 || (0, import_core.isPositiveNumber)(delay) ? delay : 300;
260
+ this.delayOptions = delayOptions;
261
+ this.onError = onError;
262
+ this.onChange = onChange;
263
+ this.parse = parse == null ? void 0 : parse.bind(this);
264
+ this.storage = storage;
265
+ this.stringify = stringify == null ? void 0 : stringify.bind(this);
266
+ this.spaces = spaces;
267
+ this.subject$ = this.cacheDisabled ? new import_rxjs.Subject() : new import_rxjs.BehaviorSubject(/* @__PURE__ */ new Map());
268
+ (0, import_core.isMap)(initialValue) && initialValue.size && this.init(initialValue, false);
269
+ }
270
+ get size() {
271
+ return this.getAll().size;
272
+ }
273
+ };
274
+ _Store.messages = Object.seal({
275
+ invalidJsonEntries: "Invalid JSON format. Parsed value must be a 2D array representing key-value pairs.",
276
+ invalidOptionsStorage: "options.storage: LocalStorage instance or equivalent required"
277
+ });
278
+ /**
279
+ * Trigger forced update of cached data from storage.
280
+ *
281
+ * @param name determines which cache-enabled storage instances to be updated.
282
+ * - name (`string` | `string[]`): update all instances with a specific name(s)
283
+ * - global (`true`): update all instances globally
284
+ *
285
+ * See {@link forceUpdateCache$} for more details.
286
+ */
287
+ _Store.forceUpdateCache = (name) => {
288
+ forceUpdateCache$.next(name);
289
+ };
290
+ var Store = _Store;
291
+ var Store_default = Store;
292
+
293
+ // src/createStore.ts
294
+ function createStore(name, options) {
295
+ const store = new Store_default(name, options);
296
+ Object.defineProperty(store, "context", {
297
+ configurable: false,
298
+ enumerable: false,
299
+ value: (0, import_core2.isFn)(options == null ? void 0 : options.context) ? options.context(store) : options == null ? void 0 : options.context,
300
+ writable: false
301
+ });
302
+ return store;
303
+ }
304
+ var createStore_default = createStore;
305
+
306
+ // src/createObjectStore.ts
307
+ function createObjectStore(name, options) {
308
+ const store = createStore_default(name, {
309
+ parse: (str) => (0, import_core3.objToMap)(JSON.parse(str != null ? str : "{}")),
310
+ stringify: function(data) {
311
+ return JSON.stringify(this.toObject(data));
312
+ },
313
+ ...options,
314
+ initialValue: !(0, import_core3.isObj)(options == null ? void 0 : options.initialValue, true) ? options == null ? void 0 : options.initialValue : (0, import_core3.objToMap)(options.initialValue)
315
+ });
316
+ store.type = "object";
317
+ return store;
318
+ }
319
+
320
+ // src/index.ts
321
+ var import_core4 = require("@superutils/core");
322
+ var index_default = Store_default;
323
+ // Annotate the CommonJS export names for ESM import in node:
324
+ 0 && (module.exports = {
325
+ Store,
326
+ Store_OnErrorType,
327
+ createObjectStore,
328
+ createStore,
329
+ forceUpdateCache$,
330
+ objToMap
331
+ });