pinia-plugin-subscription 1.0.0-beta.0 → 1.0.0-beta.10

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 (38) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +11 -251
  3. package/SECURITY.md +6 -6
  4. package/dist/chunks/PluginSubscription-BbN48iuP.js +636 -0
  5. package/dist/chunks/PluginSubscription-BbN48iuP.js.map +1 -0
  6. package/dist/core/PluginSubscriber.d.ts +6 -7
  7. package/dist/core/PluginSubscription.d.ts +17 -11
  8. package/dist/core/Store.d.ts +23 -19
  9. package/dist/factories/console-trace-listener.d.ts +7 -0
  10. package/dist/factories/plugin-subscriber.d.ts +18 -0
  11. package/dist/factories/trace-listener.d.ts +10 -0
  12. package/dist/factories/trace-registry.d.ts +2 -6
  13. package/dist/helpers/index.d.ts +6 -4
  14. package/dist/helpers.js +674 -132
  15. package/dist/helpers.js.map +1 -1
  16. package/dist/lib/main.d.ts +2 -11
  17. package/dist/pinia-plugin-subscription.js +16 -424
  18. package/dist/pinia-plugin-subscription.js.map +1 -1
  19. package/dist/system/TraceEmitter.d.ts +25 -0
  20. package/dist/system/Tracer.d.ts +7 -4
  21. package/dist/system/log.d.ts +9 -5
  22. package/dist/types/index.d.ts +7 -21
  23. package/dist/types/plugin.d.ts +81 -5
  24. package/dist/types/store.d.ts +0 -3
  25. package/dist/types/trace.d.ts +89 -9
  26. package/dist/utils/constants.d.ts +4 -0
  27. package/dist/utils/environment.d.ts +7 -0
  28. package/dist/utils/redact.d.ts +15 -0
  29. package/dist/utils/store.d.ts +4 -1
  30. package/dist/utils/traceGroups.d.ts +7 -0
  31. package/docs/authoring-plugins.md +175 -12
  32. package/docs/tracing.md +181 -0
  33. package/docs/using-plugins.md +37 -19
  34. package/package.json +2 -3
  35. package/dist/chunks/constantes-BsD73jkk.js +0 -245
  36. package/dist/chunks/constantes-BsD73jkk.js.map +0 -1
  37. package/dist/system/createConsoleTraceListener.d.ts +0 -6
  38. package/dist/utils/constantes.d.ts +0 -1
package/CHANGELOG.md CHANGED
@@ -7,9 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+ - `storeMutationSubscription` now supports several subscribers per store, like `storeOnActionSubscription`: a single `$subscribe` is registered per store and dispatches to every callback. A failing callback is reported through `traceError` without blocking the others, subscriber names are tracked, and the hook is unsubscribed when the store is disposed
12
+ - `storeOnActionSubscription` now receives the Pinia plugin context; action trace labels include the invoked action name
13
+
10
14
  ### Added
15
+ - Added `addScopesListener(scopes, context?)` to `createTracerRegistry()` for grouping events from selected store scopes; documented in `docs/tracing.md`
16
+ - `traceGroups` glossary, exported from `pinia-plugin-subscription/helpers`, building the `groupId` emitted by `PluginSubscription` (`onActionAfter`, `onActionError`, `onMutation`, `reset`); documented in `docs/tracing.md`
17
+ - `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
18
+ - Added a dedicated tracing guide, `docs/tracing.md`; the README now only presents tracing and links to it
19
+ - Moved the API reference, import subpaths, development, `Store` summary and testing sections from `README.md` to `docs/authoring-plugins.md`
20
+ - `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
21
+ - `createTracerRegistry({ enabled })`: tracing is now disabled by default in production builds (`process.env.NODE_ENV === 'production'`); `addListener()` becomes a no-op unless `enabled: true` is passed. `enabled: false` forces it off in any environment. Error reporting through `console.error` is unchanged
11
22
  - Added `createTracerRegistry()` to create isolated trace listeners and tracers for each application or Pinia instance
