@angular-architects/ngrx-toolkit 19.4.0 → 19.4.1

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 (128) hide show
  1. package/fesm2022/angular-architects-ngrx-toolkit-redux-connector.mjs +119 -0
  2. package/fesm2022/angular-architects-ngrx-toolkit-redux-connector.mjs.map +1 -0
  3. package/fesm2022/angular-architects-ngrx-toolkit.mjs +2095 -0
  4. package/fesm2022/angular-architects-ngrx-toolkit.mjs.map +1 -0
  5. package/{src/index.ts → index.d.ts} +5 -32
  6. package/lib/assertions/assertions.d.ts +2 -0
  7. package/{src/lib/devtools/features/with-disabled-name-indicies.ts → lib/devtools/features/with-disabled-name-indicies.d.ts} +1 -5
  8. package/{src/lib/devtools/features/with-glitch-tracking.ts → lib/devtools/features/with-glitch-tracking.d.ts} +1 -6
  9. package/{src/lib/devtools/features/with-mapper.ts → lib/devtools/features/with-mapper.d.ts} +1 -7
  10. package/lib/devtools/internal/current-action-names.d.ts +1 -0
  11. package/lib/devtools/internal/default-tracker.d.ts +13 -0
  12. package/lib/devtools/internal/devtools-feature.d.ts +24 -0
  13. package/lib/devtools/internal/devtools-syncer.service.d.ts +35 -0
  14. package/lib/devtools/internal/glitch-tracker.service.d.ts +18 -0
  15. package/lib/devtools/internal/models.d.ts +24 -0
  16. package/{src/lib/devtools/provide-devtools-config.ts → lib/devtools/provide-devtools-config.d.ts} +4 -16
  17. package/lib/devtools/rename-devtools-name.d.ts +7 -0
  18. package/lib/devtools/update-state.d.ts +15 -0
  19. package/{src/lib/devtools/with-dev-tools-stub.ts → lib/devtools/with-dev-tools-stub.d.ts} +1 -2
  20. package/lib/devtools/with-devtools.d.ts +24 -0
  21. package/lib/flattening-operator.d.ts +14 -0
  22. package/lib/immutable-state/deep-freeze.d.ts +11 -0
  23. package/lib/immutable-state/is-dev-mode.d.ts +1 -0
  24. package/lib/immutable-state/with-immutable-state.d.ts +60 -0
  25. package/lib/mutation/http-mutation.d.ts +86 -0
  26. package/lib/mutation/mutation.d.ts +20 -0
  27. package/lib/mutation/rx-mutation.d.ts +76 -0
  28. package/{src/lib/shared/signal-store-models.ts → lib/shared/signal-store-models.d.ts} +4 -8
  29. package/lib/shared/throw-if-null.d.ts +1 -0
  30. package/lib/storage-sync/features/with-indexed-db.d.ts +2 -0
  31. package/lib/storage-sync/features/with-local-storage.d.ts +3 -0
  32. package/lib/storage-sync/internal/indexeddb.service.d.ts +29 -0
  33. package/lib/storage-sync/internal/local-storage.service.d.ts +8 -0
  34. package/lib/storage-sync/internal/models.d.ts +45 -0
  35. package/lib/storage-sync/internal/session-storage.service.d.ts +8 -0
  36. package/lib/storage-sync/with-storage-sync.d.ts +45 -0
  37. package/lib/with-call-state.d.ts +58 -0
  38. package/{src/lib/with-conditional.ts → lib/with-conditional.d.ts} +7 -31
  39. package/lib/with-data-service.d.ts +109 -0
  40. package/{src/lib/with-feature-factory.ts → lib/with-feature-factory.d.ts} +4 -32
  41. package/lib/with-mutations.d.ts +51 -0
  42. package/lib/with-pagination.d.ts +98 -0
  43. package/lib/with-redux.d.ts +147 -0
  44. package/lib/with-reset.d.ts +29 -0
  45. package/lib/with-undo-redo.d.ts +31 -0
  46. package/package.json +21 -4
  47. package/redux-connector/index.d.ts +2 -0
  48. package/redux-connector/src/lib/create-redux.d.ts +13 -0
  49. package/redux-connector/src/lib/model.d.ts +40 -0
  50. package/redux-connector/src/lib/rxjs-interop/redux-method.d.ts +14 -0
  51. package/redux-connector/src/lib/signal-redux-store.d.ts +11 -0
  52. package/redux-connector/src/lib/util.d.ts +5 -0
  53. package/eslint.config.cjs +0 -43
  54. package/jest.config.ts +0 -22
  55. package/ng-package.json +0 -7
  56. package/project.json +0 -37
  57. package/redux-connector/docs/README.md +0 -131
  58. package/redux-connector/index.ts +0 -6
  59. package/redux-connector/ng-package.json +0 -5
  60. package/redux-connector/src/lib/create-redux.ts +0 -102
  61. package/redux-connector/src/lib/model.ts +0 -89
  62. package/redux-connector/src/lib/rxjs-interop/redux-method.ts +0 -66
  63. package/redux-connector/src/lib/signal-redux-store.ts +0 -59
  64. package/redux-connector/src/lib/util.ts +0 -22
  65. package/src/lib/assertions/assertions.ts +0 -9
  66. package/src/lib/devtools/internal/current-action-names.ts +0 -1
  67. package/src/lib/devtools/internal/default-tracker.ts +0 -60
  68. package/src/lib/devtools/internal/devtools-feature.ts +0 -37
  69. package/src/lib/devtools/internal/devtools-syncer.service.ts +0 -202
  70. package/src/lib/devtools/internal/glitch-tracker.service.ts +0 -61
  71. package/src/lib/devtools/internal/models.ts +0 -29
  72. package/src/lib/devtools/rename-devtools-name.ts +0 -21
  73. package/src/lib/devtools/tests/action-name.spec.ts +0 -48
  74. package/src/lib/devtools/tests/basic.spec.ts +0 -111
  75. package/src/lib/devtools/tests/connecting.spec.ts +0 -37
  76. package/src/lib/devtools/tests/helpers.spec.ts +0 -43
  77. package/src/lib/devtools/tests/naming.spec.ts +0 -216
  78. package/src/lib/devtools/tests/provide-devtools-config.spec.ts +0 -25
  79. package/src/lib/devtools/tests/types.spec.ts +0 -19
  80. package/src/lib/devtools/tests/update-state.spec.ts +0 -29
  81. package/src/lib/devtools/tests/with-devtools.spec.ts +0 -5
  82. package/src/lib/devtools/tests/with-glitch-tracking.spec.ts +0 -272
  83. package/src/lib/devtools/tests/with-mapper.spec.ts +0 -69
  84. package/src/lib/devtools/update-state.ts +0 -38
  85. package/src/lib/devtools/with-devtools.ts +0 -81
  86. package/src/lib/flattening-operator.ts +0 -42
  87. package/src/lib/immutable-state/deep-freeze.ts +0 -43
  88. package/src/lib/immutable-state/is-dev-mode.ts +0 -6
  89. package/src/lib/immutable-state/tests/with-immutable-state.spec.ts +0 -260
  90. package/src/lib/immutable-state/with-immutable-state.ts +0 -115
  91. package/src/lib/mutation/http-mutation.spec.ts +0 -473
  92. package/src/lib/mutation/http-mutation.ts +0 -172
  93. package/src/lib/mutation/mutation.ts +0 -26
  94. package/src/lib/mutation/rx-mutation.spec.ts +0 -594
  95. package/src/lib/mutation/rx-mutation.ts +0 -208
  96. package/src/lib/shared/prettify.ts +0 -3
  97. package/src/lib/shared/throw-if-null.ts +0 -7
  98. package/src/lib/storage-sync/features/with-indexed-db.ts +0 -81
  99. package/src/lib/storage-sync/features/with-local-storage.ts +0 -58
  100. package/src/lib/storage-sync/internal/indexeddb.service.ts +0 -124
  101. package/src/lib/storage-sync/internal/local-storage.service.ts +0 -19
  102. package/src/lib/storage-sync/internal/models.ts +0 -62
  103. package/src/lib/storage-sync/internal/session-storage.service.ts +0 -18
  104. package/src/lib/storage-sync/tests/indexeddb.service.spec.ts +0 -99
  105. package/src/lib/storage-sync/tests/with-storage-async.spec.ts +0 -308
  106. package/src/lib/storage-sync/tests/with-storage-sync.spec.ts +0 -268
  107. package/src/lib/storage-sync/with-storage-sync.ts +0 -233
  108. package/src/lib/with-call-state.spec.ts +0 -42
  109. package/src/lib/with-call-state.ts +0 -195
  110. package/src/lib/with-conditional.spec.ts +0 -125
  111. package/src/lib/with-data-service.spec.ts +0 -564
  112. package/src/lib/with-data-service.ts +0 -433
  113. package/src/lib/with-feature-factory.spec.ts +0 -69
  114. package/src/lib/with-mutations.spec.ts +0 -537
  115. package/src/lib/with-mutations.ts +0 -146
  116. package/src/lib/with-pagination.spec.ts +0 -90
  117. package/src/lib/with-pagination.ts +0 -353
  118. package/src/lib/with-redux.spec.ts +0 -258
  119. package/src/lib/with-redux.ts +0 -387
  120. package/src/lib/with-reset.spec.ts +0 -112
  121. package/src/lib/with-reset.ts +0 -62
  122. package/src/lib/with-undo-redo.spec.ts +0 -287
  123. package/src/lib/with-undo-redo.ts +0 -199
  124. package/src/test-setup.ts +0 -8
  125. package/tsconfig.json +0 -29
  126. package/tsconfig.lib.json +0 -17
  127. package/tsconfig.lib.prod.json +0 -9
  128. package/tsconfig.spec.json +0 -17
