pinia-plugin-subscription 1.0.0-beta.2 → 1.0.0-beta.20

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 (77) hide show
  1. package/CHANGELOG.md +73 -12
  2. package/CONTRIBUTING.md +10 -1
  3. package/README.md +48 -293
  4. package/SECURITY.md +6 -6
  5. package/dist/chunks/setup-context-3G3Hy1ep.js +909 -0
  6. package/dist/dictionaries/plugin-subscription-event.d.ts +20 -0
  7. package/dist/{core/Store.d.ts → enhanced-store/EnhancedStore.d.ts} +24 -29
  8. package/dist/enhanced-store/define-a-store.d.ts +64 -0
  9. package/dist/enhanced-store/setup-context.d.ts +27 -0
  10. package/dist/events/EventsEmitter.d.ts +9 -0
  11. package/dist/events/EventsSubscriber.d.ts +32 -0
  12. package/dist/events/EventsSubscription.d.ts +13 -0
  13. package/dist/events/StoreEvent.d.ts +6 -0
  14. package/dist/events/StoresEventsSubscriptionsRegistry.d.ts +31 -0
  15. package/dist/events/event.d.ts +8 -0
  16. package/dist/factories/events-registry.d.ts +9 -0
  17. package/dist/factories/events-subscriber.d.ts +11 -0
  18. package/dist/factories/messenger-registry.d.ts +16 -0
  19. package/dist/factories/plugin-subscriber.d.ts +17 -0
  20. package/dist/helpers.js +204 -312
  21. package/dist/lib/helpers.d.ts +9 -0
  22. package/dist/lib/main.d.ts +3 -12
  23. package/dist/orchestration/ExecutionPolicy.d.ts +15 -0
  24. package/dist/orchestration/PluginOrchestrator.d.ts +41 -0
  25. package/dist/orchestration/SubscriberScheduler.d.ts +31 -0
  26. package/dist/pinia-plugin-subscription.js +31 -426
  27. package/dist/plugins/createPlugin.d.ts +3 -13
  28. package/dist/services/messenger.d.ts +28 -0
  29. package/dist/services/messengerProvider.d.ts +45 -0
  30. package/dist/store-hooks/StoreHooksBinder.d.ts +20 -0
  31. package/dist/store-hooks/StoreHooksRegistry.d.ts +34 -0
  32. package/dist/{core/PluginSubscriber.d.ts → subscribers/StoreSubscriber.d.ts} +39 -28
  33. package/dist/tracing/TraceGroupHelper.d.ts +27 -0
  34. package/dist/tracing/TraceableEmitter.d.ts +60 -0
  35. package/dist/tracing/TraceableEventsSubscriber.d.ts +21 -0
  36. package/dist/tracing/TraceableStoreEventsSubscriber.d.ts +16 -0
  37. package/dist/tracing/trace-groups.d.ts +9 -0
  38. package/dist/types/core.d.ts +12 -0
  39. package/dist/types/events.d.ts +24 -0
  40. package/dist/types/index.d.ts +8 -34
  41. package/dist/types/messenger.d.ts +20 -0
  42. package/dist/types/plugin.d.ts +39 -20
  43. package/dist/types/store.d.ts +1 -9
  44. package/dist/types/trace.d.ts +35 -75
  45. package/dist/utils/constants.d.ts +4 -0
  46. package/dist/utils/events.d.ts +3 -0
  47. package/dist/utils/id.d.ts +20 -0
  48. package/dist/utils/store.d.ts +9 -93
  49. package/docs/authoring-plugins.md +330 -78
  50. package/docs/using-plugins.md +89 -53
  51. package/package.json +14 -8
  52. package/dist/chunks/constantes-CaTNAbzX.js +0 -261
  53. package/dist/chunks/constantes-CaTNAbzX.js.map +0 -1
  54. package/dist/core/PluginSubscription.d.ts +0 -92
  55. package/dist/core/RollbackStateSnapshotsHandler.d.ts +0 -65
  56. package/dist/factories/console-trace-listener.d.ts +0 -7
  57. package/dist/factories/state-snapshot.d.ts +0 -3
  58. package/dist/factories/trace-listener.d.ts +0 -16
  59. package/dist/factories/trace-registry.d.ts +0 -17
  60. package/dist/helpers/index.d.ts +0 -9
  61. package/dist/helpers.js.map +0 -1
  62. package/dist/pinia-plugin-subscription.js.map +0 -1
  63. package/dist/plugins/createHydrationPlugin.d.ts +0 -10
  64. package/dist/system/Tracer.d.ts +0 -20
  65. package/dist/system/log.d.ts +0 -35
  66. package/dist/tests/defineAStore.test-d.d.ts +0 -1
  67. package/dist/tests/storeOptionsExtensions.test-d.d.ts +0 -12
  68. package/dist/types/comparison.d.ts +0 -3
  69. package/dist/types/list.d.ts +0 -13
  70. package/dist/types/log.d.ts +0 -8
  71. package/dist/types/resourceId.d.ts +0 -4
  72. package/dist/utils/Performance.d.ts +0 -9
  73. package/dist/utils/constantes.d.ts +0 -1
  74. package/dist/utils/deep-clone.d.ts +0 -7
  75. package/dist/utils/defineStoreId.d.ts +0 -1
  76. package/dist/utils/object.d.ts +0 -4
  77. package/dist/utils/validation/object.d.ts +0 -9