23
+ - Added `createTracerRegistry()` to group matching trace events in the console
12
24
  - Added the `Tracer` class and registry methods `addTraceListener()`, `clearTraceListeners()` and `hasTraceListeners()`
25
+ - Added metadata-based trace filter criteria with `equals`, `contains`, `startsWith` and `endsWith` comparators, combined with `every` or `some`
13
26
  - Added `createConsoleTraceListener()` as an opt-in console sink for trace events
14
27
  - Added `trace()` and `traceError()` to `Store` and `PluginSubscription`
15
28
  - Added trace types: `TraceEvent`, `TraceEventMetadata`, `TraceFilter`, `TraceHandler`, `TraceLevel`, `TraceListener`, `TraceListenerRemover`, `TracePayload`, `TracerOptions`
@@ -18,19 +31,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
18
31
  - Added unit tests covering the tracing system and the leak detection logic
19
32
 
20
33
  ### Changed
34
+ - Moved the demo application from `src/demo/` to the repository-level `demo/` directory, separating example code from the library source and tracking the demo files in version control.
21
35
  - Clarified that SSR tracing registries and plugin instances must be created per request, and added coverage for listener isolation between registries
22
36
  - Replaced the `Debug` abstract class with composition: `Store` and `PluginSubscription` no longer extend it and now own a `Tracer`
23
37
  - `createPlugin()` accepts `PluginSubscriptionOptions`, including a `createTracer` factory to connect a tracer registry to plugin and store trace events
24
38
  - Trace errors with no matching listener, and failures in listener filters or handlers, are now reported with `console.error` instead of rethrowing the original error
25
39
  - Deprecated `createHydrationPlugin()` in favor of `createPlugin()` with hydration options
26
40
  - Trace payloads are now lazily resolved, so unobserved tracing no longer builds log arguments
27
- - Internal log messages became structured namespaces (`plugin:invoke`, `store:mutation`, `subscription:delivery`, …) carrying `store.$id` as `scope`
41
+ - Internal events now derive namespaces from trace labels, with `PluginSubscription` prefixed by default; store events carry `store.$id` as `scope`
28
42
  - `Tracer` now delegates all output decisions to listeners and no longer owns a console or an enabled state
29
43
  - Error events are delivered to matching listeners and reported with `console.error` when none match
44
+ - Store trace labels can include the store class name by default, and callers can override the event namespace
30
45
  - Excluded `scripts/**` from coverage thresholds, as build tooling is not shipped to consumers
46
+ - `Store` and `PluginSubscription` now share the abstract `TraceEmitter` class for `trace()`, `traceError()` and class-name label formatting, removing duplicated code
47
+ - `Tracer` listener matching no longer allocates intermediate arrays beyond the matched set, and duplicated unhandled-error reporting was factored out
48
+ - The `pluginsubscription` namespace prefix is now a shared constant (`pluginSubscriptionNamespace`) instead of a hard-coded string
49
+
50
+ ### Fixed
51
+ - `onAction`, `after` and `onError` subscription callbacks may now be asynchronous: rejections are traced instead of becoming unhandled, and their trace groups are closed once all async callbacks have settled
52
+ - Group listener filters receive only trace metadata, redaction safely copies own `__proto__` keys, and registry group payload factories are skipped when no listeners are registered
53
+ - Subscriber, subscription, action and rollback tracking keys now encode store IDs and names without delimiter collisions; disposing a store removes only its own tracking entries
54
+ - Trace groups opened by `onAction`, `$subscribe` and `$reset` are now always closed (also when the action fails or a callback throws), so grouped events no longer stay buffered forever
55
+ - Listener definitions passed to `addListener()` are no longer mutated when their `filter` is an array of criteria
56
+ - `TracerHandler` and `TraceRegistry` types now match the implementation (`createTracer(source, options?)`, `void` group callbacks, `addListener()` with options, `tracerHandler`); `createTracerRegistry()` is explicitly typed as `TraceRegistry`
57
+ - `CustomConsole.rebuildArgs()` no longer returns `undefined` for unsupported argument types
58
+ - `clearTraceListeners()` now empties the shared listener list in place, so tracers created before the call stop delivering to cleared listeners and see listeners registered afterwards
31
59
 
