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

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.
@@ -1 +1 @@
1
- {"version":3,"file":"pinia-plugin-subscription.js","sources":["../src/utils/deep-clone.ts","../src/factories/state-snapshot.ts","../src/core/RollbackStateSnapshotsHandler.ts","../src/core/PluginSubscription.ts"],"sourcesContent":["/**\n * Deeply clones the provided value, handling objects, arrays, maps, and sets. Uses `structuredClone` if available, otherwise falls back to a manual deep clone.\n * @template T The type of the value to deep clone.\n * @param value The value to deep clone.\n * @returns A deep clone of the provided value.\n */\nexport function deepClone<T>(value: T): T {\n if (typeof structuredClone === 'function') {\n try {\n return structuredClone(value)\n } catch {\n // fall through to the safe manual clone below\n }\n }\n\n if (value === null || typeof value !== 'object') {\n return value\n }\n\n if (value instanceof Map) {\n return new Map(\n Array.from(value.entries(), ([key, entryValue]) => [deepClone(key), deepClone(entryValue)])\n ) as T\n }\n\n if (value instanceof Set) {\n return new Set(Array.from(value.values(), entryValue => deepClone(entryValue))) as T\n }\n\n if (Array.isArray(value)) {\n return value.map(item => deepClone(item)) as T\n }\n\n if (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, deepClone(item)])\n ) as T\n }\n\n const clonedObject = Object.create(Object.getPrototypeOf(value)) as Record<string, unknown>\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n clonedObject[key] = deepClone(item)\n }\n\n return clonedObject as T\n}","import { toRaw } from 'vue'\nimport { deepClone } from '../utils/deep-clone'\n\nimport type { StateTree } from 'pinia'\nimport type { CreateStateSnapshotKeys } from '../types/plugin'\n\n\nexport function createStateSnapshot(state: StateTree, keys: CreateStateSnapshotKeys = 'all') {\n if (Array.isArray(keys)) {\n const clonedState: Partial<StateTree> = {}\n for (const key of keys) {\n if (key in state) {\n clonedState[key] = deepClone(toRaw(state[key]))\n }\n }\n return clonedState\n }\n\n if (keys !== 'all') {\n throw new Error(`Invalid keys parameter: ${keys}`)\n }\n\n return deepClone(toRaw(state))\n}","import { createStateSnapshot } from \"../factories/state-snapshot\"\nimport { getActionStoreKey, hasDeniedFirstChar } from '../utils/store'\n\nimport type { PiniaPluginContext, StateTree, Store } from 'pinia'\nimport type { AnyObject } from '../types'\nimport type { CreateStateSnapshotKeys } from '../types/plugin'\nimport type { RollbackActionParams } from '../types/store'\n\n\n/**\n * Handles rollback state snapshots for Pinia stores.\n * This class provides methods to add rollback actions to stores,\n * create rollback snapshots, and manage the state snapshots internally.\n */\nexport default class RollbackStateSnapshotsHandler {\n private _stateSnapshots: Map<symbol, StateTree> = new Map()\n private _storeHasRollbackSnapshots: Set<string> = new Set()\n private _storeRollbackSnapshotsParams: Map<string, CreateStateSnapshotKeys> = new Map()\n\n\n /**\n * Adds a rollback action to the given store.\n * This method extends the store with a $rollbackAfterFailure function that handles rollback logic for actions.\n * The action arguments are forwarded through apply(), so they must be provided as a single array.\n * @param {Store} store The store to which the rollback action will be added.\n * @returns void\n */\n addRollbackAction(store: Store): void {\n if (typeof store.$rollbackAfterFailure === 'function') {\n return\n }\n\n store.$rollbackAfterFailure = async ({ action, stateKeys }: RollbackActionParams, args: any[] = []) => {\n const actionFn = (store as AnyObject)[action]\n if (typeof actionFn !== 'function' || hasDeniedFirstChar(action)) {\n return\n }\n\n const keys: CreateStateSnapshotKeys = !stateKeys || stateKeys.length === 0 ? 'all' : stateKeys\n\n const snapshotKey = this.saveStateSnapshot(store, action, keys)\n try {\n await actionFn.apply(store, args)\n } catch (error) {\n this.patchStore(snapshotKey, store)\n throw error\n } finally {\n this.removeStateSnapshot(snapshotKey)\n }\n }\n }\n\n /**\n * Creates a rollback snapshot for the specified action and store.\n * This snapshot can be used to restore the store's state in case of an error during the action execution.\n * @param {string} actionName The name of the action for which the rollback snapshot is created.\n * @param {Store} store The Pinia store instance.\n * @returns An object containing `after` and `onError` callbacks for handling the rollback, or `undefined` if no snapshot is created.\n */\n createOnActionCallbacks(\n actionName: string,\n store: Store\n ): {\n after: () => void,\n onError: () => void\n } | undefined {\n const stateKeys = this._storeRollbackSnapshotsParams.get(\n getActionStoreKey(actionName, store)\n )\n\n if (!stateKeys || stateKeys.length === 0) {\n return\n }\n\n const snapshotKey = this.saveStateSnapshot(store, actionName, stateKeys)\n\n return {\n after: () => { this.removeStateSnapshot(snapshotKey) },\n onError: () => {\n this.patchStore(snapshotKey, store)\n this.removeStateSnapshot(snapshotKey)\n }\n }\n }\n\n /**\n * Initializes the rollback state snapshots handler from the given Pinia plugin context.\n * This method extracts the rollback snapshot parameters from the store options and stores them internally.\n * @param {PiniaPluginContext} param0 The Pinia plugin context containing the store and its options.\n * @returns void\n */\n initFromPluginContext({ options, store }: PiniaPluginContext) {\n const rollbackSnapshotParams = options?.storeOptions?.rollbackAfterFailure as Record<string, CreateStateSnapshotKeys>\n if (rollbackSnapshotParams && !this._storeHasRollbackSnapshots.has(store.$id)) {\n Object.keys(rollbackSnapshotParams).forEach(key => {\n this._storeRollbackSnapshotsParams.set(\n getActionStoreKey(key, store),\n rollbackSnapshotParams[key]\n )\n })\n this._storeHasRollbackSnapshots.add(store.$id)\n }\n this.addRollbackAction(store)\n }\n\n /**\n * Clears all rollback tracking data for the given store.\n * Must be called when the store is disposed to avoid memory leaks with dynamically created stores.\n * @param {Store} store The disposed Pinia store instance.\n * @returns void\n */\n clearStoreTracking(store: Store): void {\n const suffix = `-${store.$id}`\n\n for (const key of Array.from(this._storeRollbackSnapshotsParams.keys())) {\n if (key.endsWith(suffix)) {\n this._storeRollbackSnapshotsParams.delete(key)\n }\n }\n\n this._storeHasRollbackSnapshots.delete(store.$id)\n\n for (const snapshotKey of Array.from(this._stateSnapshots.keys())) {\n if (snapshotKey.description?.startsWith(`${store.$id}:`)) {\n this._stateSnapshots.delete(snapshotKey)\n }\n }\n }\n\n private patchStore(snapshotKey: symbol, store: Store): void {\n const stateSnapshot = this._stateSnapshots.get(snapshotKey)\n if (!stateSnapshot) {\n return\n }\n\n try {\n store.$patch(stateSnapshot)\n } catch (error) {\n console.error(`Failed to patch store with snapshot ${String(snapshotKey)}`, error)\n }\n }\n\n /**\n * Removes a state snapshot identified by the given snapshot key from the internal state snapshot tracking.\n * @param snapshotKey The key of the state snapshot to be removed.\n * @returns void\n */\n private removeStateSnapshot(snapshotKey?: symbol): void {\n if (!snapshotKey) {\n return\n }\n\n this._stateSnapshots.delete(snapshotKey)\n }\n\n /**\n * Saves the current state snapshot for a given store and action.\n * @param store The Pinia store instance.\n * @param actionName The name of the action being executed.\n * @param stateKeys The state keys to include in the snapshot, or 'all' for the full state.\n * @returns A unique symbol key representing the saved snapshot.\n */\n private saveStateSnapshot(store: Store, actionName: string, stateKeys: CreateStateSnapshotKeys): symbol {\n const stateSnapshot = createStateSnapshot(\n store.$state,\n stateKeys\n )\n\n const snapshotKey = Symbol(`${store.$id}:${actionName}`)\n this._stateSnapshots.set(snapshotKey, stateSnapshot)\n return snapshotKey\n }\n\n /**\n * Checks if the given store has rollback snapshots.\n * @param store The Pinia store instance.\n * @returns True if the store has rollback snapshots, false otherwise.\n */\n storeHasRollbackSnapshots(store: Store): boolean {\n return this._storeHasRollbackSnapshots.has(store.$id)\n }\n}","import Debug from \"../system/Debug\"\nimport RollbackStateSnapshotsHandler from \"./RollbackStateSnapshotsHandler\"\nimport { deepClone } from '../utils/deep-clone'\nimport { getActionStoreKey } from '../utils/store'\nimport { PluginConsole } from \"../system/log\"\nimport { isEmpty } from \"../utils/validation\"\n\nimport type { PiniaPluginContext, StateTree, Store, SubscriptionCallbackMutation } from \"pinia\"\nimport type { AnyObject } from \"../types\"\nimport type {\n PluginExecutionOptions,\n PluginHydrationScheduler,\n PluginRuntimeEnvironment,\n PluginSubscriber,\n PluginSubscription as PluginSubscriptionDefinition,\n PluginSubscriptionOptions,\n PluginSubscriptions,\n StoreMutationSubscription,\n StoreOnActionAfterCallbackParameter,\n StoreOnActionSubscriptionCallback\n} from \"../types/plugin\"\n\n\nconst className = 'PluginSubscription'\nconst defaultPluginExecution: Required<PluginExecutionOptions> = {\n environment: 'both',\n hydration: 'immediate'\n}\n\nfunction defaultHydrationScheduler(callback: () => void): void {\n if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {\n window.requestAnimationFrame(() => globalThis.setTimeout(callback, 0))\n return\n }\n\n globalThis.setTimeout(callback, 0)\n}\n\nfunction isPluginSubscriptionOptions(\n value: PluginSubscriptionOptions | string[] | undefined\n): value is PluginSubscriptionOptions {\n return value !== undefined && !Array.isArray(value)\n}\n\n\nexport default class PluginSubscription extends Debug {\n protected _className: string = className\n private _hydrationScheduler: PluginHydrationScheduler\n private _onActionSubscriptions: StoreOnActionSubscriptionCallback[] = []\n private _onActionAfterSubscriptions: Record<string, StoreOnActionAfterCallbackParameter[]> = {}\n private _onActionOnErrorSubscriptions: Record<string, Array<(error: unknown) => void>> = {}\n private _options?: PluginSubscriptionOptions\n private _pluginDebug?: string[]\n private _resetStoreCallback: Function[] = []\n private _storeRollbackSnapshotsHandler: RollbackStateSnapshotsHandler = new RollbackStateSnapshotsHandler()\n private _subscribers: PluginSubscriber[] = []\n private _subscribersDelivered: Set<string> = new Set()\n private _subscribersScheduled: Set<string> = new Set()\n private _subscriptions: PluginSubscriptions[] = []\n private _subscriptionsDelivered: Set<string> = new Set()\n private _subscriptionsScheduled: Set<string> = new Set()\n\n set subscribers(subscribers: PluginSubscriber[]) {\n this._subscribers = subscribers\n }\n\n get subscriptions(): PluginSubscriptions[] | undefined {\n if (!isEmpty(this._subscriptions)) {\n return this._subscriptions\n }\n }\n\n constructor(\n subscribers: PluginSubscriber[],\n debugOrOptions?: PluginSubscriptionOptions | string[],\n pluginOptions?: PluginSubscriptionOptions\n ) {\n const debug = Array.isArray(debugOrOptions) ? debugOrOptions : undefined\n const options = isPluginSubscriptionOptions(debugOrOptions) ? debugOrOptions : pluginOptions\n\n super(Array.isArray(debug) && !!debug?.includes(className), PluginConsole)\n this._hydrationScheduler = options?.hydrationScheduler ?? defaultHydrationScheduler\n this._options = options\n this._pluginDebug = Array.isArray(debug) ? debug : undefined\n this._subscribers = subscribers\n }\n\n\n private addOnActionAfterCallback(actionName: string, store: Store, callback: StoreOnActionAfterCallbackParameter): void {\n const key = getActionStoreKey(actionName, store)\n if (!this._onActionAfterSubscriptions[key]) {\n this._onActionAfterSubscriptions[key] = []\n }\n this._onActionAfterSubscriptions[key]?.push(callback)\n }\n\n private addOnActionOnErrorCallback(actionName: string, store: Store, callback: (error: unknown) => void): void {\n const key = getActionStoreKey(actionName, store)\n if (!this._onActionOnErrorSubscriptions[key]) {\n this._onActionOnErrorSubscriptions[key] = []\n }\n this._onActionOnErrorSubscriptions[key]?.push(callback)\n }\n\n private addResetStoreCallback(callback: Function): void {\n this._resetStoreCallback.push(callback)\n }\n\n private clearOnActionCallbacksSubscriptions(storageKey: string): void {\n delete this._onActionAfterSubscriptions[storageKey]\n delete this._onActionOnErrorSubscriptions[storageKey]\n }\n\n private clearStoreTracking(store: Store): void {\n const suffix = `-${store.$id}`\n\n for (const key of Array.from(this._subscribersDelivered)) {\n if (key.endsWith(suffix)) {\n this._subscribersDelivered.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscribersScheduled)) {\n if (key.endsWith(suffix)) {\n this._subscribersScheduled.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscriptionsDelivered)) {\n if (key.endsWith(suffix)) {\n this._subscriptionsDelivered.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscriptionsScheduled)) {\n if (key.endsWith(suffix)) {\n this._subscriptionsScheduled.delete(key)\n }\n }\n\n for (const key of Object.keys(this._onActionAfterSubscriptions)) {\n if (key.endsWith(suffix)) {\n delete this._onActionAfterSubscriptions[key]\n }\n }\n\n for (const key of Object.keys(this._onActionOnErrorSubscriptions)) {\n if (key.endsWith(suffix)) {\n delete this._onActionOnErrorSubscriptions[key]\n }\n }\n }\n\n /**\n * Creates a callback collector for the specified action and store.\n * @param actionName The name of the action to collect callbacks for.\n * @param store The store instance associated with the action.\n * @returns A function that collects callbacks for the specified action and store.\n */\n private createOnActionAfterCallbackCollector(actionName: string, store: Store) {\n return (callback: StoreOnActionAfterCallbackParameter) => {\n this.addOnActionAfterCallback(actionName, store, callback)\n }\n }\n\n /**\n * Creates a callback collector for the specified action and store that handles errors.\n * @param actionName The name of the action to collect error callbacks for.\n * @param store The store instance associated with the action.\n * @returns A function that collects error callbacks for the specified action and store.\n */\n private createOnActionOnErrorCallbackCollector(actionName: string, store: Store) {\n return (callback: (error: unknown) => void) => {\n this.addOnActionOnErrorCallback(actionName, store, callback)\n }\n }\n\n /**\n * Rolls back the state snapshot for a given action if an error occurs, and removes the snapshot after the action completes or fails.\n * @param actionName The name of the action being executed.\n * @param store The Pinia store instance.\n * @returns void\n */\n private createRollbackSnapshot(\n actionName: string,\n store: Store\n ) {\n const {\n after,\n onError\n } = this._storeRollbackSnapshotsHandler.createOnActionCallbacks(\n actionName,\n store\n ) ?? {}\n\n if (!after || !onError) {\n return\n }\n\n this.addOnActionAfterCallback(actionName, store, after)\n this.addOnActionOnErrorCallback(actionName, store, onError)\n }\n\n private defineCurrentEnvironment(): PluginRuntimeEnvironment {\n return this._options?.runtimeEnvironment\n ?? (typeof window === 'undefined' ? 'server' : 'client')\n }\n\n private definePluginDebug(subscriber: PluginSubscriber): boolean {\n return !!this._pluginDebug?.includes(subscriber.name)\n }\n\n private definePluginExecution(subscriber: PluginSubscriber): Required<PluginExecutionOptions> {\n return {\n ...defaultPluginExecution,\n ...(this._options?.execution ?? {}),\n ...(subscriber.execution ?? {}),\n ...(this._options?.subscriberExecution?.[subscriber.name] ?? {}),\n }\n }\n\n private defineHydrationScheduler(subscriber: PluginSubscriber | PluginSubscriptionDefinition['subscription']): PluginHydrationScheduler {\n return subscriber.hydrationScheduler ?? this._hydrationScheduler\n }\n\n private defineSubscriberKey(subscriber: PluginSubscriber, store: Store): string {\n return `${subscriber.name}-${store.$id}`\n }\n\n private defineSubscriptionKey(pluginName: string, store: Store): string {\n return `${pluginName}-${store.$id}`\n }\n\n private executeResetStoreCallbacks(store: Store): void {\n this._resetStoreCallback.forEach(callback => callback(store))\n }\n\n /**\n * Executes the store's onAction subscription for the given plugin subscriber.\n * @param store The Pinia store instance.\n * @param subscriber The plugin subscriber.\n * @returns void\n */\n private executeStoreOnActionSubscription(store: Store): void {\n const onActionSubscriptions = this._onActionSubscriptions\n const hasRollbackSnapshots = this._storeRollbackSnapshotsHandler.storeHasRollbackSnapshots(store)\n\n if (!onActionSubscriptions?.length && !hasRollbackSnapshots) {\n return\n }\n\n store.$onAction(({ after, args, name, onError }) => {\n const storageKey = getActionStoreKey(name, store)\n this.debugLog(`storeOnActionSubscription ${storageKey}`, { args, name, store })\n\n if (hasRollbackSnapshots) {\n this.createRollbackSnapshot(name, store)\n }\n\n if (onActionSubscriptions?.length) {\n onActionSubscriptions.forEach(callback => callback({\n after: this.createOnActionAfterCallbackCollector(name, store),\n args,\n name,\n onError: this.createOnActionOnErrorCallbackCollector(name, store)\n }))\n }\n\n const afterCallbacks = this._onActionAfterSubscriptions[storageKey]\n const onErrorCallbacks = this._onActionOnErrorSubscriptions[storageKey]\n\n this.clearOnActionCallbacksSubscriptions(storageKey)\n\n if (afterCallbacks?.length) {\n after((result) => {\n afterCallbacks.forEach(callback => callback(result))\n })\n }\n if (onErrorCallbacks?.length) {\n onError((error) => {\n onErrorCallbacks.forEach(callback => callback(error))\n })\n }\n })\n }\n\n private executeSubscriber(context: PiniaPluginContext, subscriber: PluginSubscriber): void {\n const subscriberKey = this.defineSubscriberKey(subscriber, context.store)\n const debug = this.definePluginDebug(subscriber)\n\n if (this._subscribersDelivered.has(subscriberKey)) {\n return\n }\n\n if (\n !subscriber.invoke(\n context,\n debug\n )) {\n return\n }\n\n this._subscribersDelivered.add(subscriberKey)\n\n let hydrateResult: void | Promise<void>\n\n try {\n hydrateResult = subscriber.hydrate?.(context, debug)\n } catch (error) {\n this.logError(error, context.store, context.options)\n return\n }\n\n const runAfterHydration = () => {\n try {\n const afterHydration = subscriber.afterHydration?.(context, debug)\n if (afterHydration && typeof (afterHydration as Promise<void>).then === 'function') {\n ; (afterHydration as Promise<void>).catch(error => this.logError(error, context.store, context.options))\n }\n } catch (error) {\n this.logError(error, context.store, context.options)\n }\n }\n\n if (hydrateResult && typeof (hydrateResult as Promise<void>).then === 'function') {\n ; (hydrateResult as Promise<void>)\n .then(() => runAfterHydration())\n .catch(error => this.logError(error, context.store, context.options))\n } else {\n runAfterHydration()\n }\n\n if (subscriber.subscriptions) {\n this.subscriptionDelivery(context, subscriber.subscriptions)\n }\n\n if (subscriber.storeMutationSubscription) {\n this.storeMutationSubscription(subscriber.storeMutationSubscription)\n }\n\n this.storeOnActionSubscription(subscriber)\n\n if (subscriber.resetStoreCallback) {\n this.addResetStoreCallback(subscriber.resetStoreCallback)\n }\n }\n\n private executeSubscriberSafely(context: PiniaPluginContext, subscriber: PluginSubscriber): void {\n try {\n this.executeSubscriber(context, subscriber)\n } catch (e) {\n this.logError(e, context.store, context.options)\n }\n }\n\n plugin({ store, options }: PiniaPluginContext) {\n if (!this._subscribers.length) {\n return\n }\n\n this.debugLog(`plugin() - ${store.$id}`, [\n 'subscriber:', this._subscribers,\n 'store:', store,\n 'options:', options\n ])\n\n try {\n this._subscribers.forEach(\n subscriber => {\n const subscriberKey = this.defineSubscriberKey(subscriber, store)\n const execution = this.definePluginExecution(subscriber)\n\n if (\n this._subscribersDelivered.has(subscriberKey)\n || this._subscribersScheduled.has(subscriberKey)\n ) {\n return\n }\n\n if (!this.shouldInvokePlugin(execution)) {\n return\n }\n\n if (this.shouldScheduleAfterHydration(execution)) {\n this.queueSubscriberExecution({ store, options } as PiniaPluginContext, subscriber, subscriberKey)\n return\n }\n\n this.executeSubscriber({ store, options } as PiniaPluginContext, subscriber)\n }\n )\n\n this.rewriteResetStore({ store } as PiniaPluginContext, store.$state)\n this._storeRollbackSnapshotsHandler.initFromPluginContext({ store, options } as PiniaPluginContext)\n this.executeStoreOnActionSubscription(store)\n this.registerStoreCleanup(store)\n } catch (e) {\n this.logError(e, store, options)\n }\n }\n\n private queueSubscriberExecution(\n context: PiniaPluginContext,\n subscriber: PluginSubscriber,\n subscriberKey: string\n ): void {\n const scheduler = this.defineHydrationScheduler(subscriber)\n\n this._subscribersScheduled.add(subscriberKey)\n scheduler(() => {\n this._subscribersScheduled.delete(subscriberKey)\n this.executeSubscriberSafely(context, subscriber)\n })\n }\n\n private registerStoreCleanup(store: Store): void {\n this._onActionSubscriptions = []\n if (typeof store.$dispose !== 'function') {\n return\n }\n\n const dispose = store.$dispose.bind(store)\n const scopedStore = store as AnyObject\n\n if (scopedStore.__piniaPluginSubscriptionDisposed) {\n return\n }\n\n scopedStore.__piniaPluginSubscriptionDisposed = true\n store.$dispose = () => {\n this.clearStoreTracking(store)\n this._storeRollbackSnapshotsHandler.clearStoreTracking(store)\n return dispose()\n }\n }\n\n private rewriteResetStore({ store }: PiniaPluginContext, initState: StateTree): void {\n const safeState = deepClone(initState)\n\n store.$reset = () => {\n this.debugLog('rewriteResetStore()', { initState: safeState, store })\n\n this.executeResetStoreCallbacks(store)\n\n store.$patch(deepClone(safeState))\n }\n }\n\n private shouldInvokePlugin(execution: Required<PluginExecutionOptions>): boolean {\n const currentEnvironment = this.defineCurrentEnvironment()\n\n return execution.environment === 'both' || execution.environment === currentEnvironment\n }\n\n private shouldScheduleAfterHydration(execution: Required<PluginExecutionOptions>): boolean {\n return this.defineCurrentEnvironment() === 'client' && execution.hydration === 'defer'\n }\n\n private storeOnActionSubscription(subscriber: PluginSubscriber): void {\n const { store, callback } = subscriber?.storeOnActionSubscription?.() ?? {}\n\n if (!store || !callback) {\n return\n }\n\n this._onActionSubscriptions.push(callback)\n }\n\n private storeMutationSubscription(subscription: StoreMutationSubscription): void {\n const { store, callback } = subscription()\n\n store.$subscribe((mutation: SubscriptionCallbackMutation<StateTree>) => {\n this.debugLog(`$subscribe ${store.$id}`, { mutation, store })\n callback(mutation)\n })\n }\n\n private subscriptionDelivery(\n context: PiniaPluginContext,\n pluginSubscriptions: PluginSubscriptions\n ): void {\n Object.entries(pluginSubscriptions).forEach(([pluginName, pluginSubscription]) => {\n const subscriptionKey = this.defineSubscriptionKey(pluginName, context.store)\n const execution = this.definePluginExecution(pluginSubscription.subscription)\n\n if (\n this._subscriptionsDelivered.has(subscriptionKey)\n || this._subscriptionsScheduled.has(subscriptionKey)\n ) {\n return\n }\n\n if (!this.shouldInvokePlugin(execution)) {\n return\n }\n\n if (this.shouldScheduleAfterHydration(execution)) {\n const scheduler = this.defineHydrationScheduler(pluginSubscription.subscription)\n\n this._subscriptionsScheduled.add(subscriptionKey)\n scheduler(() => {\n this._subscriptionsScheduled.delete(subscriptionKey)\n this.subscriptionDeliverySafely(context, pluginName, pluginSubscription)\n })\n return\n }\n\n this.subscriptionDeliverySafely(context, pluginName, pluginSubscription)\n })\n }\n\n private subscriptionDeliverySafely(\n { store, options }: PiniaPluginContext,\n pluginName: string,\n pluginSubscription: PluginSubscriptionDefinition\n ): void {\n try {\n if (this._subscriptionsDelivered.has(this.defineSubscriptionKey(pluginName, store))) {\n return\n }\n\n const { subscription, subscriptionOptions, stores } = pluginSubscription\n\n this.debugLog(`subscriptionDelivery() - store: ${store.$id}`, [\n 'pluginName:', pluginName,\n 'subscription:', subscription,\n 'options:', pluginSubscription,\n 'stores:', stores\n ])\n\n const pluginOptions = {\n storeOptions: { ...((options as AnyObject)?.storeOptions ?? {}), ...subscriptionOptions }\n } as AnyObject\n\n subscription.invoke(\n { store, options: { ...options, ...pluginOptions } } as PiniaPluginContext,\n this.debug\n )\n this._subscriptionsDelivered.add(this.defineSubscriptionKey(pluginName, store))\n\n if (!isEmpty(stores)) {\n stores?.forEach(\n store => subscription.invoke(\n {\n store,\n options: {\n ...options,\n ...pluginOptions,\n ...((store as AnyObject)?.storeOptions ?? {})\n }\n } as PiniaPluginContext,\n this.debug\n )\n )\n }\n } catch (e) {\n this.logError(`subscriptionDelivery()`, e, store, options)\n }\n }\n}"],"names":["deepClone","value","key","entryValue","item","clonedObject","createStateSnapshot","state","keys","clonedState","toRaw","RollbackStateSnapshotsHandler","__publicField","store","action","stateKeys","args","actionFn","hasDeniedFirstChar","snapshotKey","error","actionName","getActionStoreKey","options","rollbackSnapshotParams","suffix","stateSnapshot","className","defaultPluginExecution","defaultHydrationScheduler","callback","isPluginSubscriptionOptions","PluginSubscription","Debug","subscribers","debugOrOptions","pluginOptions","debug","PluginConsole","storageKey","after","onError","subscriber","pluginName","onActionSubscriptions","hasRollbackSnapshots","name","afterCallbacks","onErrorCallbacks","result","context","subscriberKey","hydrateResult","runAfterHydration","afterHydration","e","execution","scheduler","dispose","scopedStore","initState","safeState","currentEnvironment","subscription","mutation","pluginSubscriptions","pluginSubscription","subscriptionKey","subscriptionOptions","stores","isEmpty","store2","createPlugin","createHydrationPlugin","hydrationPlugin"],"mappings":";;;;;;AAMO,SAASA,EAAaC,GAAa;AACtC,MAAI,OAAO,mBAAoB;AAC3B,QAAI;AACA,aAAO,gBAAgBA,CAAK;AAAA,IAChC,QAAQ;AAAA,IAER;AAGJ,MAAIA,MAAU,QAAQ,OAAOA,KAAU;AACnC,WAAOA;AAGX,MAAIA,aAAiB;AACjB,WAAO,IAAI;AAAA,MACP,MAAM,KAAKA,EAAM,QAAA,GAAW,CAAC,CAACC,GAAKC,CAAU,MAAM,CAACH,EAAUE,CAAG,GAAGF,EAAUG,CAAU,CAAC,CAAC;AAAA,IAAA;AAIlG,MAAIF,aAAiB;AACjB,WAAO,IAAI,IAAI,MAAM,KAAKA,EAAM,OAAA,GAAU,CAAAE,MAAcH,EAAUG,CAAU,CAAC,CAAC;AAGlF,MAAI,MAAM,QAAQF,CAAK;AACnB,WAAOA,EAAM,IAAI,CAAAG,MAAQJ,EAAUI,CAAI,CAAC;AAG5C,MAAI,OAAO,eAAeH,CAAK,MAAM,OAAO,aAAa,OAAO,eAAeA,CAAK,MAAM;AACtF,WAAO,O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G;AAAA,QAEQ;AAAA;MAGJ,CAAA;AACJ,YAAA9B,IAAA;AAAA,QAEQ,cAAA,EAAA,GAAAb,GAA6B,gBAAsD,CAAA,GAAA,GAAA6C,EAAA;AAAA,MACvF;AACJ,MAAAL,EAAA;AAAA,QAEQ,EAAA,OAAAlD,GAAA,SAAA,EAA0B,GAAAU,GAAoC,GAAAa,EAAA,EAAA;AAAA,QAClE,KAAQ;AAAA,SAGJ,KAAA,wBAAA,IAAA,KAAA,sBAAAO,GAAA9B,CAAA,CAAA,GACJyD,EAAAD,CAAA,KAEAA,GAAK;AAAA,QACT,CAAAE,MAAAR,EAAA;AAAA,UAEQ;AAAA,YACI;YAEF;cACG,GAAAxC;AAAA,cACI,GAAAa;AAAA,cACZ,GAAAmC,GAAA,gBAAA,CAAA;AAAA,YACL;AAAA,UAEQ;AAAA,UAIG,KAAA;AAAA,QACH;AAAA,MACA;AAAA,IAMI,SAAAhB,GAAA;AACJ,WAAA,SAAA,0BAAAA,GAAA1C,GAAAU,CAAA;AAAA,IAEA;AAAA,EACI;AAAA;AAIA,SAAAiD,EAAMtC;AAEN,QAAAgC,IAAK,IAAAlC,KAA2CK,CAAA;AAChD,SAAA6B,EAAgB,OAAA,KAAAA,CAAA;AACZ;AACuE,SAC1EO,EAAAvC,GAAAX,GAAA;AACD,QAAAmD,IAAA,IAAA1C,EAAAE,GAAAX,GAAA,OAAA;AAAA,IAAA,WACJA,GAAA;AAAA,IAEA,oBAAKA,GAAA;AAAA,IACT,oBAACA,GAAA;AAAA,IACL,qBAAAA,GAAA;AAAA,EAEQ,CAAA;AAKJ,SAAImD,EAAA,OAAA,KAAAA,CAAA;AACA;"}
1
+ {"version":3,"file":"pinia-plugin-subscription.js","sources":["../src/utils/deep-clone.ts","../src/factories/state-snapshot.ts","../src/core/RollbackStateSnapshotsHandler.ts","../src/core/PluginSubscription.ts"],"sourcesContent":["/**\n * Deeply clones the provided value, handling objects, arrays, maps, and sets. Uses `structuredClone` if available, otherwise falls back to a manual deep clone.\n * @template T The type of the value to deep clone.\n * @param value The value to deep clone.\n * @returns A deep clone of the provided value.\n */\nexport function deepClone<T>(value: T): T {\n if (typeof structuredClone === 'function') {\n try {\n return structuredClone(value)\n } catch {\n // fall through to the safe manual clone below\n }\n }\n\n if (value === null || typeof value !== 'object') {\n return value\n }\n\n if (value instanceof Map) {\n return new Map(\n Array.from(value.entries(), ([key, entryValue]) => [deepClone(key), deepClone(entryValue)])\n ) as T\n }\n\n if (value instanceof Set) {\n return new Set(Array.from(value.values(), entryValue => deepClone(entryValue))) as T\n }\n\n if (Array.isArray(value)) {\n return value.map(item => deepClone(item)) as T\n }\n\n if (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, deepClone(item)])\n ) as T\n }\n\n const clonedObject = Object.create(Object.getPrototypeOf(value)) as Record<string, unknown>\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n clonedObject[key] = deepClone(item)\n }\n\n return clonedObject as T\n}","import { toRaw } from 'vue'\nimport { deepClone } from '../utils/deep-clone'\n\nimport type { StateTree } from 'pinia'\nimport type { CreateStateSnapshotKeys } from '../types/plugin'\n\n\nexport function createStateSnapshot(state: StateTree, keys: CreateStateSnapshotKeys = 'all') {\n if (Array.isArray(keys)) {\n const clonedState: Partial<StateTree> = {}\n for (const key of keys) {\n if (key in state) {\n clonedState[key] = deepClone(toRaw(state[key]))\n }\n }\n return clonedState\n }\n\n if (keys !== 'all') {\n throw new Error(`Invalid keys parameter: ${keys}`)\n }\n\n return deepClone(toRaw(state))\n}","import { createStateSnapshot } from \"../factories/state-snapshot\"\nimport { getActionStoreKey, hasDeniedFirstChar } from '../utils/store'\n\nimport type { PiniaPluginContext, StateTree, Store } from 'pinia'\nimport type { AnyObject } from '../types'\nimport type { CreateStateSnapshotKeys } from '../types/plugin'\nimport type { RollbackActionParams } from '../types/store'\n\n\n/**\n * Handles rollback state snapshots for Pinia stores.\n * This class provides methods to add rollback actions to stores,\n * create rollback snapshots, and manage the state snapshots internally.\n */\nexport default class RollbackStateSnapshotsHandler {\n private _stateSnapshots: Map<symbol, StateTree> = new Map()\n private _storeHasRollbackSnapshots: Set<string> = new Set()\n private _storeRollbackSnapshotsParams: Map<string, CreateStateSnapshotKeys> = new Map()\n\n\n /**\n * Adds a rollback action to the given store.\n * This method extends the store with a $rollbackAfterFailure function that handles rollback logic for actions.\n * The action arguments are forwarded through apply(), so they must be provided as a single array.\n * @param {Store} store The store to which the rollback action will be added.\n * @returns void\n */\n addRollbackAction(store: Store): void {\n if (typeof store.$rollbackAfterFailure === 'function') {\n return\n }\n\n store.$rollbackAfterFailure = async ({ action, stateKeys }: RollbackActionParams, args: any[] = []) => {\n const actionFn = (store as AnyObject)[action]\n if (typeof actionFn !== 'function' || hasDeniedFirstChar(action)) {\n return\n }\n\n const keys: CreateStateSnapshotKeys = !stateKeys || stateKeys.length === 0 ? 'all' : stateKeys\n\n const snapshotKey = this.saveStateSnapshot(store, action, keys)\n try {\n await actionFn.apply(store, args)\n } catch (error) {\n this.patchStore(snapshotKey, store)\n throw error\n } finally {\n this.removeStateSnapshot(snapshotKey)\n }\n }\n }\n\n /**\n * Creates a rollback snapshot for the specified action and store.\n * This snapshot can be used to restore the store's state in case of an error during the action execution.\n * @param {string} actionName The name of the action for which the rollback snapshot is created.\n * @param {Store} store The Pinia store instance.\n * @returns An object containing `after` and `onError` callbacks for handling the rollback, or `undefined` if no snapshot is created.\n */\n createOnActionCallbacks(\n actionName: string,\n store: Store\n ): {\n after: () => void,\n onError: () => void\n } | undefined {\n const stateKeys = this._storeRollbackSnapshotsParams.get(\n getActionStoreKey(actionName, store)\n )\n\n if (!stateKeys) {\n return\n }\n\n const keys: CreateStateSnapshotKeys = stateKeys.length === 0 ? 'all' : stateKeys\n const snapshotKey = this.saveStateSnapshot(store, actionName, keys)\n\n return {\n after: () => { this.removeStateSnapshot(snapshotKey) },\n onError: () => {\n this.patchStore(snapshotKey, store)\n this.removeStateSnapshot(snapshotKey)\n }\n }\n }\n\n /**\n * Initializes the rollback state snapshots handler from the given Pinia plugin context.\n * This method extracts the rollback snapshot parameters from the store options and stores them internally.\n * @param {PiniaPluginContext} param0 The Pinia plugin context containing the store and its options.\n * @returns void\n */\n initFromPluginContext({ options, store }: PiniaPluginContext) {\n const rollbackSnapshotParams = options?.storeOptions?.rollbackAfterFailure as Record<string, CreateStateSnapshotKeys>\n if (rollbackSnapshotParams && !this._storeHasRollbackSnapshots.has(store.$id)) {\n Object.keys(rollbackSnapshotParams).forEach(key => {\n this._storeRollbackSnapshotsParams.set(\n getActionStoreKey(key, store),\n rollbackSnapshotParams[key]\n )\n })\n this._storeHasRollbackSnapshots.add(store.$id)\n }\n this.addRollbackAction(store)\n }\n\n /**\n * Clears all rollback tracking data for the given store.\n * Must be called when the store is disposed to avoid memory leaks with dynamically created stores.\n * @param {Store} store The disposed Pinia store instance.\n * @returns void\n */\n clearStoreTracking(store: Store): void {\n const suffix = `-${store.$id}`\n\n for (const key of Array.from(this._storeRollbackSnapshotsParams.keys())) {\n if (key.endsWith(suffix)) {\n this._storeRollbackSnapshotsParams.delete(key)\n }\n }\n\n this._storeHasRollbackSnapshots.delete(store.$id)\n\n for (const snapshotKey of Array.from(this._stateSnapshots.keys())) {\n if (snapshotKey.description?.startsWith(`${store.$id}:`)) {\n this._stateSnapshots.delete(snapshotKey)\n }\n }\n }\n\n private patchStore(snapshotKey: symbol, store: Store): void {\n const stateSnapshot = this._stateSnapshots.get(snapshotKey)\n if (!stateSnapshot) {\n return\n }\n\n try {\n store.$patch(stateSnapshot)\n } catch (error) {\n console.error(`Failed to patch store with snapshot ${String(snapshotKey)}`, error)\n }\n }\n\n /**\n * Removes a state snapshot identified by the given snapshot key from the internal state snapshot tracking.\n * @param snapshotKey The key of the state snapshot to be removed.\n * @returns void\n */\n private removeStateSnapshot(snapshotKey?: symbol): void {\n if (!snapshotKey) {\n return\n }\n\n this._stateSnapshots.delete(snapshotKey)\n }\n\n /**\n * Saves the current state snapshot for a given store and action.\n * @param store The Pinia store instance.\n * @param actionName The name of the action being executed.\n * @param stateKeys The state keys to include in the snapshot, or 'all' for the full state.\n * @returns A unique symbol key representing the saved snapshot.\n */\n private saveStateSnapshot(store: Store, actionName: string, stateKeys: CreateStateSnapshotKeys): symbol {\n const stateSnapshot = createStateSnapshot(\n store.$state,\n stateKeys\n )\n\n const snapshotKey = Symbol(`${store.$id}:${actionName}`)\n this._stateSnapshots.set(snapshotKey, stateSnapshot)\n return snapshotKey\n }\n\n /**\n * Checks if the given store has rollback snapshots.\n * @param store The Pinia store instance.\n * @returns True if the store has rollback snapshots, false otherwise.\n */\n storeHasRollbackSnapshots(store: Store): boolean {\n return this._storeHasRollbackSnapshots.has(store.$id)\n }\n}","import RollbackStateSnapshotsHandler from \"./RollbackStateSnapshotsHandler\"\nimport { deepClone } from '../utils/deep-clone'\nimport { getActionStoreKey } from '../utils/store'\nimport Tracer from \"../system/Tracer\"\nimport { isEmpty } from \"../utils/validation\"\n\nimport type { PiniaPluginContext, StateTree, Store, SubscriptionCallbackMutation } from \"pinia\"\nimport type { AnyObject } from \"../types\"\nimport type { TracePayload } from \"../types/trace\"\nimport type {\n PluginExecutionOptions,\n PluginHydrationScheduler,\n PluginRuntimeEnvironment,\n PluginSubscriber,\n PluginSubscription as PluginSubscriptionDefinition,\n PluginSubscriptionOptions,\n PluginSubscriptions,\n StoreMutationSubscription,\n StoreOnActionAfterCallbackParameter,\n StoreOnActionSubscriptionCallback\n} from \"../types/plugin\"\n\n\nconst className = 'PluginSubscription'\nconst defaultPluginExecution: Required<PluginExecutionOptions> = {\n environment: 'both',\n hydration: 'immediate'\n}\n\nfunction defaultHydrationScheduler(callback: () => void): void {\n if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {\n window.requestAnimationFrame(() => globalThis.setTimeout(callback, 0))\n return\n }\n\n globalThis.setTimeout(callback, 0)\n}\n\nexport default class PluginSubscription {\n protected _className: string = className\n private _hydrationScheduler: PluginHydrationScheduler\n private _onActionSubscriptions: Map<Store, Set<StoreOnActionSubscriptionCallback>> = new Map()\n private _onActionStores: Set<Store> = new Set()\n private _onActionAfterSubscriptions: Record<string, StoreOnActionAfterCallbackParameter[]> = {}\n private _onActionOnErrorSubscriptions: Record<string, Array<(error: unknown) => void>> = {}\n private _options?: PluginSubscriptionOptions\n private _resetStoreCallback: Map<Store, Set<NonNullable<PluginSubscriber['resetStoreCallback']>>> = new Map()\n private _disposedStores: WeakSet<Store> = new WeakSet()\n private _storeRollbackSnapshotsHandler: RollbackStateSnapshotsHandler = new RollbackStateSnapshotsHandler()\n private _subscribers: PluginSubscriber[] = []\n private _subscribersDelivered: Set<string> = new Set()\n private _subscribersScheduled: Set<string> = new Set()\n private _subscriptions: PluginSubscriptions[] = []\n private _subscriptionsDelivered: Set<string> = new Set()\n private _subscriptionsScheduled: Set<string> = new Set()\n private _tracer?: Tracer\n\n set subscribers(subscribers: PluginSubscriber[]) {\n this._subscribers = subscribers\n }\n\n get subscriptions(): PluginSubscriptions[] | undefined {\n if (!isEmpty(this._subscriptions)) {\n return this._subscriptions\n }\n }\n\n constructor(\n subscribers: PluginSubscriber[],\n options?: PluginSubscriptionOptions\n ) {\n this._hydrationScheduler = options?.hydrationScheduler ?? defaultHydrationScheduler\n this._options = options\n this._subscribers = subscribers\n this.initializeTracer()\n }\n\n private addOnActionAfterCallback(actionName: string, store: Store, callback: StoreOnActionAfterCallbackParameter): void {\n const key = getActionStoreKey(actionName, store)\n if (!this._onActionAfterSubscriptions[key]) {\n this._onActionAfterSubscriptions[key] = []\n }\n this._onActionAfterSubscriptions[key]?.push(callback)\n }\n\n private addOnActionOnErrorCallback(actionName: string, store: Store, callback: (error: unknown) => void): void {\n const key = getActionStoreKey(actionName, store)\n if (!this._onActionOnErrorSubscriptions[key]) {\n this._onActionOnErrorSubscriptions[key] = []\n }\n this._onActionOnErrorSubscriptions[key]?.push(callback)\n }\n\n private addResetStoreCallback(store: Store, callback: NonNullable<PluginSubscriber['resetStoreCallback']>): void {\n if (!this._resetStoreCallback.has(store)) {\n this._resetStoreCallback.set(store, new Set())\n }\n this._resetStoreCallback.get(store)!.add(callback)\n }\n\n private clearOnActionCallbacksSubscriptions(storageKey: string): void {\n delete this._onActionAfterSubscriptions[storageKey]\n delete this._onActionOnErrorSubscriptions[storageKey]\n }\n\n private clearStoreTracking(store: Store): void {\n this._onActionSubscriptions.delete(store)\n this._onActionStores.delete(store)\n this._resetStoreCallback.delete(store)\n const suffix = `-${store.$id}`\n\n for (const key of Array.from(this._subscribersDelivered)) {\n if (key.endsWith(suffix)) {\n this._subscribersDelivered.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscribersScheduled)) {\n if (key.endsWith(suffix)) {\n this._subscribersScheduled.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscriptionsDelivered)) {\n if (key.endsWith(suffix)) {\n this._subscriptionsDelivered.delete(key)\n }\n }\n\n for (const key of Array.from(this._subscriptionsScheduled)) {\n if (key.endsWith(suffix)) {\n this._subscriptionsScheduled.delete(key)\n }\n }\n\n for (const key of Object.keys(this._onActionAfterSubscriptions)) {\n if (key.endsWith(suffix)) {\n delete this._onActionAfterSubscriptions[key]\n }\n }\n\n for (const key of Object.keys(this._onActionOnErrorSubscriptions)) {\n if (key.endsWith(suffix)) {\n delete this._onActionOnErrorSubscriptions[key]\n }\n }\n }\n\n /**\n * Creates a callback collector for the specified action and store.\n * @param actionName The name of the action to collect callbacks for.\n * @param store The store instance associated with the action.\n * @returns A function that collects callbacks for the specified action and store.\n */\n private createOnActionAfterCallbackCollector(actionName: string, store: Store) {\n return (callback: StoreOnActionAfterCallbackParameter) => {\n this.addOnActionAfterCallback(actionName, store, callback)\n }\n }\n\n /**\n * Creates a callback collector for the specified action and store that handles errors.\n * @param actionName The name of the action to collect error callbacks for.\n * @param store The store instance associated with the action.\n * @returns A function that collects error callbacks for the specified action and store.\n */\n private createOnActionOnErrorCallbackCollector(actionName: string, store: Store) {\n return (callback: (error: unknown) => void) => {\n this.addOnActionOnErrorCallback(actionName, store, callback)\n }\n }\n\n /**\n * Rolls back the state snapshot for a given action if an error occurs, and removes the snapshot after the action completes or fails.\n * @param actionName The name of the action being executed.\n * @param store The Pinia store instance.\n * @returns void\n */\n private createRollbackSnapshot(\n actionName: string,\n store: Store\n ) {\n const {\n after,\n onError\n } = this._storeRollbackSnapshotsHandler.createOnActionCallbacks(\n actionName,\n store\n ) ?? {}\n\n if (!after || !onError) {\n return\n }\n\n this.addOnActionAfterCallback(actionName, store, after)\n this.addOnActionOnErrorCallback(actionName, store, onError)\n }\n\n private defineCurrentEnvironment(): PluginRuntimeEnvironment {\n return this._options?.runtimeEnvironment\n ?? (typeof window === 'undefined' ? 'server' : 'client')\n }\n\n private definePluginExecution(subscriber: PluginSubscriber): Required<PluginExecutionOptions> {\n return {\n ...defaultPluginExecution,\n ...(this._options?.execution ?? {}),\n ...(subscriber.execution ?? {}),\n ...(this._options?.subscriberExecution?.[subscriber.name] ?? {}),\n }\n }\n\n private defineHydrationScheduler(subscriber: PluginSubscriber | PluginSubscriptionDefinition['subscription']): PluginHydrationScheduler {\n return subscriber.hydrationScheduler ?? this._hydrationScheduler\n }\n\n private defineSubscriberKey(subscriber: PluginSubscriber, store: Store): string {\n return `${subscriber.name}-${store.$id}`\n }\n\n private defineSubscriptionKey(pluginName: string, store: Store): string {\n return `${pluginName}-${store.$id}`\n }\n\n private executeResetStoreCallbacks(store: Store): void {\n this._resetStoreCallback.get(store)?.forEach(callback => callback(store))\n }\n\n /**\n * Executes the store's onAction subscription for the given plugin subscriber.\n * @param store The Pinia store instance.\n * @param subscriber The plugin subscriber.\n * @returns void\n */\n private executeStoreOnActionSubscription(store: Store): void {\n if (this._onActionStores.has(store) || typeof store.$onAction !== 'function') {\n return\n }\n const onActionSubscriptions = this._onActionSubscriptions.get(store)\n const hasRollbackSnapshots = this._storeRollbackSnapshotsHandler.storeHasRollbackSnapshots(store)\n\n if (!onActionSubscriptions?.size && !hasRollbackSnapshots) {\n return\n }\n\n this._onActionStores.add(store)\n store.$onAction(({ after, args, name, onError }) => {\n const storageKey = getActionStoreKey(name, store)\n this.trace('plugin:onAction', () => ({\n args,\n name,\n store,\n }), store.$id)\n\n if (this._storeRollbackSnapshotsHandler.storeHasRollbackSnapshots(store)) {\n this.createRollbackSnapshot(name, store)\n }\n\n const callbacks = this._onActionSubscriptions.get(store)\n if (callbacks?.size) {\n callbacks.forEach(callback => callback({\n after: this.createOnActionAfterCallbackCollector(name, store),\n args,\n name,\n onError: this.createOnActionOnErrorCallbackCollector(name, store)\n }))\n }\n\n const afterCallbacks = this._onActionAfterSubscriptions[storageKey]\n const onErrorCallbacks = this._onActionOnErrorSubscriptions[storageKey]\n\n this.clearOnActionCallbacksSubscriptions(storageKey)\n\n if (afterCallbacks?.length) {\n after((result) => {\n afterCallbacks.forEach(callback => callback(result))\n })\n }\n if (onErrorCallbacks?.length) {\n onError((error) => {\n onErrorCallbacks.forEach(callback => callback(error))\n })\n }\n })\n }\n\n private executeSubscriber(context: PiniaPluginContext, subscriber: PluginSubscriber): void {\n const subscriberKey = this.defineSubscriberKey(subscriber, context.store)\n\n if (this._subscribersDelivered.has(subscriberKey)) {\n return\n }\n\n if (\n !subscriber.invoke(context, this._options?.createTracer)) {\n return\n }\n\n this._subscribersDelivered.add(subscriberKey)\n\n let hydrateResult: void | Promise<void>\n\n try {\n hydrateResult = subscriber.hydrate?.(context)\n } catch (error) {\n this.traceError('subscriber:hydrate', error, () => ({ store: context.store, options: context.options }), context.store.$id)\n return\n }\n\n const runAfterHydration = () => {\n try {\n const afterHydration = subscriber.afterHydration?.(context)\n if (afterHydration && typeof (afterHydration as Promise<void>).then === 'function') {\n ; (afterHydration as Promise<void>).catch(error => this.traceError('subscriber:afterHydration', error, () => ({ store: context.store, options: context.options }), context.store.$id))\n }\n } catch (error) {\n this.traceError('subscriber:afterHydration', error, () => ({ store: context.store, options: context.options }), context.store.$id)\n }\n }\n\n if (hydrateResult && typeof (hydrateResult as Promise<void>).then === 'function') {\n ; (hydrateResult as Promise<void>)\n .then(() => runAfterHydration())\n .catch(error => this.traceError('subscriber:hydrate', error, () => ({ store: context.store, options: context.options }), context.store.$id))\n } else {\n runAfterHydration()\n }\n\n if (subscriber.subscriptions) {\n this.subscriptionDelivery(context, subscriber.subscriptions)\n }\n\n if (subscriber.storeMutationSubscription) {\n this.storeMutationSubscription(subscriber.storeMutationSubscription)\n }\n\n this.storeOnActionSubscription(subscriber)\n\n if (subscriber.resetStoreCallback) {\n this.addResetStoreCallback(context.store, subscriber.resetStoreCallback)\n }\n }\n\n private executeSubscriberSafely(context: PiniaPluginContext, subscriber: PluginSubscriber): void {\n try {\n this.executeSubscriber(context, subscriber)\n } catch (e) {\n this.traceError('subscriber:execute', e, () => ({ store: context.store, options: context.options }), context.store.$id)\n }\n }\n\n private initializeTracer() {\n if (this._options?.createTracer) {\n this._tracer = this._options.createTracer('PluginSubscription')\n }\n }\n\n /**\n * Invokes the plugin with the given Pinia plugin context, executing all relevant subscribers safely.\n * @param param0 The Pinia plugin context containing the store and options.\n * @param param0.store The Pinia store instance.\n * @param param0.options The options passed to the Pinia store.\n * @returns void\n */\n plugin({ store, options }: PiniaPluginContext) {\n if (!this._subscribers.length) {\n return\n }\n\n this.trace('plugin:invoke', () => ({\n subscribers: this._subscribers,\n store,\n options\n }), store.$id)\n\n try {\n this._subscribers.forEach(\n subscriber => {\n const subscriberKey = this.defineSubscriberKey(subscriber, store)\n const execution = this.definePluginExecution(subscriber)\n\n if (\n this._subscribersDelivered.has(subscriberKey)\n || this._subscribersScheduled.has(subscriberKey)\n ) {\n return\n }\n\n if (!this.shouldInvokePlugin(execution)) {\n return\n }\n\n if (this.shouldScheduleAfterHydration(execution)) {\n this.queueSubscriberExecution({ store, options } as PiniaPluginContext, subscriber, subscriberKey)\n return\n }\n\n this.executeSubscriber({ store, options } as PiniaPluginContext, subscriber)\n }\n )\n\n this.rewriteResetStore({ store } as PiniaPluginContext, store.$state)\n this._storeRollbackSnapshotsHandler.initFromPluginContext({ store, options } as PiniaPluginContext)\n this.executeStoreOnActionSubscription(store)\n this.registerStoreCleanup(store)\n } catch (e) {\n this.traceError('plugin:invoke', e, () => ({ store, options }), store.$id)\n }\n }\n\n private queueSubscriberExecution(\n context: PiniaPluginContext,\n subscriber: PluginSubscriber,\n subscriberKey: string\n ): void {\n const scheduler = this.defineHydrationScheduler(subscriber)\n\n this._subscribersScheduled.add(subscriberKey)\n scheduler(() => {\n if (this._disposedStores.has(context.store)) {\n return\n }\n this._subscribersScheduled.delete(subscriberKey)\n this.executeSubscriberSafely(context, subscriber)\n })\n }\n\n private registerStoreCleanup(store: Store): void {\n if (typeof store.$dispose !== 'function') {\n return\n }\n\n const dispose = store.$dispose.bind(store)\n const scopedStore = store as AnyObject\n\n if (scopedStore.__piniaPluginSubscriptionDisposed) {\n return\n }\n\n scopedStore.__piniaPluginSubscriptionDisposed = true\n store.$dispose = () => {\n this._disposedStores.add(store)\n this.clearStoreTracking(store)\n this._storeRollbackSnapshotsHandler.clearStoreTracking(store)\n return dispose()\n }\n }\n\n private rewriteResetStore({ store }: PiniaPluginContext, initState: StateTree): void {\n const safeState = deepClone(initState)\n\n store.$reset = () => {\n this.trace('plugin:reset', () => ({\n initState: safeState,\n store\n }), store.$id)\n\n this.executeResetStoreCallbacks(store)\n\n store.$patch(deepClone(safeState))\n }\n }\n\n private shouldInvokePlugin(execution: Required<PluginExecutionOptions>): boolean {\n const currentEnvironment = this.defineCurrentEnvironment()\n\n return execution.environment === 'both' || execution.environment === currentEnvironment\n }\n\n private shouldScheduleAfterHydration(execution: Required<PluginExecutionOptions>): boolean {\n return this.defineCurrentEnvironment() === 'client' && execution.hydration === 'defer'\n }\n\n private storeOnActionSubscription(subscriber: PluginSubscriber): void {\n const { store, callback } = subscriber?.storeOnActionSubscription?.() ?? {}\n\n if (!store || !callback) {\n return\n }\n\n if (!this._onActionSubscriptions.has(store)) {\n this._onActionSubscriptions.set(store, new Set())\n }\n this._onActionSubscriptions.get(store)!.add(callback)\n this.executeStoreOnActionSubscription(store)\n }\n\n private storeMutationSubscription(subscription: StoreMutationSubscription): void {\n const { store, callback } = subscription()\n\n store.$subscribe((mutation: SubscriptionCallbackMutation<StateTree>) => {\n this.trace('store:mutation', () => ({ mutation, store }), store.$id)\n callback(mutation)\n })\n }\n\n private subscriptionDelivery(\n context: PiniaPluginContext,\n pluginSubscriptions: PluginSubscriptions\n ): void {\n Object.entries(pluginSubscriptions).forEach(([pluginName, pluginSubscription]) => {\n const subscriptionKey = this.defineSubscriptionKey(pluginName, context.store)\n const execution = this.definePluginExecution(pluginSubscription.subscription)\n\n if (\n this._subscriptionsDelivered.has(subscriptionKey)\n || this._subscriptionsScheduled.has(subscriptionKey)\n ) {\n return\n }\n\n if (!this.shouldInvokePlugin(execution)) {\n return\n }\n\n if (this.shouldScheduleAfterHydration(execution)) {\n const scheduler = this.defineHydrationScheduler(pluginSubscription.subscription)\n\n this._subscriptionsScheduled.add(subscriptionKey)\n scheduler(() => {\n if (this._disposedStores.has(context.store)) {\n return\n }\n this._subscriptionsScheduled.delete(subscriptionKey)\n this.subscriptionDeliverySafely(context, pluginName, pluginSubscription)\n })\n return\n }\n\n this.subscriptionDeliverySafely(context, pluginName, pluginSubscription)\n })\n }\n\n private subscriptionDeliverySafely(\n { store, options }: PiniaPluginContext,\n pluginName: string,\n pluginSubscription: PluginSubscriptionDefinition\n ): void {\n try {\n if (this._subscriptionsDelivered.has(this.defineSubscriptionKey(pluginName, store))) {\n return\n }\n\n const { subscription, subscriptionOptions, stores } = pluginSubscription\n\n this.trace('subscription:delivery', () => ({\n pluginName,\n subscription,\n options: pluginSubscription,\n stores\n }), store.$id)\n\n const pluginOptions = {\n storeOptions: { ...((options as AnyObject)?.storeOptions ?? {}), ...subscriptionOptions }\n } as AnyObject\n\n subscription.invoke(\n { store, options: { ...options, ...pluginOptions } } as PiniaPluginContext\n )\n this._subscriptionsDelivered.add(this.defineSubscriptionKey(pluginName, store))\n\n if (!isEmpty(stores)) {\n stores?.forEach(\n store => subscription.invoke({\n store,\n options: {\n ...options,\n ...pluginOptions,\n ...((store as AnyObject)?.storeOptions ?? {})\n }\n } as PiniaPluginContext)\n )\n }\n } catch (e) {\n this.traceError('subscription:delivery', e, () => ({ store, options }), store.$id)\n }\n }\n\n /**\n * Emits a structured trace event.\n * Prefer the factory form for `payload`: it is only resolved when consumed.\n */\n private trace(namespace: string, payload?: TracePayload, scope?: string): void {\n if (this._tracer) {\n this._tracer.debug(namespace, payload, scope)\n }\n }\n\n /**\n * Emits a structured error event, or rethrows it when no listener matches.\n */\n private traceError(namespace: string, error: unknown, payload?: TracePayload, scope?: string): void {\n if (this._tracer) {\n this._tracer.error(namespace, error, payload, scope)\n } else {\n console.error(error)\n }\n }\n}"],"names":["deepClone","value","key","entryValue","item","clonedObject","createStateSnapshot","state","keys","clonedState","toRaw","RollbackStateSnapshotsHandler","__publicField","store","action","stateKeys","args","actionFn","hasDeniedFirstChar","snapshotKey","error","actionName","getActionStoreKey","options","rollbackSnapshotParams","suffix","stateSnapshot","className","defaultPluginExecution","defaultHydrationScheduler","callback","PluginSubscription","subscribers","isEmpty","storageKey","after","onError","subscriber","pluginName","onActionSubscriptions","hasRollbackSnapshots","name","callbacks","afterCallbacks","onErrorCallbacks","result","context","subscriberKey","hydrateResult","runAfterHydration","afterHydration","e","execution","scheduler","scopedStore","dispose","safeState","initState","currentEnvironment","subscription","mutation","pluginSubscriptions","pluginSubscription","subscriptionKey","subscriptionOptions","stores","pluginOptions","store2","namespace","payload","scope","createPlugin","createHydrationPlugin","hydrationPlugin"],"mappings":";;;;;;AAMO,SAASA,EAAaC,GAAa;AACtC,MAAI,OAAO,mBAAoB;AAC3B,QAAI;AACA,aAAO,gBAAgBA,CAAK;AAAA,IAChC,QAAQ;AAAA,IAER;AAGJ,MAAIA,MAAU,QAAQ,OAAOA,KAAU;AACnC,WAAOA;AAGX,MAAIA,aAAiB;AACj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AA,OAAA,KAAAA,CAAA;AACA;"}
@@ -1,3 +1,10 @@
1
1
  import type { PiniaPlugin } from 'pinia';
