pinia-plugin-subscription 1.0.0-beta.13 → 1.0.0-beta.15

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 (47) hide show
  1. package/CHANGELOG.md +29 -12
  2. package/CONTRIBUTING.md +10 -1
  3. package/README.md +11 -9
  4. package/SECURITY.md +2 -2
  5. package/dist/chunks/{PluginSubscription-Bkqj4uSK.js → PluginSubscription-GJDsym1O.js} +253 -247
  6. package/dist/core/PluginSubscriber.d.ts +1 -1
  7. package/dist/core/PluginSubscription.d.ts +13 -12
  8. package/dist/core/Store.d.ts +1 -1
  9. package/dist/helpers/index.d.ts +0 -4
  10. package/dist/helpers.js +56 -651
  11. package/dist/pinia-plugin-subscription.js +4 -5
  12. package/dist/system/TraceEmitter.d.ts +1 -2
  13. package/dist/types/index.d.ts +1 -2
  14. package/dist/types/plugin.d.ts +2 -3
  15. package/dist/types/trace.d.ts +30 -109
  16. package/dist/utils/traceGroups.d.ts +9 -7
  17. package/docs/authoring-plugins.md +13 -7
  18. package/docs/using-plugins.md +28 -19
  19. package/package.json +9 -4
  20. package/dist/chunks/PluginSubscription-Bkqj4uSK.js.map +0 -1
  21. package/dist/factories/console-trace-listener.d.ts +0 -7
  22. package/dist/factories/trace-listener.d.ts +0 -10
  23. package/dist/factories/trace-registry.d.ts +0 -2
  24. package/dist/helpers.js.map +0 -1
  25. package/dist/pinia-plugin-subscription.js.map +0 -1
  26. package/dist/system/Tracer.d.ts +0 -23
  27. package/dist/system/log/console-group.d.ts +0 -8
  28. package/dist/system/log/console.d.ts +0 -18
  29. package/dist/system/log/index.d.ts +0 -2
  30. package/dist/system/log/log-trace.d.ts +0 -8
  31. package/dist/system/log/print-array.d.ts +0 -7
  32. package/dist/system/log/print-error.d.ts +0 -6
  33. package/dist/system/log/print-object.d.ts +0 -1
  34. package/dist/system/log/print-trace-payload.d.ts +0 -1
  35. package/dist/system/log/print-trace.d.ts +0 -9
  36. package/dist/system/log/trace-console.d.ts +0 -9
  37. package/dist/tests/defineAStore.test-d.d.ts +0 -1
  38. package/dist/tests/storeOptionsExtensions.test-d.d.ts +0 -12
  39. package/dist/types/comparison.d.ts +0 -3
  40. package/dist/types/list.d.ts +0 -13
  41. package/dist/types/log.d.ts +0 -8
  42. package/dist/types/resourceId.d.ts +0 -4
  43. package/dist/utils/Performance.d.ts +0 -9
  44. package/dist/utils/environment.d.ts +0 -7
  45. package/dist/utils/object.d.ts +0 -4
  46. package/dist/utils/redact.d.ts +0 -15
  47. package/docs/tracing.md +0 -185
