|
| 1 | +import { addBreadcrumb, getClient, getCurrentScope, getGlobalScope } from '@sentry/core'; |
| 2 | +import { addNonEnumerableProperty } from '@sentry/utils'; |
| 3 | + |
| 4 | +// Inline PiniaPlugin type |
| 5 | +type PiniaPlugin = (context: { |
| 6 | + store: { |
| 7 | + $state: unknown; |
| 8 | + $onAction: (callback: (context: { name: string; after: (callback: () => void) => void }) => void) => void; |
| 9 | + }; |
| 10 | +}) => void; |
| 11 | + |
| 12 | +type SentryPiniaPluginOptions = { |
| 13 | + attachPiniaState?: boolean; |
| 14 | + actionTransformer: (action: any) => any; |
| 15 | + stateTransformer: (state: any) => any; |
| 16 | +}; |
| 17 | + |
| 18 | +export const createSentryPiniaPlugin: (options?: SentryPiniaPluginOptions) => PiniaPlugin = ( |
| 19 | + options: SentryPiniaPluginOptions = { |
| 20 | + attachPiniaState: true, |
| 21 | + actionTransformer: action => action, |
| 22 | + stateTransformer: state => state, |
| 23 | + }, |
| 24 | +) => { |
| 25 | + const plugin: PiniaPlugin = ({ store }) => { |
| 26 | + options.attachPiniaState && |
| 27 | + getGlobalScope().addEventProcessor((event, hint) => { |
| 28 | + try { |
| 29 | + hint.attachments = [ |
| 30 | + ...(hint.attachments || []), |
| 31 | + { |
| 32 | + filename: 'pinia_state.json', |
| 33 | + data: JSON.stringify(store.$state), |
| 34 | + }, |
| 35 | + ]; |
| 36 | + } catch (_) { |
| 37 | + // empty |
| 38 | + } |
| 39 | + |
| 40 | + return event; |
| 41 | + }); |
| 42 | + |
| 43 | + store.$onAction(context => { |
| 44 | + context.after(() => { |
| 45 | + const transformedAction = options.actionTransformer(context.name); |
| 46 | + |
| 47 | + if (typeof transformedAction !== 'undefined' && transformedAction !== null) { |
| 48 | + addBreadcrumb({ |
| 49 | + category: 'action', |
| 50 | + message: transformedAction, |
| 51 | + level: 'info', |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + /* Set latest state to scope */ |
| 56 | + const transformedState = options.stateTransformer(store.$state); |
| 57 | + const scope = getCurrentScope(); |
| 58 | + |
| 59 | + if (typeof transformedState !== 'undefined' && transformedState !== null) { |
| 60 | + const client = getClient(); |
| 61 | + const options = client && client.getOptions(); |
| 62 | + const normalizationDepth = (options && options.normalizeDepth) || 3; // default state normalization depth to 3 |
| 63 | + |
| 64 | + const newStateContext = { state: { type: 'pinia', value: transformedState } }; |
| 65 | + |
| 66 | + addNonEnumerableProperty( |
| 67 | + newStateContext, |
| 68 | + '__sentry_override_normalization_depth__', |
| 69 | + 3 + // 3 layers for `state.value.transformedState |
| 70 | + normalizationDepth, // rest for the actual state |
| 71 | + ); |
| 72 | + |
| 73 | + scope.setContext('state', newStateContext); |
| 74 | + } else { |
| 75 | + scope.setContext('state', null); |
| 76 | + } |
| 77 | + }); |
| 78 | + }); |
| 79 | + }; |
| 80 | + |
| 81 | + return plugin; |
| 82 | +}; |
0 commit comments