32
60
  ### Removed
33
- - **Breaking:** removed `debugLog()` and `logError()` from `Store` and `PluginSubscription` — use `trace()` and `traceError()` instead (see the migration snippet in `README.md`)
61
+ - Removed the internal `PluginConsole` singleton and the dead commented code of `system/log.ts`; `CustomConsole` stays exported from `helpers` for plugins not yet migrated to the tracer
62
+ - **Breaking:** removed `debugLog()` and `logError()` from `Store` and `PluginSubscription` — use `trace()` and `traceError()` instead (see the migration snippet in `docs/tracing.md`)
34
63
  - **Breaking:** removed the obsolete `debug` and custom-console arguments from `createPlugin()`, `PluginSubscription`, `PluginSubscriber`, `Store`, and `Store.customizeStore()`
35
64
  - **Breaking:** removed the `debug` argument from subscriber `invoke()`, `hydrate()`, and `afterHydration()` hooks; tracing is now configured exclusively through listeners
36
65
  - **Breaking:** removed the legacy `debug` and `console` accessors from `Store` and `PluginSubscription`
package/README.md CHANGED
@@ -34,7 +34,8 @@ The package serves two audiences:
34
34
  | You want to… | Guide |
35
35
  | --- | --- |
36
36
  | Use a compatible plugin (e.g. `pinia-plugin-extending-store`, `pinia-plugin-persist-state`) or this package's built-in store features (`defineAStore`, `$reset`, state rollback) in your app | [Using compatible plugins](docs/using-plugins.md) |
37
- | Build your own pinia plugin on top of `pinia-plugin-subscription` | [Plugin authoring guide](docs/authoring-plugins.md) |
37
+ | Build your own pinia plugin on top of `pinia-plugin-subscription` (API reference, `Store` class, import subpaths, development and testing) | [Plugin authoring guide](docs/authoring-plugins.md) |
38
+ | Debug stores and plugins with structured trace events | [Tracing](docs/tracing.md) |
38
39
 
39
40
  ## Installation
40
41
 
@@ -60,270 +61,29 @@ app.use(pinia)
60
61
  app.mount('#app')