@@ -1,15 +0,0 @@
1
- import type { AnyObject } from '../types';
2
- import type { TraceRedactOptions } from '../types/trace';
3
- export declare const DEFAULT_REDACTED_VALUE = "[REDACTED]";
4
- /**
5
- * Keys masked by default when redaction is enabled.
6
- * Matching is a case-insensitive "contains", so `accessToken` or `user_password` are masked too.
7
- */
8
- export declare const defaultRedactedKeys: readonly RegExp[];
9
- /**
10
- * Creates a function returning a redacted copy of a trace payload.
11
- * The original value (usually the live store state) is never mutated.
12
- * @param options Redaction options, or `true` to use the default keys.
13
- * @returns The redaction function.
14
- */
15
- export declare function createRedactor(options?: TraceRedactOptions | true): (payload: AnyObject) => AnyObject;
package/docs/tracing.md DELETED
@@ -1,185 +0,0 @@
1
- # Tracing
2
-
3
- Tracing is the debugging solution of `pinia-plugin-subscription`. It is **opt-in**, scoped to an explicit registry, and **allocation free when unused**.
4
-
5
- Create a trace-groups registry per application or Pinia instance, add criteria to select the events to group, then pass its `tracerHandler` to `createPlugin()` so plugin and store events share its groups.
6
-
7
- 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](./using-plugins.md#ssr--nuxt) for an example.
8
-
9
- ## Contents
10
-
11
- - [Quick start](#quick-start)
12
- - [Production safety](#production-safety)
13
- - [Redaction](#redaction)
14
- - [Filtering events](#filtering-events)
15
- - [Event shape](#event-shape)
16
- - [Emitting your own events](#emitting-your-own-events)
17
- - [Grouped console output](#grouped-console-output)
18
- - [Error reporting](#error-reporting)
19
- - [Migrating from `debugLog()` / `logError()`](#migrating-from-debuglog--logerror)
20
-
21
- ## Quick start
22
-
23
- ```ts
24
- import { createPlugin } from 'pinia-plugin-subscription'
25
- import { createTracerRegistry } from 'pinia-plugin-subscription/helpers'
26
-
27
- const traceGroupsRegistry = createTracerRegistry()
28
- const remove = traceGroupsRegistry.addListener([
29
- { target: 'scope', value: 'cart' },
30
- { target: 'namespace', comparator: 'startsWith', value: 'pluginsubscription:subscription:' }
31
- ])
32
-
33
- pinia.use(createPlugin(subscribers, {
34
- tracerHandler: traceGroupsRegistry.tracerHandler
35
- }))
36
-
37
- remove() // unsubscribe
38
- ```
39
-
40
- `createTracerRegistry(options?)` accepts:
41
-
42
- | Option | Description |
43
- | --- | --- |
44
- | `enabled` | Whether listeners can be registered. Defaults to `false` in production builds, `true` otherwise. See [Production safety](#production-safety). |
45
- | `redact` | Masks sensitive payload values before they reach listeners. `true` uses the default keys; an object customizes them. See [Redaction](#redaction). |
46
-
47
- ## Production safety
48
-
49
- Tracing is **disabled by default in production builds**: `createTracerRegistry()` ignores `addListener()` when `process.env.NODE_ENV === 'production'` (statically replaced by Vite, webpack and Nuxt in the consuming application), so no listener — and therefore no console output — is active. Pass `createTracerRegistry({ enabled: true })` to enable production diagnostics deliberately, with limited scope and duration; `enabled: false` forces tracing off in any environment. When no bundler replaces `process.env.NODE_ENV`, tracing is considered enabled.
50
-
51
- Events are **not redacted by default** and may include sensitive action arguments, store state, plugin options, or error details. Filters select events by metadata; they do not sanitize payloads. Enable the built-in [redaction](#redaction) and, before writing to a console or forwarding to a logging service, select an allowlist of fields rather than sending complete events.
52
-
53
- **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.
54
-
55
- ## Redaction
56
-
57
- Pass `redact` to `createTracerRegistry()` to mask sensitive values in event payloads **before** they reach any listener, including custom ones:
58
-
59
- ```ts
60
- const registry = createTracerRegistry({ redact: true }) // default keys
61
-
62
- const custom = createTracerRegistry({
63
- redact: {
64
- keys: ['iban', /^ssn/i], // added to the defaults: strings match exactly (case-insensitive), regexps match anywhere in the key
65
- includeDefaults: true, // set to false to use only `keys`
66
- replacement: '***' // default: '[REDACTED]'
67
- }
68
- })
69
- ```
70
-
71
- The default keys (`defaultRedactedKeys`, exported from `pinia-plugin-subscription/helpers`) match, case-insensitively, any key containing `password`/`passwd`/`passphrase`/`passcode`, `secret`, `token`, `authorization`, `api key`, `private/encryption/signing key`, `credential`, `cookie` or `cipher`, or starting with `pwd`. Keys are masked at any depth, including inside arrays, `Map` and `Set`; circular references are handled. Redaction works on a copy, so the live store state is never modified, and it only runs when a listener consumes the event. If redaction itself fails, the payload is replaced by `{ __traceRedactionError }` rather than delivered raw.
72
-
73
- Limits: only keys are inspected, not values (a secret stored under an innocuous key is not detected), `event.error` is not redacted, and nesting deeper than 12 levels is truncated.
74
-
75
- ## Filtering events
76
-
77
- Criteria are evaluated against event metadata, before the payload is resolved. They can target the `source`, `namespace`, `scope` or `level` of an event.
78
-
79
- By default, all criteria must match and events are grouped by `scope`. Supported comparators are `equals` (the default), `contains`, `startsWith` and `endsWith`; set `filterMode` to `some` to match any criterion, or `groupBy` to group by a different event metadata field:
80
-
81
- ```ts
82
- traceGroupsRegistry.addListener([
83
- { target: 'scope', value: 'cart' },
84
- { target: 'namespace', comparator: 'startsWith', value: 'pluginsubscription:subscription:' }
85
- ], { filterMode: 'every', groupBy: 'scope' })
86
- ```
87
-
88
- Listener definitions passed to `addListener()` are never mutated.
89
-
90
- Trace filters, including custom filters used when starting or closing groups, receive event metadata only. They never receive payloads or error objects. The built-in registry also avoids resolving group payload factories when it has no registered listeners; custom `TracerHandler` implementations may expose the optional `hasTraceListeners()` capability to enable the same optimization.
91
-
92
- For the common case of selecting several store scopes, use `addScopesListener(scopes, context?)`. It registers one listener that matches events whose `scope` equals **any** of the supplied strings, groups them by scope, and returns a remover just like `addListener()`. The optional `context` flag controls whether the plugin context is printed and defaults to `true`:
93
-
94
- ```ts
95
- const removeStoreListeners = traceGroupsRegistry.addScopesListener(
96
- ['cart', 'checkout'],
97
- false
98
- )
99
-
100
- removeStoreListeners() // unsubscribe
101
- ```
102
-
103
- Use `addListener()` when you need other metadata criteria, a different grouping field, or custom filter logic.
104
-
105
- ## Event shape
106
-
107
- | Field | Description |
108
- | --- | --- |
109
- | `namespace` | Structured identifier, derived from the label by default |
110
- | `label` | Human-readable event label |
111
- | `source` | Source passed to `createTracer`, usually `pinia-plugin-subscription` |
112
- | `scope` | Instance identifier, usually `store.$id` |
113
- | `payload` | Event data, resolved only when consumed |
114
- | `level` | `debug` or `error` |
115
- | `timestamp` | `Date.now()` at emission |
116
- | `error` | Present on `error` events |
117
-
118
- By default, `Store` prefixes its class name to labels and derived namespaces. Library events use `PluginSubscription` as their prefix (for example, `pluginsubscription:store:mutation` and `pluginsubscription:subscription:delivery`). Set `classNameAddedToTraceNamespace = false` on a `Store` subclass to omit its class prefix, or provide an explicit namespace as the fourth argument to `trace()` / `traceError()`.
119
-
120
- ## Trace groups glossary
121
-
122
- Events emitted within the same hook for the same store share a `groupId`. The `traceGroups` helper, exported from `pinia-plugin-subscription/helpers`, builds these identifiers from a store ID:
123
-
124
- | Builder | `groupId` | Hook |
125
- | --- | --- | --- |
126
- | `traceGroups.onActionAfter(id)` | `store:onAction:after:<id>` | `$onAction` `after` |
127
- | `traceGroups.onActionError(id)` | `store:onAction:onError:<id>` | `$onAction` `onError` |
128
- | `traceGroups.onMutation(id)` | `store:onMutation:<id>` | `$subscribe` |
129
- | `traceGroups.reset(id)` | `store:reset:<id>` | `$reset` |
130
-
131
- ```ts
132
- import { traceGroups } from 'pinia-plugin-subscription/helpers'
133
-
134
- registry.addListener([{ target: 'groupId', value: traceGroups.onActionAfter('cart') }])
135
- ```
136
-
137
- The plugin's action trace labels include the invoked action name (`store:onAction:<name>`). The `after` and `onError` callback trace labels also include that name, making activity from different actions distinguishable; their group IDs remain scoped to the store as shown above.
138
-
139
- Subscribers declared with `hydration: 'defer'` run after `plugin()` has closed its `PluginSubscription:context` group. Each deferred run opens its own group (label `subscriber:deferred`, no `groupId`, so it is keyed by the store scope like the `context` group); traces emitted by the subscriber during that run, such as those of a `Store` subclass, are printed inside it. The group stays open until asynchronous `hydrate()` / `afterHydration()` promises settle (fulfilled or rejected). While it is open, console listeners buffer every trace of that store scope, so a promise that never settles would hide them: after `deferredTraceGroupTimeout` milliseconds (plugin option, default `2500`) the group is closed anyway and a `subscriber:deferred:timeout` error is traced inside it.
140
-
141
- ## Emitting your own events
142
-
143
- ```ts
144
- class CartStore extends Store {
145
- hydrate() {
146
- this.trace('cart:hydrate', this.store.$id, () => ({ items: this.state.items }))
147
- }
148
- }
149
- ```
150
-
151
- `trace(label, scope?, payload?, namespace?)` and `traceError(label, error, scope?, payload?, namespace?)` are provided by the abstract `TraceEmitter` class, shared by `Store` and `PluginSubscription`. The scope defaults to the store ID for `Store`. The class name is included in the label by default; unless an explicit namespace is provided, the normalized label is used as the namespace.
152
-
153
- Always prefer the **function form** for `payload`: it is only invoked once a listener matches, so unobserved tracing costs nothing.
154
-
155
- Trace groups opened by `onAction`, `$subscribe` and `$reset` are always closed, including when the action fails or a callback throws.
156
-
157
- ## Grouped console output
158
-
159
- Normal trace events do not write to a console. The registry created by `createTracerRegistry()` uses the console's grouped output for the events matching its listeners: register listeners as shown in the [quick start](#quick-start) and pass `tracerHandler` to the plugin. Groups default to the `scope` metadata field; use the `groupBy` option of `addListener()` to group by another field.
160
-
161
- When an event has a `payload.groupId`, that value takes precedence over the configured `groupBy` field as its console-group key. Events without an open group for their key are printed immediately outside a group. If multiple groups with the same key are opened concurrently, their events share one buffer; the buffered group is printed only after every matching open has been closed.
162
-
163
- `CustomConsole` remains exported from `pinia-plugin-subscription/helpers` for plugins not yet migrated to the tracer.
164
-
165
- ## Error reporting
166
-
167
- 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.
168
-
169
- `registry.clearTraceListeners()` empties the shared listener list in place: tracers created earlier stop delivering to the cleared listeners and see listeners registered afterwards.
170
-
171
- ## Migrating from `debugLog()` / `logError()`
172
-
173
- These methods were removed in favour of structured events:
174
-
175
- ```ts
176
- // before
177
- this.debugLog(`$subscribe ${store.$id}`, { mutation, store })
178
- this.logError('subscriptionDelivery()', error, store, options)
179
-
180
- // after
181
- this.trace('store:mutation', store.$id, () => ({ mutation, store }))
182
- this.traceError('subscription:delivery', error, store.$id, () => ({ store, options }))
183
- ```
184
-
185
- The `namespace` replaces the formatted message, and the payload becomes a factory so it is only built when a listener consumes the event.