synapse-storage 3.0.3 → 3.0.4

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/utils.cjs CHANGED
@@ -1,601 +1 @@
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/utils/index.ts
21
- var utils_exports = {};
22
- __export(utils_exports, {
23
- createSynapse: () => createSynapse
24
- });
25
- module.exports = __toCommonJS(utils_exports);
26
-
27
- // src/core/selector/selector.module.ts
28
- var DEBUG = false;
29
- var GLOBAL_SELECTOR_CACHE = /* @__PURE__ */ new Map();
30
- function getStringHash(str) {
31
- let hash = 0;
32
- if (str.length === 0) return hash.toString(36);
33
- for (let i = 0; i < str.length; i++) {
34
- const char = str.charCodeAt(i);
35
- hash = (hash << 5) - hash + char;
36
- hash = hash & hash;
37
- }
38
- return Math.abs(hash).toString(36).substring(0, 6);
39
- }
40
- function defaultEquals(a, b) {
41
- if (a === b) return true;
42
- if (a == null || b == null) return false;
43
- if (typeof a !== "object" && typeof a !== "function" && typeof b !== "object" && typeof b !== "function") {
44
- return a === b;
45
- }
46
- if (typeof a !== typeof b) return false;
47
- if (a instanceof Date && b instanceof Date) {
48
- return a.getTime() === b.getTime();
49
- }
50
- if (Array.isArray(a) && Array.isArray(b)) {
51
- if (a.length !== b.length) return false;
52
- for (let i = 0; i < a.length; i++) {
53
- if (!defaultEquals(a[i], b[i])) return false;
54
- }
55
- return true;
56
- }
57
- if (typeof a === "object" && typeof b === "object") {
58
- const keysA = Object.keys(a);
59
- const keysB = Object.keys(b);
60
- if (keysA.length !== keysB.length) return false;
61
- return keysA.every((key) => {
62
- if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
63
- return defaultEquals(a[key], b[key]);
64
- });
65
- }
66
- return false;
67
- }
68
- function memoizeSelector(selectorFn, equals = defaultEquals) {
69
- let lastState;
70
- let lastResult;
71
- let hasResult = false;
72
- return function memoized(state) {
73
- if (!hasResult || lastState !== state) {
74
- const newResult = selectorFn(state);
75
- if (!hasResult || !equals(newResult, lastResult)) {
76
- lastResult = newResult;
77
- }
78
- lastState = state;
79
- hasResult = true;
80
- }
81
- return lastResult;
82
- };
83
- }
84
- var SelectorSubscription = class {
85
- constructor(name, getState, equals = defaultEquals, logger) {
86
- this.name = name;
87
- this.equals = equals;
88
- this.logger = logger;
89
- this.id = name;
90
- this.memoizedGetState = this.createMemoizedGetState(getState);
91
- if (DEBUG) {
92
- console.log(`[${this.id}] \u0421\u043E\u0437\u0434\u0430\u043D new SelectorSubscription`);
93
- }
94
- }
95
- id;
96
- subscribers = /* @__PURE__ */ new Set();
97
- lastValue;
98
- memoizedGetState;
99
- // Создает мемоизированную версию getState с кешированием результата
100
- createMemoizedGetState(getState) {
101
- let lastPromise = null;
102
- let isExecuting = false;
103
- return async () => {
104
- if (isExecuting && lastPromise) {
105
- return lastPromise;
106
- }
107
- isExecuting = true;
108
- try {
109
- lastPromise = getState();
110
- return await lastPromise;
111
- } finally {
112
- isExecuting = false;
113
- }
114
- };
115
- }
116
- async notify() {
117
- try {
118
- const newValue = await this.memoizedGetState();
119
- if (this.lastValue === void 0 || !this.equals(newValue, this.lastValue)) {
120
- if (DEBUG) {
121
- console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C, notify()`, {
122
- old: this.lastValue,
123
- new: newValue
124
- });
125
- }
126
- this.lastValue = newValue;
127
- const promises = Array.from(this.subscribers).map(async (subscriber) => {
128
- try {
129
- await subscriber.notify(newValue);
130
- } catch (error) {
131
- this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`, { error });
132
- }
133
- });
134
- await Promise.all(promises);
135
- } else if (DEBUG) {
136
- console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C in notify(), \u043F\u0440\u043E\u043F\u0443\u0441\u043A \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F`);
137
- }
138
- } catch (error) {
139
- this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`, { error });
140
- throw error;
141
- }
142
- }
143
- subscribe(subscriber) {
144
- if (DEBUG) {
145
- console.log(`[${this.id}] \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u043D\u043E\u0432\u044B\u0439 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A, \u0432\u0441\u0435\u0433\u043E: ${this.subscribers.size + 1}`);
146
- }
147
- this.subscribers.add(subscriber);
148
- if (this.lastValue !== void 0) {
149
- Promise.resolve().then(() => {
150
- try {
151
- subscriber.notify(this.lastValue);
152
- } catch (error) {
153
- this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`, { error });
154
- }
155
- });
156
- } else {
157
- this.notify().catch((error) => {
158
- this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`, { error });
159
- });
160
- }
161
- return () => {
162
- if (DEBUG) {
163
- console.log(`[${this.id}] \u041F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A \u0443\u0434\u0430\u043B\u0435\u043D, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C: ${this.subscribers.size - 1}`);
164
- }
165
- this.subscribers.delete(subscriber);
166
- };
167
- }
168
- cleanup() {
169
- if (DEBUG) {
170
- console.log(`[${this.id}] \u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438, \u0431\u044B\u043B\u043E ${this.subscribers.size} \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u043E\u0432`);
171
- }
172
- this.subscribers.clear();
173
- this.lastValue = void 0;
174
- }
175
- getId() {
176
- return this.id;
177
- }
178
- };
179
- var SelectorModule = class {
180
- constructor(source, logger) {
181
- this.source = source;
182
- this.logger = logger;
183
- this.storageName = source.name;
184
- if (DEBUG) {
185
- console.log(`\u0421\u043E\u0437\u0434\u0430\u043D SelectorModule \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${this.storageName}`);
186
- }
187
- this.source.getState().then((state) => {
188
- this.cachedState = state;
189
- if (DEBUG) {
190
- console.log(`\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F ${this.storageName}`);
191
- }
192
- });
193
- }
194
- storageName;
195
- subscriptions = /* @__PURE__ */ new Map();
196
- cachedState;
197
- localSelectorCache = /* @__PURE__ */ new Map();
198
- // Флаг для батчинга обновлений
199
- batchUpdateInProgress = false;
200
- pendingUpdates = /* @__PURE__ */ new Set();
201
- /**
202
- * Генерирует имя для селектора на основе его типа и функции
203
- */
204
- generateName(isSimpleSelector, selectorOrDeps, resultFnOrOptions) {
205
- const type = isSimpleSelector ? "simple" : "combined";
206
- let hash = "";
207
- if (isSimpleSelector) {
208
- const selectorStr = selectorOrDeps.toString();
209
- hash = getStringHash(selectorStr);
210
- } else {
211
- const depsIds = selectorOrDeps.map((s) => s.getId()).join("_");
212
- const resultFnStr = resultFnOrOptions.toString();
213
- hash = getStringHash(depsIds + resultFnStr);
214
- }
215
- return `${this.storageName}_${type}_${hash}`;
216
- }
217
- /**
218
- * Обрабатывает отложенные обновления, чтобы избежать каскадных уведомлений
219
- */
220
- processPendingUpdates() {
221
- if (this.pendingUpdates.size === 0 || this.batchUpdateInProgress) return;
222
- this.batchUpdateInProgress = true;
223
- setTimeout(async () => {
224
- try {
225
- const subscriptionsToUpdate = Array.from(this.pendingUpdates);
226
- this.pendingUpdates.clear();
227
- this.cachedState = await this.source.getState();
228
- const updatePromises = subscriptionsToUpdate.map(async (id) => {
229
- const subscription = this.subscriptions.get(id);
230
- if (subscription) {
231
- try {
232
- return await subscription.notify();
233
- } catch (error) {
234
- this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${id}`, { error });
235
- }
236
- }
237
- return Promise.resolve();
238
- });
239
- await Promise.all(updatePromises);
240
- } catch (error) {
241
- this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439", { error });
242
- } finally {
243
- this.batchUpdateInProgress = false;
244
- if (this.pendingUpdates.size > 0) {
245
- this.processPendingUpdates();
246
- }
247
- }
248
- }, 0);
249
- }
250
- createSelector(selectorOrDeps, resultFnOrOptions, optionsArg) {
251
- const isSimpleSelector = !Array.isArray(selectorOrDeps);
252
- const options = isSimpleSelector ? resultFnOrOptions || {} : optionsArg || {};
253
- const selectorId = options.name || this.generateName(isSimpleSelector, selectorOrDeps, isSimpleSelector ? void 0 : resultFnOrOptions);
254
- if (this.localSelectorCache.has(selectorId)) {
255
- if (DEBUG) {
256
- console.log(`[${this.storageName}] Reusing cached selector: ${selectorId}`);
257
- }
258
- return this.localSelectorCache.get(selectorId).api;
259
- }
260
- if (GLOBAL_SELECTOR_CACHE.has(selectorId)) {
261
- const cached = GLOBAL_SELECTOR_CACHE.get(selectorId);
262
- cached.refCount++;
263
- if (DEBUG) {
264
- console.log(`[${this.storageName}] \u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0430: ${selectorId}, refCount: ${cached.refCount}`);
265
- }
266
- return cached.api;
267
- }
268
- let result;
269
- let dependencies;
270
- let unsubscribeFunctions = [];
271
- if (isSimpleSelector) {
272
- const memoized = memoizeSelector(selectorOrDeps, options.equals || defaultEquals);
273
- const created = this.createSimpleSelector(memoized, { ...options, name: selectorId, equals: options.equals || defaultEquals });
274
- result = created.api;
275
- unsubscribeFunctions = created.unsubscribeFunctions;
276
- } else {
277
- dependencies = selectorOrDeps;
278
- const created = this.createCombinedSelector(dependencies, resultFnOrOptions, {
279
- ...options,
280
- name: selectorId,
281
- equals: options.equals || defaultEquals
282
- });
283
- result = created.api;
284
- unsubscribeFunctions = created.unsubscribeFunctions;
285
- }
286
- this.localSelectorCache.set(selectorId, {
287
- api: result,
288
- dependencies,
289
- unsubscribeFunctions
290
- });
291
- GLOBAL_SELECTOR_CACHE.set(selectorId, {
292
- api: result,
293
- refCount: 1,
294
- unsubscribeFunctions
295
- });
296
- if (DEBUG) {
297
- console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043D\u043E\u0432\u044B\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${selectorId}`);
298
- }
299
- return result;
300
- }
301
- createSimpleSelector(selector, options) {
302
- if (DEBUG) {
303
- console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${options.name}`);
304
- }
305
- const getState = async () => {
306
- if (this.cachedState) {
307
- return selector(this.cachedState);
308
- }
309
- const state = await this.source.getState();
310
- this.cachedState = state;
311
- return selector(state);
312
- };
313
- const subscription = new SelectorSubscription(options.name, getState, options.equals || defaultEquals, this.logger);
314
- const id = subscription.getId();
315
- this.subscriptions.set(id, subscription);
316
- const unsubscribeFromStorage = this.source.subscribeToAll(async (event) => {
317
- if (event?.type === "storage:update") {
318
- if (DEBUG) {
319
- console.log(`[${id}] \u041F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430`);
320
- }
321
- this.pendingUpdates.add(id);
322
- this.processPendingUpdates();
323
- }
324
- });
325
- const unsubscribeFunctions = [unsubscribeFromStorage];
326
- return {
327
- api: {
328
- select: () => getState(),
329
- subscribe: (subscriber) => {
330
- return subscription.subscribe(subscriber);
331
- },
332
- getId: () => id
333
- },
334
- unsubscribeFunctions
335
- };
336
- }
337
- createCombinedSelector(selectors, resultFn, options) {
338
- const memoizedResultFn = memoizeSelector((args) => resultFn(...args), options.equals || defaultEquals);
339
- const getState = async () => {
340
- const values = await Promise.all(selectors.map((s) => s.select()));
341
- return memoizedResultFn(values);
342
- };
343
- const subscription = new SelectorSubscription(options.name, getState, options.equals || defaultEquals, this.logger);
344
- const id = subscription.getId();
345
- this.subscriptions.set(id, subscription);
346
- let debounceTimer = null;
347
- const triggerUpdate = () => {
348
- if (debounceTimer !== null) {
349
- clearTimeout(debounceTimer);
350
- }
351
- debounceTimer = setTimeout(() => {
352
- debounceTimer = null;
353
- subscription.notify().catch((error) => this.logger?.error(`[${id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`, { error }));
354
- }, 10);
355
- };
356
- const unsubscribeFunctions = selectors.map(
357
- (selector) => selector.subscribe({
358
- notify: () => {
359
- triggerUpdate();
360
- }
361
- })
362
- );
363
- return {
364
- api: {
365
- select: () => getState(),
366
- subscribe: (subscriber) => {
367
- return subscription.subscribe(subscriber);
368
- },
369
- getId: () => id
370
- },
371
- unsubscribeFunctions
372
- };
373
- }
374
- destroy() {
375
- if (DEBUG) {
376
- console.log(`[${this.storageName}] \u041D\u0430\u0447\u0430\u043B\u043E\u0441\u044C \u0443\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D\u0438\u0435 SelectorModule`);
377
- }
378
- this.subscriptions.forEach((sub) => sub.cleanup());
379
- this.subscriptions.clear();
380
- this.cachedState = void 0;
381
- this.pendingUpdates.clear();
382
- this.localSelectorCache.forEach((cached) => {
383
- cached.unsubscribeFunctions.forEach((unsub) => unsub());
384
- });
385
- const keysToCheck = /* @__PURE__ */ new Set();
386
- this.localSelectorCache.forEach((_, key) => {
387
- keysToCheck.add(key);
388
- });
389
- this.localSelectorCache.clear();
390
- keysToCheck.forEach((key) => {
391
- const globalCached = GLOBAL_SELECTOR_CACHE.get(key);
392
- if (globalCached) {
393
- globalCached.refCount--;
394
- if (globalCached.refCount <= 0) {
395
- globalCached.unsubscribeFunctions.forEach((unsub) => unsub());
396
- GLOBAL_SELECTOR_CACHE.delete(key);
397
- if (DEBUG) {
398
- console.log(`[${this.storageName}] \u0423\u0434\u0430\u043B\u0435\u043D \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440 \u0438\u0437 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0430: ${key}`);
399
- }
400
- }
401
- }
402
- });
403
- if (DEBUG) {
404
- console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`);
405
- }
406
- }
407
- };
408
-
409
- // src/reactive/dispatcher/dispatcher.module.ts
410
- var import_rxjs = require("rxjs");
411
-
412
- // src/reactive/effects/effects.module.ts
413
- var import_rxjs4 = require("rxjs");
414
- var import_operators3 = require("rxjs/operators");
415
-
416
- // src/reactive/effects/utils/chunkRequestConsistent.ts
417
- var import_rxjs2 = require("rxjs");
418
- var import_operators = require("rxjs/operators");
419
-
420
- // src/reactive/effects/utils/chunkRequestParallel.ts
421
- var import_rxjs3 = require("rxjs");
422
- var import_operators2 = require("rxjs/operators");
423
-
424
- // src/reactive/effects/effects.module.ts
425
- var EffectsModule = class {
426
- /**
427
- * Создает модуль эффектов с доступом к состоянию, внешним состояниям и конфигурации
428
- * @param storage Хранилище состояния
429
- * @param externalStates Внешние состояния
430
- * @param dispatchers Объект с диспетчерами
431
- * @param services Объект с сервисами
432
- * @param config Глобальная конфигурация для всех эффектов
433
- */
434
- constructor(storage, externalStates = {}, dispatchers, services = {}, config = {}) {
435
- this.storage = storage;
436
- this.externalStates = externalStates;
437
- this.dispatchers = dispatchers;
438
- this.services = services;
439
- this.config = config;
440
- this.subscribeToDispatchers();
441
- this.state$ = new import_rxjs4.Observable((observer) => {
442
- this.storage.getState().then((state) => observer.next(state));
443
- const unsubscribe = this.storage.subscribeToAll(() => {
444
- this.storage.getState().then((state) => observer.next(state));
445
- });
446
- return () => unsubscribe();
447
- }).pipe((0, import_operators3.share)());
448
- }
449
- effects = [];
450
- subscriptions = [];
451
- running = false;
452
- action$ = new import_rxjs4.Subject();
453
- /**
454
- * Поток состояния
455
- */
456
- state$;
457
- /**
458
- * Подписывается на действия от всех диспетчеров
459
- */
460
- subscribeToDispatchers() {
461
- for (const [_, dispatcher] of Object.entries(this.dispatchers)) {
462
- const subscription = dispatcher.actions.subscribe((action) => {
463
- this.action$.next(action);
464
- });
465
- this.subscriptions.push(subscription);
466
- }
467
- }
468
- add(effect) {
469
- this.effects.push(effect);
470
- if (this.running) {
471
- this.subscribeToEffect(effect);
472
- }
473
- return this;
474
- }
475
- /**
476
- * Добавляет несколько эффектов
477
- * @param effects Эффекты для добавления
478
- * @returns Текущий модуль
479
- */
480
- addEffects(effects) {
481
- effects.forEach((effect) => this.add(effect));
482
- return this;
483
- }
484
- /**
485
- * Запускает все эффекты
486
- * @returns Текущий модуль
487
- */
488
- start() {
489
- if (this.running) {
490
- return this;
491
- }
492
- this.effects.forEach((effect) => this.subscribeToEffect(effect));
493
- this.running = true;
494
- return this;
495
- }
496
- /**
497
- * Останавливает все эффекты
498
- * @returns Текущий модуль
499
- */
500
- stop() {
501
- this.subscriptions.forEach((sub) => sub.unsubscribe());
502
- this.subscriptions = [];
503
- this.running = false;
504
- return this;
505
- }
506
- /**
507
- * Подписывается на конкретный эффект
508
- * @param effect Эффект для подписки
509
- */
510
- subscribeToEffect(effect) {
511
- try {
512
- const output$ = effect(this.action$.asObservable(), this.state$, this.externalStates, this.dispatchers, this.services, this.config).pipe(
513
- (0, import_operators3.catchError)((err) => {
514
- console.error("Error in effect:", err);
515
- return (0, import_rxjs4.of)(null);
516
- })
517
- );
518
- const subscription = output$.subscribe((result) => {
519
- if (result === null || result === void 0) {
520
- return;
521
- }
522
- if (typeof result === "function") {
523
- try {
524
- result();
525
- } catch (callError) {
526
- console.error("Error calling effect result function:", callError);
527
- }
528
- }
529
- });
530
- this.subscriptions.push(subscription);
531
- } catch (setupError) {
532
- console.error("Error setting up effect:", setupError);
533
- }
534
- }
535
- };
536
-
537
- // src/utils/createSynapse.ts
538
- async function createSynapse(config) {
539
- const storageInstance = config.createStorageFn ? await config.createStorageFn() : config.storage;
540
- const cleanupCallbacks = [];
541
- const result = {
542
- storage: storageInstance,
543
- selectors: {},
544
- destroy: async () => {
545
- for (const callback of cleanupCallbacks) {
546
- await callback();
547
- }
548
- }
549
- };
550
- cleanupCallbacks.push(() => storageInstance.destroy());
551
- let dispatcher;
552
- let selectorModule;
553
- let effectsModule;
554
- if (config.createSelectorsFn) {
555
- try {
556
- selectorModule = new SelectorModule(storageInstance);
557
- const externalSelectors = config.externalSelectors || {};
558
- result.selectors = config.createSelectorsFn(selectorModule, externalSelectors);
559
- if (typeof selectorModule.destroy === "function") {
560
- cleanupCallbacks.push(() => selectorModule.destroy());
561
- }
562
- } catch (error) {
563
- console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F selectors:", error);
564
- }
565
- }
566
- if (config.createDispatcherFn) {
567
- dispatcher = config.createDispatcherFn(storageInstance);
568
- result.dispatcher = dispatcher;
569
- if (dispatcher && "dispatch" in dispatcher) {
570
- result.actions = dispatcher.dispatch;
571
- if (typeof dispatcher.destroy === "function") {
572
- cleanupCallbacks.push(() => dispatcher.destroy());
573
- }
574
- }
575
- }
576
- if (config.createEffectConfig && dispatcher) {
577
- try {
578
- const { dispatchers, api, config: effectConfig, externalStates } = config.createEffectConfig(dispatcher);
579
- const effectExternalStates = externalStates || {};
580
- effectsModule = new EffectsModule(storageInstance, effectExternalStates, dispatchers, api, effectConfig);
581
- if (Array.isArray(config.effects)) {
582
- config.effects.forEach((effect) => {
583
- if (effectsModule) effectsModule.add(effect);
584
- });
585
- }
586
- effectsModule.start();
587
- result.state$ = effectsModule.state$;
588
- cleanupCallbacks.push(() => {
589
- if (effectsModule) effectsModule.stop();
590
- });
591
- } catch (error) {
592
- console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u044F \u043C\u043E\u0434\u0443\u043B\u044F \u044D\u0444\u0444\u0435\u043A\u0442\u043E\u0432:", error);
593
- }
594
- }
595
- return result;
596
- }
597
- // Annotate the CommonJS export names for ESM import in node:
598
- 0 && (module.exports = {
599
- createSynapse
600
- });
601
- //# sourceMappingURL=utils.cjs.map
1
+ 'use strict';var chunkWC5TDS6C_cjs=require('./chunk-WC5TDS6C.cjs');require('./chunk-VSIVOWZF.cjs'),require('./chunk-UFBCZ25Y.cjs'),require('./chunk-635Q6YJZ.cjs'),require('./chunk-NMDHQXMS.cjs');Object.defineProperty(exports,"createSynapse",{enumerable:true,get:function(){return chunkWC5TDS6C_cjs.a}});