61
62
  ```
62
63
 
63
- ### Import subpaths
64
-
65
- ## Usage — Examples
66
-
67
- **1) Subscriber using a `Store` subclass:**
68
-
69
- ```typescript
70
- import PluginSubscriber from 'pinia-plugin-subscription'
71
- import { Store } from 'pinia-plugin-subscription'
72
-
73
- class MyPlugin extends Store {
74
- protected override _className: string = 'MyPlugin'
75
- protected static override _requiredKeys?: string[] | undefined = ['my-plugin-option']
76
-
77
- constructor(store, options) {
78
- super(store, options)
79
- this.doSomething()
80
- }
81
- }
82
-
83
- class MyPluginSubscriber extends PluginSubscriber<MyPlugin> {
84
- constructor() {
85
- super('my-plugin', MyPlugin.customizeStore.bind(MyPlugin))
86
- }
87
- }
88
-
89
- export const myStoreSubscriber = new MyPluginSubscriber()
90
- ```
91
-
92
- **2) Simple subscriber implementing `PluginSubscriberInterface`:**
93
-
94
- ```typescript
95
- import type { PluginSubscriberInterface } from 'pinia-plugin-subscription'
96
-
97
- export const myStoreSubscriber: PluginSubscriberInterface = {
98
- name: 'my-plugin',
99
-
100
- invoke: (context) => {
101
- // context contains `store`, `options`, `pinia`
102
- console.log('store registered', context.store.$id)
103
-
104
- return true
105
- },
106
-
107
- resetStoreCallback: (store) => {
108
- console.log('store reset:', store.$id)
109
- }
110
- }
111
- ```
112
-
113
64
  ## Advanced Features
114
65
 
115
- - **Structured tracing:** Subscribe to typed trace events and filter them at runtime, per store or per namespace — see [Tracing](#tracing).
66
+ - **Structured tracing:** Subscribe to typed trace events and filter them at runtime, per store or per namespace. Group filters receive metadata only, and the built-in registry avoids preparing group payloads when it has no listeners — see [Tracing](#tracing).
67
+ - **Scope-based trace listeners:** Use `addScopesListener()` to group events from selected stores — see [Tracing](docs/tracing.md#filtering-events).
116
68
  - **Reset callbacks:** Define `resetStoreCallback` to run custom logic when a store is reset.
117
69
  - **SSR and hydration control:** Configure whether each subscribed plugin runs on the server, the client, or only after client hydration.
118
70
  - **Lifecycle safety:** Internal hydration ordering is now guarded so `hydrate()` completes before `afterHydration()` and disposed stores do not retain stale subscriber metadata.
119
71
 
120
- ## API Reference
121
-
122
- ### `createPlugin(subscribers: PluginSubscriber[]): PiniaPlugin`
123
-
124
- Creates and returns a Pinia plugin from the provided `subscribers`. Each subscriber is invoked when a store is registered.
125
-
126
- ### `createHydrationPlugin(subscribers: PluginSubscriber[], options?: PluginSubscriptionOptions): PiniaPlugin`
127
-
128
- Deprecated. Use `createPlugin()` with hydration options instead. This helper remains available for compatibility.
129
-
130
- ```typescript
131
- import { createPlugin } from 'pinia-plugin-subscription'
132
-
133
- pinia.use(createPlugin([
134
- persistedStateSubscriber
135
- ], {
136
- hydrationScheduler: (run) => {
137
- nextTick(() => run())
138
- }
139
- }))
140
- ```
141
-
142
- ### SSR / Nuxt hydration control
143
-
144
- The source of truth for hydration policy stays on the subscriber itself. For example, a client-only plugin should declare its execution directly:
145
-
146
- ```typescript
147
- export const persistedStateSubscriber: PluginSubscriberInterface = {
148
- name: 'persisted-state',
149
- execution: {
150
- environment: 'client',
151
- hydration: 'defer',
152
- },
153
- hydrationScheduler: (run) => {
154
- nextTick(() => run())
155
- },
156
- invoke: (context) => {
157
- // ...
158
- return true
159
- }
160
- }
161
- ```
162
-
163
- Available execution options:
164
-
165
- - `environment: 'both' | 'client' | 'server'` — controls where the subscriber is allowed to run.
166
- - `hydration: 'immediate' | 'defer'` — on the client, `defer` schedules execution after hydration.
167
- - `hydrationScheduler` can be provided on a subscriber or through `createPlugin()` options to override execution timing when needed.
168
-
169
- ### SSR / Nuxt best practices
170
-
171
- `pinia-plugin-subscription` is SSR-safe by design, but the runtime policy still needs to match the actual app lifecycle.
172
-
173
- For helper-only imports, the package exposes an additive subpath kept separate from the default library API:
174
-
175
- ```ts
176
- import { PluginSubscriber, Store } from 'pinia-plugin-subscription/helpers'
177
- ```
178
-
179
- For type-only imports, prefer the dedicated public types entry:
180
-
181
- ```ts
182
- import type { PluginSubscriptionOptions } from 'pinia-plugin-subscription/types'
183
- ```
184
-
185
- ## Development
186
-
187
- This example shows the recommended pattern for SSR / Nuxt-safe plugins:
188
-
189
- - `execution.environment` restricts the subscriber to `'both'`, `'client'`, or `'server'`
190
- - `execution.hydration` is `'immediate'` by default and can be set to `'defer'` when the plugin must wait for client hydration
191
- - `hydrationScheduler` lets you override the runtime scheduling behavior, for example with Nuxt/Vue `nextTick()`
192
- - `hydrate()` / `afterHydration()` are optional lifecycle hooks for browser-only initialization and post-hydration work; they help keep SSR-sensitive logic out of constructors
193
-
194
- ## The `Store` Class — Summary
195
-
196
- The `Store` class (see [src/core/Store.ts](src/core/Store.ts)) is a wrapper around a `PiniaStore` providing:
197
-
198
- - **Properties:** `options`, `state`, `store`.
199
- - **Useful methods:**
200
- - `addToState(name, value?)` — adds a property to store state and exposes it as a `Ref` when appropriate.
201
- - `addSubscription(pluginName, subscription)` — registers a plugin-specific subscription function.
202
- - `getSubscriptions()` — returns registered subscriptions.
203
- - `storeSubscribe` (getter/setter) — factory for `store.$subscribe` ({ store, callback }).
204
- - `onAction` (getter/setter) — factory for `onAction` ({ store, callback }).
205
- - `static customizeStore(store, options)` — recommended factory for class instantiation.
206
- - `trace(namespace, payload?)` — emits a structured trace event scoped to the store.
207
- - `traceError(namespace, error, payload?)` — emits an error event, or reports it with `console.error` when no listener matches.
208
- - Helpers: `stateHas()`, `storeHas()`, `getValue()`.
209
-
210
72
  ## Tracing
211
73
 
212
- Tracing is **opt-in**, scoped to an explicit registry, and **allocation free when unused**. Create one registry per application or Pinia instance, then pass its `createTracer` factory to `createPlugin()` so plugin and store events share its listeners. For SSR, create a fresh registry, Pinia instance, and plugin instance for every request; do not keep them in module-level state or clear a shared registry at request completion, since requests may overlap. See the [SSR guide](./docs/using-plugins.md#ssr--nuxt) for an example.
213
-
214
- ### Production safety
215
-
216
- Tracing is **not automatically blocked in production**. Leave normal tracing disabled by default using your application's environment configuration; enable production diagnostics only deliberately and with limited scope and duration.
217
-
218
- Events are **not automatically redacted** and may include sensitive action arguments, store state, plugin options, or error details. Filters select events by metadata; they do not sanitize payloads. Before writing to a console or forwarding to a logging service, select an allowlist of fields and redact sensitive values rather than sending complete events.
219
-
220
- **Disabling normal tracing does not disable error reporting.** Errors can still be sent to `console.error` without a tracer or when no listener matches. See [Error reporting](#error-reporting) and the [security guidance](./SECURITY.md#tracing-and-production-logging) for precautions, including log access and retention.
221
-
222
- ### Consuming events
223
-
224
- ```ts
225
- import { createPlugin, createTracerRegistry } from 'pinia-plugin-subscription'
226
-
227
- const traceRegistry = createTracerRegistry()
228
- const remove = traceRegistry.addTraceListener({
229
- filter: (event) => event.scope === 'cart' && event.namespace.startsWith('subscription:'),
230
- handler: (event) => console.log(event.namespace, event.scope, event.payload)
231
- })
232
-
233
- pinia.use(createPlugin(subscribers, {
234
- createTracer: traceRegistry.createTracer
235
- }))
236
-
237
- remove() // unsubscribe
238
- ```
239
-
240
- `filter` is evaluated on every event, so you can narrow tracing to a single store without rebuilding. Registries do not share listeners with one another.
241
-
242
- ### Event shape
243
-
244
- | Field | Description |
245
- | --- | --- |
246
- | `namespace` | Structured identifier, e.g. `subscription:delivery` |
247
- | `source` | Emitting class name, e.g. `PluginSubscription` |
248
- | `scope` | Instance identifier, usually `store.$id` |
249
- | `payload` | Event data, resolved only when consumed |
250
- | `level` | `debug` or `error` |
251
- | `timestamp` | `Date.now()` at emission |
252
- | `error` | Present on `error` events |
253
-
254
- Namespaces emitted by the plugin: `plugin:invoke`, `store:action`, `store:mutation`, `store:reset`, `subscription:delivery`, `subscriber:execute`, `subscriber:hydrate`, `subscriber:afterHydration`.
255
-
256
- ### Emitting your own events
257
-
258
- ```ts
259
- class CartStore extends Store {
260
- hydrate() {
261
- this.trace('cart:hydrate', () => ({ items: this.state.items }))
262
- }
263
- }
264
- ```
265
-
266
- Always prefer the **function form** for `payload`: it is only invoked once a listener matches, so unobserved tracing costs nothing.
267
-
268
- ### Console listener
269
-
270
- Normal trace events do not write to a console. Console output for those events is an opt-in listener:
271
-
272
- ```ts
273
- import {
274
- createTracerRegistry,
275
- createConsoleTraceListener
276
- } from 'pinia-plugin-subscription'
277
-
278
- const traceRegistry = createTracerRegistry()
279
- const remove = traceRegistry.addTraceListener(createConsoleTraceListener())
280
- ```
281
-
282
- By default, this listener uses the styled plugin console. Pass any object exposing `log` and `error` to use another target:
283
-
284
- Any object exposing `log` and `error` satisfies the `Console` interface, so external logging libraries can be connected without this plugin depending on them:
74
+ A built-in, opt-in debugging solution: plugins and stores emit structured trace events that you select with filters, optionally redact, and group in the console. It is disabled by default in production builds and costs nothing when unused.
285
75
 
286
76
  ```ts
