pinia-plugin-subscription 1.0.0-beta.6 → 1.0.0-beta.7

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/CHANGELOG.md CHANGED
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
  ## [Unreleased]
9
9
 
10
10
  ### Added
11
+ - `createPluginSubscriber(name, invoke, optionalProps?)` factory, exported from `pinia-plugin-subscription/helpers`, to build plain-object subscribers; documented in `docs/authoring-plugins.md` and used by the demo plugin
11
12
  - Added a dedicated tracing guide, `docs/tracing.md`; the README now only presents tracing and links to it
12
13
  - Moved the API reference, import subpaths, development, `Store` summary and testing sections from `README.md` to `docs/authoring-plugins.md`
13
14
  - `createTracerRegistry({ redact })`: opt-in redaction of event payloads before they reach listeners. `true` masks a default list of sensitive keys (`password`, `token`, `secret`, `authorization`, API/private keys, `credential`, `cookie`, `cipher`...); an object adds custom `keys`, a `replacement`, or drops the defaults with `includeDefaults: false`. It works on a copy, covers arrays/`Map`/`Set`, handles circular references, and replaces the payload by `__traceRedactionError` if redaction fails. `defaultRedactedKeys` and `TraceRedactOptions` are exported
package/README.md CHANGED
@@ -61,54 +61,6 @@ app.use(pinia)
61
61
  app.mount('#app')