2
2
  import type { PluginSubscriber, PluginSubscriptionOptions } from '../types/plugin';
3
+ /**
4
+ * Creates a Pinia plugin that manages hydration for the specified plugin subscribers.
5
+ * @param subscribers The list of plugin subscribers to be used by the hydration plugin.
6
+ * @param options The options for configuring the plugin subscription.
7
+ * @returns A Pinia plugin that handles hydration based on the provided subscribers and options.
8
+ * @deprecated use `createPlugin` with appropriate hydration options instead.
9
+ */
3
10
  export declare function createHydrationPlugin(subscribers: PluginSubscriber[], options?: PluginSubscriptionOptions): PiniaPlugin;
@@ -1,7 +1,14 @@
1
1
  import type { PiniaPlugin } from "pinia";
2
- import type { PluginSubscriber } from "../types/plugin";
2
+ import type { PluginSubscriber, PluginSubscriptionOptions } from "../types/plugin";
3
3
  import type { RollbackActionParams, StoreOptions } from "../types/store";
4
- export declare function createPlugin(subscribers: PluginSubscriber[], debug?: string[]): PiniaPlugin;
4
+ /**
5
+ * Creates a Pinia plugin that manages the specified plugin subscribers.
6
+ *
7
+ * @param subscribers The list of plugin subscribers to be used by the plugin.
8
+ * @param options The options for configuring the plugin subscription.
9
+ * @returns A Pinia plugin that handles the provided subscribers and options.
10
+ */
11
+ export declare function createPlugin(subscribers: PluginSubscriber[], options?: PluginSubscriptionOptions): PiniaPlugin;
5
12
  declare module 'pinia' {
6
13
  interface PiniaCustomProperties {
7
14
  /**
@@ -0,0 +1,20 @@
1
+ import type { TraceListener, TracePayload, TracerOptions } from '../types/trace';
2
+ /**
3
+ * Emits structured trace events.
4
+ *
5
+ * Nothing is allocated when no listener matches:
6
+ * the payload is a factory resolved only once a consumer is known.
7
+ */
8
+ export default class Tracer {
9
+ private readonly _listeners;
10
+ private _scope?;
11
+ private readonly _source;
12
+ constructor(source: string, listeners: TraceListener[], options?: TracerOptions);
13
+ get scope(): string | undefined;
14
+ set scope(scope: string | undefined);
15
+ get source(): string;
16
+ debug(namespace: string, payload?: TracePayload, scope?: string): void;
17
+ /** Relays the error to matching listeners, or reports it when none match. */
18
+ error(namespace: string, error: unknown, payload?: TracePayload, scope?: string): void;
19
+ private emit;
20
+ }
@@ -0,0 +1,6 @@
1
+ import type { Console } from '../types/log';
2
+ import type { TraceListener } from '../types/trace';
3
+ /**
4
+ * Creates an opt-in trace listener that reproduces the former console output.
5
+ */
6
+ export declare function createConsoleTraceListener(target?: Console): TraceListener;
@@ -1,4 +1,15 @@
1
1
  import type { PiniaPluginContext, Store as PiniaStore } from 'pinia';
2
+ /**
3
+ * Centralized extension point for per-store plugin options.
4
+ *
5
+ * Subscriber plugins MUST NOT redeclare pinia's `DefineStoreOptionsBase`:
6
+ * merging a `storeOptions` property with a different (even compatible) type
7
+ * raises TS2717 in consumer code. Instead, they augment this interface via
8
+ * `declare module 'pinia-plugin-subscription/types'`, which merges safely as
9
+ * long as each plugin declares its own optional keys.
10
+ */
11
+ export interface StoreOptionsExtensions {
12
+ }
2
13
  import type { PluginExecutionOptions, PluginHydrationScheduler, PluginSubscriptions, StoreMutationSubscription, StoreOnActionSubscription } from './plugin';
3
14
  import type { StoreOptions } from './store';
4
15
  export interface AnyObject {
@@ -19,20 +30,20 @@ export type ConsoleStyleDefinition = StyleDefinition;
19
30
  export type ConsoleStyleDefinitionKeys = StyleDefinitionKeys;
20
31
  export type ConsoleStyleDefinitions = StyleDefinitions;
21
32
  export type { List, ListTypes, ListTypesMap, PartialList } from './list';
22
- export type { CustomStore, DefineAStoreDefinition, DefineAStoreSetupContext, DefineAStoreSetupExtensions, EmptyExtensions, PluginStoreOptions, StatePropertyValue, StoreOptions, StoreOptionsExtensions, StoreOptionsPropertyValue } from './store';
33
+ export type { TraceEvent, TraceEventMetadata, TraceFilter, TraceHandler, TraceLevel, TraceListener, TraceListenerRemover, TracePayload, TraceRegistry, TracerOptions } from './trace';
34
+ export type { CustomStore, DefineAStoreSetupContext, DefineAStoreSetupExtensions, EmptyExtensions, PluginStoreOptions, StatePropertyValue, StoreOptions, StoreOptionsPropertyValue } from './store';
23
35
  export type { NativePiniaSubscription, NativePiniaSubscriptionReturn, PluginExecutionEnvironment, PluginExecutionOptions, PluginHydrationScheduler, PluginHydrationTiming, PluginRuntimeEnvironment, PluginSubscriber, PluginSubscription, PluginSubscriptionOptions, PluginSubscriptions, StoreMutationSubscription, StoreMutationSubscriptionCallback, StoreMutationSubscriptionReturn, StoreOnActionCallbackParameters, StoreOnActionSubscription, StoreOnActionSubscriptionCallback, StoreOnActionSubscriptionReturn, } from './plugin';
24
36
  export interface PluginSubscriberInterface {
25
- console?: Console;
26
37
  execution?: PluginExecutionOptions;
27
- hydrate?: (context: PiniaPluginContext, debug: boolean) => void | Promise<void>;
38
+ hydrate?: (context: PiniaPluginContext) => void | Promise<void>;
28
39
  hydrationScheduler?: PluginHydrationScheduler;
29
- invoke: (context: PiniaPluginContext, debug: boolean) => boolean;
40
+ invoke: (context: PiniaPluginContext) => boolean;
30
41
  name: string;
31
42
  resetStoreCallback?: (store?: PiniaStore) => void;
32
43
  storeOnActionSubscription?: StoreOnActionSubscription;
33
44
  storeMutationSubscription?: StoreMutationSubscription;
34
45
  subscriptions?: PluginSubscriptions;
35
- afterHydration?: (context: PiniaPluginContext, debug: boolean) => void | Promise<void>;
46
+ afterHydration?: (context: PiniaPluginContext) => void | Promise<void>;
36
47
  }
37
48
  export interface PluginSubscriptionDefinition {
38
49
  stores?: PiniaStore[];
@@ -1,6 +1,7 @@
1
1
  import type { PiniaPluginContext, StateTree, Store, SubscriptionCallbackMutation } from "pinia";
2
2
  import type { StoreOptions } from "./store";
3
- import type { Console, PluginSubscriberInterface } from ".";
3
+ import type { PluginSubscriberInterface } from ".";
4
+ import Tracer from "../system/Tracer";
4
5
  export type CreateStateSnapshotKeys = (keyof StateTree)[] | 'all';
5
6
  export type PluginHydrationScheduler = (callback: () => void) => void;
6
7
  export type PluginHydrationTiming = 'defer' | 'immediate';
@@ -11,24 +12,62 @@ export interface PluginExecutionOptions {
11
12
  hydration?: PluginHydrationTiming;
12
13
  }
13
14
  export interface PluginSubscriptionOptions {
14
- debug?: string[];
15
+ createTracer?: (source: string) => Tracer;
15
16
  execution?: PluginExecutionOptions;
16
17
  hydrationScheduler?: PluginHydrationScheduler;
17
18
  runtimeEnvironment?: PluginRuntimeEnvironment;
18
19
  subscriberExecution?: Record<string, PluginExecutionOptions>;
19
20
  }
20
21
  export interface PluginSubscriber {
21
- console?: Console;
22
+ /**
23
+ * Execution options for the plugin subscriber.
24
+ * This determines how and when the plugin subscriber should be executed.
25
+ */
22
26
  execution?: PluginExecutionOptions;
23
- hydrate?: (context: PiniaPluginContext, debug: boolean) => void | Promise<void>;
27
+ /**
28
+ * Function to hydrate the plugin subscriber.
29
+ * This is typically called during the hydration phase of the application.
30
+ */
31
+ hydrate?: (context: PiniaPluginContext) => void | Promise<void>;
32
+ /**
33
+ * Scheduler for the hydration of the plugin subscriber.
34
+ * This allows controlling when the hydration should occur.
35
+ */
24
36
  hydrationScheduler?: PluginHydrationScheduler;
25
- invoke: (context: PiniaPluginContext, debug: boolean) => boolean;
37
+ /**
38
+ * Function to invoke the plugin subscriber.
39
+ * Returns a boolean indicating whether the invocation was successful.
40
+ */
41
+ invoke: (context: PiniaPluginContext, createTracer?: (source: string) => Tracer) => boolean;
42
+ /**
43
+ * Name of the plugin subscriber.
44
+ */
26
45
  name: string;
46
+ /**
47
+ * Callback to reset the store associated with the plugin subscriber.
48
+ * This is typically used to clean up or reinitialize the store.
49
+ */
27
50
  resetStoreCallback?: (store?: Store) => void;
51
+ /**
52
+ * Subscription for store actions.
53
+ * This is typically used to listen for and respond to actions dispatched in the store.
54
+ */
28
55
  storeOnActionSubscription?: StoreOnActionSubscription;
56
+ /**
57
+ * Subscription for store mutations.
58
+ * This is typically used to listen for and respond to mutations committed in the store.
59
+ */
29
60
  storeMutationSubscription?: StoreMutationSubscription;
61
+ /**
62
+ * Subscriptions for the plugin subscriber.
63
+ * This is typically used to manage and respond to various plugin-specific events or changes.
64
+ */
30
65
  subscriptions?: PluginSubscriptions;
31
- afterHydration?: (context: PiniaPluginContext, debug: boolean) => void | Promise<void>;
66
+ /**
67
+ * Callback to be executed after the hydration of the plugin subscriber.
68
+ * This is typically used to perform any post-hydration logic.
69
+ */
70
+ afterHydration?: (context: PiniaPluginContext) => void | Promise<void>;
32
71
  }
33
72
  export interface NativePiniaSubscriptionReturn<Callback> {
34
73
  store: Store;
@@ -1,4 +1,4 @@
1
- import type { AnyObject } from ".";
1
+ import type { AnyObject, StoreOptionsExtensions } from ".";
2
2
  import type { CreateStateSnapshotKeys } from "./plugin";
3
3
  import type { Pinia, PiniaCustomProperties, StateTree, Store, StoreDefinition, StoreGeneric } from "pinia";
4
4
  import type { Ref } from "vue";
@@ -13,15 +13,22 @@ export type CustomStore<TStore, TState> = Store & TStore & TState & PiniaCustomP
13
13
  * prototypes. It extends pinia's `StoreDefinition` to stay assignable
14
14
  * wherever a standard store definition is expected.
15
15
  */
16
- export interface DefineAStoreDefinition<TStore, TState, Id extends string = string> extends StoreDefinition<Id, StateTree & TState> {
16
+ export interface DefineAStoreDefinition<TStore, TState, Id extends string = string> extends StoreDefinition<Id, StrictStateTree<TState>> {
17
17
  /**
18
18
  * Returns a store, creates it if necessary.
19
19
  *
20
20
  * @param pinia - Pinia instance to retrieve the store
21
21
  * @param hot - dev only hot module replacement
22
22
  */
23
- (pinia?: Pinia | null, hot?: StoreGeneric): Store<Id, StateTree & TState> & TStore;
23
+ (pinia?: Pinia | null, hot?: StoreGeneric): Store<Id, StrictStateTree<TState>> & TStore;
24
24
  }
25
+ /**
26
+ * Maps a state interface to a pinia `StateTree` without intersecting it with
27
+ * `StateTree` itself, whose `any` index signature would widen every store member to `any`.
28
+ */
29
+ export type StrictStateTree<TState> = {
30
+ [K in keyof TState]: TState[K];
31
+ } extends infer S extends StateTree ? S : never;
25
32
  export type EmptyExtensions = Record<never, never>;
26
33
  export interface DefineAStoreSetupExtensions<TEnhancedStore> {
27
34
  /**
@@ -58,11 +65,9 @@ type StdStatePropertyValue = AnyObject | boolean | null | number | string | unde
58
65
  * `declare module 'pinia-plugin-subscription/types'`, which merges safely as
59
66
  * long as each plugin declares its own optional keys.
60
67
  */
61
- export interface StoreOptionsExtensions {
62
- }
63
- export interface StoreOptions extends StoreOptionsExtensions {
68
+ export type StoreOptions = StoreOptionsExtensions & {
64
69
  [key: string]: StoreOptionsPropertyValue;
65
70
  rollbackAfterFailure?: RollbackAfterFailureParams;
66
- }
71
+ };
67
72
  export type StoreOptionsPropertyValue = OptionBaseProperty | OptionBaseProperty[] | ObjectBaseProperty | ObjectBaseProperty[];
68
73
  export {};
@@ -0,0 +1,80 @@
1
+ import type { AnyObject } from './index';
2
+ import type Tracer from '../system/Tracer';
3
+ /**
4
+ * Severity of a trace event.
5
+ * `error` events are delivered to matching listeners, or reported with `console.error` when none match.
6
+ */
7
+ export type TraceLevel = 'debug' | 'error';
8
+ /**
9
+ * Cheap descriptor of an event, built before the payload is resolved.
10
+ * Filters receive this object so that discarded events never allocate a payload.
11
+ */
12
+ export interface TraceEventMetadata {
13
+ level: TraceLevel;
14
+ /** Structured, colon separated identifier, e.g. `subscription:delivery`. */
15
+ namespace: string;
16
+ /** Instance the event belongs to, usually a Pinia `store.$id`. */
17
+ scope?: string;
18
+ /** Emitting class name, e.g. `PluginSubscription`. */
19
+ source: string;
20
+ }
21
+ /**
22
+ * A resolved trace event, handed over to listeners.
23
+ */
24
+ export interface TraceEvent extends TraceEventMetadata {
25
+ error?: unknown;
26
+ payload?: AnyObject;
27
+ timestamp: number;
28
+ }
29
+ /**
30
+ * Event data. Prefer the function form: it is only invoked when a listener
31
+ * actually consumes the event, keeping unobserved tracing allocation free.
32
+ */
33
+ export type TracePayload = AnyObject | (() => AnyObject);
34
+ /**
35
+ * Determines whether a trace event should be delivered to a listener.
36
+ * @param event The metadata of the trace event.
37
+ * @returns `true` if the event should be delivered to the listener, otherwise `false`.
38
+ */
39
+ export type TraceFilter = (event: TraceEventMetadata) => boolean;
40
+ /**
41
+ * Handles a trace event.
42
+ * @param event The resolved trace event to handle.
43
+ */
44
+ export type TraceHandler = (event: TraceEvent) => void;
45
+ export interface TraceListener {
46
+ /** Evaluated on every event; return `true` to receive it. Omit to receive all. */
47
+ filter?: TraceFilter;
48
+ /** Handles the trace event when it passes the filter. */
49
+ handler: TraceHandler;
50
+ }
51
+ /** Removes a previously registered listener. */
52
+ export type TraceListenerRemover = () => void;
53
+ export type TraceRegistry = {
54
+ /**
55
+ * Registers a trace listener and returns its remover.
56
+ * Listeners are evaluated in registration order.
57
+ * @param listener The trace listener to register.
58
+ * @returns A function that removes the registered listener when called.
59
+ */
60
+ addTraceListener: (listener: TraceListener) => TraceListenerRemover;
61
+ /**
62
+ * Clears all registered trace listeners.
63
+ */
64
+ clearTraceListeners: () => void;
65
+ /**
66
+ * Creates a new tracer instance.
67
+ * @param source The source of the tracer, usually the class name.
68
+ * @param options Optional tracer options.
69
+ * @returns A new tracer instance.
70
+ */
71
+ createTracer: (source: string, options?: TracerOptions) => Tracer;
72
+ /**
73
+ * Checks if there are any registered trace listeners.
74
+ * @returns True if there are registered trace listeners, otherwise false.
75
+ */
76
+ hasTraceListeners: () => boolean;
77
+ };
78
+ export interface TracerOptions {
79
+ scope?: string;
80
+ }