287
- const remove = traceRegistry.addTraceListener(createConsoleTraceListener(myLogger))
288
- ```
289
-
290
- ### Error reporting
291
-
292
- An error is delivered to every matching listener. If no listener matches — including when listeners exist but all filters reject the event — it is reported with `console.error`; it is not rethrown. Errors thrown by filters or handlers are also reported and isolated so they do not interrupt the traced process or remaining listeners.
293
-
294
- ### Migrating from `debugLog()` / `logError()`
295
-
296
- These methods were removed in favour of structured events:
297
-
298
- ```ts
299
- // before
300
- this.debugLog(`$subscribe ${store.$id}`, { mutation, store })
301
- this.logError('subscriptionDelivery()', error, store, options)
302
-
303
- // after
304
- this.trace('store:mutation', () => ({ mutation, store }))
305
- this.traceError('subscription:delivery', error, () => ({ store, options }))
306
- ```
307
-
308
- The `namespace` replaces the formatted message, store trace events are scoped to `store.$id`, and the payload becomes a factory so it is only built when a listener consumes the event.
309
-
310
- ## Testing
311
-
312
- - `npm run dev` — runs the dedicated demo app. The library build remains `npm run build` and is intentionally kept separate from the demo entry. The demo ships a complete plugin-authoring example in [`src/demo/extending-pinia-store/`](src/demo/extending-pinia-store/).
313
- - `npm test` — runs the Vitest suite, including typecheck tests (`*.test-d.ts`) validating type-level contracts such as `StoreOptionsExtensions` merging. Coverage reports are available in `coverage/`.
314
- - `npm run bundle:check` — measures the emitted bundle size.
315
-
316
- ### Dependency leak guard
317
-
318
- 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.
77
+ import { createPlugin } from 'pinia-plugin-subscription'
78
+ import { createTracerRegistry } from 'pinia-plugin-subscription/helpers'
319
79
 
320
- `npm run check:leaks` scans every built `.js` and `.d.ts` file and fails the build when a non-peer package appears:
80
+ const registry = createTracerRegistry({ redact: true })
81
+ registry.addListener([{ target: 'scope', value: 'cart' }])
321
82
 
322
- ```bash
323
- npm run check:leaks
83
+ pinia.use(createPlugin(subscribers, { tracerHandler: registry.tracerHandler }))
324
84
  ```
325
85
 
326
- 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/`.
86
+ See the [Tracing documentation](docs/tracing.md) for filtering, redaction, production safety, event shape and error reporting.
327
87
 