@@ -0,0 +1,2095 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Injectable, InjectionToken, signal, effect, inject, PLATFORM_ID, computed, isSignal, untracked, isDevMode as isDevMode$1, DestroyRef } from '@angular/core';
3
+ import { watchState, getState, signalStoreFeature, withMethods, withHooks, patchState as patchState$1, withState, withComputed, withProps } from '@ngrx/signals';
4
+ import { isPlatformBrowser, isPlatformServer } from '@angular/common';
5
+ import { Subject, switchMap, mergeMap, concatMap, exhaustMap, defer, tap, catchError, EMPTY, finalize, filter, map } from 'rxjs';
6
+ import { removeEntity, setAllEntities, updateEntity, addEntity } from '@ngrx/signals/entities';
7
+ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
8
+ import { HttpClient, HttpEventType, HttpResponse } from '@angular/common/http';
9
+
10
+ const DEVTOOLS_FEATURE = Symbol('DEVTOOLS_FEATURE');
11
+ function createDevtoolsFeature(options) {
12
+ return {
13
+ [DEVTOOLS_FEATURE]: true,
14
+ ...options,
15
+ };
16
+ }
17
+
18
+ /**
19
+ * If multiple instances of the same SignalStore class
20
+ * exist, their devtool names are indexed.
21
+ *
22
+ * For example:
23
+ *
24
+ * ```typescript
25
+ * const Store = signalStore(
26
+ * withDevtools('flights')
27
+ * )
28
+ *
29
+ * const store1 = new Store(); // will show up as 'flights'
30
+ * const store2 = new Store(); // will show up as 'flights-1'
31
+ * ```
32
+ *
33
+ * With adding `withDisabledNameIndices` to the store:
34
+ * ```typescript
35
+ * const Store = signalStore(
36
+ * withDevtools('flights', withDisabledNameIndices())
37
+ * )
38
+ *
39
+ * const store1 = new Store(); // will show up as 'flights'
40
+ * const store2 = new Store(); //💥 throws an error
41
+ * ```
42
+ *
43
+ */
44
+ function withDisabledNameIndices() {
45
+ return createDevtoolsFeature({ indexNames: false });
46
+ }
47
+
48
+ function throwIfNull(obj) {
49
+ if (obj === null || obj === undefined) {
50
+ throw new Error('');
51
+ }
52
+ return obj;
53
+ }
54
+
55
+ /**
56
+ * Internal Service used by {@link withGlitchTracking}. It does not rely
57
+ * on `effect` as {@link DefaultTracker} does but uses the NgRx function
58
+ * `watchState` to track all state changes.
59
+ */
60
+ class GlitchTrackerService {
61
+ #stores = {};
62
+ #callback;
63
+ get stores() {
64
+ return Object.entries(this.#stores).reduce((acc, [id, { store }]) => {
65
+ acc[id] = store;
66
+ return acc;
67
+ }, {});
68
+ }
69
+ onChange(callback) {
70
+ this.#callback = callback;
71
+ }
72
+ removeStore(id) {
73
+ this.#stores = Object.entries(this.#stores).reduce((newStore, [storeId, value]) => {
74
+ if (storeId !== id) {
75
+ newStore[storeId] = value;
76
+ }
77
+ else {
78
+ value.destroyWatcher();
79
+ }
80
+ return newStore;
81
+ }, {});
82
+ throwIfNull(this.#callback)({});
83
+ }
84
+ track(id, store) {
85
+ const watcher = watchState(store, (state) => {
86
+ throwIfNull(this.#callback)({ [id]: state });
87
+ });
88
+ this.#stores[id] = { destroyWatcher: watcher.destroy, store };
89
+ }
90
+ notifyRenamedStore(id) {
91
+ if (Object.keys(this.#stores).includes(id) && this.#callback) {
92
+ this.#callback({ [id]: getState(this.#stores[id].store) });
93
+ }
94
+ }
95
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: GlitchTrackerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
96
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: GlitchTrackerService, providedIn: 'root' }); }
97
+ }
98
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: GlitchTrackerService, decorators: [{
99
+ type: Injectable,
100
+ args: [{ providedIn: 'root' }]
101
+ }] });
102
+
103
+ /**
104
+ * It tracks all state changes of the State, including intermediary updates
105
+ * that are typically suppressed by Angular's glitch-free mechanism.
106
+ *
107
+ * This feature is especially useful for debugging.
108
+ *
109
+ * Example:
110
+ *
111
+ * ```typescript
112
+ * const Store = signalStore(
113
+ * { providedIn: 'root' },
114
+ * withState({ count: 0 }),
115
+ * withDevtools('counter', withGlitchTracking()),
116
+ * withMethods((store) => ({
117
+ * increase: () =>
118
+ * patchState(store, (value) => ({ count: value.count + 1 })),
119
+ * }))
120
+ * );
121
+ *
122
+ * // would show up in the DevTools with value 0
123
+ * const store = inject(Store);
124
+ *
125
+ * store.increase(); // would show up in the DevTools with value 1
126
+ * store.increase(); // would show up in the DevTools with value 2
127
+ * store.increase(); // would show up in the DevTools with value 3
128
+ * ```
129
+ *
130
+ * Without `withGlitchTracking`, the DevTools would only show the final value of 3.
131
+ */
132
+ function withGlitchTracking() {
133
+ return createDevtoolsFeature({ tracker: GlitchTrackerService });
134
+ }
135
+
136
+ /**
137
+ * Allows you to define a function to map the state.
138
+ *
139
+ * It is needed for huge states, that slows down the Devtools and where
140
+ * you don't need to see the whole state or other reasons.
141
+ *
142
+ * Example:
143
+ *
144
+ * ```typescript
145
+ * const initialState = {
146
+ * id: 1,
147
+ * email: 'john.list@host.com',
148
+ * name: 'John List',
149
+ * enteredPassword: ''
150
+ * }
151
+ *
152
+ * const Store = signalStore(
153
+ * withState(initialState),
154
+ * withDevtools(
155
+ * 'user',
156
+ * withMapper(state => ({...state, enteredPassword: '***' }))
157
+ * )
158
+ * )
159
+ * ```
160
+ *
161
+ * @param map function which maps the state
162
+ */
163
+ function withMapper(map) {
164
+ return createDevtoolsFeature({ map: map });
165
+ }
166
+
167
+ /**
168
+ * Provides the configuration options for connecting to the Redux DevTools Extension.
169
+ */
170
+ function provideDevtoolsConfig(config) {
171
+ return {
172
+ provide: REDUX_DEVTOOLS_CONFIG,
173
+ useValue: config,
174
+ };
175
+ }
176
+ /**
177
+ * Injection token for the configuration options for connecting to the Redux DevTools Extension.
178
+ */
179
+ const REDUX_DEVTOOLS_CONFIG = new InjectionToken('ReduxDevtoolsConfig');
180
+
181
+ class DefaultTracker {
182
+ #stores = signal({});
183
+ get stores() {
184
+ return this.#stores();
185
+ }
186
+ #trackCallback;
187
+ #trackingEffect = effect(() => {
188
+ if (this.#trackCallback === undefined) {
189
+ throw new Error('no callback function defined');
190
+ }
191
+ const stores = this.#stores();
192
+ const fullState = Object.entries(stores).reduce((acc, [id, store]) => {
193
+ return { ...acc, [id]: getState(store) };
194
+ }, {});
195
+ this.#trackCallback(fullState);
196
+ });
197
+ track(id, store) {
198
+ this.#stores.update((value) => ({
199
+ ...value,
200
+ [id]: store,
201
+ }));
202
+ }
203
+ onChange(callback) {
204
+ this.#trackCallback = callback;
205
+ }
206
+ removeStore(id) {
207
+ this.#stores.update((stores) => Object.entries(stores).reduce((newStore, [storeId, state]) => {
208
+ if (storeId !== id) {
209
+ newStore[storeId] = state;
210
+ }
211
+ return newStore;
212
+ }, {}));
213
+ }
214
+ notifyRenamedStore(id) {
215
+ if (this.#stores()[id]) {
216
+ this.#stores.update((stores) => {
217
+ return { ...stores };
218
+ });
219
+ }
220
+ }
221
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DefaultTracker, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
222
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DefaultTracker, providedIn: 'root' }); }
223
+ }
224
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DefaultTracker, decorators: [{
225
+ type: Injectable,
226
+ args: [{ providedIn: 'root' }]
227
+ }] });
228
+
229
+ const currentActionNames = new Set();
230
+
231
+ const dummyConnection = {
232
+ send: () => void true,
233
+ };
234
+ /**
235
+ * A service provided by the root injector is
236
+ * required because the synchronization runs
237
+ * globally.
238
+ *
239
+ * The SignalStore could be provided in a component.
240
+ * If the effect starts in the injection
241
+ * context of the SignalStore, the complete sync
242
+ * process would shut down once the component gets
243
+ * destroyed.
244
+ */
245
+ class DevtoolsSyncer {
246
+ /**
247
+ * Stores all SignalStores that are connected to the
248
+ * DevTools along their options, names and id.
249
+ */
250
+ #stores = {};
251
+ #isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
252
+ #trackers = [];
253
+ #devtoolsConfig = {
254
+ name: 'NgRx SignalStore',
255
+ ...inject(REDUX_DEVTOOLS_CONFIG, { optional: true }),
256
+ };
257
+ /**
258
+ * Maintains the current states of all stores to avoid conflicts
259
+ * between glitch-free and glitched trackers when used simultaneously.
260
+ *
261
+ * The challenge lies in ensuring that glitched trackers do not
262
+ * interfere with the synchronization process of glitch-free trackers.
263
+ * Specifically, glitched trackers could cause the synchronization to
264
+ * read the current state of stores managed by glitch-free trackers.
265
+ *
266
+ * Therefore, the synchronization process doesn't read the state from
267
+ * each store, but relies on #currentState.
268
+ *
269
+ * Please note, that here the key is the name and not the id.
270
+ */
271
+ #currentState = {};
272
+ #currentId = 1;
273
+ #connection = this.#isBrowser
274
+ ? window.__REDUX_DEVTOOLS_EXTENSION__
275
+ ? window.__REDUX_DEVTOOLS_EXTENSION__.connect(this.#devtoolsConfig)
276
+ : dummyConnection
277
+ : dummyConnection;
278
+ constructor() {
279
+ if (!this.#isBrowser) {
280
+ return;
281
+ }
282
+ }
283
+ ngOnDestroy() {
284
+ currentActionNames.clear();
285
+ }
286
+ syncToDevTools(changedStatePerId) {
287
+ const mappedChangedStatePerName = Object.entries(changedStatePerId).reduce((acc, [id, store]) => {
288
+ const { options, name } = this.#stores[id];
289
+ acc[name] = options.map(store);
290
+ return acc;
291
+ }, {});
292
+ this.#currentState = {
293
+ ...this.#currentState,
294
+ ...mappedChangedStatePerName,
295
+ };
296
+ const names = Array.from(currentActionNames);
297
+ const type = names.length ? names.join(', ') : 'Store Update';
298
+ currentActionNames.clear();
299
+ this.#connection.send({ type }, this.#currentState);
300
+ }
301
+ getNextId() {
302
+ return String(this.#currentId++);
303
+ }
304
+ /**
305
+ * Consumer provides the id. That is because we can only start
306
+ * tracking the store in the init hook.
307
+ * Unfortunately, methods for renaming having the final id
308
+ * need to be defined already before.
309
+ * That's why `withDevtools` requests first the id and
310
+ * then registers itself later.
311
+ */
312
+ addStore(id, name, store, options) {
313
+ let storeName = name;
314
+ const names = Object.values(this.#stores).map((store) => store.name);
315
+ if (names.includes(storeName)) {
316
+ // const { options } = throwIfNull(
317
+ // Object.values(this.#stores).find((store) => store.name === storeName)
318
+ // );
319
+ if (!options.indexNames) {
320
+ throw new Error(`An instance of the store ${storeName} already exists. \
321
+ Enable automatic indexing via withDevTools('${storeName}', { indexNames: true }), or rename it upon instantiation.`);
322
+ }
323
+ }
324
+ for (let i = 1; names.includes(storeName); i++) {
325
+ storeName = `${name}-${i}`;
326
+ }
327
+ this.#stores[id] = { name: storeName, options };
328
+ const tracker = options.tracker;
329
+ if (!this.#trackers.includes(tracker)) {
330
+ this.#trackers.push(tracker);
331
+ }
332
+ tracker.onChange((changedState) => this.syncToDevTools(changedState));
333
+ tracker.track(id, store);
334
+ }
335
+ removeStore(id) {
336
+ const name = this.#stores[id].name;
337
+ this.#stores = Object.entries(this.#stores).reduce((newStore, [storeId, value]) => {
338
+ if (storeId !== id) {
339
+ newStore[storeId] = value;
340
+ }
341
+ return newStore;
342
+ }, {});
343
+ this.#currentState = Object.entries(this.#currentState).reduce((newState, [storeName, state]) => {
344
+ if (storeName !== name) {
345
+ newState[name] = state;
346
+ }
347
+ return newState;
348
+ }, {});
349
+ for (const tracker of this.#trackers) {
350
+ tracker.removeStore(id);
351
+ }
352
+ }
353
+ renameStore(oldName, newName) {
354
+ const storeNames = Object.values(this.#stores).map((store) => store.name);
355
+ const id = throwIfNull(Object.keys(this.#stores).find((id) => this.#stores[id].name === oldName));
356
+ if (storeNames.includes(newName)) {
357
+ throw new Error(`NgRx Toolkit/DevTools: cannot rename from ${oldName} to ${newName}. ${newName} is already assigned to another SignalStore instance.`);
358
+ }
359
+ this.#stores = Object.entries(this.#stores).reduce((newStore, [id, value]) => {
360
+ if (value.name === oldName) {
361
+ newStore[id] = { ...value, name: newName };
362
+ }
363
+ else {
364
+ newStore[id] = value;
365
+ }
366
+ return newStore;
367
+ }, {});
368
+ // we don't rename in #currentState but wait for tracker to notify
369
+ // us with a changed state that contains that name.
370
+ this.#currentState = Object.entries(this.#currentState).reduce((newState, [storeName, state]) => {
371
+ if (storeName !== oldName) {
372
+ newState[storeName] = state;
373
+ }
374
+ return newState;
375
+ }, {});
376
+ this.#trackers.forEach((tracker) => tracker.notifyRenamedStore(id));
377
+ }
378
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DevtoolsSyncer, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
379
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DevtoolsSyncer, providedIn: 'root' }); }
380
+ }
381
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: DevtoolsSyncer, decorators: [{
382
+ type: Injectable,
383
+ args: [{ providedIn: 'root' }]
384
+ }], ctorParameters: () => [] });
385
+
386
+ const renameDevtoolsMethodName = '___renameDevtoolsName';
387
+ const uniqueDevtoolsId = '___uniqueDevtoolsId';
388
+ const EXISTING_NAMES = new InjectionToken('Array contain existing names for the signal stores', { factory: () => [], providedIn: 'root' });
389
+ /**
390
+ * Adds this store as a feature state to the Redux DevTools.
391
+ *
392
+ * By default, the action name is 'Store Update'. You can
393
+ * change that via the {@link updateState} method, which has as second
394
+ * parameter the action name.
395
+ *
396
+ * The standalone function {@link renameDevtoolsName} can rename
397
+ * the store name.
398
+ *
399
+ * @param name name of the store as it should appear in the DevTools
400
+ * @param features features to extend or modify the behavior of the Devtools
401
+ */
402
+ function withDevtools(name, ...features) {
403
+ return signalStoreFeature(withMethods(() => {
404
+ const syncer = inject(DevtoolsSyncer);
405
+ const id = syncer.getNextId();
406
+ // TODO: use withProps and symbols
407
+ return {
408
+ [renameDevtoolsMethodName]: (newName) => {
409
+ syncer.renameStore(name, newName);
410
+ },
411
+ [uniqueDevtoolsId]: () => id,
412
+ };
413
+ }), withHooks((store) => {
414
+ const syncer = inject(DevtoolsSyncer);
415
+ const id = String(store[uniqueDevtoolsId]());
416
+ return {
417
+ onInit() {
418
+ const id = String(store[uniqueDevtoolsId]());
419
+ const finalOptions = {
420
+ indexNames: !features.some((f) => f.indexNames === false),
421
+ map: features.find((f) => f.map)?.map ?? ((state) => state),
422
+ tracker: inject(features.find((f) => f.tracker)?.tracker || DefaultTracker),
423
+ };
424
+ syncer.addStore(id, name, store, finalOptions);
425
+ },
426
+ onDestroy() {
427
+ syncer.removeStore(id);
428
+ },
429
+ };
430
+ }));
431
+ }
432
+
433
+ /**
434
+ * Renames the name of a store how it appears in the Devtools.
435
+ * @param store instance of the SignalStore
436
+ * @param newName new name for the Devtools
437
+ */
438
+ function renameDevtoolsName(store, newName) {
439
+ const renameMethod = store[renameDevtoolsMethodName];
440
+ if (!renameMethod) {
441
+ throw new Error("Devtools extensions haven't been added to this store.");
442
+ }
443
+ renameMethod(newName);
444
+ }
445
+
446
+ /**
447
+ * @deprecated Has been renamed to `updateState`
448
+ */
449
+ const patchState = (state, action, ...rest) => {
450
+ updateState(state, action, ...rest);
451
+ };
452
+ /**
453
+ * Wrapper of `patchState` for DevTools integration. Next to updating the state,
454
+ * it also sends the action to the DevTools.
455
+ * @param stateSource state of Signal Store
456
+ * @param action name of action how it will show in DevTools
457
+ * @param updaters updater functions or objects
458
+ */
459
+ function updateState(stateSource, action, ...updaters) {
460
+ currentActionNames.add(action);
461
+ return patchState$1(stateSource, ...updaters);
462
+ }
463
+
464
+ /**
465
+ * Stub for DevTools integration. Can be used to disable DevTools in production.
466
+ */
467
+ const withDevToolsStub = () => (store) => store;
468
+
469
+ function assertActionFnSpecs(obj) {
470
+ if (!obj || typeof obj !== 'object') {
471
+ throw new Error('%o is not an Action Specification');
472
+ }
473
+ }
474
+
475
+ function payload() {
476
+ return {};
477
+ }
478
+ const noPayload = {};
479
+ /**
480
+ * Creates a reducer function to separate the reducer logic into another file.
481
+ *
482
+ * ```typescript
483
+ * interface FlightState {
484
+ * flights: Flight[];
485
+ * effect1: boolean;
486
+ * effect2: boolean;
487
+ * }
488
+ *
489
+ * const initialState: FlightState = {
490
+ * flights: [],
491
+ * effect1: false,
492
+ * effect2: false,
493
+ * };
494
+ *
495
+ * const actions = {
496
+ * init: noPayload,
497
+ * updateEffect1: payload<{ value: boolean }>(),
498
+ * updateEffect2: payload<{ value: boolean }>(),
499
+ * };
500
+ *
501
+ * const reducer = createReducer<FlightState, typeof actions>((actions, on) => {
502
+ * on(actions.updateEffect1, (state, { value }) => {
503
+ * patchState(state, { effect1: value });
504
+ * });
505
+ *
506
+ * on(actions.updateEffect2, (state, { value }) => {
507
+ * patchState(state, { effect2: value });
508
+ * });
509
+ * });
510
+ *
511
+ * signalStore(
512
+ * withState(initialState),
513
+ * withRedux({
514
+ * actions,
515
+ * reducer,
516
+ * })
517
+ * );
518
+ * ```
519
+ * @param reducerFactory
520
+ */
521
+ function createReducer(reducerFactory) {
522
+ return reducerFactory;
523
+ }
524
+ /**
525
+ * @deprecated Use NgRx's `@ngrx/signals/events` starting in 19.2
526
+ *
527
+ * Creates the effects function to separate the effects logic into another file.
528
+ *
529
+ * ```typescript
530
+ * interface FlightState {
531
+ * flights: Flight[];
532
+ * effect1: boolean;
533
+ * effect2: boolean;
534
+ * }
535
+ *
536
+ * const initialState: FlightState = {
537
+ * flights: [],
538
+ * effect1: false,
539
+ * effect2: false,
540
+ * };
541
+ *
542
+ * const actions = {
543
+ * init: noPayload,
544
+ * updateEffect1: payload<{ value: boolean }>(),
545
+ * updateEffect2: payload<{ value: boolean }>(),
546
+ * };
547
+ *
548
+ * const effects = createEffects(actions, (actions, create) => {
549
+ * return {
550
+ * init1$: create(actions.init).pipe(
551
+ * map(() => actions.updateEffect1({ value: true }))
552
+ * ),
553
+ * init2$: create(actions.init).pipe(
554
+ * map(() => actions.updateEffect2({ value: true }))
555
+ * ),
556
+ * };
557
+ * });
558
+ *
559
+ * signalStore(
560
+ * withState(initialState),
561
+ * withRedux({
562
+ * actions,
563
+ * effects,
564
+ * })
565
+ * );
566
+ * ```
567
+ * @param actions
568
+ * @param effectsFactory
569
+ */
570
+ function createEffects(actions, effectsFactory) {
571
+ return effectsFactory;
572
+ }
573
+ function createActionFns(actionFnSpecs, reducerRegistry, effectsRegistry, state) {
574
+ const actionFns = {};
575
+ for (const type in actionFnSpecs) {
576
+ const actionFn = (payload) => {
577
+ const fullPayload = { ...payload, type };
578
+ const reducer = reducerRegistry[type];
579
+ if (reducer) {
580
+ reducer(state, fullPayload);
581
+ }
582
+ const effectSubjects = effectsRegistry[type];
583
+ if (effectSubjects?.length) {
584
+ for (const effectSubject of effectSubjects) {
585
+ effectSubject.next(fullPayload);
586
+ }
587
+ }
588
+ return fullPayload;
589
+ };
590
+ actionFn.type = type.toString();
591
+ actionFns[type] = actionFn;
592
+ }
593
+ return actionFns;
594
+ }
595
+ function createPublicAndAllActionsFns(actionFnSpecs, reducerRegistry, effectsRegistry, state) {
596
+ if ('public' in actionFnSpecs || 'private' in actionFnSpecs) {
597
+ const privates = actionFnSpecs['private'] || {};
598
+ const publics = actionFnSpecs['public'] || {};
599
+ assertActionFnSpecs(privates);
600
+ assertActionFnSpecs(publics);
601
+ const privateActionFns = createActionFns(privates, reducerRegistry, effectsRegistry, state);
602
+ const publicActionFns = createActionFns(publics, reducerRegistry, effectsRegistry, state);
603
+ return {
604
+ all: { ...privateActionFns, ...publicActionFns },
605
+ publics: publicActionFns,
606
+ };
607
+ }
608
+ const actionFns = createActionFns(actionFnSpecs, reducerRegistry, effectsRegistry, state);
609
+ return { all: actionFns, publics: actionFns };
610
+ }
611
+ function fillReducerRegistry(reducer, actionFns, reducerRegistry) {
612
+ function on(action, reducerFn) {
613
+ reducerRegistry[action.type] = reducerFn;
614
+ }
615
+ reducer(actionFns, on);
616
+ return reducerRegistry;
617
+ }
618
+ function fillEffects(effects, actionFns, effectsRegistry = {}) {
619
+ function create(action) {
620
+ const subject = new Subject();
621
+ if (!(action.type in effectsRegistry)) {
622
+ effectsRegistry[action.type] = [];
623
+ }
624
+ effectsRegistry[action.type].push(subject);
625
+ return subject.asObservable();
626
+ }
627
+ const effectObservables = effects(actionFns, create);
628
+ return Object.values(effectObservables);
629
+ }
630
+ function startSubscriptions(observables) {
631
+ return observables.map((observable) => observable.subscribe());
632
+ }
633
+ function processRedux(actionFnSpecs, reducer, effects, store) {
634
+ const reducerRegistry = {};
635
+ const effectsRegistry = {};
636
+ const actionsMap = createPublicAndAllActionsFns(actionFnSpecs, reducerRegistry, effectsRegistry, store);
637
+ const actionFns = actionsMap.all;
638
+ const publicActionsFns = actionsMap.publics;
639
+ fillReducerRegistry(reducer, actionFns, reducerRegistry);
640
+ const effectObservables = fillEffects(effects, actionFns, effectsRegistry);
641
+ const subscriptions = startSubscriptions(effectObservables);
642
+ return {
643
+ methods: publicActionsFns,
644
+ subscriptions: subscriptions,
645
+ };
646
+ }
647
+ /**
648
+ * @param redux redux
649
+ *
650
+ * properties do not start with `with` since they are not extension functions on their own.
651
+ *
652
+ * no dependency to NgRx
653
+ *
654
+ * actions are passed to reducer and effects, but it is also possible to use other actions.
655
+ * effects provide forAction and do not return anything. that is important because effects should stay inaccessible
656
+ */
657
+ function withRedux(redux) {
658
+ return (store) => {
659
+ const { methods } = processRedux(redux.actions, redux.reducer, redux.effects, store);
660
+ return {
661
+ ...store,
662
+ methods: { ...store.methods, ...methods },
663
+ };
664
+ };
665
+ }
666
+
667
+ function deriveCallStateKeys(collection) {
668
+ return {
669
+ callStateKey: collection ? `${collection}CallState` : 'callState',
670
+ loadingKey: collection ? `${collection}Loading` : 'loading',
671
+ loadedKey: collection ? `${collection}Loaded` : 'loaded',
672
+ errorKey: collection ? `${collection}Error` : 'error',
673
+ };
674
+ }
675
+ function getCallStateKeys(config) {
676
+ const prop = config?.collection;
677
+ return deriveCallStateKeys(prop);
678
+ }
679
+ function getCollectionArray(config) {
680
+ return 'collections' in config
681
+ ? config.collections
682
+ : 'collection' in config && config.collection
683
+ ? [config.collection]
684
+ : undefined;
685
+ }
686
+ function withCallState(config) {
687
+ return signalStoreFeature(withState(() => {
688
+ if (!config) {
689
+ return { callState: 'init' };
690
+ }
691
+ const collections = getCollectionArray(config);
692
+ if (collections) {
693
+ return collections.reduce((acc, cur) => ({
694
+ ...acc,
695
+ ...{ [cur ? `${cur}CallState` : 'callState']: 'init' },
696
+ }), {});
697
+ }
698
+ return { callState: 'init' };
699
+ }), withComputed((state) => {
700
+ if (config) {
701
+ const collections = getCollectionArray(config);
702
+ if (collections) {
703
+ return collections.reduce((acc, cur) => {
704
+ const { callStateKey, errorKey, loadedKey, loadingKey } = deriveCallStateKeys(cur);
705
+ const callState = state[callStateKey];
706
+ return {
707
+ ...acc,
708
+ [loadingKey]: computed(() => callState() === 'loading'),
709
+ [loadedKey]: computed(() => callState() === 'loaded'),
710
+ [errorKey]: computed(() => {
711
+ const v = callState();
712
+ return typeof v === 'object' ? v.error : null;
713
+ }),
714
+ };
715
+ }, {});
716
+ }
717
+ }
718
+ const { callStateKey, errorKey, loadedKey, loadingKey } = deriveCallStateKeys();
719
+ const callState = state[callStateKey];
720
+ return {
721
+ [loadingKey]: computed(() => callState() === 'loading'),
722
+ [loadedKey]: computed(() => callState() === 'loaded'),
723
+ [errorKey]: computed(() => {
724
+ const v = callState();
725
+ return typeof v === 'object' ? v.error : null;
726
+ }),
727
+ };
728
+ }));
729
+ }
730
+ function setLoading(prop) {
731
+ if (prop) {
732
+ return { [`${prop}CallState`]: 'loading' };
733
+ }
734
+ return { callState: 'loading' };
735
+ }
736
+ function setLoaded(prop) {
737
+ if (prop) {
738
+ return { [`${prop}CallState`]: 'loaded' };
739
+ }
740
+ else {
741
+ return { callState: 'loaded' };
742
+ }
743
+ }
744
+ function setError(error, prop) {
745
+ let errorMessage;
746
+ if (!error) {
747
+ errorMessage = '';
748
+ }
749
+ else if (typeof error === 'object' && 'message' in error) {
750
+ errorMessage = String(error.message);
751
+ }
752
+ else {
753
+ errorMessage = String(error);
754
+ }
755
+ if (prop) {
756
+ return {
757
+ [`${prop}CallState`]: { error: errorMessage },
758
+ };
759
+ }
760
+ else {
761
+ return { callState: { error: errorMessage } };
762
+ }
763
+ }
764
+
765
+ function capitalize(str) {
766
+ return str ? str[0].toUpperCase() + str.substring(1) : str;
767
+ }
768
+ function getDataServiceKeys(options) {
769
+ const filterKey = options.collection
770
+ ? `${options.collection}Filter`
771
+ : 'filter';
772
+ const selectedIdsKey = options.collection
773
+ ? `selected${capitalize(options.collection)}Ids`
774
+ : 'selectedIds';
775
+ const selectedEntitiesKey = options.collection
776
+ ? `selected${capitalize(options.collection)}Entities`
777
+ : 'selectedEntities';
778
+ const updateFilterKey = options.collection
779
+ ? `update${capitalize(options.collection)}Filter`
780
+ : 'updateFilter';
781
+ const updateSelectedKey = options.collection
782
+ ? `updateSelected${capitalize(options.collection)}Entities`
783
+ : 'updateSelected';
784
+ const loadKey = options.collection
785
+ ? `load${capitalize(options.collection)}Entities`
786
+ : 'load';
787
+ const currentKey = options.collection
788
+ ? `current${capitalize(options.collection)}`
789
+ : 'current';
790
+ const loadByIdKey = options.collection
791
+ ? `load${capitalize(options.collection)}ById`
792
+ : 'loadById';
793
+ const setCurrentKey = options.collection
794
+ ? `setCurrent${capitalize(options.collection)}`
795
+ : 'setCurrent';
796
+ const createKey = options.collection
797
+ ? `create${capitalize(options.collection)}`
798
+ : 'create';
799
+ const updateKey = options.collection
800
+ ? `update${capitalize(options.collection)}`
801
+ : 'update';
802
+ const updateAllKey = options.collection
803
+ ? `updateAll${capitalize(options.collection)}`
804
+ : 'updateAll';
805
+ const deleteKey = options.collection
806
+ ? `delete${capitalize(options.collection)}`
807
+ : 'delete';
808
+ // TODO: Take these from @ngrx/signals/entities, when they are exported
809
+ const entitiesKey = options.collection
810
+ ? `${options.collection}Entities`
811
+ : 'entities';
812
+ const entityMapKey = options.collection
813
+ ? `${options.collection}EntityMap`
814
+ : 'entityMap';
815
+ const idsKey = options.collection ? `${options.collection}Ids` : 'ids';
816
+ return {
817
+ filterKey,
818
+ selectedIdsKey,
819
+ selectedEntitiesKey,
820
+ updateFilterKey,
821
+ updateSelectedKey,
822
+ loadKey,
823
+ entitiesKey,
824
+ entityMapKey,
825
+ idsKey,
826
+ currentKey,
827
+ loadByIdKey,
828
+ setCurrentKey,
829
+ createKey,
830
+ updateKey,
831
+ updateAllKey,
832
+ deleteKey,
833
+ };
834
+ }
835
+ function withDataService(options) {
836
+ const { dataServiceType, filter, collection: prefix } = options;
837
+ const { entitiesKey, filterKey, loadKey, selectedEntitiesKey, selectedIdsKey, updateFilterKey, updateSelectedKey, currentKey, createKey, updateKey, updateAllKey, deleteKey, loadByIdKey, setCurrentKey, } = getDataServiceKeys(options);
838
+ const { callStateKey } = getCallStateKeys({ collection: prefix });
839
+ return signalStoreFeature(withState(() => ({
840
+ [filterKey]: filter,
841
+ [selectedIdsKey]: {},
842
+ [currentKey]: undefined,
843
+ })), withComputed((store) => {
844
+ const entities = store[entitiesKey];
845
+ const selectedIds = store[selectedIdsKey];
846
+ return {
847
+ [selectedEntitiesKey]: computed(() => entities().filter((e) => selectedIds()[e.id])),
848
+ };
849
+ }), withMethods((store) => {
850
+ const dataService = inject(dataServiceType);
851
+ return {
852
+ [updateFilterKey]: (filter) => {
853
+ patchState$1(store, { [filterKey]: filter });
854
+ },
855
+ [updateSelectedKey]: (id, selected) => {
856
+ patchState$1(store, (state) => ({
857
+ [selectedIdsKey]: {
858
+ ...state[selectedIdsKey],
859
+ [id]: selected,
860
+ },
861
+ }));
862
+ },
863
+ [loadKey]: async () => {
864
+ const filter = store[filterKey];
865
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
866
+ try {
867
+ const result = await dataService.load(filter());
868
+ patchState$1(store, prefix
869
+ ? setAllEntities(result, { collection: prefix })
870
+ : setAllEntities(result));
871
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
872
+ }
873
+ catch (e) {
874
+ (() => store[callStateKey] &&
875
+ patchState$1(store, setError(e, prefix)))();
876
+ throw e;
877
+ }
878
+ },
879
+ [loadByIdKey]: async (id) => {
880
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
881
+ try {
882
+ const current = await dataService.loadById(id);
883
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
884
+ patchState$1(store, { [currentKey]: current });
885
+ }
886
+ catch (e) {
887
+ (() => store[callStateKey] &&
888
+ patchState$1(store, setError(e, prefix)))();
889
+ throw e;
890
+ }
891
+ },
892
+ [setCurrentKey]: (current) => {
893
+ patchState$1(store, { [currentKey]: current });
894
+ },
895
+ [createKey]: async (entity) => {
896
+ patchState$1(store, { [currentKey]: entity });
897
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
898
+ try {
899
+ const created = await dataService.create(entity);
900
+ patchState$1(store, { [currentKey]: created });
901
+ patchState$1(store, prefix
902
+ ? addEntity(created, { collection: prefix })
903
+ : addEntity(created));
904
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
905
+ }
906
+ catch (e) {
907
+ (() => store[callStateKey] &&
908
+ patchState$1(store, setError(e, prefix)))();
909
+ throw e;
910
+ }
911
+ },
912
+ [updateKey]: async (entity) => {
913
+ patchState$1(store, { [currentKey]: entity });
914
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
915
+ try {
916
+ const updated = await dataService.update(entity);
917
+ patchState$1(store, { [currentKey]: updated });
918
+ const updateArg = {
919
+ id: updated.id,
920
+ changes: updated,
921
+ };
922
+ const updater = (collection) => updateEntity(updateArg, { collection });
923
+ patchState$1(store, prefix ? updater(prefix) : updateEntity(updateArg));
924
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
925
+ }
926
+ catch (e) {
927
+ (() => store[callStateKey] &&
928
+ patchState$1(store, setError(e, prefix)))();
929
+ throw e;
930
+ }
931
+ },
932
+ [updateAllKey]: async (entities) => {
933
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
934
+ try {
935
+ const result = await dataService.updateAll(entities);
936
+ patchState$1(store, prefix
937
+ ? setAllEntities(result, { collection: prefix })
938
+ : setAllEntities(result));
939
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
940
+ }
941
+ catch (e) {
942
+ (() => store[callStateKey] &&
943
+ patchState$1(store, setError(e, prefix)))();
944
+ throw e;
945
+ }
946
+ },
947
+ [deleteKey]: async (entity) => {
948
+ patchState$1(store, { [currentKey]: entity });
949
+ (() => store[callStateKey] && patchState$1(store, setLoading(prefix)))();
950
+ try {
951
+ await dataService.delete(entity);
952
+ patchState$1(store, { [currentKey]: undefined });
953
+ patchState$1(store, prefix
954
+ ? removeEntity(entity.id, { collection: prefix })
955
+ : removeEntity(entity.id));
956
+ (() => store[callStateKey] && patchState$1(store, setLoaded(prefix)))();
957
+ }
958
+ catch (e) {
959
+ (() => store[callStateKey] &&
960
+ patchState$1(store, setError(e, prefix)))();
961
+ throw e;
962
+ }
963
+ },
964
+ };
965
+ }));
966
+ }
967
+
968
+ /** With pagination comes in two flavors the first one is local pagination or in memory pagination. For example we have 2000 items which we want
969
+ * to display in a table and the response payload is small enough to be stored in the memory. But we can not display all 2000 items at once
970
+ * so we need to paginate the data. The second flavor is server side pagination where the response payload is too large to be stored in the memory
971
+ * and we need to fetch the data from the server in chunks. In the second case we 'could' also cache the data in the memory but that could lead to
972
+ * other problems like memory leaks and stale data. So we will not cache the data in the memory in the second case.
973
+ * This feature implements the local pagination.
974
+ */
975
+ function withPagination(options) {
976
+ const { pageKey, pageSizeKey, entitiesKey, selectedPageEntitiesKey, totalCountKey, pageCountKey, pageNavigationArrayMaxKey, pageNavigationArrayKey, hasNextPageKey, hasPreviousPageKey, } = createPaginationKeys(options);
977
+ return signalStoreFeature(withState({
978
+ [pageKey]: 0,
979
+ [pageSizeKey]: 10,
980
+ [pageNavigationArrayMaxKey]: 7,
981
+ }), withComputed((store) => {
982
+ const entities = store[entitiesKey];
983
+ const page = store[pageKey];
984
+ const pageSize = store[pageSizeKey];
985
+ const pageNavigationArrayMax = store[pageNavigationArrayMaxKey];
986
+ return {
987
+ // The derived enitites which are displayed on the current page
988
+ [selectedPageEntitiesKey]: computed(() => {
989
+ const pageSizeValue = pageSize();
990
+ const pageValue = page();
991
+ return entities().slice(pageValue * pageSizeValue, (pageValue + 1) * pageSizeValue);
992
+ }),
993
+ [totalCountKey]: computed(() => entities().length),
994
+ [pageCountKey]: computed(() => {
995
+ const totalCountValue = entities().length;
996
+ const pageSizeValue = pageSize();
997
+ if (totalCountValue === 0) {
998
+ return 0;
999
+ }
1000
+ return Math.ceil(totalCountValue / pageSizeValue);
1001
+ }),
1002
+ [pageNavigationArrayKey]: computed(() => createPageArray(page(), pageSize(), entities().length, pageNavigationArrayMax())),
1003
+ [hasNextPageKey]: computed(() => {
1004
+ return page() < pageSize();
1005
+ }),
1006
+ [hasPreviousPageKey]: computed(() => {
1007
+ return page() > 1;
1008
+ }),
1009
+ };
1010
+ }));
1011
+ }
1012
+ function gotoPage(page, options) {
1013
+ const { pageKey } = createPaginationKeys(options);
1014
+ return {
1015
+ [pageKey]: page,
1016
+ };
1017
+ }
1018
+ function setPageSize(pageSize, options) {
1019
+ const { pageSizeKey } = createPaginationKeys(options);
1020
+ return {
1021
+ [pageSizeKey]: pageSize,
1022
+ };
1023
+ }
1024
+ function nextPage(options) {
1025
+ const { pageKey } = createPaginationKeys(options);
1026
+ return {
1027
+ [pageKey]: (currentPage) => currentPage + 1,
1028
+ };
1029
+ }
1030
+ function previousPage(options) {
1031
+ const { pageKey } = createPaginationKeys(options);
1032
+ return {
1033
+ [pageKey]: (currentPage) => Math.max(currentPage - 1, 1),
1034
+ };
1035
+ }
1036
+ function firstPage(options) {
1037
+ const { pageKey } = createPaginationKeys(options);
1038
+ return {
1039
+ [pageKey]: 1,
1040
+ };
1041
+ }
1042
+ function setMaxPageNavigationArrayItems(maxPageNavigationArrayItems, options) {
1043
+ const { pageNavigationArrayMaxKey } = createPaginationKeys(options);
1044
+ return {
1045
+ [pageNavigationArrayMaxKey]: maxPageNavigationArrayItems,
1046
+ };
1047
+ }
1048
+ function createPaginationKeys(options) {
1049
+ const entitiesKey = options?.collection
1050
+ ? `${options.collection}Entities`
1051
+ : 'entities';
1052
+ const selectedPageEntitiesKey = options?.collection
1053
+ ? `selectedPage${capitalize(options?.collection)}Entities`
1054
+ : 'selectedPageEntities';
1055
+ const pageKey = options?.collection
1056
+ ? `${options.collection}CurrentPage`
1057
+ : 'currentPage';
1058
+ const pageSizeKey = options?.collection
1059
+ ? `${options.collection}PageSize`
1060
+ : 'pageSize';
1061
+ const totalCountKey = options?.collection
1062
+ ? `${options.collection}TotalCount`
1063
+ : 'totalCount';
1064
+ const pageCountKey = options?.collection
1065
+ ? `${options.collection}PageCount`
1066
+ : 'pageCount';
1067
+ const pageNavigationArrayMaxKey = options?.collection
1068
+ ? `${options.collection}PageNavigationArrayMax`
1069
+ : 'pageNavigationArrayMax';
1070
+ const pageNavigationArrayKey = options?.collection
1071
+ ? `${options.collection}PageNavigationArray`
1072
+ : 'pageNavigationArray';
1073
+ const hasNextPageKey = options?.collection
1074
+ ? `hasNext${capitalize(options.collection)}Page`
1075
+ : 'hasNextPage';
1076
+ const hasPreviousPageKey = options?.collection
1077
+ ? `hasPrevious${capitalize(options.collection)}Page`
1078
+ : 'hasPreviousPage';
1079
+ return {
1080
+ pageKey,
1081
+ pageSizeKey,
1082
+ entitiesKey,
1083
+ selectedPageEntitiesKey,
1084
+ totalCountKey,
1085
+ pageCountKey,
1086
+ pageNavigationArrayKey,
1087
+ pageNavigationArrayMaxKey,
1088
+ hasNextPageKey,
1089
+ hasPreviousPageKey,
1090
+ };
1091
+ }
1092
+ function createPageArray(currentPage, itemsPerPage, totalItems, paginationRange) {
1093
+ // Convert paginationRange to number in case it's a string
1094
+ paginationRange = +paginationRange;
1095
+ // Calculate total number of pages
1096
+ const totalPages = Math.max(Math.ceil(totalItems / itemsPerPage), 1);
1097
+ const halfWay = Math.ceil(paginationRange / 2);
1098
+ const isStart = currentPage <= halfWay;
1099
+ const isEnd = totalPages - halfWay < currentPage;
1100
+ const isMiddle = !isStart && !isEnd;
1101
+ const ellipsesNeeded = paginationRange < totalPages;
1102
+ const pages = [];
1103
+ for (let i = 1; i <= totalPages && i <= paginationRange; i++) {
1104
+ let pageNumber = i;
1105
+ if (i === paginationRange) {
1106
+ pageNumber = totalPages;
1107
+ }
1108
+ else if (ellipsesNeeded) {
1109
+ if (isEnd) {
1110
+ pageNumber = totalPages - paginationRange + i;
1111
+ }
1112
+ else if (isMiddle) {
1113
+ pageNumber = currentPage - halfWay + i;
1114
+ }
1115
+ }
1116
+ const openingEllipsesNeeded = i === 2 && (isMiddle || isEnd);
1117
+ const closingEllipsesNeeded = i === paginationRange - 1 && (isMiddle || isStart);
1118
+ const label = ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)
1119
+ ? '...'
1120
+ : pageNumber;
1121
+ pages.push({ label, value: pageNumber });
1122
+ }
1123
+ return pages;
1124
+ }
1125
+
1126
+ /**
1127
+ * Adds a `resetState` method to the store, which resets the state
1128
+ * to the initial state.
1129
+ *
1130
+ * If you want to set a custom initial state, you can use {@link setResetState}.
1131
+ */
1132
+ function withReset() {
1133
+ return signalStoreFeature(withProps(() => ({ _resetState: { value: {} } })), withMethods((store) => {
1134
+ // workaround to TS excessive property check
1135
+ const methods = {
1136
+ resetState() {
1137
+ patchState$1(store, store._resetState.value);
1138
+ },
1139
+ __setResetState__(state) {
1140
+ store._resetState.value = state;
1141
+ },
1142
+ };
1143
+ return methods;
1144
+ }), withHooks((store) => ({
1145
+ onInit() {
1146
+ store._resetState.value = getState(store);
1147
+ },
1148
+ })));
1149
+ }
1150
+ /**
1151
+ * Sets the reset state of the store to the given state.
1152
+ *
1153
+ * Throws an error if the store is not configured with {@link withReset}.
1154
+ * @param store the instance of a SignalStore
1155
+ * @param state the state to set as the reset state
1156
+ */
1157
+ function setResetState(store, state) {
1158
+ if (!('__setResetState__' in store)) {
1159
+ throw new Error('Cannot set reset state, since store is not configured with withReset()');
1160
+ }
1161
+ store.__setResetState__(state);
1162
+ }
1163
+
1164
+ const defaultOptions = {
1165
+ maxStackSize: 100,
1166
+ keys: [],
1167
+ skip: 0,
1168
+ };
1169
+ function getUndoRedoKeys(collections) {
1170
+ if (collections) {
1171
+ return collections.flatMap((c) => [
1172
+ `${c}EntityMap`,
1173
+ `${c}Ids`,
1174
+ `selected${capitalize(c)}Ids`,
1175
+ `${c}Filter`,
1176
+ ]);
1177
+ }
1178
+ return ['entityMap', 'ids', 'selectedIds', 'filter'];
1179
+ }
1180
+ function withUndoRedo(options) {
1181
+ let previous = null;
1182
+ let skipOnce = false;
1183
+ const normalized = {
1184
+ ...defaultOptions,
1185
+ ...options,
1186
+ };
1187
+ //
1188
+ // Design Decision: This feature has its own
1189
+ // internal state.
1190
+ //
1191
+ const undoStack = [];
1192
+ const redoStack = [];
1193
+ const canUndo = signal(false);
1194
+ const canRedo = signal(false);
1195
+ const updateInternal = () => {
1196
+ canUndo.set(undoStack.length !== 0);
1197
+ canRedo.set(redoStack.length !== 0);
1198
+ };
1199
+ const keys = [...getUndoRedoKeys(normalized.collections), ...normalized.keys];
1200
+ return signalStoreFeature(withComputed(() => ({
1201
+ canUndo: canUndo.asReadonly(),
1202
+ canRedo: canRedo.asReadonly(),
1203
+ })), withMethods((store) => ({
1204
+ undo() {
1205
+ const item = undoStack.pop();
1206
+ if (item && previous) {
1207
+ redoStack.push(previous);
1208
+ }
1209
+ if (item) {
1210
+ skipOnce = true;
1211
+ patchState$1(store, item);
1212
+ previous = item;
1213
+ }
1214
+ updateInternal();
1215
+ },
1216
+ redo() {
1217
+ const item = redoStack.pop();
1218
+ if (item && previous) {
1219
+ undoStack.push(previous);
1220
+ }
1221
+ if (item) {
1222
+ skipOnce = true;
1223
+ patchState$1(store, item);
1224
+ previous = item;
1225
+ }
1226
+ updateInternal();
1227
+ },
1228
+ clearStack() {
1229
+ undoStack.splice(0);
1230
+ redoStack.splice(0);
1231
+ previous = null;
1232
+ updateInternal();
1233
+ },
1234
+ })), withHooks({
1235
+ onInit(store) {
1236
+ effect(() => {
1237
+ const cand = keys.reduce((acc, key) => {
1238
+ const s = store[key];
1239
+ if (s && isSignal(s)) {
1240
+ return {
1241
+ ...acc,
1242
+ [key]: s(),
1243
+ };
1244
+ }
1245
+ return acc;
1246
+ }, {});
1247
+ if (normalized.skip > 0) {
1248
+ normalized.skip--;
1249
+ return;
1250
+ }
1251
+ if (skipOnce) {
1252
+ skipOnce = false;
1253
+ return;
1254
+ }
1255
+ //
1256
+ // Deep Comparison to prevent duplicated entries
1257
+ // on the stack. This can e.g. happen after an undo
1258
+ // if the component sends back the undone filter
1259
+ // to the store.
1260
+ //
1261
+ if (JSON.stringify(cand) === JSON.stringify(previous)) {
1262
+ return;
1263
+ }
1264
+ // Clear redoStack after recorded action
1265
+ redoStack.splice(0);
1266
+ if (previous) {
1267
+ undoStack.push(previous);
1268
+ }
1269
+ if (redoStack.length > normalized.maxStackSize) {
1270
+ undoStack.unshift();
1271
+ }
1272
+ previous = cand;
1273
+ // Don't propogate current reactive context
1274
+ untracked(() => updateInternal());
1275
+ });
1276
+ },
1277
+ }));
1278
+ }
1279
+
1280
+ /**
1281
+ * Deep freezes a state object along its properties with primitive values
1282
+ * on the first level.
1283
+ *
1284
+ * The reason for this is that the final state is a merge of all
1285
+ * root properties of all states, i.e. `withState`,....
1286
+ *
1287
+ * Since the root object will not be part of the state (shadow clone),
1288
+ * we are not freezing it.
1289
+ */
1290
+ function deepFreeze(target,
1291
+ // if empty all properties will be frozen
1292
+ propertyNamesToBeFrozen,
1293
+ // also means that we are on the first level
1294
+ isRoot = true) {
1295
+ const runPropertyNameCheck = propertyNamesToBeFrozen.length > 0;
1296
+ for (const key of Reflect.ownKeys(target)) {
1297
+ if (runPropertyNameCheck && !propertyNamesToBeFrozen.includes(key)) {
1298
+ continue;
1299
+ }
1300
+ const propValue = target[key];
1301
+ if (isRecordLike(propValue) && !Object.isFrozen(propValue)) {
1302
+ Object.freeze(propValue);
1303
+ deepFreeze(propValue, [], false);
1304
+ }
1305
+ else if (isRoot) {
1306
+ Object.defineProperty(target, key, {
1307
+ value: propValue,
1308
+ writable: false,
1309
+ configurable: false,
1310
+ });
1311
+ }
1312
+ }
1313
+ }
1314
+ function isRecordLike(target) {
1315
+ return typeof target === 'object' && target !== null;
1316
+ }
1317
+
1318
+ // necessary wrapper function to test prod mode
1319
+ function isDevMode() {
1320
+ return isDevMode$1();
1321
+ }
1322
+
1323
+ function withImmutableState(stateOrFactory, options) {
1324
+ const immutableState = typeof stateOrFactory === 'function' ? stateOrFactory() : stateOrFactory;
1325
+ const stateKeys = Reflect.ownKeys(immutableState);
1326
+ const applyFreezing = isDevMode() || options?.enableInProduction === true;
1327
+ return signalStoreFeature(withState(immutableState), withHooks((store) => ({
1328
+ onInit() {
1329
+ if (!applyFreezing) {
1330
+ return;
1331
+ }
1332
+ /**
1333
+ * `immutableState` will be initially frozen. That is because
1334
+ * of potential mutations outside the SignalStore
1335
+ *
1336
+ * ```ts
1337
+ * const initialState = {id: 1};
1338
+ * signalStore(withImmutableState(initialState));
1339
+ *
1340
+ * initialState.id = 2; // must throw immutability
1341
+ * ```
1342
+ */
1343
+ Object.freeze(immutableState);
1344
+ watchState(store, (state) => {
1345
+ deepFreeze(state, stateKeys);
1346
+ });
1347
+ },
1348
+ })));
1349
+ }
1350
+
1351
+ const keyPath = 'ngrxToolkitKeyPath';
1352
+ const dbName = 'ngrxToolkitDb';
1353
+ const storeName = 'ngrxToolkitStore';
1354
+ const VERSION = 1;
1355
+ class IndexedDBService {
1356
+ /**
1357
+ * write to indexedDB
1358
+ * @param key
1359
+ * @param data
1360
+ */
1361
+ async setItem(key, data) {
1362
+ const db = await this.openDB();
1363
+ const tx = db.transaction(storeName, 'readwrite');
1364
+ const store = tx.objectStore(storeName);
1365
+ store.put({
1366
+ [keyPath]: key,
1367
+ value: data,
1368
+ });
1369
+ return new Promise((resolve, reject) => {
1370
+ tx.oncomplete = () => {
1371
+ db.close();
1372
+ resolve();
1373
+ };
1374
+ tx.onerror = () => {
1375
+ db.close();
1376
+ reject();
1377
+ };
1378
+ });
1379
+ }
1380
+ /**
1381
+ * read from indexedDB
1382
+ * @param key
1383
+ */
1384
+ async getItem(key) {
1385
+ const db = await this.openDB();
1386
+ const tx = db.transaction(storeName, 'readonly');
1387
+ const store = tx.objectStore(storeName);
1388
+ const request = store.get(key);
1389
+ return new Promise((resolve, reject) => {
1390
+ request.onsuccess = () => {
1391
+ db.close();
1392
+ // localStorage(sessionStorage) returns null if the key does not exist
1393
+ // Similarly, indexedDB should return null
1394
+ if (request.result === undefined) {
1395
+ resolve(null);
1396
+ }
1397
+ resolve(request.result?.['value']);
1398
+ };
1399
+ request.onerror = () => {
1400
+ db.close();
1401
+ reject();
1402
+ };
1403
+ });
1404
+ }
1405
+ /**
1406
+ * delete indexedDB
1407
+ * @param key
1408
+ */
1409
+ async clear(key) {
1410
+ const db = await this.openDB();
1411
+ const tx = db.transaction(storeName, 'readwrite');
1412
+ const store = tx.objectStore(storeName);
1413
+ const request = store.delete(key);
1414
+ return new Promise((resolve, reject) => {
1415
+ request.onsuccess = () => {
1416
+ db.close();
1417
+ resolve();
1418
+ };
1419
+ request.onerror = () => {
1420
+ db.close();
1421
+ reject();
1422
+ };
1423
+ });
1424
+ }
1425
+ /**
1426
+ * open indexedDB
1427
+ */
1428
+ async openDB() {
1429
+ return new Promise((resolve, reject) => {
1430
+ const request = indexedDB.open(dbName, VERSION);
1431
+ request.onupgradeneeded = () => {
1432
+ const db = request.result;
1433
+ if (!db.objectStoreNames.contains(storeName)) {
1434
+ db.createObjectStore(storeName, { keyPath });
1435
+ }
1436
+ };
1437
+ request.onsuccess = () => {
1438
+ resolve(request.result);
1439
+ };
1440
+ request.onerror = () => {
1441
+ reject(request.error);
1442
+ };
1443
+ });
1444
+ }
1445
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: IndexedDBService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1446
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: IndexedDBService, providedIn: 'root' }); }
1447
+ }
1448
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: IndexedDBService, decorators: [{
1449
+ type: Injectable,
1450
+ args: [{ providedIn: 'root' }]
1451
+ }] });
1452
+
1453
+ /**
1454
+ * AsyncFeatureResult is used as the public interface that users interact with
1455
+ * when calling `withIndexedDB`. It intentionally omits the internal SYNC_STATUS
1456
+ * property to avoid TypeScript error TS4058 (return type of public method
1457
+ * includes private type).
1458
+ *
1459
+ * For internal implementation, we use AsyncStoreForFactory which includes
1460
+ * the SYNC_STATUS property needed for state management.
1461
+ */
1462
+ const SYNC_STATUS = Symbol('SYNC_STATUS');
1463
+
1464
+ function withIndexedDB() {
1465
+ function factory({ key, parse, select, stringify }, store, useStubs) {
1466
+ if (useStubs) {
1467
+ return {
1468
+ clearStorage: () => Promise.resolve(),
1469
+ readFromStorage: () => Promise.resolve(),
1470
+ writeToStorage: () => Promise.resolve(),
1471
+ };
1472
+ }
1473
+ const indexeddbService = inject(IndexedDBService);
1474
+ function warnOnSyncing(mode) {
1475
+ if (store[SYNC_STATUS]() === 'syncing') {
1476
+ const prettyMode = mode === 'read' ? 'Reading' : 'Writing';
1477
+ console.warn(`${prettyMode} to Store (${key}) happened during an ongoing synchronization process.`, 'Please ensure that the store is not in syncing state via `store.whenSynced()`.', 'Alternatively, you can disable the autoSync by passing `autoSync: false` in the config.');
1478
+ }
1479
+ }
1480
+ return {
1481
+ /**
1482
+ * Removes the item stored in storage.
1483
+ */
1484
+ async clearStorage() {
1485
+ warnOnSyncing('write');
1486
+ store[SYNC_STATUS].set('syncing');
1487
+ patchState$1(store, {});
1488
+ await indexeddbService.clear(key);
1489
+ store[SYNC_STATUS].set('synced');
1490
+ },
1491
+ /**
1492
+ * Reads item from storage and patches the state.
1493
+ */
1494
+ async readFromStorage() {
1495
+ warnOnSyncing('read');
1496
+ store[SYNC_STATUS].set('syncing');
1497
+ const stateString = await indexeddbService.getItem(key);
1498
+ if (stateString) {
1499
+ patchState$1(store, parse(stateString));
1500
+ }
1501
+ store[SYNC_STATUS].set('synced');
1502
+ },
1503
+ /**
1504
+ * Writes selected portion to storage.
1505
+ */
1506
+ async writeToStorage() {
1507
+ warnOnSyncing('write');
1508
+ store[SYNC_STATUS].set('syncing');
1509
+ const slicedState = select(getState(store));
1510
+ await indexeddbService.setItem(key, stringify(slicedState));
1511
+ store[SYNC_STATUS].set('synced');
1512
+ },
1513
+ };
1514
+ }
1515
+ factory.type = 'async';
1516
+ return factory;
1517
+ }
1518
+
1519
+ class LocalStorageService {
1520
+ getItem(key) {
1521
+ return localStorage.getItem(key);
1522
+ }
1523
+ setItem(key, data) {
1524
+ return localStorage.setItem(key, data);
1525
+ }
1526
+ clear(key) {
1527
+ return localStorage.removeItem(key);
1528
+ }
1529
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: LocalStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1530
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: LocalStorageService, providedIn: 'root' }); }
1531
+ }
1532
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: LocalStorageService, decorators: [{
1533
+ type: Injectable,
1534
+ args: [{
1535
+ providedIn: 'root',
1536
+ }]
1537
+ }] });
1538
+
1539
+ class SessionStorageService {
1540
+ getItem(key) {
1541
+ return sessionStorage.getItem(key);
1542
+ }
1543
+ setItem(key, data) {
1544
+ return sessionStorage.setItem(key, data);
1545
+ }
1546
+ clear(key) {
1547
+ return sessionStorage.removeItem(key);
1548
+ }
1549
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: SessionStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1550
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: SessionStorageService, providedIn: 'root' }); }
1551
+ }
1552
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: SessionStorageService, decorators: [{
1553
+ type: Injectable,
1554
+ args: [{
1555
+ providedIn: 'root',
1556
+ }]
1557
+ }] });
1558
+
1559
+ function withLocalStorage() {
1560
+ return createSyncMethods(LocalStorageService);
1561
+ }
1562
+ function withSessionStorage() {
1563
+ return createSyncMethods(SessionStorageService);
1564
+ }
1565
+ function createSyncMethods(Storage) {
1566
+ function factory({ key, parse, select, stringify }, store, useStubs) {
1567
+ if (useStubs) {
1568
+ return {
1569
+ clearStorage: () => undefined,
1570
+ readFromStorage: () => undefined,
1571
+ writeToStorage: () => undefined,
1572
+ };
1573
+ }
1574
+ const storage = inject(Storage);
1575
+ return {
1576
+ clearStorage() {
1577
+ storage.clear(key);
1578
+ },
1579
+ readFromStorage() {
1580
+ const stateString = storage.getItem(key);
1581
+ if (stateString) {
1582
+ patchState$1(store, parse(stateString));
1583
+ }
1584
+ },
1585
+ writeToStorage() {
1586
+ const slicedState = select(getState(store));
1587
+ storage.setItem(key, stringify(slicedState));
1588
+ },
1589
+ };
1590
+ }
1591
+ factory.type = 'sync';
1592
+ return factory;
1593
+ }
1594
+
1595
+ function withStorageSync(configOrKey, storageStrategy) {
1596
+ if (typeof configOrKey !== 'string' &&
1597
+ configOrKey.storage &&
1598
+ storageStrategy) {
1599
+ throw new Error('You can either pass a storage strategy or a config with storage, but not both.');
1600
+ }
1601
+ const config = {
1602
+ autoSync: true,
1603
+ select: (state) => state,
1604
+ parse: JSON.parse,
1605
+ stringify: JSON.stringify,
1606
+ storage: () => localStorage,
1607
+ ...(typeof configOrKey === 'string' ? { key: configOrKey } : configOrKey),
1608
+ };
1609
+ const factory = storageStrategy ??
1610
+ (config.storage() === localStorage
1611
+ ? withLocalStorage()
1612
+ : withSessionStorage());
1613
+ if (factory.type === 'sync') {
1614
+ return createSyncStorageSync(factory, config);
1615
+ }
1616
+ else {
1617
+ return createAsyncStorageSync(factory, config);
1618
+ }
1619
+ }
1620
+ function createSyncStorageSync(factory, config) {
1621
+ return signalStoreFeature(withMethods((store, platformId = inject(PLATFORM_ID)) => {
1622
+ return factory(config, store, isPlatformServer(platformId));
1623
+ }), withHooks({
1624
+ onInit(store, platformId = inject(PLATFORM_ID)) {
1625
+ if (isPlatformServer(platformId)) {
1626
+ return;
1627
+ }
1628
+ if (config.autoSync) {
1629
+ store.readFromStorage();
1630
+ watchState(store, () => store.writeToStorage());
1631
+ }
1632
+ },
1633
+ }));
1634
+ }
1635
+ function createAsyncStorageSync(factory, config) {
1636
+ return signalStoreFeature(withProps(() => {
1637
+ const props = {
1638
+ /*
1639
+ // we need to have that as property (and not state)
1640
+ // Otherwise the state watcher fires when updating the sync status
1641
+ */
1642
+ [SYNC_STATUS]: signal('idle'),
1643
+ };
1644
+ const resolves = [];
1645
+ effect(() => {
1646
+ const syncStatus = props[SYNC_STATUS]();
1647
+ if (syncStatus === 'synced') {
1648
+ resolves.forEach((resolve) => resolve());
1649
+ resolves.splice(0, resolves.length);
1650
+ }
1651
+ });
1652
+ return {
1653
+ ...props,
1654
+ isSynced: computed(() => props[SYNC_STATUS]() === 'synced'),
1655
+ whenSynced: () => new Promise((resolve) => {
1656
+ if (props[SYNC_STATUS]() === 'synced') {
1657
+ resolve();
1658
+ }
1659
+ else {
1660
+ resolves.push(resolve);
1661
+ }
1662
+ }),
1663
+ };
1664
+ }), withMethods((store, platformId = inject(PLATFORM_ID)) => {
1665
+ return factory(config, store, isPlatformServer(platformId));
1666
+ }), withHooks({
1667
+ async onInit(store, platformId = inject(PLATFORM_ID)) {
1668
+ if (isPlatformServer(platformId)) {
1669
+ return;
1670
+ }
1671
+ const initialState = getState(store);
1672
+ if (config.autoSync) {
1673
+ let startWatching = false;
1674
+ watchState(store, () => {
1675
+ if (!startWatching) {
1676
+ if (getState(store) === initialState) {
1677
+ return;
1678
+ }
1679
+ console.warn(`Writing to Store (${config.key}) happened before the state was initially read from storage.`, 'Please ensure that the store is not in syncing state via `store.whenSynced()` before writing to the state.', 'Alternatively, you can disable autoSync by passing `autoSync: false` in the config.');
1680
+ return;
1681
+ }
1682
+ return store.writeToStorage();
1683
+ });
1684
+ await store.readFromStorage();
1685
+ startWatching = true;
1686
+ }
1687
+ },
1688
+ }));
1689
+ }
1690
+
1691
+ /**
1692
+ * `withConditional` activates a feature based on a given condition.
1693
+ *
1694
+ * **Use Cases**
1695
+ * - Conditionally activate features based on the **store state** or other criteria.
1696
+ * - Choose between **two different implementations** of a feature.
1697
+ *
1698
+ * **Type Constraints**
1699
+ * Both features must have **exactly the same state, props, and methods**.
1700
+ * Otherwise, a type error will occur.
1701
+ *
1702
+ *
1703
+ * **Usage**
1704
+ *
1705
+ * ```typescript
1706
+ * const withUser = signalStoreFeature(
1707
+ * withState({ id: 1, name: 'Konrad' }),
1708
+ * withHooks(store => ({
1709
+ * onInit() {
1710
+ * // user loading logic
1711
+ * }
1712
+ * }))
1713
+ * );
1714
+ *
1715
+ * function withFakeUser() {
1716
+ * return signalStoreFeature(
1717
+ * withState({ id: 0, name: 'anonymous' })
1718
+ * );
1719
+ * }
1720
+ *
1721
+ * signalStore(
1722
+ * withMethods(() => ({
1723
+ * useRealUser: () => true
1724
+ * })),
1725
+ * withConditional((store) => store.useRealUser(), withUser, withFakeUser)
1726
+ * )
1727
+ * ```
1728
+ *
1729
+ * @param condition - A function that determines which feature to activate based on the store state.
1730
+ * @param featureIfTrue - The feature to activate if the condition evaluates to `true`.
1731
+ * @param featureIfFalse - The feature to activate if the condition evaluates to `false`.
1732
+ * @returns A `SignalStoreFeature` that applies the selected feature based on the condition.
1733
+ */
1734
+ function withConditional(condition, featureIfTrue, featureIfFalse) {
1735
+ return (store) => {
1736
+ const conditionStore = {
1737
+ ...store['stateSignals'],
1738
+ ...store['props'],
1739
+ ...store['methods'],
1740
+ };
1741
+ return condition(conditionStore)
1742
+ ? featureIfTrue(store)
1743
+ : featureIfFalse(store);
1744
+ };
1745
+ }
1746
+ const emptyFeature = signalStoreFeature(withState({}));
1747
+
1748
+ /**
1749
+ * @deprecated Use `import { withFeature } from '@ngrx/signals'` instead, starting with `ngrx/signals` 19.1: https://ngrx.io/guide/signals/signal-store/custom-store-features#connecting-a-custom-feature-with-the-store
1750
+ *
1751
+ * Allows to pass properties, methods, or signals from a SignalStore
1752
+ * to a feature.
1753
+ *
1754
+ * Typically, a `signalStoreFeature` can have input constraints on
1755
+ *
1756
+ * ```typescript
1757
+ * function withSum(a: Signal<number>, b: Signal<number>) {
1758
+ * return signalStoreFeature(
1759
+ * withComputed(() => ({
1760
+ * sum: computed(() => a() + b())
1761
+ * }))
1762
+ * );
1763
+ * }
1764
+ *
1765
+ * signalStore(
1766
+ * withState({ a: 1, b: 2 }),
1767
+ * withFeatureFactory((store) => withSum(store.a, store.b))
1768
+ * );
1769
+ * ```
1770
+ * @param factoryFn
1771
+ */
1772
+ function withFeatureFactory(factoryFn) {
1773
+ return (store) => {
1774
+ const storeForFactory = {
1775
+ ...store['stateSignals'],
1776
+ ...store['props'],
1777
+ ...store['methods'],
1778
+ };
1779
+ const feature = factoryFn(storeForFactory);
1780
+ return feature(store);
1781
+ };
1782
+ }
1783
+
1784
+ const switchOp = {
1785
+ rxJsOperator: switchMap,
1786
+ exhaustSemantics: false,
1787
+ };
1788
+ const mergeOp = {
1789
+ rxJsOperator: mergeMap,
1790
+ exhaustSemantics: false,
1791
+ };
1792
+ const concatOp = {
1793
+ rxJsOperator: concatMap,
1794
+ exhaustSemantics: false,
1795
+ };
1796
+ const exhaustOp = {
1797
+ rxJsOperator: exhaustMap,
1798
+ exhaustSemantics: true,
1799
+ };
1800
+
1801
+ /**
1802
+ * Creates a mutation that leverages RxJS.
1803
+ *
1804
+ * For each mutation the following options can be defined:
1805
+ * - `operation`: A function that defines the mutation logic. It returns an Observable.
1806
+ * - `onSuccess`: A callback that is called when the mutation is successful.
1807
+ * - `onError`: A callback that is called when the mutation fails.
1808
+ * - `operator`: An optional wrapper of an RxJS flattening operator. By default `concat` sematics are used.
1809
+ * - `injector`: An optional Angular injector to use for dependency injection.
1810
+ *
1811
+ * The `operation` is the only mandatory option.
1812
+ *
1813
+ * The returned mutation can be called as an async function and returns a Promise.
1814
+ * This promise informs about whether the mutation was successful, failed, or aborted
1815
+ * (due to switchMap or exhaustMap semantics).
1816
+ *
1817
+ * The mutation also provides several Signals such as error, status or isPending (see below).
1818
+ *
1819
+ * Example usage without Store:
1820
+ *
1821
+ * ```typescript
1822
+ * const counterSignal = signal(0);
1823
+ *
1824
+ * const increment = rxMutation({
1825
+ * operation: (param: Param) => {
1826
+ * return calcSum(this.counterSignal(), param.value);
1827
+ * },
1828
+ * operator: concatOp,
1829
+ * onSuccess: (result) => {
1830
+ * this.counterSignal.set(result);
1831
+ * },
1832
+ * onError: (error) => {
1833
+ * console.error('Error occurred:', error);
1834
+ * },
1835
+ * });
1836
+ *
1837
+ * const error = increment.error;
1838
+ * const isPending = increment.isPending;
1839
+ * const status = increment.status;
1840
+ * const value = increment.value;
1841
+ * const hasValue = increment.hasValue;
1842
+ *
1843
+ * async function incrementCounter() {
1844
+ * const result = await increment({ value: 1 });
1845
+ * if (result.status === 'success') {
1846
+ * console.log('Success:', result.value);
1847
+ * }
1848
+ * if (result.status === 'error') {
1849
+ * console.log('Error:', result.error);
1850
+ * }
1851
+ * if (result.status === 'aborted') {
1852
+ * console.log('Operation aborted');
1853
+ * }
1854
+ * }
1855
+ *
1856
+ * function calcSum(a: number, b: number): Observable<number> {
1857
+ * return of(result).pipe(delay(500));
1858
+ * }
1859
+ * ```
1860
+ *
1861
+ * @param options
1862
+ * @returns the actual mutation function along tracking data as properties/methods
1863
+ */
1864
+ function rxMutation(optionsOrOperation) {
1865
+ const inputSubject = new Subject();
1866
+ const options = typeof optionsOrOperation === 'function'
1867
+ ? { operation: optionsOrOperation }
1868
+ : optionsOrOperation;
1869
+ const flatteningOp = options.operator ?? concatOp;
1870
+ const destroyRef = options.injector?.get(DestroyRef) ?? inject(DestroyRef);
1871
+ const callCount = signal(0);
1872
+ const errorSignal = signal(undefined);
1873
+ const idle = signal(true);
1874
+ const isPending = computed(() => callCount() > 0);
1875
+ const value = signal(undefined);
1876
+ const isSuccess = computed(() => !idle() && !isPending() && !errorSignal());
1877
+ const hasValue = function () {
1878
+ return typeof value() !== 'undefined';
1879
+ };
1880
+ const status = computed(() => {
1881
+ if (idle()) {
1882
+ return 'idle';
1883
+ }
1884
+ if (callCount() > 0) {
1885
+ return 'pending';
1886
+ }
1887
+ if (errorSignal()) {
1888
+ return 'error';
1889
+ }
1890
+ return 'success';
1891
+ });
1892
+ const initialInnerStatus = 'idle';
1893
+ let innerStatus = initialInnerStatus;
1894
+ inputSubject
1895
+ .pipe(flatteningOp.rxJsOperator((input) => defer(() => {
1896
+ callCount.update((c) => c + 1);
1897
+ idle.set(false);
1898
+ return options.operation(input.param).pipe(tap((result) => {
1899
+ options.onSuccess?.(result, input.param);
1900
+ innerStatus = 'success';
1901
+ errorSignal.set(undefined);
1902
+ value.set(result);
1903
+ }), catchError((error) => {
1904
+ options.onError?.(error, input.param);
1905
+ errorSignal.set(error);
1906
+ value.set(undefined);
1907
+ innerStatus = 'error';
1908
+ return EMPTY;
1909
+ }), finalize(() => {
1910
+ callCount.update((c) => c - 1);
1911
+ if (innerStatus === 'success') {
1912
+ input.resolve({
1913
+ status: 'success',
1914
+ value: value(),
1915
+ });
1916
+ }
1917
+ else if (innerStatus === 'error') {
1918
+ input.resolve({
1919
+ status: 'error',
1920
+ error: errorSignal(),
1921
+ });
1922
+ }
1923
+ else {
1924
+ input.resolve({
1925
+ status: 'aborted',
1926
+ });
1927
+ }
1928
+ innerStatus = initialInnerStatus;
1929
+ }));
1930
+ })), takeUntilDestroyed(destroyRef))
1931
+ .subscribe();
1932
+ const mutationFn = (param) => {
1933
+ return new Promise((resolve) => {
1934
+ if (callCount() > 0 && flatteningOp.exhaustSemantics) {
1935
+ resolve({
1936
+ status: 'aborted',
1937
+ });
1938
+ }
1939
+ else {
1940
+ inputSubject.next({
1941
+ param,
1942
+ resolve,
1943
+ });
1944
+ }
1945
+ });
1946
+ };
1947
+ const mutation = mutationFn;
1948
+ mutation.status = status;
1949
+ mutation.isPending = isPending;
1950
+ mutation.error = errorSignal;
1951
+ mutation.value = value;
1952
+ mutation.hasValue = hasValue;
1953
+ mutation.isSuccess = isSuccess;
1954
+ return mutation;
1955
+ }
1956
+
1957
+ function withMutations(mutationsFactory) {
1958
+ return (store) => {
1959
+ // TODO: Is this the correct usage?
1960
+ const source = store;
1961
+ const mutations = mutationsFactory({
1962
+ ...source,
1963
+ ...store.props,
1964
+ ...store.methods,
1965
+ ...store.stateSignals,
1966
+ });
1967
+ const feature = createMutationsFeature(mutations);
1968
+ return feature(store);
1969
+ };
1970
+ }
1971
+ function createMutationsFeature(mutations) {
1972
+ const keys = Object.keys(mutations);
1973
+ const feature = signalStoreFeature(withMethods(() => keys.reduce((acc, key) => ({
1974
+ ...acc,
1975
+ [key]: async (params) => {
1976
+ const mutation = mutations[key];
1977
+ if (!mutation) {
1978
+ throw new Error(`Mutation ${key} not found`);
1979
+ }
1980
+ const result = await mutation(params);
1981
+ return result;
1982
+ },
1983
+ }), {})), withComputed(() => keys.reduce((acc, key) => ({
1984
+ ...acc,
1985
+ [`${key}IsPending`]: mutations[key].isPending,
1986
+ [`${key}Status`]: mutations[key].status,
1987
+ [`${key}Error`]: mutations[key].error,
1988
+ }), {})));
1989
+ return feature;
1990
+ }
1991
+
1992
+ /**
1993
+ * Creates an HTTP mutation.
1994
+ *
1995
+ * export type Params = {
1996
+ * value: number;
1997
+ * };
1998
+ *
1999
+ * export type CounterResponse = {
2000
+ * // httpbin.org echos the request using the
2001
+ * // json property
2002
+ * json: { counter: number };
2003
+ * };
2004
+ *
2005
+ * const simpleSaveUser = httpMutation({
2006
+ * request: (userData: AddUserEntry) => ({
2007
+ * url: 'api/users',
2008
+ * body: userData,
2009
+ * }),
2010
+ * parse: Boolean,
2011
+ * })
2012
+ *
2013
+ * const saveUser = httpMutation({
2014
+ * request: (p: Params) => ({
2015
+ * url: `https://httpbin.org/post`,
2016
+ * method: 'POST',
2017
+ * body: { counter: p.value },
2018
+ * headers: { 'Content-Type': 'application/json' },
2019
+ * }),
2020
+ * onSuccess: (response: CounterResponse) => {
2021
+ * console.log('Counter sent to server:', response);
2022
+ * },
2023
+ * onError: (error) => {
2024
+ * console.error('Failed to send counter:', error);
2025
+ * },
2026
+ * });
2027
+ *
2028
+ * ...
2029
+ *
2030
+ * const result = await this.saveUser({ value: 17 });
2031
+ * if (result.status === 'success') {
2032
+ * console.log('Successfully saved to server:', result.value);
2033
+ * }
2034
+ * else if (result.status === 'error') {
2035
+ * console.log('Failed to save:', result.error);
2036
+ * }
2037
+ * else {
2038
+ * console.log('Operation aborted');
2039
+ * }
2040
+ *
2041
+ * @param options The options for the HTTP mutation.
2042
+ * @returns The HTTP mutation.
2043
+ */
2044
+ function httpMutation(optionsOrRequest) {
2045
+ const httpClient = inject(HttpClient);
2046
+ const options = typeof optionsOrRequest === 'function'
2047
+ ? { request: optionsOrRequest }
2048
+ : optionsOrRequest;
2049
+ const parse = options.parse ?? ((raw) => raw);
2050
+ const uploadProgress = signal(undefined);
2051
+ const downloadProgress = signal(undefined);
2052
+ const headers = signal(undefined);
2053
+ const statusCode = signal(undefined);
2054
+ const mutation = rxMutation({
2055
+ ...options,
2056
+ operation: (param) => {
2057
+ const httpRequest = options.request(param);
2058
+ return defer(() => {
2059
+ uploadProgress.set(undefined);
2060
+ downloadProgress.set(undefined);
2061
+ headers.set(undefined);
2062
+ statusCode.set(undefined);
2063
+ return httpClient
2064
+ .request(httpRequest.method, httpRequest.url, {
2065
+ ...httpRequest,
2066
+ observe: 'events',
2067
+ responseType: 'json',
2068
+ })
2069
+ .pipe(tap((response) => {
2070
+ if (response.type === HttpEventType.UploadProgress) {
2071
+ uploadProgress.set(response);
2072
+ }
2073
+ else if (response.type === HttpEventType.DownloadProgress) {
2074
+ downloadProgress.set(response);
2075
+ }
2076
+ }), filter((event) => event instanceof HttpResponse), tap((response) => {
2077
+ headers.set(response.headers);
2078
+ statusCode.set(response.status.toString());
2079
+ }), map((event) => parse(event.body)));
2080
+ });
2081
+ },
2082
+ });
2083
+ mutation.uploadProgress = uploadProgress;
2084
+ mutation.downloadProgress = downloadProgress;
2085
+ mutation.statusCode = statusCode;
2086
+ mutation.headers = headers;
2087
+ return mutation;
2088
+ }
2089
+
2090
+ /**
2091
+ * Generated bundle index. Do not edit.
2092
+ */
2093
+
2094
+ export { capitalize, concatOp, createEffects, createPageArray, createReducer, deriveCallStateKeys, emptyFeature, exhaustOp, firstPage, getCallStateKeys, getCollectionArray, getDataServiceKeys, getUndoRedoKeys, gotoPage, httpMutation, mergeOp, nextPage, noPayload, patchState, payload, previousPage, provideDevtoolsConfig, renameDevtoolsName, rxMutation, setError, setLoaded, setLoading, setMaxPageNavigationArrayItems, setPageSize, setResetState, switchOp, updateState, withCallState, withConditional, withDataService, withDevToolsStub, withDevtools, withDisabledNameIndices, withFeatureFactory, withGlitchTracking, withImmutableState, withIndexedDB, withIndexedDB as withIndexeddb, withLocalStorage, withMapper, withMutations, withPagination, withRedux, withReset, withSessionStorage, withStorageSync, withUndoRedo };
2095
+ //# sourceMappingURL=angular-architects-ngrx-toolkit.mjs.map