@@ -13,20 +13,20 @@ If you only want to **use** compatible plugins in an application, read
13
13
 
14
14
  ## Mental model
15
15
 
16
- - A **subscriber** is invoked by the central `PluginSubscription` engine
16
+ - A **subscriber** is invoked by the central `PluginOrchestrator`
17
17
  each time pinia registers a store.
18
18
  - A subscriber can extend the store, register callbacks (mutation
19
- subscriptions, action subscriptions, reset callbacks), and declare an
19
+ subscriptions and action subscriptions), and declare an
20
20
  execution policy for SSR.
21
21
  - `createPlugin([...subscribers])` aggregates subscribers into a single
22
22
  pinia plugin.
23
23
 
24
24
  Two authoring styles are available:
25
25
 
26
- 1. **Plain object** implementing `PluginSubscriberInterface` — lightweight,
26
+ 1. **Plain object** implementing `StoreSubscriberInterface` — lightweight,
27
27
  no classes.
28
- 2. **`PluginSubscriber` abstract class + `Store` subclass** — recommended
29
- for richer plugins: the `Store` subclass wraps the pinia store with
28
+ 2. **`StoreSubscriber` abstract class + `EnhancedStore` subclass** — recommended
29
+ for richer plugins: the `EnhancedStore` subclass wraps the Pinia store with
30
30
  helpers (state extension, subscriptions, structured tracing).
31
31
 
32
32
  ## Your first subscriber: a plain object
@@ -42,10 +42,6 @@ export const myStoreSubscriber = {
42
42
  console.log('store registered', context.store.$id)
43
43
 
44
44
  return true
45
- },
46
-
47
- resetStoreCallback: (store) => {
48
- console.log('store reset:', store.$id)
49
45
  }
50
46
  }
51
47
  ```
@@ -53,23 +49,38 @@ export const myStoreSubscriber = {
53
49
  ### TypeScript
54
50
 
55
51
  ```ts
56
- import type { PluginSubscriberInterface } from 'pinia-plugin-subscription'
52
+ import type { StoreSubscriberInterface } from 'pinia-plugin-subscription/types'
57
53
 