328
88
  ## License
329
89
 
package/SECURITY.md CHANGED
@@ -38,22 +38,22 @@ When using pinia-plugin-subscription:
38
38
 
39
39
  ### Tracing and Production Logging
40
40
 
41
- Normal trace events are opt-in: the plugin requires an explicitly configured `createTracer` factory and matching listeners to deliver them. The plugin does not automatically detect production environments or block tracing in production. Production tracing can be useful for incident diagnosis, but should only be enabled deliberately and with controlled access to its output.
41
+ Normal trace events are opt-in: the plugin requires an explicitly configured `tracerHandler` and matching listeners to deliver them. `createTracerRegistry()` ignores `addListener()` in production builds (`process.env.NODE_ENV === 'production'`) unless `createTracerRegistry({ enabled: true })` is passed. This guard relies on the consuming bundler replacing `process.env.NODE_ENV`; without it, tracing is considered enabled. Production tracing can be useful for incident diagnosis, but should only be enabled deliberately and with controlled access to its output.
42
42
 
43
- Trace events are not automatically sanitized or redacted. Depending on the event, they may contain action arguments, store state, mutations, plugin options, subscriptions, or error details. These values can include application secrets or personal data. A listener can expose them through the browser console, server logs, or an external logging service. The absence of a production block is not, by itself, a vulnerability; the disclosure risk depends on the data emitted, the logging destination, and who can access it.
43
+ Trace events are not redacted by default. Depending on the event, they may contain action arguments, store state, mutations, plugin options, subscriptions, or error details. These values can include application secrets or personal data. `createTracerRegistry({ redact: true })` masks values stored under sensitive keys (passwords, tokens, secrets, authorization, API keys, cookies...) before any listener receives them, but it inspects keys only: it does not detect secrets under innocuous keys, and it does not redact `event.error`. A listener can expose them through the browser console, server logs, or an external logging service. The absence of a production block is not, by itself, a vulnerability; the disclosure risk depends on the data emitted, the logging destination, and who can access it.
44
44
 