62
62
  ```
63
63
 
64
- ## Usage — Examples
65
-
66
- **1) Subscriber using a `Store` subclass:**
67
-
68
- ```typescript
69
- import PluginSubscriber from 'pinia-plugin-subscription'
70
- import { Store } from 'pinia-plugin-subscription'
71
-
72
- class MyPlugin extends Store {
73
- protected override _className: string = 'MyPlugin'
74
- protected static override _requiredKeys?: string[] | undefined = ['my-plugin-option']
75
-
76
- constructor(store, options) {
77
- super(store, options)
78
- this.doSomething()
79
- }
80
- }
81
-
82
- class MyPluginSubscriber extends PluginSubscriber<MyPlugin> {
83
- constructor() {
84
- super('my-plugin', MyPlugin.customizeStore.bind(MyPlugin))
85
- }
86
- }
87
-
88
- export const myStoreSubscriber = new MyPluginSubscriber()
89
- ```
90
-
91
- **2) Simple subscriber implementing `PluginSubscriberInterface`:**
92
-
93
- ```typescript
94
- import type { PluginSubscriberInterface } from 'pinia-plugin-subscription'
95
-
96
- export const myStoreSubscriber: PluginSubscriberInterface = {
97
- name: 'my-plugin',
98
-
99
- invoke: (context) => {
100
- // context contains `store`, `options`, `pinia`
101
- console.log('store registered', context.store.$id)
102
-
103
- return true
104
- },
105
-
106
- resetStoreCallback: (store) => {
107
- console.log('store reset:', store.$id)
108
- }
109
- }
110
- ```
111
-
112
64
  ## Advanced Features
113
65
 
114
66
  - **Structured tracing:** Subscribe to typed trace events and filter them at runtime, per store or per namespace — see [Tracing](#tracing).
@@ -0,0 +1,560 @@
1
+ var g = Object.defineProperty;
2
+ var w = (i, s, t) => s in i ? g(i, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[s] = t;
3
+ var a = (i, s, t) => w(i, typeof s != "symbol" ? s + "" : s, t);
4
+ import { toRaw as A } from "vue";
5
+ import { defineStore as $ } from "pinia";
6
+ function u(i) {
7
+ if (typeof structuredClone == "function")
8
+ try {
9
+ return structuredClone(i);
10
+ } catch {
11
+ }
12
+ if (i === null || typeof i != "object")
13
+ return i;
14
+ if (i instanceof Map)
15
+ return new Map(
16
+ Array.from(i.entries(), ([t, e]) => [u(t), u(e)])
17
+ );
18
+ if (i instanceof Set)
19
+ return new Set(Array.from(i.values(), (t) => u(t)));
20
+ if (Array.isArray(i))
21
+ return i.map((t) => u(t));
22
+ if (Object.getPrototypeOf(i) === Object.prototype || Object.getPrototypeOf(i) === null)
23
+ return Object.fromEntries(
24
+ Object.entries(i).map(([t, e]) => [t, u(e)])
25
+ );
26
+ const s = Object.create(Object.getPrototypeOf(i));
27
+ for (const [t, e] of Object.entries(i))
28
+ s[t] = u(e);
29
+ return s;
30
+ }
31
+ function x(i, s = "all") {
32
+ if (Array.isArray(s)) {
33
+ const t = {};
34
+ for (const e of s)
35
+ e in i && (t[e] = u(A(i[e])));
36
+ return t;
37
+ }
38
+ if (s !== "all")
39
+ throw new Error(`Invalid keys parameter: ${s}`);
40
+ return u(A(i));
41
+ }
42
+ const b = /* @__PURE__ */ new WeakMap(), S = /* @__PURE__ */ new Map(), k = /* @__PURE__ */ new WeakSet();
43
+ function H(i, s) {
44
+ if (k.has(i) || typeof i.$dispose != "function")
45
+ return;
46
+ const t = i.$dispose;
47
+ i.$dispose = (...e) => (b.delete(i), S.delete(s), t.apply(i, e)), k.add(i);
48
+ }
49
+ function N(i, s, t) {
50
+ const e = t ? { storeOptions: t } : {};
51
+ return typeof s == "function" ? C(
52
+ i,
53
+ s,
54
+ e
55
+ ) : R(
56
+ i,
57
+ s,
58
+ e
59
+ );
60
+ }
61
+ function q(i, s, t) {
62
+ const e = t ? { storeOptions: { ...t, enhancedStore: !0 } } : { storeOptions: { enhancedStore: !0 } };
63
+ return C(
64
+ i,
65
+ s,
66
+ e
67
+ );
68
+ }
69
+ function C(i, s, t) {
70
+ const e = {
71
+ id: i,
72
+ extensions: {}
73
+ }, r = t?.storeOptions?.enhancedStore === !0, n = $(
74
+ i,
75
+ () => s(e),
76
+ t
77
+ );
78
+ return Object.assign(((...c) => {
79
+ r && S.set(i, e);
80
+ const o = n(...c);
81
+ return r && (b.set(o, e), S.delete(i), H(o, i)), o;
82
+ }), n);
83
+ }
84
+ function R(i, s, t) {
85
+ return t && (s = { ...s, ...t ?? {} }), $(i, s);
86
+ }
87
+ const v = /* @__PURE__ */ new Set(["_", "$"]);
88
+ function P(i) {
89
+ return v.has(i[0]);
90
+ }
91
+ function I(i) {
92
+ const s = i;
93
+ return b.get(i) ?? (typeof s?.$id == "string" ? S.get(s.$id) : void 0);
94
+ }
95
+ function z(i) {
96
+ const s = i.extensions.enhancedStore ?? i.extensions.extending;
97
+ if (!s)
98
+ throw new Error(`${i.id}Store - getEnhancedStore - Error: enhanced store is required`);
99
+ return s;
100
+ }
101
+ function B(i, s) {
102
+ i.extensions.enhancedStore = s, i.extensions.extending = s;
103
+ }
104
+ function f(i, s) {
105
+ return `${i}-${s.$id}`;
106
+ }
107
+ class T {
108
+ constructor() {
109
+ a(this, "_stateSnapshots", /* @__PURE__ */ new Map());
110
+ a(this, "_storeHasRollbackSnapshots", /* @__PURE__ */ new Set());
111
+ a(this, "_storeRollbackSnapshotsParams", /* @__PURE__ */ new Map());
112
+ }
113
+ addRollbackAction(s) {
114
+ typeof s.$rollbackAfterFailure != "function" && (s.$rollbackAfterFailure = async ({ action: t, stateKeys: e }, r = []) => {
115
+ const n = s[t];
116
+ if (typeof n != "function" || P(t))
117
+ return;
118
+ const c = !e || e.length === 0 ? "all" : e, o = this.saveStateSnapshot(s, t, c);
119
+ try {
120
+ await n.apply(s, r);
121
+ } catch (h) {
122
+ throw this.patchStore(o, s), h;
123
+ } finally {
124
+ this.removeStateSnapshot(o);
125
+ }
126
+ });
127
+ }
128
+ createOnActionCallbacks(s, t) {
129
+ const e = this._storeRollbackSnapshotsParams.get(
130
+ f(s, t)
131
+ );
132
+ if (!e)
133
+ return;
134
+ const r = e.length === 0 ? "all" : e, n = this.saveStateSnapshot(t, s, r);
135
+ return {
136
+ after: () => {
137
+ this.removeStateSnapshot(n);
138
+ },
139
+ onError: () => {
140
+ this.patchStore(n, t), this.removeStateSnapshot(n);
141
+ }
142
+ };
143
+ }
144
+ initFromPluginContext({ options: s, store: t }) {
145
+ const e = s?.storeOptions?.rollbackAfterFailure;
146
+ e && !this._storeHasRollbackSnapshots.has(t.$id) && (Object.keys(e).forEach((r) => {
147
+ const n = e[r];
148
+ n && this._storeRollbackSnapshotsParams.set(
149
+ f(r, t),
150
+ n
151
+ );
152
+ }), this._storeHasRollbackSnapshots.add(t.$id)), this.addRollbackAction(t);
153
+ }
154
+ clearStoreTracking(s) {
155
+ const t = `-${s.$id}`;
156
+ for (const e of Array.from(this._storeRollbackSnapshotsParams.keys()))
157
+ e.endsWith(t) && this._storeRollbackSnapshotsParams.delete(e);
158
+ this._storeHasRollbackSnapshots.delete(s.$id);
159
+ for (const e of Array.from(this._stateSnapshots.keys()))
160
+ e.description?.startsWith(`${s.$id}:`) && this._stateSnapshots.delete(e);
161
+ }
162
+ patchStore(s, t) {
163
+ const e = this._stateSnapshots.get(s);
164
+ if (e)
165
+ try {
166
+ t.$patch(e);
167
+ } catch (r) {
168
+ console.error(`Failed to patch store with snapshot ${String(s)}`, r);
169
+ }
170
+ }
171
+ removeStateSnapshot(s) {
172
+ s && this._stateSnapshots.delete(s);
173
+ }
174
+ saveStateSnapshot(s, t, e) {
175
+ const r = x(
176
+ s.$state,
177
+ e
178
+ ), n = /* @__PURE__ */ Symbol(`${s.$id}:${t}`);
179
+ return this._stateSnapshots.set(n, r), n;
180
+ }
181
+ storeHasRollbackSnapshots(s) {
182
+ return this._storeHasRollbackSnapshots.has(s.$id);
183
+ }
184
+ }
185
+ class D {
186
+ constructor() {
187
+ a(this, "_tracer");
188
+ a(this, "_traceOptions", {
189
+ addClassNameToLabel: !0
190
+ });
191
+ }
192
+ get classNameAddedToTraceNamespace() {
193
+ return this._traceOptions.addClassNameToLabel === !0;
194
+ }
195
+ set classNameAddedToTraceNamespace(s) {
196
+ this._traceOptions.addClassNameToLabel = s;
197
+ }
198
+ get tracer() {
199
+ return this._tracer;
200
+ }
201
+ trace(s, t, e, r) {
202
+ const n = this.tracer;
203
+ n && (s = this.traceLabelFormatter(s), n.debug(s, r ?? s.toLowerCase(), e, t));
204
+ }
205
+ traceError(s, t, e, r, n) {
206
+ const c = this.tracer;
207
+ c ? (s = this.traceLabelFormatter(s), c.error(s, n ?? s.toLowerCase(), t, r, e)) : console.error(t);
208
+ }
209
+ traceLabelFormatter(s) {
210
+ return this.classNameAddedToTraceNamespace ? `${this._className}:${s}` : s;
211
+ }
212
+ }
213
+ function O(i) {
214
+ return i ? Array.isArray(i) ? i.length === 0 : typeof i == "object" ? Object.keys(i).length === 0 : typeof i == "string" ? i.trim() === "" : !1 : !(typeof i == "boolean" || typeof i == "number");
215
+ }
216
+ const j = "pinia-plugin-subscription", E = "PluginSubscription", J = E.toLowerCase(), G = E, F = {
217
+ environment: "both",
218
+ hydration: "immediate"
219
+ };
220
+ function K(i) {
221
+ if (typeof window < "u" && typeof window.requestAnimationFrame == "function") {
222
+ window.requestAnimationFrame(() => globalThis.setTimeout(i, 0));
223
+ return;
224
+ }
225
+ globalThis.setTimeout(i, 0);
226
+ }
227
+ class Q extends D {
228
+ constructor(t, e) {
229
+ super();
230
+ a(this, "_className", G);
231
+ a(this, "_hydrationScheduler");
232
+ a(this, "_onActionSubscriptions", /* @__PURE__ */ new Map());
233
+ a(this, "_onActionStores", /* @__PURE__ */ new Set());
234
+ a(this, "_onActionAfterSubscriptions", {});
235
+ a(this, "_onActionOnErrorSubscriptions", {});
236
+ a(this, "_options");
237
+ a(this, "_resetStoreCallback", /* @__PURE__ */ new Map());
238
+ a(this, "_disposedStores", /* @__PURE__ */ new WeakSet());
239
+ a(this, "_storeRollbackSnapshotsHandler", new T());
240
+ a(this, "_subscribers", []);
241
+ a(this, "_subscribersDelivered", /* @__PURE__ */ new Set());
242
+ a(this, "_subscribersScheduled", /* @__PURE__ */ new Set());
243
+ a(this, "_subscriptions", []);
244
+ a(this, "_subscriptionsDelivered", /* @__PURE__ */ new Set());
245
+ a(this, "_subscriptionsScheduled", /* @__PURE__ */ new Set());
246
+ this._hydrationScheduler = e?.hydrationScheduler ?? K, this._options = e, this._subscribers = t, this.initializeTracer();
247
+ }
248
+ set subscribers(t) {
249
+ this._subscribers = t;
250
+ }
251
+ get subscriptions() {
252
+ if (!O(this._subscriptions))
253
+ return this._subscriptions;
254
+ }
255
+ addOnActionAfterCallback(t, e, r) {
256
+ const n = f(t, e);
257
+ this._onActionAfterSubscriptions[n] || (this._onActionAfterSubscriptions[n] = []), this._onActionAfterSubscriptions[n]?.push(r);
258
+ }
259
+ addOnActionOnErrorCallback(t, e, r) {
260
+ const n = f(t, e);
261
+ this._onActionOnErrorSubscriptions[n] || (this._onActionOnErrorSubscriptions[n] = []), this._onActionOnErrorSubscriptions[n]?.push(r);
262
+ }
263
+ addResetStoreCallback(t, e) {
264
+ this._resetStoreCallback.has(t) || this._resetStoreCallback.set(t, /* @__PURE__ */ new Set()), this._resetStoreCallback.get(t).add(e);
265
+ }
266
+ clearOnActionCallbacksSubscriptions(t) {
267
+ delete this._onActionAfterSubscriptions[t], delete this._onActionOnErrorSubscriptions[t];
268
+ }
269
+ clearStoreTracking(t) {
270
+ this._onActionSubscriptions.delete(t), this._onActionStores.delete(t), this._resetStoreCallback.delete(t);
271
+ const e = `-${t.$id}`;
272
+ for (const r of Array.from(this._subscribersDelivered))
273
+ r.endsWith(e) && this._subscribersDelivered.delete(r);
274
+ for (const r of Array.from(this._subscribersScheduled))
275
+ r.endsWith(e) && this._subscribersScheduled.delete(r);
276
+ for (const r of Array.from(this._subscriptionsDelivered))
277
+ r.endsWith(e) && this._subscriptionsDelivered.delete(r);
278
+ for (const r of Array.from(this._subscriptionsScheduled))
279
+ r.endsWith(e) && this._subscriptionsScheduled.delete(r);
280
+ for (const r of Object.keys(this._onActionAfterSubscriptions))
281
+ r.endsWith(e) && delete this._onActionAfterSubscriptions[r];
282
+ for (const r of Object.keys(this._onActionOnErrorSubscriptions))
283
+ r.endsWith(e) && delete this._onActionOnErrorSubscriptions[r];
284
+ }
285
+ createOnActionAfterCallbackCollector(t, e) {
286
+ return (r) => {
287
+ this.addOnActionAfterCallback(t, e, r);
288
+ };
289
+ }
290
+ createOnActionOnErrorCallbackCollector(t, e) {
291
+ return (r) => {
292
+ this.addOnActionOnErrorCallback(t, e, r);
293
+ };
294
+ }
295
+ createRollbackSnapshot(t, e) {
296
+ const {
297
+ after: r,
298
+ onError: n
299
+ } = this._storeRollbackSnapshotsHandler.createOnActionCallbacks(
300
+ t,
301
+ e
302
+ ) ?? {};
303
+ !r || !n || (this.addOnActionAfterCallback(t, e, r), this.addOnActionOnErrorCallback(t, e, n), this.trace("store:onAction:rollbackSnapshot:created", e.$id));
304
+ }
305
+ defineCurrentEnvironment() {
306
+ return this._options?.runtimeEnvironment ?? (typeof window > "u" ? "server" : "client");
307
+ }
308
+ definePluginExecution(t) {
309
+ return {
310
+ ...F,
311
+ ...this._options?.execution ?? {},
312
+ ...t.execution ?? {},
313
+ ...this._options?.subscriberExecution?.[t.name] ?? {}
314
+ };
315
+ }
316
+ defineHydrationScheduler(t) {
317
+ return t.hydrationScheduler ?? this._hydrationScheduler;
318
+ }
319
+ defineSubscriberKey(t, e) {
320
+ return `${t.name}-${e.$id}`;
321
+ }
322
+ defineSubscriptionKey(t, e) {
323
+ return `${t}-${e.$id}`;
324
+ }
325
+ executeResetStoreCallbacks(t) {
326
+ this._resetStoreCallback.get(t)?.forEach((e) => e(t));
327
+ }
328
+ executeStoreOnActionSubscription(t) {
329
+ if (this._onActionStores.has(t) || typeof t.$onAction != "function")
330
+ return;
331
+ const e = this._onActionSubscriptions.get(t), r = this._storeRollbackSnapshotsHandler.storeHasRollbackSnapshots(t);
332
+ !e?.size && !r || (this._onActionStores.add(t), t.$onAction(({ after: n, args: c, name: o, onError: h }) => {
333
+ const l = this._onActionSubscriptions.get(t), d = l?.size;
334
+ if (!d)
335
+ return;
336
+ this.traceGroupStart(() => ({ args: c, callbacks: d, name: o }), t.$id, "onAction");
337
+ let _ = !1;
338
+ const y = () => {
339
+ _ || (_ = !0, this.traceGroupEnd({}, t.$id));
340
+ };
341
+ try {
342
+ const p = f(o, t);
343
+ this._storeRollbackSnapshotsHandler.storeHasRollbackSnapshots(t) && this.createRollbackSnapshot(o, t), l.forEach((m) => m({
344
+ after: this.createOnActionAfterCallbackCollector(o, t),
345
+ args: c,
346
+ name: o,
347
+ onError: this.createOnActionOnErrorCallbackCollector(o, t)
348
+ })), y(), this.executeStoreOnActionAfterCallbacks(n, p, t), this.executeStoreOnActionOnErrorCallbacks(h, p, t), this.clearOnActionCallbacksSubscriptions(p);
349
+ } catch (p) {
350
+ throw y(), p;
351
+ }
352
+ }));
353
+ }
354
+ executeStoreOnActionAfterCallbacks(t, e, r) {
355
+ const n = this._onActionAfterSubscriptions[e], c = n?.length;
356
+ c && t((o) => {
357
+ this.traceGroupStart(() => ({
358
+ callbacks: c,
359
+ result: o
360
+ }), r.$id, "execute:store:onAction:after:callbacks"), n.forEach((h) => {
361
+ try {
362
+ h(o);
363
+ } catch (l) {
364
+ this.traceError("executeStoreOnActionAfterCallbacks", l, r.$id);
365
+ }
366
+ }), this.traceGroupEnd(() => ({}), r.$id);
367
+ });
368
+ }
369
+ executeStoreOnActionOnErrorCallbacks(t, e, r) {
370
+ const n = this._onActionOnErrorSubscriptions[e];
371
+ n?.length && t((c) => {
372
+ this.traceGroupStart(() => ({
373
+ callbacks: n.length,
374
+ error: c
375
+ }), r.$id, "execute:store:onAction:onError:callbacks"), n.forEach((o) => {
376
+ try {
377
+ o(c);
378
+ } catch (h) {
379
+ this.traceError("execute:store:onAction:onError:callbacks:error", h, r.$id);
380
+ }
381
+ }), this.traceGroupEnd(() => ({}), r.$id);
382
+ });
383
+ }
384
+ executeSubscriber(t, e) {
385
+ const r = this.defineSubscriberKey(e, t.store);
386
+ if (this._subscribersDelivered.has(r) || !e.invoke(t, this._options?.tracerHandler?.createTracer))
387
+ return;
388
+ this._subscribersDelivered.add(r);
389
+ let n;
390
+ try {
391
+ n = e.hydrate?.(t);
392
+ } catch (o) {
393
+ this.traceError("subscriber:hydrate", o, t.store.$id);
394
+ return;
395
+ }
396
+ const c = () => {
397
+ try {
398
+ const o = e.afterHydration?.(t);
399
+ o && typeof o.then == "function" && o.catch(
400
+ (h) => this.traceError("subscriber:afterHydration", h, t.store.$id)
401
+ );
402
+ } catch (o) {
403
+ this.traceError("subscriber:afterHydration", o, t.store.$id);
404
+ }
405
+ };
406
+ n && typeof n.then == "function" ? n.then(() => c()).catch((o) => this.traceError("subscriber:hydrate", o, t.store.$id)) : c(), e.subscriptions && this.subscriptionDelivery(t, e.subscriptions), e.storeMutationSubscription && this.storeMutationSubscription(e.storeMutationSubscription), this.storeOnActionSubscription(e), e.resetStoreCallback && this.addResetStoreCallback(t.store, e.resetStoreCallback);
407
+ }
408
+ executeSubscriberSafely(t, e) {
409
+ try {
410
+ this.executeSubscriber(t, e);
411
+ } catch (r) {
412
+ this.traceError("subscriber:execute", r, t.store.$id);
413
+ }
414
+ }
415
+ initializeTracer() {
416
+ this._options?.tracerHandler && (this._tracer = this._options.tracerHandler.createTracer(j));
417
+ }
418
+ plugin({ store: t, options: e }) {
419
+ if (this._subscribers.length) {
420
+ this.traceGroupStart(() => ({
421
+ environment: this.defineCurrentEnvironment(),
422
+ subscribers: this._subscribers,
423
+ store: t,
424
+ options: e
425
+ }), t.$id);
426
+ try {
427
+ this._subscribers.forEach(
428
+ (r) => {
429
+ const n = this.defineSubscriberKey(r, t), c = this.definePluginExecution(r);
430
+ if (!(this._subscribersDelivered.has(n) || this._subscribersScheduled.has(n)) && this.shouldInvokePlugin(c)) {
431
+ if (this.shouldScheduleAfterHydration(c)) {
432
+ this.queueSubscriberExecution({ store: t, options: e }, r, n);
433
+ return;
434
+ }
435
+ this.executeSubscriber({ store: t, options: e }, r);
436
+ }
437
+ }
438
+ ), this.rewriteResetStore({ store: t }, t.$state), this._storeRollbackSnapshotsHandler.initFromPluginContext({ store: t, options: e }), this.executeStoreOnActionSubscription(t), this.registerStoreCleanup(t);
439
+ } catch (r) {
440
+ this.traceError("plugin:invoke", r, t.$id);
441
+ }
442
+ this.traceGroupEnd(() => ({}), t.$id);
443
+ }
444
+ }
445
+ queueSubscriberExecution(t, e, r) {
446
+ const n = this.defineHydrationScheduler(e);
447
+ this._subscribersScheduled.add(r), n(() => {
448
+ this._disposedStores.has(t.store) || (this._subscribersScheduled.delete(r), this.executeSubscriberSafely(t, e));
449
+ });
450
+ }
451
+ registerStoreCleanup(t) {
452
+ if (typeof t.$dispose != "function")
453
+ return;
454
+ const e = t.$dispose.bind(t), r = t;
455
+ r.__piniaPluginSubscriptionDisposed || (r.__piniaPluginSubscriptionDisposed = !0, t.$dispose = () => (this._disposedStores.add(t), this.clearStoreTracking(t), this._storeRollbackSnapshotsHandler.clearStoreTracking(t), e()));
456
+ }
457
+ rewriteResetStore({ store: t }, e) {
458
+ const r = u(e);
459
+ t.$reset = () => {
460
+ this.traceGroupStart(() => ({ initialState: r }), t.$id, "store:reset");
461
+ try {
462
+ this.executeResetStoreCallbacks(t), t.$patch(u(r));
463
+ } finally {
464
+ this.traceGroupEnd(() => ({ initialState: r }), t.$id);
465
+ }
466
+ };
467
+ }
468
+ shouldInvokePlugin(t) {
469
+ const e = this.defineCurrentEnvironment();
470
+ return t.environment === "both" || t.environment === e;
471
+ }
472
+ shouldScheduleAfterHydration(t) {
473
+ return this.defineCurrentEnvironment() === "client" && t.hydration === "defer";
474
+ }
475
+ storeOnActionSubscription(t) {
476
+ const { store: e, callback: r } = t?.storeOnActionSubscription?.() ?? {};
477
+ !e || !r || (this._onActionSubscriptions.has(e) || this._onActionSubscriptions.set(e, /* @__PURE__ */ new Set()), this._onActionSubscriptions.get(e).add(r), this.executeStoreOnActionSubscription(e));
478
+ }
479
+ storeMutationSubscription(t) {
480
+ const { store: e, callback: r } = t();
481
+ e.$subscribe((n) => {
482
+ this.traceGroupStart(() => ({ mutation: n }), e.$id, "store:mutation");
483
+ try {
484
+ r(n);
485
+ } finally {
486
+ this.traceGroupEnd({}, e.$id);
487
+ }
488
+ });
489
+ }
490
+ subscriptionDelivery(t, e) {
491
+ Object.entries(e).forEach(([r, n]) => {
492
+ const c = this.defineSubscriptionKey(r, t.store), o = this.definePluginExecution(n.subscription);
493
+ if (!(this._subscriptionsDelivered.has(c) || this._subscriptionsScheduled.has(c)) && this.shouldInvokePlugin(o)) {
494
+ if (this.shouldScheduleAfterHydration(o)) {
495
+ const h = this.defineHydrationScheduler(n.subscription);
496
+ this._subscriptionsScheduled.add(c), h(() => {
497
+ this._disposedStores.has(t.store) || (this._subscriptionsScheduled.delete(c), this.subscriptionDeliverySafely(t, r, n));
498
+ });
499
+ return;
500
+ }
501
+ this.subscriptionDeliverySafely(t, r, n);
502
+ }
503
+ });
504
+ }
505
+ subscriptionDeliverySafely({ store: t, options: e }, r, n) {
506
+ try {
507
+ if (this._subscriptionsDelivered.has(this.defineSubscriptionKey(r, t)))
508
+ return;
509
+ const { subscription: c, subscriptionOptions: o, stores: h } = n;
510
+ this.trace("Subscription:delivery", t.$id, () => ({
511
+ pluginName: r,
512
+ subscription: c,
513
+ subscriptionOptions: o
514
+ }));
515
+ const l = {
516
+ storeOptions: { ...e?.storeOptions ?? {}, ...o }
517
+ };
518
+ c.invoke(
519
+ { store: t, options: { ...e, ...l } }
520
+ ), this._subscriptionsDelivered.add(this.defineSubscriptionKey(r, t)), O(h) || h?.forEach(
521
+ (d) => c.invoke({
522
+ store: d,
523
+ options: {
524
+ ...e,
525
+ ...l,
526
+ ...d?.storeOptions ?? {}
527
+ }
528
+ })
529
+ );
530
+ } catch (c) {
531
+ this.traceError("subscription:delivery", c, t.$id);
532
+ }
533
+ }
534
+ traceGroupEnd(t, e) {
535
+ this._options?.tracerHandler && this._options.tracerHandler.closeGroup({
536
+ ...typeof t == "function" ? t() : t ?? {},
537
+ scope: e
538
+ });
539
+ }
540
+ traceGroupStart(t, e, r) {
541
+ this._options?.tracerHandler && (t = typeof t == "function" ? t() : t ?? {}, this._options.tracerHandler.startGroup({
542
+ ...t,
543
+ scope: e
544
+ }), this.trace(r ?? "context", e, t));
545
+ }
546
+ }
547
+ export {
548
+ Q as P,
549
+ D as T,
550
+ J as a,
551
+ q as b,
552
+ z as c,
553
+ N as d,
554
+ I as g,
555
+ P as h,
556
+ O as i,
557
+ j as p,
558
+ B as s
559
+ };
560
+ //# sourceMappingURL=PluginSubscription-DPu3ft-c.js.map