import type { ErrorContext, FetchContext, PartialContext, ResponseContext, TransformContext, ValidatedContext, WorkflowPlugin, WriteContext, } from '../types' export interface ConsoleLogOptions { /** Prefix prepended to every log line. Default: '[ZustandEngine]' */ prefix?: string /** Console method to use for regular events. Default: 'log' */ logLevel?: 'log' | 'debug' | 'info' } export function createConsoleLogPlugin( options: ConsoleLogOptions = {}, ): WorkflowPlugin { const { prefix = '[ZustandEngine]', logLevel = 'log' } = options const log = console[logLevel].bind(console) return { name: 'console-log', beforeFetch: async (ctx: FetchContext): Promise => { log(`${prefix} fetch:start`, ctx.key, ctx.options) return ctx }, afterFetch: async (ctx: ResponseContext): Promise => { log(`${prefix} fetch:done`, ctx.key, `${ctx.duration}ms`) return ctx }, afterValidate: async (ctx: ValidatedContext): Promise => { if (ctx.warnings.length > 0) { console.warn(`${prefix} validate:warnings`, ctx.key, ctx.warnings) } else { log(`${prefix} validate:ok`, ctx.key) } return ctx }, afterTransform: async ( ctx: TransformContext, ): Promise => { log(`${prefix} transform:done`, ctx.key) return ctx }, afterWrite: async (ctx: WriteContext): Promise => { const src = ctx.source === 'native-cache' ? ' [cache]' : '' if (ctx.status === 'partialSuccess') { console.warn( `${prefix} [Zustand]${src} ${ctx.key} →`, ctx.status, ctx.data, ctx.warnings, ) } else { log(`${prefix} [Zustand]${src} ${ctx.key} →`, ctx.status, ctx.data) } }, onError: async (ctx: ErrorContext): Promise => { console.error( `${prefix} [Zustand] ${ctx.key} → error (phase: ${ctx.error.phase}):`, ctx.error.cause, ) }, onPartialSuccess: async (ctx: PartialContext): Promise => { console.warn( `${prefix} [Zustand] ${ctx.key} → partialSuccess`, `${ctx.warnings.length} warning(s)`, ctx.warnings, ) }, } }