58
- export const myStoreSubscriber: PluginSubscriberInterface = {
54
+ export const myStoreSubscriber: StoreSubscriberInterface = {
59
55
  name: 'my-plugin',
60
56
 
61
57
  invoke: (context) => {
62
58
  console.log('store registered', context.store.$id)
63
59
 
64
60
  return true
65
- },
66
-
67
- resetStoreCallback: (store) => {
68
- console.log('store reset:', store.$id)
69
61
  }
70
62
  }
71
63
  ```
72
64
 
65
+ ### With the `createPluginSubscriber()` factory
66
+
67
+ `createPluginSubscriber(name, invoke, optionalProps?)` builds the same plain object with `name` and `invoke` as positional arguments. `optionalProps` accepts any other `StoreSubscriberInterface` member (`afterHydration`, `execution`, `hydrate`, `hydrationScheduler`, `storeOnActionSubscription`, `storeMutationSubscription`, `subscriptions`, `tracer`).
68
+
69
+ ```ts
70
+ import { createPluginSubscriber } from 'pinia-plugin-subscription/helpers'
71
+
72
+ export const myStoreSubscriber = createPluginSubscriber(
73
+ 'my-plugin',
74
+ (context, pluginOptions) => {
75
+ console.log('store registered', context.store.$id)
76
+ const tracer = pluginOptions?.createTracer?.('my-plugin')
77
+ tracer?.debug('Store registered', 'my-plugin:registered', { storeId: context.store.$id })
78
+
79
+ return true
80
+ }
81
+ )
82
+ ```
83
+
73
84
  The host app registers subscribers through `createPlugin()`:
74
85
 
75
86
  ```js
@@ -78,7 +89,7 @@ import { createPlugin } from 'pinia-plugin-subscription'
78
89
  pinia.use(createPlugin([myStoreSubscriber]))
79
90
  ```
80
91
 
81
- ## `PluginSubscriberInterface` reference
92
+ ## `StoreSubscriberInterface` reference
82
93
 
83
94
  | Member | Type | Description |
84
95
  | --- | --- | --- |
@@ -88,16 +99,16 @@ pinia.use(createPlugin([myStoreSubscriber]))
88
99
  | `hydrationScheduler` | `(run: () => void) => void` | Custom scheduler used when hydration is deferred. |
89
100
  | `hydrate` | `(context) => void \| Promise<void>` | SSR-safe initialization hook; guaranteed to run before `afterHydration`. |
90
101
  | `afterHydration` | `(context) => void \| Promise<void>` | Post-hydration lifecycle hook. |
91
- | `resetStoreCallback` | `(store?: Store) => void` | Custom logic executed when a registered store is reset. |
92
- | `storeOnActionSubscription` | `{ store, callback }` (getter) | Action subscription forwarded to the returned store's `$onAction`, including after deferred hydration; removed on store disposal. |
93
- | `storeMutationSubscription` | `{ store, callback }` (getter) | Mutation subscription forwarded to pinia's `$subscribe`. |
94
- | `subscriptions` | `Record<string, PluginSubscription>` | Plugin-specific subscription functions exposed to other plugins. |
102
+ | `storeOnActionSubscription` | `(context: PiniaPluginContext) => { store, callback }` | Receives the Pinia plugin context and returns an action subscription forwarded to the store's `$onAction`. Multiple subscribers can target the same store through a single `$onAction` hook; subscriptions are attached after deferred hydration and removed on store disposal. |
103
+ | `storeMutationSubscription` | `() => { store, callback }` | Returns a mutation subscription forwarded to pinia's `$subscribe`. Several subscribers can target the same store through a single `$subscribe` hook; callback errors are isolated and traced, and the hook is unsubscribed on store disposal. |
104
+ | `subscriptions` | `Record<string, PluginOrchestrator>` | Plugin-specific subscribers exposed to other plugins. |
105
+ | `tracer` | `Tracer \| undefined` | Optional tracer. `StoreSubscriber` instances receive one from `createPlugin()` when tracing is configured. |
95
106
 
96
107
  All members except `name` and `invoke` are optional.
97
108
 
98
- ## The `PluginSubscriber` abstract class
109
+ ## The `StoreSubscriber` abstract class
99
110
 
100
- For class-based plugins, extend `PluginSubscriber<Instance>`. The subscriber
111
+ For class-based plugins, extend `StoreSubscriber<Instance>`. The subscriber
101
112
  creates the instance through a factory — conventionally
102
113
  `MyPlugin.customizeStore.bind(MyPlugin)`.
103
114
 
@@ -105,49 +116,58 @@ creates the instance through a factory — conventionally
105
116
 
106
117
  | Generic | Constraint | Role |
107
118
  | --- | --- | --- |
108
- | `Instance` | `extends Store` | The `Store` subclass your plugin creates for each registered store. |
119
+ | `Instance` | `extends EnhancedStore` | The `EnhancedStore` subclass your plugin creates for each registered store. |
109
120
 
110
- The generic parameter is optional — JavaScript code and untyped TypeScript
111
- plugins can extend the class without it. Providing it types the
112
- `storeInstance` getter, so overridden hooks (`hydrate()`,
121
+ TypeScript subclasses must provide the `EnhancedStore` subclass as the generic
122
+ parameter. This types `getStoreInstance(store)`, so overridden hooks (`hydrate()`,
113
123
  `afterHydration()`, `pluginCreated`) get full autocompletion and compile-time
114
124
  checks when they call your plugin's custom methods.
115
125
 
116
126
  Constructor:
117
127
 
118
128
  ```ts
119
- constructor(pluginName: string, createInstance: CreateInstance)
129
+ constructor(createInstance: CreateInstance)
120
130
  ```
121
131
 
132
+ Each concrete subscriber must define a unique protected `_name` field. Its
133
+ value is used for subscriber identity, execution options, and tracing.
134
+
122
135
  | Member | Kind | Description |
123
136
  | --- | --- | --- |
124
137
  | `execution` | public field | Execution policy (see below). |
125
138
  | `hydrationScheduler` | public field | Custom scheduler used when hydration is deferred. |
126
139
  | `pluginCreated` | protected field | Optional hook called with the pinia store after a successful `invoke`. |
127
- | `pluginOptions` | getter/setter | Extra options merged into the options passed to your `Store` factory. |
128
- | `storeInstance` | getter | The `Store` subclass instance created for the current store. |
140
+ | `pluginOptions` | getter/setter | Extra options merged into the options passed to your `EnhancedStore` factory. |
141
+ | `getStoreInstance(store)` | method | Returns the `EnhancedStore` subclass instance for the specified Pinia store, or `undefined` if none was created. |
142
+ | `tracer` | getter | Tracer created for this subscriber during `invoke()`, or `undefined` when tracing is not configured. The same tracer is provided to the `EnhancedStore` factory through its `createTracer()` option. |
129
143
  | `hydrate()` / `afterHydration()` | methods | Lifecycle stubs to override for SSR-safe initialization. |
130
144
  | `invoke()` | method | Implemented for you: creates the instance, wires `subscriptions`, `storeSubscribe` and `onAction`, then calls `pluginCreated`. Returns `false` when the factory creates no instance. |
131
145
 
146
+ Use the store passed to each hook to retrieve its wrapper, including after an
147
+ `await`. Wrappers are held in a `WeakMap` keyed by store identity, not `$id`;
148
+ disposing a store does not itself cancel an already-running hydration hook.
149
+
132
150
  ### JavaScript
133
151
 
134
152
  ```js
135
- import { PluginSubscriber, Store } from 'pinia-plugin-subscription'
153
+ import { EnhancedStore, StoreSubscriber } from 'pinia-plugin-subscription/helpers'
136
154
 
137
- class MyPlugin extends Store {
155
+ class MyPlugin extends EnhancedStore {
138
156
  constructor(store, options) {
139
157
  super(store, options)
140
158
  this.doSomething()
141
159
  }
142
160
 
143
161
  doSomething() {
144
- this.trace('my-plugin:doSomething', () => ({ storeId: this.store.$id }))
162
+ this.trace('my-plugin:doSomething', this.store.$id, () => ({ storeId: this.store.$id }))
145
163
  }
146
164
  }
147
165
 
148
- class MyPluginSubscriber extends PluginSubscriber {
166
+ class MyPluginSubscriber extends StoreSubscriber {
167
+ _name = 'my-plugin'
168
+
149
169
  constructor() {
150
- super('my-plugin', (store, options) => new MyPlugin(store, options))
170
+ super((store, options) => new MyPlugin(store, options))
151
171
  }
152
172
  }
153
173
 
@@ -157,41 +177,45 @@ export const myStoreSubscriber = new MyPluginSubscriber()
157
177
  ### TypeScript
158
178
 
159
179
  ```ts
160
- import { PluginSubscriber, Store } from 'pinia-plugin-subscription'
180
+ import { EnhancedStore, StoreSubscriber } from 'pinia-plugin-subscription/helpers'
181
+ import type { Store as PiniaStore } from 'pinia'
182
+ import type { EnhancedStoreOptions } from 'pinia-plugin-subscription/types'
161
183
 
162
- class MyPlugin extends Store {
163
- protected override _className: string = 'MyPlugin'
184
+ class MyPlugin extends EnhancedStore {
185
+ protected override _name: string = 'MyPlugin'
164
186
  protected static override _requiredKeys?: string[] = ['my-plugin-option']
165
187
 
166
- constructor(store, options) {
188
+ constructor(store: PiniaStore, options: EnhancedStoreOptions) {
167
189
  super(store, options)
168
190
  this.doSomething()
169
191
  }
170
192
 
171
193
  doSomething(): void {
172
- this.trace('my-plugin:doSomething', () => ({ storeId: this.store.$id }))
194
+ this.trace('my-plugin:doSomething', this.store.$id, () => ({ storeId: this.store.$id }))
173
195
  }
174
196
  }
175
197
 
176
- class MyPluginSubscriber extends PluginSubscriber<MyPlugin> {
198
+ class MyPluginSubscriber extends StoreSubscriber<MyPlugin> {
199
+ protected _name = 'my-plugin'
200
+
177
201
  constructor() {
178
- super('my-plugin', MyPlugin.customizeStore.bind(MyPlugin))
202
+ super(MyPlugin.customizeStore.bind(MyPlugin))
179
203
  }
180
204
  }
181
205
 
182
206
  export const myStoreSubscriber = new MyPluginSubscriber()
183
207
  ```
184
208
 
185
- > **Important contract:** `Store.customizeStore()` only creates an instance
209
+ > **Important contract:** `EnhancedStore.customizeStore()` only creates an instance
186
210
  > when the store defines `storeOptions` **and** every key listed in the
187
211
  > static `_requiredKeys` is present in those options. When no instance is
188
212
  > created, `invoke()` returns `false` and the store is skipped by your
189
213
  > plugin. Declare `_requiredKeys = []` to accept every store that defines
190
214
  > `storeOptions`.
191
215
 
192
- ## The `Store` base class
216
+ ## The `EnhancedStore` base class
193
217
 
194
- `Store` wraps a pinia store (`PiniaStore`) and exposes:
218
+ `EnhancedStore` wraps a Pinia store (`PiniaStore`) and exposes:
195
219
 
196
220
  **Properties:** `options`, `state`, `store`.
197
221
 
@@ -207,9 +231,10 @@ export const myStoreSubscriber = new MyPluginSubscriber()
207
231
  | `storeSubscribe` (getter/setter) | Factory for pinia's `$subscribe` (`{ store, callback }`). |
208
232
  | `onAction` (getter/setter) | Factory for pinia's `$onAction` (`{ store, callback }`). |
209
233
  | `static customizeStore(store, options)` | Recommended factory; guarded by `_requiredKeys` (see above). |
210
- | `trace(label, payload?, scope?, namespace?)` | Emits a structured trace event. The default scope is the wrapped store ID. |
211
- | `traceError(label, error, payload?, scope?, namespace?)` | Emits an error event; if no listener matches, reports it with `console.error` without rethrowing it. |
212
- | `classNameAddedToTraceNamespace` (getter/setter) | Controls whether the store class name is prefixed to trace labels; enabled by default. |
234
+ | `trace(label, scope?, payload?, namespace?)` | Protected method that emits a structured trace event. The tracer's default scope is the wrapped store ID. |
235
+ | `traceError(label, error, scope?, payload?, namespace?)` | Protected method that emits an error event; without a tracer, reports it with `console.error`. |
236
+ | `traceOptions.prefixLabelWithName` | Protected option controlling whether `_name` is prefixed to trace labels; enabled by default for `EnhancedStore`. |
237
+ | `addEventSubscription(eventName, consumer, options?)` | Protected method for registering a callback with the shared event registry. |
213
238
  | `stateHas(property)` / `storeHas(property)` | Safe `hasOwnProperty` checks on state / store. |
214
239
  | `getValue(value)` | Unwraps a ref or returns the value as-is. |
215
240
  | `isOptionApi()` | Whether the store uses the options API. |
@@ -245,9 +270,9 @@ export const persistedStateSubscriber = {
245
270
 
246
271
  ```ts
247
272
  import { nextTick } from 'vue'
248
- import type { PluginSubscriberInterface } from 'pinia-plugin-subscription'
273
+ import type { StoreSubscriberInterface } from 'pinia-plugin-subscription/types'
249
274
 
250
- export const persistedStateSubscriber: PluginSubscriberInterface = {
275
+ export const persistedStateSubscriber: StoreSubscriberInterface = {
251
276
  name: 'persisted-state',
252
277
  execution: {
253
278
  environment: 'client',
@@ -269,19 +294,26 @@ Available execution options (`PluginExecutionOptions`):
269
294
  subscriber is allowed to run.
270
295
  - `hydration: 'immediate' | 'defer'` — on the client, `defer` schedules
271
296
  execution after hydration.
297
+ - `order: number` — subscribers with lower values run first. The default is
298
+ `9`; subscribers with the same value keep their declaration order. Use a
299
+ lower value when a subscriber must initialize before the default group (for
300
+ example, `StateSnapshotsSubscriber` uses `0`).
272
301
  - `hydrationScheduler` can be provided either on a subscriber or via
273
- `createHydrationPlugin()` to override the execution timing when needed.
302
+ `createPlugin()` to override the execution timing when needed.
274
303
 
275
304
  The class-based equivalent sets the same policy in the constructor and
276
305
  overrides the lifecycle hooks:
277
306
 
278
307
  ```ts
279
308
  import { nextTick } from 'vue'
280
- import { PluginSubscriber } from 'pinia-plugin-subscription'
309
+ import { StoreSubscriber } from 'pinia-plugin-subscription/helpers'
310
+ import type { PiniaPluginContext } from 'pinia'
311
+
312
+ class ExtendingStoreSubscriber extends StoreSubscriber<StoreExtension> {
313
+ protected _name = 'extendsPiniaStore'
281
314
 
282
- class ExtendingStoreSubscriber extends PluginSubscriber<StoreExtension> {
283
315
  constructor() {
284
- super('extendsPiniaStore', StoreExtension.customizeStore.bind(StoreExtension))
316
+ super(StoreExtension.customizeStore.bind(StoreExtension))
285
317
 
286
318
  // Controls when this subscriber may run and whether it should wait
287
319
  // for hydration on the client.
@@ -294,17 +326,15 @@ class ExtendingStoreSubscriber extends PluginSubscriber<StoreExtension> {
294
326
  this.hydrationScheduler = (run) => {
295
327
  nextTick(() => run())
296
328
  }
297
-
298
- this.pluginCreated = addStore
299
329
  }
300
330
 
301
- override hydrate() {
331
+ override hydrate(context: PiniaPluginContext) {
302
332
  if (typeof window === 'undefined') {
303
333
  return
304
334
  }
305
335
 
306
336
  // Safe browser-only initialization, only called when the policy allows it.
307
- return this.storeInstance?.hydrate?.()
337
+ return this.getStoreInstance(context.store)?.hydrate?.()
308
338
  }
309
339
  }
310
340
  ```
@@ -318,12 +348,12 @@ Use `hydration: 'defer'` when the subscriber depends on browser-only APIs,
318
348
  client-side cookies, `localStorage`, DOM access, or a hydrated app state
319
349
  that must exist only after the app is mounted.
320
350
 
321
- Use `runtimeEnvironment: 'server'` (on `createHydrationPlugin()`) or
351
+ Use `runtimeEnvironment: 'server'` (on `createPlugin()`) or
322
352
  `execution.environment: 'server'` when a subscriber is only valid during
323
353
  server-side rendering or should not touch browser-only objects:
324
354
 
325
355
  ```js
326
- pinia.use(createHydrationPlugin([serverOnlySubscriber], {
356
+ pinia.use(createPlugin([serverOnlySubscriber], {
327
357
  runtimeEnvironment: 'server'
328
358
  }))
329
359
  ```
@@ -362,32 +392,40 @@ initialization from crashing Nuxt or SSR builds.
362
392
 
363
393
  ### Emitting trace events
364
394
 
365
- Use `trace()` and `traceError()` from a `Store` subclass to emit structured
366
- events. The first argument is a human-readable label; by default the store
367
- class name is prefixed to it and the normalized label becomes the namespace.
368
- Pass an explicit fourth `namespace` argument to control the namespace, or set
369
- `classNameAddedToTraceNamespace = false` to omit the class prefix. Prefer a
370
- payload factory so data is not built unless a listener consumes the event:
395
+ Use the protected `trace()` and `traceError()` methods from an `EnhancedStore` subclass
396
+ to emit structured events. The first argument is a human-readable label; by
397
+ default the store's `_name` is prefixed to it and the normalized label becomes
398
+ the namespace. Pass an explicit `namespace` argument to control the namespace,
399
+ or set `this.traceOptions.prefixLabelWithName = false` in the subclass to omit
400
+ the prefix. Prefer a payload factory so data is not built unless a listener
401
+ consumes the event:
371
402
 
372
403
  ```ts
373
- class CartStore extends Store {
404
+ class CartStore extends EnhancedStore {
374
405
  reportItems(): void {
375
406
  this.trace(
376
407
  'cart:items',
377
- () => ({ items: this.state.items }),
378
408
  this.store.$id,
409
+ () => ({ items: this.state.items }),
379
410
  'cart:items'
380
411
  )
381
412
  }
382
413
  }
383
414
  ```
384
415
 
385
- `createTracerRegistry()` and `createConsoleTraceListener()` are available
386
- from `pinia-plugin-subscription/helpers`. Register listeners on a registry
387
- and pass its `createTracer` factory through `createPlugin()` options to
388
- connect them to plugin and store events. Listener filters can be callbacks
389
- over event metadata or criteria using `equals`, `contains`, `startsWith` and
390
- `endsWith` comparisons.
416
+ The plugin only emits events: it provides the `Tracer` and `TracerHandler`
417
+ types (from `pinia-plugin-subscription/types`) and ignores tracing when no
418
+ `tracerHandler` is configured. Consuming events is the job of the separate
419
+ `pinia-plugin-subscription-devtools` package, which provides
420
+ `createTracerRegistry()`. Register event criteria with `addListener()` (with
421
+ your own `handler`) and pass the registry's `tracerHandler` through
422
+ `createPlugin()` options to consume plugin and store events.
423
+ Criteria target event metadata and support `equals`, `contains`, `startsWith`
424
+ and `endsWith` comparisons. See the
425
+ [Tracing documentation](../packages/devtools/docs/tracing.md) for filtering,
426
+ redaction, production safety and error reporting. To test your plugin's
427
+ traces, install it as a development dependency, or provide a minimal
428
+ `TracerHandler` of your own.
391
429
 
392
430
  ## Typing per-store options: `StoreOptionsExtensions` (TypeScript)
393
431
 
@@ -414,7 +452,7 @@ directly in the store definition:
414
452
 
415
453
  ```ts
416
454
  export const useMyStore = defineAStore('myStore', () => { /* ... */ }, {
417
- rollbackAfterFailure: { save: 'all' }, // built-in option
455
+ rollbackAfterFailure: { save: 'all' }, // provided by pinia-plugin-state-snapshots
418
456
  myPluginOption: 'value', // typed via your augmentation
419
457
  })
420
458
  ```
@@ -429,9 +467,223 @@ Guidelines:
429
467
  - Never redeclare `DefineStoreOptionsBase` or `PiniaCustomProperties`; only
430
468
  this package owns those augmentations.
431
469
 
470
+ ## API Reference
471
+
472
+ ### Import subpaths
473
+
474
+ The root entry exports `createPlugin()`, `defineAStore()`, `defineAStoreCtx()`,
475
+ `getEnhancedStore()` and `PLUGIN_NAME`. Import subscriber classes and store
476
+ helpers from the helper subpath:
477
+
478
+ ```ts
479
+ import { EnhancedStore, PluginOrchestrator, StoreSubscriber } from 'pinia-plugin-subscription/helpers'
480
+ ```
481
+
482
+ For type-only imports, prefer the dedicated public types entry:
483
+
484
+ ```ts
485
+ import type { PluginOrchestratorOptions } from 'pinia-plugin-subscription/types'
486
+ ```
487
+
488
+ ### `createPlugin(subscribers: StoreSubscriberInterface[], options?: PluginOrchestratorOptions): PiniaPlugin`
489
+
490
+ Creates and returns a Pinia plugin from the provided `subscribers`. Each
491
+ subscriber is invoked when a store is registered. The optional `options`
492
+ configure execution and hydration defaults (`execution` and
493
+ `hydrationScheduler`), per-subscriber execution (`subscriberExecution`),
494
+ runtime environment, store behavior and tracing.
495
+
496
+ ### `createPluginSubscriber(name: string, invoke: StoreSubscriberInvoke, optionalProps?: Omit<StoreSubscriberInterface, 'name' | 'invoke'>): StoreSubscriberInterface`
497
+
498
+ Factory returning a plain-object subscriber `{ name, invoke, ...optionalProps }`. Exported from `pinia-plugin-subscription/helpers`.
499
+
500
+ ### Store event registration
501
+
502
+ `PluginSubscriberWithoutInstance` has been removed. Use a plain-object
503
+ subscriber or extend `StoreSubscriber` with an `EnhancedStore` wrapper instead.
504
+ `createPlugin()` passes a shared event registry to the subscriber and its
505
+ `EnhancedStore`. An `EnhancedStore` subclass can register callbacks with the protected
506
+ `addEventSubscription(eventName, consumer, options?)` method. Its subscriptions
507
+ default to the store's `$id` as their scope and are restricted to its Pinia
508
+ store instance, even when another instance has the same `$id`. The optional
509
+ `scope`, `source`, `instanceId`, and `payload` fields filter events by equality
510
+ when truthy; an `EnhancedStore` always sets `instanceId` to its own instance. Concrete
511
+ subscribers must define a unique protected `_name`.
512
+ `EnhancedStore.customizeStore()` initializes the instance and registers its disposal
513
+ hook; a custom factory that only calls the constructor does not perform those
514
+ steps. When creating an `EnhancedStore` outside this plugin flow, provide an
515
+ `eventsRegistry` in its options to register event callbacks.
516
+
517
+ The consumer receives an event with `name`, `scope` (the store's `$id`),
518
+ `instanceId`, `source`, and an optional lazy `payload()` function. The action
519
+ events use these payloads:
520
+
521
+ | Event | Payload |
522
+ | --- | --- |
523
+ | `STORE_EVENTS.ACTION_BEFORE` | `{ action, args, invocationKey }` before the action runs. |
524
+ | `STORE_EVENTS.ACTION_AFTER` | `{ action, result, invocationKey }` after a successful action. |
525
+ | `STORE_EVENTS.ACTION_ON_ERROR` | `{ action, error, invocationKey }` when an action fails. |
526
+ | `STORE_EVENTS.ACTION_ERROR` | `{ action, error, invocationKey }` if processing action subscriptions or registering outcome callbacks fails. |
527
+
528
+ When the store has an event subscriber, `invocationKey` is a symbol correlating
529
+ one action invocation across its events. It may be `undefined` otherwise.
530
+ Action events can be received without a `storeOnActionSubscription`; outcome
531
+ events are not emitted after store disposal.
532
+ Consumers run synchronously, but returned promises are not awaited; thrown
533
+ errors and rejections are reported to `console.error`.
534
+
535
+ ```ts
536
+ import { EnhancedStore, STORE_EVENTS } from 'pinia-plugin-subscription/helpers'
537
+
538
+ class ActionObserver extends EnhancedStore {
539
+ protected static override _requiredKeysValidation: false = false
540
+
541
+ protected override init(): void {
542
+ this.addEventSubscription(STORE_EVENTS.ACTION_BEFORE, event => {
543
+ const payload = event.payload?.()
544
+ if (payload) {
545
+ console.log(payload.action, payload.args, payload.invocationKey)
546
+ }
547
+ })
548
+ }
549
+ }
550
+ ```
551
+
552
+ As with other `EnhancedStore` subclasses, install it using `customizeStore()` and
553
+ provide `storeOptions` in the store's options.
554
+
555
+ ### Migrating subscribers from `main`
556
+
557
+ - Class-based subscribers define `_name` and pass only the store factory to
558
+ `super()`, instead of passing the name and factory.
559
+ - `invoke(context, createTracer)` now receives
560
+ `invoke(context, { createTracer, eventsRegistry })`; update custom `invoke`
561
+ implementations that use its second argument.
562
+ - `resetStoreCallback` is no longer collected by the orchestrator. Install
563
+ `pinia-plugin-state-snapshots` and register callbacks with `$onResetStore()`
564
+ when its reset wrapper is enabled. Those callbacks now run **after** state
565
+ restoration, rather than before it.
566
+ - Replace `subscriber.storeInstance` with
567
+ `subscriber.getStoreInstance(context.store)` in lifecycle hooks.
568
+
569
+ `createPlugin()` accepts hydration options directly. Set shared execution and
570
+ scheduling defaults for its subscribers, or use `subscriberExecution` to
571
+ configure execution by subscriber name:
572
+
573
+ ```typescript
574
+ import { nextTick } from 'vue'
575
+ import { createPlugin } from 'pinia-plugin-subscription'
576
+
577
+ pinia.use(createPlugin([persistedStateSubscriber], {
578
+ execution: {
579
+ environment: 'client',
580
+ hydration: 'defer',
581
+ },
582
+ hydrationScheduler: (run) => {
583
+ nextTick(() => run())
584
+ }
585
+ }))
586
+ ```
587
+
588
+ ### SSR / Nuxt hydration control
589
+
590
+ The source of truth for hydration policy stays on the subscriber itself. For example, a client-only plugin should declare its execution directly:
591
+
592
+ ```typescript
593
+ export const persistedStateSubscriber: StoreSubscriberInterface = {
594
+ name: 'persisted-state',
595
+ execution: {
596
+ environment: 'client',
597
+ hydration: 'defer',
598
+ },
599
+ hydrationScheduler: (run) => {
600
+ nextTick(() => run())
601
+ },
602
+ invoke: (context) => {
603
+ // ...
604
+ return true
605
+ }
606
+ }
607
+ ```
608
+
609
+ Available execution options:
610
+
611
+ - `environment: 'both' | 'client' | 'server'` — controls where the subscriber is allowed to run.
612
+ - `hydration: 'immediate' | 'defer'` — on the client, `defer` schedules execution after hydration.
613
+ - `hydrationScheduler` can be provided on a subscriber or through `createPlugin()` options to override execution timing when needed.
614
+
615
+ See [SSR / Nuxt best practices](#ssr--nuxt-best-practices) for guidance on matching the runtime policy to the app lifecycle.
616
+
617
+ ## Execution policy recap
618
+
619
+ The example above shows the recommended pattern for SSR / Nuxt-safe plugins:
620
+
621
+ - `execution.environment` restricts the subscriber to `'both'`, `'client'`, or `'server'`
622
+ - `execution.hydration` is `'immediate'` by default and can be set to `'defer'` when the plugin must wait for client hydration
623
+ - `hydrationScheduler` lets you override the runtime scheduling behavior, for example with Nuxt/Vue `nextTick()`
624
+ - `hydrate()` / `afterHydration()` are optional lifecycle hooks for browser-only initialization and post-hydration work; they help keep SSR-sensitive logic out of constructors
625
+
626
+ ## The `EnhancedStore` Class — Summary
627
+
628
+ The `EnhancedStore` class (see [src/enhanced-store/EnhancedStore.ts](../src/enhanced-store/EnhancedStore.ts)) is a wrapper around a `PiniaStore` providing:
629
+
630
+ - **Properties:** `options`, `state`, `store`.
631
+ - **Useful methods:**
632
+ - `addToState(name, value?)` — adds a property to store state and exposes it as a `Ref` when appropriate.
633
+ - `addSubscription(pluginName, subscription)` — registers a plugin-specific subscription function.
634
+ - `getSubscriptions()` — returns registered subscriptions.
635
+ - `storeSubscribe` (getter/setter) — factory for `store.$subscribe` ({ store, callback }).
636
+ - `onAction` (getter/setter) — factory for `onAction` ({ store, callback }).
637
+ - `static customizeStore(store, options)` — recommended factory for class instantiation.
638
+ - Protected `trace(label, scope?, payload?, namespace?)` — emits a structured trace event, scoped to the store by default when its tracer is configured.
639
+ - Protected `traceError(label, error, scope?, payload?, namespace?)` — emits an error event, or reports it with `console.error` when no tracer is configured.
640
+ - Helpers: `stateHas()`, `storeHas()`, `getValue()`.
641
+
642
+ `EnhancedStore`, `StoreSubscriber` and `PluginOrchestrator` share
643
+ protected tracing and store-event emission helpers.
644
+
645
+ ## Testing
646
+
647
+ - `npm test` — runs the Vitest suite, including the typecheck tests
648
+ (`*.test-d.ts`).
649
+ - `npm run build` — runs tests, builds the core library and both workspace
650
+ packages, and checks their published artifacts.
651
+ - `npm run build:demo` — production-builds the example application.
652
+ - `npm run dev` — runs the dedicated demo app in [`demo/`](../demo/). The library build remains `npm run build` and is intentionally kept separate from the demo entry.
653
+ - `npm run bundle:check` — measures the emitted bundle size.
654
+
655
+ ### Dependency leak guard
656
+
657
+ Published artifacts must only reference **peer dependencies** (`pinia`, `vue`) and Node builtins. A `devDependency` referenced from `src/` does not fail the local build, but it breaks consumers: Vite inlines runtime imports, while `tsc` keeps bare `import type` specifiers in the emitted `.d.ts`, which consumers cannot resolve.
658
+
659
+ `npm run check:leaks` scans every built `.js` and `.d.ts` file and fails the build when a non-peer package appears:
660
+
661
+ ```bash
662
+ npm run check:leaks
663
+ ```
664
+
665
+ It runs automatically as part of `npm run build` and in CI. If it reports a leak, either remove the import from `src/`, or duplicate the required type into `src/types/`.
666
+
432
667
  ## Reference implementation
433
668
 
434
- The demo app ships a complete plugin implementation in
435
- [`demo/`](../demo/): a
436
- `PluginSubscriber` subclass, a `Store` subclass, option typing and SSR
437
- guards. Run `npm run dev` to explore it live.
669
+ The demo app in [`demo/`](../demo/) includes class-based, plain-object, and
670
+ SSR-aware subscribers. Run `npm run dev` for client-only rendering or
671
+ `npm run dev:ssr` to run the Vite SSR server and hydrate the rendered page in
672
+ the browser. Its two subscribers hydrate the same store from different environments: a
673
+ server-only one loads request data (the server waits for its async `hydrate()` before
674
+ rendering) and a client-only, deferred one reads browser APIs after hydration. Both modes
675
+ resolve the package to `src/`, so no build is needed. See also
676
+ [`demo/README.md`](../demo/README.md).
677
+
678
+ | Style | Files | Shows |
679
+ | --- | --- | --- |
680
+ | Class-based | [`demo/plugins/DemoPluginClass.ts`](../demo/plugins/DemoPluginClass.ts), [`demo/core/DemoStore.ts`](../demo/core/DemoStore.ts) | `StoreSubscriber` subclass, `EnhancedStore` subclass, `hasRequiredKeys` gating, store augmentation (`this.state`, `this.store`), `onAction` / `storeSubscribe`, `trace()` |
681
+ | Plain object | [`demo/plugins/demoPluginObject.ts`](../demo/plugins/demoPluginObject.ts) | `createPluginSubscriber()`, per-store opt-in through `storeOptions`, `createTracer`, `traceGroups` |
682
+ | Environment-aware hydration | [`demo/plugins/demoPluginEnvironmentHydration.ts`](../demo/plugins/demoPluginEnvironmentHydration.ts), [`demo/core/VisitorEnvironmentStore.ts`](../demo/core/VisitorEnvironmentStore.ts), [`demo/stores/visitor-environment.ts`](../demo/stores/visitor-environment.ts), [`demo/entry-server.ts`](../demo/entry-server.ts) | One store hydrated by a server-only subscriber (awaited before render and serialization) and a client-only `hydration: 'defer'` subscriber; each is skipped in the other environment; traces via `EnhancedStore.trace()` and the `onMutation` group |
683
+ | Enhanced store | [`demo/stores/enhanced-store.ts`](../demo/stores/enhanced-store.ts), [`demo/components/EnhancedExample.vue`](../demo/components/EnhancedExample.vue) | `defineAStoreCtx` + `getEnhancedStore` consuming the `DemoStore` augmentations |
684
+ | Option typing | [`demo/types/plugin.ts`](../demo/types/plugin.ts) | Extending `StoreOptions` with plugin options |
685
+ | Registration & tracing | [`demo/app.ts`](../demo/app.ts) | `createPlugin()` with several subscribers, `createTraceDevtools()` from `pinia-plugin-subscription-devtools` |
686
+ | Rollback | [`demo/stores/rollback-snapshot.ts`](../demo/stores/rollback-snapshot.ts), [`demo/components/Example.vue`](../demo/components/Example.vue) | `rollbackAfterFailure` option vs manual `$rollbackAfterFailure()` |
687
+
688
+ Open the browser console to see the trace output of the
689
+ `rollbackSnapshotStoreWithRollback` scope.