45
45
  When configuring tracing:
46
46
 
47
- 1. **Disable Normal Tracing in Production by Default:** Use the application's environment configuration to omit `createTracer` or avoid registering normal trace listeners. Enable production diagnostics only when needed and limit their duration and scope.
48
- 2. **Minimize Logged Data:** Select an explicit allowlist of fields and redact sensitive values before writing or forwarding events. Avoid logging complete stores, action arguments, plugin options, or raw error objects.
49
- 3. **Do Not Treat Filters as Redaction:** Filters only select events using metadata; a matching handler receives the full event, including its resolved payload and error. Sanitize data in the handler before passing it to a logging destination.
47
+ 1. **Keep Normal Tracing Disabled in Production:** This is the default of `createTracerRegistry()`. Only pass `enabled: true` when diagnostics are needed, and limit their duration and scope.
48
+ 2. **Minimize Logged Data:** Enable `createTracerRegistry({ redact: true })` (extend it with your own `keys`) and select an explicit allowlist of fields before writing or forwarding events. Avoid logging complete stores, action arguments, plugin options, or raw error objects.
49
+ 3. **Do Not Treat Filters as Redaction:** Filters only select events using metadata; a matching handler receives the full event, including its resolved payload and error. Use the `redact` option, and sanitize `event.error` and any remaining data in the handler before passing it to a logging destination.
50
50
  4. **Protect Logging Destinations:** Review external logging services, restrict access to logs, and define appropriate retention periods. Do not assume browser console output or server logs are private.
51
51
 
52
52
  **Error reporting is separate from normal tracing.** Without a tracer, plugin and store error reporting falls back to `console.error`. With a tracer, error events also fall back to `console.error` when no listener matches, including when all filters reject the event. Exceptions thrown by listener filters or handlers are reported to `console.error` as well. Removing listeners, clearing a registry, or omitting `createTracer` therefore does not guarantee that no errors will be logged.
53
53
 
54
54
  For production, handle error events with a matching listener that reports only sanitized details, and ensure listener filters and handlers do not throw sensitive errors. Review the application's console and error logging policy as well; do not silently discard operational errors to prevent disclosure.
55
55
 
56
- See [Tracing](./README.md#tracing) for configuration and event details.
56
+ See [Tracing](./docs/tracing.md) for configuration and event details.
57
57
 
58
58
  ## Dependencies Security
59
59